All files / owid-grapher/grapher/core LegacyToOwidTable.ts

82.17% Statements 189/230
44.12% Branches 15/34
100% Functions 3/3
82.17% Lines 189/230

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 3291x 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 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 11x 11x 1x 1x 1x 1x 46x 46x 46x 46x 46x 138x 138x 46x 46x 46x   46x 46x             46x 46x 46x 46x 46x 46x   46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x     46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x   6x     46x 46x 46x 46x 46x 46x 46x 46x 46x 46x         46x 46x     3x         46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x     46x                               46x 46x 46x 46x 46x   46x 46x 46x 46x 46x 57x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 57x 46x 46x 46x 1x 1x 46x 1x 1x 1x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x                                                                                                                                                                                                      
// todo: Remove this file when we've migrated OWID data and OWID charts to next version
 
import { ChartTypeName } from "../core/GrapherConstants"
import { Color } from "../../coreTable/CoreTableConstants"
import { ColumnTypeNames, CoreColumnDef } from "../../coreTable/CoreColumnDef"
import { LegacyGrapherInterface } from "../core/GrapherInterface"
import {
    diffDateISOStringInDays,
    isNumber,
    makeAnnotationsSlug,
    trimObject,
    uniqBy,
} from "../../clientUtils/Util"
import {
    OwidVariablesAndEntityKey,
    OwidVariableWithDataAndSource,
    OwidEntityKey,
} from "../../clientUtils/OwidVariable"
import {
    StandardOwidColumnDefs,
    OwidTableSlugs,
    OwidColumnDef,
    EntityId,
} from "../../coreTable/OwidTableConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import { ColumnSlug, EPOCH_DATE } from "../../clientUtils/owidTypes"
import { OwidChartDimensionInterface } from "../../clientUtils/OwidVariableDisplayConfigInterface"
 
export const legacyToOwidTableAndDimensions = (
    json: OwidVariablesAndEntityKey,
    grapherConfig: Partial<LegacyGrapherInterface>
): { dimensions: OwidChartDimensionInterface[]; table: OwidTable } => {
    // Entity meta map
 
    const entityMetaById: OwidEntityKey = json.entityKey
 
    // Color maps
 
    const entityColorMap = new Map<EntityId, Color>()
    const columnColorMap = new Map<ColumnSlug, Color>()
 
    const dimensions = grapherConfig.dimensions || []
 
    grapherConfig.selectedData
        ?.filter((item) => item.entityId && item.color)
        .forEach((item) => {
            entityColorMap.set(item.entityId, item.color!)
            const varId = dimensions[item.index]?.variableId
            if (varId) columnColorMap.set(varId.toString(), item.color!)
        })
 
    // Base column defs, shared by all variable tables
 
    const baseColumnDefs: Map<ColumnSlug, CoreColumnDef> = new Map()
    StandardOwidColumnDefs.forEach((def) => {
        baseColumnDefs.set(def.slug, def)
    })
 
    const entityColorColumnSlug =
        entityColorMap.size > 0 || grapherConfig.selectedEntityColors
            ? OwidTableSlugs.entityColor
            : undefined
    if (entityColorColumnSlug) {
        baseColumnDefs.set(entityColorColumnSlug, {
            slug: entityColorColumnSlug,
            type: ColumnTypeNames.Color,
            name: entityColorColumnSlug,
        })
    }
 
    // We need to create a column for each unique [variable, targetTime] pair. So there can be
    // multiple columns for a single variable.
    const newDimensions = dimensions.map((dimension) => ({
        ...dimension,
        slug: dimension.targetYear
            ? `${dimension.variableId}-${dimension.targetYear}`
            : `${dimension.variableId}`,
    }))
    const dimensionColumns = uniqBy(newDimensions, (dim) => dim.slug)
    const variableTables = dimensionColumns.map((dimension) => {
        const variable = json.variables[dimension.variableId]
 
        // Copy the base columnDef
        const columnDefs = new Map(baseColumnDefs)
 
        // Time column
        const timeColumnDef = timeColumnDefFromOwidVariable(variable)
        columnDefs.set(timeColumnDef.slug, timeColumnDef)
 
        // Value column
        const valueColumnDef = columnDefFromOwidVariable(variable)
        const valueColumnColor =
            dimension.display?.color ??
            columnColorMap.get(dimension.variableId.toString())
        // Ensure the column slug is unique by copying it from the dimensions
        // (there can be two columns of the same variable with different targetTimes)
        valueColumnDef.slug = dimension.slug
        // Because database columns can contain mixed types, we want to avoid
        // parsing for Grapher data until we fix that.
        valueColumnDef.skipParsing = true
        if (valueColumnColor) {
            valueColumnDef.color = valueColumnColor
        }
        if (dimension) {
            valueColumnDef.display = {
                ...trimObject(valueColumnDef.display),
                ...trimObject(dimension.display),
            }
        }
        columnDefs.set(valueColumnDef.slug, valueColumnDef)
 
        // Annotations column
        const [annotationMap, annotationColumnDef] =
            annotationMapAndDefFromOwidVariable(variable)
 
        // Column values
 
        const times = timeColumnValuesFromOwidVariable(variable)
        const entityIds = variable.entities ?? []
        const entityNames = entityIds.map((id) => entityMetaById[id].name)
        const entityCodes = entityIds.map((id) => entityMetaById[id].code)
 
        // If there is a conversionFactor, apply it.
        let values = variable.values || []
        const conversionFactor = valueColumnDef.display?.conversionFactor
        if (conversionFactor !== undefined) {
            values = values.map((value) =>
                isNumber(value) ? value * conversionFactor : value
            )
        }
 
        const columnStore: { [key: string]: any[] } = {
            [OwidTableSlugs.entityId]: entityIds,
            [OwidTableSlugs.entityCode]: entityCodes,
            [OwidTableSlugs.entityName]: entityNames,
            [timeColumnDef.slug]: times,
            [valueColumnDef.slug]: values,
        }
 
        if (annotationColumnDef) {
            columnStore[annotationColumnDef.slug] = entityNames.map(
                (entityName) => annotationMap!.get(entityName)
            )
        }
 
        if (entityColorColumnSlug) {
            columnStore[entityColorColumnSlug] = entityIds.map(
                (entityId) =>
                    grapherConfig.selectedEntityColors?.[
                        entityMetaById[entityId].name
                    ] ?? entityColorMap.get(entityId)
            )
        }
 
        // Build the tables
 
        let variableTable = new OwidTable(
            columnStore,
            Array.from(columnDefs.values())
        )
 
        // If there is a targetTime set on the dimension, we need to perform the join on the
        // entities columns only, excluding any time columns.
        // We do this by dropping the column. We interpolate before which adds an originalTime
        // column which can be used to recover the time.
        const targetTime = dimension?.targetYear
        if (
            (grapherConfig.type === ChartTypeName.ScatterPlot ||
                grapherConfig.type === ChartTypeName.Marimekko) &&
            isNumber(targetTime)
        ) {
            variableTable = variableTable
                // interpolateColumnWithTolerance() won't handle injecting times beyond the current
                // allTimes. So if targetYear is 2018, and we have data up to 2017, the
                // interpolation won't add the 2018 rows (unless we apply the interpolation after
                // the big join).
                // This is why we use filterByTargetTimes() which handles that case.
                .filterByTargetTimes(
                    [targetTime],
                    valueColumnDef.display?.tolerance
                )
                // Interpolate with 0 to add originalTimes column
                .interpolateColumnWithTolerance(valueColumnDef.slug, 0)
                // Drop the time column to join table only on entity
                .dropColumns([timeColumnDef.slug])
        }
 
        return variableTable
    })
 
    let joinedVariablesTable = variableTables.length
        ? fullJoinTables(variableTables)
        : new OwidTable()
 
    // Inject a common "time" column that is used as the main time column for the table
    // e.g. for the timeline.
    for (const dayOrYearSlug of [OwidTableSlugs.day, OwidTableSlugs.year]) {
        if (joinedVariablesTable.columnSlugs.includes(dayOrYearSlug)) {
            joinedVariablesTable = joinedVariablesTable.duplicateColumn(
                dayOrYearSlug,
                {
                    slug: OwidTableSlugs.time,
                    name: OwidTableSlugs.time,
                }
            )
            // Do not inject multiple columns, terminate after one is successful
            break
        }
    }
 
    return { dimensions: newDimensions, table: joinedVariablesTable }
}
 
const fullJoinTables = (tables: OwidTable[]): OwidTable =>
    tables.reduce((joinedTable, table) => joinedTable.fullJoin(table))
 
const columnDefFromOwidVariable = (
    variable: OwidVariableWithDataAndSource
): OwidColumnDef => {
    const slug = variable.id.toString() // For now, the variableId will be the column slug
    const {
        unit,
        shortUnit,
        description,
        coverage,
        datasetId,
        datasetName,
        source,
        display,
        nonRedistributable,
    } = variable
 
    // Without this the much used var 123 appears as "Countries Continent". We could rename in Grapher but not sure the effects of that.
    const isContinent = variable.id == 123
    const name = isContinent ? "Continent" : variable.name
 
    return {
        name,
        slug,
        isDailyMeasurement: variable.display?.yearIsDay,
        unit,
        shortUnit,
        description,
        coverage,
        datasetId,
        datasetName,
        display,
        nonRedistributable,
        sourceLink: source?.link,
        sourceName: source?.name,
        dataPublishedBy: source?.dataPublishedBy,
        dataPublisherSource: source?.dataPublisherSource,
        retrievedDate: source?.retrievedDate,
        additionalInfo: source?.additionalInfo,
        owidVariableId: variable.id,
        type: isContinent ? ColumnTypeNames.Continent : ColumnTypeNames.Numeric,
    }
}
 
const timeColumnDefFromOwidVariable = (
    variable: OwidVariableWithDataAndSource
): OwidColumnDef => {
    return variable.display?.yearIsDay
        ? {
              slug: OwidTableSlugs.day,
              type: ColumnTypeNames.Day,
              name: "Day",
          }
        : {
              slug: OwidTableSlugs.year,
              type: ColumnTypeNames.Year,
              name: "Year",
          }
}
 
const timeColumnValuesFromOwidVariable = (
    variable: OwidVariableWithDataAndSource
): number[] => {
    const { display, years } = variable
    const yearsNeedTransform =
        display &&
        display.yearIsDay &&
        display.zeroDay !== undefined &&
        display.zeroDay !== EPOCH_DATE
    const yearsRaw = years || []
    return yearsNeedTransform
        ? convertLegacyYears(yearsRaw, display!.zeroDay!)
        : yearsRaw
}
 
const convertLegacyYears = (years: number[], zeroDay: string): number[] => {
    // Only shift years if the variable zeroDay is different from EPOCH_DATE
    // When the dataset uses days (`yearIsDay == true`), the days are expressed as integer
    // days since the specified `zeroDay`, which can be different for different variables.
    // In order to correctly join variables with different `zeroDay`s in a single chart, we
    // normalize all days to be in reference to a single epoch date.
    const diff = diffDateISOStringInDays(zeroDay, EPOCH_DATE)
    return years.map((y) => y + diff)
}
 
const annotationMapAndDefFromOwidVariable = (
    variable: OwidVariableWithDataAndSource
): [Map<string, string>, OwidColumnDef] | [] => {
    if (variable.display?.entityAnnotationsMap) {
        const slug = makeAnnotationsSlug(variable.id.toString())
        const annotationMap = annotationsToMap(
            variable.display.entityAnnotationsMap
        )
        const columnDef = {
            slug,
            type: ColumnTypeNames.SeriesAnnotation,
            name: slug,
        }
        return [annotationMap, columnDef]
    }
    return []
}
 
const annotationsToMap = (annotations: string): Map<string, string> => {
    // Todo: let's delete this and switch to traditional columns
    const entityAnnotationsMap = new Map<string, string>()
    const delimiter = ":"
    annotations.split("\n").forEach((line) => {
        const [key, ...words] = line.split(delimiter)
        entityAnnotationsMap.set(key.trim(), words.join(delimiter).trim())
    })
    return entityAnnotationsMap
}