@earthsciml/ast 0.1.1
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/LICENSE +661 -0
- package/README.md +162 -0
- package/dist/cjs/index.d.ts +4758 -0
- package/dist/cjs/index.js +20857 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/index.d.ts +4758 -0
- package/dist/esm/index.js +20683 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/index.d.ts +4758 -0
- package/package.json +97 -0
|
@@ -0,0 +1,4758 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file was automatically generated by json-schema-to-typescript.
|
|
3
|
+
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
|
|
4
|
+
* and run json-schema-to-typescript to regenerate this file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* EarthSciML Serialization Format (v1.0.0) — a language-agnostic JSON format for Earth system model components, their composition, and runtime configuration. v1.0.0 is a clean break with no deprecation path and no compatibility shims (docs/content/rfcs/unified-variable-model.md): the five declared variable types collapse to TWO. `unknown` is a quantity the solver solves for — its behavior is given by EQUATIONS and never by a field on the variable — and `parameter` is a quantity supplied to the solver, carrying a number or a `distribution` plus an optional `update` block saying when and from what it refreshes. Removed: `state` and `observed` (with the `expression` field — an observed variable becomes an unknown plus a bare-variable-LHS equation); `brownian` (with `noise_kind` / `correlation_group` — a noise source is a parameter with a `distribution` and `update.kind: "wiener"`, correlated noise being ONE vector-valued parameter whose distribution carries a `cov` matrix, which closes the gap the 0.x schema explicitly deferred); `discrete` (with `refresh` and the `RefreshTrigger` def — a refreshing input is a parameter with a `schedule` / `data` / `remesh` update); the `discrete_parameters` event lists and the event `functional_affect` (parameter mutation moves onto the parameter itself as a `condition` / `crossing` update carrying an `expression`, a `from` binding, or a `handler`; events now affect UNKNOWNS only); and the `data_loaders` COMPONENT kind together with `DataLoader.variables` (top-level `data_sources` is now a pure registry of ingest configuration — source, temporal, select, record_filter, extent, reader_options, determinism — that parameters draw from via `update.from`; a data source is no longer a coupling endpoint, a subsystem, or a scoped-name path root). Everything the solver needs is DERIVED rather than declared — which unknowns are ODE states, observed, or algebraic, and which parameters are Brownian, discrete, sampled, or constant — and every binding exposes the same classification functions to derive it (esm-spec §6.3.1). v0.9.0 changes no on-disk shape: it replaces the Option A (always-expanded) template round-trip with Option B (reference-preserving; esm-spec §9.6.4, docs/content/rfcs/out-of-line-expression-templates.md). Template references survive load and parse-then-emit; emit materializes each component's referenced templates into its `expression_templates` registry (authored entries first in authored order, materialized entries after in lexicographic UTF-8 name order; registry keys may be dotted post-rename names); eager references (target-bearing, esm-spec §9.6.4 rule 3) still expand at load, so no rewrite-target op survives inside a reference; `emit ∘ load` is a byte-wise fixed point; emitted documents carrying surviving references or materialized registries declare `esm: 0.9.0` or later. v0.8.0 is a clean break that removes all bespoke spatial-grid machinery in favor of expressing grid geometry directly with the unified Functional Aggregate Query (`aggregate`) IR (RFC semiring-faq-unified-ir), and retains no backward-compatibility shims. Removed: the top-level `grids`, `staggering_rules`, and `discretizations` blocks; the `Grid` / `GridExtent` / `GridMetricArray` / `GridMetricGenerator` / `GridConnectivity` / `GridCRS` defs; the entire stencil-template discretization rule grammar (`Discretization`, `DiscretizationVariant`, `MultiOutputStencilRule`, `DiscretizationRef`, `GridDiscretizationDescriptor`, and the `Rule` / `PatternNode` / `NeighborSelector` / `StencilEntry` / `RuleBinding` / `BoundaryPolicy` / `BoundaryPolicySpec` / `GhostWidth` / `GhostVarDecl` / `RuleRegion` / `RuleGuard` machinery, including `Equation.region`); all regridding configuration (`Model.regrid`, `RegridSpec`, `Interface.regridding`); the `Domain.spatial` / `SpatialDimension` / `CoordinateTransform` geometry block and the deprecated domain-level `boundary_conditions`; the `DataLoader.grid` / `DataLoader.mesh` descriptors and the `DataLoaderMesh` def; and the `grid_discretization_descriptor` document kind with its `grid_refs` test/example fields. Grid geometry — coordinates, extents, spacing, CRS parameters, connectivity, and metric arrays — is now ordinary data: loaded from a `data_loaders` primitive or declared as variables/parameters, with topology and metrics constructed declaratively as `aggregate` FAQs (the `intersect_polygon` kernel leaf remains for polygon clipping). Iteration domains are declared once in the document-scoped `index_sets` registry. Regridding is expressed as an ordinary coupling expression between two variables. Earlier additive features are retained: the `integral` AST op (PIDEs), array-or-single `plots.y`, sampled `function_tables` + `table_lookup`, in-file `expression_templates` + `apply_expression_template`, and the closed `enums` + `fn` / `enum` ops. The template-library RFC (docs/content/rfcs/template-library-imports.md; esm-spec §9.7) adds cross-file template sharing at esm 0.8.0: template-library files (top-level `expression_templates`), ordered `expression_template_imports` with §4.7 reference semantics, and load-time integer `metaparameters` admissible in `index_sets` sizes, `aggregate` dense ranges, and `makearray` regions — all resolved and folded at load, before validation and before the §9.6.3 rewrite fixpoint.
|
|
8
|
+
*/
|
|
9
|
+
type ESMFormat = ESMFormat1 & ESMFormat2;
|
|
10
|
+
type ESMFormat1 = {
|
|
11
|
+
[k: string]: unknown;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* A variable in a model — either an `unknown` the solver solves for, or a `parameter` supplied to it. There is no third kind. Everything the solver additionally needs to know is DERIVED: whether an unknown is an ODE state, an observed quantity, or an algebraic one follows from the EQUATIONS, and whether a parameter is Brownian, discrete, sampled, or constant follows from its `distribution` and `update` (esm-spec §6.3.1).
|
|
15
|
+
*/
|
|
16
|
+
type ModelVariable$1 = ModelVariable1 & {
|
|
17
|
+
/**
|
|
18
|
+
* unknown = a quantity the solver solves for; its behavior is stated by the model's `equations` and NOWHERE else. parameter = a quantity supplied to the solver, whose value is `default` or a `distribution`, optionally refreshed by an `update`. A checker MUST NOT infer an unknown's role from anything but the equations: an unknown under `D(·, t)` on some equation LHS is an ODE state, one with a bare-variable LHS is observed (eliminable), and one constrained only implicitly (`H*H*SO4 ~ Ksp`) is algebraic.
|
|
19
|
+
*/
|
|
20
|
+
type: "unknown" | "parameter";
|
|
21
|
+
units?: string;
|
|
22
|
+
/**
|
|
23
|
+
* For an unknown, its initial value at t=0. For a parameter, its constant value — mutually exclusive with `distribution`, which draws the value instead.
|
|
24
|
+
*/
|
|
25
|
+
default?: number;
|
|
26
|
+
/**
|
|
27
|
+
* Units of the default value, if different from the declared units field. When present, validators flag a unit_inconsistency error if these do not match the declared units (including dimensionally incompatible cases like K vs kg, and same-dimension mismatches like K vs degC). Default is the same as `units`.
|
|
28
|
+
*/
|
|
29
|
+
default_units?: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Arrayed-variable shape: ordered list of index-set names drawn from the document-scoped `index_sets` registry. Omitted or null indicates a scalar. REQUIRED for a parameter whose `update` is `schedule`, `data`, or `remesh` — such a parameter is a buffer whose extent is fixed at setup and refilled on a discrete cadence, so its extent must be known ahead of time (RFC semiring-faq-unified-ir §6.1); an empty array is a valid (scalar) shape.
|
|
33
|
+
*/
|
|
34
|
+
shape?: string[];
|
|
35
|
+
/**
|
|
36
|
+
* Optional free-form placement tag for a staggered quantity (e.g., "cell_center", "edge_normal", "x_face", "vertex"). Advisory metadata only; the index set a quantity lives on is given by `shape`. Omitted indicates no explicit placement.
|
|
37
|
+
*/
|
|
38
|
+
location?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Parameter-only: draw this parameter's value from a distribution instead of fixing it at `default`. Mutually exclusive with `default`. With no `update` it is drawn ONCE at setup (uncertainty quantification / ensembles); with `update.kind: "wiener"` it is redrawn every step with √dt scaling (a stochastic process, which makes the model an SDE).
|
|
41
|
+
*/
|
|
42
|
+
distribution?: {
|
|
43
|
+
[k: string]: unknown;
|
|
44
|
+
} | {
|
|
45
|
+
kind: "uniform";
|
|
46
|
+
low: number | [number, ...number[]];
|
|
47
|
+
high: number | [number, ...number[]];
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Parameter-only: when this parameter refreshes and what it refreshes from. Absent means it never changes after setup.
|
|
51
|
+
*/
|
|
52
|
+
update?: ParameterUpdate$1 | [
|
|
53
|
+
ParameterUpdate$1 & {
|
|
54
|
+
[k: string]: unknown;
|
|
55
|
+
},
|
|
56
|
+
ParameterUpdate$1 & {
|
|
57
|
+
[k: string]: unknown;
|
|
58
|
+
},
|
|
59
|
+
...(ParameterUpdate$1 & {
|
|
60
|
+
[k: string]: unknown;
|
|
61
|
+
})[]
|
|
62
|
+
];
|
|
63
|
+
};
|
|
64
|
+
type ModelVariable1 = {
|
|
65
|
+
[k: string]: unknown;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Declares WHEN a parameter refreshes and WHAT it refreshes from. A parameter with no `update` is a constant (or, with a `distribution`, is sampled once at setup). Six kinds. `wiener` is a driving stochastic process and takes no value form — it resamples the parameter's own `distribution`. The other five each take EXACTLY ONE value form: an `expression`, a `from` binding to a data source, or a registered `handler`. Together they subsume three constructs the 0.x format kept apart: the `brownian` variable type (now `wiener`), the `discrete` type with its `RefreshTrigger` (now `schedule` / `data` / `remesh`), and the `discrete_parameters` event lists with their `functional_affect` (now `condition` / `crossing`). This is also the sole seed of the DISCRETE cadence class in the dependency-partition pass (RFC semiring-faq-unified-ir §6.1): without it such inputs would be mis-seeded as CONST (never refresh) or CONTINUOUS (recompute every step).
|
|
69
|
+
*/
|
|
70
|
+
type ParameterUpdate$1 = {
|
|
71
|
+
kind: "wiener";
|
|
72
|
+
} | {
|
|
73
|
+
[k: string]: unknown;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
77
|
+
*/
|
|
78
|
+
type Expression = number | string | ExpressionNode;
|
|
79
|
+
/**
|
|
80
|
+
* An operation in the expression AST.
|
|
81
|
+
*/
|
|
82
|
+
type ExpressionNode = ExpressionNode1 & {
|
|
83
|
+
/**
|
|
84
|
+
* Operator name. TWO TIERS (esm-spec §4.2). (1) The CLOSED evaluable-core set — every binding's evaluator implements each one directly: `+ - * / ^`, the comparisons/booleans (`> < >= <= == != and or not`), the elementary functions (`exp log log10 sqrt abs sign sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh min max floor ceil`), `ifelse`, the calculus form-ops `D` and `ic` (structural / equation-LHS use only), `Pre`, `true`, and the array/query ops (`aggregate makearray index broadcast reshape transpose concat skolem rank argmin argmax intersect_polygon polygon_intersection_area fn enum const table_lookup apply_expression_template`). (2) The OPEN rewrite-target tier — ANY other identifier: a spatial `D` on a right-hand side, the optional sugar ops `grad`/`div`/`laplacian`/`integral`, or a user op such as `godunov_hamiltonian`. A rewrite-target op carries NO evaluator implementation and MUST be eliminated by a rewrite rule (§9.6) before evaluation. Loading is permissive — a file MAY load with rewrite-target ops still present (e.g. a coupling/scoping example that never simulates) — but one reaching evaluation/compilation without being lowered is rejected with `unlowered_operator`. The `pattern` only rejects malformed strings — it does NOT enforce membership in the core set, so the open tier stays expressible. The evaluable-core set is the ONLY set the format privileges.
|
|
85
|
+
*/
|
|
86
|
+
op: string;
|
|
87
|
+
/**
|
|
88
|
+
* Stable node identity (RFC semiring-faq-unified-ir §6.1): an optional, author-assigned identifier that makes this expression node addressable as a vertex in the inter-node dependency DAG the partition pass walks. Its primary use is to be the referent of a derived index set: an `index_sets` entry of kind "derived" names, via `from_faq`, the index-set-producing `aggregate` node that materializes it — and it names it by this id. When present it MUST be unique among the expression nodes of its model; the build-time reference-resolution pass errors on a duplicate id and on a `from_faq` that names no node. Absent ⇒ the node is addressed only by its structural path and cannot be the target of a `from_faq`. Purely additive: a file using no `id` validates and resolves exactly as before.
|
|
89
|
+
*/
|
|
90
|
+
id?: string;
|
|
91
|
+
/**
|
|
92
|
+
* Optional author assertion on this node's cadence class, checked by the dependency-partition pass (RFC semiring-faq-unified-ir §6.1; CONFORMANCE_SPEC.md §5.7). A diagnostic/test hook ONLY — it changes no semantics. The pass derives every node's class from the data-dependency DAG (`class(node) = max` over inputs; `const ⊏ discrete ⊏ continuous`); when `expect_cadence` is present the pass errors if the DERIVED class disagrees with it. "const" = never changes, folded into the artifact (parameter / literal); "discrete" = changes only at discrete events, recomputed by the per-event handler (a `discrete` variable, e.g. loaded met / reloadable mesh); "continuous" = changes every step, evaluated in the hot per-step tree (integrated state `u`, or an explicit continuous-`t` forcing). Absent ⇒ no assertion. Purely additive: a file using no `expect_cadence` validates and partitions exactly as before.
|
|
93
|
+
*/
|
|
94
|
+
expect_cadence?: "const" | "discrete" | "continuous";
|
|
95
|
+
/**
|
|
96
|
+
* Operand list. For most ops these are sub-expressions. Array ops use args for the input array operands (aggregate, broadcast, index, reshape, transpose, concat). makearray has no natural args and uses an empty array. For `D` (esm-spec §4.2 "Arity of `D`"): `args[0]` is always the differentiated operand; a STRUCTURAL `D` (`wrt` "t", or `wrt` absent) is strictly unary, while a REWRITE-TARGET `D` (spatial `wrt`) MAY carry an unbounded number of TRAILING AUXILIARY OPERANDS after `args[0]` — the per-face boundary/halo data a discretization rule binds and consumes (§9.6.8). Trailing operands carry NO evaluator semantics and no per-position meaning assigned by this format; they are matched positionally by the consuming rule.
|
|
97
|
+
*
|
|
98
|
+
* @minItems 0
|
|
99
|
+
*/
|
|
100
|
+
args: Expression[];
|
|
101
|
+
/**
|
|
102
|
+
* Differentiation variable for the `D` op: the time variable `t` (structural, equation-LHS use) OR a spatial axis (e.g. "x", "lon"). Absent means `t`. A `D` with a spatial `wrt`, or any `D` appearing in a right-hand-side expression position, is a rewrite-target (esm-spec §9.6.8): it MUST be lowered to a stencil by a discretization rule before evaluation, else `unlowered_operator`. `wrt` also fixes this node's ARITY (esm-spec §4.2 "Arity of `D`"): `wrt` "t" (or absent) is STRICTLY UNARY, enforced by the `D` clause of this object's `allOf`; a spatial `wrt` MAY carry unbounded trailing auxiliary operands in `args[1..]`.
|
|
103
|
+
*/
|
|
104
|
+
wrt?: string;
|
|
105
|
+
/**
|
|
106
|
+
* Scalar field naming a spatial axis (e.g. "x", "y", "z"). Carried by rewrite-target differential-operator sugar (`grad`/`div`/`laplacian`) and admissible on any open-tier rewrite-target op; it is an ordinary axis-naming scalar field with NO privileged status. A `dim` value names a spatial coordinate STRUCTURALLY, independent of the enclosing `op` (esm-spec §4.9.1), and confers no dimensional rule on its op (the op's dimension is UNDETERMINABLE until lowered, §4.8.3/§4.8.4). PREFER `D` with `wrt` set to the axis. Custom rewrite-target ops MAY instead carry scheme parameters in `attrs`.
|
|
107
|
+
*/
|
|
108
|
+
dim?: string;
|
|
109
|
+
/**
|
|
110
|
+
* Optional named scalar attributes for an OPEN rewrite-target op (esm-spec §4.2). Mirrors the role of the fixed `dim`/`side`/`wrt`/`var` slots that core ops use, but is open: a custom op (e.g. `godunov_hamiltonian`) carries its scheme parameters here. In a rewrite rule's `match`, an `attrs.<key>` whose value is a bare param name binds that param to the matched literal (esm-spec §9.6.1). Evaluable-core ops MUST NOT use `attrs`.
|
|
111
|
+
*/
|
|
112
|
+
attrs?: {
|
|
113
|
+
[k: string]: unknown;
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* Integration variable for the integral operator: the name of the spatial dimension being integrated over (e.g., "x").
|
|
117
|
+
*/
|
|
118
|
+
var?: string;
|
|
119
|
+
/**
|
|
120
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
121
|
+
*/
|
|
122
|
+
lower?: Expression;
|
|
123
|
+
/**
|
|
124
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
125
|
+
*/
|
|
126
|
+
upper?: Expression;
|
|
127
|
+
/**
|
|
128
|
+
* For aggregate: the result's index signature. Each entry is either a string (a symbolic index variable like "i", "j") or the integer 1 (a literal singleton dimension for reshape/broadcast). Mirrors SymbolicUtils.ArrayOp.output_idx.
|
|
129
|
+
*/
|
|
130
|
+
output_idx?: (string | 1)[];
|
|
131
|
+
/**
|
|
132
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
133
|
+
*/
|
|
134
|
+
expr?: Expression;
|
|
135
|
+
/**
|
|
136
|
+
* For aggregate: the reduction operator applied to any index symbol that appears in expr but not in output_idx. Default is "+". This names only the ⊕ operator; it is a shorthand retained for files that omit "semiring" (⊕ = reduce, ⊗ = "*"). When "semiring" is present it supersedes "reduce".
|
|
137
|
+
*/
|
|
138
|
+
reduce?: "+" | "*" | "max" | "min";
|
|
139
|
+
/**
|
|
140
|
+
* For aggregate: the named semiring (⊕, ⊗) that parameterizes the reduction (RFC semiring-faq-unified-ir §5.1). A closed, exhaustive registry — adding a semiring is a spec change, not a per-file extension. Absent ⇒ "sum_product", which reproduces today's einsum / sum-of-products semantics exactly (the strict-superset promise). The ⊕ operator, the ⊗ operator, and BOTH identity elements (the value of an empty ⊕-reduction and an empty ⊗-product) are fixed by the registry table and MUST NOT be written into the file: sum_product (+,0;×,1), max_product (max,-∞;×,1), min_sum (min,+∞;+,0), max_sum (max,-∞;+,0), bool_and_or (∨,false;∧,true).
|
|
141
|
+
*/
|
|
142
|
+
semiring?: "sum_product" | "max_product" | "min_sum" | "max_sum" | "bool_and_or";
|
|
143
|
+
/**
|
|
144
|
+
* For aggregate: optional map from index symbol name to the range it iterates over. Each value is EITHER (a) a dense integer tuple — a 2-element array [start, stop] (unit step) or a 3-element array [start, step, stop], as today, mirroring SymbolicUtils.ArrayOp.ranges — entries MAY be metaparameter expressions folded to concrete integers at load (esm-spec §9.7.6); OR (b) a reference to a declared index set (RFC semiring-faq-unified-ir §5.2): an object { "from": <index_sets key> }, optionally with "of": [parent index names] for a ragged / dependent inner set (e.g. the edges of cell "i"). Indices not present are inferred from the domain / operand shapes at runtime.
|
|
145
|
+
*/
|
|
146
|
+
ranges?: {
|
|
147
|
+
[k: string]: [MetaparameterExpression, MetaparameterExpression] | [MetaparameterExpression, MetaparameterExpression, MetaparameterExpression] | {
|
|
148
|
+
/**
|
|
149
|
+
* Name of a declared index set: a key in the document-scoped top-level index_sets registry. The resolver MUST error on an undeclared name; no implicit interval is inferred, so a typo cannot silently become an empty set.
|
|
150
|
+
*/
|
|
151
|
+
from: string;
|
|
152
|
+
/**
|
|
153
|
+
* Parent index name(s) for a ragged / dependent inner set: the members enumerated depend on these outer indices (e.g. { "from": "edges_of_cell", "of": ["i"] } iterates the edges of cell i).
|
|
154
|
+
*/
|
|
155
|
+
of?: string[];
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
/**
|
|
159
|
+
* For aggregate: optional value-equality combination of factors by key columns — an inner equi-join (RFC semiring-faq-unified-ir §5.3), subsuming ESI join and making connectivity gathers first-class. Each entry is a join clause whose "on" lists one or more key-column pairs [left, right]; a ⊗-product term is contributed only for index combinations whose key columns are equal on EVERY listed pair, and an unmatched row contributes the additive identity (the empty ⊕-reduction value), adding nothing under any semiring. Inner-only — there is no outer/left variant; many-to-many is defined, not an error (m·n product terms, each a ⊗-term into the enclosing ⊕-reduction); key columns must be exact-equality types (integer IDs or categorical members compared by Unicode code point) — floating-point join keys are forbidden. Absent ⇒ factors combine only by shared index name (positional einsum), exactly as today.
|
|
160
|
+
*/
|
|
161
|
+
join?: ({
|
|
162
|
+
[k: string]: unknown;
|
|
163
|
+
} | {
|
|
164
|
+
[k: string]: unknown;
|
|
165
|
+
})[];
|
|
166
|
+
/**
|
|
167
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
168
|
+
*/
|
|
169
|
+
filter?: Expression;
|
|
170
|
+
/**
|
|
171
|
+
* For aggregate: when true, the node has set semantics (dedup) and is index-set-producing — it materializes a data-derived index set rather than an array (RFC semiring-faq-unified-ir §5.5). Only meaningful under the `bool_and_or` semiring (the relational specialization, §5.1); combined with `key`, it enumerates the unique Skolem terms (e.g. the unique edges discovered from a face→vertex relation) and exposes the result as a `kind:"derived"` index set (§5.2) that a downstream geometric aggregate consumes. The output order is fixed by the normative determinism rules (§5.7): sort by the total tuple order, then drop adjacent duplicates — never first-seen / insertion order. Absent ⇒ false (ordinary array-producing reduction), exactly as today.
|
|
172
|
+
*/
|
|
173
|
+
distinct?: boolean;
|
|
174
|
+
/**
|
|
175
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
176
|
+
*/
|
|
177
|
+
key?: Expression;
|
|
178
|
+
/**
|
|
179
|
+
* Optional documentary relation tag for a skolem node (e.g. "edge", "bin", "pair"). Does NOT affect the emitted key; the key components are the node's args.
|
|
180
|
+
*/
|
|
181
|
+
label?: string;
|
|
182
|
+
/**
|
|
183
|
+
* For the arg-witness reducers `argmin` / `argmax` (RFC semiring-faq-unified-ir §5.7 rule 6): names the contracted `ranges` index symbol whose value (a 1-based generator id) is RETURNED at the optimum. The op reduces its `expr` body (a declarative scalar FAQ, e.g. a squared-distance metric) over the inner `ranges` candidate domain — optionally pruned by a bin-Skolem `join` / `filter` — and emits the witnessing INDEX rather than the reduced value: `assign[i] = argmin_g dist(point_i, gen_g)`, the nearest-generator assignment. NET-NEW because the closed semiring registry (§5.1) returns values and the value-invention primitives distinct/skolem/rank (§5.5) return sets — neither returns the arg. Materialized at build time as an integer per-element buffer (CONST/DISCRETE cadence, like the §A.8 bin-Skolem `:map` buffers; a CONTINUOUS arg-witness is rejected by §5.7 guard 2). The NORMATIVE tie-break is the SMALLEST arg (smallest generator id): equal `expr` values resolve to the lower index, making the buffer byte-identical across bindings (§5.7). REQUIRED on `argmin` / `argmax`; ignored on any other op. An empty candidate set is an error (no index witnesses the optimum).
|
|
184
|
+
*/
|
|
185
|
+
arg?: string;
|
|
186
|
+
/**
|
|
187
|
+
* For the `intersect_polygon` and `polygon_intersection_area` geometry-kernel leaf ops (RFC semiring-faq-unified-ir §8.1 / Appendix B; CONFORMANCE_SPEC.md §5.8.4): the geometry interpretation under which the two operand polygons are clipped, and the part of the op's contract that makes its tolerance-based conformance comparable. "planar": Cartesian/flat clipping (Sutherland–Hodgman / Foster–Hormann) — straight edges in the coordinate plane; wrong at the poles and across the antimeridian, valid only for a small projected patch. "spherical": great-circle edges on the unit sphere (the ConservativeRegridding.jl / GeometryOps.jl / S2 default for lon-lat earth meshes) — the correct model for global regridding. "geodesic": ellipsoidal-geodesic edges. Great-circle-edge assumption: under "spherical"/"geodesic" every edge — including a lon-lat edge running along a parallel, which is a small circle, not a great circle — is modelled as a great-circle geodesic, so a coarse polar cell carries a real area error (~4% for a 30° cell next to the pole, growing with the square of the cell's longitude width; RFC §B.4 / §5.8.4). The per-binding kernels offer an opt-in densification of parallel edges into short great-circle segments (`densify_parallel_edges`) to reduce it; it is off by default, so default clip behaviour is unchanged. REQUIRED on every `intersect_polygon` / `polygon_intersection_area` node (the op carries no default — the manifold must be declared, never inferred). Two bindings' clip results may be compared ONLY under the same declared manifold; the flag itself is matched EXACTLY across bindings (it is a discrete label, not a tolerance-based quantity). Meaningful only for `intersect_polygon` and `polygon_intersection_area`; ignored on any other op. TEMPLATE PARAMETERIZATION (esm-spec §9.6.1 / §9.6.3 constraint 5): inside an `expression_templates` entry's `body`, this field MAY carry a declared template-parameter name — a bare string outside the closed set — as a scalar-field substitution site, so the schema admits any string here. The closed set {planar, spherical, geodesic} is enforced on the EXPANDED form per §9.6.4: bindings MUST reject, at post-expansion validation, any `intersect_polygon` / `polygon_intersection_area` node whose `manifold` is not a member of the closed set.
|
|
188
|
+
*/
|
|
189
|
+
manifold?: (("planar" | "spherical" | "geodesic") | string) & string;
|
|
190
|
+
/**
|
|
191
|
+
* For makearray: list of sub-region boxes of the output array. Each region is an array of [start, stop] pairs, one per output dimension. The nth region is filled with the nth entry of values. Overlapping regions are permitted; later regions overwrite earlier ones. Bound pairs MAY be metaparameter expressions folded to concrete integers at load (esm-spec §9.7.6). Mirrors SymbolicUtils.ArrayMaker.regions.
|
|
192
|
+
*/
|
|
193
|
+
regions?: [
|
|
194
|
+
[
|
|
195
|
+
MetaparameterExpression,
|
|
196
|
+
MetaparameterExpression
|
|
197
|
+
],
|
|
198
|
+
...[MetaparameterExpression, MetaparameterExpression][]
|
|
199
|
+
][];
|
|
200
|
+
/**
|
|
201
|
+
* For makearray: list of expressions, one per entry in regions. Each value may be a scalar expression (broadcast across the region) or an array-valued expression whose shape matches the region (excluding singleton dimensions). Mirrors SymbolicUtils.ArrayMaker.values.
|
|
202
|
+
*/
|
|
203
|
+
values?: Expression[];
|
|
204
|
+
/**
|
|
205
|
+
* For reshape: the target shape. Each entry is either an integer (a concrete length) or a string (a symbolic dimension reference).
|
|
206
|
+
*
|
|
207
|
+
* @minItems 1
|
|
208
|
+
*/
|
|
209
|
+
shape?: [number | string, ...(number | string)[]];
|
|
210
|
+
/**
|
|
211
|
+
* For transpose: optional axis permutation. A list of 0-based axis indices giving the new order. If omitted, the matrix-transpose convention is used (reverse axes).
|
|
212
|
+
*/
|
|
213
|
+
perm?: number[];
|
|
214
|
+
/**
|
|
215
|
+
* For concat: the 0-based axis along which to concatenate the operand arrays. All operands must have identical shape on every other axis.
|
|
216
|
+
*/
|
|
217
|
+
axis?: number;
|
|
218
|
+
/**
|
|
219
|
+
* For broadcast: the name of the scalar operator to apply element-wise to the operands in args (esm-spec.md §4.3.4). `{op: 'broadcast', fn: F, args: A}` means exactly what `{op: F, args: A}` means, applied element-wise — so a ONE-operand broadcast applies `fn` UNARILY (`broadcast(fn:'-',[x])` is `-x`), and MUST NOT be treated as the identity on its operand. The value MUST be an ExpressionNode op name drawn from the closed SCALAR subset — the pointwise ops: arithmetic (`+ - * / ^ neg`), elementary functions (`exp log ln log10 sqrt abs sign floor ceil sin cos tan asin acos atan sinh cosh tanh asinh acosh atanh atan2 min max`), comparisons (`== != < <= > >=`), logical connectives (`and or not`), and `ifelse`. It may NOT name a non-pointwise op (`aggregate makearray index broadcast reshape transpose concat fn D ic Pre const true enum table_lookup apply_expression_template skolem rank distinct argmin argmax intersect_polygon polygon_intersection_area`), and `args.length` MUST satisfy the named operator's §4.2 arity. Bindings MUST reject a violation — including an absent `fn`, for which there is no default — with diagnostic 'invalid_broadcast_fn'; loading MUST fail. This is a VALUE constraint the schema deliberately does not enum-enforce, for the same reason `op` and the closed-registry `name` are not enum-enforced: the admissible set is fixed by the file's declared `esm` version, and the check must also cover arity, which a schema `enum` cannot express.
|
|
220
|
+
*/
|
|
221
|
+
fn?: string;
|
|
222
|
+
/**
|
|
223
|
+
* For fn: the dotted module path of a function in the closed function registry (esm-spec.md §9.2). The set of valid names is fixed by the spec version; bindings MUST reject unknown names with diagnostic 'unknown_closed_function'. v0.3.0 set: datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second, datetime.day_of_year, datetime.julian_day, datetime.is_leap_year, interp.searchsorted, interp.linear, interp.bilinear. For apply_expression_template: the id of an `expression_templates` entry declared in the same component (esm-spec.md §9.6 / docs/rfcs/ast-expression-templates.md). Bindings MUST reject references to undeclared template names at file-load time with diagnostic 'apply_expression_template_unknown_template'.
|
|
224
|
+
*/
|
|
225
|
+
name?: string;
|
|
226
|
+
/**
|
|
227
|
+
* For const: the inline literal value carried by this expression node (any JSON number, integer, or nested array thereof; `args` MUST be empty). For the 'bc' op with kind 'constant'/'dirichlet': the boundary value — a number, a parameter/variable-reference string, or an Expression AST node.
|
|
228
|
+
*/
|
|
229
|
+
value?: {
|
|
230
|
+
[k: string]: unknown;
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* For table_lookup: the id of the function_tables entry to evaluate. Bindings MUST reject references to undeclared tables at file-load time with diagnostic 'table_lookup_unknown_table'.
|
|
234
|
+
*/
|
|
235
|
+
table?: string;
|
|
236
|
+
/**
|
|
237
|
+
* For table_lookup: a map from axis name (matching one of the referenced table's `axes[].name` entries) to the scalar input expression supplying that coordinate at evaluation time. Every axis declared on the table MUST appear as a key; extra keys are rejected with 'table_lookup_axis_name_mismatch'. `args` MUST be empty for a table_lookup node — the per-axis expressions live here.
|
|
238
|
+
*/
|
|
239
|
+
axes?: {
|
|
240
|
+
[k: string]: Expression;
|
|
241
|
+
};
|
|
242
|
+
/**
|
|
243
|
+
* For table_lookup: which output of a multi-output table to return. Either a non-negative integer (0-based index into the leading data dimension) or a string (an entry in the table's `outputs` array). Single-output tables MAY omit this field (defaults to 0). Out-of-range or unknown-name selectors are rejected with 'table_lookup_output_out_of_range'.
|
|
244
|
+
*/
|
|
245
|
+
output?: number | string;
|
|
246
|
+
/**
|
|
247
|
+
* For apply_expression_template: a map from each parameter name declared by the referenced template to the Expression bound to that parameter. Every entry of the template's `params` MUST appear as a key; extra keys are rejected at load time with diagnostic 'apply_expression_template_bindings_mismatch'. Values may be numeric literals, variable name references (strings), or arbitrary Expression ASTs (full subtrees). `args` MUST be empty for an apply_expression_template node — the parameter values live here.
|
|
248
|
+
*/
|
|
249
|
+
bindings?: {
|
|
250
|
+
[k: string]: Expression;
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
type ExpressionNode1 = {
|
|
254
|
+
[k: string]: unknown;
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* A load-time integer expression over metaparameters (esm-spec §9.7.6): an integer literal, a declared metaparameter name, or `{op: +|-|*|/, args: [...]}` over metaparameter expressions (unary `-` allowed). Folded to a concrete integer at load with exact 64-bit arithmetic; `/` MUST divide exactly and overflow is an error (`metaparameter_type_error`). Admissible in structural integer sites (`index_sets` interval `size`, `aggregate` dense `ranges` tuple entries, `makearray` `regions` bound pairs) AND as an import-edge / subsystem-edge binding VALUE, whose free names resolve in the importing document's metaparameter scope.
|
|
258
|
+
*/
|
|
259
|
+
type MetaparameterExpression = number | string | {
|
|
260
|
+
op: "+" | "-" | "*" | "/";
|
|
261
|
+
/**
|
|
262
|
+
* @minItems 1
|
|
263
|
+
*/
|
|
264
|
+
args: [MetaparameterExpression, ...MetaparameterExpression[]];
|
|
265
|
+
};
|
|
266
|
+
/**
|
|
267
|
+
* Trigger specification for a discrete event.
|
|
268
|
+
*/
|
|
269
|
+
type DiscreteEventTrigger = {
|
|
270
|
+
type: "condition";
|
|
271
|
+
expression: Expression;
|
|
272
|
+
} | {
|
|
273
|
+
type: "periodic";
|
|
274
|
+
/**
|
|
275
|
+
* Interval in simulation time units.
|
|
276
|
+
*/
|
|
277
|
+
interval: number;
|
|
278
|
+
/**
|
|
279
|
+
* Offset from t=0 for the first firing.
|
|
280
|
+
*/
|
|
281
|
+
initial_offset?: number;
|
|
282
|
+
} | {
|
|
283
|
+
type: "preset_times";
|
|
284
|
+
/**
|
|
285
|
+
* Array of simulation times at which to fire.
|
|
286
|
+
*
|
|
287
|
+
* @minItems 1
|
|
288
|
+
*/
|
|
289
|
+
times: [number, ...number[]];
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* One native axis of a `DataLoaderSelect`. The vocabulary is shared with the projection-pushdown gate template (CONFORMANCE_SPEC §5.5): "all" keeps the axis whole; `fixed` takes one index and DROPS the axis; `range` takes a half-open strided window and keeps it; `gated_by` names a `derived` index set whose value-invention members become the axis, which DEFERS the fetch until those members exist.
|
|
293
|
+
*/
|
|
294
|
+
type DataSourceSelectAxis = "all" | {
|
|
295
|
+
/**
|
|
296
|
+
* A single 0-based native index.
|
|
297
|
+
*/
|
|
298
|
+
fixed: number | [number];
|
|
299
|
+
} | {
|
|
300
|
+
range: {
|
|
301
|
+
/**
|
|
302
|
+
* Inclusive first index (default 0). A string names a `metaparameters` entry and resolves to its default.
|
|
303
|
+
*/
|
|
304
|
+
start?: number | string;
|
|
305
|
+
/**
|
|
306
|
+
* Exclusive last index. A string names a `metaparameters` entry and resolves to its default, so a prefix is declared in the model's own terms (`W[0:N_SRC]`) rather than as a repeated literal that can drift from the index set sized by the same metaparameter.
|
|
307
|
+
*/
|
|
308
|
+
stop: number | string;
|
|
309
|
+
/**
|
|
310
|
+
* Stride (default 1; MUST be >= 1).
|
|
311
|
+
*/
|
|
312
|
+
step?: number | string;
|
|
313
|
+
};
|
|
314
|
+
} | {
|
|
315
|
+
/**
|
|
316
|
+
* Name of a `kind: "derived"` index set. The axis becomes that set's materialised members in canonical (sorted) member order (CONFORMANCE_SPEC §5.5, Hook 2), so only the rows the model can reach are ever read.
|
|
317
|
+
*/
|
|
318
|
+
gated_by: string;
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* A single scalar check against a model variable at a specific (variable, time) point. PDE-aware variants pin a spatial point via `coords`, or reduce the field to a scalar via `reduce` (domain-integral, mean, max, min, or error-norm). `coords` and `reduce` are mutually exclusive; if neither is given the assertion is pointwise and only valid on a 0-D component. Error-norm reductions (L2_error, Linf_error) require `reference`.
|
|
322
|
+
*/
|
|
323
|
+
type Assertion = Assertion1 & {
|
|
324
|
+
/**
|
|
325
|
+
* Name of the variable or species to check. Use the local name (e.g., "O3") or a scoped reference relative to this component (e.g., "subsystem.X").
|
|
326
|
+
*/
|
|
327
|
+
variable: string;
|
|
328
|
+
/**
|
|
329
|
+
* Simulation time at which to evaluate the assertion. Must lie within [time_span.start, time_span.end].
|
|
330
|
+
*/
|
|
331
|
+
time: number;
|
|
332
|
+
/**
|
|
333
|
+
* Expected scalar value of the variable at the given time.
|
|
334
|
+
*/
|
|
335
|
+
expected?: number;
|
|
336
|
+
tolerance?: Tolerance2;
|
|
337
|
+
/**
|
|
338
|
+
* Spatial-point evaluation: map from a spatial index-set / dimension name (e.g., "x", "lon") to the numeric coordinate at which to sample the field. All keys MUST be names of index sets the field is defined over. Mutually exclusive with `reduce`.
|
|
339
|
+
*/
|
|
340
|
+
coords?: {
|
|
341
|
+
[k: string]: number;
|
|
342
|
+
};
|
|
343
|
+
/**
|
|
344
|
+
* Domain reduction: collapse the spatial field to a single scalar before comparison. `integral`/`mean`/`max`/`min` are pure reductions; `L2_error`/`Linf_error` require a `reference` solution and compute ||u_actual - u_reference||_norm. Mutually exclusive with `coords`.
|
|
345
|
+
*/
|
|
346
|
+
reduce?: "integral" | "mean" | "max" | "min" | "L2_error" | "Linf_error";
|
|
347
|
+
/**
|
|
348
|
+
* Reference (analytic or precomputed) solution required by error-norm reductions. Either an inline Expression evaluated over the component's domain coordinates, or a from_file shape pointing at a precomputed snapshot.
|
|
349
|
+
*/
|
|
350
|
+
reference?: Expression | {
|
|
351
|
+
type: "from_file";
|
|
352
|
+
path: string;
|
|
353
|
+
format?: string;
|
|
354
|
+
};
|
|
355
|
+
};
|
|
356
|
+
type Assertion1 = {
|
|
357
|
+
[k: string]: unknown;
|
|
358
|
+
} & {
|
|
359
|
+
[k: string]: unknown;
|
|
360
|
+
} & {
|
|
361
|
+
[k: string]: unknown;
|
|
362
|
+
} & {
|
|
363
|
+
[k: string]: unknown;
|
|
364
|
+
};
|
|
365
|
+
/**
|
|
366
|
+
* One axis of a parameter sweep: exactly one of values or range must be given.
|
|
367
|
+
*/
|
|
368
|
+
type SweepDimension = {
|
|
369
|
+
/**
|
|
370
|
+
* Name of the parameter to vary (local to this component).
|
|
371
|
+
*/
|
|
372
|
+
parameter: string;
|
|
373
|
+
/**
|
|
374
|
+
* Enumerated values to use for this axis.
|
|
375
|
+
*
|
|
376
|
+
* @minItems 1
|
|
377
|
+
*/
|
|
378
|
+
values?: [number, ...number[]];
|
|
379
|
+
range?: SweepRange;
|
|
380
|
+
} & SweepDimension1;
|
|
381
|
+
type SweepDimension1 = {
|
|
382
|
+
[k: string]: unknown;
|
|
383
|
+
} | {
|
|
384
|
+
[k: string]: unknown;
|
|
385
|
+
};
|
|
386
|
+
/**
|
|
387
|
+
* A plot specification associated with an analysis. Only structural information is recorded — axes, series selection, and value reductions. Styling (colors, fonts, legends, themes) is the viewer's concern. PDE-aware plot types `field_slice` and `field_snapshot` visualize spatial fields at a fixed time; `x` (and `y` for snapshots) name domain dimensions, the variable value becomes the y / color channel, and any non-plotted spatial dimension MUST be pinned in `pinned_coords`.
|
|
388
|
+
*/
|
|
389
|
+
type Plot = Plot1 & {
|
|
390
|
+
/**
|
|
391
|
+
* Identifier unique within this analysis's plots array.
|
|
392
|
+
*/
|
|
393
|
+
id: string;
|
|
394
|
+
type: "line" | "scatter" | "heatmap" | "field_slice" | "field_snapshot";
|
|
395
|
+
description?: string;
|
|
396
|
+
x: PlotAxis;
|
|
397
|
+
/**
|
|
398
|
+
* Y-axis specification. May be a single PlotAxis, or an array of PlotAxis for inline multi-series line/scatter plots (alternative to the `series` field for the common case of plotting several variables against a shared x-axis).
|
|
399
|
+
*/
|
|
400
|
+
y: PlotAxis | [PlotAxis, ...PlotAxis[]];
|
|
401
|
+
value?: PlotValue;
|
|
402
|
+
/**
|
|
403
|
+
* Multiple named series for line or scatter plots. Ignored for heatmap and field plots.
|
|
404
|
+
*/
|
|
405
|
+
series?: PlotSeries[];
|
|
406
|
+
/**
|
|
407
|
+
* Required for field_slice and field_snapshot: simulation time at which to extract the spatial field. Must lie within the analysis's time_span.
|
|
408
|
+
*/
|
|
409
|
+
at_time?: number;
|
|
410
|
+
/**
|
|
411
|
+
* Required for field_slice and field_snapshot when the component domain has more spatial dimensions than the plot's spatial axes (1 for field_slice, 2 for field_snapshot). Maps each non-plotted spatial dimension name to the numeric coordinate at which to slice. Keys MUST be names of dimensions in component.domain.spatial that are not used by `x` (or `y` for field_snapshot).
|
|
412
|
+
*/
|
|
413
|
+
pinned_coords?: {
|
|
414
|
+
[k: string]: number;
|
|
415
|
+
};
|
|
416
|
+
/**
|
|
417
|
+
* Optional iso-levels to overlay as contour lines on a field plot (field_slice / field_snapshot / heatmap). Each number is a value of the plotted field at which to draw a contour line — e.g. [0] draws the zero level-set front. Purely a viewer overlay; ignored for line/scatter.
|
|
418
|
+
*/
|
|
419
|
+
contours?: number[];
|
|
420
|
+
};
|
|
421
|
+
type Plot1 = {
|
|
422
|
+
[k: string]: unknown;
|
|
423
|
+
} & {
|
|
424
|
+
[k: string]: unknown;
|
|
425
|
+
} & {
|
|
426
|
+
[k: string]: unknown;
|
|
427
|
+
};
|
|
428
|
+
/**
|
|
429
|
+
* A reaction-system parameter — rate constant, temperature, photolysis rate. Carries the same value machinery as a model `parameter`: a fixed `default`, or a `distribution`, with an optional `update` saying when it refreshes.
|
|
430
|
+
*/
|
|
431
|
+
type Parameter = Parameter1 & {
|
|
432
|
+
units?: string;
|
|
433
|
+
default?: number;
|
|
434
|
+
/**
|
|
435
|
+
* Units of the default value, if different from the declared units field. See ModelVariable.default_units for semantics.
|
|
436
|
+
*/
|
|
437
|
+
default_units?: string;
|
|
438
|
+
description?: string;
|
|
439
|
+
/**
|
|
440
|
+
* Arrayed-variable shape: ordered list of index-set names drawn from the document-scoped `index_sets` registry. Omitted or null indicates a scalar. REQUIRED for a parameter whose `update` is `schedule`, `data`, or `remesh` — such a parameter is a buffer whose extent is fixed at setup and refilled on a discrete cadence, so its extent must be known ahead of time (RFC semiring-faq-unified-ir §6.1); an empty array is a valid (scalar) shape.
|
|
441
|
+
*/
|
|
442
|
+
shape?: string[];
|
|
443
|
+
/**
|
|
444
|
+
* Draw this parameter's value from a distribution instead of fixing it at `default`. Mutually exclusive with `default`.
|
|
445
|
+
*/
|
|
446
|
+
distribution?: {
|
|
447
|
+
[k: string]: unknown;
|
|
448
|
+
} | {
|
|
449
|
+
kind: "uniform";
|
|
450
|
+
low: number | [number, ...number[]];
|
|
451
|
+
high: number | [number, ...number[]];
|
|
452
|
+
};
|
|
453
|
+
/**
|
|
454
|
+
* When this parameter refreshes and what it refreshes from.
|
|
455
|
+
*/
|
|
456
|
+
update?: ParameterUpdate$1 | [
|
|
457
|
+
ParameterUpdate$1 & {
|
|
458
|
+
[k: string]: unknown;
|
|
459
|
+
},
|
|
460
|
+
ParameterUpdate$1 & {
|
|
461
|
+
[k: string]: unknown;
|
|
462
|
+
},
|
|
463
|
+
...(ParameterUpdate$1 & {
|
|
464
|
+
[k: string]: unknown;
|
|
465
|
+
})[]
|
|
466
|
+
];
|
|
467
|
+
};
|
|
468
|
+
type Parameter1 = {
|
|
469
|
+
[k: string]: unknown;
|
|
470
|
+
};
|
|
471
|
+
/**
|
|
472
|
+
* A single coupling rule connecting models or reaction systems. A `data_sources` entry is not a component and cannot appear as a coupling endpoint; external data enters through a parameter's `update`.
|
|
473
|
+
*/
|
|
474
|
+
type CouplingEntry = CouplingOperatorCompose | CouplingCouple | CouplingVariableMap | CouplingCallback | CouplingEvent | CouplingImport;
|
|
475
|
+
/**
|
|
476
|
+
* Translation target: a simple variable reference string or an object with var and factor.
|
|
477
|
+
*/
|
|
478
|
+
type TranslateTarget = string | {
|
|
479
|
+
var: string;
|
|
480
|
+
factor?: number;
|
|
481
|
+
};
|
|
482
|
+
/**
|
|
483
|
+
* Replace a parameter in one system with a variable from another.
|
|
484
|
+
*/
|
|
485
|
+
type CouplingVariableMap = CouplingVariableMap1 & {
|
|
486
|
+
type: "variable_map";
|
|
487
|
+
/**
|
|
488
|
+
* Source variable (scoped reference, e.g., "GEOSFP.T").
|
|
489
|
+
*/
|
|
490
|
+
from: string;
|
|
491
|
+
/**
|
|
492
|
+
* Target parameter (scoped reference, e.g., "SuperFast.T").
|
|
493
|
+
*/
|
|
494
|
+
to: string;
|
|
495
|
+
/**
|
|
496
|
+
* How the mapping is applied: one of the named transforms, or an Expression evaluated on the source value(s) in the flattened coupled system's scope (spec §8.6/§10.4/§10.5 — the regridding form; the expression must reference the entry's `from` variable via a fully-scoped reference and may reference any other in-scope variable, e.g. build-once overlap weights in the receiving component; `apply_expression_template` invocations are legal and resolve at load per §9.6.4 — eager references expand, the rest survive and denote their expansion). The Expression form is an operator node: the degenerate bare-reference and literal Expression spellings are not admissible here (the named string transforms already cover bare replacement, and the string space is reserved for them).
|
|
497
|
+
*/
|
|
498
|
+
transform: ("param_to_var" | "identity" | "additive" | "multiplicative" | "conversion_factor") | ExpressionNode;
|
|
499
|
+
/**
|
|
500
|
+
* Scaling coefficient applied by a scaling transform (additive, multiplicative, conversion_factor). Not permitted with param_to_var, identity, or an Expression transform, which replace/assign/compute without a separate scaling slot.
|
|
501
|
+
*/
|
|
502
|
+
factor?: number;
|
|
503
|
+
/**
|
|
504
|
+
* Strategy for mapping between 0D and spatial systems.
|
|
505
|
+
*/
|
|
506
|
+
lifting?: "pointwise" | "broadcast" | "mean" | "integral";
|
|
507
|
+
/**
|
|
508
|
+
* Map from a target system referenced by this coupling entry to the template-library imports registered into THAT component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a PDE component as it is wired into the assembly. Each key MUST name a model/reaction-system this entry references (template_inject_target_unknown otherwise; the `variable_map` reference fields are `from`/`to`); a key resolving to neither a model nor a reaction system is template_inject_target_not_component -- which from 1.0.0 is also how a key naming a `data_sources` entry is reported, since a data source is not a component and the separate template_inject_target_is_loader code is retired. Values use the §9.7.2 entry shape. Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
509
|
+
*/
|
|
510
|
+
expression_template_imports?: {
|
|
511
|
+
[k: string]: TemplateImport[];
|
|
512
|
+
};
|
|
513
|
+
description?: string;
|
|
514
|
+
};
|
|
515
|
+
type CouplingVariableMap1 = {
|
|
516
|
+
[k: string]: unknown;
|
|
517
|
+
};
|
|
518
|
+
/**
|
|
519
|
+
* Cross-system event involving variables from multiple coupled systems.
|
|
520
|
+
*/
|
|
521
|
+
type CouplingEvent = CouplingEvent1 & {
|
|
522
|
+
type: "event";
|
|
523
|
+
/**
|
|
524
|
+
* Whether this is a continuous or discrete event.
|
|
525
|
+
*/
|
|
526
|
+
event_type: "continuous" | "discrete";
|
|
527
|
+
/**
|
|
528
|
+
* Human-readable identifier.
|
|
529
|
+
*/
|
|
530
|
+
name?: string;
|
|
531
|
+
/**
|
|
532
|
+
* Condition expressions (zero-crossing for continuous, boolean for discrete).
|
|
533
|
+
*/
|
|
534
|
+
conditions?: Expression[];
|
|
535
|
+
/**
|
|
536
|
+
* Trigger specification for a discrete event.
|
|
537
|
+
*/
|
|
538
|
+
trigger?: {
|
|
539
|
+
type: "condition";
|
|
540
|
+
expression: Expression;
|
|
541
|
+
} | {
|
|
542
|
+
type: "periodic";
|
|
543
|
+
/**
|
|
544
|
+
* Interval in simulation time units.
|
|
545
|
+
*/
|
|
546
|
+
interval: number;
|
|
547
|
+
/**
|
|
548
|
+
* Offset from t=0 for the first firing.
|
|
549
|
+
*/
|
|
550
|
+
initial_offset?: number;
|
|
551
|
+
} | {
|
|
552
|
+
type: "preset_times";
|
|
553
|
+
/**
|
|
554
|
+
* Array of simulation times at which to fire.
|
|
555
|
+
*
|
|
556
|
+
* @minItems 1
|
|
557
|
+
*/
|
|
558
|
+
times: [number, ...number[]];
|
|
559
|
+
};
|
|
560
|
+
/**
|
|
561
|
+
* Affect equations. Required unless functional_affect is used.
|
|
562
|
+
*/
|
|
563
|
+
affects: AffectEquation[];
|
|
564
|
+
affect_neg?: null | AffectEquation[];
|
|
565
|
+
root_find?: "left" | "right" | "all";
|
|
566
|
+
reinitialize?: boolean;
|
|
567
|
+
/**
|
|
568
|
+
* Map from a target system referenced by this coupling entry to the template-library imports registered into THAT component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a PDE component as it is wired into the assembly. Each key MUST name a model/reaction-system this entry references (template_inject_target_unknown otherwise); a key resolving to neither a model nor a reaction system is template_inject_target_not_component -- which from 1.0.0 is also how a key naming a `data_sources` entry is reported, since a data source is not a component and the separate template_inject_target_is_loader code is retired. Values use the §9.7.2 entry shape. Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
569
|
+
*/
|
|
570
|
+
expression_template_imports?: {
|
|
571
|
+
[k: string]: TemplateImport[];
|
|
572
|
+
};
|
|
573
|
+
description?: string;
|
|
574
|
+
};
|
|
575
|
+
type CouplingEvent1 = {
|
|
576
|
+
[k: string]: unknown;
|
|
577
|
+
} & {
|
|
578
|
+
[k: string]: unknown;
|
|
579
|
+
};
|
|
580
|
+
/**
|
|
581
|
+
* A named index set (RFC semiring-faq-unified-ir §5.2): the declaration shape for an iteration domain referenced from an `aggregate` range via { "from": <name> }. Covers grid axes and categorical dimensions under one shape. Exactly one of four kinds, each requiring its own fields.
|
|
582
|
+
*/
|
|
583
|
+
type IndexSet = IndexSet1 & {
|
|
584
|
+
/**
|
|
585
|
+
* Which of the four index-set forms this entry is. "interval": a dense [1..size] grid axis. "categorical": an explicit enumeration of members. "derived": a data-derived set materialized from an index-set-producing node (a `distinct` `aggregate`, or an `intersect_polygon` ring leaf whose clipped ring has a data-dependent vertex count, §8.1). "ragged": a per-parent (dependent) inner set backed by CSR offsets/values factors.
|
|
586
|
+
*/
|
|
587
|
+
kind: "interval" | "categorical" | "derived" | "ragged";
|
|
588
|
+
/**
|
|
589
|
+
* A load-time integer expression over metaparameters (esm-spec §9.7.6): an integer literal, a declared metaparameter name, or `{op: +|-|*|/, args: [...]}` over metaparameter expressions (unary `-` allowed). Folded to a concrete integer at load with exact 64-bit arithmetic; `/` MUST divide exactly and overflow is an error (`metaparameter_type_error`). Admissible in structural integer sites (`index_sets` interval `size`, `aggregate` dense `ranges` tuple entries, `makearray` `regions` bound pairs) AND as an import-edge / subsystem-edge binding VALUE, whose free names resolve in the importing document's metaparameter scope.
|
|
590
|
+
*/
|
|
591
|
+
size?: number | string | {
|
|
592
|
+
op: "+" | "-" | "*" | "/";
|
|
593
|
+
/**
|
|
594
|
+
* @minItems 1
|
|
595
|
+
*/
|
|
596
|
+
args: [MetaparameterExpression, ...MetaparameterExpression[]];
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* categorical: the explicit enumeration of members (e.g. county FIPS codes, fuel types). Required when kind is "categorical".
|
|
600
|
+
*/
|
|
601
|
+
members?: unknown[];
|
|
602
|
+
/**
|
|
603
|
+
* derived: the id of the index-set-producing node (RFC §5.5) that materializes this set, named by its `id`. Usually an `aggregate` node (`distinct: true`) — e.g. the unique edges discovered from a face→vertex relation. It MAY also be an `intersect_polygon` geometry-kernel leaf (RFC §8.1): the clipped overlap ring it returns has a data-dependent number of vertices, so the ring's vertex set is exactly such a derived index set, and `polygon_area` is then an ordinary `sum_product` FAQ over it. Required when kind is "derived".
|
|
604
|
+
*/
|
|
605
|
+
from_faq?: string;
|
|
606
|
+
/**
|
|
607
|
+
* derived: name of the buffer that receives the surviving member key per invented position (CONFORMANCE_SPEC §5.5, Hook 1) — fed back as a `const` factor so an aggregate ranging over the compact derived axis can gather the full-grid rows that axis selects. That is what downstream aggregates do; it is not a claim about ORIENTATION — an aggregate that reduces OVER the compact axis, and one whose overlap-gate envelope factors are themselves such gathers, gather exactly the same way (CONFORMANCE_SPEC §5.5.7). OPTIONAL, and only meaningful when kind is "derived" and `from_faq` names an overlap-gated `distinct` aggregate. Pairs with a provider axis marked `gated_by: "<this set>"`, which is DEFERRED past value-invention and then fetched with a Selection built from the materialised members in sorted order (the `gated_select` pushdown).
|
|
608
|
+
*/
|
|
609
|
+
member_factor?: string;
|
|
610
|
+
/**
|
|
611
|
+
* ragged: the parent index-set name(s) this inner set depends on (e.g. ["cells"] for the edges of each cell). Required when kind is "ragged".
|
|
612
|
+
*/
|
|
613
|
+
of?: string[];
|
|
614
|
+
/**
|
|
615
|
+
* ragged: name of the keyed factor giving |set(i)| for each parent tuple — the per-parent length / CSR offsets (e.g. MPAS nEdgesOnCell). Required when kind is "ragged".
|
|
616
|
+
*/
|
|
617
|
+
offsets?: string;
|
|
618
|
+
/**
|
|
619
|
+
* ragged: name of the keyed factor giving the member at (i, k) for k in 1…|set(i)| — the flattened CSR member array (e.g. edgesOnCell). Required when kind is "ragged".
|
|
620
|
+
*/
|
|
621
|
+
values?: string;
|
|
622
|
+
};
|
|
623
|
+
type IndexSet1 = {
|
|
624
|
+
[k: string]: unknown;
|
|
625
|
+
};
|
|
626
|
+
/**
|
|
627
|
+
* One entry of the document-scoped `coordinates` registry (RFC streaming-output-sinks §8): marks an existing data array (or an inline literal vector) as a physical coordinate and attaches CF metadata. Exactly one of `source` (reference an existing array by name) or `values` (inline literal) MUST be present. The coordinate's shape/dimensions come from its source, so no per-axis attachment is needed; the writer resolves CF role (dimension vs auxiliary) from that shape.
|
|
628
|
+
*/
|
|
629
|
+
type Coordinate = {
|
|
630
|
+
/**
|
|
631
|
+
* Name of an existing data array — a model unknown or parameter (including one fed from a `data_sources` entry) — supplying this coordinate's values. Referenced by name exactly as a ragged `IndexSet` references its `offsets`/`values` factors. Mutually exclusive with `values`. The array's declared shape (its ordered index-set dimensions) IS the coordinate's shape: 1-D monotonic over a grid axis → CF dimension coordinate; 1-D over a shared dimension (e.g. `lat(cells)`) or 2-D (`lat(y,x)`) → CF auxiliary coordinate.
|
|
632
|
+
*/
|
|
633
|
+
source?: string;
|
|
634
|
+
/**
|
|
635
|
+
* Inline literal 1-D coordinate vector for the simple rectilinear case, mirroring `FunctionTableAxis.values` (finite floats). Mutually exclusive with `source`. Use `source` for anything not a plain 1-D literal (unstructured/curvilinear coordinates live in data arrays).
|
|
636
|
+
*
|
|
637
|
+
* @minItems 1
|
|
638
|
+
*/
|
|
639
|
+
values?: [number, ...number[]];
|
|
640
|
+
/**
|
|
641
|
+
* CF standard name (e.g. "latitude", "longitude", "air_pressure"). Emitted verbatim as the coordinate variable's `standard_name` attribute.
|
|
642
|
+
*/
|
|
643
|
+
standard_name?: string;
|
|
644
|
+
/**
|
|
645
|
+
* CF/UDUNITS units string (e.g. "degrees_north", "degrees_east", "Pa"). Emitted as the coordinate variable's `units` attribute. Advisory at load time (no unit checking), matching `FunctionTableAxis.units`.
|
|
646
|
+
*/
|
|
647
|
+
units?: string;
|
|
648
|
+
/**
|
|
649
|
+
* Optional CF axis role for a rectilinear dimension coordinate. Set it ONLY for a 1-D monotonic dimension coordinate; omit it for auxiliary coordinates (unstructured/curvilinear), which have no single axis. Emitted as the `axis` attribute.
|
|
650
|
+
*/
|
|
651
|
+
axis?: "X" | "Y" | "Z" | "T";
|
|
652
|
+
} & Coordinate1;
|
|
653
|
+
type Coordinate1 = {
|
|
654
|
+
[k: string]: unknown;
|
|
655
|
+
};
|
|
656
|
+
interface ESMFormat2 {
|
|
657
|
+
/**
|
|
658
|
+
* Format version string (semver).
|
|
659
|
+
*/
|
|
660
|
+
esm: string;
|
|
661
|
+
metadata: Metadata;
|
|
662
|
+
/**
|
|
663
|
+
* ODE-based model components, keyed by unique identifier. Each component may be defined inline or included by reference to an external ESM file containing exactly one top-level model (esm-spec.md §4.7).
|
|
664
|
+
*/
|
|
665
|
+
models?: {
|
|
666
|
+
[k: string]: Model$1 | SubsystemRef;
|
|
667
|
+
};
|
|
668
|
+
/**
|
|
669
|
+
* Reaction network components, keyed by unique identifier. Each component may be defined inline or included by reference to an external ESM file containing exactly one top-level reaction system (esm-spec.md §4.7).
|
|
670
|
+
*/
|
|
671
|
+
reaction_systems?: {
|
|
672
|
+
[k: string]: ReactionSystem | SubsystemRef;
|
|
673
|
+
};
|
|
674
|
+
/**
|
|
675
|
+
* Document-scoped registry of external data sources, keyed by name. A data source is INGEST CONFIGURATION, not a component: it says where bytes live and how to decode, slice, and filter them, and it exposes no variables of its own. A model consumes one by declaring a parameter whose `update` names the source and binds a `file_variable` from it. The shared parts stay here because their guarantees are source-wide and cannot be stated per-parameter: `record_filter` computes the surviving-record mask ONCE and applies it to every parameter drawing from this source, which is what makes it impossible for two columns of one points table to fall out of alignment, and `extent` binds ONE metaparameter from that single shared record count.
|
|
676
|
+
*/
|
|
677
|
+
data_sources?: {
|
|
678
|
+
[k: string]: DataSource;
|
|
679
|
+
};
|
|
680
|
+
/**
|
|
681
|
+
* File-local symbol-to-positive-integer mappings used by the 'enum' AST op to make categorical lookups cross-binding-portable. Each entry is an enum name; its value is an object mapping symbolic names (strings) to positive integers. Two .esm files may declare an enum of the same name with different mappings; enums are file-local and never merged across files. See esm-spec.md §9.3.
|
|
682
|
+
*/
|
|
683
|
+
enums?: {
|
|
684
|
+
[k: string]: EnumDeclaration;
|
|
685
|
+
};
|
|
686
|
+
/**
|
|
687
|
+
* Composition and coupling rules.
|
|
688
|
+
*/
|
|
689
|
+
coupling?: CouplingEntry[];
|
|
690
|
+
domain?: Domain;
|
|
691
|
+
/**
|
|
692
|
+
* Component-scoped sampled function tables (v0.4.0). Each entry declares ordered named axes plus a literal nested-array data block, optionally tagged with output names; the `table_lookup` AST op references a table by id, supplies a per-axis input-coordinate expression map, and selects which output to return. Tables are syntactic sugar over `interp.linear` / `interp.bilinear` / `index`: a `table_lookup` MUST be bit-equivalent to the equivalent inline-const lookup. See esm-spec.md §9.5 and docs/rfcs/sampled-tables.md.
|
|
693
|
+
*/
|
|
694
|
+
function_tables?: {
|
|
695
|
+
[k: string]: FunctionTable;
|
|
696
|
+
};
|
|
697
|
+
/**
|
|
698
|
+
* Document-scoped registry of named index sets (RFC semiring-faq-unified-ir §5.2), keyed by name — the single, document-level declaration site for every iteration domain (grid axes, categorical dimensions, data-derived sets) shared by all models in the document. An `aggregate` range references one by name as { "from": <name> }. Each entry is an interval (dense axis), categorical enumeration, data-derived set, or ragged / dependent inner set. A reference resolves by name to exactly one entry; resolvers MUST error on an undeclared name.
|
|
699
|
+
*/
|
|
700
|
+
index_sets?: {
|
|
701
|
+
[k: string]: IndexSet;
|
|
702
|
+
};
|
|
703
|
+
/**
|
|
704
|
+
* Document-scoped, OPTIONAL registry of coordinate variables (RFC streaming-output-sinks §8), keyed by name. Purely additive: a document without it validates and emits exactly as before (bare integer axes). Each entry marks an existing data array — a model unknown or parameter referenced BY NAME (including a parameter fed from a `data_sources` entry) (exactly as a ragged `IndexSet` references its `offsets`/`values` factors), or an inline literal `values` vector — as a physical coordinate and attaches CF metadata (`standard_name`, `units`, optional `axis`). The coordinate's SHAPE is read from its source, so it is NOT attached to any single axis: this is the CF coordinate data model, covering rectilinear (1-D monotonic → CF dimension coordinate), unstructured (1-D over a shared dimension → CF auxiliary coordinate) and curvilinear (2-D `lat(y,x)`/`lon(y,x)` → auxiliary coordinate) grids under one rule. A streaming writer derives each data variable's CF `coordinates` attribute mechanically: every coordinate whose source DIMENSIONS (by identity, NOT by length) are a subset of the data variable's dimensions applies to it.
|
|
705
|
+
*/
|
|
706
|
+
coordinates?: {
|
|
707
|
+
[k: string]: Coordinate;
|
|
708
|
+
};
|
|
709
|
+
/**
|
|
710
|
+
* Top-level rewrite rules / templates — the payload of a template-library file (esm-spec §9.7.1). Only valid in a library file (which carries no models/reaction_systems/data_loaders/coupling/domain, `template_import_not_library` when imported otherwise); component-local templates stay inside their model/reaction_system (§9.6.1). Arrives at esm 0.8.0 (`template_import_version_too_old`).
|
|
711
|
+
*/
|
|
712
|
+
expression_templates?: {
|
|
713
|
+
[k: string]: ExpressionTemplate;
|
|
714
|
+
};
|
|
715
|
+
/**
|
|
716
|
+
* Ordered imports of template-library files at document top level — only valid in a library file layering on other libraries (esm-spec §9.7.2). Models and reaction systems carry their own `expression_template_imports` field.
|
|
717
|
+
*/
|
|
718
|
+
expression_template_imports?: TemplateImport[];
|
|
719
|
+
metaparameters?: Metaparameters;
|
|
720
|
+
/**
|
|
721
|
+
* Coupling-library formal component roles (esm-spec §10.9). Present only in a coupling-library file, which pairs it with a role-scoped `coupling` array and declares no models/reaction_systems/data_loaders/domain/index_sets/metaparameters/expression_templates (enforced by the resolver as `coupling_library_illegal_payload`). Presence of this key is the sole positive identifier of the coupling-library file kind. Each entry is a role descriptor carrying an optional human-readable `description`; roles are formal parameters (names, not types), bound to actual components at a `coupling_import` (esm-spec §10.10).
|
|
722
|
+
*/
|
|
723
|
+
coupling_roles?: {
|
|
724
|
+
[k: string]: {
|
|
725
|
+
description?: string;
|
|
726
|
+
};
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Authorship, provenance, and description.
|
|
731
|
+
*/
|
|
732
|
+
interface Metadata {
|
|
733
|
+
/**
|
|
734
|
+
* Short identifier for the model configuration.
|
|
735
|
+
*/
|
|
736
|
+
name: string;
|
|
737
|
+
description?: string;
|
|
738
|
+
authors?: string[];
|
|
739
|
+
license?: string;
|
|
740
|
+
/**
|
|
741
|
+
* ISO 8601 creation timestamp. The pattern duplicates `format: date-time` because `format` is an annotation, not an assertion, in JSON Schema — validators ignore it unless separately configured, so the pattern is what makes the constraint portable across bindings.
|
|
742
|
+
*/
|
|
743
|
+
created?: string;
|
|
744
|
+
/**
|
|
745
|
+
* ISO 8601 last-modified timestamp.
|
|
746
|
+
*/
|
|
747
|
+
modified?: string;
|
|
748
|
+
tags?: string[];
|
|
749
|
+
references?: Reference[];
|
|
750
|
+
/**
|
|
751
|
+
* Diagnostic stamped by discretize(): whether the resolved system is a pure ODE or a DAE (RFC §12).
|
|
752
|
+
*/
|
|
753
|
+
system_class?: "ode" | "dae";
|
|
754
|
+
/**
|
|
755
|
+
* Diagnostic stamped by discretize(): algebraic-equation accounting (RFC §12).
|
|
756
|
+
*/
|
|
757
|
+
dae_info?: {
|
|
758
|
+
algebraic_equation_count?: number;
|
|
759
|
+
per_model?: {
|
|
760
|
+
[k: string]: number;
|
|
761
|
+
};
|
|
762
|
+
[k: string]: unknown;
|
|
763
|
+
};
|
|
764
|
+
/**
|
|
765
|
+
* Diagnostic stamped by discretize(): identifies the source document this was discretized from (RFC §12).
|
|
766
|
+
*/
|
|
767
|
+
discretized_from?: {
|
|
768
|
+
/**
|
|
769
|
+
* The metadata.name of the source document.
|
|
770
|
+
*/
|
|
771
|
+
name?: string;
|
|
772
|
+
[k: string]: unknown;
|
|
773
|
+
};
|
|
774
|
+
/**
|
|
775
|
+
* Reserved extension point for downstream-catalog machine-readable metadata (e.g. the EarthSciDiscretizations rule-library catalog). Free-form JSON: the schema validates only that this is an object. The core spec NEVER interprets, validates, or transforms its contents — core tooling MUST NOT assign meaning to them and MUST preserve them across parse → emit like any other metadata field. Downstream catalogs define and version their own conventions inside it (esm-spec §3).
|
|
776
|
+
*/
|
|
777
|
+
x_esd?: {
|
|
778
|
+
[k: string]: unknown;
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Academic citation or data source reference.
|
|
783
|
+
*/
|
|
784
|
+
interface Reference {
|
|
785
|
+
/**
|
|
786
|
+
* DOI in the standard `10.<registrant>/<suffix>` form.
|
|
787
|
+
*/
|
|
788
|
+
doi?: string;
|
|
789
|
+
citation?: string;
|
|
790
|
+
/**
|
|
791
|
+
* Absolute URI. The pattern duplicates `format: uri` because `format` is an annotation, not an assertion, in JSON Schema.
|
|
792
|
+
*/
|
|
793
|
+
url?: string;
|
|
794
|
+
notes?: string;
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* An ODE system — a fully specified set of time-dependent equations.
|
|
798
|
+
*/
|
|
799
|
+
interface Model$1 {
|
|
800
|
+
reference?: Reference;
|
|
801
|
+
/**
|
|
802
|
+
* All variables, keyed by name.
|
|
803
|
+
*/
|
|
804
|
+
variables: {
|
|
805
|
+
[k: string]: ModelVariable$1;
|
|
806
|
+
};
|
|
807
|
+
/**
|
|
808
|
+
* Array of {lhs, rhs} equation objects.
|
|
809
|
+
*/
|
|
810
|
+
equations: Equation[];
|
|
811
|
+
/**
|
|
812
|
+
* Equations that hold only at t=0 (not dynamically). Used by models whose initialization requires solving an auxiliary system before time-stepping begins (e.g. aerosol equilibrium, plume rise). Each entry is a {lhs, rhs} equation evaluated/solved at t=0.
|
|
813
|
+
*/
|
|
814
|
+
initialization_equations?: Equation[];
|
|
815
|
+
/**
|
|
816
|
+
* Initial-guess seeds for nonlinear solvers during initialization, keyed by variable name. Values are Expression graphs (numbers, strings, or ExpressionNode).
|
|
817
|
+
*/
|
|
818
|
+
guesses?: {
|
|
819
|
+
[k: string]: Expression;
|
|
820
|
+
};
|
|
821
|
+
/**
|
|
822
|
+
* Discriminates the MTK system type this model maps to. Defaults to 'ode' (time-stepping). 'nonlinear' for algebraic-only systems (no time derivative; e.g. aerosol equilibrium, Mogi). 'sde' when any parameter carries a `wiener` update. 'pde' for models whose equations contain a SPATIAL DERIVATIVE -- a `D` whose `wrt` is present and is not 't', or one of the `grad`/`div`/`laplacian` sugar ops. Note this is a property of the EQUATIONS, not of the `domain` block: v0.8.0 removed `Domain.spatial`, so `domain` carries nothing spatial and the older 'spatial domain plus differential operators' wording named a test no binding could perform. From 1.0.0 this field is a DECLARATION of something the equations and parameter updates already determine: bindings expose a `system_kind` classifier that derives it, use the derivation when this field is absent, and report `system_kind_mismatch` when a present field contradicts it. Derivation order is sde, then pde, then nonlinear, then ode (esm-spec 6.3.1): a steady-state PDE has no time derivative and must not fall through to 'nonlinear', while a model that is both stochastic and spatial assembles as an SDE because there is no SPDESystem constructor.
|
|
823
|
+
*/
|
|
824
|
+
system_kind?: "ode" | "nonlinear" | "sde" | "pde";
|
|
825
|
+
discrete_events?: DiscreteEvent[];
|
|
826
|
+
continuous_events?: ContinuousEvent[];
|
|
827
|
+
/**
|
|
828
|
+
* Named child subsystems, keyed by unique identifier. A subsystem is a child model, or a reference to an external file containing exactly one. Enables hierarchical model composition. Variables in subsystems are referenced via dot notation: "ParentModel.ChildModel.var". Each subsystem can be defined inline or included by reference via a local file path or URL. A `data_sources` entry is NOT a component and cannot be a subsystem: a model reaches external data through a parameter whose `update` names the source.
|
|
829
|
+
*/
|
|
830
|
+
subsystems?: {
|
|
831
|
+
[k: string]: Model$1 | DataSource | SubsystemRef;
|
|
832
|
+
};
|
|
833
|
+
tolerance?: Tolerance;
|
|
834
|
+
/**
|
|
835
|
+
* Inline validation tests that exercise this model in isolation. Each test specifies initial conditions, parameter overrides, a time span, and scalar assertions at specific (variable, time) points.
|
|
836
|
+
*/
|
|
837
|
+
tests?: Test[];
|
|
838
|
+
/**
|
|
839
|
+
* Inline illustrative analyses of how to run this model. Each analysis specifies initial state, parameters, a time span, an optional parameter sweep, and plot specifications.
|
|
840
|
+
*/
|
|
841
|
+
analyses?: Analysis[];
|
|
842
|
+
/**
|
|
843
|
+
* Component-scoped in-file Expression-AST templates (v0.4.0; docs/rfcs/ast-expression-templates.md). Each entry names a fixed Expression body with parameter substitution slots; `apply_expression_template` AST nodes elsewhere in this component reference the entry by key with per-parameter bindings. Templates are component-local: declarations here are visible only within this model's expression positions. A body MAY reference other match-less in-scope templates as a statically-checked acyclic DAG — no cycles, no recursion (esm-spec §9.7.3). From esm 0.9.0 the round-trip is Option B (reference-preserving, esm-spec §9.6.4): references survive load and parse-then-emit and denote their expansion (`Expand`); eager (target-bearing) references still expand at load; emit materializes referenced templates into this registry — authored entries first in authored order, then materialized entries in lexicographic UTF-8 name order; keys may be dotted post-rename names. Pre-0.9.0 loaders expanded every reference at load (Option A) and emitted the expanded form.
|
|
844
|
+
*/
|
|
845
|
+
expression_templates?: {
|
|
846
|
+
[k: string]: ExpressionTemplate;
|
|
847
|
+
};
|
|
848
|
+
/**
|
|
849
|
+
* Ordered imports of template-library files into this component's template scope (esm-spec §9.7.2). Imported templates join the §9.6.3 effective declaration order ahead of local declarations (§9.7.4).
|
|
850
|
+
*/
|
|
851
|
+
expression_template_imports?: TemplateImport[];
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* An equation: lhs = rhs (or lhs ~ rhs in MTK notation).
|
|
855
|
+
*/
|
|
856
|
+
interface Equation {
|
|
857
|
+
lhs: Expression;
|
|
858
|
+
rhs: Expression;
|
|
859
|
+
_comment?: string;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Fires when a boolean condition is true at end of a timestep, or at preset/periodic times. Maps to MTK SymbolicDiscreteCallback. An event may affect UNKNOWNS ONLY: from 1.0.0 a parameter carries its own `update` block, so there is no `discrete_parameters` list and no `functional_affect` here — a handler only ever wrote parameters, and now lives on the parameter it writes.
|
|
863
|
+
*/
|
|
864
|
+
interface DiscreteEvent {
|
|
865
|
+
/**
|
|
866
|
+
* Human-readable identifier.
|
|
867
|
+
*/
|
|
868
|
+
name?: string;
|
|
869
|
+
trigger: DiscreteEventTrigger;
|
|
870
|
+
/**
|
|
871
|
+
* Affect equations. Every LHS MUST name an unknown (`event_affects_parameter` otherwise).
|
|
872
|
+
*/
|
|
873
|
+
affects: AffectEquation[];
|
|
874
|
+
/**
|
|
875
|
+
* Whether to reinitialize the system after the event.
|
|
876
|
+
*/
|
|
877
|
+
reinitialize?: boolean;
|
|
878
|
+
description?: string;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* An affect equation in an event: lhs is the target variable (string), rhs is an expression.
|
|
882
|
+
*/
|
|
883
|
+
interface AffectEquation {
|
|
884
|
+
/**
|
|
885
|
+
* Target variable name (value after the event).
|
|
886
|
+
*/
|
|
887
|
+
lhs: string;
|
|
888
|
+
/**
|
|
889
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
890
|
+
*/
|
|
891
|
+
rhs: Expression;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Fires when a condition expression crosses zero (root-finding). Maps to MTK SymbolicContinuousCallback. An event may affect UNKNOWNS ONLY; a parameter that changes on a zero crossing declares `update: {kind: "crossing", …}` on itself instead.
|
|
895
|
+
*/
|
|
896
|
+
interface ContinuousEvent {
|
|
897
|
+
/**
|
|
898
|
+
* Human-readable identifier.
|
|
899
|
+
*/
|
|
900
|
+
name?: string;
|
|
901
|
+
/**
|
|
902
|
+
* Expressions that trigger the event when they cross zero.
|
|
903
|
+
*
|
|
904
|
+
* @minItems 1
|
|
905
|
+
*/
|
|
906
|
+
conditions: [Expression, ...Expression[]];
|
|
907
|
+
/**
|
|
908
|
+
* Affect equations applied on positive-going zero crossings (or both directions if affect_neg is absent). Empty array for pure detection. Every LHS MUST name an unknown (`event_affects_parameter` otherwise).
|
|
909
|
+
*/
|
|
910
|
+
affects: AffectEquation[];
|
|
911
|
+
/**
|
|
912
|
+
* Separate affects for negative-going zero crossings. If null or absent, affects is used for both directions.
|
|
913
|
+
*/
|
|
914
|
+
affect_neg?: null | AffectEquation[];
|
|
915
|
+
/**
|
|
916
|
+
* Root-finding direction.
|
|
917
|
+
*/
|
|
918
|
+
root_find?: "left" | "right" | "all";
|
|
919
|
+
/**
|
|
920
|
+
* Whether to reinitialize the system after the event.
|
|
921
|
+
*/
|
|
922
|
+
reinitialize?: boolean;
|
|
923
|
+
description?: string;
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* A named external data source reduced to pure I/O: it locates, reads, decodes, slices, and filters bytes on disk. It performs no reprojection and no regridding, and — from 1.0.0 — it exposes no variables and is NOT a component. It cannot be a coupling endpoint, a subsystem, or a scoped-name path root; a model consumes it by declaring a parameter whose `update` names this source and binds one of its `file_variable`s. Grid geometry a source reads (coordinates, connectivity, metric arrays) arrives as ordinary parameters and is transformed downstream by `aggregate` FAQs and coupling expressions. Authentication and algorithm-specific tuning are runtime-only and not part of the schema.
|
|
927
|
+
*/
|
|
928
|
+
interface DataSource {
|
|
929
|
+
/**
|
|
930
|
+
* Structural kind of the dataset: 'grid' (gridded array source), 'points' (scattered point/station source), or 'static' (time-invariant source). Grid geometry the source reads — coordinates, connectivity, metric arrays — arrives as ordinary parameters bound to its `file_variable`s and is consumed by `aggregate` FAQs downstream; it needs no special descriptor. Scientific role (emissions, meteorology, elevation, ...) is not schema-validated and belongs in metadata.tags.
|
|
931
|
+
*/
|
|
932
|
+
kind: "grid" | "points" | "static";
|
|
933
|
+
source: DataSourceLocation;
|
|
934
|
+
temporal?: DataSourceTemporal;
|
|
935
|
+
determinism?: DataSourceDeterminism;
|
|
936
|
+
/**
|
|
937
|
+
* Format-specific DECODE options, passed through to the format reader verbatim (EarthSciIO calls them `reader_kwargs`): the zip `member_glob` and `skip_header_row` of an FF10 inventory, a GeoTIFF band naming, and so on. They say how bytes become an array, never what the array means — no remap, no unit conversion, no filtering (those are `variables`, `unit_conversion` and `record_filter`). A key the bound reader does not recognise MUST be an error, so a mis-spelled option cannot silently decode something else.
|
|
938
|
+
*/
|
|
939
|
+
reader_options?: {
|
|
940
|
+
[k: string]: unknown;
|
|
941
|
+
};
|
|
942
|
+
select?: DataSourceSelect;
|
|
943
|
+
record_filter?: DataSourceRecordFilter;
|
|
944
|
+
extent?: DataSourceExtent;
|
|
945
|
+
reference?: Reference;
|
|
946
|
+
/**
|
|
947
|
+
* Free-form metadata about the data source. The "tags" field (array of strings) is conventional for expressing scientific role (e.g. "emissions", "reanalysis") and is not schema-validated.
|
|
948
|
+
*/
|
|
949
|
+
metadata?: {
|
|
950
|
+
tags?: string[];
|
|
951
|
+
[k: string]: unknown;
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* File discovery configuration. Describes how to locate data files at runtime via URL templates with date/variable substitutions.
|
|
956
|
+
*/
|
|
957
|
+
interface DataSourceLocation {
|
|
958
|
+
/**
|
|
959
|
+
* Jinja-style URL template with substitutions. Supported: {date:<strftime>} (e.g. {date:%Y%m%d}), {var}, {sector}, {species}. Custom substitutions are allowed and the runtime must accept and pass them through.
|
|
960
|
+
*/
|
|
961
|
+
url_template: string;
|
|
962
|
+
/**
|
|
963
|
+
* Ordered fallback URL templates. Runtime tries each in order, first is primary. Follows the same substitution grammar as url_template.
|
|
964
|
+
*/
|
|
965
|
+
mirrors?: string[];
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Temporal coverage and record layout for a data source.
|
|
969
|
+
*/
|
|
970
|
+
interface DataSourceTemporal {
|
|
971
|
+
/**
|
|
972
|
+
* ISO 8601 datetime — first timestamp available from this source.
|
|
973
|
+
*/
|
|
974
|
+
start?: string;
|
|
975
|
+
/**
|
|
976
|
+
* ISO 8601 datetime — last timestamp available from this source.
|
|
977
|
+
*/
|
|
978
|
+
end?: string;
|
|
979
|
+
/**
|
|
980
|
+
* ISO 8601 duration describing how much time one file covers (e.g., "P1D", "P1M", "PT3H").
|
|
981
|
+
*/
|
|
982
|
+
file_period?: string;
|
|
983
|
+
/**
|
|
984
|
+
* ISO 8601 duration describing spacing between samples within a file.
|
|
985
|
+
*/
|
|
986
|
+
frequency?: string;
|
|
987
|
+
/**
|
|
988
|
+
* Number of time records per file. "auto" means read from file at runtime.
|
|
989
|
+
*/
|
|
990
|
+
records_per_file?: number | "auto";
|
|
991
|
+
/**
|
|
992
|
+
* Name of the time coordinate variable in the file. Used when records_per_file is absent or "auto". If both static declarations (records_per_file + frequency) and time_variable are present, the static declaration wins and time_variable is a fallback.
|
|
993
|
+
*/
|
|
994
|
+
time_variable?: string;
|
|
995
|
+
/**
|
|
996
|
+
* How many time records the source returns per query time — pure I/O; the source does NOT interpolate. Absent or 1 (default): the single at-or-before record, time axis dropped (piecewise-constant between ticks). 2: the two records bracketing the current time (floor + successor), returned with the time axis kept at length 2 so a downstream model can interpolate in time (e.g. linearly). Only 1 and 2 are supported; higher-order temporal stencils are future work. Contrast records_per_file (records IN one file).
|
|
997
|
+
*/
|
|
998
|
+
records_per_sample?: 1 | 2;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Reproducibility contract a binary-format loader advertises to bindings. A binding that cannot honor the declared endian / float_format / integer_width MUST reject the file at load rather than silently reinterpreting bytes.
|
|
1002
|
+
*/
|
|
1003
|
+
interface DataSourceDeterminism {
|
|
1004
|
+
/**
|
|
1005
|
+
* Byte order of on-wire numeric fields.
|
|
1006
|
+
*/
|
|
1007
|
+
endian?: "little" | "big";
|
|
1008
|
+
/**
|
|
1009
|
+
* Floating-point format of metric fields.
|
|
1010
|
+
*/
|
|
1011
|
+
float_format?: "ieee754_single" | "ieee754_double";
|
|
1012
|
+
/**
|
|
1013
|
+
* Integer width (in bits) of connectivity fields.
|
|
1014
|
+
*/
|
|
1015
|
+
integer_width?: 32 | 64;
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* A per-axis selection of what the source DELIVERS from an on-disk array — one entry per NATIVE array dimension, in native dims order. Declared on a source (the default for every parameter drawing from it) or on a single parameter's `from` binding (which overrides the source's). Two parameters of one source MAY read the same `file_variable` under different selections, which is how a full-grid field and a prefix of it are both declared instead of one being sliced by the caller. The selection is defined over the axis the loader DELIVERS, so it follows any `record_filter`: `range 0..200` on a filtered points table is the first 200 SURVIVING records. Whether a binding pushes it down to the reader (fetching only what it keeps) or applies it after the read is an optimization; the two MUST agree exactly.
|
|
1019
|
+
*/
|
|
1020
|
+
interface DataSourceSelect {
|
|
1021
|
+
/**
|
|
1022
|
+
* One selector per native array dimension, in native dims order.
|
|
1023
|
+
*
|
|
1024
|
+
* @minItems 1
|
|
1025
|
+
*/
|
|
1026
|
+
axes: [DataSourceSelectAxis, ...DataSourceSelectAxis[]];
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Which records of a `points` source are DELIVERED. The surviving mask is computed ONCE for the source and applied to every parameter drawing from it, so its columns can never fall out of alignment, and the surviving count is the source's `extent`. A record is dropped when any `require_finite` variable is non-finite at it, or when a `codes` map with `unmapped: "drop"` does not recognise its value.
|
|
1030
|
+
*/
|
|
1031
|
+
interface DataSourceRecordFilter {
|
|
1032
|
+
/**
|
|
1033
|
+
* `file_variable` names whose value must be finite for a record to survive. (Pre-1.0.0 this named loader variable names; a source has no variables of its own now, so it names the file's.) A point with no coordinate cannot be placed and a row with no annual total cannot be weighted; dropping it is a declaration about the source, rather than a NaN travelling into the model to surface as an empty result later.
|
|
1034
|
+
*
|
|
1035
|
+
* @minItems 1
|
|
1036
|
+
*/
|
|
1037
|
+
require_finite?: [string, ...string[]];
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Binds the source's DELIVERED record count to a metaparameter, for a source whose extent is not knowable until it is read. A binding samples such a source BEFORE it closes metaparameters (esm-spec §9.7.6 site 4), so an index set declared `size: "N_REC"` is sized by the data itself and no caller counts rows and passes the number in. Every parameter drawing from the source MUST agree on the count — that agreement is also the alignment check.
|
|
1041
|
+
*/
|
|
1042
|
+
interface DataSourceExtent {
|
|
1043
|
+
/**
|
|
1044
|
+
* Name of the `metaparameters` entry it binds. Declare that entry with a `default` (conventionally 0) so the document still validates and loads standalone.
|
|
1045
|
+
*/
|
|
1046
|
+
metaparameter: string;
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* A reference to an external ESM file containing a model or reaction system definition. The ref field can be a relative or absolute local file path, or an HTTP/HTTPS URL. Relative paths are resolved relative to the directory of the referencing file.
|
|
1050
|
+
*/
|
|
1051
|
+
interface SubsystemRef {
|
|
1052
|
+
/**
|
|
1053
|
+
* Local file path or URL pointing to an ESM file. The referenced file must contain exactly one top-level model or reaction system (unless `model` / `reaction_system` selects one of several), which is used as the subsystem definition (esm-spec.md §4.7).
|
|
1054
|
+
*/
|
|
1055
|
+
ref: string;
|
|
1056
|
+
/**
|
|
1057
|
+
* Optional model selector. When the referenced file defines more than one top-level model, names which one to splice in. Omit for single-model files. Lets a multi-model component library (e.g. an ESD regridder file holding several kernels) be referenced by one of its models.
|
|
1058
|
+
*/
|
|
1059
|
+
model?: string;
|
|
1060
|
+
/**
|
|
1061
|
+
* Optional reaction-system selector. When the referenced file defines more than one top-level reaction system, names which one to splice in. Omit for single-reaction-system files. The reaction-system analogue of `model`, used when a top-level `reaction_systems` entry is a `{ref}` stub (esm-spec.md §4.7).
|
|
1062
|
+
*/
|
|
1063
|
+
reaction_system?: string;
|
|
1064
|
+
/**
|
|
1065
|
+
* Bindings closing the referenced document's metaparameters (esm-spec §9.7.6 site 3). Each value is a metaparameter expression over the MOUNTING document's metaparameters (an integer literal, or e.g. `NX*NY`), folded to a concrete integer at the mount.
|
|
1066
|
+
*/
|
|
1067
|
+
bindings?: {
|
|
1068
|
+
[k: string]: MetaparameterExpression;
|
|
1069
|
+
};
|
|
1070
|
+
/**
|
|
1071
|
+
* Template-library imports registered into the REFERENCED component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a mounted PDE component, without editing the leaf file. Same entry shape as §9.7.2; target implicit (this edge mounts one component). Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
1072
|
+
*/
|
|
1073
|
+
expression_template_imports?: TemplateImport[];
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* One entry of `expression_template_imports` (esm-spec §9.7.2): imports the templates (and index_sets / open metaparameters) of a template-library file. `ref` uses the §4.7 reference formats (relative path, absolute path, or URL), resolved at load before validation with canonical-path cycle detection (`template_import_cycle`). `only` filters which template names become visible to the importer (`template_import_unknown_name` for unknown names). `bindings` closes the target document's open metaparameters to integers at this edge (esm-spec §9.7.6); metaparameters left unbound are re-exported into the importing document's scope. `prefix` / `rename` namespace the surviving exported names (templates after `only`, index sets, still-open metaparameters) into the importer's vocabulary, applied transitively through every occurrence inside the imported declarations; `rebind` rewrites free variable names (keyed factors and other free names in template bodies) at the same point (esm-spec §9.7.7). Renaming happens after this edge's `bindings` instantiation and `only` filtering and before the §9.7.4/§9.7.5 merge, so the same file imported under different renames registers as distinct instances while identical edges dedupe. Identifier grammar, unknown-name, and collision checks are resolver-level (`template_import_rename_invalid`, `template_import_rename_unknown_name`, `template_import_rebind_unknown_name`, `template_import_rename_collision`).
|
|
1077
|
+
*/
|
|
1078
|
+
interface TemplateImport {
|
|
1079
|
+
/**
|
|
1080
|
+
* Path or URL of a template-library file, per the §4.7 reference-format table.
|
|
1081
|
+
*/
|
|
1082
|
+
ref: string;
|
|
1083
|
+
/**
|
|
1084
|
+
* Template names to import; absent = all.
|
|
1085
|
+
*
|
|
1086
|
+
* @minItems 1
|
|
1087
|
+
*/
|
|
1088
|
+
only?: [string, ...string[]];
|
|
1089
|
+
/**
|
|
1090
|
+
* Bindings closing the target document's metaparameters at this edge (esm-spec §9.7.6 site 1). Each value is a metaparameter expression over the importing document's metaparameters; a value with still-open names is carried symbolically and folds at the importer's close.
|
|
1091
|
+
*/
|
|
1092
|
+
bindings?: {
|
|
1093
|
+
[k: string]: MetaparameterExpression;
|
|
1094
|
+
};
|
|
1095
|
+
/**
|
|
1096
|
+
* Namespace prefix: every surviving exported name without an explicit `rename` entry is renamed to `<prefix>.<name>` (esm-spec §9.7.7). Grammar (resolver-enforced): dotted identifier segments [A-Za-z_][A-Za-z0-9_]*.
|
|
1097
|
+
*/
|
|
1098
|
+
prefix?: string;
|
|
1099
|
+
/**
|
|
1100
|
+
* Explicit renames, exported name → importer-visible name; entries override `prefix`. Keys must name a surviving export (`template_import_rename_unknown_name`); targets are dotted identifiers (esm-spec §9.7.7).
|
|
1101
|
+
*/
|
|
1102
|
+
rename?: {
|
|
1103
|
+
[k: string]: string;
|
|
1104
|
+
};
|
|
1105
|
+
/**
|
|
1106
|
+
* Free-name rebinding, free name → replacement variable name (e.g. areaCell → meshA.areaCell): rewrites free variable names occurring in the imported template bodies/matches and ragged index-set offsets/values factors. Keys must occur free in the surviving declarations (`template_import_rebind_unknown_name`) (esm-spec §9.7.7).
|
|
1107
|
+
*/
|
|
1108
|
+
rebind?: {
|
|
1109
|
+
[k: string]: string;
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Model-level default numerical tolerance for tests, used when a test or assertion does not provide its own.
|
|
1114
|
+
*/
|
|
1115
|
+
interface Tolerance {
|
|
1116
|
+
/**
|
|
1117
|
+
* Absolute tolerance: |actual - expected| <= abs.
|
|
1118
|
+
*/
|
|
1119
|
+
abs?: number;
|
|
1120
|
+
/**
|
|
1121
|
+
* Relative tolerance: |actual - expected| / max(|expected|, epsilon) <= rel.
|
|
1122
|
+
*/
|
|
1123
|
+
rel?: number;
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* An inline validation test for the enclosing model or reaction system. Defines the run configuration (initial conditions, parameter overrides, time span) and the scalar assertions that must hold.
|
|
1127
|
+
*/
|
|
1128
|
+
interface Test {
|
|
1129
|
+
/**
|
|
1130
|
+
* Identifier unique within this component's tests array.
|
|
1131
|
+
*/
|
|
1132
|
+
id: string;
|
|
1133
|
+
/**
|
|
1134
|
+
* Human-readable description of what this test verifies.
|
|
1135
|
+
*/
|
|
1136
|
+
description?: string;
|
|
1137
|
+
/**
|
|
1138
|
+
* Initial-value overrides for unknowns, keyed by variable name (local to this component). Values not listed fall back to the variable's declared default.
|
|
1139
|
+
*/
|
|
1140
|
+
initial_conditions?: {
|
|
1141
|
+
[k: string]: number;
|
|
1142
|
+
};
|
|
1143
|
+
/**
|
|
1144
|
+
* Parameter overrides, keyed by parameter name (local to this component). Values not listed fall back to the parameter's declared default.
|
|
1145
|
+
*/
|
|
1146
|
+
parameter_overrides?: {
|
|
1147
|
+
[k: string]: number;
|
|
1148
|
+
};
|
|
1149
|
+
time_span: TimeSpan;
|
|
1150
|
+
tolerance?: Tolerance1;
|
|
1151
|
+
/**
|
|
1152
|
+
* Template-library imports registered into the ENCLOSING component's template scope for THIS run only (esm-spec §9.7.10 / §6.6) — lets a discretization-agnostic PDE component's inline tests run under a per-test discretization chosen without editing the leaf. Same entry shape as §9.7.2; target implicit (the enclosing component). Execution-time (ephemeral per-run build); authored per-run configuration, so it DOES survive parse→emit (peer of parameter_overrides / tolerance).
|
|
1153
|
+
*/
|
|
1154
|
+
expression_template_imports?: TemplateImport[];
|
|
1155
|
+
/**
|
|
1156
|
+
* Scalar (variable, time) checks that define the pass/fail criterion of the test.
|
|
1157
|
+
*
|
|
1158
|
+
* @minItems 1
|
|
1159
|
+
*/
|
|
1160
|
+
assertions: [Assertion, ...Assertion1[]];
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Simulation time interval expressed in the component's time units.
|
|
1164
|
+
*/
|
|
1165
|
+
interface TimeSpan {
|
|
1166
|
+
start: number;
|
|
1167
|
+
end: number;
|
|
1168
|
+
}
|
|
1169
|
+
/**
|
|
1170
|
+
* Test-level default tolerance applied to all assertions in this test that do not override it.
|
|
1171
|
+
*/
|
|
1172
|
+
interface Tolerance1 {
|
|
1173
|
+
/**
|
|
1174
|
+
* Absolute tolerance: |actual - expected| <= abs.
|
|
1175
|
+
*/
|
|
1176
|
+
abs?: number;
|
|
1177
|
+
/**
|
|
1178
|
+
* Relative tolerance: |actual - expected| / max(|expected|, epsilon) <= rel.
|
|
1179
|
+
*/
|
|
1180
|
+
rel?: number;
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Per-assertion tolerance override. If present, this takes precedence over the test-level and model-level defaults.
|
|
1184
|
+
*/
|
|
1185
|
+
interface Tolerance2 {
|
|
1186
|
+
/**
|
|
1187
|
+
* Absolute tolerance: |actual - expected| <= abs.
|
|
1188
|
+
*/
|
|
1189
|
+
abs?: number;
|
|
1190
|
+
/**
|
|
1191
|
+
* Relative tolerance: |actual - expected| / max(|expected|, epsilon) <= rel.
|
|
1192
|
+
*/
|
|
1193
|
+
rel?: number;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* An inline illustrative analysis of how to run the enclosing component. Defines the run configuration and one or more plots derived from the result.
|
|
1197
|
+
*/
|
|
1198
|
+
interface Analysis {
|
|
1199
|
+
/**
|
|
1200
|
+
* Identifier unique within this component's analyses array.
|
|
1201
|
+
*/
|
|
1202
|
+
id: string;
|
|
1203
|
+
/**
|
|
1204
|
+
* Human-readable description of what this analysis illustrates.
|
|
1205
|
+
*/
|
|
1206
|
+
description?: string;
|
|
1207
|
+
/**
|
|
1208
|
+
* Initial state for this analysis run. Either (legacy) a flat map of scalar overrides keyed by state-variable name, or the esm-spec §11.4 discriminated union: {type:"per_variable", values:{name:number}} for scalar ICs, or {type:"expression", values:{name:<expression>}} for closed-form spatial FIELD initial conditions (per-cell coordinate expressions). Field ICs may also be declared with `ic` equations in the model.
|
|
1209
|
+
*/
|
|
1210
|
+
initial_state?: {
|
|
1211
|
+
[k: string]: number;
|
|
1212
|
+
} | {
|
|
1213
|
+
type: "per_variable" | "expression";
|
|
1214
|
+
/**
|
|
1215
|
+
* For type=per_variable each value is a scalar number; for type=expression each value is an expression AST (a closed-form per-cell field over the state's index sets).
|
|
1216
|
+
*/
|
|
1217
|
+
values: {
|
|
1218
|
+
[k: string]: unknown;
|
|
1219
|
+
};
|
|
1220
|
+
};
|
|
1221
|
+
/**
|
|
1222
|
+
* Parameter overrides, keyed by parameter name (local to this component).
|
|
1223
|
+
*/
|
|
1224
|
+
parameters?: {
|
|
1225
|
+
[k: string]: number;
|
|
1226
|
+
};
|
|
1227
|
+
time_span: TimeSpan;
|
|
1228
|
+
parameter_sweep?: ParameterSweep;
|
|
1229
|
+
/**
|
|
1230
|
+
* Plot specifications derived from this analysis's run(s).
|
|
1231
|
+
*/
|
|
1232
|
+
plots?: Plot[];
|
|
1233
|
+
/**
|
|
1234
|
+
* Template-library imports registered into the ENCLOSING component's template scope for THIS run only (esm-spec §9.7.10 / §6.7) — lets a discretization-agnostic PDE component's inline analyses run under a per-run discretization chosen without editing the leaf. Same entry shape as §9.7.2; target implicit (the enclosing component). Execution-time (ephemeral per-run build); authored per-run configuration, so it DOES survive parse→emit (peer of parameters / parameter_sweep).
|
|
1235
|
+
*/
|
|
1236
|
+
expression_template_imports?: TemplateImport[];
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Optional parameter sweep. When present, the analysis represents a family of runs (one per Cartesian combination) rather than a single trajectory.
|
|
1240
|
+
*/
|
|
1241
|
+
interface ParameterSweep {
|
|
1242
|
+
/**
|
|
1243
|
+
* Sweep combination strategy. Currently only cartesian (full Cartesian product) is supported.
|
|
1244
|
+
*/
|
|
1245
|
+
type: "cartesian";
|
|
1246
|
+
/**
|
|
1247
|
+
* @minItems 1
|
|
1248
|
+
*/
|
|
1249
|
+
dimensions: [SweepDimension, ...SweepDimension1[]];
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Generated range; mutually exclusive with values.
|
|
1253
|
+
*/
|
|
1254
|
+
interface SweepRange {
|
|
1255
|
+
start: number;
|
|
1256
|
+
stop: number;
|
|
1257
|
+
count: number;
|
|
1258
|
+
/**
|
|
1259
|
+
* Spacing: linear = evenly spaced between start and stop; log = logarithmically spaced (start and stop must be strictly positive).
|
|
1260
|
+
*/
|
|
1261
|
+
scale?: "linear" | "log";
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Axis specification: any unknown, parameter name, or swept parameter may be used.
|
|
1265
|
+
*/
|
|
1266
|
+
interface PlotAxis {
|
|
1267
|
+
/**
|
|
1268
|
+
* Variable or parameter name (local to this component or scoped within a subsystem).
|
|
1269
|
+
*/
|
|
1270
|
+
variable: string;
|
|
1271
|
+
/**
|
|
1272
|
+
* Human-readable axis label. Viewers should fall back to the variable name if omitted.
|
|
1273
|
+
*/
|
|
1274
|
+
label?: string;
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* Required for heatmap; defines the color channel. Ignored for line/scatter. For field_snapshot, the variable plotted as the color channel (use `value.variable`); `at_time` and `reduce` are ignored — the field is sampled at `at_time` declared on the plot.
|
|
1278
|
+
*/
|
|
1279
|
+
interface PlotValue {
|
|
1280
|
+
/**
|
|
1281
|
+
* Variable whose trajectory is reduced to a scalar per run.
|
|
1282
|
+
*/
|
|
1283
|
+
variable: string;
|
|
1284
|
+
/**
|
|
1285
|
+
* Specific simulation time at which to sample the variable.
|
|
1286
|
+
*/
|
|
1287
|
+
at_time?: number;
|
|
1288
|
+
/**
|
|
1289
|
+
* Time-reduction applied to the trajectory: max/min/mean over the run, time integral, or the final value at time_span.end.
|
|
1290
|
+
*/
|
|
1291
|
+
reduce?: "max" | "min" | "mean" | "integral" | "final";
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* A single named series for multi-series line or scatter plots.
|
|
1295
|
+
*/
|
|
1296
|
+
interface PlotSeries {
|
|
1297
|
+
name: string;
|
|
1298
|
+
variable: string;
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* A single in-file rewrite rule / Expression-AST template (esm-spec §9.6 / docs/rfcs/ast-expression-templates.md). The `params` are metavariables; the `body` is the replacement Expression AST in which parameter occurrences are written as bare parameter-name strings. The template is applied in one of two ways. (1) WITHOUT `match`: it is invoked explicitly by name through an `apply_expression_template` node, whose `bindings` supply each parameter's AST. (2) WITH `match`: it is an auto-applied rewrite rule — `match` is a pattern Expression in which parameters are wildcards (a parameter in an operand/`args` position binds to the matched sub-AST; a parameter in a scalar field such as `dim`/`side` binds to the matched literal), and the rule fires wherever the pattern structurally matches a node. This unifies variable substitution (a bare-metavar `match`), named-template expansion (no `match`), and rewrite-target-op lowering (an operator `match` like `{op:'D', args:['f'], wrt:'x'}` → an `aggregate`/`makearray` stencil). Either way the `body` is instantiated by pure structural substitution of the bound metavariables — no evaluation, no metaprogramming. Rewriting is an outermost-first, priority-ordered, bounded-fixpoint load-time process (esm-spec §9.6.3): each pass is a pre-order walk that fires, at each node, the matching rule of highest `priority` (ties broken by declaration order); passes repeat to a fixpoint or until MAX_REWRITE_PASSES=64, at which point a non-converging rule set is rejected with diagnostic 'rewrite_rule_nonterminating'. A rewrite-target op (esm-spec §4.2) surviving the fixpoint into an evaluation position is rejected with diagnostic 'unlowered_operator'. A `body` MAY contain `apply_expression_template` nodes referencing other match-less in-scope templates (declared locally or imported, esm-spec §9.7.2); these are checked at registration time as a statically-checked acyclic DAG (cycles rejected with 'apply_expression_template_recursive_body'; chains deeper than MAX_TEMPLATE_EXPANSION_DEPTH=32 rejected with 'template_body_expansion_too_deep'); from esm 0.9.0 they are preserved uninlined and denote their expansion (Option B, esm-spec §9.6.4; pre-0.9.0 loaders inlined them here by pure substitution). `match` patterns MUST NOT contain `apply_expression_template` nodes. An optional `where` block adds static match-scoping constraints on the captured parameters (declared-shape/index-set scoping, filtered before priority selection — see the `where` property and esm-spec §9.6.1).
|
|
1302
|
+
*/
|
|
1303
|
+
interface ExpressionTemplate {
|
|
1304
|
+
/**
|
|
1305
|
+
* Ordered list of parameter (metavariable) names. MUST be unique within this template; MAY be empty (a zero-parameter template is a named constant fragment, common in library files). Each name occurs zero or more times inside `body` and (when present) `match`; for an explicitly-invoked template every name MUST also appear as a key in every `apply_expression_template.bindings` referencing it.
|
|
1306
|
+
*
|
|
1307
|
+
* @minItems 0
|
|
1308
|
+
*/
|
|
1309
|
+
params: string[];
|
|
1310
|
+
/**
|
|
1311
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
1312
|
+
*/
|
|
1313
|
+
match?: Expression;
|
|
1314
|
+
/**
|
|
1315
|
+
* Optional static match-scoping constraints for an auto-applied (`match`) rule (esm-spec §9.6.1; docs/rfcs/match-pattern-scoping-constraints.md). Keys are declared `params`; each value is a constraint object — the v1 vocabulary is exactly one kind, `shape`: an ordered list of index-set names as spelled in the CONSUMING document's merged index_sets registry (esm-spec §9.7.5, composing with import-edge index-set renaming). After the pattern structurally matches, the rule is eligible only if every constrained parameter bound to a BARE variable reference whose declaration in the enclosing component carries exactly that `shape` (same names, same order); a compound sub-AST, literal, scoped reference, undeclared name, or scalar fails the constraint. Evaluation is fully static — declared shapes at lowering time, never runtime values — and is part of match ELIGIBILITY: it filters BEFORE the §9.6.3 priority/declaration-order selection, so a constraint-excluded rule is simply a non-matching rule at that node. A constraint naming an index set absent from the consuming document's registry is rejected at rule registration with 'template_constraint_unknown_index_set'; a constrained rule that never fires is NOT an error (an un-lowered rewrite-target op is caught by the ordinary 'unlowered_operator' gate). Admissible only alongside `match` (else 'apply_expression_template_invalid_declaration').
|
|
1316
|
+
*/
|
|
1317
|
+
where?: {
|
|
1318
|
+
[k: string]: {
|
|
1319
|
+
/**
|
|
1320
|
+
* @minItems 1
|
|
1321
|
+
*/
|
|
1322
|
+
shape: [string, ...string[]];
|
|
1323
|
+
};
|
|
1324
|
+
};
|
|
1325
|
+
/**
|
|
1326
|
+
* Selection precedence for an auto-applied (`match`) rule (esm-spec §9.6.3). When more than one rule matches a node, the highest `priority` wins; ties break by declaration order. This lets a compound-term rule (Godunov / WENO / flux-limited) out-rank the plain per-derivative rule so it fires on the whole compound before the inner derivatives are lowered. Ignored when `match` is absent. Absent ⇒ 0.
|
|
1327
|
+
*/
|
|
1328
|
+
priority?: number;
|
|
1329
|
+
/**
|
|
1330
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
1331
|
+
*/
|
|
1332
|
+
body: Expression;
|
|
1333
|
+
description?: string;
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* A reaction network — declarative representation of chemical or biological reactions.
|
|
1337
|
+
*/
|
|
1338
|
+
interface ReactionSystem {
|
|
1339
|
+
reference?: Reference;
|
|
1340
|
+
/**
|
|
1341
|
+
* Named reactive species.
|
|
1342
|
+
*/
|
|
1343
|
+
species: {
|
|
1344
|
+
[k: string]: Species;
|
|
1345
|
+
};
|
|
1346
|
+
/**
|
|
1347
|
+
* Named parameters (rate constants, temperature, photolysis rates, etc.).
|
|
1348
|
+
*/
|
|
1349
|
+
parameters: {
|
|
1350
|
+
[k: string]: Parameter;
|
|
1351
|
+
};
|
|
1352
|
+
/**
|
|
1353
|
+
* Array of reaction definitions.
|
|
1354
|
+
*
|
|
1355
|
+
* @minItems 1
|
|
1356
|
+
*/
|
|
1357
|
+
reactions: [Reaction, ...Reaction[]];
|
|
1358
|
+
/**
|
|
1359
|
+
* Additional algebraic or ODE constraints.
|
|
1360
|
+
*/
|
|
1361
|
+
constraint_equations?: Equation[];
|
|
1362
|
+
discrete_events?: DiscreteEvent[];
|
|
1363
|
+
continuous_events?: ContinuousEvent[];
|
|
1364
|
+
/**
|
|
1365
|
+
* Named child reaction systems (subsystems), keyed by unique identifier. Enables hierarchical system composition. Variables in subsystems are referenced via dot notation: "ParentSystem.ChildSystem.species". Each subsystem can be defined inline or included by reference via a local file path or URL.
|
|
1366
|
+
*/
|
|
1367
|
+
subsystems?: {
|
|
1368
|
+
[k: string]: ReactionSystem | SubsystemRef;
|
|
1369
|
+
};
|
|
1370
|
+
tolerance?: Tolerance3;
|
|
1371
|
+
/**
|
|
1372
|
+
* Inline validation tests that exercise this reaction system in isolation. Each test specifies initial conditions, parameter overrides, a time span, and scalar assertions at specific (species/variable, time) points.
|
|
1373
|
+
*/
|
|
1374
|
+
tests?: Test[];
|
|
1375
|
+
/**
|
|
1376
|
+
* Inline illustrative analyses of how to run this reaction system. Each analysis specifies initial state, parameters, a time span, an optional parameter sweep, and plot specifications.
|
|
1377
|
+
*/
|
|
1378
|
+
analyses?: Analysis[];
|
|
1379
|
+
/**
|
|
1380
|
+
* Component-scoped in-file Expression-AST templates (v0.4.0; docs/rfcs/ast-expression-templates.md). Each entry names a fixed Expression body with parameter substitution slots; `apply_expression_template` AST nodes elsewhere in this component (typically inside `reactions[*].rate`) reference the entry by key with per-parameter bindings. Templates are component-local: declarations here are visible only within this reaction system's expression positions. A body MAY reference other match-less in-scope templates as a statically-checked acyclic DAG — no cycles, no recursion (esm-spec §9.7.3). From esm 0.9.0 the round-trip is Option B (reference-preserving, esm-spec §9.6.4): references survive load and parse-then-emit and denote their expansion (`Expand`); eager (target-bearing) references still expand at load; emit materializes referenced templates into this registry — authored entries first in authored order, then materialized entries in lexicographic UTF-8 name order; keys may be dotted post-rename names. Pre-0.9.0 loaders expanded every reference at load (Option A) and emitted the expanded form.
|
|
1381
|
+
*/
|
|
1382
|
+
expression_templates?: {
|
|
1383
|
+
[k: string]: ExpressionTemplate;
|
|
1384
|
+
};
|
|
1385
|
+
/**
|
|
1386
|
+
* Ordered imports of template-library files into this component's template scope (esm-spec §9.7.2). Imported templates join the §9.6.3 effective declaration order ahead of local declarations (§9.7.4).
|
|
1387
|
+
*/
|
|
1388
|
+
expression_template_imports?: TemplateImport[];
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* A reactive species in a reaction system.
|
|
1392
|
+
*/
|
|
1393
|
+
interface Species {
|
|
1394
|
+
units?: string;
|
|
1395
|
+
default?: number;
|
|
1396
|
+
/**
|
|
1397
|
+
* Units of the default value, if different from the declared units field. See ModelVariable.default_units for semantics.
|
|
1398
|
+
*/
|
|
1399
|
+
default_units?: string;
|
|
1400
|
+
description?: string;
|
|
1401
|
+
/**
|
|
1402
|
+
* When true, the species participates in reactions as a reactant/product but its concentration is held fixed (no ODE integration) — a reservoir species. Maps to Catalyst's @species [isconstantspecies=true]. Absent or false means an ordinary state species with an ODE.
|
|
1403
|
+
*/
|
|
1404
|
+
constant?: boolean;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* A single reaction in a reaction system.
|
|
1408
|
+
*/
|
|
1409
|
+
interface Reaction {
|
|
1410
|
+
/**
|
|
1411
|
+
* Unique reaction identifier (e.g., "R1").
|
|
1412
|
+
*/
|
|
1413
|
+
id: string;
|
|
1414
|
+
name?: string;
|
|
1415
|
+
/**
|
|
1416
|
+
* Array of {species, stoichiometry} or null for source reactions (∅ → X).
|
|
1417
|
+
*/
|
|
1418
|
+
substrates: null | [StoichiometryEntry, ...StoichiometryEntry[]];
|
|
1419
|
+
/**
|
|
1420
|
+
* Array of {species, stoichiometry} or null for sink reactions (X → ∅).
|
|
1421
|
+
*/
|
|
1422
|
+
products: null | [StoichiometryEntry, ...StoichiometryEntry[]];
|
|
1423
|
+
/**
|
|
1424
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
1425
|
+
*/
|
|
1426
|
+
rate: Expression;
|
|
1427
|
+
reference?: Reference;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* A species with its stoichiometric coefficient in a reaction. Coefficients MUST be positive and finite (NaN / ±Infinity are rejected at parse time). Fractional values are supported to preserve fidelity with atmospheric-chemistry mechanisms whose products include non-integer yields (e.g. `0.87 CH2O`, `1.86 CH3O2`). Integer values remain valid — they are a subset of the permitted number range.
|
|
1431
|
+
*/
|
|
1432
|
+
interface StoichiometryEntry {
|
|
1433
|
+
species: string;
|
|
1434
|
+
stoichiometry: number;
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* System-level default numerical tolerance for tests, used when a test or assertion does not provide its own.
|
|
1438
|
+
*/
|
|
1439
|
+
interface Tolerance3 {
|
|
1440
|
+
/**
|
|
1441
|
+
* Absolute tolerance: |actual - expected| <= abs.
|
|
1442
|
+
*/
|
|
1443
|
+
abs?: number;
|
|
1444
|
+
/**
|
|
1445
|
+
* Relative tolerance: |actual - expected| / max(|expected|, epsilon) <= rel.
|
|
1446
|
+
*/
|
|
1447
|
+
rel?: number;
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* A file-local enum mapping symbolic names to positive integers (esm-spec.md §9.3). Within a single enum, integer values MUST be unique. Across enums, values MAY collide (each enum is its own namespace). Bindings resolve enum-op nodes at load time before evaluating expressions.
|
|
1451
|
+
*/
|
|
1452
|
+
interface EnumDeclaration {
|
|
1453
|
+
[k: string]: number;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Match LHS time derivatives and add RHS terms together.
|
|
1457
|
+
*/
|
|
1458
|
+
interface CouplingOperatorCompose {
|
|
1459
|
+
type: "operator_compose";
|
|
1460
|
+
/**
|
|
1461
|
+
* The two systems to compose.
|
|
1462
|
+
*
|
|
1463
|
+
* @minItems 2
|
|
1464
|
+
* @maxItems 2
|
|
1465
|
+
*/
|
|
1466
|
+
systems: [string, string];
|
|
1467
|
+
/**
|
|
1468
|
+
* Variable mappings when LHS variables don't have matching names.
|
|
1469
|
+
*/
|
|
1470
|
+
translate?: {
|
|
1471
|
+
[k: string]: TranslateTarget;
|
|
1472
|
+
};
|
|
1473
|
+
/**
|
|
1474
|
+
* Strategy for mapping between 0D and spatial systems.
|
|
1475
|
+
*/
|
|
1476
|
+
lifting?: "pointwise" | "broadcast" | "mean" | "integral";
|
|
1477
|
+
/**
|
|
1478
|
+
* Map from a target system referenced by this coupling entry to the template-library imports registered into THAT component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a PDE component as it is wired into the assembly. Each key MUST name a model/reaction-system this entry references (template_inject_target_unknown otherwise); a key resolving to neither a model nor a reaction system is template_inject_target_not_component -- which from 1.0.0 is also how a key naming a `data_sources` entry is reported, since a data source is not a component and the separate template_inject_target_is_loader code is retired. Values use the §9.7.2 entry shape. Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
1479
|
+
*/
|
|
1480
|
+
expression_template_imports?: {
|
|
1481
|
+
[k: string]: TemplateImport[];
|
|
1482
|
+
};
|
|
1483
|
+
description?: string;
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Bi-directional coupling via explicit ConnectorSystem equations.
|
|
1487
|
+
*/
|
|
1488
|
+
interface CouplingCouple {
|
|
1489
|
+
type: "couple";
|
|
1490
|
+
/**
|
|
1491
|
+
* @minItems 2
|
|
1492
|
+
* @maxItems 2
|
|
1493
|
+
*/
|
|
1494
|
+
systems: [string, string];
|
|
1495
|
+
connector: {
|
|
1496
|
+
/**
|
|
1497
|
+
* @minItems 1
|
|
1498
|
+
*/
|
|
1499
|
+
equations: [ConnectorEquation, ...ConnectorEquation[]];
|
|
1500
|
+
};
|
|
1501
|
+
/**
|
|
1502
|
+
* Strategy for mapping between 0D and spatial systems.
|
|
1503
|
+
*/
|
|
1504
|
+
lifting?: "pointwise" | "broadcast" | "mean" | "integral";
|
|
1505
|
+
/**
|
|
1506
|
+
* Map from a target system referenced by this coupling entry to the template-library imports registered into THAT component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a PDE component as it is wired into the assembly. Each key MUST name a model/reaction-system this entry references (template_inject_target_unknown otherwise); a key resolving to neither a model nor a reaction system is template_inject_target_not_component -- which from 1.0.0 is also how a key naming a `data_sources` entry is reported, since a data source is not a component and the separate template_inject_target_is_loader code is retired. Values use the §9.7.2 entry shape. Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
1507
|
+
*/
|
|
1508
|
+
expression_template_imports?: {
|
|
1509
|
+
[k: string]: TemplateImport[];
|
|
1510
|
+
};
|
|
1511
|
+
description?: string;
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* A single equation in a ConnectorSystem linking two coupled systems.
|
|
1515
|
+
*/
|
|
1516
|
+
interface ConnectorEquation {
|
|
1517
|
+
/**
|
|
1518
|
+
* Source variable (scoped reference).
|
|
1519
|
+
*/
|
|
1520
|
+
from: string;
|
|
1521
|
+
/**
|
|
1522
|
+
* Target variable (scoped reference).
|
|
1523
|
+
*/
|
|
1524
|
+
to: string;
|
|
1525
|
+
/**
|
|
1526
|
+
* How the expression modifies the target.
|
|
1527
|
+
*/
|
|
1528
|
+
transform: "additive" | "multiplicative" | "replacement";
|
|
1529
|
+
/**
|
|
1530
|
+
* Mathematical expression: a number literal, a variable/parameter reference string, or an operator node.
|
|
1531
|
+
*/
|
|
1532
|
+
expression?: Expression;
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Register a callback for simulation events.
|
|
1536
|
+
*/
|
|
1537
|
+
interface CouplingCallback {
|
|
1538
|
+
type: "callback";
|
|
1539
|
+
/**
|
|
1540
|
+
* Registered identifier for the callback.
|
|
1541
|
+
*/
|
|
1542
|
+
callback_id: string;
|
|
1543
|
+
config?: {
|
|
1544
|
+
[k: string]: unknown;
|
|
1545
|
+
};
|
|
1546
|
+
/**
|
|
1547
|
+
* Map from a target system referenced by this coupling entry to the template-library imports registered into THAT component's template scope (esm-spec §9.7.10) — assembler-chosen discretization for a PDE component as it is wired into the assembly. Each key MUST name a model/reaction-system this entry references (template_inject_target_unknown otherwise); a key resolving to neither a model nor a reaction system is template_inject_target_not_component -- which from 1.0.0 is also how a key naming a `data_sources` entry is reported, since a data source is not a component and the separate template_inject_target_is_loader code is retired. Values use the §9.7.2 entry shape. Load-time only; consumed by the §9.6.3 fixpoint; does not survive parse→emit.
|
|
1548
|
+
*/
|
|
1549
|
+
expression_template_imports?: {
|
|
1550
|
+
[k: string]: TemplateImport[];
|
|
1551
|
+
};
|
|
1552
|
+
description?: string;
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Reuse of a coupling-library file (esm-spec §10.9, §10.10): imports the library named by `ref` and binds each of its declared roles to a component in the assembly. Expands at flatten into concrete variable_map/couple/operator_compose/event edges by substituting bound actuals for role names; the entry itself round-trips intact. Carries no `expression_template_imports` (injection is a property of the wiring entries, not of an import indirection).
|
|
1556
|
+
*/
|
|
1557
|
+
interface CouplingImport {
|
|
1558
|
+
type: "coupling_import";
|
|
1559
|
+
/**
|
|
1560
|
+
* §4.7 reference (relative path, absolute path, URL, or ${VAR}) to a coupling-library file (a document with top-level `coupling_roles`).
|
|
1561
|
+
*/
|
|
1562
|
+
ref: string;
|
|
1563
|
+
/**
|
|
1564
|
+
* Total map from every library role name to a scoped component reference in the assembly (esm-spec §10.10.1). Each value names a top-level or nested models/reaction_systems component (a system node), not a variable. No role may be omitted; there is no auto-binding.
|
|
1565
|
+
*/
|
|
1566
|
+
bind?: {
|
|
1567
|
+
[k: string]: string;
|
|
1568
|
+
};
|
|
1569
|
+
description?: string;
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* The single temporal domain shared by every component in the document (temporal extent + numeric representation). A document has at most one domain; all spatial models live on it, and 0-D models simply have scalar-shaped variables.
|
|
1573
|
+
*/
|
|
1574
|
+
interface Domain {
|
|
1575
|
+
/**
|
|
1576
|
+
* Name of the independent (time) variable.
|
|
1577
|
+
*/
|
|
1578
|
+
independent_variable?: string;
|
|
1579
|
+
temporal?: {
|
|
1580
|
+
start?: string;
|
|
1581
|
+
end?: string;
|
|
1582
|
+
reference_time?: string;
|
|
1583
|
+
};
|
|
1584
|
+
/**
|
|
1585
|
+
* Floating point precision.
|
|
1586
|
+
*/
|
|
1587
|
+
element_type?: "Float32" | "Float64";
|
|
1588
|
+
/**
|
|
1589
|
+
* Array backend (e.g., "Array", "CuArray").
|
|
1590
|
+
*/
|
|
1591
|
+
array_type?: string;
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* A sampled function table (esm-spec.md §9.5). Carries one or more named axes and a literal nested-array data block. The shape of `data` is [len(outputs), len(axes[0].values), len(axes[1].values), ...] when `outputs` is declared; otherwise [len(axes[0].values), ...] (single-output convenience form). `table_lookup` AST nodes evaluate this table by supplying a per-axis input expression and selecting an output. Tables are syntactic sugar over `interp.linear` (1 axis) / `interp.bilinear` (2 axes) / `index` (nearest); the materialized AST a binding produces from a `table_lookup` MUST be bit-equivalent to the equivalent inline-const lookup.
|
|
1595
|
+
*/
|
|
1596
|
+
interface FunctionTable {
|
|
1597
|
+
description?: string;
|
|
1598
|
+
/**
|
|
1599
|
+
* Ordered list of named axes. The order of entries defines the order of inner dimensions in `data` (after the leading output dimension when `outputs` is present). Axis names within a single table MUST be unique.
|
|
1600
|
+
*
|
|
1601
|
+
* @minItems 1
|
|
1602
|
+
* @maxItems 2
|
|
1603
|
+
*/
|
|
1604
|
+
axes: [FunctionTableAxis] | [FunctionTableAxis, FunctionTableAxis];
|
|
1605
|
+
/**
|
|
1606
|
+
* Interpolation kind applied by `table_lookup`. 'linear' (1 axis) lowers to `interp.linear`. 'bilinear' (2 axes) lowers to `interp.bilinear`. 'nearest' lowers to `index` after `interp.searchsorted`. The chosen kind MUST be consistent with the number of axes; mismatch is rejected at load time with diagnostic 'table_interpolation_axes_mismatch'.
|
|
1607
|
+
*/
|
|
1608
|
+
interpolation?: "linear" | "bilinear" | "nearest";
|
|
1609
|
+
/**
|
|
1610
|
+
* Out-of-bounds policy applied to query coordinates that fall outside an axis range. 'clamp' pins to the nearest edge — this matches the semantics of `interp.linear` and `interp.bilinear` (extrapolate-flat). 'error' MUST raise at evaluation time; bindings emit diagnostic 'table_lookup_out_of_bounds' on first violation. v0.4.0: 'clamp' is the only policy required of all five bindings; 'error' is conformant when the binding implements it.
|
|
1611
|
+
*/
|
|
1612
|
+
out_of_bounds?: "clamp" | "error";
|
|
1613
|
+
/**
|
|
1614
|
+
* Optional ordered list of output names. When present, `table_lookup.output` MAY name an entry of this list (in addition to using a 0-based integer index). Names within a table MUST be unique. The leading dimension of `data` MUST equal the length of `outputs`.
|
|
1615
|
+
*
|
|
1616
|
+
* @minItems 1
|
|
1617
|
+
*/
|
|
1618
|
+
outputs?: [string, ...string[]];
|
|
1619
|
+
/**
|
|
1620
|
+
* Nested-array literal carrying the table's sampled values. Leaves MUST be finite numbers (NaN entries are rejected at load time with 'table_data_nan'). Shape: [len(outputs), len(axes[0].values), ...] when `outputs` is present; [len(axes[0].values), ...] otherwise. Mismatched nesting is rejected with 'table_data_shape_mismatch'.
|
|
1621
|
+
*/
|
|
1622
|
+
data: {
|
|
1623
|
+
[k: string]: unknown;
|
|
1624
|
+
};
|
|
1625
|
+
/**
|
|
1626
|
+
* Optional redundant shape assertion. If present, MUST match the actual nesting of `data`; loaders verify and reject mismatches with 'table_data_shape_mismatch'. `data` is the canonical representation; `shape` is a load-time assertion only.
|
|
1627
|
+
*
|
|
1628
|
+
* @minItems 1
|
|
1629
|
+
*/
|
|
1630
|
+
shape?: [number, ...number[]];
|
|
1631
|
+
/**
|
|
1632
|
+
* Optional pin of the table-schema minor version this entry was authored against. Bindings ignore the value beyond a same-major-version compatibility check; informational for tooling.
|
|
1633
|
+
*/
|
|
1634
|
+
schema_version?: string;
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* A single named axis inside a FunctionTable. The `values` array supplies the sample coordinates along this axis; it MUST be strictly increasing finite floats with at least 2 entries (mirrors the `interp.linear` / `interp.bilinear` axis contract in §9.2).
|
|
1638
|
+
*/
|
|
1639
|
+
interface FunctionTableAxis {
|
|
1640
|
+
/**
|
|
1641
|
+
* Axis identifier. Used as the key in `table_lookup.axes` to bind the input-coordinate expression.
|
|
1642
|
+
*/
|
|
1643
|
+
name: string;
|
|
1644
|
+
/**
|
|
1645
|
+
* Optional advisory units string (e.g. 'Pa', 'K'). v0.4.0 records this for documentation only — no load-time unit checking is performed against the supplied input expression. Promotion to enforcement is deferred to a future units RFC.
|
|
1646
|
+
*/
|
|
1647
|
+
units?: string;
|
|
1648
|
+
/**
|
|
1649
|
+
* Strictly-increasing finite floats. Bindings MUST reject non-monotonic axes at load time with diagnostic 'table_axis_non_monotonic' and NaN entries with 'table_axis_nan'.
|
|
1650
|
+
*
|
|
1651
|
+
* @minItems 2
|
|
1652
|
+
*/
|
|
1653
|
+
values: [number, number, ...number[]];
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Document-scoped named integers bound at load (esm-spec §9.7.6): at import/subsystem edges via `bindings`, at the loader API for the root document, or by `default`. Admissible — as names or `{op, args}` integer expressions — in `index_sets` interval sizes, `aggregate` dense ranges, and `makearray` regions (folded exactly at load), and substituted as integer literals in ordinary expression positions. A metaparameter name MUST NOT collide with any visible variable/parameter/species/index-set name (`metaparameter_name_conflict`).
|
|
1657
|
+
*/
|
|
1658
|
+
interface Metaparameters {
|
|
1659
|
+
[k: string]: {
|
|
1660
|
+
/**
|
|
1661
|
+
* The only v1 metaparameter kind.
|
|
1662
|
+
*/
|
|
1663
|
+
type: "integer";
|
|
1664
|
+
/**
|
|
1665
|
+
* Fallback applied at root resolution, after edge and loader-API bindings; a still-open metaparameter with no default is `metaparameter_unbound`.
|
|
1666
|
+
*/
|
|
1667
|
+
default?: number;
|
|
1668
|
+
description?: string;
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
/**
|
|
1673
|
+
* Tagged numeric-literal AST nodes and lossless JSON I/O per
|
|
1674
|
+
* discretization RFC §5.4.1 (int/float distinction) and §5.4.6
|
|
1675
|
+
* (on-wire number formatting).
|
|
1676
|
+
*
|
|
1677
|
+
* JS has a single IEEE-754 `number` type, so `JSON.parse("1")` and
|
|
1678
|
+
* `JSON.parse("1.0")` both yield `1`. To preserve the RFC-mandated
|
|
1679
|
+
* integer-vs-float AST-node distinction, this module provides:
|
|
1680
|
+
*
|
|
1681
|
+
* - `NumericLiteral` — a tagged `{kind, value}` leaf that records
|
|
1682
|
+
* whether the on-wire token was a JSON-integer or a JSON-float.
|
|
1683
|
+
* - `losslessJsonParse` — a minimal JSON parser that emits
|
|
1684
|
+
* `NumericLiteral` at every numeric-token position. Token shape
|
|
1685
|
+
* (presence of `.`, `e`, `E`) determines kind per the RFC §5.4.6
|
|
1686
|
+
* round-trip parse rule.
|
|
1687
|
+
* - `losslessJsonStringify` — inverse: `NumericLiteral{kind:int}`
|
|
1688
|
+
* → JSON integer; `NumericLiteral{kind:float}` → RFC §5.4.6 float
|
|
1689
|
+
* with the trailing-`.0` override for integer-valued magnitudes
|
|
1690
|
+
* in `[−(1e21 − 1), 1e21 − 1]`.
|
|
1691
|
+
* - `intLit`, `floatLit`, `isNumericLiteral`, `isIntLit`, `isFloatLit`,
|
|
1692
|
+
* `numericValue` — ergonomic helpers so existing consumers of the
|
|
1693
|
+
* `number | string | ExpressionNode` union can accept
|
|
1694
|
+
* `NumericLiteral` with minimal churn.
|
|
1695
|
+
*
|
|
1696
|
+
* NaN and ±Infinity are rejected on serialize with
|
|
1697
|
+
* `E_CANONICAL_NONFINITE` per RFC §5.4.6.
|
|
1698
|
+
*/
|
|
1699
|
+
interface NumericLiteral {
|
|
1700
|
+
readonly kind: 'int' | 'float';
|
|
1701
|
+
readonly value: number;
|
|
1702
|
+
}
|
|
1703
|
+
declare function intLit(value: number): NumericLiteral;
|
|
1704
|
+
declare function floatLit(value: number): NumericLiteral;
|
|
1705
|
+
declare function isNumericLiteral(x: unknown): x is NumericLiteral;
|
|
1706
|
+
declare function isIntLit(x: unknown): x is NumericLiteral & {
|
|
1707
|
+
kind: 'int';
|
|
1708
|
+
};
|
|
1709
|
+
declare function isFloatLit(x: unknown): x is NumericLiteral & {
|
|
1710
|
+
kind: 'float';
|
|
1711
|
+
};
|
|
1712
|
+
/**
|
|
1713
|
+
* Return the underlying numeric value of a plain `number` or a
|
|
1714
|
+
* `NumericLiteral`. Returns `undefined` for anything else. Use this
|
|
1715
|
+
* at the boundary between kind-aware and kind-agnostic code.
|
|
1716
|
+
*/
|
|
1717
|
+
declare function numericValue(x: unknown): number | undefined;
|
|
1718
|
+
declare class LosslessJsonParseError extends Error {
|
|
1719
|
+
readonly position: number;
|
|
1720
|
+
constructor(message: string, position: number);
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Parse a JSON document, preserving the integer-vs-float distinction
|
|
1724
|
+
* of every numeric token per RFC §5.4.6: a token containing `.`, `e`,
|
|
1725
|
+
* or `E` becomes `NumericLiteral{kind:'float'}`; otherwise it becomes
|
|
1726
|
+
* `NumericLiteral{kind:'int'}`. All other JSON values (strings, bools,
|
|
1727
|
+
* null, arrays, objects) decode to their native JS equivalents.
|
|
1728
|
+
*
|
|
1729
|
+
* Integer-grammar tokens outside the safe-integer range fall back to
|
|
1730
|
+
* `float` kind to avoid silent precision loss, matching the Go
|
|
1731
|
+
* binding's `normalizeJSONNumber` behavior.
|
|
1732
|
+
*/
|
|
1733
|
+
declare function losslessJsonParse(text: string): unknown;
|
|
1734
|
+
/**
|
|
1735
|
+
* Canonical-form error carrying a stable RFC §5.4.6 / §5.4.7 `code` string
|
|
1736
|
+
* (`E_CANONICAL_NONFINITE`, `E_CANONICAL_DIVBY_ZERO`).
|
|
1737
|
+
*
|
|
1738
|
+
* Defined here — the lowest module in the canonical-form stack — so that both
|
|
1739
|
+
* this module's serializer and `canonicalize.ts` can share ONE nonfinite error
|
|
1740
|
+
* type ({@link CanonicalNonfiniteError} extends it) without an import cycle.
|
|
1741
|
+
* `canonicalize.ts` re-exports this class under the same name, so consumers may
|
|
1742
|
+
* keep importing `CanonicalizeError` from either module.
|
|
1743
|
+
*/
|
|
1744
|
+
declare class CanonicalizeError extends Error {
|
|
1745
|
+
/** Stable RFC §5.4.6 / §5.4.7 error code. */
|
|
1746
|
+
readonly code: string;
|
|
1747
|
+
constructor(code: string, message?: string);
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Raised when a non-finite number (NaN, ±Infinity) reaches canonical / lossless
|
|
1751
|
+
* serialization — RFC §5.4.6 forbids non-finite numbers in the wire form. A
|
|
1752
|
+
* specialization of {@link CanonicalizeError} carrying the
|
|
1753
|
+
* `E_CANONICAL_NONFINITE` code plus the offending `value` and its `path`, so a
|
|
1754
|
+
* single `instanceof CanonicalizeError` check catches every canonical-form
|
|
1755
|
+
* failure regardless of which pass raised it.
|
|
1756
|
+
*/
|
|
1757
|
+
declare class CanonicalNonfiniteError extends CanonicalizeError {
|
|
1758
|
+
readonly value: number;
|
|
1759
|
+
readonly path: string;
|
|
1760
|
+
constructor(value: number, path: string);
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Stringify a value to JSON, emitting `NumericLiteral` leaves per RFC
|
|
1764
|
+
* §5.4.6:
|
|
1765
|
+
*
|
|
1766
|
+
* - `kind: 'int'` → JSON-integer token (no `.`, no `e`).
|
|
1767
|
+
* - `kind: 'float'` with integer-valued magnitude in
|
|
1768
|
+
* `[−(1e21 − 1), 1e21 − 1]` → `ToString(Number)` with trailing
|
|
1769
|
+
* `.0` appended so the token cannot be confused with an integer
|
|
1770
|
+
* on parse-back (e.g. `1.0`, `-3.0`, `0.0`).
|
|
1771
|
+
* - `kind: 'float'` otherwise → native `ToString(Number)` (which is
|
|
1772
|
+
* already distinguishable via `.` or `e`).
|
|
1773
|
+
* - `-0.0` float → `-0.0`.
|
|
1774
|
+
* - NaN or ±Infinity → throws `CanonicalNonfiniteError`.
|
|
1775
|
+
*
|
|
1776
|
+
* Plain JS `number` values are serialized with `JSON.stringify`'s
|
|
1777
|
+
* default rules (no trailing `.0` override); callers that want
|
|
1778
|
+
* canonical emission must tag literals via `intLit` / `floatLit`.
|
|
1779
|
+
*/
|
|
1780
|
+
declare function losslessJsonStringify(value: unknown): string;
|
|
1781
|
+
/**
|
|
1782
|
+
* Emit a float token via ECMAScript `ToString(Number)` with a trailing
|
|
1783
|
+
* `.0` override when the result is an integer-valued plain-decimal token.
|
|
1784
|
+
*
|
|
1785
|
+
* NAMING: this is the DOCUMENT-serialization float emitter (used by
|
|
1786
|
+
* {@link losslessJsonStringify} and `save()`), which relies on
|
|
1787
|
+
* `ToString(Number)`'s own exponent formatting. It is deliberately NOT the
|
|
1788
|
+
* strict RFC §5.4.6 CANONICAL-FORM emitter — that is the confusingly-similar
|
|
1789
|
+
* `formatCanonicalFloat` in `canonicalize.ts`, which additionally normalizes
|
|
1790
|
+
* exponent notation (strips the leading `+` and forces the §5.4.6 exponent
|
|
1791
|
+
* thresholds). Keep the two distinct: `formatFloatToken` for wire round-trip,
|
|
1792
|
+
* `formatCanonicalFloat` for byte-canonical output.
|
|
1793
|
+
*/
|
|
1794
|
+
declare function formatFloatToken(value: number): string;
|
|
1795
|
+
|
|
1796
|
+
/**
|
|
1797
|
+
* EarthSciML Serialization Format TypeScript type definitions — plus a small
|
|
1798
|
+
* set of RUNTIME re-exports.
|
|
1799
|
+
*
|
|
1800
|
+
* Provides the complete type definitions for the ESM format: the auto-generated
|
|
1801
|
+
* types from the JSON schema (`export * from './generated.js'`) and manual
|
|
1802
|
+
* augmentations for discriminated unions and ergonomics. For convenience this
|
|
1803
|
+
* module ALSO re-exports the runtime tagged numeric-literal API (`intLit`,
|
|
1804
|
+
* `floatLit`, `losslessJsonParse`, …) from `./numeric-literal.js`, so it is not
|
|
1805
|
+
* purely type-level; `index.ts` re-exports both surfaces from here (do not move
|
|
1806
|
+
* the runtime re-exports without updating `index.ts`).
|
|
1807
|
+
*
|
|
1808
|
+
* Canonical alias names (duplicates are kept for back-compat but marked
|
|
1809
|
+
* `@deprecated`):
|
|
1810
|
+
* - root file structure → `EsmFile` (aliases: `EsmFormat`, generated `ESMFormat`)
|
|
1811
|
+
* - operator node → `ExpressionNode` (alias: `ExprNode`)
|
|
1812
|
+
* - `Expression` (wire / schema-shaped value) and `Expr` (widened in-memory
|
|
1813
|
+
* value that MAY carry a tagged `NumericLiteral`) are DISTINCT types, not
|
|
1814
|
+
* aliases — pick by whether you hold a wire value or an in-memory one.
|
|
1815
|
+
*/
|
|
1816
|
+
|
|
1817
|
+
/**
|
|
1818
|
+
* An expression node whose OPERANDS are in-memory {@link Expr} values.
|
|
1819
|
+
*
|
|
1820
|
+
* The wire `ExpressionNode` has `args: Expression[]`, which cannot hold a
|
|
1821
|
+
* tagged `NumericLiteral`. Every rewriting pass (differentiation, substitution,
|
|
1822
|
+
* simplification, CSE) builds nodes out of operands it was handed, so those
|
|
1823
|
+
* operands are `Expr` and the node it builds is this. `ExpressionNode` is
|
|
1824
|
+
* assignable to it — `Expression` is a subset of `Expr` and `args` is covariant
|
|
1825
|
+
* — so a wire node flows into a rewriting pass unchanged.
|
|
1826
|
+
*
|
|
1827
|
+
* Before esm 1.0.0 this widening was ACCIDENTAL: json2ts resolved the generated
|
|
1828
|
+
* `Expression` to `number | string | { [k: string]: unknown }`, whose open
|
|
1829
|
+
* object branch swallowed anything at all. The 1.0.0 schema restructure made it
|
|
1830
|
+
* resolve to the real `ExpressionNode` — strictly more faithful — which exposed
|
|
1831
|
+
* every site that had been relying on that looseness. This states the widening
|
|
1832
|
+
* deliberately instead of inheriting it from a generator artifact.
|
|
1833
|
+
*/
|
|
1834
|
+
interface ExprNodeOf {
|
|
1835
|
+
op: string;
|
|
1836
|
+
args: Expr[];
|
|
1837
|
+
[k: string]: unknown;
|
|
1838
|
+
}
|
|
1839
|
+
type Expr = Expression | NumericLiteral | ExprNodeOf;
|
|
1840
|
+
|
|
1841
|
+
type EsmFile = ESMFormat1 & Omit<ESMFormat2, 'models'> & {
|
|
1842
|
+
/**
|
|
1843
|
+
* Narrowed so that a model reached from the document root is the 1.0.0
|
|
1844
|
+
* {@link Model} — closed variables, no data-source subsystem — rather than
|
|
1845
|
+
* the generated shape. Without this the strictness stops at the root and
|
|
1846
|
+
* `file.models[m].variables[v].expression` reads as `unknown` again.
|
|
1847
|
+
*
|
|
1848
|
+
* This REPLACES the generated `models` (via `Omit`) rather than
|
|
1849
|
+
* intersecting with it. Intersecting produced
|
|
1850
|
+
* `(GeneratedModel | SubsystemRef) & (Model | SubsystemRef)`, which
|
|
1851
|
+
* TypeScript does not simplify — so assigning a `Model`-typed VARIABLE
|
|
1852
|
+
* (as opposed to a fresh object literal, which gets an implicit index
|
|
1853
|
+
* signature) demanded it also satisfy `SubsystemRef`, and failed with
|
|
1854
|
+
* "Property 'ref' is missing".
|
|
1855
|
+
*/
|
|
1856
|
+
models?: {
|
|
1857
|
+
[k: string]: Model | SubsystemRef;
|
|
1858
|
+
};
|
|
1859
|
+
};
|
|
1860
|
+
/** @deprecated Prefer {@link EsmFile}. Identical to the generated `ESMFormat`. */
|
|
1861
|
+
type EsmFormat = ESMFormat;
|
|
1862
|
+
/** @deprecated Prefer {@link ExpressionNode} (the generated name). */
|
|
1863
|
+
type ExprNode = ExpressionNode;
|
|
1864
|
+
|
|
1865
|
+
/**
|
|
1866
|
+
* Symmetric positive-semidefinite covariance matrix, row-major: `[i][j]` is the
|
|
1867
|
+
* covariance of components i and j. Square, with order equal to the length of
|
|
1868
|
+
* the accompanying `mean` / `mu` vector and of the parameter's `shape`.
|
|
1869
|
+
*/
|
|
1870
|
+
type CovarianceMatrix = number[][];
|
|
1871
|
+
/**
|
|
1872
|
+
* Gaussian. Exactly one of `std` (independent components) or `cov` (a full
|
|
1873
|
+
* covariance matrix) — never both, which is why this is a union rather than two
|
|
1874
|
+
* optional fields.
|
|
1875
|
+
*/
|
|
1876
|
+
type NormalDistribution = {
|
|
1877
|
+
kind: 'normal';
|
|
1878
|
+
mean: number | number[];
|
|
1879
|
+
} & ({
|
|
1880
|
+
std: number | number[];
|
|
1881
|
+
cov?: never;
|
|
1882
|
+
} | {
|
|
1883
|
+
cov: CovarianceMatrix;
|
|
1884
|
+
std?: never;
|
|
1885
|
+
});
|
|
1886
|
+
/**
|
|
1887
|
+
* Log-normal: `log(value)` is normal with mean `mu` and spread `sigma` / `cov`.
|
|
1888
|
+
* Both spread forms are on the LOG scale. Exactly one of `sigma` or `cov`.
|
|
1889
|
+
*/
|
|
1890
|
+
type LognormalDistribution = {
|
|
1891
|
+
kind: 'lognormal';
|
|
1892
|
+
mu: number | number[];
|
|
1893
|
+
} & ({
|
|
1894
|
+
sigma: number | number[];
|
|
1895
|
+
cov?: never;
|
|
1896
|
+
} | {
|
|
1897
|
+
cov: CovarianceMatrix;
|
|
1898
|
+
sigma?: never;
|
|
1899
|
+
});
|
|
1900
|
+
/**
|
|
1901
|
+
* Uniform on `[low, high]`. Components are independent by construction, so
|
|
1902
|
+
* there is no covariance form.
|
|
1903
|
+
*/
|
|
1904
|
+
interface UniformDistribution {
|
|
1905
|
+
kind: 'uniform';
|
|
1906
|
+
low: number | number[];
|
|
1907
|
+
high: number | number[];
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* A parameter's value drawn from a probability distribution rather than fixed.
|
|
1911
|
+
* The closed set is `normal` | `lognormal` | `uniform`. Mutually exclusive with
|
|
1912
|
+
* `default`. WHEN it is drawn is decided by the parameter's `update`: with no
|
|
1913
|
+
* update it is sampled ONCE at setup; with `update.kind: "wiener"` it is
|
|
1914
|
+
* resampled every step with √dt scaling.
|
|
1915
|
+
*
|
|
1916
|
+
* Univariate when the location parameter is a number, multivariate when it is
|
|
1917
|
+
* an array (in which case the parameter's `shape` must agree).
|
|
1918
|
+
*/
|
|
1919
|
+
type Distribution = NormalDistribution | LognormalDistribution | UniformDistribution;
|
|
1920
|
+
/**
|
|
1921
|
+
* A registered handler computing a parameter's new value when its update fires
|
|
1922
|
+
* — the 0.x event `functional_affect`, relocated onto the parameter it writes.
|
|
1923
|
+
*/
|
|
1924
|
+
interface FunctionalUpdate {
|
|
1925
|
+
handler_id: string;
|
|
1926
|
+
read_vars?: string[];
|
|
1927
|
+
read_params?: string[];
|
|
1928
|
+
config?: {
|
|
1929
|
+
[k: string]: unknown;
|
|
1930
|
+
};
|
|
1931
|
+
}
|
|
1932
|
+
/** Decodes a TEXT source column into numbers a model can compute with. */
|
|
1933
|
+
interface DataSourceCodes {
|
|
1934
|
+
map: {
|
|
1935
|
+
[k: string]: number;
|
|
1936
|
+
};
|
|
1937
|
+
case_insensitive?: boolean;
|
|
1938
|
+
unmapped?: 'drop' | 'error' | number;
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* Binds a parameter to one variable of a `data_sources` entry. This is the 0.x
|
|
1942
|
+
* `DataLoaderVariable` minus `units`: the units are the parameter's own,
|
|
1943
|
+
* declared once on the parameter instead of twice.
|
|
1944
|
+
*/
|
|
1945
|
+
interface DataSourceBinding {
|
|
1946
|
+
file_variable: string;
|
|
1947
|
+
unit_conversion?: Expression;
|
|
1948
|
+
codes?: DataSourceCodes;
|
|
1949
|
+
select?: DataSourceSelect;
|
|
1950
|
+
description?: string;
|
|
1951
|
+
reference?: Reference;
|
|
1952
|
+
}
|
|
1953
|
+
/**
|
|
1954
|
+
* The value form every non-`wiener` update kind takes EXACTLY ONE of: computed
|
|
1955
|
+
* symbolically (`expression`), read from a data source (`from`), or produced by
|
|
1956
|
+
* a registered handler (`handler`).
|
|
1957
|
+
*/
|
|
1958
|
+
type UpdateValueForm = {
|
|
1959
|
+
expression: Expression;
|
|
1960
|
+
from?: never;
|
|
1961
|
+
handler?: never;
|
|
1962
|
+
} | {
|
|
1963
|
+
from: DataSourceBinding;
|
|
1964
|
+
expression?: never;
|
|
1965
|
+
handler?: never;
|
|
1966
|
+
} | {
|
|
1967
|
+
handler: FunctionalUpdate;
|
|
1968
|
+
expression?: never;
|
|
1969
|
+
from?: never;
|
|
1970
|
+
};
|
|
1971
|
+
/**
|
|
1972
|
+
* A driving Wiener (Brownian) process: the parameter's `distribution` is
|
|
1973
|
+
* resampled every step with √dt increment scaling. Takes NO value form — the
|
|
1974
|
+
* distribution IS the value — and requires `distribution` on the variable.
|
|
1975
|
+
* Its presence promotes the enclosing model from an ODE system to an SDE.
|
|
1976
|
+
*/
|
|
1977
|
+
interface WienerUpdate {
|
|
1978
|
+
kind: 'wiener';
|
|
1979
|
+
}
|
|
1980
|
+
/** Time-driven refresh at preset `times` and/or on a periodic `interval`. */
|
|
1981
|
+
type ScheduleUpdate = {
|
|
1982
|
+
kind: 'schedule';
|
|
1983
|
+
times?: number[];
|
|
1984
|
+
interval?: number;
|
|
1985
|
+
initial_offset?: number;
|
|
1986
|
+
} & UpdateValueForm;
|
|
1987
|
+
/** Refresh at the end of any timestep at which `when` is true. */
|
|
1988
|
+
type ConditionUpdate = {
|
|
1989
|
+
kind: 'condition';
|
|
1990
|
+
when: Expression;
|
|
1991
|
+
} & UpdateValueForm;
|
|
1992
|
+
/** Refresh when `when` crosses zero, located by root-finding. */
|
|
1993
|
+
type CrossingUpdate = {
|
|
1994
|
+
kind: 'crossing';
|
|
1995
|
+
when: Expression;
|
|
1996
|
+
direction?: 'up' | 'down' | 'any';
|
|
1997
|
+
} & UpdateValueForm;
|
|
1998
|
+
/**
|
|
1999
|
+
* Refresh when the named data source advances a record. `source` MUST resolve
|
|
2000
|
+
* to a `data_sources` key (`data_source_undefined`).
|
|
2001
|
+
*/
|
|
2002
|
+
type DataUpdate = {
|
|
2003
|
+
kind: 'data';
|
|
2004
|
+
source: string;
|
|
2005
|
+
} & UpdateValueForm;
|
|
2006
|
+
/** Refresh on a mesh-topology change (AMR refinement, moving/reloaded mesh). */
|
|
2007
|
+
type RemeshUpdate = {
|
|
2008
|
+
kind: 'remesh';
|
|
2009
|
+
hook?: string;
|
|
2010
|
+
} & UpdateValueForm;
|
|
2011
|
+
/**
|
|
2012
|
+
* Every update kind except `wiener`. The schema forbids `wiener` inside an
|
|
2013
|
+
* update ARRAY (a driving noise process is the parameter's whole value), which
|
|
2014
|
+
* is what this type names.
|
|
2015
|
+
*/
|
|
2016
|
+
type NonWienerParameterUpdate = ScheduleUpdate | ConditionUpdate | CrossingUpdate | DataUpdate | RemeshUpdate;
|
|
2017
|
+
/** One update rule. Six kinds, discriminated by `kind`. */
|
|
2018
|
+
type ParameterUpdate = WienerUpdate | NonWienerParameterUpdate;
|
|
2019
|
+
/**
|
|
2020
|
+
* A parameter's update behavior: EITHER a single rule, OR an ordered array of
|
|
2021
|
+
* TWO OR MORE rules applied in declaration order. A single rule MUST be the
|
|
2022
|
+
* object form — a one-element array is invalid — so the representation of any
|
|
2023
|
+
* given update set is unique and the round-trip is stable.
|
|
2024
|
+
*/
|
|
2025
|
+
type ParameterUpdateSpec = ParameterUpdate | [NonWienerParameterUpdate, NonWienerParameterUpdate, ...NonWienerParameterUpdate[]];
|
|
2026
|
+
/**
|
|
2027
|
+
* A variable in a model — either an `unknown` the solver solves for, or a
|
|
2028
|
+
* `parameter` supplied to it. There is no third kind, and no `expression`
|
|
2029
|
+
* field: an unknown's behavior is stated by the model's `equations` and nowhere
|
|
2030
|
+
* else.
|
|
2031
|
+
*
|
|
2032
|
+
* Everything a solver additionally needs is DERIVED, never declared — see the
|
|
2033
|
+
* classification API in `./classification.js` (`odeStates`, `observedUnknowns`,
|
|
2034
|
+
* `algebraicUnknowns`, `brownianParameters`, `discreteParameters`,
|
|
2035
|
+
* `sampledParameters`, `constantParameters`, `systemKind`).
|
|
2036
|
+
*
|
|
2037
|
+
* Deliberately CLOSED (no index signature): reading a field 1.0.0 removed —
|
|
2038
|
+
* `expression`, `noise_kind`, `correlation_group`, `refresh` — is a compile
|
|
2039
|
+
* error rather than a silent `unknown`.
|
|
2040
|
+
*/
|
|
2041
|
+
interface ModelVariable {
|
|
2042
|
+
type: 'unknown' | 'parameter';
|
|
2043
|
+
units?: string;
|
|
2044
|
+
/** For an unknown, its value at t=0. For a parameter, its constant value. */
|
|
2045
|
+
default?: number;
|
|
2046
|
+
default_units?: string;
|
|
2047
|
+
description?: string;
|
|
2048
|
+
/**
|
|
2049
|
+
* Ordered index-set names. REQUIRED for a parameter whose `update` is
|
|
2050
|
+
* `schedule`, `data`, or `remesh`.
|
|
2051
|
+
*/
|
|
2052
|
+
shape?: string[];
|
|
2053
|
+
location?: string;
|
|
2054
|
+
/** Parameter-only. Mutually exclusive with `default`. */
|
|
2055
|
+
distribution?: Distribution;
|
|
2056
|
+
/** Parameter-only. Absent means the parameter never changes after setup. */
|
|
2057
|
+
update?: ParameterUpdateSpec;
|
|
2058
|
+
}
|
|
2059
|
+
/**
|
|
2060
|
+
* A model node. Narrows the generated type in the two places that matter: its
|
|
2061
|
+
* variables are the CLOSED {@link ModelVariable} above, and a subsystem is a
|
|
2062
|
+
* child model or a reference — never a data source, which from 1.0.0 is not a
|
|
2063
|
+
* component and cannot be a subsystem, a coupling endpoint, or a scoped-name
|
|
2064
|
+
* path root.
|
|
2065
|
+
*/
|
|
2066
|
+
type Model = Omit<Model$1, 'variables' | 'subsystems'> & {
|
|
2067
|
+
variables: {
|
|
2068
|
+
[k: string]: ModelVariable;
|
|
2069
|
+
};
|
|
2070
|
+
subsystems?: {
|
|
2071
|
+
[k: string]: Model | SubsystemRef;
|
|
2072
|
+
};
|
|
2073
|
+
};
|
|
2074
|
+
|
|
2075
|
+
/**
|
|
2076
|
+
* Runtime unit conversion for ESM format.
|
|
2077
|
+
*
|
|
2078
|
+
* Complements `units.ts` (which performs dimensional analysis) by adding
|
|
2079
|
+
* numeric value conversion between compatible units: `convertUnits(1, "km", "m")` → 1000.
|
|
2080
|
+
*
|
|
2081
|
+
* Representation: each unit parses to a canonical SI-base dimension vector plus a
|
|
2082
|
+
* multiplicative scale factor and (for temperature) an additive offset. Conversion
|
|
2083
|
+
* goes through SI base: `value_SI = value * scale + offset`, then `target = (value_SI - offset_t) / scale_t`.
|
|
2084
|
+
*
|
|
2085
|
+
* This module is intentionally independent of the `DimensionalRep` used by `units.ts`
|
|
2086
|
+
* — that representation lacks scale tracking and treats `cm`, `J`, `Pa` as base
|
|
2087
|
+
* dimensions, which would make extension invasive.
|
|
2088
|
+
*/
|
|
2089
|
+
/**
|
|
2090
|
+
* Exponents over the SI base dimensions — the SAME eight axes, in the same
|
|
2091
|
+
* roles, as the Go reference's `Dimension` vector (`m kg s mol K A cd rad`),
|
|
2092
|
+
* which is the cross-binding contract for what a unit string MEANS.
|
|
2093
|
+
*
|
|
2094
|
+
* `molec` is deliberately NOT an axis. A count of discrete things carries no
|
|
2095
|
+
* physical dimension, so `molec` (and `individuals`, `vehicles`, `units`,
|
|
2096
|
+
* `count`) is a DIMENSIONLESS unit in the table below — which is what makes
|
|
2097
|
+
* `molec/cm^3` compare equal to `1/cm^3`, as every other binding has it. Giving
|
|
2098
|
+
* counts their own axis made TS the only binding that could report a mismatch
|
|
2099
|
+
* between the two spellings of a number density.
|
|
2100
|
+
*/
|
|
2101
|
+
interface CanonicalDims {
|
|
2102
|
+
kg?: number;
|
|
2103
|
+
m?: number;
|
|
2104
|
+
s?: number;
|
|
2105
|
+
K?: number;
|
|
2106
|
+
mol?: number;
|
|
2107
|
+
A?: number;
|
|
2108
|
+
cd?: number;
|
|
2109
|
+
rad?: number;
|
|
2110
|
+
}
|
|
2111
|
+
interface ParsedUnit {
|
|
2112
|
+
dims: CanonicalDims;
|
|
2113
|
+
scale: number;
|
|
2114
|
+
offset?: number;
|
|
2115
|
+
}
|
|
2116
|
+
declare class UnitConversionError extends Error {
|
|
2117
|
+
constructor(message: string);
|
|
2118
|
+
}
|
|
2119
|
+
/**
|
|
2120
|
+
* Parse a unit string into canonical SI dimensions plus scale (and optional offset).
|
|
2121
|
+
*
|
|
2122
|
+
* Recursive-descent parser over the grammar of the Go reference implementation
|
|
2123
|
+
* (`pkg/earthsci-ast-go/pkg/esm/units.go`), so the bindings agree on how a unit
|
|
2124
|
+
* string associates:
|
|
2125
|
+
*
|
|
2126
|
+
* ```
|
|
2127
|
+
* unit := term ( ('*' | '/')? term )*
|
|
2128
|
+
* term := atom ( ('^' | '**') exponent )?
|
|
2129
|
+
* exponent := integer | decimal | '(' integer '/' integer ')'
|
|
2130
|
+
* atom := '1' | symbol | '(' unit ')'
|
|
2131
|
+
* ```
|
|
2132
|
+
*
|
|
2133
|
+
* EXPONENTS ARE RATIONAL, not integral: `1/s^0.5` (an SDE noise intensity) and
|
|
2134
|
+
* `m^(1/2)` are legitimate corpus units, and a dimension vector may therefore
|
|
2135
|
+
* carry fractional entries.
|
|
2136
|
+
*
|
|
2137
|
+
* `*` and `/` share one precedence level and associate LEFT — so `kg/m*s` is
|
|
2138
|
+
* `(kg/m)*s` = kg·s·m⁻¹, NOT kg·m⁻¹·s⁻¹, and `a/b/c` is `a/(b*c)`. Grouping with
|
|
2139
|
+
* parentheses is supported, so the ordinary earth-science spellings `J/(mol*K)`
|
|
2140
|
+
* and `cm^3/(molec*s)` parse.
|
|
2141
|
+
*
|
|
2142
|
+
* WHITESPACE BETWEEN TWO TERMS IS MULTIPLICATION — the SI style `kg m^2 s^-2`
|
|
2143
|
+
* and the corpus's `ppb^-1 s^-1`. The scanner is greedy over identifier
|
|
2144
|
+
* characters, so `ms` stays ONE symbol (millisecond); juxtaposition can only
|
|
2145
|
+
* arise across a real token boundary. `**` is accepted as a synonym for `^` (the
|
|
2146
|
+
* Python/pint spelling, e.g. the corpus's `Pa*m**3`).
|
|
2147
|
+
*
|
|
2148
|
+
* The empty string, `"1"` and `"dimensionless"` are the dimensionless unit.
|
|
2149
|
+
* Non-ASCII spellings (`μg`, `°C`) are normalized first — see
|
|
2150
|
+
* {@link normalizeUnitString}.
|
|
2151
|
+
*
|
|
2152
|
+
* @throws {UnitConversionError} on unknown unit names, malformed tokens,
|
|
2153
|
+
* unbalanced parentheses, or trailing input.
|
|
2154
|
+
*/
|
|
2155
|
+
declare function parseUnitForConversion(unitStr: string): ParsedUnit;
|
|
2156
|
+
/**
|
|
2157
|
+
* Convert a numeric value from one unit string to another.
|
|
2158
|
+
*
|
|
2159
|
+
* @example
|
|
2160
|
+
* convertUnits(1, 'km', 'm') // 1000
|
|
2161
|
+
* convertUnits(0, 'Celsius', 'K') // 273.15
|
|
2162
|
+
* convertUnits(1, 'atm', 'Pa') // 101325
|
|
2163
|
+
* convertUnits(1, 'Dobson', 'molec/m^2') // 2.6867e20
|
|
2164
|
+
*
|
|
2165
|
+
* @throws {UnitConversionError} when the unit strings have incompatible dimensions
|
|
2166
|
+
* or cannot be parsed.
|
|
2167
|
+
*/
|
|
2168
|
+
declare function convertUnits(value: number, from: string, to: string): number;
|
|
2169
|
+
/**
|
|
2170
|
+
* Report whether two unit strings represent compatible (same-dimension) quantities.
|
|
2171
|
+
* A non-throwing companion to `convertUnits`.
|
|
2172
|
+
*/
|
|
2173
|
+
declare function unitsCompatible(a: string, b: string): boolean;
|
|
2174
|
+
|
|
2175
|
+
/**
|
|
2176
|
+
* Unit parsing and dimensional analysis for ESM format
|
|
2177
|
+
*
|
|
2178
|
+
* This module implements unit string parsing and dimensional consistency
|
|
2179
|
+
* checking following the ESM specification Section 3.3.1. It shares its
|
|
2180
|
+
* canonical representation (`CanonicalDims` + `ParsedUnit`) with
|
|
2181
|
+
* `unit-conversion.ts`, so derived units like `cm`, `J`, `Pa` collapse to
|
|
2182
|
+
* their SI-base decomposition (`m`, `kg·m²·s⁻²`, `kg·m⁻¹·s⁻²`) with a scale
|
|
2183
|
+
* factor rather than being treated as independent dimensions.
|
|
2184
|
+
*/
|
|
2185
|
+
|
|
2186
|
+
/**
|
|
2187
|
+
* A single dimensional-analysis diagnostic: the message plus the classification
|
|
2188
|
+
* decided AT THE POINT it was raised (see {@link UnitWarning.code}). The code is
|
|
2189
|
+
* explicit rather than recovered from the prose, so rewording a message can
|
|
2190
|
+
* never silently flip a warning between `analysis` and `dimensional_mismatch`.
|
|
2191
|
+
*/
|
|
2192
|
+
interface UnitDiagnostic {
|
|
2193
|
+
message: string;
|
|
2194
|
+
code: UnitWarning['code'];
|
|
2195
|
+
}
|
|
2196
|
+
/**
|
|
2197
|
+
* Result of dimensional analysis for a single expression.
|
|
2198
|
+
*/
|
|
2199
|
+
interface UnitResult {
|
|
2200
|
+
/**
|
|
2201
|
+
* The expression's canonical dimension, or `null` when it is INDETERMINATE.
|
|
2202
|
+
*
|
|
2203
|
+
* `null` is not "dimensionless" — it is "this analysis cannot say", and it is
|
|
2204
|
+
* the value returned for an unknown variable, an unparseable unit
|
|
2205
|
+
* declaration, and any operator whose dimensional semantics this module does
|
|
2206
|
+
* not model (`index`, `fn`, `aggregate`, `makearray`, `table_lookup`, ...).
|
|
2207
|
+
* Keeping the two apart is what stops a structural op from being *assumed*
|
|
2208
|
+
* dimensionless and thereby manufacturing a false mismatch against a
|
|
2209
|
+
* dimensional operand. `null` propagates through every combining rule, and a
|
|
2210
|
+
* comparison against `null` is never a mismatch — it is simply skipped, which
|
|
2211
|
+
* mirrors the Go reference (`PropagateDimension` returns `nil, nil`).
|
|
2212
|
+
*/
|
|
2213
|
+
dimensions: ParsedUnit | null;
|
|
2214
|
+
/** Message-only view, retained for the public `checkDimensions` API and
|
|
2215
|
+
* legacy callers that inspect warning prose. */
|
|
2216
|
+
warnings: string[];
|
|
2217
|
+
/** Structured view of {@link warnings}: each message with its explicit
|
|
2218
|
+
* classification. `validateUnits` uses these codes (not a prose regex) to
|
|
2219
|
+
* decide which warnings `validate()` promotes to errors. */
|
|
2220
|
+
diagnostics: UnitDiagnostic[];
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* Dimensional-consistency warning emitted during file-level validation.
|
|
2224
|
+
*/
|
|
2225
|
+
interface UnitWarning {
|
|
2226
|
+
message: string;
|
|
2227
|
+
/**
|
|
2228
|
+
* Structured finding kind, and the whole of the severity policy.
|
|
2229
|
+
*
|
|
2230
|
+
* A unit finding is either a DEFECT IN THE FILE — which invalidates the
|
|
2231
|
+
* document — or a limit of the ANALYSIS, which does not. The classification is
|
|
2232
|
+
* decided AT THE POINT the finding is raised (never recovered later from the
|
|
2233
|
+
* prose, so rewording a message can never silently change its severity), and
|
|
2234
|
+
* `validate()` promotes exactly the defect-bearing codes to
|
|
2235
|
+
* `unit_inconsistency` structural errors.
|
|
2236
|
+
*
|
|
2237
|
+
* - `dimensional_mismatch` — a PROVABLE inconsistency: metres added to
|
|
2238
|
+
* kilograms, `log()` of a dimensional quantity, an equation whose sides
|
|
2239
|
+
* cannot agree. The file is wrong. → HARD ERROR.
|
|
2240
|
+
* - `unparseable_unit` — a declared unit string that does not denote a real
|
|
2241
|
+
* unit (`"not_a_unit"`). A unit that names nothing is not an ambiguity to be
|
|
2242
|
+
* worked around; the declaration is meaningless, and that is a defect in the
|
|
2243
|
+
* FILE, not in the checker. → HARD ERROR. (Which is why the registry in
|
|
2244
|
+
* `unit-conversion.ts` must not be missing real units — under this policy a
|
|
2245
|
+
* registry gap is a false rejection.)
|
|
2246
|
+
* - `analysis` — the checker cannot DETERMINE a dimension: a symbolic
|
|
2247
|
+
* exponent (`x^n`, whose dimension depends on `n`'s runtime value), an
|
|
2248
|
+
* operator with no dimensional rule (`aggregate`, `index`, `fn`,
|
|
2249
|
+
* `table_lookup`), a malformed arity, an unknown variable. Genuinely
|
|
2250
|
+
* undeterminable — a statement about the checker, not the file. → WARNING,
|
|
2251
|
+
* and the dimension is reported UNKNOWN and the check SKIPPED, never assumed
|
|
2252
|
+
* dimensionless.
|
|
2253
|
+
*
|
|
2254
|
+
* An unknown VARIABLE is an `analysis` finding here and nothing more: it is
|
|
2255
|
+
* separately a hard `undefined_variable` error, so the units layer does not
|
|
2256
|
+
* double-report it.
|
|
2257
|
+
*/
|
|
2258
|
+
code: 'dimensional_mismatch' | 'unparseable_unit' | 'analysis';
|
|
2259
|
+
location?: string;
|
|
2260
|
+
equation?: string;
|
|
2261
|
+
/** For `unparseable_unit`: the declaration at fault. `validate()` promotes the
|
|
2262
|
+
* finding to a `unit_parse_error` structural error and reports these verbatim
|
|
2263
|
+
* as its `details`, which the shared corpus pins. */
|
|
2264
|
+
variable?: string;
|
|
2265
|
+
units?: string;
|
|
2266
|
+
}
|
|
2267
|
+
/**
|
|
2268
|
+
* Parse a unit string into canonical SI dimensions plus scale factor, or return
|
|
2269
|
+
* `null` when the string cannot be parsed.
|
|
2270
|
+
*
|
|
2271
|
+
* This is the fallible companion to {@link parseUnit}: instead of swallowing a
|
|
2272
|
+
* parse failure into a dimensionless fallback, it surfaces the failure as
|
|
2273
|
+
* `null`. Callers can then leave the variable's dimension UNKNOWN (unbound) and
|
|
2274
|
+
* emit a warning, rather than silently manufacturing a dimensionless binding
|
|
2275
|
+
* that HIDES real dimensional mismatches — or MANUFACTURES false ones
|
|
2276
|
+
* (esm-libraries-spec §3.3.3/§3.4, matching the Julia reference). A
|
|
2277
|
+
* `UnitConversionError` (unknown unit name, malformed token, misused offset
|
|
2278
|
+
* unit) maps to `null`; any other error is rethrown.
|
|
2279
|
+
*
|
|
2280
|
+
* `"degree"` / `"degrees"` are resolved by the canonical table as long-form
|
|
2281
|
+
* aliases of `deg` (esm-spec §4.8.1), i.e. as the ANGLE axis scaled by π/180 —
|
|
2282
|
+
* the reading the Rust, Julia and Python tables already carry. They used to be
|
|
2283
|
+
* short-circuited to dimensionless here, which both disagreed with those three
|
|
2284
|
+
* bindings and left the SINGULAR spelling unresolvable, since only the plural
|
|
2285
|
+
* was special-cased and neither was in the table.
|
|
2286
|
+
*/
|
|
2287
|
+
declare function tryParseUnit(unitStr: string): ParsedUnit | null;
|
|
2288
|
+
/**
|
|
2289
|
+
* Parse a unit string into canonical SI dimensions plus scale factor.
|
|
2290
|
+
*
|
|
2291
|
+
* STRICT: an unparseable unit string is an ERROR. It is never silently
|
|
2292
|
+
* collapsed to dimensionless — a dimensionless fallback is a *claim* about the
|
|
2293
|
+
* quantity, and a wrong one, which both hides real mismatches (everything
|
|
2294
|
+
* compares equal to everything) and manufactures false ones (against genuinely
|
|
2295
|
+
* dimensional operands). `J/(mol*K)` used to land in exactly that trap.
|
|
2296
|
+
*
|
|
2297
|
+
* Callers that must degrade gracefully rather than throw — the validators, which
|
|
2298
|
+
* want to leave a dimension UNKNOWN and carry on — use {@link tryParseUnit},
|
|
2299
|
+
* which returns `null` instead.
|
|
2300
|
+
*
|
|
2301
|
+
* @throws {UnitConversionError} on an unknown unit name, a malformed token,
|
|
2302
|
+
* unbalanced parentheses, or a misused offset unit.
|
|
2303
|
+
*/
|
|
2304
|
+
declare function parseUnit(unitStr: string): ParsedUnit;
|
|
2305
|
+
/**
|
|
2306
|
+
* Check dimensional consistency of an expression.
|
|
2307
|
+
*
|
|
2308
|
+
* Follows ESM spec Section 3.3.1:
|
|
2309
|
+
* - Addition/subtraction: operands must share canonical dimensions
|
|
2310
|
+
* - Multiplication: dimensions add (scales multiply)
|
|
2311
|
+
* - Division: dimensions subtract (scales divide)
|
|
2312
|
+
* - `^` with a constant integer exponent: dimensions scale by the exponent
|
|
2313
|
+
* - `sqrt`: dimensions halve
|
|
2314
|
+
* - `D(x, wrt=t)`: dimension of x divided by dimension of t
|
|
2315
|
+
* - Transcendental functions require dimensionless arguments
|
|
2316
|
+
*
|
|
2317
|
+
* Returns `dimensions: null` for anything INDETERMINATE (see
|
|
2318
|
+
* {@link UnitResult.dimensions}) — an unknown variable, or an operator this
|
|
2319
|
+
* module does not model dimensionally. Indeterminate operands never produce a
|
|
2320
|
+
* mismatch; only a *provable* inconsistency does.
|
|
2321
|
+
*/
|
|
2322
|
+
declare function checkDimensions(expr: Expression, unitBindings: Map<string, ParsedUnit>): UnitResult;
|
|
2323
|
+
/**
|
|
2324
|
+
* Validate dimensional consistency of equations in an ESM file.
|
|
2325
|
+
*
|
|
2326
|
+
* SCOPE: every real inline component — each top-level model / reaction system
|
|
2327
|
+
* AND their inline `subsystems` (walked via `forEachComponent(..., {recurse:
|
|
2328
|
+
* true})`; reference-stub and data-loader subsystems are opaque leaves and are
|
|
2329
|
+
* skipped). For each, `forEachEquation` covers a model's dynamic `equations`
|
|
2330
|
+
* and a reaction system's `constraint_equations`; models additionally have
|
|
2331
|
+
* their `observed` variable expressions checked.
|
|
2332
|
+
*
|
|
2333
|
+
* BINDINGS: the shared top-level environment (top-level models' variables +
|
|
2334
|
+
* reaction systems' species/parameters, scoped key + bare first-wins) is used
|
|
2335
|
+
* for EVERY component, including subsystems. Subsystem-local declarations are
|
|
2336
|
+
* deliberately NOT added, so a name defined only inside a subsystem stays an
|
|
2337
|
+
* "Unknown variable" and keeps the mismatch-suppression in `checkAndReport`.
|
|
2338
|
+
* This is the conservative scope required to broaden coverage without
|
|
2339
|
+
* introducing cross-language divergence: binding a subsystem's own variables
|
|
2340
|
+
* would un-suppress equation-level mismatches for nondimensionalized subsystem
|
|
2341
|
+
* ODEs (e.g. `D(u,t) = k*u` with a dimensionless `u`), which the other bindings
|
|
2342
|
+
* — none of which run a full per-equation dimensional check — never flag. A
|
|
2343
|
+
* top-level reaction system's `constraint_equations` still resolve fully,
|
|
2344
|
+
* because that system's species/parameters ARE in the shared environment.
|
|
2345
|
+
*
|
|
2346
|
+
* SPATIAL-CALCULUS SUGAR: `grad`/`div`/`laplacian` (and `integral`, and any user
|
|
2347
|
+
* op) are ordinary open-tier rewrite-target ops with NO dimensional rule
|
|
2348
|
+
* (esm-spec §4.2 / §4.8.3 "any other op"): their dimension is UNDETERMINABLE
|
|
2349
|
+
* until a discretization rule lowers them to a `D` stencil, so `checkDimensions`
|
|
2350
|
+
* reports UNKNOWN and skips the enclosing check (§4.8.4). There is no coordinate
|
|
2351
|
+
* table and no op-name special case — the checker never divides an operand by a
|
|
2352
|
+
* coordinate's units. Unparseable variable-unit DECLARATIONS are still a defect;
|
|
2353
|
+
* {@link reportUnparseableVariableUnits} flags them per component (the only pass
|
|
2354
|
+
* that sees inline-subsystem variables).
|
|
2355
|
+
*/
|
|
2356
|
+
declare function validateUnits(file: EsmFile): UnitWarning[];
|
|
2357
|
+
|
|
2358
|
+
/**
|
|
2359
|
+
* ESM Format JSON Parsing
|
|
2360
|
+
*
|
|
2361
|
+
* Provides functionality to load and validate ESM files from JSON strings or objects.
|
|
2362
|
+
* Separates concerns: JSON parsing → schema validation → type coercion.
|
|
2363
|
+
*/
|
|
2364
|
+
|
|
2365
|
+
/**
|
|
2366
|
+
* Schema validation error with JSON Pointer path
|
|
2367
|
+
*/
|
|
2368
|
+
interface SchemaError {
|
|
2369
|
+
/** JSON Pointer path to the error location */
|
|
2370
|
+
path: string;
|
|
2371
|
+
/** Human-readable error message */
|
|
2372
|
+
message: string;
|
|
2373
|
+
/** AJV validation keyword that failed */
|
|
2374
|
+
keyword: string;
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Parse error - thrown when JSON parsing fails
|
|
2378
|
+
*/
|
|
2379
|
+
declare class ParseError extends Error {
|
|
2380
|
+
originalError?: Error | undefined;
|
|
2381
|
+
constructor(message: string, originalError?: Error | undefined);
|
|
2382
|
+
}
|
|
2383
|
+
/**
|
|
2384
|
+
* Schema validation error - thrown when schema validation fails
|
|
2385
|
+
*/
|
|
2386
|
+
declare class SchemaValidationError extends Error {
|
|
2387
|
+
errors: SchemaError[];
|
|
2388
|
+
constructor(message: string, errors: SchemaError[]);
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* The schema version this library implements, derived from the embedded
|
|
2392
|
+
* schema's `$id` (https://earthsciml.org/schemas/esm/<version>/esm.schema.json)
|
|
2393
|
+
* so it cannot hand-drift from the canonical esm-schema.json. The package
|
|
2394
|
+
* version in package.json is kept in lockstep.
|
|
2395
|
+
*/
|
|
2396
|
+
declare const SCHEMA_VERSION: string;
|
|
2397
|
+
/**
|
|
2398
|
+
* Validate data against the ESM schema
|
|
2399
|
+
*/
|
|
2400
|
+
declare function validateSchema(data: unknown): SchemaError[];
|
|
2401
|
+
/**
|
|
2402
|
+
* Options controlling how `load()` parses and represents an ESM file.
|
|
2403
|
+
*/
|
|
2404
|
+
interface LoadOptions {
|
|
2405
|
+
/**
|
|
2406
|
+
* When `true`, numeric literals at Expression-bearing positions are
|
|
2407
|
+
* decoded to tagged `NumericLiteral` leaves (see
|
|
2408
|
+
* {@link losslessJsonParse}) so downstream consumers can preserve the
|
|
2409
|
+
* integer-vs-float distinction required by the canonical form
|
|
2410
|
+
* (discretization RFC §5.4.1 / §5.4.6). When `false` or absent
|
|
2411
|
+
* (default), numeric literals decode to plain JS numbers for
|
|
2412
|
+
* backwards compatibility.
|
|
2413
|
+
*
|
|
2414
|
+
* Canonical mode only takes effect for string inputs; pre-parsed
|
|
2415
|
+
* objects are returned as-is (callers that want tagged leaves should
|
|
2416
|
+
* run `losslessJsonParse` themselves before passing the object in).
|
|
2417
|
+
*/
|
|
2418
|
+
canonical?: boolean;
|
|
2419
|
+
/**
|
|
2420
|
+
* Directory anchoring relative `expression_template_imports` refs
|
|
2421
|
+
* (esm-spec §9.7.2). Defaults to the current working directory. Callers
|
|
2422
|
+
* loading from a known file path should pass that file's directory.
|
|
2423
|
+
*/
|
|
2424
|
+
basePath?: string | undefined;
|
|
2425
|
+
/**
|
|
2426
|
+
* Loader-API metaparameter bindings for the root document
|
|
2427
|
+
* (esm-spec §9.7.6 binding site 4): name → integer. Already-closed edge
|
|
2428
|
+
* bindings win; API bindings beat `default`s. Binding a name the
|
|
2429
|
+
* document does not declare raises `template_import_unknown_name`.
|
|
2430
|
+
*/
|
|
2431
|
+
metaparameters?: Record<string, number> | undefined;
|
|
2432
|
+
/**
|
|
2433
|
+
* Synchronous file reader used to resolve template-library import refs.
|
|
2434
|
+
* Defaults to Node's `fs.readFileSync` (via `process.getBuiltinModule`);
|
|
2435
|
+
* browser hosts that need template imports must supply their own.
|
|
2436
|
+
*/
|
|
2437
|
+
readFile?: ((path: string) => string) | undefined;
|
|
2438
|
+
/**
|
|
2439
|
+
* Scope-directed template injection for a §4.7 subsystem-ref edge
|
|
2440
|
+
* (esm-spec §9.7.10 form A): raw §9.7.2 import entries folded into this
|
|
2441
|
+
* document's single top-level component's own scope BEFORE the §9.6.3
|
|
2442
|
+
* fixpoint, so a mounted discretization-agnostic PDE leaf is lowered under
|
|
2443
|
+
* the assembler-chosen discretization. Threaded in by `resolveSubsystemRefs`
|
|
2444
|
+
* from the subsystem edge; not part of the public authoring surface.
|
|
2445
|
+
*/
|
|
2446
|
+
injectedImports?: readonly unknown[] | undefined;
|
|
2447
|
+
/**
|
|
2448
|
+
* Skip schema validation because the caller has already run
|
|
2449
|
+
* {@link validateSchema} on this input. Version checks and the
|
|
2450
|
+
* removed-construct rejections still apply. Used by `validate()` to avoid
|
|
2451
|
+
* validating the same document twice.
|
|
2452
|
+
*/
|
|
2453
|
+
assumeValid?: boolean | undefined;
|
|
2454
|
+
/**
|
|
2455
|
+
* Receives each dimensional-analysis warning instead of the default
|
|
2456
|
+
* `console.warn`. Used by `validate()` to collect unit warnings into its
|
|
2457
|
+
* structured result.
|
|
2458
|
+
*/
|
|
2459
|
+
onUnitWarning?: ((warning: UnitWarning) => void) | undefined;
|
|
2460
|
+
/**
|
|
2461
|
+
* Receives the forward-compatibility warning emitted when the file's minor
|
|
2462
|
+
* version is newer than the schema this build implements, instead of the
|
|
2463
|
+
* default `console.warn`. Parallels {@link onUnitWarning} so hosts can route
|
|
2464
|
+
* both load-time warnings into a structured channel.
|
|
2465
|
+
*/
|
|
2466
|
+
onVersionWarning?: ((message: string) => void) | undefined;
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* Load an ESM file from a JSON string or pre-parsed object
|
|
2470
|
+
*
|
|
2471
|
+
* @param input - JSON string or pre-parsed JavaScript object
|
|
2472
|
+
* @param options - Optional load-time settings (see {@link LoadOptions})
|
|
2473
|
+
* @returns Typed EsmFile object
|
|
2474
|
+
* @throws {ParseError} When JSON parsing fails or version is incompatible
|
|
2475
|
+
* @throws {SchemaValidationError} When schema validation fails
|
|
2476
|
+
*/
|
|
2477
|
+
declare function load(input: string | object, options?: LoadOptions): EsmFile;
|
|
2478
|
+
|
|
2479
|
+
/**
|
|
2480
|
+
* ESM Format JSON Serialization (esm-cs3).
|
|
2481
|
+
*
|
|
2482
|
+
* `save(file)` emits an `EsmFile` as wire-form JSON suitable for round-trip
|
|
2483
|
+
* through `load()`. Mirrors the Python and Julia serializers in three respects:
|
|
2484
|
+
*
|
|
2485
|
+
* 1. **AST canonical numeric handling.** `NumericLiteral` tagged leaves
|
|
2486
|
+
* (the in-memory int/float carrier produced by `losslessJsonParse` and
|
|
2487
|
+
* `intLit` / `floatLit`) are emitted as bare JSON numbers. In default
|
|
2488
|
+
* mode they collapse to plain `number` tokens via `JSON.stringify`. In
|
|
2489
|
+
* `canonical: true` mode they emit per RFC §5.4.6: integer-tagged
|
|
2490
|
+
* leaves as integer tokens, float-tagged leaves with the trailing
|
|
2491
|
+
* `.0` discriminator preserved.
|
|
2492
|
+
*
|
|
2493
|
+
* 2. **Drop transient flags.** The Symbol-keyed
|
|
2494
|
+
* `[NUMERIC_LITERAL_TAG]` brand on tagged literals is non-enumerable
|
|
2495
|
+
* string-key-wise, so `JSON.stringify` already skips it; this module
|
|
2496
|
+
* strips the user-visible `kind` / `value` fields too so the wire
|
|
2497
|
+
* form contains only bare JSON numbers, never the in-memory
|
|
2498
|
+
* `{kind,value}` carrier.
|
|
2499
|
+
*
|
|
2500
|
+
* 3. **Wire-form keys.** TypeScript types are generated from the JSON
|
|
2501
|
+
* schema, so the in-memory shape already matches the wire form (no
|
|
2502
|
+
* Python-style dataclass → wire field-name remapping is needed).
|
|
2503
|
+
* Object key order is the insertion order produced by `load()` /
|
|
2504
|
+
* authored constructors, which is itself schema-driven.
|
|
2505
|
+
*
|
|
2506
|
+
* The Python reference at `pkg/earthsci-ast-py/src/earthsci_ast/serialize.py`
|
|
2507
|
+
* is 1172 LoC because it carries dataclass → wire field-name mappings the
|
|
2508
|
+
* TypeScript binding does not need. The TS implementation stays compact by
|
|
2509
|
+
* delegating shape preservation to the generated types.
|
|
2510
|
+
*/
|
|
2511
|
+
|
|
2512
|
+
/** Optional behavior controls for {@link save}. */
|
|
2513
|
+
interface SaveOptions {
|
|
2514
|
+
/**
|
|
2515
|
+
* When `true`, emit byte-canonical JSON per RFC §5.4.6: integer-tagged
|
|
2516
|
+
* `NumericLiteral` leaves as integer tokens, float-tagged leaves with
|
|
2517
|
+
* the trailing `.0` discriminator preserved (e.g. `1.0` stays `1.0`
|
|
2518
|
+
* rather than collapsing to `1`). Plain JS `number` values keep
|
|
2519
|
+
* `JSON.stringify` semantics in either mode.
|
|
2520
|
+
*
|
|
2521
|
+
* Default: `false` (structural round-trip; integer-valued floats may
|
|
2522
|
+
* collapse to JSON integers).
|
|
2523
|
+
*/
|
|
2524
|
+
canonical?: boolean;
|
|
2525
|
+
/**
|
|
2526
|
+
* Indentation passed through to the underlying JSON formatter.
|
|
2527
|
+
* Default `2` to match the Python and Julia reference serializers.
|
|
2528
|
+
* Set to `0` for a single-line emission.
|
|
2529
|
+
*/
|
|
2530
|
+
indent?: number;
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Serialize an `EsmFile` to wire-form JSON.
|
|
2534
|
+
*
|
|
2535
|
+
* @param file - The `EsmFile` to serialize.
|
|
2536
|
+
* @param options - Optional behavior controls (see {@link SaveOptions}).
|
|
2537
|
+
* @returns Wire-form JSON string.
|
|
2538
|
+
* @throws {CanonicalNonfiniteError} In `canonical: true` mode, if a
|
|
2539
|
+
* `NumericLiteral` leaf holds NaN or ±Infinity (RFC §5.4.6 forbids
|
|
2540
|
+
* non-finite numbers in the canonical wire form).
|
|
2541
|
+
*/
|
|
2542
|
+
declare function save(file: EsmFile, options?: SaveOptions): string;
|
|
2543
|
+
|
|
2544
|
+
/**
|
|
2545
|
+
* Shared validation result / error types for the structural-validation modules.
|
|
2546
|
+
*
|
|
2547
|
+
* Leaf module: no dependency on any other `validate/` file, so the check
|
|
2548
|
+
* modules and the orchestrator can all import these shapes without a cycle.
|
|
2549
|
+
*/
|
|
2550
|
+
|
|
2551
|
+
/**
|
|
2552
|
+
* Validation error with structured details
|
|
2553
|
+
*/
|
|
2554
|
+
interface ValidationError {
|
|
2555
|
+
path: string;
|
|
2556
|
+
message: string;
|
|
2557
|
+
code: string;
|
|
2558
|
+
details: Record<string, unknown>;
|
|
2559
|
+
}
|
|
2560
|
+
/**
|
|
2561
|
+
* Structured validation result
|
|
2562
|
+
*/
|
|
2563
|
+
interface ValidationResult {
|
|
2564
|
+
is_valid: boolean;
|
|
2565
|
+
schema_errors: ValidationError[];
|
|
2566
|
+
structural_errors: ValidationError[];
|
|
2567
|
+
unit_warnings: UnitWarning[];
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
/**
|
|
2571
|
+
* Public `validate()` orchestrator: parses/loads an ESM file, runs schema
|
|
2572
|
+
* validation, then drives every structural (post-schema) validator and
|
|
2573
|
+
* aggregates the results into a {@link ValidationResult}.
|
|
2574
|
+
*
|
|
2575
|
+
* This module imports the check modules (model-, reaction-, coupling-checks)
|
|
2576
|
+
* and shared helpers; the check modules never import back, so there is no cycle.
|
|
2577
|
+
*/
|
|
2578
|
+
|
|
2579
|
+
/**
|
|
2580
|
+
* Options for {@link validate}.
|
|
2581
|
+
*/
|
|
2582
|
+
interface ValidateOptions {
|
|
2583
|
+
/**
|
|
2584
|
+
* Base directory that relative `{ref}` targets and `expression_template_imports`
|
|
2585
|
+
* resolve against — normally the directory of the file being validated.
|
|
2586
|
+
*
|
|
2587
|
+
* WITHOUT it, `validate()` does no file I/O: it cannot open a ref target, so it
|
|
2588
|
+
* cannot know whether that target exists, and every `{ref}` subsystem is
|
|
2589
|
+
* reported as `unresolved_subsystem_ref`. That is a truthful answer (the
|
|
2590
|
+
* document has an unresolved mount) but a useless one for a caller who has the
|
|
2591
|
+
* file on disk and simply wants it validated — and it makes every subsystem-ref
|
|
2592
|
+
* and template-import pin in the shared corpus unsatisfiable, because a
|
|
2593
|
+
* MISSING target and a PRESENT one produce the identical verdict.
|
|
2594
|
+
*
|
|
2595
|
+
* WITH it, refs are resolved (recursively, including the §4.7 index-set merge
|
|
2596
|
+
* and §9.7 template machinery) before structural validation runs: a present
|
|
2597
|
+
* target validates through, and a missing one yields `unresolved_subsystem_ref`
|
|
2598
|
+
* — the two are now distinguishable, which is the whole point.
|
|
2599
|
+
*
|
|
2600
|
+
* Only LOCAL paths resolve here, because `validate()` is synchronous and
|
|
2601
|
+
* `fetch` cannot be awaited; a remote (`http(s)://`) ref is reported as
|
|
2602
|
+
* unresolved with a message pointing at the async `resolveSubsystemRefs()`.
|
|
2603
|
+
*/
|
|
2604
|
+
basePath?: string;
|
|
2605
|
+
}
|
|
2606
|
+
/**
|
|
2607
|
+
* Validate ESM data and return structured validation result.
|
|
2608
|
+
*
|
|
2609
|
+
* @param data - ESM data as JSON string or object
|
|
2610
|
+
* @param options - Optional {@link ValidateOptions}; pass `basePath` to let
|
|
2611
|
+
* relative `{ref}` / template-import targets be opened and resolved.
|
|
2612
|
+
* @returns ValidationResult with validation status and errors
|
|
2613
|
+
*/
|
|
2614
|
+
declare function validate(data: string | object, options?: ValidateOptions): ValidationResult;
|
|
2615
|
+
|
|
2616
|
+
/**
|
|
2617
|
+
* The esm 1.0.0 classification API (esm-spec §6.3.1).
|
|
2618
|
+
*
|
|
2619
|
+
* The format declares TWO variable types, `unknown` and `parameter`. Everything
|
|
2620
|
+
* a solver additionally needs — which unknowns are ODE states, which are
|
|
2621
|
+
* observed, which are algebraic; which parameters are Brownian, discrete,
|
|
2622
|
+
* sampled, constant — is DERIVED from the equations and from each parameter's
|
|
2623
|
+
* `distribution` / `update`, never read off a declared type.
|
|
2624
|
+
*
|
|
2625
|
+
* Every binding exposes the same pure functions of a model, spelled in its own
|
|
2626
|
+
* idiom: snake_case in Julia, Python, Rust and Go; camelCase HERE and only
|
|
2627
|
+
* here. The semantics are identical; only the spelling differs.
|
|
2628
|
+
*
|
|
2629
|
+
* These functions are the ONLY sanctioned way to ask these questions. A site
|
|
2630
|
+
* that used to branch on `variable.type === 'state'` calls {@link isOdeState};
|
|
2631
|
+
* one that branched on `'observed'` calls {@link observedUnknowns}; `'brownian'`
|
|
2632
|
+
* and `'discrete'` call {@link brownianParameters} / {@link discreteParameters}.
|
|
2633
|
+
* Reading a declared type to answer a derived question is precisely what 1.0.0
|
|
2634
|
+
* removes.
|
|
2635
|
+
*
|
|
2636
|
+
* The cross-language oracle is `tests/conformance/classification/`.
|
|
2637
|
+
*/
|
|
2638
|
+
|
|
2639
|
+
/** The four derived parameter categories (esm-spec §6.3.1). */
|
|
2640
|
+
type ParameterClass = 'brownian' | 'discrete' | 'sampled' | 'constant';
|
|
2641
|
+
/** The three derived unknown categories (esm-spec §6.3.1). */
|
|
2642
|
+
type UnknownClass = 'ode_state' | 'observed' | 'algebraic';
|
|
2643
|
+
/** The MTK system type a model maps to. */
|
|
2644
|
+
type SystemKind = 'ode' | 'nonlinear' | 'sde' | 'pde';
|
|
2645
|
+
/** Names of every variable declared `unknown`, sorted. */
|
|
2646
|
+
declare function unknowns(model: Model): string[];
|
|
2647
|
+
/** Names of every variable declared `parameter`, sorted. */
|
|
2648
|
+
declare function parameters(model: Model): string[];
|
|
2649
|
+
/**
|
|
2650
|
+
* Unknowns appearing under `D(·, t)` on some equation LHS — the integrated
|
|
2651
|
+
* states.
|
|
2652
|
+
*/
|
|
2653
|
+
declare function odeStates(model: Model): string[];
|
|
2654
|
+
/** Membership test for {@link odeStates}. */
|
|
2655
|
+
declare function isOdeState(model: Model, name: string): boolean;
|
|
2656
|
+
/**
|
|
2657
|
+
* Unknowns defined by a BARE-VARIABLE LHS (`y ~ f(…)`) — eliminable,
|
|
2658
|
+
* materializable. An unknown that is already an ODE state is not observed.
|
|
2659
|
+
*/
|
|
2660
|
+
declare function observedUnknowns(model: Model): string[];
|
|
2661
|
+
/**
|
|
2662
|
+
* The DEFINING EXPRESSION of every observed unknown: the RHS of the
|
|
2663
|
+
* bare-variable-LHS equation whose LHS is that name.
|
|
2664
|
+
*
|
|
2665
|
+
* This is the 1.0.0 relocation, in one place. An observed unknown's definition
|
|
2666
|
+
* used to live in `variables[v].expression`; it now lives in the model's
|
|
2667
|
+
* `equations` array. Every site that read the removed field reads this instead,
|
|
2668
|
+
* so the relocation is expressed once rather than in each of the ten passes
|
|
2669
|
+
* that used to reach for `variable.expression`.
|
|
2670
|
+
*
|
|
2671
|
+
* Only the first equation for a name is recorded: a second one is an unbalanced
|
|
2672
|
+
* system, which {@link validateEquationBalance} reports rather than this.
|
|
2673
|
+
*/
|
|
2674
|
+
declare function observedDefinitions(model: Model): Map<string, Expression>;
|
|
2675
|
+
/**
|
|
2676
|
+
* Unknowns constrained only implicitly (`H*H*SO4 ~ Ksp`) — everything left once
|
|
2677
|
+
* the ODE states and the observed unknowns are removed. Defining this set by
|
|
2678
|
+
* elimination is what makes the three sets a partition by construction.
|
|
2679
|
+
*/
|
|
2680
|
+
declare function algebraicUnknowns(model: Model): string[];
|
|
2681
|
+
/** The update rules of a parameter, normalized to an array (possibly empty). */
|
|
2682
|
+
declare function updateRules(spec: ParameterUpdateSpec | undefined): ParameterUpdate[];
|
|
2683
|
+
/**
|
|
2684
|
+
* The derived class of ONE parameter. Exported because the cadence pass seeds
|
|
2685
|
+
* its leaves from this rather than re-deriving the categories locally
|
|
2686
|
+
* (CONFORMANCE_SPEC §5.7.2).
|
|
2687
|
+
*/
|
|
2688
|
+
declare function parameterClass(variable: ModelVariable): ParameterClass;
|
|
2689
|
+
/** Parameters whose `update.kind` is `wiener` — the SDE noise sources. */
|
|
2690
|
+
declare function brownianParameters(model: Model): string[];
|
|
2691
|
+
/** Parameters carrying any OTHER update — piecewise-constant between refreshes. */
|
|
2692
|
+
declare function discreteParameters(model: Model): string[];
|
|
2693
|
+
/** Parameters with a `distribution` and no `update` — drawn once at setup. */
|
|
2694
|
+
declare function sampledParameters(model: Model): string[];
|
|
2695
|
+
/** Parameters with neither a `distribution` nor an `update` — plain constants. */
|
|
2696
|
+
declare function constantParameters(model: Model): string[];
|
|
2697
|
+
/**
|
|
2698
|
+
* The system kind DERIVED from the equations and the parameter updates.
|
|
2699
|
+
*
|
|
2700
|
+
* FIRST match wins, and the order is normative
|
|
2701
|
+
* (`tests/conformance/classification/manifest.json`, `system_kind_order`):
|
|
2702
|
+
*
|
|
2703
|
+
* 1. `sde` — any Brownian parameter.
|
|
2704
|
+
* 2. `pde` — any equation contains a spatial derivative.
|
|
2705
|
+
* 3. `nonlinear` — no time-derivative equation at all.
|
|
2706
|
+
* 4. `ode` — otherwise.
|
|
2707
|
+
*
|
|
2708
|
+
* Two orderings that look equivalent are not. `pde` is tested BEFORE
|
|
2709
|
+
* `nonlinear`, so a steady-state PDE (`laplacian(phi) ~ f`, no time derivative)
|
|
2710
|
+
* is `pde`. `sde` is tested BEFORE `pde`, so a model carrying both a wiener
|
|
2711
|
+
* parameter and a spatial derivative is `sde` — not because it is not spatial,
|
|
2712
|
+
* but because there is no SPDESystem constructor to select.
|
|
2713
|
+
*
|
|
2714
|
+
* Detection is a property of the EQUATIONS and never of the `domain` block:
|
|
2715
|
+
* v0.8.0 removed `Domain.spatial`, so `domain` carries nothing spatial.
|
|
2716
|
+
*/
|
|
2717
|
+
declare function systemKind(model: Model): SystemKind;
|
|
2718
|
+
/** The model's explicit `system_kind` field, or `null` when absent. */
|
|
2719
|
+
declare function declaredSystemKind(model: Model): SystemKind | null;
|
|
2720
|
+
/** Every derived set for one model node, as the conformance goldens spell it. */
|
|
2721
|
+
interface ModelClassification {
|
|
2722
|
+
odeStates: string[];
|
|
2723
|
+
observedUnknowns: string[];
|
|
2724
|
+
algebraicUnknowns: string[];
|
|
2725
|
+
brownianParameters: string[];
|
|
2726
|
+
discreteParameters: string[];
|
|
2727
|
+
sampledParameters: string[];
|
|
2728
|
+
constantParameters: string[];
|
|
2729
|
+
systemKind: SystemKind;
|
|
2730
|
+
declaredSystemKind: SystemKind | null;
|
|
2731
|
+
}
|
|
2732
|
+
/** Classify one model node. */
|
|
2733
|
+
declare function classifyModel(model: Model): ModelClassification;
|
|
2734
|
+
/**
|
|
2735
|
+
* Classify every model node in a document, keyed by DOT-PATH from the document
|
|
2736
|
+
* root, so a subsystem is `Parent.Child`. Classification is per model NODE, not
|
|
2737
|
+
* per document: the names inside each list are LOCAL to that model and are not
|
|
2738
|
+
* namespaced. A binding that flattens the document first and classifies once
|
|
2739
|
+
* returns one merged answer instead of a scoped answer per node.
|
|
2740
|
+
*/
|
|
2741
|
+
declare function classifyDocument(models: {
|
|
2742
|
+
[k: string]: unknown;
|
|
2743
|
+
}): {
|
|
2744
|
+
[path: string]: ModelClassification;
|
|
2745
|
+
};
|
|
2746
|
+
|
|
2747
|
+
/**
|
|
2748
|
+
* Cadence-class seeding for the dependency-partition pass
|
|
2749
|
+
* (CONFORMANCE_SPEC §5.7, normative; RFC semiring-faq-unified-ir §6.1).
|
|
2750
|
+
*
|
|
2751
|
+
* Every value is determined at one of three cadences, totally ordered
|
|
2752
|
+
* `const ⊏ discrete ⊏ continuous`, and a node's class is `max` over its inputs.
|
|
2753
|
+
* This module supplies the LEAF SEEDS that recursion bottoms out at, plus the
|
|
2754
|
+
* `max`-over-an-expression helper built on them.
|
|
2755
|
+
*
|
|
2756
|
+
* **The seeds come from the §6.3.1 classification API, never from a locally
|
|
2757
|
+
* re-derived notion of the categories.** §5.7.2 states the leaf-seed table in
|
|
2758
|
+
* terms of those functions precisely so that five bindings cannot disagree
|
|
2759
|
+
* about which nodes fold. Re-deriving "is this a state" here would be a sixth
|
|
2760
|
+
* derivation and a sixth chance to be wrong.
|
|
2761
|
+
*
|
|
2762
|
+
* | Leaf | Seed |
|
|
2763
|
+
* |---|---|
|
|
2764
|
+
* | the independent variable `t` | `continuous` |
|
|
2765
|
+
* | an unknown in `odeStates` | `continuous` |
|
|
2766
|
+
* | an unknown in `algebraicUnknowns` | `continuous` |
|
|
2767
|
+
* | an unknown in `observedUnknowns` | the join of its DEFINING EQUATION's RHS |
|
|
2768
|
+
* | a parameter in `brownianParameters` | `continuous` (resampled every step) |
|
|
2769
|
+
* | a parameter in `discreteParameters` | `discrete`, refined by its source |
|
|
2770
|
+
* | a parameter in `sampledParameters` / `constantParameters` | `const` |
|
|
2771
|
+
* | a numeric literal, index-set name, bound index symbol | `const` |
|
|
2772
|
+
*
|
|
2773
|
+
* The OBSERVED leaf is the one 1.0.0 changes, and it must not be shortcut.
|
|
2774
|
+
* Before 1.0.0 an observed leaf seeded `const`, with the code admitting that
|
|
2775
|
+
* was imprecise and unexercised. That is now both unavailable (observed and
|
|
2776
|
+
* ODE-state are the same declared type) and unsound, since an observed defined
|
|
2777
|
+
* from a state is `continuous`. Seeding every unknown `continuous` is equally
|
|
2778
|
+
* wrong the other way: it would stop a STATE-FREE observed from folding, and
|
|
2779
|
+
* const-folding exactly those is what the geometry and projection-pushdown
|
|
2780
|
+
* paths rely on. So an observed leaf resolves to the join of its defining
|
|
2781
|
+
* equation's RHS, transitively, memoised, with a cycle guard.
|
|
2782
|
+
*/
|
|
2783
|
+
|
|
2784
|
+
/** The three cadence classes, totally ordered `const ⊏ discrete ⊏ continuous`. */
|
|
2785
|
+
type CadenceClass = 'const' | 'discrete' | 'continuous';
|
|
2786
|
+
/** The join (`max`) of two cadence classes. */
|
|
2787
|
+
declare function joinCadence(a: CadenceClass, b: CadenceClass): CadenceClass;
|
|
2788
|
+
/** The join of any number of cadence classes; `const` when there are none. */
|
|
2789
|
+
declare function joinAll(classes: Iterable<CadenceClass>): CadenceClass;
|
|
2790
|
+
/** Raised when the observed-definition chain contains a cycle. */
|
|
2791
|
+
declare class CadenceCycleError extends Error {
|
|
2792
|
+
readonly cycle: string[];
|
|
2793
|
+
constructor(cycle: string[]);
|
|
2794
|
+
}
|
|
2795
|
+
/**
|
|
2796
|
+
* A reusable cadence seeder for ONE model. Holds the memo table for observed
|
|
2797
|
+
* resolution, so a chain of observeds is resolved once rather than once per
|
|
2798
|
+
* reference.
|
|
2799
|
+
*/
|
|
2800
|
+
declare class CadenceSeeder {
|
|
2801
|
+
private readonly model;
|
|
2802
|
+
private readonly esmFile?;
|
|
2803
|
+
private readonly states;
|
|
2804
|
+
private readonly algebraic;
|
|
2805
|
+
private readonly brownian;
|
|
2806
|
+
private readonly observedDefs;
|
|
2807
|
+
private readonly memo;
|
|
2808
|
+
private readonly inProgress;
|
|
2809
|
+
private readonly independentVariable;
|
|
2810
|
+
constructor(model: Model, esmFile?: EsmFile | undefined);
|
|
2811
|
+
/** The set of observed unknowns, for callers that want to enumerate them. */
|
|
2812
|
+
observedNames(): string[];
|
|
2813
|
+
/**
|
|
2814
|
+
* The cadence seed of a single NAME appearing as a leaf.
|
|
2815
|
+
*
|
|
2816
|
+
* A name that is not declared in this model — an index-set name, a bound index
|
|
2817
|
+
* symbol, a relation tag, a coupled reference — seeds `const`, matching the
|
|
2818
|
+
* final row of the §5.7.2 table.
|
|
2819
|
+
*/
|
|
2820
|
+
leaf(name: string): CadenceClass;
|
|
2821
|
+
/**
|
|
2822
|
+
* A parameter's seed: `continuous` when Brownian, `const` when sampled or
|
|
2823
|
+
* constant, otherwise `discrete` subject to the source refinement.
|
|
2824
|
+
*
|
|
2825
|
+
* **Source-seeded refinement** (§5.7.2, RFC pure-io-data-loaders §4.6). When a
|
|
2826
|
+
* parameter's `update` is the `data` kind, its `source` names a `data_sources`
|
|
2827
|
+
* entry, and it is the SOURCE — not the parameter's own declaration — that
|
|
2828
|
+
* fixes the seed. A source WITH `temporal` keeps the parameter `discrete`
|
|
2829
|
+
* (its refresh cadence is the source's update times); one WITHOUT describes
|
|
2830
|
+
* non-time-varying data, so the parameter refines down to `const` — loaded
|
|
2831
|
+
* once. Any other update kind, or a `source` that resolves to no entry, keeps
|
|
2832
|
+
* the `discrete` seed.
|
|
2833
|
+
*
|
|
2834
|
+
* This is the one context in which a leaf's seed reads a document field
|
|
2835
|
+
* outside its own declaration.
|
|
2836
|
+
*/
|
|
2837
|
+
private parameterSeed;
|
|
2838
|
+
/**
|
|
2839
|
+
* The cadence of an EXPRESSION: `max` over its leaves.
|
|
2840
|
+
*
|
|
2841
|
+
* The gather rule needs no special case — index expressions are ordinary
|
|
2842
|
+
* children, so `index(u, index(nbr, i, k))` splits naturally, the inner
|
|
2843
|
+
* neighbour selection staying `const` while the outer value load is
|
|
2844
|
+
* `continuous` because it touches `u`.
|
|
2845
|
+
*/
|
|
2846
|
+
expression(expr: Expression): CadenceClass;
|
|
2847
|
+
}
|
|
2848
|
+
/** The cadence seed of one leaf NAME in a model. */
|
|
2849
|
+
declare function leafCadence(model: Model, name: string, esmFile?: EsmFile): CadenceClass;
|
|
2850
|
+
/** The cadence of an expression in a model: `max` over its leaves. */
|
|
2851
|
+
declare function expressionCadence(model: Model, expr: Expression, esmFile?: EsmFile): CadenceClass;
|
|
2852
|
+
|
|
2853
|
+
/**
|
|
2854
|
+
* Graph generation utilities for ESM files
|
|
2855
|
+
*
|
|
2856
|
+
* Provides functions to extract different graph representations from ESM files,
|
|
2857
|
+
* as specified in the ESM Libraries Specification Section 4.8.
|
|
2858
|
+
*/
|
|
2859
|
+
|
|
2860
|
+
/** Graph node representing a component in the system */
|
|
2861
|
+
interface ComponentNode {
|
|
2862
|
+
/** Unique identifier for this component */
|
|
2863
|
+
id: string;
|
|
2864
|
+
/** Display name for the component */
|
|
2865
|
+
name: string;
|
|
2866
|
+
/**
|
|
2867
|
+
* Type of component. From 1.0.0 there is no `data_loader`: a data source is
|
|
2868
|
+
* ingest configuration, not a component, so it is neither a graph node nor a
|
|
2869
|
+
* coupling endpoint (esm-spec §5.5).
|
|
2870
|
+
*/
|
|
2871
|
+
type: 'model' | 'reaction_system';
|
|
2872
|
+
/** Optional description */
|
|
2873
|
+
description?: string;
|
|
2874
|
+
/** Optional reference information */
|
|
2875
|
+
reference?: Reference;
|
|
2876
|
+
/** Metadata with counts for this component */
|
|
2877
|
+
metadata: {
|
|
2878
|
+
/** Number of variables */
|
|
2879
|
+
var_count: number;
|
|
2880
|
+
/** Number of equations */
|
|
2881
|
+
eq_count: number;
|
|
2882
|
+
/** Number of species (for reaction systems) */
|
|
2883
|
+
species_count: number;
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
/** Graph edge representing a coupling relationship */
|
|
2887
|
+
interface CouplingEdge {
|
|
2888
|
+
/** Unique identifier for this edge */
|
|
2889
|
+
id: string;
|
|
2890
|
+
/** Source component ID */
|
|
2891
|
+
from: string;
|
|
2892
|
+
/** Target component ID */
|
|
2893
|
+
to: string;
|
|
2894
|
+
/** Type of coupling */
|
|
2895
|
+
type: CouplingEntry['type'];
|
|
2896
|
+
/** Display label for the edge */
|
|
2897
|
+
label: string;
|
|
2898
|
+
/** Optional description */
|
|
2899
|
+
description?: string;
|
|
2900
|
+
/** Full coupling entry for editing */
|
|
2901
|
+
coupling: CouplingEntry;
|
|
2902
|
+
}
|
|
2903
|
+
/** System graph representation with components and couplings */
|
|
2904
|
+
interface ComponentGraph {
|
|
2905
|
+
/** All components in the system */
|
|
2906
|
+
nodes: ComponentNode[];
|
|
2907
|
+
/** All coupling relationships */
|
|
2908
|
+
edges: CouplingEdge[];
|
|
2909
|
+
}
|
|
2910
|
+
/**
|
|
2911
|
+
* Directed graph with node/edge lists plus adjacency, predecessor, and
|
|
2912
|
+
* successor lookups (ESM Libraries Specification §4.8). Nodes are addressed by
|
|
2913
|
+
* a string key (`ComponentNode.id` / `VariableNode.name`); edges reference
|
|
2914
|
+
* those keys through `source`/`target`.
|
|
2915
|
+
*/
|
|
2916
|
+
interface Graph<N, E> {
|
|
2917
|
+
/** All nodes in the graph */
|
|
2918
|
+
nodes: N[];
|
|
2919
|
+
/** All edges in the graph */
|
|
2920
|
+
edges: Array<{
|
|
2921
|
+
source: string;
|
|
2922
|
+
target: string;
|
|
2923
|
+
data: E;
|
|
2924
|
+
}>;
|
|
2925
|
+
/** Get adjacent nodes for a given node */
|
|
2926
|
+
adjacency(node: string): string[];
|
|
2927
|
+
/** Get predecessor nodes for a given node */
|
|
2928
|
+
predecessors(node: string): string[];
|
|
2929
|
+
/** Get successor nodes for a given node */
|
|
2930
|
+
successors(node: string): string[];
|
|
2931
|
+
}
|
|
2932
|
+
/** Graph node representing a variable/parameter/species in the system */
|
|
2933
|
+
interface VariableNode {
|
|
2934
|
+
/** Unique identifier for this variable (scoped, e.g., "Transport.temperature") */
|
|
2935
|
+
name: string;
|
|
2936
|
+
/**
|
|
2937
|
+
* The variable's DERIVED category (esm-spec §6.3.1), not its declared type.
|
|
2938
|
+
* The format declares only `unknown` and `parameter`; these are the finer
|
|
2939
|
+
* categories a consumer of the graph actually wants, recovered from the
|
|
2940
|
+
* equations and from each parameter's `distribution` / `update`.
|
|
2941
|
+
*
|
|
2942
|
+
* `state` is an ODE state, `observed` an unknown with a bare-variable-LHS
|
|
2943
|
+
* definition, `algebraic` an implicitly-constrained unknown, `brownian` a
|
|
2944
|
+
* wiener-updated parameter, `discrete` a parameter with any other update,
|
|
2945
|
+
* `parameter` a sampled or constant one, and `species` a reaction-system
|
|
2946
|
+
* species.
|
|
2947
|
+
*/
|
|
2948
|
+
kind: 'state' | 'algebraic' | 'parameter' | 'observed' | 'brownian' | 'discrete' | 'species';
|
|
2949
|
+
/** Units if specified */
|
|
2950
|
+
units?: string;
|
|
2951
|
+
/** System/component this variable belongs to */
|
|
2952
|
+
system: string;
|
|
2953
|
+
}
|
|
2954
|
+
/**
|
|
2955
|
+
* Graph edge representing a dependency between variables.
|
|
2956
|
+
*
|
|
2957
|
+
* The `equation_index` sentinel {@link NON_EQUATION_INDEX} (`-1`) marks a
|
|
2958
|
+
* dependency that does not originate from a positionally-numbered equation or
|
|
2959
|
+
* reaction — i.e. an observed/expression definition or a coupling variable map.
|
|
2960
|
+
*/
|
|
2961
|
+
interface DependencyEdge {
|
|
2962
|
+
/** Source variable name */
|
|
2963
|
+
source: string;
|
|
2964
|
+
/** Target variable name */
|
|
2965
|
+
target: string;
|
|
2966
|
+
/**
|
|
2967
|
+
* PROVENANCE category of the dependency — which structural site produced it,
|
|
2968
|
+
* NOT a classification of the operators involved. See {@link EDGE_PROVENANCE}
|
|
2969
|
+
* for the mapping. These values are historical labels and do NOT track the
|
|
2970
|
+
* actual operator: an equation edge is always `'additive'` (even for
|
|
2971
|
+
* `w = u * v`) and an observed-definition edge is always `'multiplicative'`
|
|
2972
|
+
* (even for `w = u + v`), regardless of the `+`/`*`/etc. actually used. Do
|
|
2973
|
+
* not read arithmetic meaning into them.
|
|
2974
|
+
*/
|
|
2975
|
+
relationship: 'additive' | 'multiplicative' | 'rate' | 'stoichiometric';
|
|
2976
|
+
/**
|
|
2977
|
+
* Position of the equation/reaction that created this dependency, or
|
|
2978
|
+
* {@link NON_EQUATION_INDEX} (`-1`) when the dependency has no positional
|
|
2979
|
+
* equation (observed-variable definitions and coupling maps).
|
|
2980
|
+
*/
|
|
2981
|
+
equation_index: number;
|
|
2982
|
+
/** The expression that created this dependency */
|
|
2983
|
+
expression: Expr;
|
|
2984
|
+
}
|
|
2985
|
+
/**
|
|
2986
|
+
* Extract the system graph from an ESM file.
|
|
2987
|
+
* Returns a directed graph (ESM Libraries Specification §4.8) where nodes are
|
|
2988
|
+
* model components and edges are coupling rules, with adjacency helpers.
|
|
2989
|
+
*/
|
|
2990
|
+
declare function componentGraph(file: EsmFile): Graph<ComponentNode, CouplingEdge>;
|
|
2991
|
+
/**
|
|
2992
|
+
* Extract the system graph from an ESM file in the legacy `{nodes, edges}`
|
|
2993
|
+
* {@link ComponentGraph} shape (edges as {@link CouplingEdge} carrying
|
|
2994
|
+
* `from`/`to`).
|
|
2995
|
+
*
|
|
2996
|
+
* @deprecated Prefer {@link componentGraph}, which returns the richer
|
|
2997
|
+
* {@link Graph} with adjacency/predecessor/successor helpers. This snake_case
|
|
2998
|
+
* alias is retained because the editor's web-components consume the flat
|
|
2999
|
+
* `{nodes, edges}` shape; it will be removed once those callers migrate.
|
|
3000
|
+
*/
|
|
3001
|
+
declare function component_graph(esmFile: EsmFile): ComponentGraph;
|
|
3002
|
+
/**
|
|
3003
|
+
* Utility to check if a component exists in the ESM file
|
|
3004
|
+
*/
|
|
3005
|
+
declare function componentExists(esmFile: EsmFile, componentId: string): boolean;
|
|
3006
|
+
/**
|
|
3007
|
+
* Get the type of a component by its ID
|
|
3008
|
+
*/
|
|
3009
|
+
declare function getComponentType(esmFile: EsmFile, componentId: string): ComponentNode['type'] | null;
|
|
3010
|
+
/**
|
|
3011
|
+
* Extract a variable-level dependency graph from an ESM file, model, reaction
|
|
3012
|
+
* system, equation, reaction, or expression. Nodes are variables/parameters/
|
|
3013
|
+
* species; edges represent dependencies (ESM Libraries Specification §4.8).
|
|
3014
|
+
*
|
|
3015
|
+
* @param target The target to analyze (EsmFile, Model, ReactionSystem, Equation, Reaction, or Expr)
|
|
3016
|
+
* @param options Optional settings. `mergeCoupled` folds `variable_map` coupling
|
|
3017
|
+
* entries into cross-system edges (EsmFile targets only). `merge_coupled` is a
|
|
3018
|
+
* deprecated alias accepted for back-compat.
|
|
3019
|
+
* @returns Graph with VariableNode nodes and DependencyEdge edges
|
|
3020
|
+
*/
|
|
3021
|
+
declare function expressionGraph(target: EsmFile | Model | ReactionSystem | Equation | Reaction | Expr, options?: {
|
|
3022
|
+
mergeCoupled?: boolean;
|
|
3023
|
+
/** @deprecated Use `mergeCoupled`. */
|
|
3024
|
+
merge_coupled?: boolean;
|
|
3025
|
+
}): Graph<VariableNode, DependencyEdge>;
|
|
3026
|
+
/**
|
|
3027
|
+
* Export graph as Graphviz DOT format.
|
|
3028
|
+
* Node shapes: box for models and reaction systems, diamond for operators.
|
|
3029
|
+
* Edge styles: solid for compose, dashed for variable_map.
|
|
3030
|
+
*/
|
|
3031
|
+
declare function toDot<N extends object, E>(graph: Graph<N, E>): string;
|
|
3032
|
+
/**
|
|
3033
|
+
* Export graph as Mermaid flowchart format for Markdown embedding.
|
|
3034
|
+
*/
|
|
3035
|
+
declare function toMermaid<N extends object, E>(graph: Graph<N, E>): string;
|
|
3036
|
+
/**
|
|
3037
|
+
* Export graph as JSON adjacency list format for web consumption.
|
|
3038
|
+
*/
|
|
3039
|
+
declare function toJsonGraph<N extends object, E>(graph: Graph<N, E>): string;
|
|
3040
|
+
|
|
3041
|
+
/**
|
|
3042
|
+
* Advanced expression analysis and manipulation types
|
|
3043
|
+
*
|
|
3044
|
+
* This module defines the core types for advanced expression analysis,
|
|
3045
|
+
* including dependency graphs, complexity metrics, and manipulation utilities.
|
|
3046
|
+
*/
|
|
3047
|
+
|
|
3048
|
+
/**
|
|
3049
|
+
* The kind of a variable node. Derived from graph.ts's {@link VariableNode} so
|
|
3050
|
+
* the union lives in exactly one place (analysis and the parent graph module
|
|
3051
|
+
* must agree on the vocabulary of variable kinds).
|
|
3052
|
+
*/
|
|
3053
|
+
type VariableKind = VariableNode['kind'];
|
|
3054
|
+
/**
|
|
3055
|
+
* Node representing a variable in a dependency graph.
|
|
3056
|
+
*
|
|
3057
|
+
* Overlaps graph.ts's {@link VariableNode} (both carry `name`/`kind`/`units`/
|
|
3058
|
+
* `system`); this analysis variant additionally tracks the defining expression
|
|
3059
|
+
* ({@link definition}) and the topological {@link depth}. The two families are
|
|
3060
|
+
* kept separate because they are produced by different builders
|
|
3061
|
+
* (`analysis/buildDependencyGraph` vs graph.ts's `expressionGraph`) with
|
|
3062
|
+
* different edge payloads; the shared `kind` vocabulary is unified via
|
|
3063
|
+
* {@link VariableKind}.
|
|
3064
|
+
*/
|
|
3065
|
+
interface DependencyNode {
|
|
3066
|
+
/** Variable name */
|
|
3067
|
+
name: string;
|
|
3068
|
+
/** DERIVED variable category (state, algebraic, observed, parameter, brownian, discrete, species) — see {@link VariableKind}. */
|
|
3069
|
+
kind: VariableKind;
|
|
3070
|
+
/** System/model this variable belongs to */
|
|
3071
|
+
system: string;
|
|
3072
|
+
/** Units if specified */
|
|
3073
|
+
units?: string;
|
|
3074
|
+
/** Definition expression if available */
|
|
3075
|
+
definition?: Expr;
|
|
3076
|
+
/** Nesting level in the dependency graph */
|
|
3077
|
+
depth: number;
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* Edge representing a dependency relationship between variables.
|
|
3081
|
+
*
|
|
3082
|
+
* Analysis-local counterpart of graph.ts's {@link DependencyEdge}; the two use
|
|
3083
|
+
* disjoint edge vocabularies (`type` here vs `relationship`/`equation_index`
|
|
3084
|
+
* there) because they are built by different graph constructors.
|
|
3085
|
+
*/
|
|
3086
|
+
interface DependencyRelation {
|
|
3087
|
+
/** Source variable */
|
|
3088
|
+
source: string;
|
|
3089
|
+
/** Target variable */
|
|
3090
|
+
target: string;
|
|
3091
|
+
/** Type of dependency */
|
|
3092
|
+
type: 'direct' | 'circular' | 'parameter_dependency' | 'definition_dependency';
|
|
3093
|
+
/** Expression that creates this dependency */
|
|
3094
|
+
expression?: Expr;
|
|
3095
|
+
}
|
|
3096
|
+
/** Graph representing variable dependencies */
|
|
3097
|
+
interface DependencyGraph extends Graph<DependencyNode, DependencyRelation> {
|
|
3098
|
+
/** Check for circular dependencies */
|
|
3099
|
+
hasCircularDependencies(): boolean;
|
|
3100
|
+
/**
|
|
3101
|
+
* Circular-dependency cycles. Each entry is one back-edge cycle found by a
|
|
3102
|
+
* DFS over the directed edges; distinct cycles may share nodes (these are
|
|
3103
|
+
* NOT strongly-connected components).
|
|
3104
|
+
*/
|
|
3105
|
+
getCycles(): DependencyNode[][];
|
|
3106
|
+
/**
|
|
3107
|
+
* @deprecated Misnomer — this does NOT compute strongly-connected
|
|
3108
|
+
* components; it returns the raw DFS cycles from {@link getCycles}. Use
|
|
3109
|
+
* {@link getCycles} instead.
|
|
3110
|
+
*/
|
|
3111
|
+
getStronglyConnectedComponents(): DependencyNode[][];
|
|
3112
|
+
/** Topological sort of dependencies */
|
|
3113
|
+
topologicalSort(): DependencyNode[];
|
|
3114
|
+
}
|
|
3115
|
+
/** Complexity metrics for an expression */
|
|
3116
|
+
interface ComplexityMetrics {
|
|
3117
|
+
/** Total depth of the expression tree */
|
|
3118
|
+
depth: number;
|
|
3119
|
+
/** Total number of operations */
|
|
3120
|
+
operationCount: number;
|
|
3121
|
+
/** Number of unique variables */
|
|
3122
|
+
variableCount: number;
|
|
3123
|
+
/** Number of constants */
|
|
3124
|
+
constantCount: number;
|
|
3125
|
+
/** Distribution of operation types */
|
|
3126
|
+
operationTypes: Record<string, number>;
|
|
3127
|
+
/** Estimated computational cost (arbitrary units) */
|
|
3128
|
+
computationalCost: number;
|
|
3129
|
+
/** Memory usage estimate (arbitrary units) */
|
|
3130
|
+
memoryUsage: number;
|
|
3131
|
+
}
|
|
3132
|
+
/** A single numerical-stability finding produced by `detectStabilityIssues`. */
|
|
3133
|
+
interface StabilityIssue {
|
|
3134
|
+
/** Human-readable description of the issue */
|
|
3135
|
+
issue: string;
|
|
3136
|
+
/** Severity of the issue */
|
|
3137
|
+
severity: 'low' | 'medium' | 'high';
|
|
3138
|
+
/** Path to the offending subexpression (e.g. `['args[1]']`) */
|
|
3139
|
+
path: string[];
|
|
3140
|
+
/** Suggested remediation */
|
|
3141
|
+
suggestion: string;
|
|
3142
|
+
}
|
|
3143
|
+
/** Common subexpression identification result */
|
|
3144
|
+
interface CommonSubexpression {
|
|
3145
|
+
/** The common subexpression */
|
|
3146
|
+
expression: Expr;
|
|
3147
|
+
/** Locations where this subexpression appears */
|
|
3148
|
+
locations: ExpressionLocation[];
|
|
3149
|
+
/** Number of occurrences */
|
|
3150
|
+
count: number;
|
|
3151
|
+
/** Estimated cost savings from factoring out */
|
|
3152
|
+
savings: number;
|
|
3153
|
+
}
|
|
3154
|
+
/** Location of an expression within a larger structure */
|
|
3155
|
+
interface ExpressionLocation {
|
|
3156
|
+
/** Path to the expression (e.g. `['root', 'args[0]', 'args[1]']`) */
|
|
3157
|
+
path: string[];
|
|
3158
|
+
/** Human-readable description */
|
|
3159
|
+
description: string;
|
|
3160
|
+
/** Parent expression context */
|
|
3161
|
+
context?: Expr;
|
|
3162
|
+
}
|
|
3163
|
+
/** Result of symbolic differentiation */
|
|
3164
|
+
interface DerivativeResult {
|
|
3165
|
+
/** The derivative expression */
|
|
3166
|
+
derivative: Expr;
|
|
3167
|
+
/** Variable with respect to which we differentiated */
|
|
3168
|
+
variable: string;
|
|
3169
|
+
/** Simplified form if different from derivative */
|
|
3170
|
+
simplified?: Expr;
|
|
3171
|
+
/**
|
|
3172
|
+
* For {@link higherOrderDerivative}: one entry per differentiation order,
|
|
3173
|
+
* recording the expression at that order (`expression`) and its derivative
|
|
3174
|
+
* (`derivative`, i.e. the expression at the next order). These are the
|
|
3175
|
+
* successive derivative steps, NOT chain-rule multiplicative factors — hence
|
|
3176
|
+
* the name `derivativeSteps` rather than the former misnomer `chainComponents`.
|
|
3177
|
+
*/
|
|
3178
|
+
derivativeSteps?: Array<{
|
|
3179
|
+
expression: Expr;
|
|
3180
|
+
derivative: Expr;
|
|
3181
|
+
}>;
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
/**
|
|
3185
|
+
* Variable dependency graph construction and analysis
|
|
3186
|
+
*
|
|
3187
|
+
* This module provides functions to construct and analyze dependency graphs
|
|
3188
|
+
* for variables in ESM files, supporting circular dependency detection,
|
|
3189
|
+
* topological sorting, and dead code elimination.
|
|
3190
|
+
*/
|
|
3191
|
+
|
|
3192
|
+
/**
|
|
3193
|
+
* Build a dependency graph from an ESM file, model, or expression
|
|
3194
|
+
* @param target The target to analyze
|
|
3195
|
+
* @param options Analysis options
|
|
3196
|
+
* @returns Dependency graph with nodes and edges
|
|
3197
|
+
*/
|
|
3198
|
+
declare function buildDependencyGraph(target: EsmFile | Model | ReactionSystem | Expr, options?: {
|
|
3199
|
+
includeParameters?: boolean;
|
|
3200
|
+
includeObserved?: boolean;
|
|
3201
|
+
mergeAcrossSystems?: boolean;
|
|
3202
|
+
}): DependencyGraph;
|
|
3203
|
+
/**
|
|
3204
|
+
* Find dependency-graph sinks: non-state variables that nothing else depends
|
|
3205
|
+
* on. Note this includes terminal observed outputs — a sink is only truly
|
|
3206
|
+
* "dead" if it is also not consumed outside the model (plots, couplings,
|
|
3207
|
+
* downstream tooling), which this graph cannot see. State variables are
|
|
3208
|
+
* excluded because they are integration outputs by definition.
|
|
3209
|
+
*/
|
|
3210
|
+
declare function findDeadVariables(graph: DependencyGraph): DependencyNode[];
|
|
3211
|
+
/**
|
|
3212
|
+
* Enumerate every path from `startNode` to a sink (a node with no successors),
|
|
3213
|
+
* following successor edges. Paths that revisit a node or exceed `maxDepth`
|
|
3214
|
+
* hops are pruned.
|
|
3215
|
+
*/
|
|
3216
|
+
declare function findDependencyChains(graph: DependencyGraph, startNode: string, maxDepth?: number): string[][];
|
|
3217
|
+
|
|
3218
|
+
/**
|
|
3219
|
+
* Expression complexity metrics and analysis
|
|
3220
|
+
*
|
|
3221
|
+
* This module provides functions to analyze the computational complexity
|
|
3222
|
+
* of expressions, including depth, operation counts, and estimated costs.
|
|
3223
|
+
*/
|
|
3224
|
+
|
|
3225
|
+
/**
|
|
3226
|
+
* Analyze the complexity of an expression
|
|
3227
|
+
* @param expr Expression to analyze
|
|
3228
|
+
* @returns Complexity metrics
|
|
3229
|
+
*/
|
|
3230
|
+
declare function analyzeComplexity(expr: Expr): ComplexityMetrics;
|
|
3231
|
+
/**
|
|
3232
|
+
* Compare complexity of two expressions
|
|
3233
|
+
* @param expr1 First expression
|
|
3234
|
+
* @param expr2 Second expression
|
|
3235
|
+
* @returns Comparison result (-1: expr1 simpler, 0: equal, 1: expr1 more complex)
|
|
3236
|
+
*/
|
|
3237
|
+
declare function compareComplexity(expr1: Expr, expr2: Expr): number;
|
|
3238
|
+
/**
|
|
3239
|
+
* Classify expression complexity level
|
|
3240
|
+
* @param expr Expression to classify
|
|
3241
|
+
* @returns Complexity level
|
|
3242
|
+
*/
|
|
3243
|
+
declare function classifyComplexity(expr: Expr): 'trivial' | 'simple' | 'moderate' | 'complex' | 'very_complex';
|
|
3244
|
+
/**
|
|
3245
|
+
* Find the most expensive sub-expressions in an expression
|
|
3246
|
+
* @param expr Expression to analyze
|
|
3247
|
+
* @param limit Maximum number of results to return
|
|
3248
|
+
* @returns Array of expensive sub-expressions with their costs
|
|
3249
|
+
*/
|
|
3250
|
+
declare function findExpensiveSubexpressions(expr: Expr, limit?: number): Array<{
|
|
3251
|
+
expression: Expr;
|
|
3252
|
+
cost: number;
|
|
3253
|
+
path: string[];
|
|
3254
|
+
}>;
|
|
3255
|
+
/**
|
|
3256
|
+
* Estimate parallel execution potential
|
|
3257
|
+
* @param expr Expression to analyze
|
|
3258
|
+
* @returns Parallelization score (0-1, higher means more parallelizable)
|
|
3259
|
+
*/
|
|
3260
|
+
declare function estimateParallelPotential(expr: Expr): number;
|
|
3261
|
+
/**
|
|
3262
|
+
* Detect numerical stability issues in expressions
|
|
3263
|
+
* @param expr Expression to analyze
|
|
3264
|
+
* @returns Array of potential stability issues
|
|
3265
|
+
*/
|
|
3266
|
+
declare function detectStabilityIssues(expr: Expr): StabilityIssue[];
|
|
3267
|
+
|
|
3268
|
+
/**
|
|
3269
|
+
* Common subexpression identification and elimination
|
|
3270
|
+
*
|
|
3271
|
+
* This module provides functions to identify repeated subexpressions
|
|
3272
|
+
* within expressions or across multiple expressions in a model.
|
|
3273
|
+
*/
|
|
3274
|
+
|
|
3275
|
+
/**
|
|
3276
|
+
* Default minimum {@link analyzeComplexity} cost a subexpression must reach to
|
|
3277
|
+
* be considered for factoring. Shared by every entry point below.
|
|
3278
|
+
*/
|
|
3279
|
+
declare const DEFAULT_MIN_COMPLEXITY = 5;
|
|
3280
|
+
/**
|
|
3281
|
+
* Find common subexpressions in a single expression
|
|
3282
|
+
* @param expr Expression to analyze
|
|
3283
|
+
* @param minComplexity Minimum complexity threshold for considering subexpressions
|
|
3284
|
+
* @returns Array of common subexpressions found
|
|
3285
|
+
*/
|
|
3286
|
+
declare function findCommonSubexpressions(expr: Expr, minComplexity?: number): CommonSubexpression[];
|
|
3287
|
+
/**
|
|
3288
|
+
* Find common subexpressions across multiple expressions
|
|
3289
|
+
* @param expressions Array of expressions to analyze
|
|
3290
|
+
* @param minComplexity Minimum complexity threshold
|
|
3291
|
+
* @returns Array of common subexpressions found across expressions
|
|
3292
|
+
*/
|
|
3293
|
+
declare function findCommonSubexpressionsAcrossExpressions(expressions: Array<{
|
|
3294
|
+
expr: Expr;
|
|
3295
|
+
name: string;
|
|
3296
|
+
}>, minComplexity?: number): CommonSubexpression[];
|
|
3297
|
+
/**
|
|
3298
|
+
* Find common subexpressions in a model (including its subsystems). All of
|
|
3299
|
+
* the model's expressions are analyzed in a single pass so duplicates that
|
|
3300
|
+
* span the parent and a subsystem are counted together.
|
|
3301
|
+
* @param model Model to analyze
|
|
3302
|
+
* @param minComplexity Minimum complexity threshold
|
|
3303
|
+
* @returns Array of common subexpressions found in the model
|
|
3304
|
+
*/
|
|
3305
|
+
declare function findCommonSubexpressionsInModel(model: Model, minComplexity?: number): CommonSubexpression[];
|
|
3306
|
+
/**
|
|
3307
|
+
* Find common subexpressions across an entire ESM file. All models' and
|
|
3308
|
+
* reaction systems' raw expressions are aggregated into ONE analysis pass so
|
|
3309
|
+
* occurrence counts and locations reflect actual appearances — including
|
|
3310
|
+
* duplicates local to a single model and duplicates spanning components.
|
|
3311
|
+
* @param esmFile ESM file to analyze
|
|
3312
|
+
* @param minComplexity Minimum complexity threshold
|
|
3313
|
+
* @returns Array of common subexpressions found across the file
|
|
3314
|
+
*/
|
|
3315
|
+
declare function findCommonSubexpressionsInEsmFile(esmFile: EsmFile, minComplexity?: number): CommonSubexpression[];
|
|
3316
|
+
/**
|
|
3317
|
+
* Estimate the cost savings from factoring out common subexpressions
|
|
3318
|
+
* @param commonSubexpressions Array of common subexpressions
|
|
3319
|
+
* @returns Total estimated cost savings
|
|
3320
|
+
*/
|
|
3321
|
+
declare function estimateSavings(commonSubexpressions: CommonSubexpression[]): number;
|
|
3322
|
+
/**
|
|
3323
|
+
* Generate variable names for factored subexpressions.
|
|
3324
|
+
*
|
|
3325
|
+
* Keyed by the {@link CommonSubexpression} object itself so callers can look up
|
|
3326
|
+
* a generated name directly from the array element (the previous private
|
|
3327
|
+
* string key could not be reconstructed by callers).
|
|
3328
|
+
* @param commonSubexpressions Array of common subexpressions
|
|
3329
|
+
* @param prefix Prefix for generated variable names
|
|
3330
|
+
* @returns Map from each common subexpression to its generated variable name
|
|
3331
|
+
*/
|
|
3332
|
+
declare function generateFactoredVariableNames(commonSubexpressions: CommonSubexpression[], prefix?: string): Map<CommonSubexpression, string>;
|
|
3333
|
+
/**
|
|
3334
|
+
* Group common subexpressions by their structure type
|
|
3335
|
+
* @param commonSubexpressions Array of common subexpressions
|
|
3336
|
+
* @returns Grouped subexpressions by operation type
|
|
3337
|
+
*/
|
|
3338
|
+
declare function groupSubexpressionsByType(commonSubexpressions: CommonSubexpression[]): Record<string, CommonSubexpression[]>;
|
|
3339
|
+
|
|
3340
|
+
/**
|
|
3341
|
+
* Symbolic differentiation capabilities
|
|
3342
|
+
*
|
|
3343
|
+
* This module provides functions to compute symbolic derivatives
|
|
3344
|
+
* of expressions with respect to variables, supporting the chain rule
|
|
3345
|
+
* and various mathematical functions.
|
|
3346
|
+
*/
|
|
3347
|
+
|
|
3348
|
+
/**
|
|
3349
|
+
* Thrown when {@link differentiate} encounters an operator with no
|
|
3350
|
+
* differentiation rule, or a known operator applied with an arity its rule
|
|
3351
|
+
* does not cover. Callers that need a boolean answer should use
|
|
3352
|
+
* {@link isDifferentiable}.
|
|
3353
|
+
*/
|
|
3354
|
+
declare class NonDifferentiableExpressionError extends Error {
|
|
3355
|
+
readonly op: string;
|
|
3356
|
+
readonly variable: string;
|
|
3357
|
+
constructor(op: string, variable: string);
|
|
3358
|
+
}
|
|
3359
|
+
/** Thrown by {@link higherOrderDerivative} when `order` is not positive. */
|
|
3360
|
+
declare class InvalidDerivativeOrderError extends Error {
|
|
3361
|
+
readonly order: number;
|
|
3362
|
+
constructor(order: number);
|
|
3363
|
+
}
|
|
3364
|
+
/**
|
|
3365
|
+
* Compute the symbolic derivative of an expression with respect to a variable
|
|
3366
|
+
* @param expr Expression to differentiate
|
|
3367
|
+
* @param variable Variable with respect to which to differentiate
|
|
3368
|
+
* @returns Derivative result with simplified form
|
|
3369
|
+
*/
|
|
3370
|
+
declare function differentiate(expr: Expr, variable: string): DerivativeResult;
|
|
3371
|
+
/**
|
|
3372
|
+
* Compute partial derivatives with respect to multiple variables
|
|
3373
|
+
* @param expr Expression to differentiate
|
|
3374
|
+
* @param variables Array of variables to differentiate with respect to
|
|
3375
|
+
* @returns Map of variable names to their derivative results
|
|
3376
|
+
*/
|
|
3377
|
+
declare function partialDerivatives(expr: Expr, variables: string[]): Map<string, DerivativeResult>;
|
|
3378
|
+
/**
|
|
3379
|
+
* Compute the gradient (all first partial derivatives)
|
|
3380
|
+
* @param expr Expression to differentiate
|
|
3381
|
+
* @param variables Array of variables (if not provided, will extract from expression)
|
|
3382
|
+
* @returns Gradient as array of derivatives
|
|
3383
|
+
*/
|
|
3384
|
+
declare function gradient(expr: Expr, variables?: string[]): DerivativeResult[];
|
|
3385
|
+
/**
|
|
3386
|
+
* Compute higher-order derivatives
|
|
3387
|
+
* @param expr Expression to differentiate
|
|
3388
|
+
* @param variable Variable with respect to which to differentiate
|
|
3389
|
+
* @param order Order of derivative (default: 1)
|
|
3390
|
+
* @returns Higher-order derivative result
|
|
3391
|
+
*/
|
|
3392
|
+
declare function higherOrderDerivative(expr: Expr, variable: string, order?: number): DerivativeResult;
|
|
3393
|
+
/**
|
|
3394
|
+
* Check if an expression is differentiable with respect to a variable
|
|
3395
|
+
* @param expr Expression to check
|
|
3396
|
+
* @param variable Variable to check differentiability with respect to
|
|
3397
|
+
* @returns True if differentiable, false otherwise
|
|
3398
|
+
*/
|
|
3399
|
+
declare function isDifferentiable(expr: Expr, variable: string): boolean;
|
|
3400
|
+
/**
|
|
3401
|
+
* Find critical points (where derivative equals zero)
|
|
3402
|
+
* This is a symbolic analysis - actual solving would require numerical methods
|
|
3403
|
+
* @param expr Expression to analyze
|
|
3404
|
+
* @param variable Variable to find critical points for
|
|
3405
|
+
* @returns Information about potential critical points
|
|
3406
|
+
*/
|
|
3407
|
+
declare function findCriticalPoints(expr: Expr, variable: string): {
|
|
3408
|
+
derivative: Expr;
|
|
3409
|
+
simplified?: Expr;
|
|
3410
|
+
hasConstantDerivative: boolean;
|
|
3411
|
+
isConstantZero: boolean;
|
|
3412
|
+
};
|
|
3413
|
+
|
|
3414
|
+
/**
|
|
3415
|
+
* Advanced Expression Analysis and Manipulation
|
|
3416
|
+
*
|
|
3417
|
+
* This module provides analysis and manipulation capabilities for
|
|
3418
|
+
* mathematical expressions in the ESM format:
|
|
3419
|
+
*
|
|
3420
|
+
* - Variable dependency graph construction and analysis
|
|
3421
|
+
* - Expression complexity metrics
|
|
3422
|
+
* - Common subexpression identification
|
|
3423
|
+
* - Symbolic differentiation
|
|
3424
|
+
*
|
|
3425
|
+
* It re-exports only the symbols it owns. Graph generation/export
|
|
3426
|
+
* (`expressionGraph`, `toDot`, ...), unit analysis, reaction ODE derivation,
|
|
3427
|
+
* and model-editing operations live in their own modules and are re-exported
|
|
3428
|
+
* from the package root (`../index.ts`), not duplicated here.
|
|
3429
|
+
*/
|
|
3430
|
+
|
|
3431
|
+
/** Combined results returned by {@link analyzeExpression}. */
|
|
3432
|
+
interface AnalysisResults {
|
|
3433
|
+
complexity?: ComplexityMetrics;
|
|
3434
|
+
stabilityIssues?: StabilityIssue[];
|
|
3435
|
+
commonSubexpressions?: CommonSubexpression[];
|
|
3436
|
+
dependencyGraph?: DependencyGraph;
|
|
3437
|
+
partialDerivatives?: Map<string, DerivativeResult>;
|
|
3438
|
+
gradient?: DerivativeResult[];
|
|
3439
|
+
}
|
|
3440
|
+
/** Options controlling which analyses {@link analyzeExpression} runs. */
|
|
3441
|
+
interface AnalysisOptions {
|
|
3442
|
+
/** Compute complexity metrics and stability issues (expression targets only). */
|
|
3443
|
+
includeComplexity?: boolean;
|
|
3444
|
+
/** Identify common subexpressions (expression targets only). */
|
|
3445
|
+
includeSubexpressions?: boolean;
|
|
3446
|
+
/** Build the variable dependency graph. */
|
|
3447
|
+
includeDependencies?: boolean;
|
|
3448
|
+
/** Compute partial derivatives and gradient (expression targets only). */
|
|
3449
|
+
includeDerivatives?: boolean;
|
|
3450
|
+
/** Variables to differentiate with respect to (required for derivatives). */
|
|
3451
|
+
variables?: string[];
|
|
3452
|
+
/** Minimum complexity threshold for common-subexpression detection. */
|
|
3453
|
+
minComplexityThreshold?: number;
|
|
3454
|
+
}
|
|
3455
|
+
/**
|
|
3456
|
+
* Perform comprehensive analysis of an expression or model.
|
|
3457
|
+
* @param target Expression, Model, or ESM file to analyze
|
|
3458
|
+
* @param options Analysis options
|
|
3459
|
+
* @returns Complete analysis results
|
|
3460
|
+
*/
|
|
3461
|
+
declare function analyzeExpression(target: Expr | Model | EsmFile, options?: AnalysisOptions): AnalysisResults;
|
|
3462
|
+
/**
|
|
3463
|
+
* Static namespace wrapping {@link analyzeExpression}.
|
|
3464
|
+
* @deprecated Call {@link analyzeExpression} directly.
|
|
3465
|
+
*/
|
|
3466
|
+
declare const ExpressionAnalyzer: {
|
|
3467
|
+
analyze: typeof analyzeExpression;
|
|
3468
|
+
};
|
|
3469
|
+
|
|
3470
|
+
/**
|
|
3471
|
+
* Pretty-printing formatters for ESM format expressions, equations, models, and files.
|
|
3472
|
+
*
|
|
3473
|
+
* Public output formats:
|
|
3474
|
+
* - toUnicode(): Unicode mathematical notation with chemical subscripts
|
|
3475
|
+
* - toLatex(): LaTeX mathematical notation
|
|
3476
|
+
* - toAscii(): Plain text representation
|
|
3477
|
+
* - toMathML(): MathML markup for web / academic publishing
|
|
3478
|
+
* - formatChemicalName(): Unicode chemical-subscript rendering of a bare name
|
|
3479
|
+
*
|
|
3480
|
+
* The per-format rendering of each operator lives in one place — the
|
|
3481
|
+
* {@link OP_RENDERERS} table — so adding an operator is a single entry
|
|
3482
|
+
* (op-registry.ts:10-12).
|
|
3483
|
+
*
|
|
3484
|
+
* Based on ESM Format Specification Section 6.1
|
|
3485
|
+
*/
|
|
3486
|
+
|
|
3487
|
+
/**
|
|
3488
|
+
* Format an expression as Unicode mathematical notation
|
|
3489
|
+
*/
|
|
3490
|
+
declare function toUnicode(expr: Expr | Equation | Model | ReactionSystem | Reaction | EsmFile): string;
|
|
3491
|
+
/**
|
|
3492
|
+
* Format an expression as LaTeX mathematical notation
|
|
3493
|
+
*/
|
|
3494
|
+
declare function toLatex(expr: Expr | Equation | Model | ReactionSystem | Reaction | EsmFile): string;
|
|
3495
|
+
/**
|
|
3496
|
+
* Format an expression as plain ASCII text
|
|
3497
|
+
*/
|
|
3498
|
+
declare function toAscii(expr: Expr | Equation | Model | ReactionSystem | Reaction | EsmFile): string;
|
|
3499
|
+
/**
|
|
3500
|
+
* Apply element-aware chemical subscript formatting to a bare variable /
|
|
3501
|
+
* species name using Unicode subscript digits (e.g. "H2SO4" → "H₂SO₄").
|
|
3502
|
+
* Exported for graph rendering (toDot / toMermaid labels).
|
|
3503
|
+
*/
|
|
3504
|
+
declare function formatChemicalName(name: string): string;
|
|
3505
|
+
/**
|
|
3506
|
+
* Format an expression as MathML markup for web/academic publishing
|
|
3507
|
+
*/
|
|
3508
|
+
declare function toMathML(expr: Expr | Equation | Model | ReactionSystem | Reaction | EsmFile): string;
|
|
3509
|
+
|
|
3510
|
+
/**
|
|
3511
|
+
* parse-expression — the INVERSE of `toAscii` (pretty-print.ts) for authoring
|
|
3512
|
+
* EarthSciAST expressions (esm-spec §4.2) as text.
|
|
3513
|
+
*
|
|
3514
|
+
* The concrete syntax IS what `toAscii` emits, so the pair round-trips:
|
|
3515
|
+
* `toAscii(parseExpression(s)) === s`. Precedence is sourced from
|
|
3516
|
+
* {@link opPrecedence} (op-registry.ts) so the parser can never drift from the
|
|
3517
|
+
* printer. This parser RECONSTRUCTS existing AST node shapes; it never invents
|
|
3518
|
+
* new ones, and it requires no change to `toAscii`.
|
|
3519
|
+
*
|
|
3520
|
+
* Coverage:
|
|
3521
|
+
* - scalar tier: arithmetic, powers, comparisons, boolean logic, elementary
|
|
3522
|
+
* functions, derivatives (`D(x)/Dt` and `D(x, t)`), open/user function calls;
|
|
3523
|
+
* - array & call-shaped tier: array literals `[…]` (`const`), indexing
|
|
3524
|
+
* `a[i, j]` (`index`), dotted closed-function calls `datetime.year(t)` (`fn`),
|
|
3525
|
+
* the `true` literal, and `integral` / `reshape` / `transpose` / `concat`;
|
|
3526
|
+
* - reduction & array-query tier: `aggregate` reductions
|
|
3527
|
+
* `sum[i] (expr) where {i in set, j in lo:hi} join(a=b) if pred distinct
|
|
3528
|
+
* key=k [semiring=…]` (all clause shapes), the `argmin`/`argmax` arg-witnesses
|
|
3529
|
+
* `argmin[g] (expr) where {…}`, template application
|
|
3530
|
+
* `name<binding = value, …>` (`apply_expression_template`),
|
|
3531
|
+
* `polygon_intersection_area(a, b, manifold=…)`, and the piecewise-region
|
|
3532
|
+
* array `makearray([lo:hi, …] = value, …)`.
|
|
3533
|
+
*
|
|
3534
|
+
* Aggregate `args` is a derived operand cache the printer doesn't emit; it's
|
|
3535
|
+
* reconstructed best-effort (see {@link deriveAggregateArgs}) and is
|
|
3536
|
+
* reprint-neutral. `sum` with neither an explicit `[semiring=…]` nor a `join`
|
|
3537
|
+
* reconstructs as a plain `+` reduction — the join-less `sum_product` annotation
|
|
3538
|
+
* (semantically identical there) is not recovered; both reprint identically.
|
|
3539
|
+
*
|
|
3540
|
+
* Still deferred (need dedicated surface syntax — a later pass): `table_lookup`,
|
|
3541
|
+
* `broadcast`, `enum`, and `intersect_polygon` (its `id` field is not printed, so
|
|
3542
|
+
* it can't round-trip). Those are refused with an {@link ExpressionParseError}.
|
|
3543
|
+
*
|
|
3544
|
+
* Design rules: multiplication is ALWAYS explicit (`k * A`) — no implicit
|
|
3545
|
+
* juxtaposition, because identifiers are multi-letter (`NO2`, `O3`, `k_photo`).
|
|
3546
|
+
* Two known non-exactnesses trace to `toAscii`, not the parser: float
|
|
3547
|
+
* serialization (`formatNumber` routes through a JS double), and unary-minus
|
|
3548
|
+
* operands being under-parenthesized (`-(a+b)` and `(-a)+b` both print
|
|
3549
|
+
* `-a + b`) — the parser matches the printer's loose convention. Because the
|
|
3550
|
+
* printer is not injective, `parseExpression(toAscii(ast))` is a faithful
|
|
3551
|
+
* SEMANTIC round-trip but may normalize structure (flat vs. nested `+`; a scalar
|
|
3552
|
+
* `const`/`fn` with a non-dotted name reprints identically to a plain
|
|
3553
|
+
* number/op). Editors should treat text as a derived view and re-parse only
|
|
3554
|
+
* dirtied expressions.
|
|
3555
|
+
*/
|
|
3556
|
+
|
|
3557
|
+
/** Thrown when an expression string cannot be parsed. */
|
|
3558
|
+
declare class ExpressionParseError extends Error {
|
|
3559
|
+
/** 0-based character offset into the source where parsing failed. */
|
|
3560
|
+
pos: number;
|
|
3561
|
+
constructor(message: string,
|
|
3562
|
+
/** 0-based character offset into the source where parsing failed. */
|
|
3563
|
+
pos: number);
|
|
3564
|
+
}
|
|
3565
|
+
/**
|
|
3566
|
+
* Parse a single expression string into an AST expression — the inverse of
|
|
3567
|
+
* {@link toAscii}. Throws {@link ExpressionParseError} on malformed input or an
|
|
3568
|
+
* operator with no text surface yet.
|
|
3569
|
+
*/
|
|
3570
|
+
declare function parseExpression(src: string): Expr;
|
|
3571
|
+
/**
|
|
3572
|
+
* Parse `lhs = rhs` into an {@link Equation}. The top-level separator is a LONE
|
|
3573
|
+
* `=`; `==` (and `>=`/`<=`/`!=`) remain comparison operators within either side.
|
|
3574
|
+
*/
|
|
3575
|
+
declare function parseEquation(src: string): Equation;
|
|
3576
|
+
|
|
3577
|
+
/**
|
|
3578
|
+
* parse-reaction.ts — the inverse of the reaction printer (`toAscii(reaction)`).
|
|
3579
|
+
*
|
|
3580
|
+
* Parses a single chemical reaction written in the text DSL, e.g.
|
|
3581
|
+
*
|
|
3582
|
+
* 2 NO + O3 -> [k1] NO2 + O2
|
|
3583
|
+
* CH4 + OH -> [arr(2.45e-12, 1775)] CH3O2 + H2O
|
|
3584
|
+
* -> [k_emit] O3 (source: ∅ → X, empty reactant side)
|
|
3585
|
+
* O3 -> [k_dep] (sink: X → ∅, empty product side)
|
|
3586
|
+
*
|
|
3587
|
+
* Grammar:
|
|
3588
|
+
* reaction := side? arrow rate? side?
|
|
3589
|
+
* arrow := '->' | '→' | '⟶'
|
|
3590
|
+
* rate := '[' expression ']' (required — a reaction must have a rate)
|
|
3591
|
+
* side := term ('+' term)* (empty / '∅' ⇒ null: a source or sink)
|
|
3592
|
+
* term := coefficient? species
|
|
3593
|
+
* coefficient := positive finite number (default 1; fractional yields allowed)
|
|
3594
|
+
* species := any run of non-whitespace characters (a chemical formula token)
|
|
3595
|
+
*
|
|
3596
|
+
* The rate is parsed with the shared {@link parseExpression}, so a rate is any
|
|
3597
|
+
* expression the DSL accepts (a parameter name, a number, an operator tree, a
|
|
3598
|
+
* template application, …). The returned reaction carries an empty `id` — the
|
|
3599
|
+
* caller (e.g. the editor merging into an existing reaction) supplies id/name.
|
|
3600
|
+
*/
|
|
3601
|
+
|
|
3602
|
+
/**
|
|
3603
|
+
* Parse a single reaction from its text-DSL form. Throws
|
|
3604
|
+
* {@link ExpressionParseError} on any malformed input (the editor surfaces the
|
|
3605
|
+
* message and blocks the edit). The returned reaction's `id` is empty — the
|
|
3606
|
+
* caller assigns identity when merging into an existing reaction.
|
|
3607
|
+
*/
|
|
3608
|
+
declare function parseReaction(src: string): Reaction;
|
|
3609
|
+
|
|
3610
|
+
/**
|
|
3611
|
+
* Expression substitution functionality for the ESM format
|
|
3612
|
+
*
|
|
3613
|
+
* Provides immutable substitution operations that replace variable references
|
|
3614
|
+
* with bound expressions throughout ESM structures.
|
|
3615
|
+
*/
|
|
3616
|
+
|
|
3617
|
+
/**
|
|
3618
|
+
* Context for resolving scoped references during substitution
|
|
3619
|
+
*/
|
|
3620
|
+
interface SubstitutionContext {
|
|
3621
|
+
esmFile: EsmFile;
|
|
3622
|
+
}
|
|
3623
|
+
/**
|
|
3624
|
+
* Recursively substitute variable references in an expression with bound expressions.
|
|
3625
|
+
* Handles scoped references (Model.Subsystem.var) by splitting on '.' and matching
|
|
3626
|
+
* path through system hierarchy per format spec Section 4.3.
|
|
3627
|
+
*
|
|
3628
|
+
* NOTE: when a `context` is supplied, any dotted reference NOT covered by
|
|
3629
|
+
* `bindings` is resolved through the file hierarchy and replaced with the
|
|
3630
|
+
* referenced variable's DECLARED DEFAULT VALUE. Callers that only want to
|
|
3631
|
+
* rename/replace bound names must omit `context`.
|
|
3632
|
+
*
|
|
3633
|
+
* @param expr - Expression to substitute into
|
|
3634
|
+
* @param bindings - Variable name to expression mappings
|
|
3635
|
+
* @param context - Optional context; enables default-value inlining for
|
|
3636
|
+
* scoped references (see note above)
|
|
3637
|
+
* @returns New expression with substitutions applied (immutable)
|
|
3638
|
+
*/
|
|
3639
|
+
declare function substitute(expr: Expr, bindings: Record<string, Expr>, context?: SubstitutionContext): Expr;
|
|
3640
|
+
/**
|
|
3641
|
+
* Apply substitution across an ENTIRE model, not just its equations.
|
|
3642
|
+
*
|
|
3643
|
+
* The rewritten expression sites are, exhaustively (this is the single write
|
|
3644
|
+
* definition of "a model's expression sites"; `edit.ts`'s read-side
|
|
3645
|
+
* `forEachModelExpressionSite` MUST cover the same set):
|
|
3646
|
+
* - every equation `lhs` / `rhs`;
|
|
3647
|
+
* - every observed variable's `expression`;
|
|
3648
|
+
* - every continuous event's `conditions[]`, `affects[].rhs`, and
|
|
3649
|
+
* `affect_neg[].rhs`;
|
|
3650
|
+
* - every discrete event's condition-`trigger.expression` and `affects[].rhs`;
|
|
3651
|
+
* - recursively, every inline-model subsystem (data loaders and unresolved
|
|
3652
|
+
* `{ref}` subsystems pass through unchanged).
|
|
3653
|
+
*
|
|
3654
|
+
* Event affect `lhs` values are write-TARGET names (`string`), not expression
|
|
3655
|
+
* read-sites, and are intentionally left untouched — substitution replaces
|
|
3656
|
+
* references, not assignment targets.
|
|
3657
|
+
*
|
|
3658
|
+
* Returns a new model with substitutions applied (immutable).
|
|
3659
|
+
*
|
|
3660
|
+
* @param model - Model to substitute into
|
|
3661
|
+
* @param bindings - Variable name to expression mappings
|
|
3662
|
+
* @param context - Optional context for resolving scoped references
|
|
3663
|
+
* @returns New model with substitutions applied
|
|
3664
|
+
*/
|
|
3665
|
+
declare function substituteInModel(model: Model, bindings: Record<string, Expr>, context?: SubstitutionContext): Model;
|
|
3666
|
+
/**
|
|
3667
|
+
* Apply substitution across all rate expressions in a reaction system.
|
|
3668
|
+
* Returns a new reaction system with substitutions applied (immutable).
|
|
3669
|
+
*
|
|
3670
|
+
* @param system - ReactionSystem to substitute into
|
|
3671
|
+
* @param bindings - Variable name to expression mappings
|
|
3672
|
+
* @param context - Optional context for resolving scoped references
|
|
3673
|
+
* @returns New reaction system with substitutions applied
|
|
3674
|
+
*/
|
|
3675
|
+
declare function substituteInReactionSystem(system: ReactionSystem, bindings: Record<string, Expr>, context?: SubstitutionContext): ReactionSystem;
|
|
3676
|
+
|
|
3677
|
+
/**
|
|
3678
|
+
* Reaction system ODE derivation for the ESM format
|
|
3679
|
+
*
|
|
3680
|
+
* This module provides utilities for deriving ordinary differential equations (ODEs)
|
|
3681
|
+
* from reaction systems using standard mass action kinetics.
|
|
3682
|
+
*/
|
|
3683
|
+
|
|
3684
|
+
/**
|
|
3685
|
+
* Derive ODEs from a reaction system using mass action kinetics
|
|
3686
|
+
*
|
|
3687
|
+
* Generates an ODE model from reaction stoichiometry and rate laws. For each reaction
|
|
3688
|
+
* with rate k, substrates {Si} with stoichiometries {ni}, products {Pj} with
|
|
3689
|
+
* stoichiometries {mj}:
|
|
3690
|
+
* - rate law: v = k * prod(Si^ni)
|
|
3691
|
+
* - ODE contribution: dX/dt += net_stoich_X * v
|
|
3692
|
+
*
|
|
3693
|
+
* Handles:
|
|
3694
|
+
* - Source reactions (null substrates): rate is the direct production term
|
|
3695
|
+
* - Sink reactions (null products): rate is the direct loss term
|
|
3696
|
+
* - Constraint equations are appended as additional equations
|
|
3697
|
+
*
|
|
3698
|
+
* @param system ReactionSystem to derive ODEs from
|
|
3699
|
+
* @returns Model with species as state variables, derived ODEs plus constraints
|
|
3700
|
+
*/
|
|
3701
|
+
declare function deriveODEs(system: ReactionSystem): Model;
|
|
3702
|
+
/**
|
|
3703
|
+
* Compute stoichiometric matrix from a reaction system
|
|
3704
|
+
*
|
|
3705
|
+
* Returns the net stoichiometric matrix (species × reactions) where:
|
|
3706
|
+
* - Rows are species (in declaration order)
|
|
3707
|
+
* - Columns are reactions (in array order)
|
|
3708
|
+
* - Entry [i][j] = (stoichiometry as product) - (stoichiometry as substrate) for species i in reaction j
|
|
3709
|
+
* - Null substrates contribute 0 to substrate stoichiometry
|
|
3710
|
+
* - Null products contribute 0 to product stoichiometry
|
|
3711
|
+
*
|
|
3712
|
+
* @param system ReactionSystem to compute matrix from
|
|
3713
|
+
* @returns Object containing matrix, species list, and reactions list
|
|
3714
|
+
*/
|
|
3715
|
+
declare function stoichiometricMatrix(system: ReactionSystem): {
|
|
3716
|
+
matrix: number[][];
|
|
3717
|
+
species: string[];
|
|
3718
|
+
reactions: string[];
|
|
3719
|
+
};
|
|
3720
|
+
/**
|
|
3721
|
+
* Compute substrate stoichiometric matrix from a reaction system
|
|
3722
|
+
*
|
|
3723
|
+
* Returns the substrate stoichiometric matrix (species × reactions) where:
|
|
3724
|
+
* - Rows are species (in declaration order)
|
|
3725
|
+
* - Columns are reactions (in array order)
|
|
3726
|
+
* - Entry [i][j] = substrate stoichiometry for species i in reaction j
|
|
3727
|
+
* - Null substrates contribute 0
|
|
3728
|
+
*
|
|
3729
|
+
* @param system ReactionSystem to compute matrix from
|
|
3730
|
+
* @returns Substrate stoichiometric matrix
|
|
3731
|
+
*/
|
|
3732
|
+
declare function substrateMatrix(system: ReactionSystem): number[][];
|
|
3733
|
+
/**
|
|
3734
|
+
* Compute product stoichiometric matrix from a reaction system
|
|
3735
|
+
*
|
|
3736
|
+
* Returns the product stoichiometric matrix (species × reactions) where:
|
|
3737
|
+
* - Rows are species (in declaration order)
|
|
3738
|
+
* - Columns are reactions (in array order)
|
|
3739
|
+
* - Entry [i][j] = product stoichiometry for species i in reaction j
|
|
3740
|
+
* - Null products contribute 0
|
|
3741
|
+
*
|
|
3742
|
+
* @param system ReactionSystem to compute matrix from
|
|
3743
|
+
* @returns Product stoichiometric matrix
|
|
3744
|
+
*/
|
|
3745
|
+
declare function productMatrix(system: ReactionSystem): number[][];
|
|
3746
|
+
|
|
3747
|
+
/**
|
|
3748
|
+
* Immutable editing operations for the ESM format
|
|
3749
|
+
*
|
|
3750
|
+
* This module provides comprehensive editing operations for ESM files, models,
|
|
3751
|
+
* and reaction systems. All operations are immutable and return new objects.
|
|
3752
|
+
*/
|
|
3753
|
+
|
|
3754
|
+
/**
|
|
3755
|
+
* Error thrown when attempting to remove a variable that is still referenced
|
|
3756
|
+
*/
|
|
3757
|
+
declare class VariableInUseError extends Error {
|
|
3758
|
+
variableName: string;
|
|
3759
|
+
references: string[];
|
|
3760
|
+
constructor(variableName: string, references: string[]);
|
|
3761
|
+
}
|
|
3762
|
+
/**
|
|
3763
|
+
* Error thrown when attempting an operation on a non-existent entity
|
|
3764
|
+
*/
|
|
3765
|
+
declare class EntityNotFoundError extends Error {
|
|
3766
|
+
entityType: string;
|
|
3767
|
+
entityName: string;
|
|
3768
|
+
constructor(entityType: string, entityName: string);
|
|
3769
|
+
}
|
|
3770
|
+
/**
|
|
3771
|
+
* Add a new variable to a model
|
|
3772
|
+
* @param model Model to add variable to
|
|
3773
|
+
* @param name Variable name
|
|
3774
|
+
* @param variable Variable definition
|
|
3775
|
+
* @returns New model with variable added
|
|
3776
|
+
*/
|
|
3777
|
+
declare function addVariable(model: Model, name: string, variable: ModelVariable): Model;
|
|
3778
|
+
/**
|
|
3779
|
+
* Remove a variable from a model, with reference checking
|
|
3780
|
+
* @param model Model to remove variable from
|
|
3781
|
+
* @param name Variable name to remove
|
|
3782
|
+
* @returns New model with variable removed
|
|
3783
|
+
* @throws VariableInUseError if variable is still referenced
|
|
3784
|
+
* @throws EntityNotFoundError if variable doesn't exist
|
|
3785
|
+
*/
|
|
3786
|
+
declare function removeVariable(model: Model, name: string): Model;
|
|
3787
|
+
/**
|
|
3788
|
+
* Rename a variable throughout a model.
|
|
3789
|
+
*
|
|
3790
|
+
* The rewrite covers exactly the expression sites `removeVariable` scans (via
|
|
3791
|
+
* `substituteInModel` — equations, observed-variable expressions, event
|
|
3792
|
+
* conditions/triggers/affect RHSs, and inline subsystems), so a rename never
|
|
3793
|
+
* leaves a dangling reference in a site the removal guard would have flagged.
|
|
3794
|
+
*
|
|
3795
|
+
* @param model Model to rename variable in
|
|
3796
|
+
* @param oldName Current variable name
|
|
3797
|
+
* @param newName New variable name
|
|
3798
|
+
* @returns New model with variable renamed
|
|
3799
|
+
* @throws EntityNotFoundError if variable doesn't exist
|
|
3800
|
+
*/
|
|
3801
|
+
declare function renameVariable(model: Model, oldName: string, newName: string): Model;
|
|
3802
|
+
/**
|
|
3803
|
+
* Add a new equation to a model
|
|
3804
|
+
* @param model Model to add equation to
|
|
3805
|
+
* @param equation Equation to add
|
|
3806
|
+
* @returns New model with equation added
|
|
3807
|
+
*/
|
|
3808
|
+
declare function addEquation(model: Model, equation: Equation): Model;
|
|
3809
|
+
/**
|
|
3810
|
+
* Remove an equation from a model
|
|
3811
|
+
* @param model Model to remove equation from
|
|
3812
|
+
* @param indexOrLhs Either the numeric index or the LHS expression of the equation
|
|
3813
|
+
* @returns New model with equation removed
|
|
3814
|
+
* @throws EntityNotFoundError if equation not found
|
|
3815
|
+
*/
|
|
3816
|
+
declare function removeEquation(model: Model, indexOrLhs: number | Expr): Model;
|
|
3817
|
+
/**
|
|
3818
|
+
* Apply substitutions across a model.
|
|
3819
|
+
*
|
|
3820
|
+
* NOTE: despite the historical name, this does NOT touch only equations — it is
|
|
3821
|
+
* a thin alias for {@link substituteInModel} and therefore also rewrites
|
|
3822
|
+
* observed-variable expressions, event expression positions, and inline
|
|
3823
|
+
* subsystems. See `substituteInModel` for the full list of rewritten sites.
|
|
3824
|
+
*
|
|
3825
|
+
* @deprecated The name understates its blast radius; call `substituteInModel`
|
|
3826
|
+
* (exported from `substitute.js`) directly. Retained as a public back-compat
|
|
3827
|
+
* export (re-exported via `index.ts` and `analysis/index.ts`).
|
|
3828
|
+
* @param model Model to apply substitutions to
|
|
3829
|
+
* @param bindings Variable name to expression mappings
|
|
3830
|
+
* @returns New model with substitutions applied
|
|
3831
|
+
*/
|
|
3832
|
+
declare function substituteInEquations(model: Model, bindings: Record<string, Expr>): Model;
|
|
3833
|
+
/**
|
|
3834
|
+
* Add a new reaction to a reaction system
|
|
3835
|
+
* @param system ReactionSystem to add reaction to
|
|
3836
|
+
* @param reaction Reaction to add
|
|
3837
|
+
* @returns New reaction system with reaction added
|
|
3838
|
+
*/
|
|
3839
|
+
declare function addReaction(system: ReactionSystem, reaction: Reaction): ReactionSystem;
|
|
3840
|
+
/**
|
|
3841
|
+
* Remove a reaction from a reaction system
|
|
3842
|
+
* @param system ReactionSystem to remove reaction from
|
|
3843
|
+
* @param id Reaction ID to remove
|
|
3844
|
+
* @returns New reaction system with reaction removed
|
|
3845
|
+
* @throws EntityNotFoundError if reaction not found
|
|
3846
|
+
*/
|
|
3847
|
+
declare function removeReaction(system: ReactionSystem, id: string): ReactionSystem;
|
|
3848
|
+
/**
|
|
3849
|
+
* Add a new species to a reaction system
|
|
3850
|
+
* @param system ReactionSystem to add species to
|
|
3851
|
+
* @param name Species name
|
|
3852
|
+
* @param species Species definition
|
|
3853
|
+
* @returns New reaction system with species added
|
|
3854
|
+
*/
|
|
3855
|
+
declare function addSpecies(system: ReactionSystem, name: string, species: Species): ReactionSystem;
|
|
3856
|
+
/**
|
|
3857
|
+
* Remove a species from a reaction system, with reference checking
|
|
3858
|
+
* @param system ReactionSystem to remove species from
|
|
3859
|
+
* @param name Species name to remove
|
|
3860
|
+
* @returns New reaction system with species removed
|
|
3861
|
+
* @throws VariableInUseError if species is still referenced in reactions
|
|
3862
|
+
* @throws EntityNotFoundError if species doesn't exist
|
|
3863
|
+
*/
|
|
3864
|
+
declare function removeSpecies(system: ReactionSystem, name: string): ReactionSystem;
|
|
3865
|
+
/**
|
|
3866
|
+
* Add a continuous event to a model
|
|
3867
|
+
* @param model Model to add event to
|
|
3868
|
+
* @param event Continuous event to add
|
|
3869
|
+
* @returns New model with event added
|
|
3870
|
+
*/
|
|
3871
|
+
declare function addContinuousEvent(model: Model, event: ContinuousEvent): Model;
|
|
3872
|
+
/**
|
|
3873
|
+
* Add a discrete event to a model
|
|
3874
|
+
* @param model Model to add event to
|
|
3875
|
+
* @param event Discrete event to add
|
|
3876
|
+
* @returns New model with event added
|
|
3877
|
+
*/
|
|
3878
|
+
declare function addDiscreteEvent(model: Model, event: DiscreteEvent): Model;
|
|
3879
|
+
/**
|
|
3880
|
+
* Remove events from a model by name.
|
|
3881
|
+
*
|
|
3882
|
+
* Remove-ALL semantics: EVERY event whose `name` matches is removed, not just
|
|
3883
|
+
* the first. Containers are tried in order — if any continuous event matches,
|
|
3884
|
+
* only continuous events are filtered; otherwise discrete events are filtered
|
|
3885
|
+
* (a name present in both containers is removed only from `continuous_events`).
|
|
3886
|
+
* If the filtered container ends up empty, its key is dropped per the
|
|
3887
|
+
* module-wide drop-when-empty convention (see `withCollection`).
|
|
3888
|
+
*
|
|
3889
|
+
* @param model Model to remove event(s) from
|
|
3890
|
+
* @param name Event name to remove
|
|
3891
|
+
* @returns New model with matching event(s) removed
|
|
3892
|
+
* @throws EntityNotFoundError if no event with that name exists
|
|
3893
|
+
*/
|
|
3894
|
+
declare function removeEvent(model: Model, name: string): Model;
|
|
3895
|
+
/**
|
|
3896
|
+
* Add a coupling entry to an ESM file
|
|
3897
|
+
* @param file ESM file to add coupling to
|
|
3898
|
+
* @param entry Coupling entry to add
|
|
3899
|
+
* @returns New ESM file with coupling added
|
|
3900
|
+
*/
|
|
3901
|
+
declare function addCoupling(file: EsmFile, entry: CouplingEntry): EsmFile;
|
|
3902
|
+
/**
|
|
3903
|
+
* Remove a coupling entry from an ESM file by index
|
|
3904
|
+
* @param file ESM file to remove coupling from
|
|
3905
|
+
* @param index Index of coupling entry to remove
|
|
3906
|
+
* @returns New ESM file with coupling removed
|
|
3907
|
+
* @throws EntityNotFoundError if index is out of bounds
|
|
3908
|
+
*/
|
|
3909
|
+
declare function removeCoupling(file: EsmFile, index: number): EsmFile;
|
|
3910
|
+
/**
|
|
3911
|
+
* Compose two systems using a coupling entry
|
|
3912
|
+
* @param file ESM file
|
|
3913
|
+
* @param a First system name
|
|
3914
|
+
* @param b Second system name
|
|
3915
|
+
* @returns New ESM file with composition coupling added
|
|
3916
|
+
*/
|
|
3917
|
+
declare function compose(file: EsmFile, a: string, b: string): EsmFile;
|
|
3918
|
+
/**
|
|
3919
|
+
* Map a variable from one system to another with optional transformation
|
|
3920
|
+
* @param file ESM file
|
|
3921
|
+
* @param from Source variable reference
|
|
3922
|
+
* @param to Target variable reference
|
|
3923
|
+
* @param transform Optional transformation: one of the named transform strings,
|
|
3924
|
+
* or an Expression operator node evaluated in the flattened coupled system's
|
|
3925
|
+
* scope (esm-spec §8.6 — the regridding form)
|
|
3926
|
+
* @returns New ESM file with variable mapping coupling added
|
|
3927
|
+
*/
|
|
3928
|
+
declare function mapVariable(file: EsmFile, from: string, to: string, transform?: CouplingVariableMap['transform']): EsmFile;
|
|
3929
|
+
/**
|
|
3930
|
+
* Merge two ESM files
|
|
3931
|
+
* @param fileA First ESM file
|
|
3932
|
+
* @param fileB Second ESM file
|
|
3933
|
+
* @returns New ESM file with merged content
|
|
3934
|
+
*/
|
|
3935
|
+
declare function merge(fileA: EsmFile, fileB: EsmFile): EsmFile;
|
|
3936
|
+
/**
|
|
3937
|
+
* Extract a specific component from an ESM file into a new file
|
|
3938
|
+
* @param file ESM file to extract from
|
|
3939
|
+
* @param componentName Name of the component to extract
|
|
3940
|
+
* @returns New ESM file containing only the specified component
|
|
3941
|
+
* @throws EntityNotFoundError if component not found
|
|
3942
|
+
*/
|
|
3943
|
+
declare function extract(file: EsmFile, componentName: string): EsmFile;
|
|
3944
|
+
|
|
3945
|
+
/**
|
|
3946
|
+
* Expression structural operations for the ESM format
|
|
3947
|
+
*
|
|
3948
|
+
* This module provides utilities for analyzing and manipulating mathematical
|
|
3949
|
+
* expressions in the ESM format AST.
|
|
3950
|
+
*/
|
|
3951
|
+
|
|
3952
|
+
/**
|
|
3953
|
+
* Extract all variable references from an expression.
|
|
3954
|
+
*
|
|
3955
|
+
* Routes through {@link forEachChild} — the ONE walker — so every
|
|
3956
|
+
* expression-bearing field is seen, not just `args`. Walking `args` alone made
|
|
3957
|
+
* whole sidecar subtrees invisible:
|
|
3958
|
+
*
|
|
3959
|
+
* - `table_lookup{axes:{temp:'T_air'}}` → `[]` (missed `T_air`)
|
|
3960
|
+
* - `aggregate{args:['A'], expr:{*:['A','w']}}` → `['A']` (missed `w`)
|
|
3961
|
+
* - `integral{lower:'a', upper:{+:['b',1]}}` → missed `a`, `b`
|
|
3962
|
+
*
|
|
3963
|
+
* `graph.ts` builds the dependency DAG from this, so every one of those misses
|
|
3964
|
+
* was a silently-absent edge.
|
|
3965
|
+
*/
|
|
3966
|
+
declare function freeVariables(expr: Expr): Set<string>;
|
|
3967
|
+
/**
|
|
3968
|
+
* Extract free parameters from an expression within a model context
|
|
3969
|
+
* @param expr Expression to analyze
|
|
3970
|
+
* @param model Model context to determine parameter vs state variables
|
|
3971
|
+
* @returns Set of parameter names referenced in the expression
|
|
3972
|
+
*/
|
|
3973
|
+
declare function freeParameters(expr: Expr, model: Model): Set<string>;
|
|
3974
|
+
/**
|
|
3975
|
+
* Check if an expression contains a specific variable
|
|
3976
|
+
* @param expr Expression to search
|
|
3977
|
+
* @param varName Variable name to look for
|
|
3978
|
+
* @returns True if the variable appears in the expression
|
|
3979
|
+
*/
|
|
3980
|
+
declare function contains(expr: Expr, varName: string): boolean;
|
|
3981
|
+
/**
|
|
3982
|
+
* Simplify an expression using basic algebraic rules
|
|
3983
|
+
* @param expr Expression to simplify
|
|
3984
|
+
* @returns Simplified expression
|
|
3985
|
+
*/
|
|
3986
|
+
declare function simplify(expr: Expr): Expr;
|
|
3987
|
+
|
|
3988
|
+
/**
|
|
3989
|
+
* Tree-walking scalar evaluator (`compileExpression` / `evaluateExpression`)
|
|
3990
|
+
* — the EarthSciAST TypeScript in-process runner. Despite the historical
|
|
3991
|
+
* "codegen" filename this performs NO code generation or lowering: a
|
|
3992
|
+
* canonical-form `Expr` is walked directly. `compileExpression` returns a
|
|
3993
|
+
* closure over a free-variable bindings map that returns the scalar numeric
|
|
3994
|
+
* result; `evaluateExpression` walks and applies in one step.
|
|
3995
|
+
*
|
|
3996
|
+
* Structural / array ops and the closed-function registry are dispatched to
|
|
3997
|
+
* their consumers; ANY op the evaluable-core op-registry does not know — the
|
|
3998
|
+
* open-tier rewrite-target sugar `grad`/`div`/`laplacian`/`integral`, a user op,
|
|
3999
|
+
* or a spatial / right-hand-side `D` — is rejected here as an unlowered
|
|
4000
|
+
* rewrite-target: it must be lowered to a stencil by a rewrite rule before
|
|
4001
|
+
* evaluation.
|
|
4002
|
+
*/
|
|
4003
|
+
|
|
4004
|
+
/**
|
|
4005
|
+
* Compiled expression closure produced by {@link compileExpression}.
|
|
4006
|
+
* Accepts a `bindings` map of free-variable name → numeric value and
|
|
4007
|
+
* returns the scalar result.
|
|
4008
|
+
*/
|
|
4009
|
+
type CompiledExpression = (bindings: Map<string, number>) => number;
|
|
4010
|
+
/**
|
|
4011
|
+
* Error carrying the stable, cross-binding `unlowered_operator` diagnostic
|
|
4012
|
+
* (esm-spec §4.2 / §9.6.3 constraint 6 / §9.6.8). Raised when a rewrite-target
|
|
4013
|
+
* op reaches evaluation/compilation without having been lowered — the uniform
|
|
4014
|
+
* gate that supersedes the old per-binding UnreachableSpatialOperator /
|
|
4015
|
+
* UnsupportedDimensionality codes. Loading stays permissive (the op namespace
|
|
4016
|
+
* is open); the gate fires only at evaluation, mirroring the Julia `_compile`
|
|
4017
|
+
* gate in tree_walk.jl.
|
|
4018
|
+
*/
|
|
4019
|
+
declare class UnloweredOperatorError extends Error {
|
|
4020
|
+
readonly code = "unlowered_operator";
|
|
4021
|
+
constructor(message: string);
|
|
4022
|
+
}
|
|
4023
|
+
/**
|
|
4024
|
+
* Error raised by the tree-walking evaluator for a node it cannot reduce to a
|
|
4025
|
+
* scalar: an unbound variable, an unsupported operator, an unlowered `enum`, a
|
|
4026
|
+
* non-scalar `const`, a malformed `fn`, or a non-expression value. Carries a
|
|
4027
|
+
* stable `code` field so callers can branch programmatically instead of
|
|
4028
|
+
* regex-matching prose.
|
|
4029
|
+
*
|
|
4030
|
+
* Unlike {@link UnloweredOperatorError}, the `message` is passed through
|
|
4031
|
+
* VERBATIM (not `[code]`-prefixed): several of these strings are matched
|
|
4032
|
+
* byte-for-byte by the cross-binding runner tests, so the wording is pinned.
|
|
4033
|
+
* These `code` values are binding-local diagnostics for the in-process runner,
|
|
4034
|
+
* distinct from the cross-language conformance codes in `errors.ts`.
|
|
4035
|
+
*/
|
|
4036
|
+
declare class EvaluatorError extends Error {
|
|
4037
|
+
readonly code: string;
|
|
4038
|
+
constructor(code: string, message: string);
|
|
4039
|
+
}
|
|
4040
|
+
/**
|
|
4041
|
+
* Build a reusable closure that walks the canonical-AST {@link Expr} and
|
|
4042
|
+
* evaluates it against a bindings map. This is the EarthSciAST TypeScript
|
|
4043
|
+
* runner's entry point for scalar evaluation.
|
|
4044
|
+
*
|
|
4045
|
+
* The walker rejects unlowered `enum` ops (lower via `lowerEnums()` at
|
|
4046
|
+
* load time) and array-valued `const` nodes (those are consumed by
|
|
4047
|
+
* container ops such as `interp.searchsorted` and `index`, not by
|
|
4048
|
+
* scalar evaluation).
|
|
4049
|
+
*/
|
|
4050
|
+
declare function compileExpression(expr: Expr): CompiledExpression;
|
|
4051
|
+
/**
|
|
4052
|
+
* Compile and apply in one step. Equivalent to
|
|
4053
|
+
* `compileExpression(expr)(bindings)` but avoids allocating a closure
|
|
4054
|
+
* for one-shot callers (`simplify`'s constant-folding path,
|
|
4055
|
+
* fixed-point observed-variable resolution, unit-conversion
|
|
4056
|
+
* folding).
|
|
4057
|
+
*/
|
|
4058
|
+
declare function evaluateExpression(expr: Expr, bindings: Map<string, number>): number;
|
|
4059
|
+
|
|
4060
|
+
/**
|
|
4061
|
+
* Migration utilities for ESM format version upgrades.
|
|
4062
|
+
*
|
|
4063
|
+
* A migration here is a pure version-MARKER bump: it changes the `esm` field
|
|
4064
|
+
* and touches nothing else. That is only ever sound along an ADDITIVE line —
|
|
4065
|
+
* a run of schema releases each of which introduced its changes as additive,
|
|
4066
|
+
* backward-compatible fields, so an older file already loads under the newer
|
|
4067
|
+
* schema without any mechanical transform.
|
|
4068
|
+
*
|
|
4069
|
+
* The current additive line is `1.0.0 … <current schema version>`.
|
|
4070
|
+
*
|
|
4071
|
+
* **There is no migration across the 1.0.0 boundary.** esm 1.0.0 is a clean
|
|
4072
|
+
* break with no deprecation path: the five declared variable types collapse to
|
|
4073
|
+
* two, an observed variable's `expression` becomes an equation, `data_loaders`
|
|
4074
|
+
* becomes a non-component `data_sources` registry, and parameter mutation moves
|
|
4075
|
+
* off events onto the parameter. None of that is a marker bump — every one of
|
|
4076
|
+
* them RESHAPES the document, and several need information (which unknowns are
|
|
4077
|
+
* ODE states) that only the equations carry. A 0.x source therefore yields no
|
|
4078
|
+
* supported targets rather than a bump that would produce a file claiming 1.0.0
|
|
4079
|
+
* while still carrying 0.x shapes. Converting a 0.x document is a rewrite, and
|
|
4080
|
+
* deliberately not offered as an automated one.
|
|
4081
|
+
*
|
|
4082
|
+
* The single supported target for an additive-line source is the CURRENT schema
|
|
4083
|
+
* version (`SCHEMA_VERSION`); arbitrary intermediate targets are deliberately
|
|
4084
|
+
* NOT offered — there is no per-minor transform to encode, only "bring this
|
|
4085
|
+
* file up to current". Sources outside that line (newer than current, a
|
|
4086
|
+
* different major, or malformed) yield no supported targets.
|
|
4087
|
+
*/
|
|
4088
|
+
|
|
4089
|
+
/**
|
|
4090
|
+
* Error thrown when migration fails.
|
|
4091
|
+
*/
|
|
4092
|
+
declare class MigrationError extends Error {
|
|
4093
|
+
constructor(message: string);
|
|
4094
|
+
}
|
|
4095
|
+
/**
|
|
4096
|
+
* Check if migration is possible from the source version to target version.
|
|
4097
|
+
*/
|
|
4098
|
+
declare function canMigrate(sourceVersion: string, targetVersion: string): boolean;
|
|
4099
|
+
/**
|
|
4100
|
+
* Get the list of schema versions that a given source version can migrate to.
|
|
4101
|
+
*
|
|
4102
|
+
* - any version on the additive line `1.0.0 … <current schema version>` →
|
|
4103
|
+
* `[SCHEMA_VERSION]` (a no-op marker bump to the current schema).
|
|
4104
|
+
* - everything else — including EVERY 0.x version, which 1.0.0's clean break
|
|
4105
|
+
* puts out of reach of a marker bump — → `[]`.
|
|
4106
|
+
*/
|
|
4107
|
+
declare function getSupportedMigrationTargets(sourceVersion: string): string[];
|
|
4108
|
+
/**
|
|
4109
|
+
* Migrate an ESM file from its current schema version to the target version.
|
|
4110
|
+
*
|
|
4111
|
+
* Every supported step is a pure version-marker bump with no structural
|
|
4112
|
+
* transform: an additive-line source (`1.0.0 … <current>`) advanced to the
|
|
4113
|
+
* current schema version (see the module header). Any other version pair — a
|
|
4114
|
+
* 0.x source included — throws {@link MigrationError}. Content-level changes
|
|
4115
|
+
* are not performed; they are modeling decisions, not mechanical migrations.
|
|
4116
|
+
* The input file is never mutated; a new object with the updated `esm` marker
|
|
4117
|
+
* is returned.
|
|
4118
|
+
*/
|
|
4119
|
+
declare function migrate(file: EsmFile, targetVersion: string): EsmFile;
|
|
4120
|
+
|
|
4121
|
+
/**
|
|
4122
|
+
* Coupling-library files and `coupling_import` role binding (esm-spec §10.9–§10.11).
|
|
4123
|
+
*
|
|
4124
|
+
* A *coupling-library file* is a document whose payload is a top-level
|
|
4125
|
+
* `coupling_roles` map plus a role-scoped `coupling` array. An assembly reuses
|
|
4126
|
+
* it with a `{ type: "coupling_import", ref, bind }` coupling entry: at flatten
|
|
4127
|
+
* the import expands into concrete `variable_map` / `couple` / `operator_compose`
|
|
4128
|
+
* / `event` edges by substituting the bound actual component for every
|
|
4129
|
+
* role-named top-level segment (the §10.10.2 occurrence surface).
|
|
4130
|
+
*
|
|
4131
|
+
* Expansion runs *inside* flatten (esm-spec §10.10.3), after subsystem mounting
|
|
4132
|
+
* (which happens at load, §2.1b) and before the coupling-rule step, so every
|
|
4133
|
+
* `bind` target resolves against fully-mounted components. The `coupling_import`
|
|
4134
|
+
* source entry is preserved for round-trip; only the flattened system carries
|
|
4135
|
+
* the expanded edges.
|
|
4136
|
+
*/
|
|
4137
|
+
|
|
4138
|
+
/** Options controlling how `coupling_import` refs are resolved at flatten. */
|
|
4139
|
+
interface CouplingImportOptions {
|
|
4140
|
+
/** Directory the import `ref`s resolve against. Defaults to '.'. */
|
|
4141
|
+
basePath?: string;
|
|
4142
|
+
/**
|
|
4143
|
+
* Resolve a `ref` string to a parsed coupling-library document. Defaults to a
|
|
4144
|
+
* synchronous Node `fs` reader. Tests may supply an in-memory resolver.
|
|
4145
|
+
*/
|
|
4146
|
+
loadRef?: (ref: string, basePath: string) => unknown;
|
|
4147
|
+
}
|
|
4148
|
+
/**
|
|
4149
|
+
* True when `raw` has the coupling-library-file FORM (top-level
|
|
4150
|
+
* `coupling_roles`, esm-spec §10.9). Presence of that key is the sole positive
|
|
4151
|
+
* identifier of the file kind; purity is checked separately at the import edge.
|
|
4152
|
+
*/
|
|
4153
|
+
declare function isCouplingLibraryDoc(raw: unknown): boolean;
|
|
4154
|
+
/**
|
|
4155
|
+
* Expand every `coupling_import` entry in `file.coupling` into concrete edges,
|
|
4156
|
+
* splicing them in the position of the import entry (esm-spec §10.10.3).
|
|
4157
|
+
* Returns the effective coupling array, or `undefined` if the file has no
|
|
4158
|
+
* `coupling` block. Non-import entries pass through untouched; a file with no
|
|
4159
|
+
* `coupling_import` entries needs no `options` and returns `file.coupling`
|
|
4160
|
+
* verbatim.
|
|
4161
|
+
*/
|
|
4162
|
+
declare function expandCouplingImports(file: EsmFile, options?: CouplingImportOptions): CouplingEntry[] | undefined;
|
|
4163
|
+
|
|
4164
|
+
/**
|
|
4165
|
+
* Coupled System Flattening for the ESM format
|
|
4166
|
+
*
|
|
4167
|
+
* Transforms a multi-system ESM file into a single unified flattened system
|
|
4168
|
+
* by namespacing all variables with their source system prefix and processing
|
|
4169
|
+
* coupling entries to produce a unified equation set.
|
|
4170
|
+
*/
|
|
4171
|
+
|
|
4172
|
+
/** Options for {@link flatten}. Only needed when the file uses `coupling_import`. */
|
|
4173
|
+
type FlattenOptions = CouplingImportOptions;
|
|
4174
|
+
/**
|
|
4175
|
+
* A single equation in the flattened system, with dot-namespaced variable names.
|
|
4176
|
+
*/
|
|
4177
|
+
interface FlattenedEquation {
|
|
4178
|
+
/** Dot-namespaced LHS variable name (e.g., "Atmos.O3") */
|
|
4179
|
+
lhs: string;
|
|
4180
|
+
/**
|
|
4181
|
+
* Expression string with namespaced references.
|
|
4182
|
+
*
|
|
4183
|
+
* For equations produced from a `couple` connector, the string uses a
|
|
4184
|
+
* `transform(expr)` pseudo-function convention: the connector's `transform`
|
|
4185
|
+
* (`"additive"` / `"multiplicative"` / `"replacement"`) is emitted as the
|
|
4186
|
+
* function name wrapping the (already-scoped) connector expression — e.g.
|
|
4187
|
+
* `additive(A.x)`. These are provenance/intent markers, not scalar operators
|
|
4188
|
+
* in {@link OPS}; a downstream consumer interprets the wrapper.
|
|
4189
|
+
*/
|
|
4190
|
+
rhs: string;
|
|
4191
|
+
/** Name of the source system this equation originated from */
|
|
4192
|
+
sourceSystem: string;
|
|
4193
|
+
}
|
|
4194
|
+
/**
|
|
4195
|
+
* Metadata describing the origin of the flattened system.
|
|
4196
|
+
*/
|
|
4197
|
+
interface FlattenMetadata {
|
|
4198
|
+
/** Names of all source systems that were flattened */
|
|
4199
|
+
sourceSystems: string[];
|
|
4200
|
+
/** Human-readable descriptions of coupling rules applied */
|
|
4201
|
+
couplingRules: string[];
|
|
4202
|
+
}
|
|
4203
|
+
/**
|
|
4204
|
+
* A fully flattened representation of a coupled ESM system.
|
|
4205
|
+
*/
|
|
4206
|
+
interface FlattenedSystem {
|
|
4207
|
+
/** All state variable names (dot-namespaced) */
|
|
4208
|
+
stateVariables: string[];
|
|
4209
|
+
/** All parameter names (dot-namespaced) */
|
|
4210
|
+
parameters: string[];
|
|
4211
|
+
/** All brownian (Wiener) noise variables (dot-namespaced). Any brownian => SDE system. */
|
|
4212
|
+
brownianVariables: string[];
|
|
4213
|
+
/** Observed/derived variables: namespaced name -> expression string */
|
|
4214
|
+
variables: Record<string, string>;
|
|
4215
|
+
/** All equations from all systems, with namespaced references */
|
|
4216
|
+
equations: FlattenedEquation[];
|
|
4217
|
+
/** Provenance metadata */
|
|
4218
|
+
metadata: FlattenMetadata;
|
|
4219
|
+
}
|
|
4220
|
+
/**
|
|
4221
|
+
* Flatten a multi-system ESM file into a single unified system.
|
|
4222
|
+
*
|
|
4223
|
+
* The algorithm:
|
|
4224
|
+
* 1. Iterates over all models and reaction_systems in the file
|
|
4225
|
+
* 2. Namespaces all variables with their system name prefix (dot notation)
|
|
4226
|
+
* 3. Processes coupling entries to produce variable mappings and connector equations
|
|
4227
|
+
* 4. Returns a unified flattened system
|
|
4228
|
+
*
|
|
4229
|
+
* @param file - The ESM file to flatten
|
|
4230
|
+
* @returns A FlattenedSystem with all variables namespaced and equations unified
|
|
4231
|
+
*/
|
|
4232
|
+
declare function flatten(file: EsmFile, options?: FlattenOptions): FlattenedSystem;
|
|
4233
|
+
|
|
4234
|
+
/**
|
|
4235
|
+
* Subsystem reference loading for the ESM format (esm-spec §4.7).
|
|
4236
|
+
*
|
|
4237
|
+
* Resolves subsystem `ref` fields by loading the referenced ESM file (local
|
|
4238
|
+
* path or remote URL), resolving any §9.7 template machinery + metaparameters
|
|
4239
|
+
* the referenced document carries against this edge's `bindings` / injected
|
|
4240
|
+
* imports, lowering it to the §9.6.3 fixpoint, then inlining the single
|
|
4241
|
+
* extracted component in place. Resolution is recursive with path-scoped
|
|
4242
|
+
* circular-reference detection.
|
|
4243
|
+
*
|
|
4244
|
+
* File access: local refs are read asynchronously via `node:fs/promises`
|
|
4245
|
+
* (dynamic import so the module still parses in a browser), remote refs via
|
|
4246
|
+
* `fetch`. Historically this module was purely fetch/fs I/O and so worked in
|
|
4247
|
+
* both Node and the browser; that is no longer unconditional. Once a ref
|
|
4248
|
+
* carries §9.7 machinery, resolution drives the SYNCHRONOUS §9.7 resolver over
|
|
4249
|
+
* the already-loaded content (`resolveTemplateMachinery`), which needs a
|
|
4250
|
+
* synchronous file reader for any transitive template-library imports — a
|
|
4251
|
+
* plain-fetch browser host cannot satisfy that, so a machinery-bearing ref is
|
|
4252
|
+
* fully resolvable only under Node (or a host supplying its own readFile hook).
|
|
4253
|
+
*/
|
|
4254
|
+
|
|
4255
|
+
/**
|
|
4256
|
+
* Error thrown when a circular reference is detected during subsystem resolution.
|
|
4257
|
+
*/
|
|
4258
|
+
declare class CircularReferenceError extends Error {
|
|
4259
|
+
/** The chain of references that form the cycle */
|
|
4260
|
+
readonly chain: string[];
|
|
4261
|
+
constructor(chain: string[]);
|
|
4262
|
+
}
|
|
4263
|
+
/**
|
|
4264
|
+
* Error thrown when a referenced file cannot be loaded, parsed, or uniquely
|
|
4265
|
+
* resolved to one system.
|
|
4266
|
+
*
|
|
4267
|
+
* Carries the CANONICAL cross-binding diagnostic code (see `ERROR_CODES`):
|
|
4268
|
+
*
|
|
4269
|
+
* - `unresolved_subsystem_ref` (default) — the file does not exist, or could
|
|
4270
|
+
* not be read or parsed.
|
|
4271
|
+
* - `ambiguous_subsystem_ref` — the file WAS read, and holds more than one
|
|
4272
|
+
* top-level system; §4.7 requires exactly one.
|
|
4273
|
+
*
|
|
4274
|
+
* The resolver is the only layer that reads the referenced file, so it is the
|
|
4275
|
+
* only layer that can tell those two apart — the synchronous `validate()` does
|
|
4276
|
+
* no I/O and reports every unresolved `{ref}` as `unresolved_subsystem_ref`.
|
|
4277
|
+
*/
|
|
4278
|
+
declare class RefLoadError extends Error {
|
|
4279
|
+
/** The reference path or URL that failed to load */
|
|
4280
|
+
readonly ref: string;
|
|
4281
|
+
/** Canonical code: `unresolved_subsystem_ref` or `ambiguous_subsystem_ref`. */
|
|
4282
|
+
readonly code: string;
|
|
4283
|
+
/**
|
|
4284
|
+
* JSON Pointer of the SUBSYSTEM ENTRY that carries the bad ref (e.g.
|
|
4285
|
+
* `/models/ClimateModel/subsystems/Atm`) — not the document root. The corpus
|
|
4286
|
+
* pins these errors at the offending mount, and a caller handed `$` has to go
|
|
4287
|
+
* hunting for which of a dozen mounts failed.
|
|
4288
|
+
*/
|
|
4289
|
+
readonly path: string;
|
|
4290
|
+
constructor(ref: string, cause?: Error, code?: string, message?: string, path?: string);
|
|
4291
|
+
}
|
|
4292
|
+
/**
|
|
4293
|
+
* Async resolution — the historical entry point, and the only one that can reach
|
|
4294
|
+
* a REMOTE (`http(s)://`) ref, since `fetch` cannot be awaited synchronously.
|
|
4295
|
+
*
|
|
4296
|
+
* It is now a thin shell around the SYNC core: fetch every reachable ref into a
|
|
4297
|
+
* cache first, then run the one and only resolution walk against that cache.
|
|
4298
|
+
* There is deliberately no second walk implementing the same semantics — index-set
|
|
4299
|
+
* merging, the §4.7 single-component invariant, template-machinery lowering,
|
|
4300
|
+
* cycle detection and component inlining exist in exactly one place, so the sync
|
|
4301
|
+
* and async paths cannot drift apart.
|
|
4302
|
+
*/
|
|
4303
|
+
declare function resolveSubsystemRefs(file: EsmFile, basePath: string): Promise<void>;
|
|
4304
|
+
/**
|
|
4305
|
+
* esm-spec §9.7.10 form C: build a throwaway `EsmFile` in which component
|
|
4306
|
+
* `mname` has the run's `imports` (raw §9.7.2 entries) appended to its own
|
|
4307
|
+
* `expression_template_imports`, so the ordinary import resolver + §9.6.3
|
|
4308
|
+
* fixpoint lower its rewrite-targets under the run-chosen discretization. The
|
|
4309
|
+
* persisted `file` is never mutated. This is what lets one test/analysis suite
|
|
4310
|
+
* exercise a discretization-agnostic PDE leaf under several schemes with no
|
|
4311
|
+
* conflict between runs.
|
|
4312
|
+
*
|
|
4313
|
+
* The raw base is re-read from `sourcePath` when given (relative import `ref`s
|
|
4314
|
+
* resolve against its directory), else re-serialized from `file`; `baseDir`
|
|
4315
|
+
* anchors the injected `ref`s. Mirrors the Julia reference
|
|
4316
|
+
* `_ephemeral_injected_file` (`EarthSciAST.jl/src/pde_inline_tests.jl`).
|
|
4317
|
+
*
|
|
4318
|
+
* This binding does not numerically simulate PDEs; the ephemeral build is the
|
|
4319
|
+
* structural-lowering half of form C (the leaf's rewrite-target is lowered in
|
|
4320
|
+
* this copy only). No solver is implied.
|
|
4321
|
+
*/
|
|
4322
|
+
declare function ephemeralInjectedFile(file: EsmFile | null, sourcePath: string | null, mname: string, imports: readonly unknown[], baseDir: string): Promise<EsmFile>;
|
|
4323
|
+
|
|
4324
|
+
/**
|
|
4325
|
+
* Canonical AST form per discretization RFC §5.4.
|
|
4326
|
+
*
|
|
4327
|
+
* Implements `canonicalize(expr)` and `canonicalJson(expr)` for the TypeScript
|
|
4328
|
+
* binding. Integer-vs-float AST-node distinction is carried by the
|
|
4329
|
+
* `NumericLiteral` tagged leaf (see `./numeric-literal.ts`); plain JS
|
|
4330
|
+
* `number` values are treated as untagged float-like literals for backward
|
|
4331
|
+
* compatibility with callers that have not migrated to `intLit` / `floatLit`.
|
|
4332
|
+
*
|
|
4333
|
+
* See `docs/rfcs/discretization.md` §5.4.1–§5.4.7 for the normative rules.
|
|
4334
|
+
*/
|
|
4335
|
+
|
|
4336
|
+
/** `E_CANONICAL_NONFINITE` — NaN or ±Inf (§5.4.6). */
|
|
4337
|
+
declare const E_CANONICAL_NONFINITE = "E_CANONICAL_NONFINITE";
|
|
4338
|
+
/** `E_CANONICAL_DIVBY_ZERO` — `/(0, 0)` (§5.4.7). */
|
|
4339
|
+
declare const E_CANONICAL_DIVBY_ZERO = "E_CANONICAL_DIVBY_ZERO";
|
|
4340
|
+
/** Canonicalize an expression tree per RFC §5.4. Input is not mutated. */
|
|
4341
|
+
declare function canonicalize(expr: Expr): Expr;
|
|
4342
|
+
/**
|
|
4343
|
+
* Emit canonical on-wire JSON per §5.4.6 (sorted keys, no whitespace).
|
|
4344
|
+
*
|
|
4345
|
+
* FAIL-CLOSED (matching the Julia reference): `canonicalize` PRESERVES every
|
|
4346
|
+
* node field, then this validates the canonicalized tree and throws
|
|
4347
|
+
* `E_CANONICAL_UNSUPPORTED_FIELD` if any node carries an own key (with a defined
|
|
4348
|
+
* value) outside the emissible ∪ tolerated set. A node carrying a non-emissible
|
|
4349
|
+
* aggregate/geometry field has NO faithful canonical JSON — emitting only the
|
|
4350
|
+
* pinned fields would collapse structurally-different nodes to identical bytes.
|
|
4351
|
+
*/
|
|
4352
|
+
declare function canonicalJson(expr: Expr): string;
|
|
4353
|
+
/**
|
|
4354
|
+
* Format a finite `number` as a byte-CANONICAL float token per RFC §5.4.6.
|
|
4355
|
+
* Only handles float-typed values: integer-typed `NumericLiteral` nodes are
|
|
4356
|
+
* emitted as bare JSON integers by {@link canonicalJson} directly.
|
|
4357
|
+
*
|
|
4358
|
+
* NAMING: distinct from `formatFloatToken` in `./numeric-literal` (the
|
|
4359
|
+
* document-serialization emitter used by `save()` / `losslessJsonStringify`).
|
|
4360
|
+
* This canonical version additionally NORMALIZES exponent notation — it strips
|
|
4361
|
+
* the leading `+` (RFC §5.4.6: "no leading + on the exponent") so `1e25` emits
|
|
4362
|
+
* as `1e25`, not `1e+25`, and forces the §5.4.6 exponent thresholds. Use this
|
|
4363
|
+
* one for canonical output, `formatFloatToken` for wire round-trip.
|
|
4364
|
+
*/
|
|
4365
|
+
declare function formatCanonicalFloat(f: number): string;
|
|
4366
|
+
|
|
4367
|
+
/**
|
|
4368
|
+
* Closed function registry — TypeScript binding for esm-spec §9.2.
|
|
4369
|
+
*
|
|
4370
|
+
* v0.3.0 set:
|
|
4371
|
+
* - datetime.year / .month / .day / .hour / .minute / .second
|
|
4372
|
+
* - datetime.day_of_year / .julian_day / .is_leap_year
|
|
4373
|
+
* - interp.searchsorted
|
|
4374
|
+
* - interp.linear, interp.bilinear (named tensor-interpolation primitives, esm-94w)
|
|
4375
|
+
*
|
|
4376
|
+
* The dispatch table is closed by construction. `fn`-op nodes whose name
|
|
4377
|
+
* is not in this set MUST be rejected with diagnostic
|
|
4378
|
+
* `unknown_closed_function`.
|
|
4379
|
+
*
|
|
4380
|
+
* Boundary semantics, tolerances, and error codes match the Julia
|
|
4381
|
+
* reference implementation (pkg/EarthSciAST.jl/src/registered_functions.jl).
|
|
4382
|
+
*/
|
|
4383
|
+
/** Stable diagnostic codes raised by the registry. */
|
|
4384
|
+
type ClosedFunctionErrorCode = 'unknown_closed_function' | 'closed_function_arity' | 'closed_function_overflow' | 'searchsorted_non_monotonic' | 'searchsorted_nan_in_table' | 'interp_non_monotonic_axis' | 'interp_axis_length_mismatch' | 'interp_nan_in_axis' | 'interp_axis_too_short' | 'interp_table_not_const' | 'interp_axis_not_const';
|
|
4385
|
+
/**
|
|
4386
|
+
* Error thrown by closed function dispatch and load-time table validation.
|
|
4387
|
+
* `code` identifies the spec-pinned diagnostic; cross-binding harnesses
|
|
4388
|
+
* compare against this exact string.
|
|
4389
|
+
*/
|
|
4390
|
+
declare class ClosedFunctionError extends Error {
|
|
4391
|
+
code: ClosedFunctionErrorCode;
|
|
4392
|
+
constructor(code: ClosedFunctionErrorCode, message: string);
|
|
4393
|
+
}
|
|
4394
|
+
/**
|
|
4395
|
+
* Validate a `searchsorted` xs table. Throws on NaN entries or
|
|
4396
|
+
* non-monotonic order. Empty arrays are rejected with the spec arity
|
|
4397
|
+
* code (the registry requires N ≥ 1).
|
|
4398
|
+
*/
|
|
4399
|
+
declare function validateSearchsortedTable(xs: readonly number[], where?: string): void;
|
|
4400
|
+
/**
|
|
4401
|
+
* Smallest 1-based `i` with `xs[i] ≥ x` (Julia `searchsortedfirst`
|
|
4402
|
+
* semantics). NaN x → N+1. xs MUST be pre-validated; the table is
|
|
4403
|
+
* inspected at every call so the caller can pass a fresh array each
|
|
4404
|
+
* scenario without bookkeeping (validation is cheap relative to the
|
|
4405
|
+
* dispatch overhead).
|
|
4406
|
+
*/
|
|
4407
|
+
declare function searchsortedFirst(x: number, xs: readonly number[]): number;
|
|
4408
|
+
/**
|
|
4409
|
+
* Validate a 1-D interpolation axis (`interp.linear` / `interp.bilinear`).
|
|
4410
|
+
* Strictly increasing, no NaN, length ≥ 2. Diagnostic codes match
|
|
4411
|
+
* esm-spec §9.2 "Errors (load time)" table.
|
|
4412
|
+
*/
|
|
4413
|
+
declare function validateInterpAxis(axis: readonly number[], where: string): void;
|
|
4414
|
+
/**
|
|
4415
|
+
* 1-D linear interpolation with extrapolate-flat clamps. Pinned form
|
|
4416
|
+
* `result = t[i] + w * (t[i+1] - t[i])` so that w=0/1 reproduce the
|
|
4417
|
+
* endpoint exactly under IEEE-754 round-to-nearest.
|
|
4418
|
+
*
|
|
4419
|
+
* Validates `axis` on every call (cheap relative to dispatch overhead;
|
|
4420
|
+
* matches the `searchsortedFirst` convention in this module).
|
|
4421
|
+
*/
|
|
4422
|
+
declare function interpLinear(table: readonly number[], axis: readonly number[], x: number): number;
|
|
4423
|
+
/**
|
|
4424
|
+
* 2-D bilinear interpolation with per-axis extrapolate-flat clamps.
|
|
4425
|
+
* Pinned evaluation order: two x-blends followed by one y-blend, each
|
|
4426
|
+
* in the form `a + w*(b - a)` (esm-spec §9.2). `table` is row-major:
|
|
4427
|
+
* `table[i][j]` is the value at `(axis_x[i], axis_y[j])`.
|
|
4428
|
+
*/
|
|
4429
|
+
declare function interpBilinear(table: readonly (readonly number[])[], axisX: readonly number[], axisY: readonly number[], x: number, y: number): number;
|
|
4430
|
+
/** Names that bindings MUST recognize (derived from the dispatch table keys). */
|
|
4431
|
+
declare const CLOSED_FUNCTION_NAMES: readonly string[];
|
|
4432
|
+
/**
|
|
4433
|
+
* Resolve a closed-function name + already-evaluated positional args into a
|
|
4434
|
+
* scalar result via {@link CLOSED_FUNCTION_DISPATCH}. Unknown names raise
|
|
4435
|
+
* `unknown_closed_function`.
|
|
4436
|
+
*/
|
|
4437
|
+
declare function dispatchClosedFunction(name: string, args: unknown[]): number;
|
|
4438
|
+
|
|
4439
|
+
/**
|
|
4440
|
+
* Load-time enum lowering pass — esm-spec §9.3.
|
|
4441
|
+
*
|
|
4442
|
+
* Walks the AST of a parsed EsmFile and rewrites every
|
|
4443
|
+
* `{op: "enum", args: [enum_name, member_name]}` node into the
|
|
4444
|
+
* equivalent `{op: "const", args: [], value: <integer>}` node, using the
|
|
4445
|
+
* file-local `enums` block to resolve the symbol.
|
|
4446
|
+
*
|
|
4447
|
+
* The pass is a no-op when no `enums` block is present. After lowering,
|
|
4448
|
+
* the file's expression trees contain no `enum` ops; the codegen
|
|
4449
|
+
* runner (`compileExpression` / `evaluateExpression`) sees only
|
|
4450
|
+
* `const`. Mirrors the Julia `lower_enums!` pass.
|
|
4451
|
+
*
|
|
4452
|
+
* Errors are `EnumLoweringError`s carrying stable, registry-backed diagnostic
|
|
4453
|
+
* codes (see `errors.ts` `ERROR_CODES`, mirrored by the Python `ErrorCode`
|
|
4454
|
+
* enum):
|
|
4455
|
+
* - `enum_op_malformed` — an `enum` op whose args are not
|
|
4456
|
+
* `[enum_name, member_name]` (two strings).
|
|
4457
|
+
* - `enum_not_declared` — reference to an enum name not present in the file's
|
|
4458
|
+
* top-level `enums` block.
|
|
4459
|
+
* - `enum_member_not_found` — reference to an unknown member of a declared
|
|
4460
|
+
* enum.
|
|
4461
|
+
*/
|
|
4462
|
+
|
|
4463
|
+
declare class EnumLoweringError extends Error {
|
|
4464
|
+
code: string;
|
|
4465
|
+
constructor(code: string, message: string);
|
|
4466
|
+
}
|
|
4467
|
+
/**
|
|
4468
|
+
* Resolve every `enum` op in `file` against `file.enums`. Returns the
|
|
4469
|
+
* (possibly identical) input — the rewrite is structural, immutable:
|
|
4470
|
+
* unchanged subtrees are shared with the input.
|
|
4471
|
+
*/
|
|
4472
|
+
declare function lowerEnums(file: EsmFile): EsmFile;
|
|
4473
|
+
|
|
4474
|
+
/**
|
|
4475
|
+
* Neutral base for EarthSciAST diagnostics: an `Error` carrying a stable `code`
|
|
4476
|
+
* string (from {@link ERROR_CODES}) and optional structured `details`. This is
|
|
4477
|
+
* purely additive — a single home for future diagnostics. It intentionally does
|
|
4478
|
+
* NOT touch the existing `EsmMachineryError` / `EnumLoweringError` /
|
|
4479
|
+
* `ClosedFunctionError` classes, which another file owns.
|
|
4480
|
+
*/
|
|
4481
|
+
declare class EsmDiagnosticError extends Error {
|
|
4482
|
+
readonly code: string;
|
|
4483
|
+
readonly details?: Record<string, unknown> | undefined;
|
|
4484
|
+
constructor(code: string, message: string, details?: Record<string, unknown> | undefined);
|
|
4485
|
+
}
|
|
4486
|
+
|
|
4487
|
+
/**
|
|
4488
|
+
* Load-time rewrite pass for `expression_templates` (esm-spec §9.6 /
|
|
4489
|
+
* docs/rfcs/ast-expression-templates.md, docs/rfcs/open-op-namespace-fixpoint-rewrite.md).
|
|
4490
|
+
*
|
|
4491
|
+
* An `expression_templates` entry is a **rewrite rule** with `params`
|
|
4492
|
+
* (metavariables), a `body` (the replacement Expression), an optional
|
|
4493
|
+
* integer `priority`, and an optional `match` pattern. This single engine
|
|
4494
|
+
* covers both application modes:
|
|
4495
|
+
*
|
|
4496
|
+
* - **No `match`** — the entry is applied only by an explicit
|
|
4497
|
+
* `apply_expression_template` node that names it and supplies
|
|
4498
|
+
* per-parameter `bindings` (named-template expansion).
|
|
4499
|
+
* - **With `match`** — the entry is an *auto-applied* rewrite rule.
|
|
4500
|
+
* `match` is a pattern Expression in which the params are wildcards:
|
|
4501
|
+
* a param in an operand/`args` position binds to the matched sub-AST;
|
|
4502
|
+
* a param in a scalar field (e.g. `dim`, `side`, or a custom `attrs.<key>`)
|
|
4503
|
+
* binds to the matched literal. The rule fires wherever the pattern
|
|
4504
|
+
* structurally matches a node.
|
|
4505
|
+
*
|
|
4506
|
+
* Rewriting is an **outermost-first, priority-ordered, bounded-fixpoint**
|
|
4507
|
+
* process (esm-spec §9.6.3; mirrors the Julia reference `_rewrite_pass` /
|
|
4508
|
+
* `_rewrite_to_fixpoint`). Rule application proceeds in **passes**; one pass
|
|
4509
|
+
* (`onePass`) is a single **pre-order (outermost-first)** walk of the tree. At
|
|
4510
|
+
* each node visited the engine first tries to fire a rule AT that node before
|
|
4511
|
+
* descending: an `apply_expression_template` op is expanded (counts as a
|
|
4512
|
+
* rewrite), otherwise the structurally-matching `match` rule of highest
|
|
4513
|
+
* `priority` (integer, default 0; ties broken by DECLARATION order) fires. A
|
|
4514
|
+
* fired rule's `body` replaces the node and the walk does **not** descend into
|
|
4515
|
+
* that freshly-produced body during the current pass (it is revisited next
|
|
4516
|
+
* pass). If nothing fires, the walk descends into children. Passes repeat until
|
|
4517
|
+
* a pass performs **zero** rewrites (the fixpoint) or until
|
|
4518
|
+
* `MAX_REWRITE_PASSES = 64` productive passes have run without converging, in
|
|
4519
|
+
* which case the file is rejected with `rewrite_rule_nonterminating`. The pass
|
|
4520
|
+
* bound — NOT a static check — is the authoritative termination guard, so a
|
|
4521
|
+
* self-reintroducing rule simply fails to converge. Because selection and
|
|
4522
|
+
* traversal are fully deterministic, all bindings produce byte-identical
|
|
4523
|
+
* fixpoints.
|
|
4524
|
+
*
|
|
4525
|
+
* After convergence the component carries no `expression_templates` block and
|
|
4526
|
+
* no `apply_expression_template` ops — downstream consumers see only normal
|
|
4527
|
+
* Expression ASTs (Option A round-trip). Any rewrite-target op (e.g. a spatial
|
|
4528
|
+
* `D`) that survives the fixpoint into an evaluation position is caught later by
|
|
4529
|
+
* the `unlowered_operator` gate (`evaluateExpression`), not here.
|
|
4530
|
+
*
|
|
4531
|
+
* Operates on the pre-coercion JSON view (plain objects) — runs in
|
|
4532
|
+
* `load()` after schema validation but before typed coercion.
|
|
4533
|
+
*
|
|
4534
|
+
* Errors (raised directly by this file; the code STRINGS live in
|
|
4535
|
+
* `./errors.js` `ERROR_CODES`):
|
|
4536
|
+
* - apply_expression_template_unknown_template
|
|
4537
|
+
* - apply_expression_template_bindings_mismatch
|
|
4538
|
+
* - apply_expression_template_recursive_body
|
|
4539
|
+
* - apply_expression_template_version_too_old
|
|
4540
|
+
* - apply_expression_template_invalid_declaration
|
|
4541
|
+
* - rewrite_rule_nonterminating
|
|
4542
|
+
* - template_constraint_unknown_index_set (§9.6.1 `where` registration)
|
|
4543
|
+
* - geometry_manifold_invalid (§9.6.4 expanded-form validator)
|
|
4544
|
+
* - makearray_region_inverted (§9.6.4 expanded-form validator)
|
|
4545
|
+
*
|
|
4546
|
+
* plus the esm-spec §9.7 template-library / metaparameter codes (§9.6.6,
|
|
4547
|
+
* raised from `template-imports.ts` and `ref-loading.ts`):
|
|
4548
|
+
*
|
|
4549
|
+
* - template_import_version_too_old
|
|
4550
|
+
* - template_import_unresolved
|
|
4551
|
+
* - template_import_not_library
|
|
4552
|
+
* - subsystem_ref_is_template_library
|
|
4553
|
+
* - template_import_cycle
|
|
4554
|
+
* - template_import_name_conflict
|
|
4555
|
+
* - template_import_unknown_name
|
|
4556
|
+
* - template_import_index_set_conflict
|
|
4557
|
+
* - template_body_expansion_too_deep
|
|
4558
|
+
* - metaparameter_unbound
|
|
4559
|
+
* - metaparameter_type_error
|
|
4560
|
+
* - metaparameter_name_conflict
|
|
4561
|
+
*/
|
|
4562
|
+
|
|
4563
|
+
/**
|
|
4564
|
+
* Shared load-time diagnostic for the §9.x machinery: expression-template
|
|
4565
|
+
* lowering (§9.6), template-library imports (§9.7), coupling-library imports
|
|
4566
|
+
* (§10.10), subsystem-ref loading, and the §9.6.4 expanded-form validators all
|
|
4567
|
+
* raise it as their common coded-diagnostic class — validate.ts maps it (by
|
|
4568
|
+
* `instanceof`) to the `expression_template_error` load-error kind. Extends the
|
|
4569
|
+
* neutral {@link EsmDiagnosticError} additively: the `(code, message)`
|
|
4570
|
+
* constructor signature, the `[code] message` text, and the public `code`
|
|
4571
|
+
* string property are all preserved byte-for-byte, so the emitted diagnostic is
|
|
4572
|
+
* unchanged and every `instanceof` check is unaffected.
|
|
4573
|
+
*/
|
|
4574
|
+
declare class EsmMachineryError extends EsmDiagnosticError {
|
|
4575
|
+
constructor(code: string, message: string);
|
|
4576
|
+
}
|
|
4577
|
+
|
|
4578
|
+
/**
|
|
4579
|
+
* Maximum template-body reference-chain depth (counted in TEMPLATES along the
|
|
4580
|
+
* longest chain, so a 33-template chain is rejected while a 32-template chain
|
|
4581
|
+
* is accepted) before a file is rejected with
|
|
4582
|
+
* `template_body_expansion_too_deep` (esm-spec §9.7.3). Pinned identically
|
|
4583
|
+
* across all bindings.
|
|
4584
|
+
*/
|
|
4585
|
+
declare const MAX_TEMPLATE_EXPANSION_DEPTH = 32;
|
|
4586
|
+
/**
|
|
4587
|
+
* Reject `apply_expression_template` and `expression_templates` in files
|
|
4588
|
+
* declaring `esm` < 0.4.0. Operates on the pre-coercion JSON view.
|
|
4589
|
+
*/
|
|
4590
|
+
declare function rejectExpressionTemplatesPreV04(view: unknown): void;
|
|
4591
|
+
/**
|
|
4592
|
+
* Load the file under Option B (reference preservation, esm-spec §9.6.4): fire
|
|
4593
|
+
* auto-applied `match` rules and eagerly expand target-bearing references to a
|
|
4594
|
+
* fixpoint per component (outermost-first, priority-ordered, bounded — §9.6.3),
|
|
4595
|
+
* but leave NON-eager `apply_expression_template` references intact (they
|
|
4596
|
+
* denote their expansion, §9.6.4 rule 2). The per-component
|
|
4597
|
+
* `expression_templates` registries are RETAINED — they are what {@link
|
|
4598
|
+
* expandDocument} consumes (rule 2) and emit materializes (rule 5). Call-site
|
|
4599
|
+
* checks (§9.6.9), the reference-aware geometry-manifold check, and the
|
|
4600
|
+
* registration-time makearray-region check run on the reference-preserving form.
|
|
4601
|
+
*
|
|
4602
|
+
* Returns a new file object; the input is not mutated.
|
|
4603
|
+
*
|
|
4604
|
+
* Pre-condition: the input has been schema-validated.
|
|
4605
|
+
*/
|
|
4606
|
+
declare function lowerExpressionTemplates<T extends object>(file: T): T;
|
|
4607
|
+
/**
|
|
4608
|
+
* Fully expand every surviving `apply_expression_template` reference in a
|
|
4609
|
+
* document `loaded` by {@link lowerExpressionTemplates} (Option B), producing
|
|
4610
|
+
* the Option-A image: every reference replaced by its expansion (pure
|
|
4611
|
+
* substitution to the acyclic fixpoint, §9.6.4 rule 2) and every per-component
|
|
4612
|
+
* `expression_templates` block stripped. Deterministic — the §9.7.3 DAG is
|
|
4613
|
+
* acyclic and substitution confluent, so `expandDocument(load(f))` is
|
|
4614
|
+
* structurally equal to the pre-0.9.0 expanded form (the `expanded*.esm`
|
|
4615
|
+
* conformance oracle). Non-destructive: `loaded` is deep-cloned first. Mirrors
|
|
4616
|
+
* the Julia reference `expand_document` / `Expand`.
|
|
4617
|
+
*/
|
|
4618
|
+
declare function expandDocument<T extends object>(loaded: T): T;
|
|
4619
|
+
|
|
4620
|
+
/**
|
|
4621
|
+
* Per-component MATCH-LESS template names authored in-file in `rawSource`
|
|
4622
|
+
* (`compKind.cname` → ordered names). Emit keeps these verbatim as authored
|
|
4623
|
+
* entries (esm-spec §9.6.4 rule 5); imported/derived templates are materialized
|
|
4624
|
+
* instead. Mirrors the Julia reference `_authored_template_names`.
|
|
4625
|
+
*/
|
|
4626
|
+
declare function authoredTemplateNames(rawSource: unknown): Record<string, string[]>;
|
|
4627
|
+
/**
|
|
4628
|
+
* Build the reference-preserving, self-contained emitted document (esm-spec
|
|
4629
|
+
* §9.6.4 rule 5, §7.5) from an already Option-B-loaded document `loaded` and
|
|
4630
|
+
* the authored-name map from the pristine source. For every component builds
|
|
4631
|
+
* its emitted `expression_templates` block — authored match-less entries first
|
|
4632
|
+
* in authored order, then the materialized transitive closure of its surviving
|
|
4633
|
+
* references (match-less), lexicographically sorted — drops consumed
|
|
4634
|
+
* `expression_template_imports`, and version-stamps `esm: 0.9.0` when any
|
|
4635
|
+
* surviving reference or materialized entry remains (§9.6.4 rule 8). Mutates
|
|
4636
|
+
* and returns `loaded`. Mirrors the Julia reference `emit_document` tail.
|
|
4637
|
+
*/
|
|
4638
|
+
declare function buildEmittedDocument(loaded: Record<string, unknown>, authored: Record<string, string[]>): Record<string, unknown>;
|
|
4639
|
+
/**
|
|
4640
|
+
* Canonical byte serialization of an emitted document (esm-spec §9.6.4 rule 5):
|
|
4641
|
+
* 2-space indent, object keys sorted lexicographically (UTF-8 byte order)
|
|
4642
|
+
* EXCEPT the entries of an `expression_templates` object, which preserve their
|
|
4643
|
+
* authored-first / materialized-sorted order. The cross-binding byte-identity
|
|
4644
|
+
* surface for the Option-B emitted form and the target of the `emitted.esm`
|
|
4645
|
+
* goldens. Mirrors the Julia reference `emit_esm_string`.
|
|
4646
|
+
*/
|
|
4647
|
+
declare function emitEsmString(doc: unknown): string;
|
|
4648
|
+
/** Result of {@link flattenTemplateRegistries}: the rewritten document + merged registry. */
|
|
4649
|
+
interface FlattenedTemplateRegistries {
|
|
4650
|
+
root: Record<string, unknown>;
|
|
4651
|
+
merged: Record<string, unknown>;
|
|
4652
|
+
}
|
|
4653
|
+
/**
|
|
4654
|
+
* The flatten-time template-registry merge (esm-spec §9.6.4 rule 7, §10.7;
|
|
4655
|
+
* esm-libraries-spec §4.7.5 step 4). Given an Option-B loaded multi-component
|
|
4656
|
+
* document `loaded`, merge every component's match-less `expression_templates`
|
|
4657
|
+
* registry into a single document-scoped merged registry:
|
|
4658
|
+
*
|
|
4659
|
+
* - **Deep-equal dedup at first occurrence** — two components importing one
|
|
4660
|
+
* stencil produce identical folded bodies, kept once under the bare name.
|
|
4661
|
+
* - **Non-deep-equal same-name collision** — both entries are renamed
|
|
4662
|
+
* deterministically to `<ComponentPath>.<name>` and their
|
|
4663
|
+
* `apply_expression_template` references are rewritten in lockstep.
|
|
4664
|
+
* - **Collisions propagate along the reference DAG** — a declaration that
|
|
4665
|
+
* references a colliding name collides too (see
|
|
4666
|
+
* {@link registryCollisionNames}), so a byte-identical wrapper over a
|
|
4667
|
+
* per-component leaf is renamed per owner rather than deduped into one body
|
|
4668
|
+
* whose nested reference no longer resolves.
|
|
4669
|
+
*
|
|
4670
|
+
* Returns the rewritten document `root` (component reference sites updated) and
|
|
4671
|
+
* the merged registry (the FlattenedSystem's first-class registry field).
|
|
4672
|
+
* `match` rules are not merged (only match-less templates are referenceable).
|
|
4673
|
+
* Mirrors the Julia reference `flatten_template_registries`.
|
|
4674
|
+
*/
|
|
4675
|
+
declare function flattenTemplateRegistries(loaded: object): FlattenedTemplateRegistries;
|
|
4676
|
+
|
|
4677
|
+
type JsonObject = Record<string, unknown>;
|
|
4678
|
+
/** Schema-error shape accepted from the host's schema validator. */
|
|
4679
|
+
interface TemplateSchemaError {
|
|
4680
|
+
path: string;
|
|
4681
|
+
message: string;
|
|
4682
|
+
}
|
|
4683
|
+
/** Options threaded through §9.7 resolution. */
|
|
4684
|
+
interface TemplateResolveOptions {
|
|
4685
|
+
/**
|
|
4686
|
+
* Loader-API metaparameter bindings for the ROOT document
|
|
4687
|
+
* (esm-spec §9.7.6 binding site 4). Already-closed edge bindings win;
|
|
4688
|
+
* API bindings beat `default`s.
|
|
4689
|
+
*/
|
|
4690
|
+
metaparameters?: Record<string, number> | undefined;
|
|
4691
|
+
/**
|
|
4692
|
+
* Synchronous file reader for import refs. Defaults to Node's
|
|
4693
|
+
* `fs.readFileSync` (via `process.getBuiltinModule`); browser hosts must
|
|
4694
|
+
* supply their own.
|
|
4695
|
+
*/
|
|
4696
|
+
readFile?: ((path: string) => string) | undefined;
|
|
4697
|
+
/**
|
|
4698
|
+
* Schema validator applied to each import target (a target failing schema
|
|
4699
|
+
* validation is `template_import_unresolved`, mirroring the Julia
|
|
4700
|
+
* reference). Supplied by `load()`; optional for direct/raw use.
|
|
4701
|
+
*/
|
|
4702
|
+
validateSchema?: ((raw: unknown) => TemplateSchemaError[]) | undefined;
|
|
4703
|
+
}
|
|
4704
|
+
/**
|
|
4705
|
+
* `expression_template_imports`, top-level `expression_templates`
|
|
4706
|
+
* (template-library files), and `metaparameters` arrive at `esm: 0.8.0`;
|
|
4707
|
+
* files declaring an earlier version that carry any of them are rejected
|
|
4708
|
+
* with `template_import_version_too_old` (esm-spec §9.6.5). Mirrors
|
|
4709
|
+
* `rejectExpressionTemplatesPreV04` for the §9.7 constructs.
|
|
4710
|
+
*/
|
|
4711
|
+
declare function rejectTemplateImportsPreV08(view: unknown): void;
|
|
4712
|
+
/**
|
|
4713
|
+
* True when `raw` has the template-library-file FORM (top-level
|
|
4714
|
+
* `expression_templates`, esm-spec §9.7.1). Purity (no models / reaction
|
|
4715
|
+
* systems / loaders / coupling / domain) is checked separately at import
|
|
4716
|
+
* edges.
|
|
4717
|
+
*/
|
|
4718
|
+
declare function isTemplateLibraryDoc(raw: unknown): boolean;
|
|
4719
|
+
/**
|
|
4720
|
+
* Resolve every esm-spec §9.7 construct of the ROOT document `rawData`
|
|
4721
|
+
* (relative import refs resolve against `basePath`): imports recursively
|
|
4722
|
+
* with per-edge instantiation, `index_sets` merge, metaparameter close
|
|
4723
|
+
* (`options.metaparameters` is the loader-API binding site 4;
|
|
4724
|
+
* already-closed edge bindings win, then API bindings, then defaults) and
|
|
4725
|
+
* fold, expression-position substitution, and — for a root library file —
|
|
4726
|
+
* §9.7.3 body composition.
|
|
4727
|
+
*
|
|
4728
|
+
* Returns an order-preserving plain-object tree ready for
|
|
4729
|
+
* `lowerExpressionTemplates` with `expression_template_imports`,
|
|
4730
|
+
* `metaparameters`, and top-level `expression_templates` consumed (Option A
|
|
4731
|
+
* round-trip: none survives `parse → emit`), or `null` when the document
|
|
4732
|
+
* carries no §9.7 machinery (the legacy fast path).
|
|
4733
|
+
*/
|
|
4734
|
+
declare function resolveTemplateMachinery(rawData: unknown, basePath: string, options?: TemplateResolveOptions): JsonObject | null;
|
|
4735
|
+
/**
|
|
4736
|
+
* Produce the reference-preserving, self-contained emitted document (esm-spec
|
|
4737
|
+
* §9.6.4 rule 5, RFC out-of-line-expression-templates §7.5) from a source
|
|
4738
|
+
* document `rawSource` (a fixture, or an already-emitted document for the
|
|
4739
|
+
* idempotency property; relative import refs resolve against `basePath`). Loads
|
|
4740
|
+
* `rawSource` under Option B, then materializes each component's surviving
|
|
4741
|
+
* reference closure into its `expression_templates` block, drops consumed
|
|
4742
|
+
* imports, and version-stamps `esm: 0.9.0` when any reference/materialized entry
|
|
4743
|
+
* remains (§9.6.4 rule 8). `emitEsmString ∘ emitDocument` is a byte-wise fixed
|
|
4744
|
+
* point under reload. Mirrors the Julia reference `emit_document`.
|
|
4745
|
+
*/
|
|
4746
|
+
declare function emitDocument(rawSource: unknown, basePath: string, options?: TemplateResolveOptions): JsonObject;
|
|
4747
|
+
/**
|
|
4748
|
+
* esm-spec §9.7.10 forms A + B: if `raw` needs a scope-directed injection (a
|
|
4749
|
+
* non-empty subsystem-ref edge list `injected`, or a coupling entry carrying
|
|
4750
|
+
* an injection map), return a fresh plain-object tree with the injected
|
|
4751
|
+
* imports folded into the target components' own `expression_template_imports`,
|
|
4752
|
+
* ready for `resolveTemplateMachinery`. Returns `null` when no injection
|
|
4753
|
+
* applies, so the caller keeps its original fast path.
|
|
4754
|
+
*/
|
|
4755
|
+
declare function applyScopeInjections(raw: unknown, injected?: readonly unknown[]): JsonObject | null;
|
|
4756
|
+
|
|
4757
|
+
export { CLOSED_FUNCTION_NAMES, CadenceCycleError, CadenceSeeder, CanonicalNonfiniteError, CanonicalizeError, CircularReferenceError, ClosedFunctionError, DEFAULT_MIN_COMPLEXITY, E_CANONICAL_DIVBY_ZERO, E_CANONICAL_NONFINITE, EntityNotFoundError, EnumLoweringError, EsmMachineryError, EvaluatorError, expandDocument as Expand, ExpressionAnalyzer, ExpressionParseError, EsmMachineryError as ExpressionTemplateError, InvalidDerivativeOrderError, LosslessJsonParseError, MAX_TEMPLATE_EXPANSION_DEPTH, MigrationError, NonDifferentiableExpressionError, ParseError, RefLoadError, SCHEMA_VERSION, SchemaValidationError, UnitConversionError, UnloweredOperatorError, SCHEMA_VERSION as VERSION, VariableInUseError, addContinuousEvent, addCoupling, addDiscreteEvent, addEquation, addReaction, addSpecies, addVariable, algebraicUnknowns, analyzeComplexity, analyzeExpression, applyScopeInjections, authoredTemplateNames, brownianParameters, buildDependencyGraph, buildEmittedDocument, canMigrate, canonicalJson, canonicalize, checkDimensions, classifyComplexity, classifyDocument, classifyModel, compareComplexity, compileExpression, componentExists, componentGraph, component_graph, compose, constantParameters, contains, convertUnits, declaredSystemKind, deriveODEs, detectStabilityIssues, differentiate, discreteParameters, dispatchClosedFunction, emitDocument, emitEsmString, ephemeralInjectedFile, estimateParallelPotential, estimateSavings, evaluateExpression, expandCouplingImports, expandDocument, expressionCadence, expressionGraph, extract, findCommonSubexpressions, findCommonSubexpressionsAcrossExpressions, findCommonSubexpressionsInEsmFile, findCommonSubexpressionsInModel, findCriticalPoints, findDeadVariables, findDependencyChains, findExpensiveSubexpressions, flatten, flattenTemplateRegistries, floatLit, formatCanonicalFloat, formatChemicalName, formatFloatToken, freeParameters, freeVariables, generateFactoredVariableNames, getComponentType, getSupportedMigrationTargets, gradient, groupSubexpressionsByType, higherOrderDerivative, intLit, interpBilinear, interpLinear, isCouplingLibraryDoc, isDifferentiable, isFloatLit, isIntLit, isNumericLiteral, isOdeState, isTemplateLibraryDoc, joinAll, joinCadence, leafCadence, load, losslessJsonParse, losslessJsonStringify, lowerEnums, lowerExpressionTemplates, mapVariable, merge, migrate, numericValue, observedDefinitions, observedUnknowns, odeStates, parameterClass, parameters, parseEquation, parseExpression, parseReaction, parseUnit, parseUnitForConversion, partialDerivatives, productMatrix, rejectExpressionTemplatesPreV04, rejectTemplateImportsPreV08, removeCoupling, removeEquation, removeEvent, removeReaction, removeSpecies, removeVariable, renameVariable, resolveSubsystemRefs, resolveTemplateMachinery, sampledParameters, save, searchsortedFirst, simplify, stoichiometricMatrix, substitute, substituteInEquations, substituteInModel, substituteInReactionSystem, substrateMatrix, systemKind, toAscii, toDot, toJsonGraph, toLatex, toMathML, toMermaid, toUnicode, tryParseUnit, unitsCompatible, unknowns, updateRules, validate, validateInterpAxis, validateSchema, validateSearchsortedTable, validateUnits };
|
|
4758
|
+
export type { AffectEquation, Analysis, AnalysisOptions, AnalysisResults, Assertion, Assertion1, CadenceClass, CanonicalDims, ClosedFunctionErrorCode, CommonSubexpression, CompiledExpression, ComplexityMetrics, ComponentGraph, ComponentNode, ConditionUpdate, ConnectorEquation, ContinuousEvent, Coordinate, Coordinate1, CouplingCallback, CouplingCouple, CouplingEdge, CouplingEntry, CouplingEvent, CouplingEvent1, CouplingImport, CouplingImportOptions, CouplingOperatorCompose, CouplingVariableMap, CouplingVariableMap1, CovarianceMatrix, CrossingUpdate, DataSource, DataSourceBinding, DataSourceCodes, DataSourceDeterminism, DataSourceExtent, DataSourceLocation, DataSourceRecordFilter, DataSourceSelect, DataSourceSelectAxis, DataSourceTemporal, DataUpdate, DependencyEdge, DependencyGraph, DependencyNode, DependencyRelation, DerivativeResult, DiscreteEvent, DiscreteEventTrigger, Distribution, Domain, ESMFormat, ESMFormat1, ESMFormat2, EnumDeclaration, Equation, EsmFile, EsmFormat, Expr, ExprNode, ExprNodeOf, Expression, ExpressionLocation, ExpressionNode, ExpressionNode1, ExpressionTemplate, FlattenMetadata, FlattenOptions, FlattenedEquation, FlattenedSystem, FlattenedTemplateRegistries, FunctionTable, FunctionTableAxis, FunctionalUpdate, Graph, IndexSet, IndexSet1, LoadOptions, LognormalDistribution, Metadata, MetaparameterExpression, Metaparameters, Model, ModelClassification, ModelVariable, ModelVariable1, NonWienerParameterUpdate, NormalDistribution, NumericLiteral, Parameter, Parameter1, ParameterClass, ParameterSweep, ParameterUpdate, ParameterUpdateSpec, ParsedUnit, Plot, Plot1, PlotAxis, PlotSeries, PlotValue, Reaction, ReactionSystem, Reference, RemeshUpdate, SaveOptions, ScheduleUpdate, SchemaError, Species, StabilityIssue, StoichiometryEntry, SubsystemRef, SweepDimension, SweepDimension1, SweepRange, SystemKind, TemplateImport, TemplateResolveOptions, TemplateSchemaError, Test, TimeSpan, Tolerance, Tolerance1, Tolerance2, Tolerance3, TranslateTarget, UniformDistribution, UnitResult, UnitWarning, UnknownClass, UpdateValueForm, ValidationError, ValidationResult, VariableKind, VariableNode, WienerUpdate };
|