datakit: how likely is a published number wrong? (#15)

* datakit: how likely is a published number wrong?

A new package, moved from Solon: checks a figure against its own series,
the parts of its table and a second publisher, and a seeded benchmark that
scores the checks on planted mistakes. Private until its first publish,
which needs one npm sign-in.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

* datakit: a figure is not compared with neighbours years away

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

* datakit: publishable (0.1.0)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
CatoandClaude Fable 5.2 authored and GitHub committed 2026-11-28 18:24:59 +01:00
1 parent 592949d62a
commit 14574b7987
15 files changed
+879

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ version, changelog and history — only the address of the source moved.
| `@bitbaum/bip-kit` | 0.10.0 | `packages/bip-kit` |
| `@bitbaum/chartkit` | 0.8.0 | `packages/chartkit` |
| `@bitbaum/chatkit` | 0.45.0 | `packages/chatkit` |
| `@bitbaum/datakit` | new here, 0.1.0 | `packages/datakit` |
| `@bitbaum/design-tokens` | 1.7.1 | `packages/design-tokens` |
| `@bitbaum/geo-kit` | 0.8.0 | `packages/geo-kit` |
| `@bitbaum/limitkit` | 0.2.1 | `packages/limitkit` |
+4
View File
@@ -0,0 +1,4 @@
node_modules/
dist/
*.log
.DS_Store
+31
View File
@@ -0,0 +1,31 @@
# Build output and vendored trees — formatting these is noise.
node_modules
.next
dist
build
out
coverage
.turbo
.vercel
*.min.js
*.min.css
# Generated during a build, so it is absent locally and present in CI — which
# makes a clean local --check no evidence at all. Contentlayer's output also
# uses import assertions, which prettier's parser rejects outright.
.contentlayer
.astro
.svelte-kit
storybook-static
test-results
playwright-report
# Lockfiles are generated; prettier would rewrite them wholesale.
package-lock.json
pnpm-lock.yaml
yarn.lock
# Markdown is deliberately out of scope for now. Prettier rewraps prose, which
# is where it is most opinionated and least useful, and it would bury the real
# diff. Remove this line when you want docs formatted too.
*.md
+9
View File
@@ -0,0 +1,9 @@
{
"semi": true,
"singleQuote": false,
"printWidth": 100,
"tabWidth": 2,
"trailingComma": "all",
"arrowParens": "always",
"endOfLine": "lf"
}
+7
View File
@@ -0,0 +1,7 @@
# Changelog
## 0.1.0 — 2026-11-28
- First version, moved from Solon (`src/lib/datakit`): `assessSeries`,
`checkIdentity`, `compareSources`, `runBenchmark`, `stateOf`, `HOLD_AT`,
`FLAG_AT`.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Mao Nakamoto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+70
View File
@@ -0,0 +1,70 @@
# @bitbaum/datakit
How likely is a published number wrong?
A figure read from a statistics office or an international database is a claim
by its publisher, and publishers make mistakes: an empty cell exported as `0`,
a series broken by a change of currency, a sign or a digit lost. datakit looks
at a figure beside the rest of its own series, the parts of its table and a
second publisher, and says how likely it is to be such a mistake, with the
check that caught it. It judges nothing about the subject of the data.
No dependencies, no I/O, pure functions: the same input gives the same answer.
```ts
import { assessSeries, stateOf } from "@bitbaum/datakit";
// OECD, Latvia's top income tax rate, per cent (read 2026-11-28).
const doubts = assessSeries(
[
{ period: 2022, value: 31.155779 },
{ period: 2023, value: 31.155779 },
{ period: 2024, value: 31.155779 },
{ period: 2025, value: 0 },
// …earlier years
],
{ fixedByLaw: true },
);
// → [{ period: 2025, check: "zero_in_nonzero_series", likelihood: 0.9, expected: 31.16 }]
stateOf(0.9); // "held"
```
## What it checks
| Function | Question |
| --- | --- |
| `assessSeries(observations, context)` | Is a figure unlike the rest of its own series? Not a number, outside the measure's band, a zero where nothing is near zero, a lone figure of the opposite sign, a spike that returns, a newest figure far from everything before. |
| `checkIdentity(total, parts, { grain })` | Do the parts of the publisher's own table add up to its total, within rounding? |
| `compareSources(a, b, { relative })` | Do two publishers agree, period by period? |
| `runBenchmark(series, { seed })` | How many planted mistakes do the checks catch, and how many true figures do they wrongly doubt? |
A likelihood of `HOLD_AT` (0.9) or more means the figure should not be shown;
from `FLAG_AT` (0.5) it should be shown and marked. The likelihoods are
judgements written beside each rule in `src/checks.ts`, not measured
frequencies; the benchmark is the measurement.
The `context` says what only the caller knows: the band the measure can lie
in, whether it is fixed by law (a tax rate moves in steps), and whether
nothing is an ordinary value (`canBeZero`: dwellings built in a village).
## Every rule comes from a real figure
The tests name them: Latvia's top income tax rate and Venezuela's government
consumption (publishers' zeros, held); Iceland's 2016 capital transfers (a
real spike, marked and shown); Lithuania's balanced budget, Iceland's years
without a homicide and a commune of 86 people where no dwelling was built
(real zeros, left alone). A mistake found in any app becomes a test here.
## First score
On the 2,437 national series of solon.orangecat.ch (65,918 figures,
2026-11-28): no true figure wrongly held, 5 marked. Of planted mistakes held:
thousand-fold 99.6 %, hundred-fold 92.0 %, sign 92.4 %, zero 83.1 %, ten-fold
74.2 %; a tenth of the size is only marked (77.8 %) and two swapped digits
mostly pass (13.6 % marked). Those need `checkIdentity` or `compareSources`.
## Install
```bash
pnpm add @bitbaum/datakit
```
+25
View File
@@ -0,0 +1,25 @@
// Flat config (ESLint 9). Recommended presets only: this is ~600 lines of
// library code, and a bespoke rule set would be a second opinion to maintain
// for no benefit. The floor is "lint runs and can fail", not "lint encodes
// taste".
import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
// dist/ is generated by `tsc`.
ignores: ["dist/**", "node_modules/**"],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ["**/*.ts"],
languageOptions: { globals: globals.node },
},
{
// Tests are plain Node ESM running under `node --test`.
files: ["test/**/*.js", "scripts/**/*.{js,mjs}"],
languageOptions: { globals: { ...globals.node, ...globals.nodeBuiltin } },
},
);
+62
View File
@@ -0,0 +1,62 @@
{
"name": "@bitbaum/datakit",
"version": "0.1.0",
"description": "How likely is a published number wrong? Checks a figure against its own series, the parts of its table and a second publisher, and scores the checks on planted mistakes. No dependencies.",
"license": "MIT",
"author": "Cato",
"homepage": "https://github.com/bitbaum/kits/tree/main/packages/datakit#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/bitbaum/kits.git",
"directory": "packages/datakit"
},
"bugs": {
"url": "https://github.com/bitbaum/kits/issues"
},
"keywords": [
"data-quality",
"statistics",
"validation",
"outliers",
"time-series",
"headless"
],
"type": "module",
"sideEffects": false,
"packageManager": "pnpm@11.25.0",
"engines": {
"node": ">=20"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --test test/*.test.js",
"verify": "pnpm run format:check && pnpm run lint && pnpm run typecheck && pnpm run build && pnpm test",
"prepare": "pnpm run build",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^26.4.1",
"eslint": "^10.9.1",
"globals": "^17.12.0",
"prettier": "3.10.0",
"typescript": "^6.0.3",
"typescript-eslint": "^8.69.0"
}
}
+115
View File
@@ -0,0 +1,115 @@
/**
* How good are the checks? Measured, not asserted: take real series, plant the
* mistakes publishers actually make into them one at a time, and count how many
* the checks catch and how many true figures they wrongly doubt.
*
* Pure and seeded: the same series and seed give the same score, so a change to
* a rule shows as a change in these numbers.
*/
import { assessSeries, stateOf, type Observation, type SeriesContext } from "./checks.js";
/** The mistakes planted, each one a way a published figure really goes wrong. */
export const PLANTED = {
/** An empty cell exported as 0. */
zero: () => 0,
/** A decimal point one place off. */
times10: (v: number) => v * 10,
tenth: (v: number) => v / 10,
/** A unit mix-up: thousands for units, per cent for a ratio. */
times100: (v: number) => v * 100,
times1000: (v: number) => v * 1000,
/** A sign lost or added. */
signFlip: (v: number) => -v,
/** Two leading digits swapped (31.2 read as 13.2). */
digitSwap: (v: number) => {
const digits = Math.abs(v).toExponential(6);
const swapped = digits[2]! + "." + digits[0]! + digits.slice(3);
return Math.sign(v) * Number(swapped);
},
} as const;
export type PlantedKind = keyof typeof PLANTED;
export interface BenchmarkSeries {
id: string;
observations: Observation[];
context?: SeriesContext;
}
export interface BenchmarkScore {
/** Per planted mistake: how many were planted, held, and at least marked. */
planted: Record<PlantedKind, { planted: number; held: number; marked: number }>;
/** The same split by where in the series the mistake sat. */
atNewest: { planted: number; held: number; marked: number };
inside: { planted: number; held: number; marked: number };
/** True figures, untouched, that the checks held or marked anyway. */
clean: { figures: number; held: number; marked: number };
}
/** A small seeded generator (mulberry32): the benchmark must not change between runs. */
function seeded(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const tally = () => ({ planted: 0, held: 0, marked: 0 });
/**
* Scores the checks on `series`, taken as true. `perSeries` mistakes of each
* kind are planted into each series that is long enough, one at a time.
*/
export function runBenchmark(
series: readonly BenchmarkSeries[],
{
seed = 1,
perSeries = 2,
minLength = 8,
}: { seed?: number; perSeries?: number; minLength?: number } = {},
): BenchmarkScore {
const random = seeded(seed);
const kinds = Object.keys(PLANTED) as PlantedKind[];
const score: BenchmarkScore = {
planted: Object.fromEntries(kinds.map((k) => [k, tally()])) as BenchmarkScore["planted"],
atNewest: tally(),
inside: tally(),
clean: { figures: 0, held: 0, marked: 0 },
};
for (const s of series) {
const points = [...s.observations].sort((a, b) => a.period - b.period);
const doubts = assessSeries(points, s.context);
score.clean.figures += points.length;
for (const d of doubts) {
const state = stateOf(d.likelihood);
if (state === "held") score.clean.held += 1;
else if (state === "flagged") score.clean.marked += 1;
}
if (points.length < minLength) continue;
// A series the checks already doubt is not a clean bed to plant in.
if (doubts.length > 0) continue;
for (const kind of kinds) {
for (let n = 0; n < perSeries; n += 1) {
// Half the mistakes sit at the newest figure, where a reader looks first.
const newest = random() < 0.5;
const at = newest ? points.length - 1 : 1 + Math.floor(random() * (points.length - 2));
const truth = points[at]!.value;
const wrong = PLANTED[kind](truth);
if (!Number.isFinite(wrong) || wrong === truth) continue;
const planted = points.map((p, i) => (i === at ? { ...p, value: wrong } : p));
const found = assessSeries(planted, s.context).find((d) => d.period === points[at]!.period);
const state = found ? stateOf(found.likelihood) : "published";
for (const bucket of [score.planted[kind], newest ? score.atNewest : score.inside]) {
bucket.planted += 1;
if (state === "held") bucket.held += 1;
if (state !== "published") bucket.marked += 1;
}
}
}
}
return score;
}
+348
View File
@@ -0,0 +1,348 @@
/**
* datakit: how likely is a published number wrong?
*
* A figure read from a statistics office or a database is a claim by its
* publisher, and publishers make mistakes: an empty cell exported as 0, a
* series broken by a change of currency, a digit dropped. This module looks at
* a figure beside the rest of its own series and says how likely it is to be
* such a mistake, with the reason in words a reader can check. It decides
* nothing about the subject of the data, only whether the number can be what
* the publisher meant.
*
* Self-contained on purpose: no imports from the app, so it can move to the
* shared kits repository unchanged and judge any app's numbers the same way.
* Pure: the same series gives the same answer.
*
* Each rule here exists because of a real figure; the tests name them.
*/
export interface Observation {
/** The period the figure describes; a year for yearly series. */
period: number;
value: number;
}
export interface SeriesContext {
/** The band the measure can lie in at all, in the series' own unit. */
band?: { min: number; max: number };
/**
* The figure is set by a law or a decision (a tax rate), not measured: it
* moves in steps and stays put, so a step is no surprise but a fall to
* nothing is.
*/
fixedByLaw?: boolean;
/**
* Nothing is an ordinary value of the measure: a count of rare things in a small place
* (dwellings built in a commune of 86 people), or a rate worked out from one. A zero is
* then never doubted for being a zero. Only the caller knows this; the default is that
* the measure, like a share of GDP or a tax rate, is not expected to be nothing.
*/
canBeZero?: boolean;
}
export type CheckKind =
/** Not a finite number. */
| "not_a_number"
/** Outside what the measure can be. */
| "outside_band"
/** Exactly zero in a series that is otherwise well away from zero. */
| "zero_in_nonzero_series"
/** The one figure of the opposite sign in a series that keeps well to one side of zero. */
| "sign_break"
/** Far from both neighbours, which agree with each other: a spike that returns. */
| "isolated_spike"
/** The newest figure is far from everything before it, with nothing after it to confirm. */
| "unconfirmed_break";
export interface Suspicion {
period: number;
value: number;
check: CheckKind;
/**
* How likely the figure is a mistake rather than a fact, 0 to 1. A judgement
* written down, not a measured frequency: each rule's number is argued beside it.
*/
likelihood: number;
/** What the figure was compared with, for the page to say. */
expected: number | null;
}
/** At or above this a figure is held back: not shown, and listed as held. */
export const HOLD_AT = 0.9;
/** At or above this a figure is shown with a mark that it is doubted. */
export const FLAG_AT = 0.5;
export type FigureState = "published" | "flagged" | "held";
export const stateOf = (likelihood: number): FigureState =>
likelihood >= HOLD_AT ? "held" : likelihood >= FLAG_AT ? "flagged" : "published";
const median = (values: readonly number[]): number => {
const sorted = [...values].sort((a, b) => a - b);
const mid = sorted.length >> 1;
return sorted.length % 2 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
};
/** A series' usual size of change from one period to the next, robust to its own outliers. */
function usualStep(values: readonly number[]): number {
const steps: number[] = [];
for (let i = 1; i < values.length; i += 1) steps.push(Math.abs(values[i]! - values[i - 1]!));
return steps.length ? median(steps) : 0;
}
/** How many usual steps away a spike must be, and how many times the level. */
const SPIKE_STEPS = 12;
const SPIKE_RATIO = 4;
/**
* The grain a series is written in: the smallest gap between two different figures, or, where
* every figure is the same, the last decimal place it is written to. A share kept to a tenth
* of a per cent of GDP cannot tell 0.04 % from nothing.
*/
function grain(values: readonly number[]): number {
const distinct = [...new Set(values.map(Math.abs))].sort((a, b) => a - b);
let smallest = Infinity;
for (let i = 1; i < distinct.length; i += 1) {
smallest = Math.min(smallest, distinct[i]! - distinct[i - 1]!);
}
if (Number.isFinite(smallest)) return smallest;
const decimals = (String(distinct[0] ?? 0).split(".")[1] ?? "").length;
return 10 ** -Math.min(decimals, 12);
}
/** A real figure must stand this many grains above zero for a zero beside it to be doubted. */
const ZERO_GRAINS = 10;
/** Fewer real figures than this say too little about whether zero is unusual. */
const ZERO_HISTORY = 5;
/** How many usual steps the lowest real figure must stand above zero for a zero to be doubted. */
const ZERO_STEPS = 8;
/** A neighbour further away than this many usual gaps is no neighbour. */
const SPACING_SLACK = 3;
/** Fewer figures than this say too little about what is usual. */
const MIN_HISTORY = 6;
/**
* The most doubtful thing about each figure of one series, if anything. A
* figure with nothing against it is absent from the answer.
*/
export function assessSeries(
observations: readonly Observation[],
context: SeriesContext = {},
): Suspicion[] {
const points = [...observations].sort((a, b) => a.period - b.period);
const finite = points.filter((p) => Number.isFinite(p.value));
const values = finite.map((p) => p.value);
const out: Suspicion[] = [];
const nonZero = values.filter((v) => v !== 0).map(Math.abs);
const level = nonZero.length ? median(nonZero) : 0;
const step = usualStep(values.filter((v) => v !== 0));
// "Well away from zero": every other figure has one sign, the smallest is still half the
// usual level, and zero lies many usual steps below it. A budget balance crosses zero, a
// village has years without a homicide, a small share rounds to nothing: none of those pass.
const oneSign = values.every((v) => v >= 0) || values.every((v) => v <= 0);
const lowest = nonZero.length ? Math.min(...nonZero) : 0;
// Zeros that come and go between real figures are the measure's own (a principality of
// 36,000 has years with one homicide and years with none): only one run of them is doubted.
let zeroRuns = 0;
for (let k = 1; k < values.length; k += 1) {
if (values[k] === 0 && values[k - 1] !== 0) zeroRuns += 1;
}
const awayFromZero =
!context.canBeZero &&
oneSign &&
zeroRuns === 1 &&
nonZero.length >= ZERO_HISTORY &&
lowest >= ZERO_GRAINS * grain(nonZero) &&
lowest > level / 2 &&
lowest > ZERO_STEPS * step;
// The index of a lone figure of the opposite sign, where every other real figure has one
// sign and stands well away from zero.
const positives = values.filter((v) => v > 0).length;
const negatives = values.filter((v) => v < 0).length;
let signBreakAt = -1;
if (nonZero.length >= ZERO_HISTORY + 1 && Math.min(positives, negatives) === 1) {
const lone = values.findIndex((v) => (positives === 1 ? v > 0 : v < 0));
const others = values.filter((v, k) => k !== lone && v !== 0).map(Math.abs);
const othersLevel = median(others);
const size = Math.abs(values[lone]!);
if (
Math.min(...others) > othersLevel / 2 &&
Math.min(...others) > ZERO_STEPS * usualStep(values.filter((_, k) => k !== lone)) &&
size > othersLevel / 2 &&
size < othersLevel * 2
) {
signBreakAt = lone;
}
}
// The usual distance between two figures of the series, in its own periods.
const gaps: number[] = [];
for (let k = 1; k < finite.length; k += 1) gaps.push(finite[k]!.period - finite[k - 1]!.period);
const spacing = gaps.length ? median(gaps) : 0;
for (const p of points) {
if (!Number.isFinite(p.value)) {
out.push({ ...p, check: "not_a_number", likelihood: 1, expected: null });
continue;
}
const { band } = context;
if (band && (p.value < band.min || p.value > band.max)) {
// What cannot be is not a fact, whatever the publisher printed.
out.push({ ...p, check: "outside_band", likelihood: 1, expected: null });
continue;
}
const i = finite.indexOf(p);
const before = finite[i - 1]?.value;
const after = finite[i + 1]?.value;
const neighbours = [before, after].filter((v): v is number => v !== undefined);
if (neighbours.length === 0) continue;
const expected = neighbours.reduce((sum, v) => sum + v, 0) / neighbours.length;
if (p.value !== 0 && signBreakAt === i) {
// The only figure on the other side of zero, as large as its neighbours are on theirs:
// a sign lost or added on the way. A series that crosses zero by itself (a balance,
// a growth rate) has more than one, or comes near zero first, and is left alone.
out.push({ ...p, check: "sign_break", likelihood: 0.9, expected: -p.value });
continue;
}
if (p.value === 0 && awayFromZero) {
// The nearest real figures on each side; a zero before the series' first real figure
// is a measure that did not exist yet (a tax not yet levied), and is left alone.
const earlier = values
.slice(0, i)
.reverse()
.find((v) => v !== 0);
const later = values.slice(i + 1).find((v) => v !== 0);
if (earlier === undefined) continue;
const around = later === undefined ? earlier : (earlier + later) / 2;
// How many zeros run to the end of the series, this one among them.
let trailing = 0;
if (later === undefined) {
for (let k = values.length - 1; k >= 0 && values[k] === 0; k -= 1) trailing += 1;
}
// An exact zero among figures that never come near it is the signature of an empty
// cell or a broken series. Between real figures it is all but certain (World Bank,
// Venezuela's government consumption 1991 to 2011). As the newest figure alone it is
// held until the publisher's next release confirms or corrects it (OECD, Latvia's top
// income tax rate 2025: 0 after 31.16 three years running). Two or more zeros running
// to the end may be a measure abolished, so they are marked, not held.
const likelihood = later !== undefined ? 0.97 : trailing === 1 ? 0.9 : 0.5;
out.push({ ...p, check: "zero_in_nonzero_series", likelihood, expected: around });
continue;
}
if (finite.length < MIN_HISTORY || step === 0 || context.fixedByLaw) continue;
// A neighbour years away says nothing about this period: a price read in 2009, 2018 and
// then every quarter from 2024 has no neighbours for its 2018 figure.
const nearBefore = i > 0 && p.period - finite[i - 1]!.period <= SPACING_SLACK * spacing;
const nearAfter =
i < finite.length - 1 && finite[i + 1]!.period - p.period <= SPACING_SLACK * spacing;
if (!nearBefore || (after !== undefined && !nearAfter)) continue;
const distance = Math.abs(p.value - expected);
const ratio =
expected !== 0 && p.value !== 0
? Math.max(Math.abs(p.value / expected), Math.abs(expected / p.value))
: Infinity;
// Beside a zero there is no level to be far from.
const far =
expected !== 0 && p.value !== 0 && distance > SPIKE_STEPS * step && ratio >= SPIKE_RATIO;
if (!far) continue;
if (before !== undefined && after !== undefined) {
// Far from both sides while the two sides agree with each other: the level did not
// move, one figure did. Usually a misplaced decimal or a unit mix-up.
const sidesAgree = Math.abs(before - after) <= SPIKE_STEPS * step;
// Marked, not held: of the first three found in live data (2026-11-28), all were real
// events (Iceland's 2016 stability contributions, Myanmar's 2021 killings).
if (sidesAgree) out.push({ ...p, check: "isolated_spike", likelihood: 0.5, expected });
} else if (after === undefined) {
// The newest figure, with no later one to say whether the level really moved:
// marked, not held, since real breaks also look like this at first.
out.push({ ...p, check: "unconfirmed_break", likelihood: 0.5, expected });
}
}
return out;
}
export interface IdentityGap {
period: number;
/** What the publisher states as the whole. */
total: number;
/** What its parts add up to. */
sum: number;
gap: number;
}
export interface IdentityResult {
/** Periods where the whole and every part were published. */
compared: number;
/** Those where the parts do not add up to the whole, beyond what rounding explains. */
gaps: IdentityGap[];
}
/**
* Do the parts add up to the whole? A publisher's own table that does not add
* up holds a wrong figure somewhere, and this is the check that sees a figure a
* tenth of its size or two digits swapped, which no look at one series can.
* `grain` is the step the figures are written in (0.001 for a tenth of a per
* cent of GDP); each part may be off by half of it.
*/
export function checkIdentity(
total: readonly Observation[],
parts: readonly (readonly Observation[])[],
{ grain: step, relative = 0.005 }: { grain: number; relative?: number },
): IdentityResult {
const result: IdentityResult = { compared: 0, gaps: [] };
const byPeriod = parts.map((part) => new Map(part.map((o) => [o.period, o.value])));
for (const whole of total) {
const values = byPeriod.map((m) => m.get(whole.period));
if (values.some((v) => v === undefined) || !Number.isFinite(whole.value)) continue;
result.compared += 1;
const sum = (values as number[]).reduce((a, b) => a + b, 0);
const gap = sum - whole.value;
// Rounding: each part and the whole within half a grain; then a little for the publisher's own arithmetic.
const allowed = ((parts.length + 1) * step) / 2 + Math.abs(whole.value) * relative;
if (Math.abs(gap) > allowed)
result.gaps.push({ period: whole.period, total: whole.value, sum, gap });
}
return result;
}
export interface SourceDisagreement {
period: number;
a: number;
b: number;
/** The difference as a share of the larger figure. */
relative: number;
}
export interface SourceComparison {
/** Periods both sources publish. */
compared: number;
agreed: number;
disagreements: SourceDisagreement[];
}
/**
* Two publishers' figures for the same thing, period by period. Agreement is
* evidence only as far as the two are independent, which the caller must say
* where it shows the result: an international database that republishes a
* national office's figure is one source twice.
*/
export function compareSources(
a: readonly Observation[],
b: readonly Observation[],
{ relative = 0.05, absolute = 0 }: { relative?: number; absolute?: number } = {},
): SourceComparison {
const other = new Map(b.map((o) => [o.period, o.value]));
const out: SourceComparison = { compared: 0, agreed: 0, disagreements: [] };
for (const o of a) {
const v = other.get(o.period);
if (v === undefined || !Number.isFinite(v) || !Number.isFinite(o.value)) continue;
out.compared += 1;
const diff = Math.abs(o.value - v);
const scale = Math.max(Math.abs(o.value), Math.abs(v));
const share = scale === 0 ? 0 : diff / scale;
if (diff <= absolute || share <= relative) out.agreed += 1;
else out.disagreements.push({ period: o.period, a: o.value, b: v, relative: share });
}
return out;
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./checks.js";
export * from "./benchmark.js";
+142
View File
@@ -0,0 +1,142 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
assessSeries,
checkIdentity,
compareSources,
runBenchmark,
stateOf,
} from "../dist/index.js";
const series = (from, values) => values.map((value, i) => ({ period: from + i, value }));
test("holds the OECD's zero for Latvia's top income tax rate in 2025", () => {
// OECD Tax Database, LVA.A..TS_PIT, read 2026-11-28: the rate in per cent.
const found = assessSeries(
series(2018, [31.4, 31.4, 31.4, 31.0, 31.155779, 31.155779, 31.155779, 0]),
{ fixedByLaw: true },
);
assert.equal(found.length, 1);
assert.equal(found[0].period, 2025);
assert.equal(found[0].check, "zero_in_nonzero_series");
assert.equal(stateOf(found[0].likelihood), "held");
});
test("holds the World Bank's zeros for Venezuela's government consumption", () => {
const found = assessSeries(series(1986, [0.11, 0.1, 0.09, 0.085, 0.0814, 0, 0, 0, 0.12, 0.13]));
assert.deepEqual(
found.map((f) => f.period),
[1991, 1992, 1993],
);
assert.ok(found.every((f) => stateOf(f.likelihood) === "held"));
});
test("leaves real zeros alone", () => {
// A budget balance crosses zero; a small country has years without a homicide; a small
// share rounds to nothing; a tax wedge is zero every year.
assert.deepEqual(
assessSeries(series(2012, [-0.031, -0.026, -0.006, -0.003, 0, 0.004, 0.005])),
[],
);
assert.deepEqual(assessSeries(series(2002, [1.4, 0, 1.0, 1.0, 0, 0.6, 0, 0.3, 0.6])), []);
assert.deepEqual(assessSeries(series(2002, [0.006, 0.005, 0.004, 0.004, 0, 0.004, 0.006])), []);
assert.deepEqual(assessSeries(series(2000, [0, 0, 0, 0, 0, 0, 0, 0])), []);
});
test("needs telling where nothing is an ordinary value", () => {
// Dwellings built per 1,000 residents, five-year average, a commune of 86 people.
const commune = series(2019, [10.99, 11.63, 9.2, 9.09, 9.3, 0]);
assert.deepEqual(assessSeries(commune, { canBeZero: true }), []);
assert.equal(assessSeries(commune).length, 1);
});
test("marks a spike that returns, without holding it", () => {
// Capital transfers received, share of GDP: Iceland 2016 is real.
const found = assessSeries(
series(2011, [0.004, 0.005, 0.004, 0.005, 0.003, 0.155, 0.006, 0.004]),
);
assert.equal(found.length, 1);
assert.equal(found[0].check, "isolated_spike");
assert.equal(stateOf(found[0].likelihood), "flagged");
});
test("holds a lone figure of the opposite sign, not a balance in surplus once", () => {
const found = assessSeries(series(2015, [41, 42, 41.5, 42, -41.8, 42.2, 42, 41.9]));
assert.equal(found[0].check, "sign_break");
assert.deepEqual(assessSeries(series(2015, [-3.1, -2.2, -0.8, 0.3, -0.9, -6.5, -4.1, -2.8])), []);
});
test("does not doubt a rate set by law for moving in a step", () => {
assert.deepEqual(
assessSeries(series(2015, [20, 20, 20, 20, 20, 20, 20, 22, 22]), { fixedByLaw: true }),
[],
);
});
test("finds the year the parts stop adding up", () => {
const part = (values) => series(2020, values);
const ok = checkIdentity(
part([0.48, 0.5]),
[part([0.2, 0.21]), part([0.181, 0.19]), part([0.1, 0.1])],
{
grain: 0.001,
},
);
assert.deepEqual(ok, { compared: 2, gaps: [] });
const bad = checkIdentity(
part([0.48, 0.5]),
[part([0.2, 0.021]), part([0.18, 0.19]), part([0.1, 0.1])],
{
grain: 0.001,
},
);
assert.deepEqual(
bad.gaps.map((g) => g.period),
[2021],
);
});
test("compares two publishers year by year", () => {
const result = compareSources(
series(2020, [0.33, 0.34, 0.5]),
series(2020, [0.332, 0.341, 0.35]),
);
assert.equal(result.compared, 3);
assert.equal(result.agreed, 2);
assert.deepEqual(
result.disagreements.map((d) => d.period),
[2022],
);
});
test("the benchmark is seeded, and steady series score clean", () => {
const steady = Array.from({ length: 20 }, (_, n) => ({
id: `s${n}`,
observations: Array.from({ length: 15 }, (_, i) => ({
period: 2010 + i,
value: 30 + n + Math.sin(i + n) * 0.4,
})),
}));
assert.deepEqual(runBenchmark(steady, { seed: 7 }), runBenchmark(steady, { seed: 7 }));
const score = runBenchmark(steady);
assert.deepEqual(score.clean, { figures: 300, held: 0, marked: 0 });
assert.equal(score.planted.zero.held, score.planted.zero.planted);
});
test("does not compare a figure with neighbours years away", () => {
// Spot price of uranium enrichment, USD per SWU (Substrata, from Centrus's filings): read for
// 2009, for the 2018 low, then every quarter from 2024. The low is real.
const swu = [
[2009.25, 163],
[2018.58, 34],
[2024.17, 166],
[2024.42, 176],
[2024.67, 180],
[2024.92, 195],
[2025.17, 190],
[2025.42, 190],
[2025.67, 220],
[2025.92, 200],
].map(([period, value]) => ({ period, value }));
assert.deepEqual(assessSeries(swu), []);
});
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "ESNext",
"moduleResolution": "bundler",
"declaration": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
+24
View File
@@ -285,6 +285,30 @@ importers:
specifier: ^8.68.0
version: 8.73.0(eslint@10.15.0)(typescript@6.0.3)
packages/datakit:
devDependencies:
'@eslint/js':
specifier: ^10.0.1
version: 10.0.1(eslint@10.15.0)
'@types/node':
specifier: ^26.4.1
version: 26.6.6
eslint:
specifier: ^10.9.1
version: 10.15.0
globals:
specifier: ^17.12.0
version: 17.14.0
prettier:
specifier: 3.10.0
version: 3.10.0
typescript:
specifier: ^6.0.3
version: 6.0.3
typescript-eslint:
specifier: ^8.69.0
version: 8.73.0(eslint@10.15.0)(typescript@6.0.3)
packages/design-tokens:
devDependencies:
'@eslint/js':