Terms and equations
Refitting a set of terms on one dataset, checking that a term is well formed, and deciding whether two equations state the same law are the three jobs here. The term syntax is described under Equation representation, and what the numbers mean under Score conventions and comparability.
| Name | Summary |
|---|---|
kd.evaluate_terms(dataset, terms[, ...]) |
Evaluate candidate terms against a dataset, fail-loud. |
kd.validate_terms(dataset, terms[, ...]) |
Classify each term as valid / rejected WITHOUT fitting. |
kd.verify_equation(eq, executor[, ...]) |
Verify an equation on a dataset using its reported coefficients unchanged. |
kd.law_signature(eq) |
Build a versioned signature from an equation's active law. |
kd.Sketch(lhs_spec, vocabulary[, ...]) |
A versioned evolution-law template with pinned, anchored, and hole clauses. |
kd.EvaluationResult(mse, nmse[, ...]) |
Result from evaluating an expression or term list. |
kd.TermValidationReport(results, valid[, ...]) |
Structured result of validate_terms (JSON-dumpable, no fitting). |
kd.TermRejection(term, reason) |
A single rejected term and the reason it was rejected. |
kd.VerificationReport(signature, form[, ...]) |
JSON-serializable measurements for one equation on one dataset. |
kd.VerifyPolicy(nmse_max, coeff_atol[, ...]) |
Thresholds used when reporting and comparing empirical verification. |
kd.InvalidTermsError(rejected) |
Raised when one or more terms are rejected and cannot be fitted. |
kd.EvaluationFailedError |
Raised when the final fit is invalid (solver failure / non-finite MSE). |
evaluate_terms
evaluate_terms(
dataset: PDEDataset,
terms: Sequence[str],
*,
skip_invalid: bool = False,
max_order: int = 2,
lhs_order: int | None = None,
) -> EvaluationResult
Evaluate candidate terms against a dataset, fail-loud.
Parameters:
-
dataset(PDEDataset) –The PDE dataset to evaluate against (never mutated).
-
terms(Sequence[str]) –Candidate term strings (canonical funcall IR).
-
skip_invalid(bool, default:False) –When
False(default, strict), ANY rejected term raisesInvalidTermsErrorcarrying every rejection and nothing is fitted. WhenTrue(lenient), rejected terms are dropped with exactly onelogger.warningand the survivors are fitted. -
max_order(int, default:2) –Maximum atomic derivative order (
-> max_atomic_order). -
lhs_order(int | None, default:None) –LHS derivative order targeted by the fit (
1->u_t,2->u_tt;-> DerivativeReqs.lhs_order). DefaultNoneDERIVES fromdataset.lhs_order(single source of truth).
Returns:
-
EvaluationResult–An
EvaluationResultwithis_valid is True(honest metrics). -
EvaluationResult–This entry always measures
condition_number(candidate-library -
EvaluationResult–collinearity). The measured matrix is the one the solver was handed:
-
EvaluationResult–under
skip_invalid=Truethat is the SURVIVING columns, not every -
EvaluationResult–string in
terms— a term dropped asshape/all-zero/ -
EvaluationResult–tautologyis not in the number. Strict mode fits every submitted -
EvaluationResult–term or raises, so there the two coincide.
Raises:
-
ValueError–If
termsis empty. -
ValueError–Propagated from
PlatformBuilderwhen the resolved LHS field/axis is absent from the dataset, when the resolvedlhs_order > max_order(the LHS is read from the same precomputed derivative cache thatmax_orderbounds), or whenmax_order > 3(provider cap). -
InvalidTermsError–If terms are rejected (see
skip_invalid). -
EvaluationFailedError–If the final fit is invalid (the penalty sentinel is never returned).
validate_terms
validate_terms(
dataset: PDEDataset,
terms: Sequence[str],
*,
max_order: int = 2,
lhs_order: int | None = None,
) -> TermValidationReport
Classify each term as valid / rejected WITHOUT fitting.
Parameters:
-
dataset(PDEDataset) –The PDE dataset to evaluate against (never mutated).
-
terms(Sequence[str]) –Candidate term strings (canonical funcall IR).
-
max_order(int, default:2) –Maximum atomic derivative order made resolvable (
-> DerivativeReqs.max_atomic_order). Gates terminal tokens such asu_xx; open-formdiff*_xcalls are not gated. -
lhs_order(int | None, default:None) –LHS derivative order the tautology guard compares against (
1->u_t,2->u_tt). DefaultNoneDERIVES the order fromdataset.lhs_order(the single source of truth).
Returns:
-
TermValidationReport–A
TermValidationReportpartitioning the terms into valid / rejected, JSON-dumpable viato_dict().
Raises:
-
ValueError–If
termsis empty. -
ValueError–Propagated from
PlatformBuilderwhen the resolved LHS field/axis is absent from the dataset, when the resolvedlhs_order > max_order(the LHS is read from the same precomputed derivative cache thatmax_orderbounds), or whenmax_order > 3(provider cap).
verify_equation
verify_equation(
eq: Equation,
*,
executor: PythonExecutor,
context: ExecutionContext,
policy: VerifyPolicy = VerifyPolicy(),
) -> VerificationReport
Verify an equation on a dataset using its reported coefficients unchanged.
law_signature
law_signature(eq: Equation) -> LawSignature
Build a versioned signature from an equation's active law.
Sketch
dataclass
A versioned evolution-law template with pinned, anchored, and hole clauses.
matches
matches(eq: Equation) -> SketchVerdict
Match an EVOLUTION law using the policy's exact coefficient band.
EvaluationResult
dataclass
Result from evaluating an expression or term list.
Attributes:
-
mse(float) –Mean squared error between prediction and target.
-
nmse(float) –Normalized MSE (MSE / variance of target).
-
r2(float) –R-squared (coefficient of determination).
-
score(float | None) –Score from the configured scorer (if computed).
-
complexity(int) –Number of active terms for AIC. Selected count for sparse solvers, total for dense.
-
coefficients(Tensor | None) –Fitted coefficients (one per term).
-
is_valid(bool) –Whether evaluation succeeded.
-
error_message(str) –Error description if is_valid is False.
-
invalid_reason(str | None) –Schema-owned invalid category supplied by the producer;
Nonefor valid or legacy results. -
selected_indices(list[int] | None) –Indices of terms selected by sparse solver (None for dense solvers). Relative to
terms. -
residuals(Tensor | None) –Detached residual tensor (predicted - actual), shape
(n_samples,). Sign convention: positive means over-prediction. -
terms(list[str] | None) –Term strings used for evaluation (defensive copy).
-
expression(str) –Original expression string, set only by
evaluate_expression(). -
lhs_name(str | None) –Optional plugin-reported LHS label for result assembly.
-
condition_number(float | None) –Condition number of the FULL candidate term library Theta (all submitted columns, float64 upcast, exactly the matrix handed to the solver) — computed BEFORE any sparse selection or column normalization.
-
form(Form) –Transient equation-form dispatch signal for result assembly.
to_dict
to_dict(
*, include_residuals: bool = True
) -> dict[str, Any]
Return a JSON-safe dict of this result (single serialization source).
Parameters:
-
include_residuals(bool, default:True) –When
False, the"residuals"key is kept (schema-stable) but its value isNone— for MCP-boundary use where a 50k-float list is unwanted. All other keys are identical to theinclude_residuals=Trueoutput.
Returns:
-
dict[str, Any]–A
json.dumps-safe dictionary.
TermValidationReport
dataclass
Structured result of validate_terms (JSON-dumpable, no fitting).
Attributes:
-
results(list[TermValidation]) –Per-term validation outcomes in input order.
-
valid(list[str]) –Term strings that passed validation, in input order.
-
rejected(list[TermRejection]) –TermRejectionentries for the failed terms. -
ok(bool) –True iff every term passed (
rejectedis empty).
to_dict
to_dict() -> dict[str, Any]
Return a JSON-safe dict of the full report (MCP-boundary contract).
TermRejection
dataclass
A single rejected term and the reason it was rejected.
Attributes:
-
term(str) –The offending term string.
-
reason(str) –Human-readable rejection reason. Distinguishable across the rejection categories; for execution errors it surfaces the original failure message (including the offending token/op name).
to_dict
to_dict() -> dict[str, str]
Return a JSON-safe dict of this rejection.
VerificationReport
dataclass
JSON-serializable measurements for one equation on one dataset.
to_dict
to_dict() -> dict[str, object]
Return a JSON-safe representation of this report.
VerifyPolicy
dataclass
Thresholds used when reporting and comparing empirical verification.
InvalidTermsError
Bases: ValueError
Raised when one or more terms are rejected and cannot be fitted.
Attributes:
-
rejected–Every rejected term with its classification.
EvaluationFailedError
Bases: RuntimeError
Raised when the final fit is invalid (solver failure / non-finite MSE).