All files / owid-grapher/coreTable Transforms.ts

53.39% Statements 134/251
95.65% Branches 22/23
37.5% Functions 3/8
53.39% Lines 134/251

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 3451x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 2x 8x 8x 2x 2x 8x 8x 8x 2x 2x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 25x 25x 25x 1x 1x 25x 1x 1x 24x 1x 1x 1x 22x 22x 22x 22x 22x 22x 22x 22x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 40x 40x 40x 39x 40x 40x 38x 38x 38x 40x 22x 22x 22x 6x 6x 6x 1x 1x 1x 1x                                                   1x 1x 1x 1x                                                                             1x 1x                             1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                       1x 1x 1x                                                                                                                                                                                            
import { flatten } from "../clientUtils/Util"
import { CoreColumnStore, Time, CoreValueType } from "./CoreTableConstants"
import { CoreColumnDef } from "./CoreColumnDef"
import {
    ErrorValue,
    ErrorValueTypes,
    isNotErrorValue,
    MissingValuePlaceholder,
    ValueTooLow,
    DivideByZeroError,
} from "./ErrorValues"
import { ColumnSlug } from "../clientUtils/owidTypes"
 
// In Grapher we return just the years for which we have values for. This puts MissingValuePlaceholder
// in the spots where we are missing values (added to make computing rolling windows easier).
// Takes an array of value/year pairs and expands it so that there is an undefined
// for each missing value from the first year to the last year, preserving the position of
// the existing values.
export const insertMissingValuePlaceholders = (
    values: number[],
    times: number[]
): (number | MissingValuePlaceholder)[] => {
    const startTime = times[0]
    const endTime = times[times.length - 1]
    const filledRange = []
    let time = startTime
    const timeToValueIndex = new Map()
    times.forEach((time, index) => {
        timeToValueIndex.set(time, index)
    })
    while (time <= endTime) {
        filledRange.push(
            timeToValueIndex.has(time)
                ? values[timeToValueIndex.get(time)]
                : ErrorValueTypes.MissingValuePlaceholder
        )
        time++
    }
    return filledRange
}
 
// todo: add the precision param to ensure no floating point effects
export function computeRollingAverage(
    numbers: (number | undefined | null | ErrorValue)[],
    windowSize: number,
    align: "right" | "center" = "right"
): (number | ErrorValue)[] {
    const result: (number | ErrorValue)[] = []
 
    for (let valueIndex = 0; valueIndex < numbers.length; valueIndex++) {
        // If a value is undefined in the original input, keep it undefined in the output
        const currentVal = numbers[valueIndex]
        if (currentVal === null) {
            result[valueIndex] = ErrorValueTypes.NullButShouldBeNumber
            continue
        } else if (currentVal === undefined) {
            result[valueIndex] = ErrorValueTypes.UndefinedButShouldBeNumber
            continue
        } else if (currentVal instanceof ErrorValue) {
            result[valueIndex] = currentVal
            continue
        }
 
        // Take away 1 for the current value (windowSize=1 means no smoothing & no expansion)
        const expand = windowSize - 1
 
        // With centered smoothing, expand uneven windows asymmetrically (ceil & floor) to ensure
        // a correct number of window values get taken into account.
        // Arbitrarily biased towards left (past).
        const expandLeft = align === "center" ? Math.ceil(expand / 2) : expand
        const expandRight = align === "center" ? Math.floor(expand / 2) : 0
 
        const startIndex = Math.max(valueIndex - expandLeft, 0)
        const endIndex = Math.min(valueIndex + expandRight, numbers.length - 1)
 
        let count = 0
        let sum = 0
        for (
            let windowIndex = startIndex;
            windowIndex <= endIndex;
            windowIndex++
        ) {
            const value = numbers[windowIndex]
            if (
                value !== undefined &&
                value !== null &&
                !(value instanceof ErrorValue)
            ) {
                sum += value!
                count++
            }
        }
 
        result[valueIndex] = sum / count
    }
 
    return result
}
 
// Assumptions: data is sorted by entity, then time
// todo: move tests over from CE
const timeSinceEntityExceededThreshold = (
    columnStore: CoreColumnStore,
    timeSlug: ColumnSlug,
    entitySlug: ColumnSlug,
    columnSlug: ColumnSlug,
    thresholdAsString: string
): (number | ValueTooLow)[] => {
    const threshold = parseFloat(thresholdAsString)
    const groupValues = columnStore[entitySlug] as string[]
    const columnValues = columnStore[columnSlug] as number[]
    const timeValues = columnStore[timeSlug] as number[]
    let currentGroup: string
    let groupExceededThresholdAtTime: number
    return columnValues.map((value, index) => {
        const group = groupValues[index]
        const currentTime = timeValues[index]
        if (group !== currentGroup) {
            if (!isNotErrorValue(value)) return value
            if (value < threshold) return ErrorValueTypes.ValueTooLow

            currentGroup = group
            groupExceededThresholdAtTime = currentTime
        }
        return currentTime - groupExceededThresholdAtTime
    })
}
 
// Assumptions: data is sorted by entity, then time
// todo: move tests over from CE
const rollingAverage = (
    columnStore: CoreColumnStore,
    timeSlug: ColumnSlug,
    entitySlug: ColumnSlug,
    columnSlug: ColumnSlug,
    windowSize: number
): (number | ErrorValue)[] => {
    const entityNames = columnStore[entitySlug] as string[]
    const columnValues = columnStore[columnSlug] as number[]
    const timeValues = columnStore[timeSlug] as number[]
    const len = entityNames.length
    if (!len) return []
    let currentEntity = entityNames[0]
    let currentValues: number[] = []
    let currentTimes: Time[] = []

    const groups: (number | ErrorValue)[][] = []
    for (let rowIndex = 0; rowIndex <= len; rowIndex++) {
        const entityName = entityNames[rowIndex]
        const value = columnValues[rowIndex]
        const time = timeValues[rowIndex]
        if (currentEntity !== entityName) {
            const averages = computeRollingAverage(
                insertMissingValuePlaceholders(currentValues, currentTimes),
                windowSize
            ).filter(
                (value) => !(value === ErrorValueTypes.MissingValuePlaceholder)
            ) // filter the placeholders back out
            groups.push(averages)
            if (value === undefined) break // We iterate to <= so that we push the last row
            currentValues = []
            currentTimes = []
            currentEntity = entityName
        }
        currentValues.push(value)
        currentTimes.push(time)
    }
    return flatten(groups)
}
 
const divideBy = (
    columnStore: CoreColumnStore,
    numeratorSlug: ColumnSlug,
    denominatorSlug: ColumnSlug
): (number | DivideByZeroError)[] => {
    const numeratorValues = columnStore[numeratorSlug] as number[]
    const denominatorValues = columnStore[denominatorSlug] as number[]
    return denominatorValues.map((denominator, index) => {
        if (denominator === 0) return ErrorValueTypes.DivideByZeroError
        const numerator = numeratorValues[index]
        if (!isNotErrorValue(numerator)) return numerator
        if (!isNotErrorValue(denominator)) return denominator
        return numerator / denominator
    })
}
 
const multiplyBy = (
    columnStore: CoreColumnStore,
    columnSlug: ColumnSlug,
    factor: number
) =>
    columnStore[columnSlug].map((value) =>
        isNotErrorValue(value) ? (value as number) * factor : value
    )
 
const subtract = (
    columnStore: CoreColumnStore,
    columnSlugA: ColumnSlug,
    columnSlugB: ColumnSlug
) => {
    const values = columnStore[columnSlugA] as number[]
    const subValues = columnStore[columnSlugB] as number[]
    return subValues.map((subValue, index) => {
        const value = values[index]
        if (!isNotErrorValue(value)) return value
        if (!isNotErrorValue(subValue)) return subValue
        return value - subValue
    })
}
 
enum WhereOperators {
    is = "is",
    isNot = "isNot",
    isGreaterThan = "isGreaterThan",
    isGreaterThanOrEqual = "isGreaterThanOrEqual",
    isLessThan = "isLessThan",
    isLessThanOrEqual = "isLessThanOrEqual",
}
// Todo: add tests/expand capabilities/remove?
// Currently this just supports `columnSlug where someColumnSlug (isNot|is) this or that or this`
const where = (
    columnStore: CoreColumnStore,
    columnSlug: ColumnSlug,
    conditionSlug: ColumnSlug,
    ...condition: string[]
): CoreValueType[] => {
    const values = columnStore[columnSlug]
    const conditionValues = columnStore[conditionSlug]
    const operator = condition.shift()
    let passes = (value: any) => true
    if (operator === WhereOperators.isNot || operator === WhereOperators.is) {
        const result = operator === "isNot" ? false : true
        const list = condition.join(" ").split(" or ")
        const set = new Set(list)
        passes = (value: any) => (set.has(value) ? result : !result)
    } else if (operator === WhereOperators.isGreaterThan)
        passes = (value: any) => value > parseFloat(condition.join(""))
    else if (operator === WhereOperators.isGreaterThanOrEqual)
        passes = (value: any) => value >= parseFloat(condition.join(""))
    else if (operator === WhereOperators.isLessThan)
        passes = (value: any) => value < parseFloat(condition.join(""))
    else if (operator === WhereOperators.isLessThanOrEqual)
        passes = (value: any) => value <= parseFloat(condition.join(""))

    return values.map((value, index) =>
        passes(conditionValues[index]) ? value : ErrorValueTypes.FilteredValue
    )
}
 
// Assumptions: data is sorted by entity, then time, and time is a continous integer with a row for each time step.
// todo: move tests over from CE
const percentChange = (
    columnStore: CoreColumnStore,
    timeSlug: ColumnSlug,
    entitySlug: ColumnSlug,
    columnSlug: ColumnSlug,
    windowSize: number
): (number | ErrorValue)[] => {
    const entityNames = columnStore[entitySlug] as string[]
    const columnValues = columnStore[columnSlug] as number[]
 
    // If windowSize is 0 then there is zero change for every valid value
    if (!windowSize)
        return columnValues.map((val) => (isNotErrorValue(val) ? 0 : val))
 
    let currentEntity: string
    return columnValues.map((value: any, index) => {
        const entity = entityNames[index]
        const previousEntity = entityNames[index - windowSize] as any
        const previousValue = columnValues[index - windowSize] as any
        if (
            !currentEntity ||
            currentEntity !== entity ||
            previousEntity !== entity
        ) {
            currentEntity = entity
            return ErrorValueTypes.NoValueToCompareAgainst
        }
        if (previousValue instanceof ErrorValue) return previousValue
        if (value instanceof ErrorValue) return value
 
        if (previousValue === 0) return ErrorValueTypes.DivideByZeroError
        if (previousValue === undefined)
            return ErrorValueTypes.NoValueToCompareAgainst
 
        return (100 * (value - previousValue)) / previousValue
    })
}
 
// Todo: remove?
const asPercentageOf = (
    columnStore: CoreColumnStore,
    numeratorSlug: ColumnSlug,
    denominatorSlug: ColumnSlug
): (number | DivideByZeroError)[] =>
    divideBy(columnStore, numeratorSlug, denominatorSlug).map((num) =>
        typeof num === "number" ? 100 * num : num
    )
 
const availableTransforms: any = {
    asPercentageOf: asPercentageOf,
    timeSinceEntityExceededThreshold: timeSinceEntityExceededThreshold,
    divideBy: divideBy,
    rollingAverage: rollingAverage,
    percentChange: percentChange,
    multiplyBy: multiplyBy,
    subtract: subtract,
    where: where,
} as const
 
export const AvailableTransforms = Object.keys(availableTransforms)
 
export const applyTransforms = (
    columnStore: CoreColumnStore,
    defs: CoreColumnDef[]
): CoreColumnStore => {
    defs.forEach((def) => {
        const words = def.transform!.split(" ")
        const transformName = words.find(
            (word) => availableTransforms[word] !== undefined
        )
        if (!transformName) {
            console.warn(`Warning: transform '${transformName}' not found`)
            return
        }
        const params = words.filter((word) => word !== transformName)
        const fn = availableTransforms[transformName]
        try {
            columnStore[def.slug] = fn(columnStore, ...params)
        } catch (err) {
            console.error(
                `Error performing transform '${def.transform}' for column '${
                    def.slug
                }'. Expected args: ${fn.length}. Provided args: ${
                    1 + params.length
                }. Ran as ${transformName}(columnStore, ${params
                    .map((param) => `"${param}"`)
                    .join(",")}).`
            )
            console.error(err)
        }
    })
    return columnStore
}