universal-physics-tensor 11.0.0 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -34
- package/data/applied-cases.json +1892 -0
- package/data/applied-cases.schema.json +194 -0
- package/data/atlas/atlas.json +21 -21
- package/data/atlas/atlas.jsonld +1 -1
- package/data/atlas/diffusion.json +5 -5
- package/data/atlas/oscillators.json +7 -7
- package/data/atlas/waves.json +11 -11
- package/data/bridge-catalog.json +20 -4
- package/data/units.json +6 -25
- package/dist/atlas/benchmark/stats.d.ts.map +1 -1
- package/dist/atlas/benchmark/stats.js +6 -20
- package/dist/atlas/benchmark/stats.js.map +1 -1
- package/dist/atlas/physjs-entries.generated.d.ts +13 -4
- package/dist/atlas/physjs-entries.generated.d.ts.map +1 -1
- package/dist/atlas/physjs-entries.generated.js +15 -4
- package/dist/atlas/physjs-entries.generated.js.map +1 -1
- package/dist/atlas/physjs-reviewed.js +2 -2
- package/dist/atlas/physjs-reviewed.js.map +1 -1
- package/dist/cases/catalog-checks.d.ts +10 -0
- package/dist/cases/catalog-checks.d.ts.map +1 -0
- package/dist/cases/catalog-checks.js +241 -0
- package/dist/cases/catalog-checks.js.map +1 -0
- package/dist/cases/catalog.d.ts +83 -0
- package/dist/cases/catalog.d.ts.map +1 -0
- package/dist/cases/catalog.js +118 -0
- package/dist/cases/catalog.js.map +1 -0
- package/dist/cases/engine.d.ts +13 -0
- package/dist/cases/engine.d.ts.map +1 -0
- package/dist/cases/engine.js +179 -0
- package/dist/cases/engine.js.map +1 -0
- package/dist/cases/index.d.ts.map +1 -1
- package/dist/cases/index.js +5 -7
- package/dist/cases/index.js.map +1 -1
- package/dist/cases/methods.d.ts +215 -0
- package/dist/cases/methods.d.ts.map +1 -0
- package/dist/cases/methods.js +743 -0
- package/dist/cases/methods.js.map +1 -0
- package/dist/cases/types.d.ts +12 -0
- package/dist/cases/types.d.ts.map +1 -1
- package/dist/cases/types.js.map +1 -1
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/command.d.ts +3 -0
- package/dist/cli/command.d.ts.map +1 -1
- package/dist/cli/command.js.map +1 -1
- package/dist/cli/commands/_discovery-opts.d.ts +1 -0
- package/dist/cli/commands/_discovery-opts.d.ts.map +1 -1
- package/dist/cli/commands/_discovery-opts.js +1 -0
- package/dist/cli/commands/_discovery-opts.js.map +1 -1
- package/dist/cli/commands/discover.d.ts.map +1 -1
- package/dist/cli/commands/discover.js +116 -71
- package/dist/cli/commands/discover.js.map +1 -1
- package/dist/cli/commands/evaluate.js +2 -2
- package/dist/cli/commands/evaluate.js.map +1 -1
- package/dist/cli/commands/explain.d.ts.map +1 -1
- package/dist/cli/commands/explain.js +22 -2
- package/dist/cli/commands/explain.js.map +1 -1
- package/dist/cli/commands/ground.d.ts.map +1 -1
- package/dist/cli/commands/ground.js +6 -1
- package/dist/cli/commands/ground.js.map +1 -1
- package/dist/cli/commands/map.d.ts.map +1 -1
- package/dist/cli/commands/map.js +9 -6
- package/dist/cli/commands/map.js.map +1 -1
- package/dist/cli/determination.d.ts +1 -0
- package/dist/cli/determination.d.ts.map +1 -1
- package/dist/cli/determination.js.map +1 -1
- package/dist/cli/flag-help.d.ts +1 -0
- package/dist/cli/flag-help.d.ts.map +1 -1
- package/dist/cli/flag-help.js +1 -0
- package/dist/cli/flag-help.js.map +1 -1
- package/dist/cli/graphs.d.ts +2 -0
- package/dist/cli/graphs.d.ts.map +1 -1
- package/dist/cli/graphs.js +1 -0
- package/dist/cli/graphs.js.map +1 -1
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +1 -0
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/output.d.ts +8 -0
- package/dist/cli/output.d.ts.map +1 -1
- package/dist/cli/output.js +8 -0
- package/dist/cli/output.js.map +1 -1
- package/dist/cli/statuses.d.ts.map +1 -1
- package/dist/cli/statuses.js +12 -2
- package/dist/cli/statuses.js.map +1 -1
- package/dist/cli/version.d.ts +1 -0
- package/dist/cli/version.d.ts.map +1 -1
- package/dist/cli/version.js +1 -0
- package/dist/cli/version.js.map +1 -1
- package/dist/cli-api.d.ts +2 -0
- package/dist/cli-api.d.ts.map +1 -1
- package/dist/cli-api.js +2 -0
- package/dist/cli-api.js.map +1 -1
- package/dist/composition/canonical-graph.d.ts +2 -2
- package/dist/composition/canonical-graph.js +2 -2
- package/dist/composition/canonical-graph.js.map +1 -1
- package/dist/composition/consequence.d.ts +15 -5
- package/dist/composition/consequence.d.ts.map +1 -1
- package/dist/composition/consequence.js +6 -4
- package/dist/composition/consequence.js.map +1 -1
- package/dist/composition/discovery.d.ts +78 -14
- package/dist/composition/discovery.d.ts.map +1 -1
- package/dist/composition/discovery.js +73 -23
- package/dist/composition/discovery.js.map +1 -1
- package/dist/composition/expr-eval.d.ts +1 -1
- package/dist/composition/expr-eval.d.ts.map +1 -1
- package/dist/composition/expr-eval.js +4 -4
- package/dist/composition/expr-eval.js.map +1 -1
- package/dist/composition/expr-simplify.d.ts +10 -14
- package/dist/composition/expr-simplify.d.ts.map +1 -1
- package/dist/composition/expr-simplify.js +49 -52
- package/dist/composition/expr-simplify.js.map +1 -1
- package/dist/composition/grounding.d.ts.map +1 -1
- package/dist/composition/grounding.js +19 -7
- package/dist/composition/grounding.js.map +1 -1
- package/dist/composition/mathts-quiet.d.ts +4 -6
- package/dist/composition/mathts-quiet.d.ts.map +1 -1
- package/dist/composition/mathts-quiet.js +4 -14
- package/dist/composition/mathts-quiet.js.map +1 -1
- package/dist/composition/own-equation-magnitude.d.ts +95 -0
- package/dist/composition/own-equation-magnitude.d.ts.map +1 -0
- package/dist/composition/own-equation-magnitude.js +270 -0
- package/dist/composition/own-equation-magnitude.js.map +1 -0
- package/dist/composition/probe/backend-protocol.d.ts +3 -0
- package/dist/composition/probe/backend-protocol.d.ts.map +1 -1
- package/dist/composition/probe/backend-protocol.js.map +1 -1
- package/dist/composition/probe/candidate-store.d.ts +1 -0
- package/dist/composition/probe/candidate-store.d.ts.map +1 -1
- package/dist/composition/probe/candidate-store.js +1 -0
- package/dist/composition/probe/candidate-store.js.map +1 -1
- package/dist/composition/probe/corpus.d.ts +4 -2
- package/dist/composition/probe/corpus.d.ts.map +1 -1
- package/dist/composition/probe/corpus.js +3 -3
- package/dist/composition/probe/corpus.js.map +1 -1
- package/dist/composition/probe/dataset.d.ts +1 -0
- package/dist/composition/probe/dataset.d.ts.map +1 -1
- package/dist/composition/probe/dataset.js.map +1 -1
- package/dist/composition/probe/experiment-design.d.ts +2 -0
- package/dist/composition/probe/experiment-design.d.ts.map +1 -1
- package/dist/composition/probe/experiment-design.js.map +1 -1
- package/dist/composition/probe/falsify.d.ts +2 -0
- package/dist/composition/probe/falsify.d.ts.map +1 -1
- package/dist/composition/probe/falsify.js.map +1 -1
- package/dist/composition/probe/fit.d.ts +1 -0
- package/dist/composition/probe/fit.d.ts.map +1 -1
- package/dist/composition/probe/fit.js.map +1 -1
- package/dist/composition/probe/generator.d.ts +3 -0
- package/dist/composition/probe/generator.d.ts.map +1 -1
- package/dist/composition/probe/generator.js +5 -6
- package/dist/composition/probe/generator.js.map +1 -1
- package/dist/composition/probe/limits.d.ts +1 -0
- package/dist/composition/probe/limits.d.ts.map +1 -1
- package/dist/composition/probe/limits.js.map +1 -1
- package/dist/composition/probe/pipeline.d.ts +5 -0
- package/dist/composition/probe/pipeline.d.ts.map +1 -1
- package/dist/composition/probe/pipeline.js +64 -21
- package/dist/composition/probe/pipeline.js.map +1 -1
- package/dist/composition/probe/power-law.d.ts.map +1 -1
- package/dist/composition/probe/power-law.js +3 -7
- package/dist/composition/probe/power-law.js.map +1 -1
- package/dist/composition/probe/problem.d.ts +1 -0
- package/dist/composition/probe/problem.d.ts.map +1 -1
- package/dist/composition/probe/problem.js.map +1 -1
- package/dist/composition/probe/residual.d.ts +1 -0
- package/dist/composition/probe/residual.d.ts.map +1 -1
- package/dist/composition/probe/residual.js +1 -0
- package/dist/composition/probe/residual.js.map +1 -1
- package/dist/composition/probe/run-manifest.d.ts +1 -0
- package/dist/composition/probe/run-manifest.d.ts.map +1 -1
- package/dist/composition/probe/run-manifest.js.map +1 -1
- package/dist/composition/probe/scalar-search.d.ts +50 -0
- package/dist/composition/probe/scalar-search.d.ts.map +1 -0
- package/dist/composition/probe/scalar-search.js +169 -0
- package/dist/composition/probe/scalar-search.js.map +1 -0
- package/dist/composition/probe/scoring.d.ts +1 -0
- package/dist/composition/probe/scoring.d.ts.map +1 -1
- package/dist/composition/probe/scoring.js.map +1 -1
- package/dist/composition/probe/study.d.ts +2 -2
- package/dist/composition/probe/study.d.ts.map +1 -1
- package/dist/composition/probe/study.js +6 -10
- package/dist/composition/probe/study.js.map +1 -1
- package/dist/composition/probe/t-tail.d.ts +3 -4
- package/dist/composition/probe/t-tail.d.ts.map +1 -1
- package/dist/composition/probe/t-tail.js +7 -10
- package/dist/composition/probe/t-tail.js.map +1 -1
- package/dist/composition/proposed-bridges.d.ts +11 -2
- package/dist/composition/proposed-bridges.d.ts.map +1 -1
- package/dist/composition/proposed-bridges.js +7 -5
- package/dist/composition/proposed-bridges.js.map +1 -1
- package/dist/composition/rational-exponent.d.ts +2 -2
- package/dist/composition/rational-exponent.d.ts.map +1 -1
- package/dist/composition/rational-exponent.js +4 -4
- package/dist/composition/rational-exponent.js.map +1 -1
- package/dist/composition/representative-values.d.ts.map +1 -1
- package/dist/composition/representative-values.js +6 -0
- package/dist/composition/representative-values.js.map +1 -1
- package/dist/composition/retrodiction.d.ts +15 -0
- package/dist/composition/retrodiction.d.ts.map +1 -1
- package/dist/composition/retrodiction.js +10 -3
- package/dist/composition/retrodiction.js.map +1 -1
- package/dist/composition/user-equation.d.ts +1 -0
- package/dist/composition/user-equation.d.ts.map +1 -1
- package/dist/composition/user-equation.js +1 -0
- package/dist/composition/user-equation.js.map +1 -1
- package/dist/core/constants.d.ts +12 -11
- package/dist/core/constants.d.ts.map +1 -1
- package/dist/core/constants.js +24 -21
- package/dist/core/constants.js.map +1 -1
- package/dist/diff/bridge-ast-gradient.d.ts +27 -23
- package/dist/diff/bridge-ast-gradient.d.ts.map +1 -1
- package/dist/diff/bridge-ast-gradient.js +75 -173
- package/dist/diff/bridge-ast-gradient.js.map +1 -1
- package/dist/dimensional/ast-types.d.ts +15 -0
- package/dist/dimensional/ast-types.d.ts.map +1 -1
- package/dist/dimensional/ast-types.js.map +1 -1
- package/dist/dimensional/curvature-composite.d.ts +1 -1
- package/dist/dimensional/curvature-composite.js.map +1 -1
- package/dist/dimensional/exact-scale.d.ts +41 -11
- package/dist/dimensional/exact-scale.d.ts.map +1 -1
- package/dist/dimensional/exact-scale.js +115 -123
- package/dist/dimensional/exact-scale.js.map +1 -1
- package/dist/dimensional/mathts-unit-delegation.d.ts +29 -0
- package/dist/dimensional/mathts-unit-delegation.d.ts.map +1 -0
- package/dist/dimensional/mathts-unit-delegation.js +187 -0
- package/dist/dimensional/mathts-unit-delegation.js.map +1 -0
- package/dist/dimensional/mathts-unit-wrapper.d.ts +33 -0
- package/dist/dimensional/mathts-unit-wrapper.d.ts.map +1 -0
- package/dist/dimensional/mathts-unit-wrapper.js +190 -0
- package/dist/dimensional/mathts-unit-wrapper.js.map +1 -0
- package/dist/dimensional/scalar-lowering.d.ts +21 -0
- package/dist/dimensional/scalar-lowering.d.ts.map +1 -0
- package/dist/dimensional/scalar-lowering.js +45 -0
- package/dist/dimensional/scalar-lowering.js.map +1 -0
- package/dist/dimensional/unit-data.d.ts +5 -1
- package/dist/dimensional/unit-data.d.ts.map +1 -1
- package/dist/dimensional/unit-data.js +28 -4
- package/dist/dimensional/unit-data.js.map +1 -1
- package/dist/dimensional/units.d.ts +2 -0
- package/dist/dimensional/units.d.ts.map +1 -1
- package/dist/dimensional/units.js +59 -3
- package/dist/dimensional/units.js.map +1 -1
- package/dist/dimensional/validator.d.ts +2 -0
- package/dist/dimensional/validator.d.ts.map +1 -1
- package/dist/dimensional/validator.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/numerical/connection-lowering-helpers.d.ts +3 -1
- package/dist/numerical/connection-lowering-helpers.d.ts.map +1 -1
- package/dist/numerical/connection-lowering-helpers.js +11 -15
- package/dist/numerical/connection-lowering-helpers.js.map +1 -1
- package/dist/numerical/pderiv.d.ts.map +1 -1
- package/dist/numerical/pderiv.js +2 -6
- package/dist/numerical/pderiv.js.map +1 -1
- package/dist/numerical/quadrature.js +3 -3
- package/dist/numerical/quadrature.js.map +1 -1
- package/dist/numerical/statistics.js +1 -1
- package/dist/numerical/statistics.js.map +1 -1
- package/dist/numerical/strides.d.ts +3 -2
- package/dist/numerical/strides.d.ts.map +1 -1
- package/dist/numerical/strides.js +3 -10
- package/dist/numerical/strides.js.map +1 -1
- package/package.json +9 -12
- package/dist/cases/brownian-sphere.d.ts +0 -68
- package/dist/cases/brownian-sphere.d.ts.map +0 -1
- package/dist/cases/brownian-sphere.js +0 -355
- package/dist/cases/brownian-sphere.js.map +0 -1
- package/dist/cases/damped-resonator.d.ts +0 -23
- package/dist/cases/damped-resonator.d.ts.map +0 -1
- package/dist/cases/damped-resonator.js +0 -221
- package/dist/cases/damped-resonator.js.map +0 -1
- package/dist/cases/kepler-rv.d.ts +0 -13
- package/dist/cases/kepler-rv.d.ts.map +0 -1
- package/dist/cases/kepler-rv.js +0 -173
- package/dist/cases/kepler-rv.js.map +0 -1
- package/dist/cases/lumped-cooling.d.ts +0 -51
- package/dist/cases/lumped-cooling.d.ts.map +0 -1
- package/dist/cases/lumped-cooling.js +0 -259
- package/dist/cases/lumped-cooling.js.map +0 -1
- package/dist/cases/resistor-noise.d.ts +0 -14
- package/dist/cases/resistor-noise.d.ts.map +0 -1
- package/dist/cases/resistor-noise.js +0 -215
- package/dist/cases/resistor-noise.js.map +0 -1
- package/dist/cases/skin-depth.d.ts +0 -17
- package/dist/cases/skin-depth.d.ts.map +0 -1
- package/dist/cases/skin-depth.js +0 -170
- package/dist/cases/skin-depth.js.map +0 -1
|
@@ -41,8 +41,11 @@ import { classifyAll } from './identifiability.js';
|
|
|
41
41
|
* Source values, plus a dimensionless group the edge multiplies when the
|
|
42
42
|
* ground truth names it. The group is not a source: Buckingham cannot see
|
|
43
43
|
* it, and a missing group is the unset coefficient, not a missing input.
|
|
44
|
+
* Exported for the own-equation magnitudes (`own-equation-magnitude.ts`),
|
|
45
|
+
* which evaluate an edge the same way.
|
|
46
|
+
* @internal
|
|
44
47
|
*/
|
|
45
|
-
function evaluationInputs(edge, values) {
|
|
48
|
+
export function evaluationInputs(edge, values) {
|
|
46
49
|
const inputs = {};
|
|
47
50
|
for (const s of edge.sources)
|
|
48
51
|
inputs[s.name] = values.get(s.name);
|
|
@@ -66,8 +69,12 @@ function refusalKind(err) {
|
|
|
66
69
|
return 'formula';
|
|
67
70
|
return undefined;
|
|
68
71
|
}
|
|
69
|
-
/**
|
|
70
|
-
|
|
72
|
+
/**
|
|
73
|
+
* True when the error says the edge does not fire here (or at all, for an unset coefficient).
|
|
74
|
+
* Exported so the own-equation magnitudes read an edge's refusal by this one rule.
|
|
75
|
+
* @internal
|
|
76
|
+
*/
|
|
77
|
+
export function refusesThePoint(err) {
|
|
71
78
|
return refusalKind(err) !== undefined;
|
|
72
79
|
}
|
|
73
80
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retrodiction.js","sourceRoot":"","sources":["../../src/composition/retrodiction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;A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,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAExE,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAChC,aAAa,CAAC,KAAK,EAAE,WAAW,EAAE,CAAC,EAAE,IAAI,CAAC,CAC3C,CAAC;IAEF,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,YAAY,CAAC,CAAC,MAAM,CAAC;IAC5E,MAAM,YAAY,GAAG,OAAO,CAAC,MAAM,CACjC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,cAAc,CACpC,CAAC,MAAM,CAAC;IAET,OAAO;QACL,OAAO;QACP,OAAO,EAAE,UAAU,GAAG,YAAY;QAClC,UAAU;QACV,YAAY;QACZ,aAAa,EAAE,YAAY,KAAK,CAAC;KAClC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Retrodiction harness (Consequence 2 of\n * docs/planning/Bridge-Inference-Epistemics-Note.md, designed in\n * docs/planning/Retrodiction-Harness-Design-Note.md).\n *\n * The framework's own falsification benchmark. Mask a quantity the graph\n * can compute, recompute it from ground-truth inputs via EACH independent\n * derivation, and check the predictions agree. This operationalizes the\n * identifiability classifier's OVER-DETERMINED verdict: the surplus\n * derivations of an over-determined node are PREDICTED to be consistency\n * constraints; the harness evaluates them and checks that numerically.\n *\n * - consistent — ≥2 derivations agree within tolerance.\n * - inconsistent — ≥2 derivations DISAGREE (a falsification: two\n * encodings of one quantity-name are not the same\n * physics).\n * - single — exactly one derivation fired (recovered, no check).\n * - unrecoverable — no derivation fired from the ground truth.\n *\n * \"Mask\" = compute source values over the graph with every edge INTO the\n * target removed (the classifier's target-removed closure — so the node\n * is genuinely hidden, never read back through its own derivation).\n * Forward evaluation honors `QUANTITY_IDENTIFICATIONS` and is\n * domain-checked (an edge that refuses its domain contributes no\n * prediction). The consistency check needs no external truth and is the\n * re-runnable core; an optional `references` map adds external-value\n * scoring. Pass bar pre-registered in the design note (spread ≤ 1e-6).\n *\n * @module composition/retrodiction\n */\n\nimport type { BridgeEdge } from './edge.js';\nimport { CANONICAL_GROUP_PREFACTORS } from './canonical-prefactors.js';\nimport { CoefficientUnsetError, evaluateEdge } from './edge.js';\nimport { DomainViolationError } from '../bridges/evaluation-errors.js';\nimport { CarrierSignError } from '../bridges/carrier-sign.js';\nimport { FormulaError } from '../numerical/formula-contract.js';\nimport { meanOf } from '../numerical/statistics.js';\nimport type { QuantityIdentification } from './compose.js';\nimport { QUANTITY_IDENTIFICATIONS } from './compose.js';\nimport { conventionFactor } from '../dimensional/unit-convention.js';\nimport { classifyAll } from './identifiability.js';\n\n/**\n * Source values, plus a dimensionless group the edge multiplies when the\n * ground truth names it. The group is not a source: Buckingham cannot see\n * it, and a missing group is the unset coefficient, not a missing input.\n */\nfunction evaluationInputs(edge: BridgeEdge, values: ReadonlyMap<string, number>): Record<string, number> {\n const inputs: Record<string, number> = {};\n for (const s of edge.sources) inputs[s.name] = values.get(s.name)!;\n const group = CANONICAL_GROUP_PREFACTORS.find((g) => g.id === edge.id);\n if (group !== undefined) {\n const g = values.get(group.group);\n if (g !== undefined) inputs[group.group] = g;\n }\n return inputs;\n}\n\n/** Outcome of retrodicting one node. @public */\nexport type RetrodictionOutcome =\n | 'consistent'\n | 'inconsistent'\n | 'single'\n | 'unrecoverable';\n\n/** One derivation's recovered value for a masked node. @public */\nexport interface RetrodictionPrediction {\n /** The edge id that produced this value. */\n readonly edge: string;\n readonly value: number;\n}\n\n/** Options for the harness. @public */\nexport interface RetrodictionOptions {\n /** Identifications honored in forward evaluation (default registered). */\n readonly identifications?: readonly QuantityIdentification[];\n /** Relative-spread tolerance for `consistent` (default 1e-6). */\n readonly tolerance?: number;\n /** External (textbook) values to score recovered nodes against. */\n readonly references?: Readonly<Record<string, number>>;\n /** Relative-error tolerance for reference scoring (default 1e-3). */\n readonly referenceTolerance?: number;\n}\n\n/** One refused edge in a retrodiction, with the kind of refusal. @public */\nexport interface RetrodictionRefusal {\n readonly edge: string;\n /**\n * `domain`: the validity domain rejected the point. `coefficient-unset`: the edge has no\n * sourced prefactor, whatever the values. `carrier-sign`: the carrier charge and the\n * mobility had opposite signs. `formula`: the relation's formula did not evaluate at the\n * point (a 0/0, say). Four facts, kept apart (AGENTS law 4).\n */\n readonly kind: 'domain' | 'coefficient-unset' | 'carrier-sign' | 'formula';\n readonly reason: string;\n}\n\n/** The result of retrodicting one node. @public */\nexport interface RetrodictionResult {\n readonly target: string;\n readonly outcome: RetrodictionOutcome;\n /** Recovered values, one per derivation that fired. */\n readonly predictions: readonly RetrodictionPrediction[];\n /** (max − min)/|mean| across predictions; 0 when fewer than two. */\n readonly relativeSpread: number;\n readonly tolerance: number;\n /**\n * Edges that refused the supplied values. `kind` keeps the refusals apart (AGENTS law 4):\n * `domain`, `carrier-sign` and `formula` are the point (the edge does not fire there);\n * `coefficient-unset` is the edge's own state (no sourced prefactor), whatever the values.\n */\n readonly refusals?: readonly RetrodictionRefusal[];\n /** `outcome !== 'inconsistent'` — the falsification gate. */\n readonly pass: boolean;\n /** Supplied external value, when scored. */\n readonly referenceValue?: number;\n /** |mean(predictions) − reference| / |reference|, when scored. */\n readonly referenceRelError?: number;\n readonly referencePass?: boolean;\n}\n\n/** Aggregate report across the swept nodes. @public */\nexport interface RetrodictionReport {\n readonly results: readonly RetrodictionResult[];\n /** Nodes with ≥2 derivations (consistent + inconsistent). */\n readonly checked: number;\n readonly consistent: number;\n readonly inconsistent: number;\n /** The headline gate: no inconsistent node was found. */\n readonly allConsistent: boolean;\n}\n\n/** The refusal an evaluator error is, or `undefined` when it is not a refusal at all. */\nfunction refusalKind(err: unknown): RetrodictionRefusal['kind'] | undefined {\n if (err instanceof DomainViolationError) return 'domain';\n if (err instanceof CoefficientUnsetError) return 'coefficient-unset';\n if (err instanceof CarrierSignError) return 'carrier-sign';\n if (err instanceof FormulaError) return 'formula';\n return undefined;\n}\n\n/** True when the error says the edge does not fire here (or at all, for an unset coefficient). */\nfunction refusesThePoint(err: unknown): boolean {\n return refusalKind(err) !== undefined;\n}\n\n/**\n * Monotone forward EVALUATION: propagate values from `groundTruth` through\n * the graph (domain-checked; identifications supply identified names;\n * non-finite or domain-refused edges do not fire). Each node is assigned\n * the value of the first edge that fires for it.\n *\n * Exported `@internal` so the discovery magnitude-gate can read a quantity's\n * value AT THE REGISTERED ANCHOR when the static representative-value table\n * has no entry for it (graph-derived quantities like `schwarzschild-radius`).\n *\n * @internal\n */\nexport function forwardEvaluate(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n idents: readonly QuantityIdentification[],\n): Map<string, number> {\n // Finite-seed guard (matches the computed-value guard below and the\n // library-wide finiteness discipline): a NaN/∞ seed would propagate silently\n // through the graph and spoof downstream magnitude/consistency checks.\n for (const [name, v] of Object.entries(groundTruth)) {\n if (!Number.isFinite(v)) {\n throw new TypeError(\n `forwardEvaluate: ground-truth seed '${name}' must be a finite number, got ${v}.`,\n );\n }\n }\n const values = new Map<string, number>(Object.entries(groundTruth));\n let changed = true;\n while (changed) {\n changed = false;\n for (const id of idents) {\n const fromVal = values.get(id.from);\n if (fromVal !== undefined && !values.has(id.to)) {\n const converted = fromVal * conventionFactor(id.from, id.to);\n if (Number.isFinite(converted)) {\n values.set(id.to, converted);\n changed = true;\n }\n }\n }\n for (const e of edges) {\n if (values.has(e.target.name)) continue;\n if (!e.sources.every((s) => values.has(s.name))) continue;\n const inputs = evaluationInputs(e, values);\n let v: number;\n try {\n v = evaluateEdge(e, inputs);\n } catch (err) {\n // The edge refusing this point (a domain miss, opposite carrier signs, a formula\n // that has no finite value there) or an unset coefficient is \"the edge does not\n // fire\". Anything else (an alias conflict, a TypeError in an evaluator) is a\n // different fact and is not hidden as a non-derivation (9.0.0 audit §4 C6).\n if (!refusesThePoint(err)) throw err;\n continue;\n }\n if (Number.isFinite(v)) {\n values.set(e.target.name, v);\n changed = true;\n }\n }\n }\n return values;\n}\n\n/**\n * Retrodict one node: mask it (source values from the target-removed\n * graph), recover it via each incoming edge, and score the spread.\n *\n * @public\n */\nexport function retrodictNode(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n target: string,\n opts: RetrodictionOptions = {},\n): RetrodictionResult {\n const idents = opts.identifications ?? QUANTITY_IDENTIFICATIONS;\n const tolerance = opts.tolerance ?? 1e-6;\n\n // Masked source values: never let the target be assigned (so no\n // derivation reads it back — circular self-support excluded).\n const edgesMinusIntoTarget = edges.filter((e) => e.target.name !== target);\n const values = forwardEvaluate(edgesMinusIntoTarget, groundTruth, idents);\n\n const predictions: RetrodictionPrediction[] = [];\n const refusals: RetrodictionRefusal[] = [];\n for (const e of edges) {\n if (e.target.name !== target) continue;\n if (!e.sources.every((s) => values.has(s.name))) continue;\n const inputs = evaluationInputs(e, values);\n let v: number;\n try {\n v = evaluateEdge(e, inputs);\n } catch (err) {\n // A refusal of the point or an unset coefficient is a recorded refusal of\n // this edge, under its own kind. Any other error (an alias conflict, a\n // TypeError in an evaluator) is a different fact and propagates instead of\n // reading as \"unrecoverable\" (§4 C6).\n const kind = refusalKind(err);\n if (kind === undefined) throw err;\n refusals.push({ edge: e.id, kind, reason: (err as Error).message });\n continue;\n }\n if (Number.isFinite(v)) predictions.push({ edge: e.id, value: v });\n }\n\n let relativeSpread = 0;\n if (predictions.length >= 2) {\n const vals = predictions.map((p) => p.value);\n const max = Math.max(...vals);\n const min = Math.min(...vals);\n // Normalize the (max − min) span by the largest MAGNITUDE, not the mean:\n // opposite-sign predictions (e.g. +6 and −6) cancel in the mean → a ~0\n // denominator → spurious Infinity, even though the true relative spread is\n // finite (12/6 = 2). `maxAbs === 0` only when every value is 0 (max = min),\n // so the span is 0 too.\n const maxAbs = Math.max(...vals.map(Math.abs));\n relativeSpread = maxAbs > 0 ? (max - min) / maxAbs : 0;\n }\n\n let outcome: RetrodictionOutcome;\n if (predictions.length === 0) outcome = 'unrecoverable';\n else if (predictions.length === 1) outcome = 'single';\n else outcome = relativeSpread <= tolerance ? 'consistent' : 'inconsistent';\n\n const result: RetrodictionResult = {\n target,\n outcome,\n predictions,\n relativeSpread,\n tolerance,\n ...(refusals.length > 0 ? { refusals } : {}),\n pass: outcome !== 'inconsistent',\n };\n\n const ref = opts.references?.[target];\n if (ref !== undefined && predictions.length >= 1) {\n const mean = meanOf(predictions.map((p) => p.value));\n const referenceRelError = Math.abs(mean - ref) / (Math.abs(ref) || 1);\n return {\n ...result,\n referenceValue: ref,\n referenceRelError,\n referencePass: referenceRelError <= (opts.referenceTolerance ?? 1e-3),\n };\n }\n\n return result;\n}\n\n/**\n * Sweep the graph: retrodict every over-determined node (the classifier\n * is the feeder), plus any node with a supplied reference value. Returns\n * the per-node results and the headline `allConsistent` gate.\n *\n * @public\n */\nexport function retrodict(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n opts: RetrodictionOptions = {},\n): RetrodictionReport {\n const idents = opts.identifications ?? QUANTITY_IDENTIFICATIONS;\n const known = Object.keys(groundTruth);\n const classified = classifyAll(edges, known, { identifications: idents });\n\n const overDetermined = classified\n .filter((r) => r.verdict === 'over-determined')\n .map((r) => r.target);\n const refTargets = opts.references ? Object.keys(opts.references) : [];\n const targets = [...new Set([...overDetermined, ...refTargets])].sort();\n\n const results = targets.map((t) =>\n retrodictNode(edges, groundTruth, t, opts),\n );\n\n const consistent = results.filter((r) => r.outcome === 'consistent').length;\n const inconsistent = results.filter(\n (r) => r.outcome === 'inconsistent',\n ).length;\n\n return {\n results,\n checked: consistent + inconsistent,\n consistent,\n inconsistent,\n allConsistent: inconsistent === 0,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retrodiction.js","sourceRoot":"","sources":["../../src/composition/retrodiction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAA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IACxB,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACvE,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,cAAc,EAAE,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAExE,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAChC,aAAa,CAAC,KAAK,EAAE,WAAW,EAAE,CAAC,EAAE,IAAI,CAAC,CAC3C,CAAC;IAEF,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,YAAY,CAAC,CAAC,MAAM,CAAC;IAC5E,MAAM,YAAY,GAAG,OAAO,CAAC,MAAM,CACjC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,cAAc,CACpC,CAAC,MAAM,CAAC;IAET,OAAO;QACL,OAAO;QACP,OAAO,EAAE,UAAU,GAAG,YAAY;QAClC,UAAU;QACV,YAAY;QACZ,aAAa,EAAE,YAAY,KAAK,CAAC;KAClC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Retrodiction harness (Consequence 2 of\n * docs/planning/Bridge-Inference-Epistemics-Note.md, designed in\n * docs/planning/Retrodiction-Harness-Design-Note.md).\n *\n * The framework's own falsification benchmark. Mask a quantity the graph\n * can compute, recompute it from ground-truth inputs via EACH independent\n * derivation, and check the predictions agree. This operationalizes the\n * identifiability classifier's OVER-DETERMINED verdict: the surplus\n * derivations of an over-determined node are PREDICTED to be consistency\n * constraints; the harness evaluates them and checks that numerically.\n *\n * - consistent — ≥2 derivations agree within tolerance.\n * - inconsistent — ≥2 derivations DISAGREE (a falsification: two\n * encodings of one quantity-name are not the same\n * physics).\n * - single — exactly one derivation fired (recovered, no check).\n * - unrecoverable — no derivation fired from the ground truth.\n *\n * \"Mask\" = compute source values over the graph with every edge INTO the\n * target removed (the classifier's target-removed closure — so the node\n * is genuinely hidden, never read back through its own derivation).\n * Forward evaluation honors `QUANTITY_IDENTIFICATIONS` and is\n * domain-checked (an edge that refuses its domain contributes no\n * prediction). The consistency check needs no external truth and is the\n * re-runnable core; an optional `references` map adds external-value\n * scoring. Pass bar pre-registered in the design note (spread ≤ 1e-6).\n *\n * @module composition/retrodiction\n */\n\nimport type { BridgeEdge } from './edge.js';\nimport { CANONICAL_GROUP_PREFACTORS } from './canonical-prefactors.js';\nimport { CoefficientUnsetError, evaluateEdge } from './edge.js';\nimport { DomainViolationError } from '../bridges/evaluation-errors.js';\nimport { CarrierSignError } from '../bridges/carrier-sign.js';\nimport { FormulaError } from '../numerical/formula-contract.js';\nimport { meanOf } from '../numerical/statistics.js';\nimport type { QuantityIdentification } from './compose.js';\nimport { QUANTITY_IDENTIFICATIONS } from './compose.js';\nimport { conventionFactor } from '../dimensional/unit-convention.js';\nimport { classifyAll } from './identifiability.js';\n\n/**\n * Source values, plus a dimensionless group the edge multiplies when the\n * ground truth names it. The group is not a source: Buckingham cannot see\n * it, and a missing group is the unset coefficient, not a missing input.\n * Exported for the own-equation magnitudes (`own-equation-magnitude.ts`),\n * which evaluate an edge the same way.\n * @internal\n */\nexport function evaluationInputs(edge: BridgeEdge, values: ReadonlyMap<string, number>): Record<string, number> {\n const inputs: Record<string, number> = {};\n for (const s of edge.sources) inputs[s.name] = values.get(s.name)!;\n const group = CANONICAL_GROUP_PREFACTORS.find((g) => g.id === edge.id);\n if (group !== undefined) {\n const g = values.get(group.group);\n if (g !== undefined) inputs[group.group] = g;\n }\n return inputs;\n}\n\n/** Outcome of retrodicting one node. @public */\nexport type RetrodictionOutcome =\n | 'consistent'\n | 'inconsistent'\n | 'single'\n | 'unrecoverable';\n\n/** One derivation's recovered value for a masked node. @public */\nexport interface RetrodictionPrediction {\n /** The edge id that produced this value. */\n readonly edge: string;\n readonly value: number;\n}\n\n/** Options for the harness. @public */\nexport interface RetrodictionOptions {\n /** Identifications honored in forward evaluation (default registered). */\n readonly identifications?: readonly QuantityIdentification[];\n /** Relative-spread tolerance for `consistent` (default 1e-6). */\n readonly tolerance?: number;\n /** External (textbook) values to score recovered nodes against. */\n readonly references?: Readonly<Record<string, number>>;\n /** Relative-error tolerance for reference scoring (default 1e-3). */\n readonly referenceTolerance?: number;\n}\n\n/** One refused edge in a retrodiction, with the kind of refusal. @public */\nexport interface RetrodictionRefusal {\n readonly edge: string;\n /**\n * `domain`: the validity domain rejected the point. `coefficient-unset`: the edge has no\n * sourced prefactor, whatever the values. `carrier-sign`: the carrier charge and the\n * mobility had opposite signs. `formula`: the relation's formula did not evaluate at the\n * point (a 0/0, say). Four facts, kept apart (AGENTS law 4).\n */\n readonly kind: 'domain' | 'coefficient-unset' | 'carrier-sign' | 'formula';\n readonly reason: string;\n}\n\n/** The result of retrodicting one node. @public */\nexport interface RetrodictionResult {\n readonly target: string;\n readonly outcome: RetrodictionOutcome;\n /** Recovered values, one per derivation that fired. */\n readonly predictions: readonly RetrodictionPrediction[];\n /** (max − min)/|mean| across predictions; 0 when fewer than two. */\n readonly relativeSpread: number;\n readonly tolerance: number;\n /**\n * Edges that refused the supplied values. `kind` keeps the refusals apart (AGENTS law 4):\n * `domain`, `carrier-sign` and `formula` are the point (the edge does not fire there);\n * `coefficient-unset` is the edge's own state (no sourced prefactor), whatever the values.\n */\n readonly refusals?: readonly RetrodictionRefusal[];\n /** `outcome !== 'inconsistent'` — the falsification gate. */\n readonly pass: boolean;\n /** Supplied external value, when scored. */\n readonly referenceValue?: number;\n /** |mean(predictions) − reference| / |reference|, when scored. */\n readonly referenceRelError?: number;\n readonly referencePass?: boolean;\n}\n\n/** Aggregate report across the swept nodes. @public */\nexport interface RetrodictionReport {\n readonly results: readonly RetrodictionResult[];\n /** Nodes with ≥2 derivations (consistent + inconsistent). */\n readonly checked: number;\n readonly consistent: number;\n readonly inconsistent: number;\n /** The headline gate: no inconsistent node was found. */\n readonly allConsistent: boolean;\n}\n\n/** The refusal an evaluator error is, or `undefined` when it is not a refusal at all. */\nfunction refusalKind(err: unknown): RetrodictionRefusal['kind'] | undefined {\n if (err instanceof DomainViolationError) return 'domain';\n if (err instanceof CoefficientUnsetError) return 'coefficient-unset';\n if (err instanceof CarrierSignError) return 'carrier-sign';\n if (err instanceof FormulaError) return 'formula';\n return undefined;\n}\n\n/**\n * True when the error says the edge does not fire here (or at all, for an unset coefficient).\n * Exported so the own-equation magnitudes read an edge's refusal by this one rule.\n * @internal\n */\nexport function refusesThePoint(err: unknown): boolean {\n return refusalKind(err) !== undefined;\n}\n\n/**\n * Monotone forward EVALUATION: propagate values from `groundTruth` through\n * the graph (domain-checked; identifications supply identified names;\n * non-finite or domain-refused edges do not fire). Each node is assigned\n * the value of the first edge that fires for it.\n *\n * Exported `@internal` so the discovery magnitude-gate can read a quantity's\n * value AT THE REGISTERED ANCHOR when the static representative-value table\n * has no entry for it (graph-derived quantities like `schwarzschild-radius`).\n *\n * @internal\n */\nexport function forwardEvaluate(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n idents: readonly QuantityIdentification[],\n): Map<string, number> {\n // Finite-seed guard (matches the computed-value guard below and the\n // library-wide finiteness discipline): a NaN/∞ seed would propagate silently\n // through the graph and spoof downstream magnitude/consistency checks.\n for (const [name, v] of Object.entries(groundTruth)) {\n if (!Number.isFinite(v)) {\n throw new TypeError(\n `forwardEvaluate: ground-truth seed '${name}' must be a finite number, got ${v}.`,\n );\n }\n }\n const values = new Map<string, number>(Object.entries(groundTruth));\n let changed = true;\n while (changed) {\n changed = false;\n for (const id of idents) {\n const fromVal = values.get(id.from);\n if (fromVal !== undefined && !values.has(id.to)) {\n const converted = fromVal * conventionFactor(id.from, id.to);\n if (Number.isFinite(converted)) {\n values.set(id.to, converted);\n changed = true;\n }\n }\n }\n for (const e of edges) {\n if (values.has(e.target.name)) continue;\n if (!e.sources.every((s) => values.has(s.name))) continue;\n const inputs = evaluationInputs(e, values);\n let v: number;\n try {\n v = evaluateEdge(e, inputs);\n } catch (err) {\n // The edge refusing this point (a domain miss, opposite carrier signs, a formula\n // that has no finite value there) or an unset coefficient is \"the edge does not\n // fire\". Anything else (an alias conflict, a TypeError in an evaluator) is a\n // different fact and is not hidden as a non-derivation (9.0.0 audit §4 C6).\n if (!refusesThePoint(err)) throw err;\n continue;\n }\n if (Number.isFinite(v)) {\n values.set(e.target.name, v);\n changed = true;\n }\n }\n }\n return values;\n}\n\n/**\n * Retrodict one node: mask it (source values from the target-removed\n * graph), recover it via each incoming edge, and score the spread.\n *\n * @public\n */\nexport function retrodictNode(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n target: string,\n opts: RetrodictionOptions = {},\n): RetrodictionResult {\n const idents = opts.identifications ?? QUANTITY_IDENTIFICATIONS;\n const tolerance = opts.tolerance ?? 1e-6;\n\n // Masked source values: never let the target be assigned (so no\n // derivation reads it back — circular self-support excluded).\n const edgesMinusIntoTarget = edges.filter((e) => e.target.name !== target);\n const values = forwardEvaluate(edgesMinusIntoTarget, groundTruth, idents);\n\n const predictions: RetrodictionPrediction[] = [];\n const refusals: RetrodictionRefusal[] = [];\n for (const e of edges) {\n if (e.target.name !== target) continue;\n if (!e.sources.every((s) => values.has(s.name))) continue;\n const inputs = evaluationInputs(e, values);\n let v: number;\n try {\n v = evaluateEdge(e, inputs);\n } catch (err) {\n // A refusal of the point or an unset coefficient is a recorded refusal of\n // this edge, under its own kind. Any other error (an alias conflict, a\n // TypeError in an evaluator) is a different fact and propagates instead of\n // reading as \"unrecoverable\" (§4 C6).\n const kind = refusalKind(err);\n if (kind === undefined) throw err;\n refusals.push({ edge: e.id, kind, reason: (err as Error).message });\n continue;\n }\n if (Number.isFinite(v)) predictions.push({ edge: e.id, value: v });\n }\n\n let relativeSpread = 0;\n if (predictions.length >= 2) {\n const vals = predictions.map((p) => p.value);\n const max = Math.max(...vals);\n const min = Math.min(...vals);\n // Normalize the (max − min) span by the largest MAGNITUDE, not the mean:\n // opposite-sign predictions (e.g. +6 and −6) cancel in the mean → a ~0\n // denominator → spurious Infinity, even though the true relative spread is\n // finite (12/6 = 2). `maxAbs === 0` only when every value is 0 (max = min),\n // so the span is 0 too.\n const maxAbs = Math.max(...vals.map(Math.abs));\n relativeSpread = maxAbs > 0 ? (max - min) / maxAbs : 0;\n }\n\n let outcome: RetrodictionOutcome;\n if (predictions.length === 0) outcome = 'unrecoverable';\n else if (predictions.length === 1) outcome = 'single';\n else outcome = relativeSpread <= tolerance ? 'consistent' : 'inconsistent';\n\n const result: RetrodictionResult = {\n target,\n outcome,\n predictions,\n relativeSpread,\n tolerance,\n ...(refusals.length > 0 ? { refusals } : {}),\n pass: outcome !== 'inconsistent',\n };\n\n const ref = opts.references?.[target];\n if (ref !== undefined && predictions.length >= 1) {\n const mean = meanOf(predictions.map((p) => p.value));\n const referenceRelError = Math.abs(mean - ref) / (Math.abs(ref) || 1);\n return {\n ...result,\n referenceValue: ref,\n referenceRelError,\n referencePass: referenceRelError <= (opts.referenceTolerance ?? 1e-3),\n };\n }\n\n return result;\n}\n\n/**\n * Sweep the graph: retrodict every over-determined node (the classifier\n * is the feeder), plus any node with a supplied reference value. Returns\n * the per-node results and the headline `allConsistent` gate.\n *\n * @public\n */\nexport function retrodict(\n edges: readonly BridgeEdge[],\n groundTruth: Readonly<Record<string, number>>,\n opts: RetrodictionOptions = {},\n): RetrodictionReport {\n const idents = opts.identifications ?? QUANTITY_IDENTIFICATIONS;\n const known = Object.keys(groundTruth);\n const classified = classifyAll(edges, known, { identifications: idents });\n\n const overDetermined = classified\n .filter((r) => r.verdict === 'over-determined')\n .map((r) => r.target);\n const refTargets = opts.references ? Object.keys(opts.references) : [];\n const targets = [...new Set([...overDetermined, ...refTargets])].sort();\n\n const results = targets.map((t) =>\n retrodictNode(edges, groundTruth, t, opts),\n );\n\n const consistent = results.filter((r) => r.outcome === 'consistent').length;\n const inconsistent = results.filter(\n (r) => r.outcome === 'inconsistent',\n ).length;\n\n return {\n results,\n checked: consistent + inconsistent,\n consistent,\n inconsistent,\n allConsistent: inconsistent === 0,\n };\n}\n"]}
|
|
@@ -64,6 +64,7 @@ export interface AnalyzeUserEquationOptions {
|
|
|
64
64
|
/** Reconcile a dimension difference by powers of c, ħ, and (geometrized) G. */
|
|
65
65
|
readonly units?: Exclude<UnitMode, 'si'>;
|
|
66
66
|
}
|
|
67
|
+
/** Parse a `TARGET = EXPR` equation into its target and source quantities. A malformed equation throws. */
|
|
67
68
|
export declare function parseUserEquation(equation: string, catalogNames?: ReadonlySet<string> | Iterable<string>): Promise<UserEquation>;
|
|
68
69
|
/**
|
|
69
70
|
* Up to `k` catalog names most similar to `name` — the "did you mean?" set for an
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-equation.d.ts","sourceRoot":"","sources":["../../src/composition/user-equation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAOH,OAAO,EAA8B,KAAK,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAI5F,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAKzD,oFAAoF;AACpF,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,iEAAiE;IACjE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAiBD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,oFAAoF;AACpF,OAAO,EAAE,qBAAqB,EA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,WAAW,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,EAC3C,OAAO,CAAC,EAAE,0BAA0B,GACnC,OAAO,CAAC,gBAAgB,CAAC,CAgI3B"}
|
|
@@ -104,6 +104,7 @@ function withFormulaNames(catalog) {
|
|
|
104
104
|
}
|
|
105
105
|
return out;
|
|
106
106
|
}
|
|
107
|
+
/** Parse a `TARGET = EXPR` equation into its target and source quantities. A malformed equation throws. */
|
|
107
108
|
export async function parseUserEquation(equation, catalogNames) {
|
|
108
109
|
if (equation.length > MAX_USER_EQUATION_LEN) {
|
|
109
110
|
throw new UserEquationError(`equation exceeds ${MAX_USER_EQUATION_LEN} characters (${equation.length})`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-equation.js","sourceRoot":"","sources":["../../src/composition/user-equation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAiB,MAAM,iCAAiC,CAAC;AAC5F,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD,OAAO,EAAE,aAAa,EAAE,MAAM,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CAAC,CAAC,CAAC,IAAI,CAAC;IAChG,IAAI,OAA2B,CAAC;IAChC,IACE,UAAU,KAAK,KAAK;QACpB,YAAY;QACZ,eAAe;QACf,OAAO,EAAE,KAAK,KAAK,SAAS;QAC5B,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,EACpB,CAAC;QACD,MAAM,MAAM,GAAG,aAAa,CAAC,YAAY,EAAE,eAAe,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QAC3E,MAAM,IAAI,GAAG,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QACzE,IAAI,IAAI,EAAE,CAAC;YACT,UAAU,GAAG,IAAI,CAAC;YAClB,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IAED,OAAO;QACL,QAAQ,EAAE;YACR,EAAE,EAAE,eAAe;YACnB,KAAK,EAAE,EAAE,CAAC,IAAI;YACd,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC/C,MAAM,EAAE,cAAc,IAAI,EAAE,CAAC,MAAM;SACpC;QACD,UAAU;QACV,YAAY;QACZ,eAAe;QACf,UAAU;QACV,KAAK;QACL,aAAa,EAAE,CAAC,GAAG,QAAQ,EAAE,GAAG,UAAU,EAAE,GAAG,cAAc,CAAC;QAC9D,YAAY;QACZ,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;KAC3D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * User-equation injection — turn a free-form `TARGET = EXPR` string into a graph\n * junction (a target quantity + its source quantities), resolve the user's\n * symbols onto the catalog vocabulary, suggest near-misses, and report where the\n * injected junction lands in a built {@link VizModel}.\n *\n * Free-form means no dimensions: source quantities are the RHS's free variables\n * — extracted by the MathTS expression parser via {@link getFormulaParser},\n * which already drops constants like `pi`/`tau`, numbers, and functions —\n * minus the physics {@link CONSTANTS}. Multi-word quantities may be typed with\n * underscores **or** the catalog's own hyphens (`planck-length`): before parse,\n * {@link rewriteCatalogHyphens} rewrites kebab catalog names to underscores so\n * `-` is not read as subtraction (persona finding W2). Resolution still tries\n * the literal form first, then the `_`↔`-` swap.\n *\n * Pure: no file I/O. The injected junction is rendered as an `extraJunction`\n * (status `'user'`) and is never written into the catalog.\n *\n * @module composition/user-equation\n */\n\nimport { getFormulaParser, parsePhysics } from '../numerical/formula-registry.js';\nimport { formulaSymbolDimension } from '../numerical/formula-dimension.js';\nimport { CONSTANT_SPELLINGS } from '../dimensional/dimension-spec.js';\nimport { CONSTANTS, isRegisteredConstant } from '../dimensional/symbolic-constants.js';\nimport { formulaNameDimensions } from '../dimensional/formula-names.js';\nimport { naturalNote, naturalPowers, type UnitMode } from '../dimensional/natural-units.js';\nimport { aliasesForTarget, editDistance } from './aliases.js';\nimport { resolveQuantityName } from '../dimensional/formula-names.js';\nimport { CATALOG_GRAPH } from './catalog-graph.js';\nimport type { VizModel, VizJunction } from './graph-viz.js';\nimport type { Dimension } from '../dimensional/types.js';\nimport { DIMENSIONLESS } from '../dimensional/types.js';\nimport { equals } from '../dimensional/algebra.js';\nimport { inferUnknownDimension } from '../dimensional/dimension-inference.js';\n\n/** Thrown when a user equation cannot be parsed into a target + sources. @public */\nexport class UserEquationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserEquationError';\n }\n}\n\n/**\n * A parsed user equation: the target quantity and its source quantities, as\n * written (underscores preserved; constants/numbers/functions removed).\n *\n * @public\n */\nexport interface UserEquation {\n readonly target: string;\n readonly sources: readonly string[];\n /** The original `TARGET = EXPR` text, for the junction label. */\n readonly text: string;\n}\n\n/**\n * Parse `TARGET = EXPR` into `{ target, sources }`. The target is the text left\n * of the first `=`; the sources are the RHS's free variables minus the physics\n * constants.\n *\n * Uses the active formula parser (MathTS when installed, built-in otherwise) to\n * extract the RHS's free variables.\n *\n * @throws {UserEquationError} on a missing `=`, an empty target, an unparseable\n * RHS, or an RHS with no source quantities.\n * @public\n */\n/** Upper bound on user `--equation` text to keep hint computation bounded. */\nconst MAX_USER_EQUATION_LEN = 8192;\n\nimport { rewriteCatalogHyphens } from '../dimensional/hyphen-names.js';\n/** Rewrite a catalog hyphenated name to underscores before the expression parse. */\nexport { rewriteCatalogHyphens };\n\n/** A hyphen-joined run of names, `a-b` or `a-b-c`, not the exponent of `1e-5`. */\nconst HYPHEN_RUN = /(?<![A-Za-z0-9_.])[A-Za-z_][A-Za-z0-9_]*(?:-[A-Za-z0-9_]+)+/g;\n\n/**\n * When the parse read a hyphen-joined run (`thermal-mass`) as a subtraction of\n * its pieces, and the run read as one name is a catalog quantity, tell the user\n * `-` is arithmetic here and to use underscores. Persona finding I2.\n *\n * Decided from the parse, not from an error's text: `variables` are the free\n * variables the formula parser read from `rhs`. The parser has no hyphenated\n * identifier, so a run whose underscored name is not a variable and whose\n * pieces are was parsed as a subtraction.\n *\n * @internal\n */\nexport function hyphenSubtractHint(\n rhs: string,\n variables: readonly string[],\n catalogNames: ReadonlySet<string>,\n): string | null {\n const read = new Set(variables);\n const split = (rhs.match(HYPHEN_RUN) ?? []).filter(\n (run) =>\n !read.has(run.replace(/-/g, '_')) &&\n run.split('-').some((piece) => read.has(piece)) &&\n resolveQuantityName(run, catalogNames) !== null,\n );\n if (split.length === 0) return null;\n const example = split.sort((a, b) => b.length - a.length)[0]!;\n return (\n `'-' is arithmetic here; multi-word catalog names use underscores ` +\n `(${example} → ${example.replace(/-/g, '_')})`\n );\n}\n\n/**\n * Spellings that must not be a bare `e`. Constant aliases come from\n * {@link CONSTANT_SPELLINGS}. `1-eccentricity^2` is the perihelion factor\n * `one_minus_e_sq`.\n */\nfunction rewriteFormulaSpellings(text: string): string {\n let out = text;\n for (const { names } of CONSTANT_SPELLINGS) {\n const canonical = names[0]!;\n for (const alias of names.slice(1)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias)) continue;\n out = out.replace(new RegExp(`(?<![A-Za-z0-9_])${alias}(?![A-Za-z0-9_])`, 'g'), canonical);\n }\n }\n return out.replace(\n /(?<![A-Za-z0-9_])1\\s*-\\s*eccentricity\\s*(?:\\^|\\*\\*)\\s*2(?![A-Za-z0-9_])/g,\n 'one_minus_e_sq',\n );\n}\n\n/** Options for {@link analyzeUserEquation}. @internal */\nexport interface AnalyzeUserEquationOptions {\n /**\n * Bind a one-letter token that is itself a catalog quantity (`a`, `r`, …).\n * Default false: the match is reported and not applied. The alias `T` →\n * `temperature` is not a one-letter catalog name and still binds.\n */\n readonly bindShortNames?: boolean;\n /** Reconcile a dimension difference by powers of c, ħ, and (geometrized) G. */\n readonly units?: Exclude<UnitMode, 'si'>;\n}\n\nfunction withFormulaNames(catalog: ReadonlyMap<string, Dimension>): Map<string, Dimension> {\n const out = new Map(catalog);\n for (const [name, dim] of formulaNameDimensions()) {\n if (!out.has(name)) out.set(name, dim);\n }\n return out;\n}\n\nexport async function parseUserEquation(\n equation: string,\n catalogNames?: ReadonlySet<string> | Iterable<string>,\n): Promise<UserEquation> {\n if (equation.length > MAX_USER_EQUATION_LEN) {\n throw new UserEquationError(\n `equation exceeds ${MAX_USER_EQUATION_LEN} characters (${equation.length})`,\n );\n }\n // Materialized once: an iterator (`map.keys()`) would be spent by the first use.\n const names = catalogNames === undefined ? undefined : new Set(catalogNames);\n const spelled = rewriteFormulaSpellings(equation);\n const rewritten = names === undefined ? spelled : rewriteCatalogHyphens(spelled, names);\n const eqIdx = rewritten.indexOf('=');\n if (eqIdx < 0) {\n throw new UserEquationError(\n `equation must be \"TARGET = EXPR\" (no \"=\" found in '${equation}')`,\n );\n }\n const target = rewritten.slice(0, eqIdx).trim();\n if (!target) throw new UserEquationError('equation has an empty target (left of \"=\")');\n const rhs = rewritten.slice(eqIdx + 1).trim();\n if (!rhs) throw new UserEquationError('equation has an empty right-hand side');\n\n let variables: readonly string[];\n try {\n const parser = await getFormulaParser();\n ({ variables } = parser.parse(rhs));\n } catch (e) {\n // No parse tree, so no subtraction was read: the hyphen hint needs the parsed variables.\n throw new UserEquationError(`could not parse the right-hand side '${rhs}': ${(e as Error).message}`);\n }\n const sources = variables.filter((v) => !isRegisteredConstant(v));\n // An all-constant right-hand side (the Planck length) is an equation about a catalog quantity\n // only when its target is one; otherwise it names nothing to check (persona finding W5).\n const targetIsCatalog = names !== undefined && resolveQuantityName(target, names) !== null;\n if (sources.length === 0 && !targetIsCatalog) {\n throw new UserEquationError(\n `no source quantities in '${rhs}' (only constants/numbers?)`,\n );\n }\n return { target, sources, text: rewritten.trim() };\n}\n\n/** Normalize for comparison: lowercase, `_`/`-` unified. */\nconst normalizeForCompare = (s: string): string => s.toLowerCase().replace(/[_-]/g, '-');\n\n/** The shortest name that counts as contained in another for the \"did you mean?\" ranking. */\nconst MIN_CONTAINED = 3;\n\n/**\n * The one \"did you mean?\" ranking, shared by {@link suggestQuantities} and\n * {@link suggestByDimension}: edit distance first, then containment (one name\n * inside the other), then length, then name. Edit distance leads so a one-edit\n * typo beats a substring: `hawkng-temperature` → `hawking-temperature` before\n * `temperature` (persona finding N5). `gate` keeps a candidate only if one name\n * contains the other (the contained one at least three characters long) or the\n * distance is small against the query length; the\n * dimension-based caller passes `false`, because there the dimension is the evidence.\n */\nfunction rankByName(name: string, candidates: Iterable<string>, gate: boolean): string[] {\n const needle = normalizeForCompare(name);\n // Without the gate, short catalog names (`a`, `nu`) are spurious \"matches\" for any typo.\n const maxDist = Math.max(1, Math.ceil(needle.length / 2));\n // A contained name counts only from MIN_CONTAINED characters: every one-letter name occurs inside\n // a long input (`schrodinger-equation` holds a, g, q, r), and that is not nearness (audit I5).\n const within = (outer: string, inner: string): boolean => inner.length >= MIN_CONTAINED && outer.includes(inner);\n return [...candidates]\n .map((cand) => {\n const hay = normalizeForCompare(cand);\n const contains = within(hay, needle) || within(needle, hay) ? 0 : 1;\n return { cand, contains, dist: editDistance(needle, hay) };\n })\n .filter((s) => !gate || s.contains === 0 || s.dist <= maxDist)\n .sort(\n (x, y) =>\n x.dist - y.dist ||\n x.contains - y.contains ||\n x.cand.length - y.cand.length ||\n x.cand.localeCompare(y.cand),\n )\n .map((s) => s.cand);\n}\n\n/**\n * Up to `k` catalog names most similar to `name` — the \"did you mean?\" set for an\n * unmatched user symbol. Ranked by edit distance first, then containment, then\n * length (the shared ranking of `upt map` and `upt explain`).\n *\n * @public\n */\nexport function suggestQuantities(\n name: string,\n catalogNames: Iterable<string>,\n k = 5,\n): string[] {\n return rankByName(name, catalogNames, true).slice(0, k);\n}\n\n/**\n * Catalog quantity names whose dimension equals `dim`, capped at `k` — the\n * dimension-based \"did you mean?\" set once an unknown symbol's dimension has\n * been inferred. With `near` (the unknown symbol) they are ranked by the same\n * edit-distance ranking as {@link suggestQuantities}, so `lenght` lists `length`\n * first (persona finding N2); without it they are sorted by name.\n *\n * @public\n */\nexport function suggestByDimension(\n dim: Dimension,\n catalogDims: ReadonlyMap<string, Dimension>,\n k = 5,\n near?: string,\n): string[] {\n const same = [...catalogDims.entries()].filter(([, d]) => equals(d, dim)).map(([name]) => name);\n return (near === undefined ? same.sort() : rankByName(near, same, false)).slice(0, k);\n}\n\n/**\n * Where the injected user junction landed, computed from a built `VizModel`.\n *\n * @public\n */\nexport interface EquationLanding {\n readonly isolated: boolean;\n /** Junctions in the user equation's connected component (including itself). */\n readonly clusterSize: number;\n /** The component holds a law/established junction (anchored to known physics). */\n readonly anchored: boolean;\n /** User-equation quantities that also appear in a neighbouring junction. */\n readonly sharedQuantities: readonly string[];\n /** Other junction ids in the user equation's component. */\n readonly connectedJunctionIds: readonly string[];\n}\n\n/**\n * Describe where `userJunctionId` sits in `model`: its component, the junctions it\n * connects to, and the quantities that link it to them.\n *\n * @public\n */\nexport function equationLanding(model: VizModel, userJunctionId: string): EquationLanding {\n const cluster = model.clusters.find((c) => c.junctionIds.includes(userJunctionId));\n const self = model.junctions.find((j) => j.id === userJunctionId);\n if (!cluster || !self) {\n return { isolated: true, clusterSize: 1, anchored: false, sharedQuantities: [], connectedJunctionIds: [] };\n }\n const connectedJunctionIds = cluster.junctionIds.filter((id) => id !== userJunctionId);\n const selfQuantities = new Set([...self.sources, self.target]);\n const neighbourQuantities = new Set<string>();\n for (const j of model.junctions) {\n if (j.id === userJunctionId || !cluster.junctionIds.includes(j.id)) continue;\n for (const qn of [...j.sources, j.target]) neighbourQuantities.add(qn);\n }\n const sharedQuantities = [...selfQuantities].filter((qn) => neighbourQuantities.has(qn)).sort();\n return {\n isolated: cluster.size === 1,\n clusterSize: cluster.size,\n anchored: cluster.anchored,\n sharedQuantities,\n connectedJunctionIds,\n };\n}\n\n/**\n * One or two lines summarising `connects to:` (persona findings W3 / I3).\n * Dumping ~100 edge ids next to a correct pendulum equation made shared\n * `length`/`temperature` look like a physics claim. Rank by overlap with the\n * user's shared quantities first, then textbook/law over bridges, then name.\n * When the list is long, state the structural caveat explicitly.\n *\n * @internal\n */\nexport function formatConnectedSummary(\n model: VizModel,\n landing: EquationLanding,\n maxShow = 5,\n): readonly string[] {\n const ids = landing.connectedJunctionIds;\n if (ids.length === 0) return [];\n const shared = new Set(landing.sharedQuantities);\n const byId = new Map(model.junctions.map((j) => [j.id, j]));\n const tier = (id: string): number =>\n id.startsWith('CE-') || id.startsWith('law-') ? 0 : id.startsWith('be-') ? 1 : 2;\n const overlap = (id: string): number => {\n const j = byId.get(id);\n if (!j) return 0;\n let n = 0;\n for (const qn of [...j.sources, j.target]) if (shared.has(qn)) n++;\n return n;\n };\n const ranked = [...ids].sort(\n (a, b) => overlap(b) - overlap(a) || tier(a) - tier(b) || a.localeCompare(b),\n );\n const shown = ranked.slice(0, maxShow);\n const more = ranked.length - shown.length;\n if (more <= 0) {\n return [` nearest equations: ${shown.join(', ')}`];\n }\n return [\n ` nearest equations: ${shown.join(', ')} (+${more} more)`,\n ' (shared-quantity connectivity, not a physics claim)',\n ];\n}\n\n/** A \"did you mean?\" suggestion for an unmatched symbol. */\nexport interface EquationHint {\n readonly name: string;\n readonly suggestions: readonly string[];\n /** True when the suggestions come from the symbol's INFERRED dimension. */\n readonly byDimension: boolean;\n /**\n * Registered constants that carry the symbol's inferred dimension (`sigma` → `sigma_sb`,\n * persona finding L5). Present only when a dimension was inferred and it is not dimensionless.\n */\n readonly constants?: readonly string[];\n}\n\n/** A one-letter user name bound to a catalog quantity (persona finding W6). */\nexport interface ShortBinding {\n readonly name: string;\n readonly quantity: string;\n readonly dim: Dimension;\n /**\n * Present and false when a one-letter catalog name was recognised and not\n * applied. Omitted when the name was bound.\n */\n readonly bound?: false;\n}\n\n/**\n * Full analysis of a user equation against a catalog name→dimension map: the\n * `user` junction (for the graph), the dimensional verdict (RHS dimension vs the\n * target's catalog dimension), and \"did you mean?\" hints (dimension-based when a\n * single unknown's dimension can be inferred, else name-similarity).\n *\n * Physics constants (`hbar`, `c`, `k_B`, …) are supplied to the parser with\n * their real dimensions (from `CONSTANTS`) so the dimensional check is correct.\n *\n * @public\n */\nexport interface EquationAnalysis {\n readonly junction: VizJunction;\n /** Set when the RHS is not dimensionally well-formed (then dims are null). */\n readonly parseError: string | null;\n readonly rhsDimension: Dimension | null;\n readonly targetDimension: Dimension | null;\n /** rhsDimension === targetDimension; null when unknowable or parse failed. */\n readonly consistent: boolean | null;\n readonly hints: readonly EquationHint[];\n /**\n * One-letter names that resolved to a catalog quantity. A one-letter name is the likeliest to\n * mean something else: the catalog's `a` is perihelion's semi-major axis, a length, and the\n * Unruh formula's `a` is an acceleration (persona finding W6).\n */\n readonly shortBindings: readonly ShortBinding[];\n /**\n * RHS names given a dimensionless placeholder because they did not resolve.\n * The reported RHS dimension treats them as dimensionless, so it is not a\n * check of the formula until they are bound.\n */\n readonly placeholders: readonly string[];\n /** Set when `--natural` / `--geometrized` reconciled the two dimensions. */\n readonly naturalNote?: string;\n}\n\n/**\n * Parse + dimensionally analyze a user `TARGET = EXPR` against `catalogDims`\n * (catalog quantity name → dimension). Throws {@link UserEquationError} on a\n * structurally malformed equation; reports a dimensional malformation via\n * `parseError`.\n *\n * @public\n */\nexport async function analyzeUserEquation(\n equation: string,\n catalogDims: ReadonlyMap<string, Dimension>,\n options?: AnalyzeUserEquationOptions,\n): Promise<EquationAnalysis> {\n const dimsIn = withFormulaNames(catalogDims);\n const catalogNames = new Set(dimsIn.keys());\n const bindShort = options?.bindShortNames === true;\n // W2: rewrite catalog kebabs before either parser sees `-` as subtraction.\n const eq = await parseUserEquation(equation, catalogNames);\n const literalShort = (n: string): string | null =>\n n.length === 1 && catalogNames.has(n) ? n : null;\n const resolveCatalog = (n: string): string | null => {\n if (!bindShort && literalShort(n) !== null) return null;\n return resolveQuantityName(n, catalogNames);\n };\n // Evaluate keys are aliases of this target's sources. `R` is reflectance\n // on radiation-pressure and is not a global name.\n const aliasMap = aliasesForTarget(CATALOG_GRAPH, resolveCatalog(eq.target) ?? '');\n const resolve = (n: string): string | null => {\n if (!bindShort && literalShort(n) !== null) return null;\n return resolveQuantityName(n, catalogNames, aliasMap);\n };\n\n // dims for parsePhysics: physics constants carry their REAL dimensions; matched\n // sources their catalog dimension; the (≤1) unmatched source a DIMENSIONLESS\n // placeholder so the RHS still parses.\n const dims: Record<string, Dimension> = {};\n for (const [name, c] of Object.entries(CONSTANTS)) dims[name] = c.dim;\n for (const s of eq.sources) {\n const r = resolve(s);\n dims[s] = r ? (dimsIn.get(r) as Dimension) : (formulaSymbolDimension(s) ?? DIMENSIONLESS);\n }\n // Use the rewritten equation's RHS (eq.text) so planck-length has already\n // become planck_length before dimensional parse.\n const rhsText = eq.text.slice(eq.text.indexOf('=') + 1);\n\n let rhsDimension: Dimension | null = null;\n let exprForInference: import('../dimensional/validator.js').ExprNode | null = null;\n let parseError: string | null = null;\n try {\n const parsed = await parsePhysics(rhsText, dims);\n rhsDimension = parsed.dimension;\n exprForInference = parsed.expr;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // The formula parser already read this right-hand side (parseUserEquation), so its variables are the tree's.\n const { variables } = (await getFormulaParser()).parse(rhsText);\n const hint = hyphenSubtractHint(rhsText, variables, catalogNames);\n parseError = hint ? `${msg}. ${hint}` : msg;\n }\n\n const resolvedTarget = resolve(eq.target);\n const targetDimension = resolvedTarget ? (dimsIn.get(resolvedTarget) as Dimension) : null;\n\n const placeholders = eq.sources.filter((s) => !resolve(s));\n const hints: EquationHint[] = [];\n if (exprForInference) {\n const unmatchedSources = placeholders.filter((s) => bindShort || literalShort(s) === null);\n const totalUnmatched = placeholders.length + (resolvedTarget ? 0 : 1);\n for (const s of unmatchedSources) {\n let byDim: string[] | null = null;\n let constants: string[] = [];\n if (targetDimension && totalUnmatched === 1) {\n const inferred = inferUnknownDimension(exprForInference, s, targetDimension);\n if (inferred) {\n byDim = suggestByDimension(inferred, dimsIn, 5, s);\n if (!equals(inferred, DIMENSIONLESS)) {\n constants = Object.entries(CONSTANTS)\n .filter(([, c]) => equals(c.dim, inferred))\n .map(([name]) => name)\n .sort();\n }\n }\n }\n const withConstants = constants.length > 0 ? { constants } : {};\n hints.push(\n byDim\n ? { name: s, suggestions: byDim, byDimension: true, ...withConstants }\n : { name: s, suggestions: suggestQuantities(s, catalogNames, 5), byDimension: false, ...withConstants },\n );\n }\n if (!resolvedTarget && (bindShort || literalShort(eq.target) === null)) {\n hints.push({ name: eq.target, suggestions: suggestQuantities(eq.target, catalogNames, 5), byDimension: false });\n }\n }\n\n const declined = eq.sources\n .filter((s) => !bindShort && literalShort(s) !== null)\n .map((s) => ({ name: s, quantity: s, dim: dimsIn.get(s) as Dimension, bound: false as const }));\n const declinedTarget =\n !bindShort && literalShort(eq.target) !== null\n ? [{ name: eq.target, quantity: eq.target, dim: dimsIn.get(eq.target) as Dimension, bound: false as const }]\n : [];\n const boundShort = eq.sources\n .filter((s) => s.length === 1 && resolve(s) !== null)\n .map((s) => ({ name: s, quantity: resolve(s)!, dim: dimsIn.get(resolve(s)!) as Dimension }));\n\n let consistent = rhsDimension && targetDimension ? equals(rhsDimension, targetDimension) : null;\n let natural: string | undefined;\n if (\n consistent === false &&\n rhsDimension &&\n targetDimension &&\n options?.units !== undefined &&\n (hints.length === 0)\n ) {\n const powers = naturalPowers(rhsDimension, targetDimension, options.units);\n const note = powers === null ? null : naturalNote(powers, options.units);\n if (note) {\n consistent = true;\n natural = note;\n }\n }\n\n return {\n junction: {\n id: 'user-equation',\n label: eq.text,\n status: 'user',\n sources: eq.sources.map((s) => resolve(s) ?? s),\n target: resolvedTarget ?? eq.target,\n },\n parseError,\n rhsDimension,\n targetDimension,\n consistent,\n hints,\n shortBindings: [...declined, ...boundShort, ...declinedTarget],\n placeholders,\n ...(natural === undefined ? {} : { naturalNote: natural }),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"user-equation.js","sourceRoot":"","sources":["../../src/composition/user-equation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAiB,MAAM,iCAAiC,CAAC;AAC5F,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,MAAM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I,CAAC;IAChG,IAAI,OAA2B,CAAC;IAChC,IACE,UAAU,KAAK,KAAK;QACpB,YAAY;QACZ,eAAe;QACf,OAAO,EAAE,KAAK,KAAK,SAAS;QAC5B,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,EACpB,CAAC;QACD,MAAM,MAAM,GAAG,aAAa,CAAC,YAAY,EAAE,eAAe,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QAC3E,MAAM,IAAI,GAAG,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QACzE,IAAI,IAAI,EAAE,CAAC;YACT,UAAU,GAAG,IAAI,CAAC;YAClB,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IAED,OAAO;QACL,QAAQ,EAAE;YACR,EAAE,EAAE,eAAe;YACnB,KAAK,EAAE,EAAE,CAAC,IAAI;YACd,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC/C,MAAM,EAAE,cAAc,IAAI,EAAE,CAAC,MAAM;SACpC;QACD,UAAU;QACV,YAAY;QACZ,eAAe;QACf,UAAU;QACV,KAAK;QACL,aAAa,EAAE,CAAC,GAAG,QAAQ,EAAE,GAAG,UAAU,EAAE,GAAG,cAAc,CAAC;QAC9D,YAAY;QACZ,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;KAC3D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * User-equation injection — turn a free-form `TARGET = EXPR` string into a graph\n * junction (a target quantity + its source quantities), resolve the user's\n * symbols onto the catalog vocabulary, suggest near-misses, and report where the\n * injected junction lands in a built {@link VizModel}.\n *\n * Free-form means no dimensions: source quantities are the RHS's free variables\n * — extracted by the MathTS expression parser via {@link getFormulaParser},\n * which already drops constants like `pi`/`tau`, numbers, and functions —\n * minus the physics {@link CONSTANTS}. Multi-word quantities may be typed with\n * underscores **or** the catalog's own hyphens (`planck-length`): before parse,\n * {@link rewriteCatalogHyphens} rewrites kebab catalog names to underscores so\n * `-` is not read as subtraction (persona finding W2). Resolution still tries\n * the literal form first, then the `_`↔`-` swap.\n *\n * Pure: no file I/O. The injected junction is rendered as an `extraJunction`\n * (status `'user'`) and is never written into the catalog.\n *\n * @module composition/user-equation\n */\n\nimport { getFormulaParser, parsePhysics } from '../numerical/formula-registry.js';\nimport { formulaSymbolDimension } from '../numerical/formula-dimension.js';\nimport { CONSTANT_SPELLINGS } from '../dimensional/dimension-spec.js';\nimport { CONSTANTS, isRegisteredConstant } from '../dimensional/symbolic-constants.js';\nimport { formulaNameDimensions } from '../dimensional/formula-names.js';\nimport { naturalNote, naturalPowers, type UnitMode } from '../dimensional/natural-units.js';\nimport { aliasesForTarget, editDistance } from './aliases.js';\nimport { resolveQuantityName } from '../dimensional/formula-names.js';\nimport { CATALOG_GRAPH } from './catalog-graph.js';\nimport type { VizModel, VizJunction } from './graph-viz.js';\nimport type { Dimension } from '../dimensional/types.js';\nimport { DIMENSIONLESS } from '../dimensional/types.js';\nimport { equals } from '../dimensional/algebra.js';\nimport { inferUnknownDimension } from '../dimensional/dimension-inference.js';\n\n/** Thrown when a user equation cannot be parsed into a target + sources. @public */\nexport class UserEquationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UserEquationError';\n }\n}\n\n/**\n * A parsed user equation: the target quantity and its source quantities, as\n * written (underscores preserved; constants/numbers/functions removed).\n *\n * @public\n */\nexport interface UserEquation {\n readonly target: string;\n readonly sources: readonly string[];\n /** The original `TARGET = EXPR` text, for the junction label. */\n readonly text: string;\n}\n\n/**\n * Parse `TARGET = EXPR` into `{ target, sources }`. The target is the text left\n * of the first `=`; the sources are the RHS's free variables minus the physics\n * constants.\n *\n * Uses the active formula parser (MathTS when installed, built-in otherwise) to\n * extract the RHS's free variables.\n *\n * @throws {UserEquationError} on a missing `=`, an empty target, an unparseable\n * RHS, or an RHS with no source quantities.\n * @public\n */\n/** Upper bound on user `--equation` text to keep hint computation bounded. */\nconst MAX_USER_EQUATION_LEN = 8192;\n\nimport { rewriteCatalogHyphens } from '../dimensional/hyphen-names.js';\n/** Rewrite a catalog hyphenated name to underscores before the expression parse. */\nexport { rewriteCatalogHyphens };\n\n/** A hyphen-joined run of names, `a-b` or `a-b-c`, not the exponent of `1e-5`. */\nconst HYPHEN_RUN = /(?<![A-Za-z0-9_.])[A-Za-z_][A-Za-z0-9_]*(?:-[A-Za-z0-9_]+)+/g;\n\n/**\n * When the parse read a hyphen-joined run (`thermal-mass`) as a subtraction of\n * its pieces, and the run read as one name is a catalog quantity, tell the user\n * `-` is arithmetic here and to use underscores. Persona finding I2.\n *\n * Decided from the parse, not from an error's text: `variables` are the free\n * variables the formula parser read from `rhs`. The parser has no hyphenated\n * identifier, so a run whose underscored name is not a variable and whose\n * pieces are was parsed as a subtraction.\n *\n * @internal\n */\nexport function hyphenSubtractHint(\n rhs: string,\n variables: readonly string[],\n catalogNames: ReadonlySet<string>,\n): string | null {\n const read = new Set(variables);\n const split = (rhs.match(HYPHEN_RUN) ?? []).filter(\n (run) =>\n !read.has(run.replace(/-/g, '_')) &&\n run.split('-').some((piece) => read.has(piece)) &&\n resolveQuantityName(run, catalogNames) !== null,\n );\n if (split.length === 0) return null;\n const example = split.sort((a, b) => b.length - a.length)[0]!;\n return (\n `'-' is arithmetic here; multi-word catalog names use underscores ` +\n `(${example} → ${example.replace(/-/g, '_')})`\n );\n}\n\n/**\n * Spellings that must not be a bare `e`. Constant aliases come from\n * {@link CONSTANT_SPELLINGS}. `1-eccentricity^2` is the perihelion factor\n * `one_minus_e_sq`.\n */\nfunction rewriteFormulaSpellings(text: string): string {\n let out = text;\n for (const { names } of CONSTANT_SPELLINGS) {\n const canonical = names[0]!;\n for (const alias of names.slice(1)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias)) continue;\n out = out.replace(new RegExp(`(?<![A-Za-z0-9_])${alias}(?![A-Za-z0-9_])`, 'g'), canonical);\n }\n }\n return out.replace(\n /(?<![A-Za-z0-9_])1\\s*-\\s*eccentricity\\s*(?:\\^|\\*\\*)\\s*2(?![A-Za-z0-9_])/g,\n 'one_minus_e_sq',\n );\n}\n\n/** Options for {@link analyzeUserEquation}. @internal */\nexport interface AnalyzeUserEquationOptions {\n /**\n * Bind a one-letter token that is itself a catalog quantity (`a`, `r`, …).\n * Default false: the match is reported and not applied. The alias `T` →\n * `temperature` is not a one-letter catalog name and still binds.\n */\n readonly bindShortNames?: boolean;\n /** Reconcile a dimension difference by powers of c, ħ, and (geometrized) G. */\n readonly units?: Exclude<UnitMode, 'si'>;\n}\n\nfunction withFormulaNames(catalog: ReadonlyMap<string, Dimension>): Map<string, Dimension> {\n const out = new Map(catalog);\n for (const [name, dim] of formulaNameDimensions()) {\n if (!out.has(name)) out.set(name, dim);\n }\n return out;\n}\n\n/** Parse a `TARGET = EXPR` equation into its target and source quantities. A malformed equation throws. */\nexport async function parseUserEquation(\n equation: string,\n catalogNames?: ReadonlySet<string> | Iterable<string>,\n): Promise<UserEquation> {\n if (equation.length > MAX_USER_EQUATION_LEN) {\n throw new UserEquationError(\n `equation exceeds ${MAX_USER_EQUATION_LEN} characters (${equation.length})`,\n );\n }\n // Materialized once: an iterator (`map.keys()`) would be spent by the first use.\n const names = catalogNames === undefined ? undefined : new Set(catalogNames);\n const spelled = rewriteFormulaSpellings(equation);\n const rewritten = names === undefined ? spelled : rewriteCatalogHyphens(spelled, names);\n const eqIdx = rewritten.indexOf('=');\n if (eqIdx < 0) {\n throw new UserEquationError(\n `equation must be \"TARGET = EXPR\" (no \"=\" found in '${equation}')`,\n );\n }\n const target = rewritten.slice(0, eqIdx).trim();\n if (!target) throw new UserEquationError('equation has an empty target (left of \"=\")');\n const rhs = rewritten.slice(eqIdx + 1).trim();\n if (!rhs) throw new UserEquationError('equation has an empty right-hand side');\n\n let variables: readonly string[];\n try {\n const parser = await getFormulaParser();\n ({ variables } = parser.parse(rhs));\n } catch (e) {\n // No parse tree, so no subtraction was read: the hyphen hint needs the parsed variables.\n throw new UserEquationError(`could not parse the right-hand side '${rhs}': ${(e as Error).message}`);\n }\n const sources = variables.filter((v) => !isRegisteredConstant(v));\n // An all-constant right-hand side (the Planck length) is an equation about a catalog quantity\n // only when its target is one; otherwise it names nothing to check (persona finding W5).\n const targetIsCatalog = names !== undefined && resolveQuantityName(target, names) !== null;\n if (sources.length === 0 && !targetIsCatalog) {\n throw new UserEquationError(\n `no source quantities in '${rhs}' (only constants/numbers?)`,\n );\n }\n return { target, sources, text: rewritten.trim() };\n}\n\n/** Normalize for comparison: lowercase, `_`/`-` unified. */\nconst normalizeForCompare = (s: string): string => s.toLowerCase().replace(/[_-]/g, '-');\n\n/** The shortest name that counts as contained in another for the \"did you mean?\" ranking. */\nconst MIN_CONTAINED = 3;\n\n/**\n * The one \"did you mean?\" ranking, shared by {@link suggestQuantities} and\n * {@link suggestByDimension}: edit distance first, then containment (one name\n * inside the other), then length, then name. Edit distance leads so a one-edit\n * typo beats a substring: `hawkng-temperature` → `hawking-temperature` before\n * `temperature` (persona finding N5). `gate` keeps a candidate only if one name\n * contains the other (the contained one at least three characters long) or the\n * distance is small against the query length; the\n * dimension-based caller passes `false`, because there the dimension is the evidence.\n */\nfunction rankByName(name: string, candidates: Iterable<string>, gate: boolean): string[] {\n const needle = normalizeForCompare(name);\n // Without the gate, short catalog names (`a`, `nu`) are spurious \"matches\" for any typo.\n const maxDist = Math.max(1, Math.ceil(needle.length / 2));\n // A contained name counts only from MIN_CONTAINED characters: every one-letter name occurs inside\n // a long input (`schrodinger-equation` holds a, g, q, r), and that is not nearness (audit I5).\n const within = (outer: string, inner: string): boolean => inner.length >= MIN_CONTAINED && outer.includes(inner);\n return [...candidates]\n .map((cand) => {\n const hay = normalizeForCompare(cand);\n const contains = within(hay, needle) || within(needle, hay) ? 0 : 1;\n return { cand, contains, dist: editDistance(needle, hay) };\n })\n .filter((s) => !gate || s.contains === 0 || s.dist <= maxDist)\n .sort(\n (x, y) =>\n x.dist - y.dist ||\n x.contains - y.contains ||\n x.cand.length - y.cand.length ||\n x.cand.localeCompare(y.cand),\n )\n .map((s) => s.cand);\n}\n\n/**\n * Up to `k` catalog names most similar to `name` — the \"did you mean?\" set for an\n * unmatched user symbol. Ranked by edit distance first, then containment, then\n * length (the shared ranking of `upt map` and `upt explain`).\n *\n * @public\n */\nexport function suggestQuantities(\n name: string,\n catalogNames: Iterable<string>,\n k = 5,\n): string[] {\n return rankByName(name, catalogNames, true).slice(0, k);\n}\n\n/**\n * Catalog quantity names whose dimension equals `dim`, capped at `k` — the\n * dimension-based \"did you mean?\" set once an unknown symbol's dimension has\n * been inferred. With `near` (the unknown symbol) they are ranked by the same\n * edit-distance ranking as {@link suggestQuantities}, so `lenght` lists `length`\n * first (persona finding N2); without it they are sorted by name.\n *\n * @public\n */\nexport function suggestByDimension(\n dim: Dimension,\n catalogDims: ReadonlyMap<string, Dimension>,\n k = 5,\n near?: string,\n): string[] {\n const same = [...catalogDims.entries()].filter(([, d]) => equals(d, dim)).map(([name]) => name);\n return (near === undefined ? same.sort() : rankByName(near, same, false)).slice(0, k);\n}\n\n/**\n * Where the injected user junction landed, computed from a built `VizModel`.\n *\n * @public\n */\nexport interface EquationLanding {\n readonly isolated: boolean;\n /** Junctions in the user equation's connected component (including itself). */\n readonly clusterSize: number;\n /** The component holds a law/established junction (anchored to known physics). */\n readonly anchored: boolean;\n /** User-equation quantities that also appear in a neighbouring junction. */\n readonly sharedQuantities: readonly string[];\n /** Other junction ids in the user equation's component. */\n readonly connectedJunctionIds: readonly string[];\n}\n\n/**\n * Describe where `userJunctionId` sits in `model`: its component, the junctions it\n * connects to, and the quantities that link it to them.\n *\n * @public\n */\nexport function equationLanding(model: VizModel, userJunctionId: string): EquationLanding {\n const cluster = model.clusters.find((c) => c.junctionIds.includes(userJunctionId));\n const self = model.junctions.find((j) => j.id === userJunctionId);\n if (!cluster || !self) {\n return { isolated: true, clusterSize: 1, anchored: false, sharedQuantities: [], connectedJunctionIds: [] };\n }\n const connectedJunctionIds = cluster.junctionIds.filter((id) => id !== userJunctionId);\n const selfQuantities = new Set([...self.sources, self.target]);\n const neighbourQuantities = new Set<string>();\n for (const j of model.junctions) {\n if (j.id === userJunctionId || !cluster.junctionIds.includes(j.id)) continue;\n for (const qn of [...j.sources, j.target]) neighbourQuantities.add(qn);\n }\n const sharedQuantities = [...selfQuantities].filter((qn) => neighbourQuantities.has(qn)).sort();\n return {\n isolated: cluster.size === 1,\n clusterSize: cluster.size,\n anchored: cluster.anchored,\n sharedQuantities,\n connectedJunctionIds,\n };\n}\n\n/**\n * One or two lines summarising `connects to:` (persona findings W3 / I3).\n * Dumping ~100 edge ids next to a correct pendulum equation made shared\n * `length`/`temperature` look like a physics claim. Rank by overlap with the\n * user's shared quantities first, then textbook/law over bridges, then name.\n * When the list is long, state the structural caveat explicitly.\n *\n * @internal\n */\nexport function formatConnectedSummary(\n model: VizModel,\n landing: EquationLanding,\n maxShow = 5,\n): readonly string[] {\n const ids = landing.connectedJunctionIds;\n if (ids.length === 0) return [];\n const shared = new Set(landing.sharedQuantities);\n const byId = new Map(model.junctions.map((j) => [j.id, j]));\n const tier = (id: string): number =>\n id.startsWith('CE-') || id.startsWith('law-') ? 0 : id.startsWith('be-') ? 1 : 2;\n const overlap = (id: string): number => {\n const j = byId.get(id);\n if (!j) return 0;\n let n = 0;\n for (const qn of [...j.sources, j.target]) if (shared.has(qn)) n++;\n return n;\n };\n const ranked = [...ids].sort(\n (a, b) => overlap(b) - overlap(a) || tier(a) - tier(b) || a.localeCompare(b),\n );\n const shown = ranked.slice(0, maxShow);\n const more = ranked.length - shown.length;\n if (more <= 0) {\n return [` nearest equations: ${shown.join(', ')}`];\n }\n return [\n ` nearest equations: ${shown.join(', ')} (+${more} more)`,\n ' (shared-quantity connectivity, not a physics claim)',\n ];\n}\n\n/** A \"did you mean?\" suggestion for an unmatched symbol. */\nexport interface EquationHint {\n readonly name: string;\n readonly suggestions: readonly string[];\n /** True when the suggestions come from the symbol's INFERRED dimension. */\n readonly byDimension: boolean;\n /**\n * Registered constants that carry the symbol's inferred dimension (`sigma` → `sigma_sb`,\n * persona finding L5). Present only when a dimension was inferred and it is not dimensionless.\n */\n readonly constants?: readonly string[];\n}\n\n/** A one-letter user name bound to a catalog quantity (persona finding W6). */\nexport interface ShortBinding {\n readonly name: string;\n readonly quantity: string;\n readonly dim: Dimension;\n /**\n * Present and false when a one-letter catalog name was recognised and not\n * applied. Omitted when the name was bound.\n */\n readonly bound?: false;\n}\n\n/**\n * Full analysis of a user equation against a catalog name→dimension map: the\n * `user` junction (for the graph), the dimensional verdict (RHS dimension vs the\n * target's catalog dimension), and \"did you mean?\" hints (dimension-based when a\n * single unknown's dimension can be inferred, else name-similarity).\n *\n * Physics constants (`hbar`, `c`, `k_B`, …) are supplied to the parser with\n * their real dimensions (from `CONSTANTS`) so the dimensional check is correct.\n *\n * @public\n */\nexport interface EquationAnalysis {\n readonly junction: VizJunction;\n /** Set when the RHS is not dimensionally well-formed (then dims are null). */\n readonly parseError: string | null;\n readonly rhsDimension: Dimension | null;\n readonly targetDimension: Dimension | null;\n /** rhsDimension === targetDimension; null when unknowable or parse failed. */\n readonly consistent: boolean | null;\n readonly hints: readonly EquationHint[];\n /**\n * One-letter names that resolved to a catalog quantity. A one-letter name is the likeliest to\n * mean something else: the catalog's `a` is perihelion's semi-major axis, a length, and the\n * Unruh formula's `a` is an acceleration (persona finding W6).\n */\n readonly shortBindings: readonly ShortBinding[];\n /**\n * RHS names given a dimensionless placeholder because they did not resolve.\n * The reported RHS dimension treats them as dimensionless, so it is not a\n * check of the formula until they are bound.\n */\n readonly placeholders: readonly string[];\n /** Set when `--natural` / `--geometrized` reconciled the two dimensions. */\n readonly naturalNote?: string;\n}\n\n/**\n * Parse + dimensionally analyze a user `TARGET = EXPR` against `catalogDims`\n * (catalog quantity name → dimension). Throws {@link UserEquationError} on a\n * structurally malformed equation; reports a dimensional malformation via\n * `parseError`.\n *\n * @public\n */\nexport async function analyzeUserEquation(\n equation: string,\n catalogDims: ReadonlyMap<string, Dimension>,\n options?: AnalyzeUserEquationOptions,\n): Promise<EquationAnalysis> {\n const dimsIn = withFormulaNames(catalogDims);\n const catalogNames = new Set(dimsIn.keys());\n const bindShort = options?.bindShortNames === true;\n // W2: rewrite catalog kebabs before either parser sees `-` as subtraction.\n const eq = await parseUserEquation(equation, catalogNames);\n const literalShort = (n: string): string | null =>\n n.length === 1 && catalogNames.has(n) ? n : null;\n const resolveCatalog = (n: string): string | null => {\n if (!bindShort && literalShort(n) !== null) return null;\n return resolveQuantityName(n, catalogNames);\n };\n // Evaluate keys are aliases of this target's sources. `R` is reflectance\n // on radiation-pressure and is not a global name.\n const aliasMap = aliasesForTarget(CATALOG_GRAPH, resolveCatalog(eq.target) ?? '');\n const resolve = (n: string): string | null => {\n if (!bindShort && literalShort(n) !== null) return null;\n return resolveQuantityName(n, catalogNames, aliasMap);\n };\n\n // dims for parsePhysics: physics constants carry their REAL dimensions; matched\n // sources their catalog dimension; the (≤1) unmatched source a DIMENSIONLESS\n // placeholder so the RHS still parses.\n const dims: Record<string, Dimension> = {};\n for (const [name, c] of Object.entries(CONSTANTS)) dims[name] = c.dim;\n for (const s of eq.sources) {\n const r = resolve(s);\n dims[s] = r ? (dimsIn.get(r) as Dimension) : (formulaSymbolDimension(s) ?? DIMENSIONLESS);\n }\n // Use the rewritten equation's RHS (eq.text) so planck-length has already\n // become planck_length before dimensional parse.\n const rhsText = eq.text.slice(eq.text.indexOf('=') + 1);\n\n let rhsDimension: Dimension | null = null;\n let exprForInference: import('../dimensional/validator.js').ExprNode | null = null;\n let parseError: string | null = null;\n try {\n const parsed = await parsePhysics(rhsText, dims);\n rhsDimension = parsed.dimension;\n exprForInference = parsed.expr;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // The formula parser already read this right-hand side (parseUserEquation), so its variables are the tree's.\n const { variables } = (await getFormulaParser()).parse(rhsText);\n const hint = hyphenSubtractHint(rhsText, variables, catalogNames);\n parseError = hint ? `${msg}. ${hint}` : msg;\n }\n\n const resolvedTarget = resolve(eq.target);\n const targetDimension = resolvedTarget ? (dimsIn.get(resolvedTarget) as Dimension) : null;\n\n const placeholders = eq.sources.filter((s) => !resolve(s));\n const hints: EquationHint[] = [];\n if (exprForInference) {\n const unmatchedSources = placeholders.filter((s) => bindShort || literalShort(s) === null);\n const totalUnmatched = placeholders.length + (resolvedTarget ? 0 : 1);\n for (const s of unmatchedSources) {\n let byDim: string[] | null = null;\n let constants: string[] = [];\n if (targetDimension && totalUnmatched === 1) {\n const inferred = inferUnknownDimension(exprForInference, s, targetDimension);\n if (inferred) {\n byDim = suggestByDimension(inferred, dimsIn, 5, s);\n if (!equals(inferred, DIMENSIONLESS)) {\n constants = Object.entries(CONSTANTS)\n .filter(([, c]) => equals(c.dim, inferred))\n .map(([name]) => name)\n .sort();\n }\n }\n }\n const withConstants = constants.length > 0 ? { constants } : {};\n hints.push(\n byDim\n ? { name: s, suggestions: byDim, byDimension: true, ...withConstants }\n : { name: s, suggestions: suggestQuantities(s, catalogNames, 5), byDimension: false, ...withConstants },\n );\n }\n if (!resolvedTarget && (bindShort || literalShort(eq.target) === null)) {\n hints.push({ name: eq.target, suggestions: suggestQuantities(eq.target, catalogNames, 5), byDimension: false });\n }\n }\n\n const declined = eq.sources\n .filter((s) => !bindShort && literalShort(s) !== null)\n .map((s) => ({ name: s, quantity: s, dim: dimsIn.get(s) as Dimension, bound: false as const }));\n const declinedTarget =\n !bindShort && literalShort(eq.target) !== null\n ? [{ name: eq.target, quantity: eq.target, dim: dimsIn.get(eq.target) as Dimension, bound: false as const }]\n : [];\n const boundShort = eq.sources\n .filter((s) => s.length === 1 && resolve(s) !== null)\n .map((s) => ({ name: s, quantity: resolve(s)!, dim: dimsIn.get(resolve(s)!) as Dimension }));\n\n let consistent = rhsDimension && targetDimension ? equals(rhsDimension, targetDimension) : null;\n let natural: string | undefined;\n if (\n consistent === false &&\n rhsDimension &&\n targetDimension &&\n options?.units !== undefined &&\n (hints.length === 0)\n ) {\n const powers = naturalPowers(rhsDimension, targetDimension, options.units);\n const note = powers === null ? null : naturalNote(powers, options.units);\n if (note) {\n consistent = true;\n natural = note;\n }\n }\n\n return {\n junction: {\n id: 'user-equation',\n label: eq.text,\n status: 'user',\n sources: eq.sources.map((s) => resolve(s) ?? s),\n target: resolvedTarget ?? eq.target,\n },\n parseError,\n rhsDimension,\n targetDimension,\n consistent,\n hints,\n shortBindings: [...declined, ...boundShort, ...declinedTarget],\n placeholders,\n ...(natural === undefined ? {} : { naturalNote: natural }),\n };\n}\n"]}
|
package/dist/core/constants.d.ts
CHANGED
|
@@ -10,15 +10,15 @@
|
|
|
10
10
|
* 2019 SI redefinition fixed their values exactly.
|
|
11
11
|
* • `HBAR_SI` is the exact quotient `H_SI / (2π)`, not the truncated CODATA display.
|
|
12
12
|
* • CODATA 2022 best estimates for measured constants (`G_SI`, `ALPHA`, Planck units).
|
|
13
|
-
* • Planck 2018 best estimate for `H0_SI`, in SI through
|
|
13
|
+
* • Planck 2018 best estimate for `H0_SI`, in SI through MathTS
|
|
14
|
+
* `Unit.exactScale('km/s/Mpc')` — the same exact-scale path the unit
|
|
15
|
+
* reader delegates to. This module cannot import `convertValue`
|
|
16
|
+
* (`dimensional/` is tier 1; `core/` is tier 0).
|
|
14
17
|
*
|
|
15
18
|
* This file is the one owner of every value. `PhysicalConstants` in
|
|
16
19
|
* `src/core/types.ts` and the constant registry in
|
|
17
20
|
* `src/dimensional/symbolic-constants.ts` are projections of it, and a test
|
|
18
|
-
* refuses a CODATA literal anywhere else under `src/`.
|
|
19
|
-
* table's: `H0_SI` reads the parsec from `data/units.json` rather than
|
|
20
|
-
* restating it, so the Hubble rate here and `67.4 km/s/Mpc` read through the
|
|
21
|
-
* unit table are one number.
|
|
21
|
+
* refuses a CODATA literal anywhere else under `src/`.
|
|
22
22
|
*
|
|
23
23
|
* @module core/constants
|
|
24
24
|
* @public
|
|
@@ -61,11 +61,12 @@ export declare const T_P_SI: number;
|
|
|
61
61
|
/**
|
|
62
62
|
* Hubble parameter H₀ (s⁻¹).
|
|
63
63
|
*
|
|
64
|
-
* Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
64
|
+
* Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc. The
|
|
65
|
+
* conversion to Hz is `Unit.exactScale('km/s/Mpc')` rounded once — the same
|
|
66
|
+
* exact-scale path `convertValue('67.4km/s/Mpc', 'Hz')` delegates to. Calling
|
|
67
|
+
* `convertValue` from this file is a layer-order violation (`core/` cannot
|
|
68
|
+
* import `dimensional/units.ts`).
|
|
69
|
+
* @public
|
|
69
70
|
*/
|
|
70
71
|
export declare const H0_SI: number;
|
|
71
72
|
/**
|
|
@@ -119,7 +120,7 @@ export declare const M_E_SI: number;
|
|
|
119
120
|
/**
|
|
120
121
|
* Proton mass (kg). CODATA 2022. Shared by the Eddington evaluator and
|
|
121
122
|
* `upt eval` (`m_p`, `m_proton`). Not the Planck mass `M_P_SI`.
|
|
122
|
-
* @
|
|
123
|
+
* @public
|
|
123
124
|
*/
|
|
124
125
|
export declare const M_PROTON_SI: number;
|
|
125
126
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/core/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAoBH,sEAAsE;AACtE,eAAO,MAAM,IAAI,YAAY,CAAC;AAC9B,wFAAwF;AACxF,eAAO,MAAM,QAAQ,QAAoB,CAAC;AAE1C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AAM,UAAU,QAAgB,CAAC;AAExC;;;;GAIG;AACH,eAAO,MAAM,SAAS,QAA6B,CAAC;AAEpD;;;;;GAKG;AACH,eAAO,MAAM,MAAM,QAAuB,CAAC"}
|
package/dist/core/constants.js
CHANGED
|
@@ -10,21 +10,21 @@
|
|
|
10
10
|
* 2019 SI redefinition fixed their values exactly.
|
|
11
11
|
* • `HBAR_SI` is the exact quotient `H_SI / (2π)`, not the truncated CODATA display.
|
|
12
12
|
* • CODATA 2022 best estimates for measured constants (`G_SI`, `ALPHA`, Planck units).
|
|
13
|
-
* • Planck 2018 best estimate for `H0_SI`, in SI through
|
|
13
|
+
* • Planck 2018 best estimate for `H0_SI`, in SI through MathTS
|
|
14
|
+
* `Unit.exactScale('km/s/Mpc')` — the same exact-scale path the unit
|
|
15
|
+
* reader delegates to. This module cannot import `convertValue`
|
|
16
|
+
* (`dimensional/` is tier 1; `core/` is tier 0).
|
|
14
17
|
*
|
|
15
18
|
* This file is the one owner of every value. `PhysicalConstants` in
|
|
16
19
|
* `src/core/types.ts` and the constant registry in
|
|
17
20
|
* `src/dimensional/symbolic-constants.ts` are projections of it, and a test
|
|
18
|
-
* refuses a CODATA literal anywhere else under `src/`.
|
|
19
|
-
* table's: `H0_SI` reads the parsec from `data/units.json` rather than
|
|
20
|
-
* restating it, so the Hubble rate here and `67.4 km/s/Mpc` read through the
|
|
21
|
-
* unit table are one number.
|
|
21
|
+
* refuses a CODATA literal anywhere else under `src/`.
|
|
22
22
|
*
|
|
23
23
|
* @module core/constants
|
|
24
24
|
* @public
|
|
25
25
|
*/
|
|
26
|
+
import { Unit, exactScaleToNumber } from '@danielsimonjr/mathts-core';
|
|
26
27
|
import * as mathtsConstants from '@danielsimonjr/mathts-functions';
|
|
27
|
-
import { checkedDataFile } from './data-file.js';
|
|
28
28
|
/**
|
|
29
29
|
* A measured constant's SI value, read from MathTS (CODATA 2022). MathTS is the
|
|
30
30
|
* one source of measured constants; UPT keeps no copy of their decimals. A
|
|
@@ -76,25 +76,28 @@ export const M_P_SI = codata('planckMass');
|
|
|
76
76
|
export const L_P_SI = codata('planckLength');
|
|
77
77
|
/** Planck time √(ℏG/c⁵) (s). CODATA 2022. */
|
|
78
78
|
export const T_P_SI = codata('planckTime');
|
|
79
|
-
/**
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
79
|
+
/**
|
|
80
|
+
* MathTS exact scale of a valueless unit text, rounded once. This is the
|
|
81
|
+
* same pair of calls the delegated unit reader uses (`Unit.exactScale` then
|
|
82
|
+
* `exactScaleToNumber`).
|
|
83
|
+
*/
|
|
84
|
+
function exactScaleNumber(text) {
|
|
85
|
+
const exact = Unit.exactScale(text);
|
|
86
|
+
if (exact === null)
|
|
87
|
+
throw new Error(`MathTS has no exact scale for '${text}'`);
|
|
88
|
+
return exactScaleToNumber(exact);
|
|
87
89
|
}
|
|
88
90
|
/**
|
|
89
91
|
* Hubble parameter H₀ (s⁻¹).
|
|
90
92
|
*
|
|
91
|
-
* Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
93
|
+
* Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc. The
|
|
94
|
+
* conversion to Hz is `Unit.exactScale('km/s/Mpc')` rounded once — the same
|
|
95
|
+
* exact-scale path `convertValue('67.4km/s/Mpc', 'Hz')` delegates to. Calling
|
|
96
|
+
* `convertValue` from this file is a layer-order violation (`core/` cannot
|
|
97
|
+
* import `dimensional/units.ts`).
|
|
98
|
+
* @public
|
|
96
99
|
*/
|
|
97
|
-
export const H0_SI = 67.
|
|
100
|
+
export const H0_SI = 67.4 * exactScaleNumber('km/s/Mpc');
|
|
98
101
|
/**
|
|
99
102
|
* Solar mass (kg). IAU 2015 nominal value rounded to the
|
|
100
103
|
* repo-conventional literal (used by the BE-42 docstring, the
|
|
@@ -146,7 +149,7 @@ export const M_E_SI = codata('electronMass');
|
|
|
146
149
|
/**
|
|
147
150
|
* Proton mass (kg). CODATA 2022. Shared by the Eddington evaluator and
|
|
148
151
|
* `upt eval` (`m_p`, `m_proton`). Not the Planck mass `M_P_SI`.
|
|
149
|
-
* @
|
|
152
|
+
* @public
|
|
150
153
|
*/
|
|
151
154
|
export const M_PROTON_SI = codata('protonMass');
|
|
152
155
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/core/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,eAAe,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEjD;;;;GAIG;AACH,SAAS,MAAM,CAAC,IAAY;IAC1B,MAAM,KAAK,GAAa,eAA2C,CAAC,IAAI,CAAC,CAAC;IAC1E,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAiC,CAAC,SAAS,KAAK,UAAU,EAAE,CAAC;QACtH,MAAM,CAAC,GAAI,KAAsC,CAAC,SAAS,EAAE,CAAC;QAC9D,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;YAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,kCAAkC,IAAI,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,MAAM,IAAI,GAAG,SAAS,CAAC;AAC9B,wFAAwF;AACxF,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAE1C,mEAAmE;AACnE,MAAM,CAAC,MAAM,IA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AAC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAEzC,kCAAkC;AAClC,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAEtE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,YAAY,CAAC;AAEtC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,SAAS,GAAG,IAAI,CAAC;AAE7C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,aAAa,CAAC;AAEpC;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,GAAG,IAAI,CAAC;AAExC;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC","sourcesContent":["/**\n * Canonical CODATA 2022 + SI-defined physical constants for UPT.\n *\n * The one owner of every fundamental physical constant used across the\n * numerical, dimensional, and bridge layers; `tests/core/constants-owner.test.ts`\n * fails on a second copy of any of these decimals elsewhere under `src/`.\n *\n * Values use:\n * • Exact-SI definitions (`C_SI`, `H_SI`, `K_B_SI`, `E_SI`) where the\n * 2019 SI redefinition fixed their values exactly.\n * • `HBAR_SI` is the exact quotient `H_SI / (2π)`, not the truncated CODATA display.\n * • CODATA 2022 best estimates for measured constants (`G_SI`, `ALPHA`, Planck units).\n * • Planck 2018 best estimate for `H0_SI`, in SI through the unit table's parsec.\n *\n * This file is the one owner of every value. `PhysicalConstants` in\n * `src/core/types.ts` and the constant registry in\n * `src/dimensional/symbolic-constants.ts` are projections of it, and a test\n * refuses a CODATA literal anywhere else under `src/`. A unit is the unit\n * table's: `H0_SI` reads the parsec from `data/units.json` rather than\n * restating it, so the Hubble rate here and `67.4 km/s/Mpc` read through the\n * unit table are one number.\n *\n * @module core/constants\n * @public\n */\n\nimport * as mathtsConstants from '@danielsimonjr/mathts-functions';\nimport { checkedDataFile } from './data-file.js';\n\n/**\n * A measured constant's SI value, read from MathTS (CODATA 2022). MathTS is the\n * one source of measured constants; UPT keeps no copy of their decimals. A\n * constant MathTS lacks is a MathTS issue, not a local value.\n */\nfunction codata(name: string): number {\n const value: unknown = (mathtsConstants as Record<string, unknown>)[name];\n if (typeof value === 'number') return value;\n if (typeof value === 'object' && value !== null && typeof (value as { toNumeric?: unknown }).toNumeric === 'function') {\n const n = (value as { toNumeric: () => unknown }).toNumeric();\n if (typeof n === 'number' && Number.isFinite(n)) return n;\n }\n throw new Error(`MathTS has no numeric constant ${name}`);\n}\n\n/** Speed of light in vacuum (m/s). Exact SI definition since 1983. */\nexport const C_SI = 299792458;\n/** Rydberg constant R∞ (infinite nuclear mass), CODATA 2022 (m⁻¹), read from MathTS. */\nexport const R_INF_SI = codata('rydberg');\n\n/** Newtonian gravitational constant (m³ kg⁻¹ s⁻²). CODATA 2022. */\nexport const G_SI = codata('gravitationConstant');\n\n/** Planck constant (J·s). Exact SI definition since 2019. */\nexport const H_SI = 6.62607015e-34;\n\n/**\n * Reduced Planck constant h/(2π) (J·s). Exact, from the 2019 SI definition of\n * h. The CODATA display `1.054571817e-34` is that quotient truncated; it is\n * smaller by a relative `6.127e-10`. The Planck units below are\n * MathTS's CODATA 2022 values, not recomputed here from {@link HBAR_SI}.\n */\nexport const HBAR_SI = H_SI / (2 * Math.PI);\n\n/** The CODATA display value of ħ: {@link HBAR_SI} truncated. Kept so the difference is computed, not typed. @internal */\nexport const HBAR_CODATA_DISPLAY = 1.054571817e-34;\n\n/** Boltzmann constant (J/K). Exact SI definition since 2019. */\nexport const K_B_SI = 1.380649e-23;\n\n/** Elementary charge (C). Exact SI definition since 2019. */\nexport const E_SI = 1.602176634e-19;\n\n/** Fine-structure constant α (dimensionless). CODATA 2022. */\nexport const ALPHA = codata('fineStructure');\n\n/** Vacuum permittivity ε₀ (F/m). CODATA 2022. @internal */\nexport const EPS0_SI = codata('electricConstant');\n\n/** Vacuum permeability μ₀ = 1/(ε₀ c²) (H/m), from ε₀ and the exact c. @internal */\nexport const MU0_SI = 1 / (EPS0_SI * C_SI * C_SI);\n\n/** Stefan–Boltzmann constant σ (W m⁻² K⁻⁴). CODATA 2022. @internal */\nexport const SIGMA_SB_SI = codata('stefanBoltzmann');\n\n/** Planck mass √(ℏc/G) (kg). CODATA 2022. */\nexport const M_P_SI = codata('planckMass');\n\n/** Planck length √(ℏG/c³) (m). CODATA 2022. */\nexport const L_P_SI = codata('planckLength');\n\n/** Planck time √(ℏG/c⁵) (s). CODATA 2022. */\nexport const T_P_SI = codata('planckTime');\n\n/** The `scale` of the `symbol` row in `data/units.json`, which must be a plain decimal (metres for a length). */\nfunction unitTableDecimal(symbol: string): number {\n const file = checkedDataFile('units.json') as { readonly units: readonly { readonly symbols: readonly string[]; readonly scale: string }[] };\n const scale = file.units.find((row) => row.symbols.includes(symbol))?.scale;\n const value = scale === undefined ? Number.NaN : Number(scale);\n if (!Number.isFinite(value)) throw new Error(`data/units.json: the '${symbol}' row must state a decimal scale (got ${scale ?? 'no row'})`);\n return value;\n}\n\n/**\n * Hubble parameter H₀ (s⁻¹).\n *\n * Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc, converted\n * with the parsec of the unit table (`data/units.json`, 648000/π au), so it is\n * the value `convertValue('67.4km/s/Mpc', 'Hz')` reads: one Hubble rate,\n * 2.1842852410855023e-18 s⁻¹. The unit table is the one place the parsec is\n * written; this module reads it rather than restating it.\n */\nexport const H0_SI = 67.4e3 / (1e6 * unitTableDecimal('pc'));\n\n/**\n * Solar mass (kg). IAU 2015 nominal value rounded to the\n * repo-conventional literal (used by the BE-42 docstring, the\n * bridge-gradient tests, and the v0.8.0 calibration edges).\n * @public\n */\nexport const M_SUN_SI = 1.989e30;\n\n/** Solar mass in kilograms. The same value as {@link M_SUN_SI}. */\nexport const M_SUN_KG = M_SUN_SI;\n\n/** von Klitzing constant R_K = h/e² (ohm). */\nexport const VON_KLITZING_SI = H_SI / (E_SI * E_SI);\n\n/** Josephson constant K_J = 2e/h (Hz/V). */\nexport const JOSEPHSON_CONSTANT_SI = (2 * E_SI) / H_SI;\n\n/** Lorenz number L = (π²/3) (k_B/e)² (W Ω K⁻²). */\nexport const LORENZ_NUMBER_SI = (Math.PI ** 2 / 3) * (K_B_SI / E_SI) ** 2;\n\n/** Euler–Mascheroni constant γ. The BCS gap is π k_B T_c / e^γ; the formula name is `euler_gamma`. */\nexport const EULER_GAMMA = 0.5772156649015329;\n\n/** Weak-coupling BCS gap ratio 2Δ(0)/(k_B T_c) = 2π e^{−γ}. */\nexport const BCS_GAP_RATIO = (2 * Math.PI) / Math.exp(EULER_GAMMA);\n\n/** Lane-Emden n=3 dimensionless radius used by the white-dwarf mass. */\nexport const LANE_EMDEN_OMEGA3 = 2.01824;\n\n/** Thomson cross section (m²). */\nexport const THOMSON_CROSS_SECTION_SI = codata('thomsonCrossSection');\n\n/**\n * Nominal solar gravitational parameter (GM)☉ (m³ s⁻²), IAU 2015 Resolution B3.\n *\n * The product GM☉ is known to about 10 significant digits, while G alone is\n * known to about 5, so a confrontation that needs GM☉ takes this value rather\n * than `G_SI × M_SUN_SI`: that product is 3.0e-4 too high, five times the VLBI\n * 1σ on the solar-limb deflection. A mass that some evaluator requires in kg\n * is `GM_SUN_SI / G_SI`, which reproduces G·M = GM☉ exactly.\n * @public\n */\nexport const GM_SUN_SI = 1.3271244e20;\n\n/**\n * The solar mass (kg) that reproduces {@link GM_SUN_SI} with {@link G_SI}:\n * the double `GM_SUN_SI / G_SI`. The unit `Msun_iau` and the registry name\n * `Msun_iau` both read this one value.\n * @internal\n */\nexport const M_SUN_IAU_SI = GM_SUN_SI / G_SI;\n\n/**\n * Electron mass (kg), CODATA 2022. Added for the v0.11 namespacing\n * gate's criterion-3 pin (λ_T of an electron at the Hawking\n * temperature — see the Adam vet A-5).\n * @public\n */\nexport const M_E_SI = codata('electronMass');\n\n/**\n * Proton mass (kg). CODATA 2022. Shared by the Eddington evaluator and\n * `upt eval` (`m_p`, `m_proton`). Not the Planck mass `M_P_SI`.\n * @internal\n */\nexport const M_PROTON_SI = codata('protonMass');\n\n/**\n * Avogadro constant (mol⁻¹). Exact in the 2019 SI.\n * @internal\n */\nexport const N_A_SI = 6.02214076e23;\n\n/**\n * Faraday constant (C·mol⁻¹), `N_A * e`.\n * @internal\n */\nexport const FARADAY_SI = N_A_SI * E_SI;\n\n/**\n * Wien displacement-law constant b = λ_max·T (m·K). CODATA 2022.\n *\n * @public\n */\nexport const B_WIEN_SI = codata('wienDisplacement');\n\n/**\n * Unified atomic mass unit (kg). CODATA 2022 atomic mass constant.\n * One value for the Chandrasekhar evaluator and the symbolic constant `m_u`.\n * Kept off the package barrel: callers use `m_u` in the symbolic registry.\n * @internal\n */\nexport const M_U_SI = codata('atomicMass');\n"]}
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/core/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,KAAK,eAAe,MAAM,iCAAiC,CAAC;AAEnE;;;;GAIG;AACH,SAAS,MAAM,CAAC,IAAY;IAC1B,MAAM,KAAK,GAAa,eAA2C,CAAC,IAAI,CAAC,CAAC;IAC1E,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAiC,CAAC,SAAS,KAAK,UAAU,EAAE,CAAC;QACtH,MAAM,CAAC,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C,GAAG,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAEnE,wEAAwE;AACxE,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAEzC,kCAAkC;AAClC,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAEtE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,YAAY,CAAC;AAEtC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,SAAS,GAAG,IAAI,CAAC;AAE7C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,aAAa,CAAC;AAEpC;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,GAAG,IAAI,CAAC;AAExC;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC","sourcesContent":["/**\n * Canonical CODATA 2022 + SI-defined physical constants for UPT.\n *\n * The one owner of every fundamental physical constant used across the\n * numerical, dimensional, and bridge layers; `tests/core/constants-owner.test.ts`\n * fails on a second copy of any of these decimals elsewhere under `src/`.\n *\n * Values use:\n * • Exact-SI definitions (`C_SI`, `H_SI`, `K_B_SI`, `E_SI`) where the\n * 2019 SI redefinition fixed their values exactly.\n * • `HBAR_SI` is the exact quotient `H_SI / (2π)`, not the truncated CODATA display.\n * • CODATA 2022 best estimates for measured constants (`G_SI`, `ALPHA`, Planck units).\n * • Planck 2018 best estimate for `H0_SI`, in SI through MathTS\n * `Unit.exactScale('km/s/Mpc')` — the same exact-scale path the unit\n * reader delegates to. This module cannot import `convertValue`\n * (`dimensional/` is tier 1; `core/` is tier 0).\n *\n * This file is the one owner of every value. `PhysicalConstants` in\n * `src/core/types.ts` and the constant registry in\n * `src/dimensional/symbolic-constants.ts` are projections of it, and a test\n * refuses a CODATA literal anywhere else under `src/`.\n *\n * @module core/constants\n * @public\n */\n\nimport { Unit, exactScaleToNumber } from '@danielsimonjr/mathts-core';\nimport * as mathtsConstants from '@danielsimonjr/mathts-functions';\n\n/**\n * A measured constant's SI value, read from MathTS (CODATA 2022). MathTS is the\n * one source of measured constants; UPT keeps no copy of their decimals. A\n * constant MathTS lacks is a MathTS issue, not a local value.\n */\nfunction codata(name: string): number {\n const value: unknown = (mathtsConstants as Record<string, unknown>)[name];\n if (typeof value === 'number') return value;\n if (typeof value === 'object' && value !== null && typeof (value as { toNumeric?: unknown }).toNumeric === 'function') {\n const n = (value as { toNumeric: () => unknown }).toNumeric();\n if (typeof n === 'number' && Number.isFinite(n)) return n;\n }\n throw new Error(`MathTS has no numeric constant ${name}`);\n}\n\n/** Speed of light in vacuum (m/s). Exact SI definition since 1983. */\nexport const C_SI = 299792458;\n/** Rydberg constant R∞ (infinite nuclear mass), CODATA 2022 (m⁻¹), read from MathTS. */\nexport const R_INF_SI = codata('rydberg');\n\n/** Newtonian gravitational constant (m³ kg⁻¹ s⁻²). CODATA 2022. */\nexport const G_SI = codata('gravitationConstant');\n\n/** Planck constant (J·s). Exact SI definition since 2019. */\nexport const H_SI = 6.62607015e-34;\n\n/**\n * Reduced Planck constant h/(2π) (J·s). Exact, from the 2019 SI definition of\n * h. The CODATA display `1.054571817e-34` is that quotient truncated; it is\n * smaller by a relative `6.127e-10`. The Planck units below are\n * MathTS's CODATA 2022 values, not recomputed here from {@link HBAR_SI}.\n */\nexport const HBAR_SI = H_SI / (2 * Math.PI);\n\n/** The CODATA display value of ħ: {@link HBAR_SI} truncated. Kept so the difference is computed, not typed. @internal */\nexport const HBAR_CODATA_DISPLAY = 1.054571817e-34;\n\n/** Boltzmann constant (J/K). Exact SI definition since 2019. */\nexport const K_B_SI = 1.380649e-23;\n\n/** Elementary charge (C). Exact SI definition since 2019. */\nexport const E_SI = 1.602176634e-19;\n\n/** Fine-structure constant α (dimensionless). CODATA 2022. */\nexport const ALPHA = codata('fineStructure');\n\n/** Vacuum permittivity ε₀ (F/m). CODATA 2022. @internal */\nexport const EPS0_SI = codata('electricConstant');\n\n/** Vacuum permeability μ₀ = 1/(ε₀ c²) (H/m), from ε₀ and the exact c. @internal */\nexport const MU0_SI = 1 / (EPS0_SI * C_SI * C_SI);\n\n/** Stefan–Boltzmann constant σ (W m⁻² K⁻⁴). CODATA 2022. @internal */\nexport const SIGMA_SB_SI = codata('stefanBoltzmann');\n\n/** Planck mass √(ℏc/G) (kg). CODATA 2022. */\nexport const M_P_SI = codata('planckMass');\n\n/** Planck length √(ℏG/c³) (m). CODATA 2022. */\nexport const L_P_SI = codata('planckLength');\n\n/** Planck time √(ℏG/c⁵) (s). CODATA 2022. */\nexport const T_P_SI = codata('planckTime');\n\n/**\n * MathTS exact scale of a valueless unit text, rounded once. This is the\n * same pair of calls the delegated unit reader uses (`Unit.exactScale` then\n * `exactScaleToNumber`).\n */\nfunction exactScaleNumber(text: string): number {\n const exact = Unit.exactScale(text);\n if (exact === null) throw new Error(`MathTS has no exact scale for '${text}'`);\n return exactScaleToNumber(exact);\n}\n\n/**\n * Hubble parameter H₀ (s⁻¹).\n *\n * Planck 2018 TT,TE,EE+lowE+lensing best estimate: 67.4 km/s/Mpc. The\n * conversion to Hz is `Unit.exactScale('km/s/Mpc')` rounded once — the same\n * exact-scale path `convertValue('67.4km/s/Mpc', 'Hz')` delegates to. Calling\n * `convertValue` from this file is a layer-order violation (`core/` cannot\n * import `dimensional/units.ts`).\n * @public\n */\nexport const H0_SI = 67.4 * exactScaleNumber('km/s/Mpc');\n\n/**\n * Solar mass (kg). IAU 2015 nominal value rounded to the\n * repo-conventional literal (used by the BE-42 docstring, the\n * bridge-gradient tests, and the v0.8.0 calibration edges).\n * @public\n */\nexport const M_SUN_SI = 1.989e30;\n\n/** Solar mass in kilograms. The same value as {@link M_SUN_SI}. */\nexport const M_SUN_KG = M_SUN_SI;\n\n/** von Klitzing constant R_K = h/e² (ohm). */\nexport const VON_KLITZING_SI = H_SI / (E_SI * E_SI);\n\n/** Josephson constant K_J = 2e/h (Hz/V). */\nexport const JOSEPHSON_CONSTANT_SI = (2 * E_SI) / H_SI;\n\n/** Lorenz number L = (π²/3) (k_B/e)² (W Ω K⁻²). */\nexport const LORENZ_NUMBER_SI = (Math.PI ** 2 / 3) * (K_B_SI / E_SI) ** 2;\n\n/** Euler–Mascheroni constant γ. The BCS gap is π k_B T_c / e^γ; the formula name is `euler_gamma`. */\nexport const EULER_GAMMA = 0.5772156649015329;\n\n/** Weak-coupling BCS gap ratio 2Δ(0)/(k_B T_c) = 2π e^{−γ}. */\nexport const BCS_GAP_RATIO = (2 * Math.PI) / Math.exp(EULER_GAMMA);\n\n/** Lane-Emden n=3 dimensionless radius used by the white-dwarf mass. */\nexport const LANE_EMDEN_OMEGA3 = 2.01824;\n\n/** Thomson cross section (m²). */\nexport const THOMSON_CROSS_SECTION_SI = codata('thomsonCrossSection');\n\n/**\n * Nominal solar gravitational parameter (GM)☉ (m³ s⁻²), IAU 2015 Resolution B3.\n *\n * The product GM☉ is known to about 10 significant digits, while G alone is\n * known to about 5, so a confrontation that needs GM☉ takes this value rather\n * than `G_SI × M_SUN_SI`: that product is 3.0e-4 too high, five times the VLBI\n * 1σ on the solar-limb deflection. A mass that some evaluator requires in kg\n * is `GM_SUN_SI / G_SI`, which reproduces G·M = GM☉ exactly.\n * @public\n */\nexport const GM_SUN_SI = 1.3271244e20;\n\n/**\n * The solar mass (kg) that reproduces {@link GM_SUN_SI} with {@link G_SI}:\n * the double `GM_SUN_SI / G_SI`. The unit `Msun_iau` and the registry name\n * `Msun_iau` both read this one value.\n * @internal\n */\nexport const M_SUN_IAU_SI = GM_SUN_SI / G_SI;\n\n/**\n * Electron mass (kg), CODATA 2022. Added for the v0.11 namespacing\n * gate's criterion-3 pin (λ_T of an electron at the Hawking\n * temperature — see the Adam vet A-5).\n * @public\n */\nexport const M_E_SI = codata('electronMass');\n\n/**\n * Proton mass (kg). CODATA 2022. Shared by the Eddington evaluator and\n * `upt eval` (`m_p`, `m_proton`). Not the Planck mass `M_P_SI`.\n * @public\n */\nexport const M_PROTON_SI = codata('protonMass');\n\n/**\n * Avogadro constant (mol⁻¹). Exact in the 2019 SI.\n * @internal\n */\nexport const N_A_SI = 6.02214076e23;\n\n/**\n * Faraday constant (C·mol⁻¹), `N_A * e`.\n * @internal\n */\nexport const FARADAY_SI = N_A_SI * E_SI;\n\n/**\n * Wien displacement-law constant b = λ_max·T (m·K). CODATA 2022.\n *\n * @public\n */\nexport const B_WIEN_SI = codata('wienDisplacement');\n\n/**\n * Unified atomic mass unit (kg). CODATA 2022 atomic mass constant.\n * One value for the Chandrasekhar evaluator and the symbolic constant `m_u`.\n * Kept off the package barrel: callers use `m_u` in the symbolic registry.\n * @internal\n */\nexport const M_U_SI = codata('atomicMass');\n"]}
|