TypeScript extension seams
TypeScript's extension-tier names: documented, reachable, not portable.
Extension-tier names are part of this binding’s documented surface but are not harmonized across bindings, and may change in a minor release (API_SPEC.md §7 ).
91 names.
AnalysisOptions
type · canonical name analysis_options
interface AnalysisOptions {
includeComplexity?: boolean;
includeSubexpressions?: boolean;
includeDependencies?: boolean;
includeDerivatives?: boolean;
variables?: string[];
minComplexityThreshold?: number;
}
Options controlling which analyses analyzeExpression
runs.
Properties
includeComplexity— Compute complexity metrics and stability issues (expression targets only).includeSubexpressions— Identify common subexpressions (expression targets only).includeDependencies— Build the variable dependency graph.includeDerivatives— Compute partial derivatives and gradient (expression targets only).variables— Variables to differentiate with respect to (required for derivatives).minComplexityThreshold— Minimum complexity threshold for common-subexpression detection.
AnalysisResults
type · canonical name analysis_results
interface AnalysisResults {
complexity?: ComplexityMetrics;
stabilityIssues?: StabilityIssue[];
commonSubexpressions?: CommonSubexpression[];
dependencyGraph?: DependencyGraphType;
partialDerivatives?: Map<string, DerivativeResult>;
gradient?: DerivativeResult[];
}
Combined results returned by analyzeExpression
.
analyzeComplexity
function · canonical name analyze_complexity
function analyzeComplexity(expr: Expr): ComplexityMetrics
Analyze the complexity of an expression
Parameters
expr— Expression to analyze
Returns
Complexity metrics
analyzeExpression
function · canonical name analyze_expression
function analyzeExpression(target: Expr | Model | EsmFile, options?: AnalysisOptions): AnalysisResults
Perform comprehensive analysis of an expression or model.
Parameters
target— Expression, Model, or ESM file to analyzeoptions— Analysis options
Returns
Complete analysis results
authoredTemplateNames
function · canonical name authored_template_names
function authoredTemplateNames(rawSource: unknown): Record<string, string[]>
Per-component MATCH-LESS template names authored in-file in rawSource
(compKind.cname → ordered names). Emit keeps these verbatim as authored
entries (esm-spec §9.6.4 rule 5); imported/derived templates are materialized
instead. Mirrors the Julia reference _authored_template_names.
buildDependencyGraph
function · canonical name build_dependency_graph
function buildDependencyGraph(target: EsmFile | Model | ReactionSystem | Expr, options?: { includeParameters?: boolean; includeObserved?: boolean; mergeAcrossSystems?: boolean }): DependencyGraph
Build a dependency graph from an ESM file, model, or expression
Parameters
target— The target to analyzeoptions— Analysis options
Returns
Dependency graph with nodes and edges
buildEmittedDocument
function · canonical name build_emitted_document
function buildEmittedDocument(loaded: Record<string, unknown>, authored: Record<string, string[]>): Record<string, unknown>
Build the reference-preserving, self-contained emitted document (esm-spec
§9.6.4 rule 5, §7.5) from an already Option-B-loaded document loaded and
the authored-name map from the pristine source. For every component builds
its emitted expression_templates block — authored match-less entries first
in authored order, then the materialized transitive closure of its surviving
references (match-less), lexicographically sorted — drops consumed
expression_template_imports, and version-stamps esm: 0.9.0 when any
surviving reference or materialized entry remains (§9.6.4 rule 8). Mutates
and returns loaded. Mirrors the Julia reference emit_document tail.
CadenceClass
type · canonical name cadence_class
type CadenceClass = 'const' | 'discrete' | 'continuous';
The three cadence classes, totally ordered const ⊏ discrete ⊏ continuous.
CadenceCycleError
error · canonical name cadence_cycle_error
class CadenceCycleError extends EsmDiagnosticError
new CadenceCycleError(cycle: string[]): CadenceCycleError
Raised when the observed-definition chain contains a cycle.
CadenceSeeder
type · canonical name cadence_seeder
class CadenceSeeder
new CadenceSeeder(model: Model, esmFile?: EsmFile): CadenceSeeder
CadenceSeeder.prototype.observedNames(): string[]
CadenceSeeder.prototype.leaf(name: string): CadenceClass
CadenceSeeder.prototype.expression(expr: Expression): CadenceClass
A reusable cadence seeder for ONE model. Holds the memo table for observed resolution, so a chain of observeds is resolved once rather than once per reference.
Members
observedNames— The set of observed unknowns, for callers that want to enumerate them.leaf— The cadence seed of a single NAME appearing as a leaf.A name that is not declared in this model — an index-set name, a bound index symbol, a relation tag, a coupled reference — seeds
const, matching the final row of the §5.7.2 table.expression— The cadence of an EXPRESSION:maxover its leaves.The gather rule needs no special case — index expressions are ordinary children, so
index(u, index(nbr, i, k))splits naturally, the inner neighbour selection stayingconstwhile the outer value load iscontinuousbecause it touchesu.
CanonicalDims
type · canonical name canonical_dims
interface CanonicalDims {
kg?: number;
m?: number;
s?: number;
K?: number;
mol?: number;
A?: number;
cd?: number;
rad?: number;
}
Exponents over the SI base dimensions — the SAME eight axes, in the same
roles, as the Go reference’s Dimension vector (m kg s mol K A cd rad),
which is the cross-binding contract for what a unit string MEANS.
molec is deliberately NOT an axis. A count of discrete things carries no
physical dimension, so molec (and individuals, vehicles, units,
count) is a DIMENSIONLESS unit in the table below — which is what makes
molec/cm^3 compare equal to 1/cm^3, as every other binding has it.
A missing key means exponent zero; {} is dimensionless.
checkDimensions
function · canonical name check_dimensions
function checkDimensions(expr: Expression, unitBindings: Map<string, ParsedUnit>, options?: DimensionOptions): UnitResult
Check dimensional consistency of an expression.
Follows ESM spec Section 3.3.1:
- Addition/subtraction: operands must share canonical dimensions
- Multiplication: dimensions add (scales multiply)
- Division: dimensions subtract (scales divide)
^with a constant integer exponent: dimensions scale by the exponentsqrt: dimensions halveD(x, wrt=t): dimension of x divided by dimension of t- Transcendental functions require dimensionless arguments
Returns dimensions: null for anything INDETERMINATE (see
UnitResult.dimensions) — an unknown variable, or an operator this
module does not model dimensionally. Indeterminate operands never produce a
mismatch; only a provable inconsistency does.
classifyComplexity
function · canonical name classify_complexity
function classifyComplexity(expr: Expr): 'trivial' | 'simple' | 'moderate' | 'complex' | 'very_complex'
Classify expression complexity level
Parameters
expr— Expression to classify
Returns
Complexity level
classifyDocument
function · canonical name classify_document
function classifyDocument(models: { [k: string]: unknown }): { [path: string]: ModelClassification }
Classify every model node in a document, keyed by DOT-PATH from the document
root, so a subsystem is Parent.Child. Classification is per model NODE, not
per document: the names inside each list are LOCAL to that model and are not
namespaced. A binding that flattens the document first and classifies once
returns one merged answer instead of a scoped answer per node.
classifyModel
function · canonical name classify_model
function classifyModel(model: Model): ModelClassification
Classify one model node.
CLOSED_FUNCTION_NAMES
constant · canonical name closed_function_names
const CLOSED_FUNCTION_NAMES: readonly string[]
Deprecated. Use closedFunctionNames().
Deprecated. Use closedFunctionNames
. Kept for one minor per
API_SPEC.md §10; removed at the next major.
ClosedFunctionErrorCode
type · canonical name closed_function_error_code
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';
The stable diagnostic codes a ClosedFunctionError
can carry: an
unrecognized function name or wrong argument count at dispatch, a non-finite
input or out-of-range integer result, and the load-time validation failures of
interp.searchsorted tables and interp.linear / interp.bilinear axes
and tables (non-monotonic, NaN, length mismatch, too short, not a constant).
CommonSubexpression
type · canonical name common_subexpression
interface CommonSubexpression {
expression: Expr;
locations: ExpressionLocation[];
count: number;
savings: number;
}
Common subexpression identification result
Properties
expression— The common subexpressionlocations— Locations where this subexpression appearscount— Number of occurrencessavings— Estimated cost savings from factoring out
compareComplexity
function · canonical name compare_complexity
function compareComplexity(expr1: Expr, expr2: Expr): number
Compare complexity of two expressions
Parameters
expr1— First expressionexpr2— Second expression
Returns
Comparison result (-1: expr1 simpler, 0: equal, 1: expr1 more complex)
CompiledExpression
type · canonical name compiled_expression
type CompiledExpression = (bindings: Map<string, number>) => number;
Compiled expression closure produced by compileExpression
.
Accepts a bindings map of free-variable name → numeric value and
returns the scalar result.
compileExpression
function · canonical name compile_expression
function compileExpression(expr: Expr, options?: EvaluateOptions): CompiledExpression
Build a reusable closure that walks the canonical-AST Expr and
evaluates it against a bindings map. This is the EarthSciAST TypeScript
runner’s entry point for scalar evaluation.
The walker rejects unlowered enum ops (lower via lowerEnums() at
load time) and array-valued const nodes (those are consumed by
container ops such as interp.searchsorted and index, not by
scalar evaluation).
Pass { functionTables: file.function_tables } to evaluate an expression
containing table_lookup nodes — see EvaluateOptions.
ComplexityMetrics
type · canonical name complexity_metrics
interface ComplexityMetrics {
depth: number;
operationCount: number;
variableCount: number;
constantCount: number;
operationTypes: Record<string, number>;
computationalCost: number;
memoryUsage: number;
}
Complexity metrics for an expression
Properties
depth— Total depth of the expression treeoperationCount— Total number of operationsvariableCount— Number of unique variablesconstantCount— Number of constantsoperationTypes— Distribution of operation typescomputationalCost— Estimated computational cost (arbitrary units)memoryUsage— Memory usage estimate (arbitrary units)
DEFAULT_MIN_COMPLEXITY
constant · canonical name default_min_complexity
const DEFAULT_MIN_COMPLEXITY: 5
Default minimum analyzeComplexity
cost a subexpression must reach to
be considered for factoring. Shared by every entry point below.
DependencyGraph
type · canonical name dependency_graph
interface DependencyGraph extends Graph<DependencyNode, DependencyRelation> {
hasCircularDependencies(): boolean;
getCycles(): DependencyNode[][];
getStronglyConnectedComponents(): DependencyNode[][];
topologicalSort(): DependencyNode[];
}
Graph representing variable dependencies
Properties
hasCircularDependencies— Check for circular dependenciesgetCycles— Circular-dependency cycles. Each entry is one back-edge cycle found by a DFS over the directed edges; distinct cycles may share nodes (these are NOT strongly-connected components).getStronglyConnectedComponents— Deprecated. Misnomer — this does NOT compute strongly-connected components; it returns the raw DFS cycles fromgetCycles. UsegetCyclesinstead.topologicalSort— Topological sort of dependencies
DependencyNode
type · canonical name dependency_node
interface DependencyNode {
name: string;
kind: VariableKind;
system: string;
units?: string;
definition?: Expr;
depth: number;
}
Node representing a variable in a dependency graph.
Overlaps graph.ts’s VariableNode
(both carry name/kind/units/
system); this analysis variant additionally tracks the defining expression
(definition) and the topological depth. The two families are
kept separate because they are produced by different builders
(analysis/buildDependencyGraph vs graph.ts’s expressionGraph) with
different edge payloads; the shared kind vocabulary is unified via
VariableKind
.
Properties
name— Variable namekind— DERIVED variable category (state, algebraic, observed, parameter, brownian, discrete, species) — seeVariableKind.system— System/model this variable belongs tounits— Units if specifieddefinition— Definition expression if availabledepth— Nesting level in the dependency graph
DependencyRelation
type · canonical name dependency_relation
interface DependencyRelation {
source: string;
target: string;
type: 'direct' | 'circular' | 'parameter_dependency' | 'definition_dependency';
expression?: Expr;
}
Edge representing a dependency relationship between variables.
Analysis-local counterpart of graph.ts’s DependencyEdge
; the two use
disjoint edge vocabularies (type here vs relationship/equation_index
there) because they are built by different graph constructors.
Properties
source— Source variabletarget— Target variabletype— Type of dependencyexpression— Expression that creates this dependency
DerivativeResult
type · canonical name derivative_result
interface DerivativeResult {
derivative: Expr;
variable: string;
simplified?: Expr;
derivativeSteps?: Array<{
expression: Expr;
derivative: Expr;
}>;
}
Result of symbolic differentiation
Properties
derivative— The derivative expressionvariable— Variable with respect to which we differentiatedsimplified— Simplified form if different from derivativederivativeSteps— ForhigherOrderDerivative: one entry per differentiation order, recording the expression at that order (expression) and its derivative (derivative, i.e. the expression at the next order). These are the successive derivative steps, NOT chain-rule multiplicative factors.
detectStabilityIssues
function · canonical name detect_stability_issues
function detectStabilityIssues(expr: Expr): StabilityIssue[]
Detect numerical stability issues in expressions
Parameters
expr— Expression to analyze
Returns
Array of potential stability issues
differentiate
function · canonical name differentiate
function differentiate(expr: Expr, variable: string): DerivativeResult
Compute the symbolic derivative of an expression with respect to a variable
Parameters
expr— Expression to differentiatevariable— Variable with respect to which to differentiate
Returns
Derivative result with simplified form
dispatchClosedFunction
function · canonical name dispatch_closed_function
function dispatchClosedFunction(name: string, args: unknown[]): number
Resolve a closed-function name + already-evaluated positional args into a
scalar result via CLOSED_FUNCTION_DISPATCH. Unknown names raise
unknown_closed_function.
E_CANONICAL_DIVBY_ZERO
constant · canonical name e_canonical_divby_zero
const E_CANONICAL_DIVBY_ZERO: "E_CANONICAL_DIVBY_ZERO"
E_CANONICAL_DIVBY_ZERO — /(0, 0) (§5.4.7).
E_CANONICAL_NONFINITE
constant · canonical name e_canonical_nonfinite
const E_CANONICAL_NONFINITE: "E_CANONICAL_NONFINITE"
E_CANONICAL_NONFINITE — NaN or ±Inf (§5.4.6).
ErrorCode
type · canonical name error_code
type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
A diagnostic code string from ERROR_CODES
.
EsmDiagnosticError
error · canonical name esm_diagnostic_error
class EsmDiagnosticError extends Error
new EsmDiagnosticError(code: string, message: string, details?: Record<string, unknown>): EsmDiagnosticError
Neutral base for EarthSciAST diagnostics: an Error carrying a stable code
string (from ERROR_CODES
) and optional structured details. The
package’s error classes extend it — EsmMachineryError, EnumLoweringError,
ClosedFunctionError, FlattenError, UnitConversionError and the rest —
so one instanceof EsmDiagnosticError check catches them, and code names
the specific diagnostic.
One exception: the operator registry’s arity and domain checks (an operator
given the wrong number of arguments, log of a non-positive value, division
by zero) throw a plain Error with no code.
EsmMachineryError
error · canonical name esm_machinery_error
class EsmMachineryError extends EsmDiagnosticError
new EsmMachineryError(code: string, message: string): EsmMachineryError
Shared load-time diagnostic for the §9.x machinery: expression-template
lowering (§9.6), template-library imports (§9.7), coupling-library imports
(§10.10), subsystem-ref loading, and the §9.6.4 expanded-form validators all
raise it as their common coded-diagnostic class — validate maps it (by
instanceof) to the expression_template_error load-error kind. A subclass
of EsmDiagnosticError
: code is the specific diagnostic and the
message text is [code] message.
estimateParallelPotential
function · canonical name estimate_parallel_potential
function estimateParallelPotential(expr: Expr): number
Estimate parallel execution potential
Parameters
expr— Expression to analyze
Returns
Parallelization score (0-1, higher means more parallelizable)
estimateSavings
function · canonical name estimate_savings
function estimateSavings(commonSubexpressions: CommonSubexpression[]): number
Estimate the cost savings from factoring out common subexpressions
Parameters
commonSubexpressions— Array of common subexpressions
Returns
Total estimated cost savings
evaluateExpression
function · canonical name evaluate_expression
function evaluateExpression(expr: Expr, bindings: Map<string, number>, options?: EvaluateOptions): number
Compile and apply in one step. Equivalent to
compileExpression(expr)(bindings) but avoids allocating a closure
for one-shot callers (simplify’s constant-folding path,
fixed-point observed-variable resolution, unit-conversion
folding).
EvaluatorError
error · canonical name evaluator_error
class EvaluatorError extends EsmDiagnosticError
new EvaluatorError(code: string, message: string): EvaluatorError
Error raised by the tree-walking evaluator for a node it cannot reduce to a
scalar: an unbound variable, an unsupported operator, an unlowered enum, a
non-scalar const, a malformed fn, or a non-expression value. Carries a
stable code field so callers can branch programmatically instead of
regex-matching prose.
Unlike UnloweredOperatorError
, the message is passed through
VERBATIM (not [code]-prefixed): several of these strings are matched
byte-for-byte by the cross-binding runner tests, so the wording is pinned.
These code values are binding-local diagnostics for the in-process runner,
distinct from the cross-language conformance codes in errors.ts.
Expand
type · canonical name expand
function Expand<T extends object>(loaded: T): T
Public alias for expandDocument
using the spec’s spelling (§9.6.4 rule 2).
Fully expand every surviving apply_expression_template reference in a
document loaded by lowerExpressionTemplates
(Option B), producing
the Option-A image: every reference replaced by its expansion (pure
substitution to the acyclic fixpoint, §9.6.4 rule 2) and every per-component
expression_templates block stripped. Deterministic — the §9.7.3 DAG is
acyclic and substitution confluent, so expandDocument(load(f)) is
structurally equal to the pre-0.9.0 expanded form (the expanded*.esm
conformance oracle). Non-destructive: loaded is deep-cloned first. Mirrors
the Julia reference expand_document / Expand.
expressionCadence
function · canonical name expression_cadence
function expressionCadence(model: Model, expr: Expression, esmFile?: EsmFile): CadenceClass
The cadence of an expression in a model: max over its leaves.
ExpressionLocation
type · canonical name expression_location
interface ExpressionLocation {
path: string[];
description: string;
context?: Expr;
}
Location of an expression within a larger structure
Properties
path— Path to the expression (e.g.['root', 'args[0]', 'args[1]'])description— Human-readable descriptioncontext— Parent expression context
FieldInitialCondition
type · canonical name field_initial_condition
interface FieldInitialCondition {
state: string;
expr: Expression;
}
A deferred ic equation (esm-spec §11.4.1): an initial condition, not dynamics.
Properties
state— The namespaced state the condition pins.expr— The value at t=0.
findCommonSubexpressions
function · canonical name find_common_subexpressions
function findCommonSubexpressions(expr: Expr, minComplexity?: number): CommonSubexpression[]
Find common subexpressions in a single expression
Parameters
expr— Expression to analyzeminComplexity— Minimum complexity threshold for considering subexpressions
Returns
Array of common subexpressions found
findCommonSubexpressionsAcrossExpressions
function · canonical name find_common_subexpressions_across_expressions
function findCommonSubexpressionsAcrossExpressions(expressions: Array<{ expr: Expr; name: string }>, minComplexity?: number): CommonSubexpression[]
Find common subexpressions across multiple expressions
Parameters
expressions— Array of expressions to analyzeminComplexity— Minimum complexity threshold
Returns
Array of common subexpressions found across expressions
findCommonSubexpressionsInEsmFile
function · canonical name find_common_subexpressions_in_esm_file
function findCommonSubexpressionsInEsmFile(esmFile: EsmFile, minComplexity?: number): CommonSubexpression[]
Find common subexpressions across an entire ESM file. All models’ and reaction systems’ raw expressions are aggregated into ONE analysis pass so occurrence counts and locations reflect actual appearances — including duplicates local to a single model and duplicates spanning components.
Parameters
esmFile— ESM file to analyzeminComplexity— Minimum complexity threshold
Returns
Array of common subexpressions found across the file
findCommonSubexpressionsInModel
function · canonical name find_common_subexpressions_in_model
function findCommonSubexpressionsInModel(model: Model, minComplexity?: number): CommonSubexpression[]
Find common subexpressions in a model (including its subsystems). All of the model’s expressions are analyzed in a single pass so duplicates that span the parent and a subsystem are counted together.
Parameters
model— Model to analyzeminComplexity— Minimum complexity threshold
Returns
Array of common subexpressions found in the model
findCriticalPoints
function · canonical name find_critical_points
function findCriticalPoints(expr: Expr, variable: string): { derivative: Expr; simplified?: Expr; hasConstantDerivative: boolean; isConstantZero: boolean }
Find critical points (where derivative equals zero) This is a symbolic analysis - actual solving would require numerical methods
Parameters
expr— Expression to analyzevariable— Variable to find critical points for
Returns
Information about potential critical points
findDeadVariables
function · canonical name find_dead_variables
function findDeadVariables(graph: DependencyGraph): DependencyNode[]
Find dependency-graph sinks: non-state variables that nothing else depends on. Note this includes terminal observed outputs — a sink is only truly “dead” if it is also not consumed outside the model (plots, couplings, downstream tooling), which this graph cannot see. State variables are excluded because they are integration outputs by definition.
findDependencyChains
function · canonical name find_dependency_chains
function findDependencyChains(graph: DependencyGraph, startNode: string, maxDepth?: number): string[][]
Enumerate every path from startNode to a sink (a node with no successors),
following successor edges. Paths that revisit a node or exceed maxDepth
hops are pruned.
findExpensiveSubexpressions
function · canonical name find_expensive_subexpressions
function findExpensiveSubexpressions(expr: Expr, limit?: number): Array<{ expression: Expr; cost: number; path: string[] }>
Find the most expensive sub-expressions in an expression
Parameters
expr— Expression to analyzelimit— Maximum number of results to return
Returns
Array of expensive sub-expressions with their costs
FlattenedTemplateRegistries
type · canonical name flattened_template_registries
interface FlattenedTemplateRegistries {
root: Record<string, unknown>;
merged: Record<string, unknown>;
}
Result of flattenTemplateRegistries
: the rewritten document + merged registry.
FlattenedVariableMap
type · canonical name flattened_variable_map
type FlattenedVariableMap = Record<string, FlattenedVariable>;
An insertion-ORDERED map from namespaced name to variable. Order is part of the cross-binding contract (see the module doc); JavaScript preserves the insertion order of string keys that do not look like array indices, which a dot-namespaced variable name never does.
FlattenedVariableRole
type · canonical name flattened_variable_role
type FlattenedVariableRole = 'state' | 'parameter' | 'observed' | 'species';
The DERIVED role of a flattened variable (esm-spec §6.3.1) — never a declared
type, which from 1.0.0 is only unknown or parameter.
state— solved for and defined by no equation of its own: an ODE state or an algebraic unknown.observed— an unknown an equation DEFINES, at either LHS spelling. A scalar one is eliminable by inlining and appears inobservedVariablesalone; an arrayed one materializes into a buffer and appears instateVariablestoo, keeping this role in both (esm-libraries-spec §4.7.5 step 4:stateVariablesis the solved-for vector, not a classification).parameter— a parameter of any cadence.species— a reaction-system state (astatethat came from a species).
FlattenOptions
type · canonical name flatten_options
type FlattenOptions = CouplingImportOptions;
Options for flatten
. Only needed when the file uses coupling_import.
formatChemicalName
function · canonical name format_chemical_name
function formatChemicalName(name: string): string
Apply element-aware chemical subscript formatting to a bare variable / species name using Unicode subscript digits (e.g. “H2SO4” → “H₂SO₄”). Exported for graph rendering (toDot / toMermaid labels).
generateFactoredVariableNames
function · canonical name generate_factored_variable_names
function generateFactoredVariableNames(commonSubexpressions: CommonSubexpression[], prefix?: string): Map<CommonSubexpression, string>
Generate variable names for factored subexpressions.
Keyed by the CommonSubexpression
object itself so callers can look up
a generated name directly from the array element (the previous private
string key could not be reconstructed by callers).
Parameters
commonSubexpressions— Array of common subexpressionsprefix— Prefix for generated variable names
Returns
Map from each common subexpression to its generated variable name
gradient
function · canonical name gradient
function gradient(expr: Expr, variables?: string[]): DerivativeResult[]
Compute the gradient (all first partial derivatives)
Parameters
expr— Expression to differentiatevariables— Array of variables (if not provided, will extract from expression)
Returns
Gradient as array of derivatives
groupSubexpressionsByType
function · canonical name group_subexpressions_by_type
function groupSubexpressionsByType(commonSubexpressions: CommonSubexpression[]): Record<string, CommonSubexpression[]>
Group common subexpressions by their structure type
Parameters
commonSubexpressions— Array of common subexpressions
Returns
Grouped subexpressions by operation type
higherOrderDerivative
function · canonical name higher_order_derivative
function higherOrderDerivative(expr: Expr, variable: string, order?: number): DerivativeResult
Compute higher-order derivatives
Parameters
expr— Expression to differentiatevariable— Variable with respect to which to differentiateorder— Order of derivative (default: 1)
Returns
Higher-order derivative result
interpBilinear
function · canonical name interp_bilinear
function interpBilinear(table: readonly (readonly number[])[], axisX: readonly number[], axisY: readonly number[], x: number, y: number): number
2-D bilinear interpolation with per-axis extrapolate-flat clamps.
Pinned evaluation order: two x-blends followed by one y-blend, each
in the form a + w*(b - a) (esm-spec §9.2). table is row-major:
table[i][j] is the value at (axis_x[i], axis_y[j]).
interpLinear
function · canonical name interp_linear
function interpLinear(table: readonly number[], axis: readonly number[], x: number): number
1-D linear interpolation with extrapolate-flat clamps. Pinned form
result = t[i] + w * (t[i+1] - t[i]) so that w=0/1 reproduce the
endpoint exactly under IEEE-754 round-to-nearest.
Validates axis on every call (cheap relative to dispatch overhead;
matches the searchsortedFirst convention in this module).
InvalidDerivativeOrderError
error · canonical name invalid_derivative_order_error
class InvalidDerivativeOrderError extends EsmDiagnosticError
new InvalidDerivativeOrderError(order: number): InvalidDerivativeOrderError
Thrown by higherOrderDerivative
when order is not positive.
isDifferentiable
function · canonical name is_differentiable
function isDifferentiable(expr: Expr, variable: string): boolean
Check if an expression is differentiable with respect to a variable
Parameters
expr— Expression to checkvariable— Variable to check differentiability with respect to
Returns
True if differentiable, false otherwise
joinAll
function · canonical name join_all
function joinAll(classes: Iterable<CadenceClass>): CadenceClass
The join of any number of cadence classes; const when there are none.
joinCadence
function · canonical name join_cadence
function joinCadence(a: CadenceClass, b: CadenceClass): CadenceClass
The join (max) of two cadence classes.
leafCadence
function · canonical name leaf_cadence
function leafCadence(model: Model, name: string, esmFile?: EsmFile): CadenceClass
The cadence seed of one leaf NAME in a model.
ModelClassification
type · canonical name model_classification
interface ModelClassification {
odeStates: string[];
observedUnknowns: string[];
algebraicUnknowns: string[];
brownianParameters: string[];
discreteParameters: string[];
sampledParameters: string[];
constantParameters: string[];
systemKind: SystemKind;
declaredSystemKind: SystemKind | null;
}
Every derived set for one model node, as the conformance goldens spell it.
NonDifferentiableExpressionError
error · canonical name non_differentiable_expression_error
class NonDifferentiableExpressionError extends EsmDiagnosticError
new NonDifferentiableExpressionError(op: string, variable: string): NonDifferentiableExpressionError
Thrown when differentiate
encounters an operator with no
differentiation rule, or a known operator applied with an arity its rule
does not cover. Callers that need a boolean answer should use
isDifferentiable
.
ParameterClass
type · canonical name parameter_class
type ParameterClass = 'brownian' | 'discrete' | 'sampled' | 'constant';
The four derived parameter categories (esm-spec §6.3.1).
parameterClass
function · canonical name parameter_class
function parameterClass(variable: ModelVariable): ParameterClass
The derived class of ONE parameter. Exported because the cadence pass seeds its leaves from this rather than re-deriving the categories locally (CONFORMANCE_SPEC §5.7.2).
ParsedUnit
type · canonical name parsed_unit
interface ParsedUnit {
dims: CanonicalDims;
scale: number;
offset?: number;
exact: ExactScale;
}
Properties
exact— The scale every agreement is decided on (esm-spec §4.8.1).
parseReaction
function · canonical name parse_reaction
function parseReaction(src: string): Reaction
Parse a single reaction from its text-DSL form. Throws
ExpressionParseError
on any malformed input (the editor surfaces the
message and blocks the edit). The returned reaction’s id is empty — the
caller assigns identity when merging into an existing reaction.
parseUnitForConversion
function · canonical name parse_unit_for_conversion
function parseUnitForConversion(unitStr: string): ParsedUnit
Parse a unit string into canonical SI dimensions plus scale (and optional offset).
Recursive-descent parser over the grammar of the Go reference implementation
(pkg/earthsci-ast-go/pkg/esm/units.go), so the bindings agree on how a unit
string associates:
unit := term ( ('*' | '/')? term )*
term := atom ( ('^' | '**') exponent )?
exponent := integer | decimal | '(' integer '/' integer ')'
atom := '1' | symbol | '(' unit ')'
EXPONENTS ARE RATIONAL, not integral: 1/s^0.5 (an SDE noise intensity) and
m^(1/2) are legitimate corpus units, and a dimension vector may therefore
carry fractional entries.
* and / share one precedence level and associate LEFT — so kg/m*s is
(kg/m)*s = kg·s·m⁻¹, NOT kg·m⁻¹·s⁻¹, and a/b/c is a/(b*c). Grouping with
parentheses is supported, so the ordinary earth-science spellings J/(mol*K)
and cm^3/(molec*s) parse.
WHITESPACE BETWEEN TWO TERMS IS MULTIPLICATION — the SI style kg m^2 s^-2
and the corpus’s ppb^-1 s^-1. The scanner is greedy over identifier
characters, so ms stays ONE symbol (millisecond); juxtaposition can only
arise across a real token boundary. ** is accepted as a synonym for ^ (the
Python/pint spelling, e.g. the corpus’s Pa*m**3).
The empty string, "1" and "dimensionless" are the dimensionless unit.
Non-ASCII spellings (μg, °C) are normalized first — see
normalizeUnitString.
Throws
UnitConversionError— on unknown unit names, malformed tokens, unbalanced parentheses, or trailing input.
partialDerivatives
function · canonical name partial_derivatives
function partialDerivatives(expr: Expr, variables: string[]): Map<string, DerivativeResult>
Compute partial derivatives with respect to multiple variables
Parameters
expr— Expression to differentiatevariables— Array of variables to differentiate with respect to
Returns
Map of variable names to their derivative results
RefLoadError
error · canonical name ref_load_error
class RefLoadError extends EsmDiagnosticError
new RefLoadError(ref: string, cause?: Error, code?: string, message?: string, path?: string): RefLoadError
readonly RefLoadError.prototype.ref: string
readonly RefLoadError.prototype.code: string
readonly RefLoadError.prototype.path: string
Error thrown when a referenced file cannot be loaded, parsed, or uniquely resolved to one system.
Carries the CANONICAL cross-binding diagnostic code (see ERROR_CODES):
unresolved_subsystem_ref(default) — the file does not exist, or could not be read or parsed.ambiguous_subsystem_ref— the file WAS read, and holds more than one top-level system; §4.7 requires exactly one.
The resolver is the only layer that reads the referenced file, so it is the
only layer that can tell those two apart — the synchronous validate() does
no I/O and reports every unresolved {ref} as unresolved_subsystem_ref.
Members
ref— The reference path or URL that failed to loadcode— Canonical code:unresolved_subsystem_ref,ambiguous_subsystem_ref, ormount_form_unsupportedfor a mount form this binding does not implement.path— JSON Pointer of the SUBSYSTEM ENTRY that carries the bad ref (e.g./models/ClimateModel/subsystems/Atm) — not the document root. The corpus pins these errors at the offending mount, and a caller handed$has to go hunting for which of a dozen mounts failed.
searchsortedFirst
function · canonical name searchsorted_first
function searchsortedFirst(x: number, xs: readonly number[]): number
Smallest 1-based i with xs[i] ≥ x (Julia searchsortedfirst
semantics). NaN x → N+1. xs MUST be pre-validated; the table is
inspected at every call so the caller can pass a fresh array each
scenario without bookkeeping (validation is cheap relative to the
dispatch overhead).
StabilityIssue
type · canonical name stability_issue
interface StabilityIssue {
issue: string;
severity: 'low' | 'medium' | 'high';
path: string[];
suggestion: string;
}
A single numerical-stability finding produced by detectStabilityIssues.
Properties
issue— Human-readable description of the issueseverity— Severity of the issuepath— Path to the offending subexpression (e.g.['args[1]'])suggestion— Suggested remediation
TemplateResolveOptions
type · canonical name template_resolve_options
interface TemplateResolveOptions {
metaparameters?: Record<string, number> | undefined;
readFile?: ((path: string) => string) | undefined;
validateSchema?: ((raw: unknown) => TemplateSchemaError[]) | undefined;
mountDeclared?: ReadonlySet<string> | undefined;
mountedLeaf?: boolean | undefined;
}
Options threaded through §9.7 resolution.
Properties
metaparameters— Loader-API metaparameter bindings for the ROOT document (esm-spec §9.7.6 binding site 4). Already-closed edge bindings win; API bindings beatdefaults.readFile— Synchronous file reader for import refs. Defaults to Node’sfs.readFileSync(viaprocess.getBuiltinModule); browser hosts must supply their own.validateSchema— Schema validator applied to each import target (a target failing schema validation istemplate_import_unresolved, mirroring the Julia reference). Supplied by theload*entry points; optional for direct/raw use.mountDeclared— Metaparameter names declared by the documents this one MOUNTS (esm-spec §4.7, either mount form, transitively) — seecollectMountDeclaredMetaparameters. Widens the §9.7.6 site-4 check: a loader-API binding naming one of these is meaningful even though THIS document does not declare it, because the mount edge forwards it into the leaf’s own close.mountedLeaf— This call IS a §4.7 mount edge, so index-set sizes this scope cannot close stay symbolic for the MOUNTING document’s registry to close (§9.7.6 site 5) instead of beingmetaparameter_unboundhere. A root document leaves it unset.
TemplateSchemaError
type · canonical name template_schema_error
interface TemplateSchemaError {
path: string;
message: string;
}
Schema-error shape accepted from the host’s schema validator.
ToJsonOptions
type · canonical name to_json_options
interface ToJsonOptions {
canonical?: boolean;
indent?: number;
}
Optional behavior controls for toJson
/ writePath
.
Properties
canonical— Whentrue, emit byte-canonical JSON per RFC §5.4.6: integer-taggedNumericLiteralleaves as integer tokens, float-tagged leaves with the trailing.0discriminator preserved (e.g.1.0stays1.0rather than collapsing to1). Plain JSnumbervalues keepJSON.stringifysemantics in either mode.Default:
false(structural round-trip; integer-valued floats may collapse to JSON integers).indent— Indentation passed through to the underlying JSON formatter. Default2to match the Python and Julia reference serializers. Set to0for a single-line emission.
toMathML
function · canonical name to_math_ml
function toMathML(expr: Expr | Equation | Model | ReactionSystem | Reaction | EsmFile): string
Format an expression as MathML markup for web/academic publishing
tryParseUnit
function · canonical name try_parse_unit
function tryParseUnit(unitStr: string): ParsedUnit | null
Parse a unit string into canonical SI dimensions plus scale factor, or return
null when the string cannot be parsed.
This is the fallible companion to parseUnit
: instead of swallowing a
parse failure into a dimensionless fallback, it surfaces the failure as
null. Callers can then leave the variable’s dimension UNKNOWN (unbound) and
emit a warning, rather than silently manufacturing a dimensionless binding
that HIDES real dimensional mismatches — or MANUFACTURES false ones
(esm-libraries-spec §3.3.3/§3.4, matching the Julia reference). A
UnitConversionError (unknown unit name, malformed token, misused offset
unit) maps to null; any other error is rethrown.
"degree" / "degrees" are resolved by the canonical table as long-form
aliases of deg (esm-spec §4.8.1), i.e. as the ANGLE axis scaled by π/180 —
the reading the Rust, Julia and Python tables carry too.
UnevaluableOperatorError
error · canonical name unevaluable_operator_error
class UnevaluableOperatorError extends EsmDiagnosticError
new UnevaluableOperatorError(op: string, remedy?: string): UnevaluableOperatorError
readonly UnevaluableOperatorError.prototype.op: string
Error carrying the stable, cross-binding unevaluable_operator diagnostic
(esm-spec §9.6.6): an op that IS in the §4.2 evaluable-core set but that this
scalar evaluator has no rule for. The complement of
UnloweredOperatorError
, which is for an op OUTSIDE the core, so it
carries no rewrite-rule advice: the op needs an earlier pipeline stage (value
invention, or a load-time lowering pass), not a rewrite rule.
Members
op— The offending operator name.
UnitResult
type · canonical name unit_result
interface UnitResult {
dimensions: ParsedUnit | null;
warnings: string[];
diagnostics: UnitDiagnostic[];
}
Result of dimensional analysis for a single expression.
Properties
dimensions— The expression’s canonical dimension, ornullwhen it is INDETERMINATE.nullis not “dimensionless” — it is “this analysis cannot say”, and it is the value returned for an unknown variable, an unparseable unit declaration, and any operator whose dimensional semantics this module does not model (fn,table_lookup, an faq underreduce: "*"with a dimensional body, …). Keeping the two apart is what stops a structural op from being assumed dimensionless and thereby manufacturing a false mismatch against a dimensional operand.nullpropagates through every combining rule, and a comparison againstnullis never a mismatch — it is simply skipped, which mirrors the Go reference (PropagateDimensionreturnsnil, nil).warnings— Message-only view, for the publiccheckDimensionsAPI and callers that inspect warning prose.diagnostics— Structured view ofwarnings: each message with its explicit classification.validateUnitsuses these codes (not a prose regex) to decide which warningsvalidate()promotes to errors.
unitsCompatible
function · canonical name units_compatible
function unitsCompatible(a: string, b: string): boolean
Report whether two unit strings represent compatible (same-dimension) quantities.
A non-throwing companion to convertUnits.
UnknownClass
type · canonical name unknown_class
type UnknownClass = 'ode_state' | 'observed' | 'algebraic';
The three derived unknown categories (esm-spec §6.3.1).
UnloweredOperatorError
error · canonical name unlowered_operator_error
class UnloweredOperatorError extends EsmDiagnosticError
new UnloweredOperatorError(message: string): UnloweredOperatorError
Error carrying the stable, cross-binding unlowered_operator diagnostic
(esm-spec §4.2 / §9.6.3 constraint 6 / §9.6.8). Raised when a rewrite-target
op reaches evaluation/compilation without having been lowered — one uniform
gate, the same in every binding. Loading stays permissive (the op namespace
is open); the gate fires only at evaluation, as in the Julia reference.
updateRules
function · canonical name update_rules
function updateRules(spec: ParameterUpdateSpec | undefined): ParameterUpdate[]
The update rules of a parameter, normalized to an array (possibly empty).
validateInterpAxis
function · canonical name validate_interp_axis
function validateInterpAxis(axis: readonly number[], where: string): void
Validate a 1-D interpolation axis (interp.linear / interp.bilinear).
Strictly increasing, no NaN, length ≥ 2. Diagnostic codes match
esm-spec §9.2 “Errors (load time)” table.
validateSearchsortedTable
function · canonical name validate_searchsorted_table
function validateSearchsortedTable(xs: readonly number[], where?: string): void
Validate a searchsorted xs table. Throws on NaN entries or
non-monotonic order. Empty arrays are rejected with the spec arity
code (the registry requires N ≥ 1).