All files / owid-grapher/grapher/color ColorScale.ts

91.82% Statements 359/391
59.52% Branches 50/84
97.5% Functions 39/40
91.82% Lines 359/391

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 3831x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 81x 81x 1x 1x 1x 1x 63x 63x 1x 1x 1x 1x 1x 1x 49x 49x 1x 1x 49x 49x 49x 49x 49x 1x 1x 49x 49x 49x 49x 1x 1x 49x       49x     1x 1x 49x 49x 1x 1x 49x 49x 49x 49x 1x 1x 49x 49x     49x 49x 1x 1x     1x 1x 63x 63x 1x 1x 49x 49x 1x 1x 8x 8x 1x 1x 63x 63x 63x 63x 63x 63x     34x 34x     34x   1x 1x 1x 1x 49x 49x 1x 1x 49x 49x     49x 49x 1x 1x 49x 49x 1x 1x 49x 49x 1x 1x 49x 49x 1x 1x 49x 49x 1x 1x 1x 1x 1x 1x 49x 49x 49x 1x 1x 49x 49x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 49x 49x 49x 49x 49x 49x 49x 1x 1x 49x   49x 49x 1x 1x 1x 63x 63x 63x 63x 63x 63x 63x 63x 1x 1x 21x 21x 1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 1x 1x 49x 49x 1x 1x 49x 49x 1x 1x 1x     1x 1x 1x 1x 49x 49x   49x 49x 49x 49x 49x 49x 49x 49x 49x         49x 1x 1x 1x 49x 49x 49x 49x 1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x         14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 7x 7x 7x 7x 7x 7x 49x 49x 276x     276x 276x 276x 276x 276x 276x 276x 276x 276x 276x 276x 276x 49x 1x 1x 59x 59x 59x   59x 59x 1x 1x 96x 96x 96x 1x 1x
import { computed, toJS } from "mobx"
import { mean, deviation } from "d3-array"
import {
    ColorScaleConfig,
    ColorScaleConfigDefaults,
    ColorScaleConfigInterface,
} from "./ColorScaleConfig"
import {
    isEmpty,
    reverse,
    first,
    last,
    roundSigFig,
    mapNullToUndefined,
    isString,
    mapValues,
    identity,
} from "../../clientUtils/Util"
import { Color, CoreValueType } from "../../coreTable/CoreTableConstants"
import { ColorSchemes } from "../color/ColorSchemes"
import { ColorScheme } from "../color/ColorScheme"
import { ColorScaleBin, NumericBin, CategoricalBin } from "./ColorScaleBin"
import { ColorSchemeName } from "./ColorConstants"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { getBinMaximums } from "./BinningStrategies"
import { BinningStrategy } from "./BinningStrategy"
 
export const NO_DATA_LABEL = "No data"
 
export interface ColorScaleManager {
    colorScaleConfig?: ColorScaleConfigInterface
    hasNoDataBin?: boolean
    defaultNoDataColor?: string
    defaultBaseColorScheme?: ColorSchemeName
    colorScaleColumn?: CoreColumn
    transformColor?: (color: Color) => Color
}
 
export class ColorScale {
    private manager: Readonly<ColorScaleManager>
    constructor(manager: ColorScaleManager = {}) {
        this.manager = manager
    }
 
    // Config accessors
 
    @computed get config(): ColorScaleConfigDefaults {
        return this.manager.colorScaleConfig ?? new ColorScaleConfig()
    }
 
    @computed get customNumericValues(): number[] {
        return this.config.customNumericValues ?? []
    }
 
    @computed get customNumericColorsActive(): boolean {
        return this.config.customNumericColorsActive ?? false
    }
 
    @computed get customNumericColors(): (Color | undefined)[] {
        const colors = this.customNumericColorsActive
            ? mapNullToUndefined(this.config.customNumericColors)
            : []
        return colors.map(this.transformColor)
    }
 
    @computed get customHiddenCategories(): {
        [key: string]: true | undefined
    } {
        return this.config.customHiddenCategories ?? {}
    }
 
    @computed get customNumericLabels(): (string | undefined)[] {
        if (!this.isManualBuckets) return []

        const labels =
            mapNullToUndefined(toJS(this.config.customNumericLabels)) || []
        while (labels.length < this.numBins) labels.push(undefined)
        return labels
    }
 
    @computed get isColorSchemeInverted(): boolean {
        return this.config.colorSchemeInvert ?? false
    }
 
    @computed private get customCategoryLabels(): {
        [key: string]: string | undefined
    } {
        return this.config.customCategoryLabels ?? {}
    }
 
    @computed get baseColorScheme(): ColorSchemeName {
        return (
            this.config.baseColorScheme ??
            this.manager.defaultBaseColorScheme ??
            ColorSchemeName.BuGn
        )
    }
 
    @computed private get defaultColorScheme(): ColorScheme {
        return ColorSchemes[ColorSchemeName.BuGn]
    }
 
    @computed private get defaultNoDataColor(): Color {
        return this.transformColor(this.manager.defaultNoDataColor ?? "#eee")
    }
 
    @computed get colorScaleColumn(): CoreColumn | undefined {
        return this.manager.colorScaleColumn
    }
 
    @computed get legendDescription(): string | undefined {
        return this.config.legendDescription
    }
 
    @computed private get transformColor(): <
        MaybeColor extends Color | undefined
    >(
        color: MaybeColor
    ) => MaybeColor {
        const transform = this.manager.transformColor
        if (!transform) return identity
        return <MaybeColor extends Color | undefined>(
            color: MaybeColor
        ): MaybeColor => {
            return isString(color) && transform
                ? (transform(color) as MaybeColor)
                : color
        }
    }
 
    // Transforms
 
    @computed private get hasNoDataBin(): boolean {
        return this.manager.hasNoDataBin || false
    }
 
    @computed get sortedNumericValues(): any[] {
        return (
            this.colorScaleColumn?.valuesAscending?.filter(
                (x) => typeof x === "number"
            ) ?? []
        )
    }
 
    @computed private get minPossibleValue(): any {
        return first(this.sortedNumericValues)
    }
 
    @computed private get maxPossibleValue(): any {
        return last(this.sortedNumericValues)
    }
 
    @computed private get categoricalValues(): any[] {
        return this.colorScaleColumn?.sortedUniqNonEmptyStringVals ?? []
    }
 
    @computed private get colorScheme(): ColorScheme {
        return ColorSchemes[this.baseColorScheme] ?? this.defaultColorScheme
    }
 
    @computed get singleColorScale(): boolean {
        return this.colorScheme.singleColorScale
    }
 
    @computed get autoMinBinValue(): number {
        const minValue = Math.min(0, this.sortedNumericValuesWithoutOutliers[0])
        return isNaN(minValue) ? 0 : roundSigFig(minValue, 1)
    }
 
    @computed private get minBinValue(): number {
        return this.config.customNumericMinValue ?? this.autoMinBinValue
    }
 
    @computed private get manualBinMaximums(): number[] {
        if (!this.sortedNumericValues.length || this.numBins <= 0) return []
 
        const { numBins, customNumericValues } = this
 
        let values = [...customNumericValues]
        while (values.length < numBins) values.push(0)
        while (values.length > numBins) values = values.slice(0, numBins)
        return values
    }
 
    // When automatic classification is turned on, this takes the numeric map data
    // and works out some discrete ranges to assign colors to
    @computed get autoBinMaximums(): number[] {
        return getBinMaximums({
            binningStrategy: this.config.binningStrategy,
            sortedValues: this.sortedNumericBinningValues,
            binCount: this.numAutoBins,
            minBinValue: this.minBinValue,
        })
    }
 
    @computed private get bucketMaximums(): number[] {
        return this.isManualBuckets
            ? this.manualBinMaximums
            : this.autoBinMaximums
    }
 
    // Ensure there's always a custom color for "No data"
    @computed private get customCategoryColors(): { [key: string]: Color } {
        return mapValues(
            {
                [NO_DATA_LABEL]: this.defaultNoDataColor, // default 'no data' color
                ...this.config.customCategoryColors,
            },
            this.transformColor
        )
    }
 
    @computed get noDataColor(): Color {
        return this.transformColor(this.customCategoryColors[NO_DATA_LABEL])
    }
 
    @computed get baseColors(): Color[] {
        const {
            categoricalValues,
            colorScheme,
            bucketMaximums,
            isColorSchemeInverted,
            transformColor,
        } = this
        const numColors = bucketMaximums.length + categoricalValues.length
        const colors = colorScheme.getColors(numColors)
 
        if (isColorSchemeInverted) reverse(colors)
 
        return colors.map(transformColor)
    }
 
    @computed get numAutoBins(): number {
        return this.config.binningStrategyBinCount ?? 5
    }
 
    @computed get isManualBuckets(): boolean {
        return this.config.binningStrategy === BinningStrategy.manual
    }
 
    @computed get numBins(): number {
        return this.isManualBuckets
            ? this.customNumericValues.length
            : this.numAutoBins
    }
 
    // Exclude any major outliers for legend calculation (they will be relegated to open-ended bins)
    @computed get sortedNumericValuesWithoutOutliers(): any[] {
        const { sortedNumericValues } = this
        if (!sortedNumericValues.length) return []
        const sampleMean = mean(sortedNumericValues) as number
        const sampleDeviation = deviation(sortedNumericValues) ?? 0
        const withoutOutliers = sortedNumericValues.filter(
            (d) => Math.abs(d - sampleMean) <= sampleDeviation * 2
        )
 
        // d3-array returns a deviation of `undefined` for arrays of length <= 1, so set it to 0 in that case
        const deviationWithoutOutliers = deviation(withoutOutliers) ?? 0
 
        if (deviationWithoutOutliers === 0) {
            // if after removing outliers we end up in a state where the std. dev. is 0, i.e. we only
            // have one distinct value, then we actually want to _keep_ the outliers in
            return sortedNumericValues
        } else return withoutOutliers
    }
 
    /** Sorted numeric values passed onto the binning algorithms */
    @computed private get sortedNumericBinningValues(): any[] {
        return this.sortedNumericValuesWithoutOutliers.filter(
            (v) => v > this.minBinValue
        )
    }
 
    @computed private get numericLegendBins(): NumericBin[] {
        const {
            customNumericLabels,
            minBinValue,
            minPossibleValue,
            maxPossibleValue,
            customNumericColors,
            bucketMaximums,
            baseColors,
        } = this
 
        if (minPossibleValue === undefined || maxPossibleValue === undefined)
            return []

        let min = minBinValue

        return bucketMaximums.map((max, index) => {
            const baseColor = baseColors[index]
            const color = customNumericColors[index] ?? baseColor
            const label = customNumericLabels[index]
 
            const displayMin =
                this.colorScaleColumn?.formatValueShort(min) ?? min.toString()
            const displayMax =
                this.colorScaleColumn?.formatValueShort(max) ?? max.toString()
 
            const currentMin = min
            const isFirst = index === 0
            const isLast = index === bucketMaximums.length - 1
            min = max
            return new NumericBin({
                isFirst,
                isOpenLeft: isFirst && currentMin > minPossibleValue,
                isOpenRight: isLast && max < maxPossibleValue,
                min: currentMin,
                max,
                color,
                label,
                displayMin,
                displayMax,
            })
        })
    }
 
    @computed get legendBins(): ColorScaleBin[] {
        // todo: turn comment into unit test
        // Will eventually produce something like this:
        // [{ min: 10, max: 20, minText: "10%", maxText: "20%", color: '#faeaef' },
        //  { min: 20, max: 30, minText: "20%", maxText: "30%", color: '#fefabc' },
        //  { value: 'Foobar', text: "Foobar Boop", color: '#bbbbbb'}]
        return [
            ...this.numericLegendBins,
            ...this.categoricalLegendBins,
        ] as ColorScaleBin[]
    }
 
    @computed get categoricalLegendBins(): CategoricalBin[] {
        const {
            bucketMaximums,
            baseColors,
            hasNoDataBin,
            categoricalValues,
            customCategoryColors,
            customCategoryLabels,
            customHiddenCategories,
        } = this
 
        let allCategoricalValues = categoricalValues
 
        // Inject "No data" bin
        if (hasNoDataBin && !allCategoricalValues.includes(NO_DATA_LABEL)) {
            // The color scheme colors get applied in order, starting from first, and we only use
            // as many colors as there are categorical values (excluding "No data").
            // So in order to leave it colorless, we want to append the "No data" label last.
            // -@danielgavrilov, 2020-06-02
            allCategoricalValues = [...allCategoricalValues, NO_DATA_LABEL]
        }
 
        return allCategoricalValues.map((value, index) => {
            const boundingOffset = isEmpty(bucketMaximums)
                ? 0
                : bucketMaximums.length - 1
            const baseColor = baseColors[index + boundingOffset]
            const color = customCategoryColors[value] ?? baseColor
            const label = customCategoryLabels[value] ?? value
 
            return new CategoricalBin({
                index,
                value,
                color,
                label,
                isHidden: !!customHiddenCategories[value],
            })
        })
    }
 
    getBinForValue(
        value: CoreValueType | undefined
    ): ColorScaleBin | undefined {
        return value === undefined
            ? undefined
            : this.legendBins.find((bin) => bin.contains(value))
    }
 
    getColor(value: CoreValueType | undefined): string | undefined {
        if (value === undefined) return this.noDataColor
        return this.getBinForValue(value)?.color
    }
}