All files / owid-grapher/coreTable OwidTable.ts

87.44% Statements 550/629
87.96% Branches 95/108
92.5% Functions 37/40
87.44% Lines 550/629

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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 9861x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 65x 65x 1x 1x 65x 65x 1x 1x 1x           1x 1x 1x           1x 1x 1x 58x 58x 58x 58x 58x 1x 1x 1x 58x 58x 58x 58x 58x 1x 1x 1x 1x 1x 1x 58x 58x 58x 58x 58x 1x 1x 58x 58x 2x 58x 58x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 6x     6x 1x 1x 1x 6x 6x 6x 6x 1x 1x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 1x 1x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 1x 1x 63x 63x 63x 63x 63x 63x 63x 1x 1x 1x 10x 10x 10x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 5x 5x 5x 5x 5x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 886x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 886x 886x 886x 886x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 12x 12x 8x 8x 8x 8x 8x 2x 2x 2x 2x 2x 8x 16x 16x 16x 2x 2x 2x 4x 16x 16x 14x 14x 14x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 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 11x 11x 11x 11x 11x 11x 11x 11x 11x 25x 25x 25x 25x 80x 157x 157x 157x 25x 25x 25x 25x 25x 25x 25x 25x 25x 42x 42x 42x 42x 25x 25x 25x 11x 11x 11x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 17x 17x 17x 17x 17x 34x 34x 34x 34x 34x 34x 34x 34x 17x 17x 11x 11x 11x 11x 22x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 1x 1x 5x 5x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 6x 6x 1x 1x 1x 1x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 18x 18x 18x 18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import {
    max,
    min,
    intersectionOfSets,
    findClosestTimeIndex,
    sumBy,
    flatten,
    uniq,
    sortNumeric,
    last,
    groupBy,
    isNumber,
    isEmpty,
    getClosestTimePairs,
    sortedFindClosest,
    pairs,
    maxBy,
    minBy,
    cagr,
    makeAnnotationsSlug,
} from "../clientUtils/Util"
import { isPresent } from "../clientUtils/isPresent"
import {
    Integer,
    Time,
    TransformType,
    CoreColumnStore,
    Color,
    CoreValueType,
} from "./CoreTableConstants"
import { ColumnTypeNames } from "./CoreColumnDef"
import { CoreTable } from "./CoreTable"
import { populationMap } from "./PopulationMap"
import {
    EntityName,
    OwidColumnDef,
    OwidRow,
    OwidTableSlugs,
} from "./OwidTableConstants"
import { ErrorValue, ErrorValueTypes, isNotErrorValue } from "./ErrorValues"
import { TimeBound } from "../clientUtils/TimeBounds"
import {
    getOriginalTimeColumnSlug,
    makeOriginalTimeSlugFromColumnSlug,
    timeColumnSlugFromColumnDef,
    toPercentageColumnDef,
} from "./OwidTableUtil"
import {
    imemo,
    linearInterpolation,
    toleranceInterpolation,
    replaceDef,
    InterpolationProvider,
} from "./CoreTableUtils"
import { CoreColumn, ColumnTypeMap } from "./CoreTableColumns"
import { ColumnSlug } from "../clientUtils/owidTypes"
 
// An OwidTable is a subset of Table. An OwidTable always has EntityName, EntityCode, EntityId, and Time columns,
// and value column(s). Whether or not we need in the long run is uncertain and it may just be a stepping stone
// to go from our Variables paradigm to the Table paradigm.
export class OwidTable extends CoreTable<OwidRow, OwidColumnDef> {
    @imemo get availableEntityNames(): any[] {
        return Array.from(this.availableEntityNameSet)
    }
 
    @imemo get availableEntityNameSet(): Set<string> {
        return new Set<string>(this.entityNameColumn.uniqValues)
    }
 
    // todo: can we remove at some point?
    @imemo get entityIdToNameMap(): Map<number, string> {
        return this.valueIndex(
            this.entityIdColumn.slug,
            this.entityNameColumn.slug
        ) as Map<number, string>
    }
 
    // todo: can we remove at some point?
    @imemo get entityCodeToNameMap(): Map<string, string> {
        return this.valueIndex(
            this.entityCodeColumn.slug,
            this.entityNameColumn.slug
        ) as Map<string, string>
    }
 
    // todo: can we remove at some point?
    @imemo get entityNameToIdMap(): Map<string, number> {
        return this.valueIndex(
            this.entityNameColumn.slug,
            this.entityIdColumn.slug
        ) as Map<string, number>
    }
 
    // todo: can we remove at some point?
    @imemo get entityNameToCodeMap(): Map<string, string> {
        return this.valueIndex(
            this.entityNameColumn.slug,
            this.entityCodeColumn.slug
        ) as Map<string, string>
    }
 
    @imemo get maxTime(): number | undefined {
        return last(this.allTimes)
    }
 
    @imemo get entityIdColumn(): CoreColumn {
        return (
            this.getFirstColumnWithType(ColumnTypeNames.EntityId) ??
            this.get(OwidTableSlugs.entityId)
        )
    }
 
    @imemo get entityCodeColumn(): CoreColumn {
        return (
            this.getFirstColumnWithType(ColumnTypeNames.EntityCode) ??
            this.get(OwidTableSlugs.entityCode)
        )
    }
 
    @imemo get minTime(): Time {
        return this.allTimes[0]
    }
 
    @imemo private get allTimes(): Time[] {
        return this.sortedByTime.get(this.timeColumn.slug).values
    }
 
    @imemo get rowIndicesByEntityName(): Map<string, number[]> {
        return this.rowIndex([this.entityNameSlug])
    }
 
    getAnnotationColumnSlug(columnDef: OwidColumnDef): string | undefined {
        return isEmpty(columnDef?.annotationsColumnSlug)
            ? makeAnnotationsSlug(columnDef.slug)
            : columnDef.annotationsColumnSlug
    }
 
    // todo: instead of this we should probably make annotations another property on charts—something like "annotationsColumnSlugs"
    getAnnotationColumnForColumn(columnSlug: ColumnSlug): CoreColumn {
        const def = this.get(columnSlug).def as OwidColumnDef
        const slug = this.getAnnotationColumnSlug(def)
        return this.get(slug)
    }
 
    getTimesUniqSortedAscForColumns(columnSlugs: ColumnSlug[]): number[] {
        // todo: should be easy to speed up if necessary.
        return sortNumeric(
            uniq(
                flatten(
                    this.getColumns(columnSlugs)
                        .filter((col) => col)
                        .map((col) => col.uniqTimesAsc)
                )
            )
        )
    }
 
    timeDomainFor(slugs: ColumnSlug[]): [Time | undefined, Time | undefined] {
        const cols = this.getColumns(slugs)
        const mins = cols.map((col) => col.minTime)
        const maxes = cols.map((col) => col.maxTime)
        return [min(mins), max(maxes)]
    }
 
    originalTimeDomainFor(
        slugs: ColumnSlug[]
    ): [Time | undefined, Time | undefined] {
        const cols = this.getColumns(slugs)
        const mins = cols.map((col) => min(col.originalTimes))
        const maxes = cols.map((col) => max(col.originalTimes))
        return [min(mins), max(maxes)]
    }
 
    filterByEntityNames(names: EntityName[]): this {
        const namesSet = new Set(names)
        return this.columnFilter(
            this.entityNameSlug,
            (value) => namesSet.has(value as string),
            `Filter out all entities except '${names}'`
        )
    }
 
    // Does a stable sort by time. You can refer to this table for fast time filtering.
    @imemo private get sortedByTime(): this {
        if (this.timeColumn.isMissing) return this
        return this.sortBy([this.timeColumn.slug])
    }
 
    filterByTimeRange(start: TimeBound, end: TimeBound): this {
        // We may want to do this time adjustment in Grapher instead of here.
        const adjustedStart = start === Infinity ? this.maxTime! : start
        const adjustedEnd = end === -Infinity ? this.minTime! : end
        // todo: we should set a time column onload so we don't have to worry about it again.
        const timeColumnSlug = this.timeColumn?.slug || OwidTableSlugs.time
        // Sorting by time, because incidentally some parts of the code depended on this method
        // returning sorted rows.
        return this.sortedByTime.columnFilter(
            timeColumnSlug,
            (time) => time >= adjustedStart && time <= adjustedEnd,
            `Keep only rows with Time between ${adjustedStart} - ${adjustedEnd}`
        )
    }
 
    filterByTargetTimes(targetTimes: Time[], tolerance = 0): this {
        const timeColumn = this.timeColumn!
        const timeValues = timeColumn.valuesIncludingErrorValues
        const entityNameToIndices = this.rowIndicesByEntityName
        const matchingIndices = new Set<number>()
        this.availableEntityNames.forEach((entityName) => {
            const indices = entityNameToIndices.get(entityName) || []
            const allTimes = indices.map(
                (index) => timeValues[index]
            ) as number[]
 
            targetTimes.forEach((targetTime) => {
                const index = findClosestTimeIndex(
                    allTimes,
                    targetTime,
                    tolerance
                )
                if (index !== undefined) matchingIndices.add(indices[index])
            })
        })
 
        return this.columnFilter(
            this.entityNameSlug,
            (row, index) => matchingIndices.has(index),
            `Keep a row for each entity for each of the closest times ${targetTimes.join(
                ", "
            )} with tolerance ${tolerance}`
        )
    }
 
    dropRowsWithErrorValuesForColumn(slug: ColumnSlug): this {
        return this.columnFilter(
            slug,
            (value) => isNotErrorValue(value),
            `Drop rows with empty or ErrorValues in ${slug} column`
        )
    }
 
    // TODO rewrite with column ops
    // TODO move to CoreTable
    dropRowsWithErrorValuesForAnyColumn(slugs: ColumnSlug[]): this {
        return this.rowFilter(
            (row) => slugs.every((slug) => isNotErrorValue(row[slug])),
            `Drop rows with empty or ErrorValues in any column: ${slugs.join(
                ", "
            )}`
        )
    }
 
    // TODO rewrite with column ops
    // TODO move to CoreTable
    dropRowsWithErrorValuesForAllColumns(slugs: ColumnSlug[]): this {
        return this.rowFilter(
            (row) => slugs.some((slug) => isNotErrorValue(row[slug])),
            `Drop rows with empty or ErrorValues in every column: ${slugs.join(
                ", "
            )}`
        )
    }
 
    private sumsByTime(columnSlug: ColumnSlug): Map<number, number> {
        const timeValues = this.timeColumn.values
        const values = this.get(columnSlug).values as number[]
        if (timeValues.length !== values.length)
            // Throwing here may seem drastic but this will lead to an error in any case if the lengths are different
            // (can happen when dropping rows with errors is done incorrectly).
            // When it happens then throwing here is an easier to diagnose error
            throw Error(
                `Tried to run sumsByTime when timeValues (${timeValues.length}) and values (${values.length}) had different length`
            )
        const map = new Map<number, number>()
        timeValues.forEach((time, index) =>
            map.set(time, (map.get(time) ?? 0) + values[index])
        )
        return map
    }
 
    // todo: this needs tests (and/or drop in favor of someone else's package)
    // Shows how much each entity contributed to the given column for each time period
    toPercentageFromEachEntityForEachTime(columnSlug: ColumnSlug) {
        if (!this.has(columnSlug)) return this
        const timeColumn = this.timeColumn!
        const col = this.get(columnSlug)
        const timeTotals = this.sumsByTime(columnSlug)
        const timeValues = timeColumn.values
        const newDefs = replaceDef(this.defs, [
            toPercentageColumnDef(col.def, ColumnTypeNames.RelativePercentage),
        ])
        const newColumnStore: CoreColumnStore = {
            ...this.columnStore,
            [columnSlug]: this.columnStore[columnSlug].map((val, index) => {
                const timeTotal = timeTotals.get(timeValues[index])
                if (timeTotal === 0) return ErrorValueTypes.DivideByZeroError
                return (100 * (val as number)) / timeTotal!
            }),
        }
        return this.transform(
            newColumnStore,
            newDefs,
            `Transformed ${columnSlug} column to be % contribution of each entity for that time`,
            TransformType.UpdateColumnDefsAndApply
        )
    }
 
    // If you want to see how much each column contributed to the entity for that year, use this.
    // NB: Uses absolute value. So if one entity added 100, and another -100, they both would have contributed "50%" to that year.
    // Otherwise we'd have NaN.
    toPercentageFromEachColumnForEachEntityAndTime(columnSlugs: ColumnSlug[]) {
        columnSlugs = columnSlugs.filter((slug) => this.has(slug))
        if (!columnSlugs.length) return this
 
        const newDefs = this.defs.map((def) => {
            if (columnSlugs.includes(def.slug))
                return toPercentageColumnDef(
                    def,
                    ColumnTypeNames.RelativePercentage
                )
            return def
        })
 
        const columnStore = this.columnStore
        const columnStorePatch: CoreColumnStore = {}
 
        const totals = new Array(this.numRows).fill(0).map((_, i) =>
            sumBy(columnSlugs, (slug) => {
                const value = columnStore[slug][i]
                return isNumber(value) ? Math.abs(value) : 0
            })
        )
 
        columnSlugs.forEach((slug) => {
            columnStorePatch[slug] = columnStore[slug].map((value, i) => {
                const total = totals[i]
                if (!isNumber(value) || !isNumber(total)) return value
                if (total === 0) return ErrorValueTypes.DivideByZeroError
                return (100 * Math.abs(value)) / total
            })
        })
 
        const newColumnStore = {
            ...columnStore,
            ...columnStorePatch,
        }
 
        return this.transform(
            newColumnStore,
            newDefs,
            `Transformed columns from absolute numbers to % of abs sum of ${columnSlugs.join(
                ","
            )} `,
            TransformType.UpdateColumnDefs
        )
    }
 
    // todo: this needs tests (and/or drop in favor of someone else's package)
    // If you wanted to build a table showing something like GDP growth relative to 1950, use this.
    toTotalGrowthForEachColumnComparedToStartTime(
        startTimeBound: TimeBound,
        columnSlugs: ColumnSlug[]
    ): this {
        if (this.timeColumn.isMissing) return this
        const timeColumnSlug = this.timeColumn.slug
        const newDefs = this.defs.map((def) => {
            if (columnSlugs.includes(def.slug))
                return toPercentageColumnDef(
                    def,
                    ColumnTypeNames.PercentChangeOverTime
                )
            return def
        })
        const newRows = flatten(
            Object.values(
                groupBy(
                    this.sortedByTime.rows,
                    (row) => row[this.entityNameSlug]
                )
            ).map((rowsForSingleEntity) => {
                columnSlugs.forEach((valueSlug) => {
                    let comparisonValue: number
                    rowsForSingleEntity = rowsForSingleEntity.map(
                        (row: Readonly<OwidRow>) => {
                            const newRow = {
                                ...row,
                            }

                            const value = row[valueSlug]

                            if (row[timeColumnSlug] < startTimeBound) {
                                newRow[valueSlug] =
                                    ErrorValueTypes.MissingValuePlaceholder
                            } else if (!isNumber(value)) {
                                newRow[valueSlug] =
                                    ErrorValueTypes.NaNButShouldBeNumber
                            } else if (comparisonValue !== undefined) {
                                // Note: comparisonValue can be negative!
                                // +value / -comparisonValue = negative growth, which is incorrect.
                                newRow[valueSlug] =
                                    (100 * (value - comparisonValue)) /
                                    Math.abs(comparisonValue)
                            } else if (value === 0) {
                                newRow[valueSlug] =
                                    ErrorValueTypes.MissingValuePlaceholder
                            } else {
                                comparisonValue = value
                                newRow[valueSlug] = 0
                            }

                            return newRow
                        }
                    )
                })
                return rowsForSingleEntity
            })
        )

        return this.transform(
            newRows,
            newDefs,
            `Transformed columns from absolute values to % of time ${startTimeBound} for columns ${columnSlugs.join(
                ","
            )} `,
            TransformType.UpdateColumnDefs
        )
    }
 
    keepMinTimeAndMaxTimeForEachEntityOnly(): this {
        const indexMap = this.rowIndicesByEntityName
        const timeColumn = this.timeColumn
        if (timeColumn.isMissing) return this
        const timeValues = timeColumn.valuesIncludingErrorValues
        const matchingIndices = new Set<number>()
        indexMap.forEach((indices) =>
            [minBy, maxBy]
                .map((f) => f(indices, (index) => timeValues[index]))
                .filter(isPresent)
                .forEach((index) => matchingIndices.add(index))
        )
        return this.columnFilter(
            timeColumn.slug,
            (row, index) => matchingIndices.has(index),
            `Keep minTime & maxTime rows only for each entity`
        )
    }
 
    private getAverageAnnualChangeIndicesByEntity(
        columnSlugs: ColumnSlug[]
    ): Map<EntityName, [number, number]> {
        const columns = columnSlugs.map((slug) => this.get(slug))
        const indexMap = this.rowIndicesByEntityName
        const timeValues = this.timeColumn.valuesIncludingErrorValues
 
        // Find indices of min & max rows
        const entityNameToIndices = new Map<EntityName, [number, number]>()
        indexMap.forEach((indices, entityName) => {
            // We are discarding every row which contains a 0 for any columnSlug.
            // Technically, to be more correct, we should support distinct min/max indices for each
            // columnSlug, but that only makes a tiny difference in a tiny subset of charts.
            const nonZeroValueIndices = indices.filter((index) =>
                columns.every((col) => {
                    const value = col.valuesIncludingErrorValues[index]
                    return isNumber(value) && value !== 0
                })
            )
            const minIndex = minBy(
                nonZeroValueIndices,
                (index) => timeValues[index]
            )
            const maxIndex = maxBy(indices, (index) => timeValues[index])
            if (minIndex === undefined || maxIndex === undefined) return
 
            const allValuePairsHaveDistinctTime = columns.every((col) => {
                const originalTimes =
                    this.columnStore[col.originalTimeColumnSlug]
                return originalTimes[minIndex] !== originalTimes[maxIndex]
            })
            if (allValuePairsHaveDistinctTime)
                entityNameToIndices.set(entityName, [minIndex, maxIndex])
        })
 
        return entityNameToIndices
    }
 
    toAverageAnnualChangeForEachEntity(columnSlugs: ColumnSlug[]): this {
        columnSlugs = columnSlugs.filter((slug) => this.has(slug))
        if (
            this.timeColumn.isMissing ||
            !(this.timeColumn instanceof ColumnTypeMap.Year) ||
            columnSlugs.length === 0
        )
            return this
 
        const columns = columnSlugs.map((slug) => this.get(slug))
        const entityNameToIndices =
            this.getAverageAnnualChangeIndicesByEntity(columnSlugs)
 
        // Overwrite table rows
        const rows: OwidRow[] = []
        entityNameToIndices.forEach((indices) => {
            const [startRow, endRow] = this.rowsAt(indices)
            const newRow: OwidRow = {
                ...endRow,
            }
            columns.forEach((col) => {
                const timeSlug = col.originalTimeColumnSlug
                const yearsElapsed = endRow[timeSlug] - startRow[timeSlug]
                newRow[col.slug] = cagr(
                    startRow[col.slug],
                    endRow[col.slug],
                    yearsElapsed
                )
            })
            rows.push(newRow)
        })
 
        const newDefs = replaceDef(
            this.defs,
            columns.map((col) =>
                toPercentageColumnDef(
                    col.def,
                    ColumnTypeNames.PercentChangeOverTime
                )
            )
        )
 
        return this.transform(
            rows,
            newDefs,
            `Average annual change for columns: ${columnSlugs.join(", ")}`,
            TransformType.UpdateRows
        )
    }
 
    // Return slugs that would be good to chart
    @imemo get suggestedYColumnSlugs(): string[] {
        const skips = new Set<ColumnSlug>([
            OwidTableSlugs.entityId,
            OwidTableSlugs.time,
            OwidTableSlugs.year,
            OwidTableSlugs.day,
        ])
        return this.numericColumnSlugs.filter((slug) => !skips.has(slug))
    }
 
    // Give our users a clean CSV of each Grapher. Assumes an Owid Table with entityName.
    toPrettyCsv(): string {
        return this.dropColumns([
            OwidTableSlugs.entityId,
            OwidTableSlugs.time,
            OwidTableSlugs.entityColor,
        ])
            .sortBy([this.entityNameSlug])
            .toCsvWithColumnNames()
    }
 
    @imemo get entityNameColorIndex(): Map<EntityName, Color> {
        return this.valueIndex(
            this.entityNameSlug,
            OwidTableSlugs.entityColor
        ) as Map<EntityName, Color>
    }
 
    getColorForEntityName(entityName: EntityName): Color | undefined {
        return this.entityNameColorIndex.get(entityName)
    }
 
    @imemo get columnDisplayNameToColorMap(): Map<string, Color> {
        return new Map(
            this.columnsAsArray
                .filter((col) => col.def.color)
                .map((col) => [col.displayName, col.def.color!])
        )
    }
 
    getColorForColumnByDisplayName(displayName: string) {
        return this.columnDisplayNameToColorMap.get(displayName)
    }
 
    // This assumes the table is sorted where the times for entity names go in asc order.
    // The whole table does not have to be sorted by time.
    getLatestValueForEntity(
        entityName: EntityName,
        columnSlug: ColumnSlug
    ): CoreValueType | undefined {
        const indices = this.rowIndicesByEntityName.get(entityName)
        if (!indices) return undefined
        const values = this.get(columnSlug).valuesIncludingErrorValues
        const descending = indices.slice().reverse()
        const index = descending.find(
            (index) => !(values[index] instanceof ErrorValue)
        )
        return index !== undefined ? values[index] : undefined
    }
 
    entitiesWith(columnSlugs: ColumnSlug[]): Set<EntityName> {
        if (!columnSlugs.length) return new Set()
        if (columnSlugs.length === 1)
            return new Set(this.get(columnSlugs[0]).uniqEntityNames)
 
        return intersectionOfSets<EntityName>(
            columnSlugs.map((slug) => new Set(this.get(slug).uniqEntityNames))
        )
    }
 
    // Retrieves the two columns `columnSlug` and `timeColumnSlug` from the table and
    // passes their values to the respective interpolation method.
    // `withAllRows` is expected to be completed and sorted.
    private interpolate<K>(
        withAllRows: this,
        columnSlug: ColumnSlug,
        timeColumnSlug: ColumnSlug,
        interpolation: InterpolationProvider<K>,
        context: K
    ): { values: number[]; times: number[] } {
        const groupBoundaries = withAllRows.groupBoundaries(this.entityNameSlug)
        const newValues = withAllRows
            .get(columnSlug)
            .valuesIncludingErrorValues.slice() as number[]
        const newTimes = withAllRows
            .get(timeColumnSlug)
            .valuesIncludingErrorValues.slice() as Time[]
 
        groupBoundaries.forEach((_, index) => {
            interpolation(
                newValues,
                newTimes,
                context,
                groupBoundaries[index],
                groupBoundaries[index + 1]
            )
        })
 
        return {
            values: newValues,
            times: newTimes,
        }
    }
 
    // TODO generalize `interpolateColumnWithTolerance` and `interpolateColumnLinearly` more
    // There are finicky details in both of them that complicate this
    interpolateColumnWithTolerance(
        columnSlug: ColumnSlug,
        toleranceOverride?: number
    ): this {
        // If the column doesn't exist, return the table unchanged.
        if (!this.has(columnSlug)) return this
 
        const column = this.get(columnSlug)
        const columnDef = column.def as OwidColumnDef
        const tolerance = toleranceOverride ?? column.tolerance ?? 0
 
        const timeColumnOfTable = !this.timeColumn.isMissing
            ? this.timeColumn
            : // CovidTable does not have a day or year column so we need to use time.
              (this.get(OwidTableSlugs.time) as CoreColumn)
 
        const maybeTimeColumnOfValue =
            getOriginalTimeColumnSlug(this, columnSlug) ??
            timeColumnSlugFromColumnDef(columnDef)
        const timeColumnOfValue = this.get(maybeTimeColumnOfValue)
        const originalTimeSlug = makeOriginalTimeSlugFromColumnSlug(columnSlug)
 
        let columnStore: CoreColumnStore
        if (tolerance) {
            const withAllRows = this.complete([
                this.entityNameSlug,
                timeColumnOfTable.slug,
            ]).sortBy([this.entityNameSlug, timeColumnOfTable.slug])
 
            const interpolationResult = this.interpolate(
                withAllRows,
                columnSlug,
                timeColumnOfValue.slug,
                toleranceInterpolation,
                { timeTolerance: tolerance }
            )
 
            columnStore = {
                ...withAllRows.columnStore,
                [columnSlug]: interpolationResult.values,
                [originalTimeSlug]: interpolationResult.times,
            }
        } else {
            // If there is no tolerance still append the tolerance column
            columnStore = {
                ...this.columnStore,
                [originalTimeSlug]:
                    timeColumnOfValue.valuesIncludingErrorValues,
            }
        }
 
        return this.transform(
            columnStore,
            [
                ...this.defs,
                {
                    ...timeColumnOfValue.def,
                    slug: originalTimeSlug,
                },
            ],
            `Interpolated values in column ${columnSlug} with tolerance ${tolerance} and appended column ${originalTimeSlug} with the original times`,
            TransformType.UpdateColumnDefs
        )
    }
 
    interpolateColumnLinearly(
        columnSlug: ColumnSlug,
        extrapolate: boolean = false
    ): this {
        // If the column doesn't exist, return the table unchanged.
        if (!this.has(columnSlug)) return this
 
        const column = this.get(columnSlug)
        const columnDef = column?.def as OwidColumnDef
 
        const maybeTimeColumnSlug =
            getOriginalTimeColumnSlug(this, columnSlug) ??
            timeColumnSlugFromColumnDef(columnDef)
        const timeColumn =
            this.get(maybeTimeColumnSlug) ??
            (this.get(OwidTableSlugs.time) as CoreColumn) // CovidTable does not have a day or year column so we need to use time.
 
        // todo: we can probably do this once early in the pipeline so we dont have to do it again since complete and sort can be expensive.
        const withAllRows = this.complete([
            this.entityNameSlug,
            timeColumn.slug,
        ]).sortBy([this.entityNameSlug, timeColumn.slug])
 
        const interpolationResult = this.interpolate(
            withAllRows,
            columnSlug,
            timeColumn.slug,
            linearInterpolation,
            { extrapolateAtStart: extrapolate, extrapolateAtEnd: extrapolate }
        )
 
        const columnStore = {
            ...withAllRows.columnStore,
            [columnSlug]: interpolationResult.values,
        }
 
        return this.transform(
            columnStore,
            [
                ...this.defs,
                {
                    ...timeColumn.def,
                },
            ],
            `Interpolated values in column ${columnSlug} linearly`,
            TransformType.UpdateColumnDefs
        )
    }
 
    interpolateColumnsByClosestTimeMatch(
        columnSlugA: ColumnSlug,
        columnSlugB: ColumnSlug
    ): this {
        if (!this.has(columnSlugA) || !this.has(columnSlugB)) return this
 
        const columnA = this.get(columnSlugA)
        const columnB = this.get(columnSlugB)
 
        const toleranceA = columnA.tolerance ?? 0
        const toleranceB = columnB.tolerance ?? 0
 
        // If the columns are of mismatching time types, then we can't do any time matching.
        // This can happen when we have a ScatterPlot with days in one column, and a column with
        // xOverrideYear.
        // We also don't need to do any time matching when the tolerance of both columns is 0.
        if (
            this.timeColumn.isMissing ||
            this.timeColumn.slug !== columnA.originalTimeColumnSlug ||
            this.timeColumn.slug !== columnB.originalTimeColumnSlug ||
            (toleranceA === 0 && toleranceB === 0)
        ) {
            return this
        }
 
        const maxDiff = Math.max(toleranceA, toleranceB)
 
        const withAllRows = this.complete([
            this.entityNameSlug,
            this.timeColumn.slug,
        ]).sortBy([this.entityNameSlug, this.timeColumn.slug])
 
        // Existing columns
        const valuesA = withAllRows.get(columnA.slug).valuesIncludingErrorValues
        const valuesB = withAllRows.get(columnB.slug).valuesIncludingErrorValues
        const times = withAllRows.timeColumn
            .valuesIncludingErrorValues as Time[]
 
        // New columns
        const newValuesA = new Array(times.length).fill(
            ErrorValueTypes.NoValueWithinTolerance
        )
        const newValuesB = new Array(times.length).fill(
            ErrorValueTypes.NoValueWithinTolerance
        )
        const newTimesA = new Array(times.length).fill(
            ErrorValueTypes.NoValueWithinTolerance
        )
        const newTimesB = new Array(times.length).fill(
            ErrorValueTypes.NoValueWithinTolerance
        )
 
        const groupBoundaries = withAllRows.groupBoundaries(this.entityNameSlug)
 
        pairs(groupBoundaries).forEach(([startIndex, endIndex]) => {
            const availableTimesA = []
            const availableTimesB = []
 
            for (let index = startIndex; index < endIndex; index++) {
                if (isNotErrorValue(valuesA[index]))
                    availableTimesA.push(times[index])
                if (isNotErrorValue(valuesB[index]))
                    availableTimesB.push(times[index])
            }
 
            const timePairs = getClosestTimePairs(
                availableTimesA,
                availableTimesB,
                maxDiff
            )
            const timeAtoTimeB = new Map(timePairs)
            const pairedTimesInA = sortNumeric(
                Array.from(timeAtoTimeB.keys())
            ) as Time[]
 
            for (let index = startIndex; index < endIndex; index++) {
                const currentTime = times[index]
 
                const candidateTimeA = sortedFindClosest(
                    pairedTimesInA,
                    currentTime
                )
 
                if (candidateTimeA === undefined) continue
 
                const candidateIndexA = times.indexOf(
                    candidateTimeA,
                    startIndex
                )
 
                if (Math.abs(currentTime - candidateTimeA) > toleranceA)
                    continue
 
                const candidateTimeB = timeAtoTimeB.get(candidateTimeA)
 
                if (
                    candidateTimeB === undefined ||
                    Math.abs(currentTime - candidateTimeB) > toleranceB
                ) {
                    continue
                }
 
                const candidateIndexB = times.indexOf(
                    candidateTimeB,
                    startIndex
                )
 
                newValuesA[index] = valuesA[candidateIndexA]
                newValuesB[index] = valuesB[candidateIndexB]
                newTimesA[index] = times[candidateIndexA]
                newTimesB[index] = times[candidateIndexB]
            }
        })
 
        const originalTimeColumnASlug = makeOriginalTimeSlugFromColumnSlug(
            columnA.slug
        )
        const originalTimeColumnBSlug = makeOriginalTimeSlugFromColumnSlug(
            columnB.slug
        )
 
        const columnStore = {
            ...withAllRows.columnStore,
            [columnA.slug]: newValuesA,
            [columnB.slug]: newValuesB,
            [originalTimeColumnASlug]: newTimesA,
            [originalTimeColumnBSlug]: newTimesB,
        }
 
        return withAllRows.transform(
            columnStore,
            [
                ...withAllRows.defs,
                {
                    ...withAllRows.timeColumn.def,
                    slug: originalTimeColumnASlug,
                },
                {
                    ...withAllRows.timeColumn.def,
                    slug: originalTimeColumnBSlug,
                },
            ],
            `Interpolated values`,
            TransformType.UpdateColumnDefs
        )
    }
 
    // one datum per entityName. use the closest value to target year within tolerance.
    // selected rows only. value from any primary column.
    // getClosestRowForEachSelectedEntity(targetYear, tolerance)
    // Make sure we use the closest value to the target year within tolerance (preferring later)
    getClosestIndexForEachEntity(
        entityNames: EntityName[],
        targetTime: Time,
        tolerance: Integer
    ): number[] {
        const indexMap = this.rowIndicesByEntityName
        const timeColumn = this.timeColumn
        if (this.timeColumn.isMissing) return []
        const timeValues = timeColumn.valuesIncludingErrorValues
        return entityNames
            .map((name) => {
                const rowIndices = indexMap.get(name)
                if (!rowIndices) return null
 
                const rowIndex = findClosestTimeIndex(
                    rowIndices.map((index) => timeValues[index]) as number[],
                    targetTime,
                    tolerance
                )
                return rowIndex ? rowIndices[rowIndex] : null
            })
            .filter(isPresent)
    }
 
    filterByPopulationExcept(minPop: number, entityNames: string[] = []): this {
        const set = new Set(entityNames)
        return this.columnFilter(
            this.entityNameSlug,
            (value) => {
                const name = value as string
                const pop = populationMap[name]
                return !pop || set.has(name) || pop >= minPop
            },
            `Filter out countries with population less than ${minPop}`
        )
    }
 
    @imemo get availableEntities() {
        const { entityNameToCodeMap, entityNameToIdMap } = this
        return this.availableEntityNames.map((entityName) => {
            return {
                entityName,
                entityId: entityNameToIdMap.get(entityName),
                entityCode: entityNameToCodeMap.get(entityName),
            }
        })
    }
 
    sampleEntityName(howMany = 1): any[] {
        return this.availableEntityNames.slice(0, howMany)
    }
 
    get isBlank(): boolean {
        return (
            this.tableDescription.startsWith(BLANK_TABLE_MESSAGE) &&
            !this.numRows
        )
    }
}
 
const BLANK_TABLE_MESSAGE = `Table is empty.`
 
// This just assures that even an emtpty OwidTable will have an entityName column. Probably a cleaner way to do this pattern (add a defaultColumns prop??)
export const BlankOwidTable = (
    tableSlug = `blankOwidTable`,
    extraTableDescription = ""
): OwidTable =>
    new OwidTable(
        undefined,
        [
            { slug: OwidTableSlugs.entityName },
            { slug: OwidTableSlugs.year, type: ColumnTypeNames.Year },
        ],
        {
            tableDescription: BLANK_TABLE_MESSAGE + extraTableDescription,
            tableSlug,
        }
    )