Deductive verification of model properties
A calculation can depend on more than a formula: an optimum may need
concavity, or a local approximation may need continuous second derivatives.
Changing a component can invalidate those premises even when the new formula
still evaluates successfully. modello.contrib.verification attempts to
establish such properties from a model’s definitions, observations, and
assumptions, and records the evidence needed before a method runs.
Start with planning record checking.
That worked example builds a workload model from a familiar budget, explains
its calculus, and follows the same decision through assumptions, component
replacement, a failed smoothness claim, and exported evidence. It needs
undergraduate calculus and the ordinary modello installation. Plotting is
optional.
This page is a reference for readers applying that workflow to their own models. Start modelling introduces the underlying declarations.
Read an obligation in its context
An obligation is a mathematical claim to establish. The same record can
serve as a declaration’s property, a method’s precondition, or an
inference-rule premise. specifies attaches obligations without assuming
their truth. VerificationModel checks them at definition time; ordinary
Modello classes can be checked explicitly with a VerificationContext.
A context retains definitions, observations, and assumptions for one branch.
Operations such as observe, assume, and replace return new contexts.
A report interprets every claim under its coordinate domain and those premises:
strictly trueThe property is established under the recorded premises.
conditionally trueconditiongives a sufficient parameter condition. It need not be the only condition under which the property holds.strictly falseA checked refutation establishes that the stated property fails.
unresolvedThe attempt leaves an open obligation: for example, an unsupported operation, a missing proof, an exhausted attempt budget, or an inapplicable inference rule.
Assumption consistency is reported separately; contradictory premises cannot
establish a result. Numerical samples remain observations, rather than proofs
of global claims. A Method can run once the premises it consumes are
established. Its result retains the report that permitted execution;
VerificationError retains the context and report when execution is blocked.
Reference: contracts, domains, and proof limits
Use these rules when a replacement or proof attempt needs closer inspection. The API reference below lists the workflow objects and property functions.
Select inputs and read model fields
context.symbols and context.model both carry the declared model type,
including nested component types. Editors can complete their attributes and
type checkers can reject missing names. Use symbols to select scalar inputs
or whole components in an observation mapping, and to select a replacement:
>>> from examples.record_review import RationalReview, review_context
>>> context = review_context()
>>> observed = context.observe({context.symbols.candidate.review.response.minutes_per_record: 2})
>>> observed.model.candidate.review.response.minutes_per_record
2
>>> changed = context.replace(context.symbols.candidate.review.response, RationalReview)
>>> changed = changed.observe({changed.symbols.candidate.review.response.minutes_per_record: 2})
>>> changed.model.candidate.minutes_per_record
9
model is a read-only field namespace. Its scalar and vector expressions,
recurrence laws, and model-collection members use the context’s observations
and assumptions. It retains free parameters and held operations, without
selecting a solution or establishing proof obligations. Use run for a
computation guarded by those obligations, or family.values to inspect
possible results.
After replace, take references from the returned context’s symbols.
Selectors from another model problem are rejected. Reading model can
produce a constant, so select observations through symbols instead.
expression(subject, wrt=coordinate) remains useful when the coordinate must
stay symbolic despite an observation. Both arguments accept native references.
Constructor-style keyword observations and string paths remain accepted.
Name an investigation’s proof declarations
Use with_specification(factory) to name additional obligations and trusted
inference rules in an ordinary frozen dataclass. The factory receives the
context’s typed symbols tree. Dataclass fields and tuple positions become
the declarations’ names, preserving their concrete Python types:
>>> from dataclasses import dataclass
>>> from modello.contrib.verification import Obligation, positive
>>> @dataclass(frozen=True)
... class CheckingSpecification:
... positive_rate: Obligation
>>> named = context.with_specification(
... lambda symbols: CheckingSpecification(positive(symbols.candidate.review.response.detection_rate)))
>>> named.explain(named.specification.positive_rate).verdict
'strictly true'
>>> named.verify().explain(named.specification.positive_rate).id
'positive_rate'
specification is the typed catalog. obligations and rules are
read-only inventories of the context-level declarations, including any added
through with_obligations or with_rule. Obligations attached to model
fields through specifies remain part of the model and are also checked;
the context catalog names the investigation’s additional declarations.
specifies stays a declaration function rather than a second metadata tree.
The catalog is rebuilt on immutable context updates. Factories must use the
symbols they receive, so component replacement binds the declarations to the
new model. Shared obligations keep one canonical name, and inference-rule
conclusions and premises retain their references to those named declarations.
Premise names are checked for uniqueness when a rule is registered, after
catalog field names have been assigned.
Changing a named declaration uses with_specification; returning None
removes the catalog while retaining separately added goals and rules.
without_obligations still removes separately added exploratory goals.
explain accepts an obligation, a registered inference rule, or a report ID.
An obligation not already registered can be attempted without adding it to the
context. Explaining a rule attempts its conclusion. Reports accept these
objects too and retain the same string IDs for exported evidence.
with_bound_hint and without_obligations also accept obligation records.
The optional second type parameter records the catalog type:
VerificationContext[ReviewPlanning, ReviewSpecification]. The existing
VerificationContext[ReviewPlanning] form denotes a context without a
catalog. Python 3.11 and 3.12 use typing_extensions for this typing default.
Specifications, obligations, and inference rules
The terminology follows deductive verification, as used in the
Why3 specification and verification guide.
Here the verified subjects are mathematical expressions and their domains.
Method.execute is ordinary Python code whose implementation remains part
of the study’s trust boundary.
This is deductive verification of mathematical model properties. A
VerificationContext supplies the premises \(\Gamma\); an
Obligation states a proposition \(P\). The verifier attempts to
establish \(\Gamma\vdash P\) using supported scalar rules and explicitly
registered inference rules. It checks context consistency separately and
retains conditional, refuted, and unresolved results for exploration.
A specification states desired properties of a declaration.
specifiesattaches these properties to a field or model; their truth is determined by verification, rather than assumed from the annotation.An obligation is a named proposition to establish. The same
Obligationrecord represents a model property, a method precondition, or an inference-rule premise.A context supplies definitions, observations, and assumptions.
assumeadds premises;with_obligationsadds goals. A goal does not become an assumption.A precondition must be established before its method runs.
Method.preconditionsadds explicit preconditions to those consumed throughMethod.uses.An inference rule derives a conclusion when its premises are established.
InferenceRuleregisters such a trusted implication; the report retains evidence for its recursively checked premises.Evidence records a verification attempt, including a sufficient condition, counterexample, or open obligation. A
Sampleinstead records finite numerical observations.
The API names the activity verify, since an attempted check can leave an
obligation unresolved. VerificationModel automatically checks declarations;
its name does not assert that every declaration has been established.
expression, observe, replace, sample, explain, and run
retain their names because they describe distinct operations on the context.
Model and component contracts
Obligations use relative paths. Nested components acquire their parent path when inspected; replacing a component or redefining an inherited formula rebinds its obligations. The stored annotations describe claims, not old verdicts. Definition checking does not construct a model or select a solver candidate. Failed and unresolved obligations remain available for exploration.
Every property function accepts optional consumer, reason, and
source metadata. reason and source describe the claim’s purpose and
provenance. consumer can associate a claim with a method name or field path
for execution. Methods also consume the obligations declared on the fields
in Method.uses and their dependencies. These labels leave the mathematical
property being checked unchanged. The same Obligation works in
context.with_obligations(...), Method.preconditions, and InferenceRule.premises.
Constrained = specifies(Model, *obligations) returns a subclass carrying
additional model-wide conditions. For a VerificationModel subclass, it also
refreshes the definition report automatically. For an ordinary Modello
class, inspect the conditions with VerificationContext.for_model(Constrained).verify().
The original model and earlier contexts remain unchanged. These conditions follow
the model into nested components and are consumed by methods that read its fields.
Coordinate paths follow inheritance: a subclass that shadows a coordinate with
a regular attribute removes that path from the verification interface. Scalar
fields declared at the same path remain available as model quantities.
Native expressions in declaration annotations are rebound in their component’s scope. Paths are useful for contracts that should follow a named formula through replacement. Equivalent component coordinates are matched by their relative attribute paths; ambiguous joins of changed and unchanged coordinates require an explicit new declaration. Coordinate rebinding includes native derivative and reduction variables, even when they do not occur freely. Keep component field references in reusable native claims and hints: expanded expressions cannot identify which component owns a shared coordinate, so replacement rejects that ambiguity. Replacement cannot split previously aliased fields or coordinate paths into independent quantities within the same component. Start a new model and context to give them separate observations, argument scopes, and contracts. Named symbolic declarations, such as series and recurrence laws, follow the same path-based rebinding as fields in observations, claims, and hints. Recorded declaration paths and argument signatures must remain compatible; removing or changing that interface requires a new model and context. Local argument names in independent declarations can change independently. Coordinate paths also retain their argument role during replacement. Changing one into an observed or derived model field requires a new model and context; replacement rejects that change before it can alter an inherited derivative. Coordinates used by inherited calculations, observations, assumptions, claims, or hints must remain available through a compatible path or coordinate alias. Callable expected formulas are evaluated when a claim is checked. Resolve coordinates through their reference callback so the formula follows the current component interface. A callback that captures a coordinate from a changed interface, or a scalar symbol from an earlier context, must be rebuilt before it can establish a claim. Fresh local variables in native operations remain valid.
Replacement preserves explicit observations. Inferred values copied from an affected constructor snapshot are invalidated and listed in the report, so its equations can be solved again in either direction. Inferred values whose definitions depend on the replaced component are invalidated too. Unrelated constructor snapshots retain their inferred observations. An old calculated intensity therefore cannot constrain its replacement. Dependencies include named laws and composed series queries, even when they have no free scalar parameters. Methods also consume the component contracts reached through those declarations. Selecting one recurrence explicitly does not consume an alternative law merely because it targets the same series. Equivalent declarations with renamed local variables share their contracts; ambiguous series queries remain unresolved until a law is selected explicitly.
Independent coordinates with the same name receive distinct scoped labels in
exports, such as a.x and b.x. Deliberately shared coordinates retain one
identity even when reached through several component paths. Report printers
label the original symbolic tree without substituting or simplifying it, so
formatting cannot turn a difference of independent coordinates into zero.
Retire explicit assumptions and obligations
without_assumptions removes only explicitly recorded predicates, matching
their retained native scopes. Mathematically equal substitutions with different
coordinate domains remain separate assumptions. To change an intrinsic symbol
domain or an observation, change the declaration or branch before that
observation. without_obligations(*ids, reason=...) removes
obligations added with context.with_obligations and records their retirement
in the report. Declaration annotations and obligations from symbolic operations
are changed at their source. Retiring an exploratory obligation leaves a
method’s preconditions in place; run verifies them again. Identical
obligation records shared by a context and a method reuse one verification, while
conflicting uses of an ID remain definition errors.
The same policy applies to rule premises: identical obligations reuse one
verification, while conflicting conditions need distinct name values.
All evidence IDs, including nested inference-rule premise paths, must be unique
within a report; a collision is a definition error.
Coordinates and observation domains
Fully bound native values, including reductions, retain the model field’s
declared domain. Subs(log(x), x, 0) leaves no admissible finite complex value
and blocks execution, while substitution at -1 preserves the finite complex
result. This admissibility check does not replace the native operation’s own
premises, such as differentiability at an evaluation point.
A quantified curve coordinate is protected from scalar observations. Observing inventory at 3 specializes a state, while a convexity claim about the risk law still quantifies inventory over its explicit domain. A claim’s remaining free symbols are parameters. Conditions on them are retained rather than silently assumed.
wrt selects an independent model quantity or a declared Coordinate.
Use a path or the original symbol identity. A new same-named SymPy symbol is
rejected as foreign to the context. A defined quantity such as doubled = 2*x
is rejected as a differentiation coordinate with ModelDefinitionError:
reparameterize the curve explicitly before asking about its derivatives.
Quantities in unresolved defining cycles, and quantities that depend on them,
also need reparameterization before serving as coordinates.
expression(path, wrt=...) keeps the selected quantity symbolic even after
it has been observed; without wrt, it resolves the observed point.
expression and sample apply the same coordinate validation as property
checks. Parameter observations, including cyclic observations, do not turn an
independent quantity into a defined coordinate.
A curve through unresolved defining cycles also needs reparameterization when
its sources depend on the selected coordinate, including when observation
equations refer to that curve indirectly. Property checks retain unresolved
evidence; expression and sample raise NotImplementedError. Point
queries without wrt can still resolve the joint equations.
Property truth and proof attempts
Boolean predicates also require defined scalar operands. Negation, disjunction,
and implication do not turn a comparison with an undefined operand into a proof.
For example, predicate(Eq(1/a, 1/a, evaluate=False)) retains Ne(a, 0);
observing a=0 cannot establish it. Explicit and active SymPy assumptions
retain these domains too. Unsupported comparisons remain inspectable and block
methods that need them.
Scalar declarations retain their operands before simplification too. A held
0*log(x) or exp(log(x)) therefore keeps the hole at zero when inspected,
checked, or sampled. Native operations in assumptions use the same premise
checks as property subjects. A refuted native premise makes the context
inconsistent; an unestablished premise blocks methods until supported
parameter facts establish it. The native assumption cannot establish its own
operation’s premises.
If upstream CAS source binding, proof, or assumption-consistency checks exhaust
their recursion limit, the report keeps an unresolved obligation and blocks
dependent methods. A branch selector with unsupported source binding also
leaves an inspectable report, including during VerificationModel declaration.
Checks also bind active SymPy assuming(...) predicates through observations
and record them in their report, checking the combined premises for consistency.
Cached expression bindings, solution families, and proof attempts remain scoped
to that global assumption context, including its retained native coordinate
scopes. Context-bound methods distinguish those scopes too. Leaving the context
checks the original branch again without retaining context-dependent
simplifications. Use explicit context.assume(...) branches for premises that
should persist in the study.
Native substitution coordinates keep their own declared domains in cached
bindings, proof attempts, and inference-rule matching. SymPy can consider
two Subs expressions mathematically equal after renaming their bound
variables; that equality does not transfer a derivative certificate between
their scopes.
Coordinate discovery for component replacement visits every retained scope,
including mathematically equal substitutions with different bound coordinates.
For example, evaluation at zero on a real coordinate does not establish the
same operation on a positive coordinate whose domain excludes zero.
Binding and replacement also retain pending native operations before checking
their premises. If a CAS constructor drops an operation or substitutes a stale
coordinate scope, verify() reports unresolved evidence and run() blocks
methods that need it. expression(), sample(), and replacement raise
ModelInputError when that scope cannot be preserved; declare the expression
with its new coordinates instead.
The positive-derivative test is sufficient for strict increase, but it is not its definition. The polynomial rule can establish strict increase of \(x^3\) despite its zero derivative at zero. Likewise, \(|x|\) is convex and fails differentiability at zero. Failed C2 certificates alone do not refute convexity or twice differentiability. Discontinuity alone does not refute positivity, nonzero values, or an identity. Tail-limit claims inspect eventual behavior rather than requiring regularity at every finite point. Their requested domain, after applying source guards, must be established unbounded above. A bounded domain or a domain extending only toward negative infinity cannot establish a right-tail certificate.
For a parameterized polynomial such as \(a x^3\), that rule retains the nonconstancy condition. Assuming only \(a\geq0\) cannot establish strict increase because \(a=0\) remains admissible.
Continuity-domain failures can also depend on parameters. For example, \(a\sqrt{x}\) on \([0,1]\) has a smooth zero specialization at \(a=0\). Its general smoothness check remains unresolved; observing \(a=1\) establishes failure. A CAS continuity-domain exclusion alone does not refute every parameter specialization. Derivative formulas can also have removable singularities. Such exclusions remain unresolved unless a checked one-sided divergence or another supported rule establishes a refutation.
The curvature characterization of convexity applies on real intervals with nonempty interior. A singleton is checked by its finite real value instead; other discrete or disconnected domains remain unsupported by that rule.
Obligation domains must be established to be nonempty. Empty domains, including reversed intervals after observing their endpoints, remain unresolved with an explicit diagnostic. A symbolic interval with unknown endpoint order also stays unresolved. This policy applies before applying a trusted inference rule and prevents an empty scope from certifying a computation or supplying a refutation.
Supported proofs cover scalar real functions on real intervals, sign and
polynomial arguments, supported continuity domains, limits, and checked
uniform bounds. Unknown functions, mixed derivative regularity, and unsupported
parameter domains can remain unresolved. verify(max_steps=100) bounds proof
attempts, not wall-clock time within a CAS call.
Native derivatives introduce differentiability obligations with their order and evaluation point. They do not imply convexity or continuity of the derivatives. Divisions introduce definedness obligations before verification-layer cancellation. Inspection sees the expressions SymPy and Modello retained; it cannot recover syntax already simplified away before declaration. Empty sums, products, and zero-width integrals skip their inactive bodies, but their endpoint operations still need established premises. An undefined endpoint derivative cannot certify an identity merely because the resulting range is empty. For a supported single-limit scope, an inactive body can contain an unknown function or a cyclic model definition without blocking the empty operation.
Parameter observations also retain the source operands’ definedness. For
example, setting a=0 in a*log(x) does not define its value at x=0.
Symbolic observations retain their native operations too: supplying an
undefined derivative as an observation cannot establish a method’s premises,
even if a later multiplication would erase its value. Automatic obligations
follow these observations as well as model definitions.
Joint solving retains the source operands of observations and implicit defining
equations for checking and sampling. Evidence and exported reports expose them
as source_operands, alongside the resolved expression.
Supported source domains are checked alongside the simplified formula;
unsupported operand domains remain unresolved. These checks keep local
substitutions and derivative evaluation points in their original scopes.
Known finite piecewise values do not need continuity to establish definedness.
Real continuity domains provide sufficient definedness and regularity
certificates. Their failure alone does not refute claims involving finite
complex intermediate values, such as 0*log(x) or cos(sqrt(x)) on a
negative interval. Unsupported source domains remain
unresolved even when point samples happen to be finite.
Native SymPy substitutions retain these domains. Numerical compilation of
unsupported operand guards raises NotImplementedError instead of using
backend-specific values to fill undefined points.
Automatic obligations use a coordinate’s declared domain: a positive coordinate is checked on \((0,\infty)\), while a nonnegative coordinate still includes zero and retains a denominator failure there. Explicit claims keep their own requested domains, which must lie inside the intrinsic domain. The same domain rules as solution families retain integer, rational, parity, zero, and other declared restrictions. A discrete coordinate is not silently treated as a real continuum; unsupported proof scopes remain unresolved. Sampling checks membership using those same restrictions. Ordinary derivative certificates require an established real interior in the coordinate’s intrinsic domain. Global regularity claims and native derivatives on integer or rational coordinates therefore remain unresolved. Value checks and sampling retain their declared restrictions. A real coordinate can still be differentiated at a discrete set of evaluation points, and supported closed real intervals retain their regularity certificates.
Native Subs and Derivative expressions on either side of an identity,
in target bounds, evaluation points, domains, and proposed hints are evaluated
after checking their own derivative scopes. Their local evaluation points
need an established real neighborhood inside the derivative coordinate’s domain.
Undefined evaluation points remain failures. An invalid optional hint supplies
no certificate; it does not refute the requested bound.
Native Subs bindings retain their declared order. A derivative’s local
coordinate also stays independent of symbols introduced by those bindings.
For example, Subs(Derivative(Abs(x - y), x), y, x) evaluates the original
curve’s derivative at a cusp. Simplifying Abs(x - x) first would change
the function being differentiated. Replacing y with x - 1 instead
keeps the local derivative well-defined.
When flattening would lose that scope, the automatic obligation retains the
derivative and its native binders in a premise predicate. This checks the
derivative without imposing finiteness on unrelated symbolic terms or
convergence on an enclosing integral. Division obligations likewise preserve
their original substitution scopes: a later replacement of x**2 cannot
erase a pole introduced by an earlier binding of x. Native derivative
premises under compound substitutions, such as replacing x**2, currently
remain unresolved. Overlapping or compound substitutions inside a ranged
denominator also remain unresolved when their coordinate scopes cannot be
established.
Native derivative premises in Piecewise expressions respect the active
branch’s domain. Missing regularity proofs remain unresolved, including when
the operation occurs in a conditional branch.
Automatic obligations skip branches excluded by established parameter choices;
a global certificate also establishes an operation whose activation is unknown.
Otherwise the obligation remains unresolved. Coordinate assumptions cannot
select away branches of a globally quantified automatic obligation.
Native reductions retain their bound variables and supported integration or summation ranges. Assumptions on a free parameter cannot certify a locally bound variable with the same name. Single definite real integration intervals and integer reduction ranges have explicit scopes; unsupported nested ranges remain unresolved. These checks establish the operations used in an integrand or term; they do not establish convergence of an integral, series, or limit.
Implicit defining equations and intrinsic field domains participate in joint feasibility checks even without observations. Inconsistent contexts block method execution. Unsupported cyclic calculus remains inspectable as unresolved evidence, and blocks computations that depend on the unavailable model algebra. Unsupported inequality reasoning, including the solver’s limits on irrational coefficients, leaves consistency or evidence conditions unresolved. The report retains the assumptions, and a method still needs its required evidence before it can execute.
A nonzero real coordinate keeps zero excluded even when its sign is unknown.
An inner derivative cannot borrow an unrelated outer coordinate’s domain.
For a supported two-branch piecewise curve with one constant interior join,
the checker compares actual assigned values and finite one-sided derivatives
through order two. A local differentiability check away from the join checks
the active branch’s neighborhood and source guards; matching the other branch
at the join is unnecessary. Unsupported joins stay unresolved; an included
interval endpoint with only one active side does not establish ordinary differentiability.
Pointwise definedness at a guarded boundary is insufficient: an ordinary
derivative needs a defined neighborhood around every point, including points
in finite or closed interval domains. This obligation also applies to
continuously_differentiable(order=1) and continuously_differentiable(order=2). Continuity checks remain relative to
the requested domain.
A uniform-bound hint supplies a sufficient certificate. If its parameter guard fails, that certificate remains unestablished; a loose hint cannot refute the bound. A failed certificate also cannot erase an independently checked failure of a necessary premise. This includes hints with undefined or unsupported native operations, whether supplied directly or retained from observations. If a hint cannot be resolved from the model, the report retains its original expression and checks necessary premises independently. An optional certificate that conflicts with the subject’s admissible source conditions stays unresolved; that contradiction does not refute the subject. A curvature ratio still fails when its subject has a checked nondifferentiable join, even if the ratio simplifies to a smooth expression. Consumed hint keys, including canonical paths and inference-rule premise hints, are excluded from unused-hint diagnostics.
Use deferred Derivative(named_quantity, coordinate) inside declarations.
A named quantity acts as a symbol while the class body is collected, so eager
diff can treat it as independent of the coordinate. Differentiate a resolved
context.expression when performing a calculation outside the declaration.
Methods and inference rules
Pass either a prepared method or a method factory to
context.run(method, **settings). A factory receives the current context and returns
a Method; the runner then checks its premises and relevant automatic
obligations before executing it. Settings go to the computation, not the
factory. A blocked computation raises
VerificationError with context and report; numerical failures retain the
same context. Unrelated unresolved claims do not block a method.
Method.execute is ordinary Python code. Automatic obligations come from
the model expressions and retained native operands inspected by the verification
engine. Add mathematical premises needed only by the callback to
Method.preconditions. The callback implementation is part of the trust
boundary. The study supplies checks connecting its proposed answer to the
model, such as exact identities or optimality certificates; numerical
comparisons remain observations.
Reading a field through an alias consumes the same automatic obligations as
reading its original path, including aliases exposed from nested components.
Branch selection uses the report’s resolved parameter assumptions, including
assumptions expressed through aliases and active SymPy assumptions. Predicates
involving local or quantified coordinates cannot select away their operations.
Piecewise selectors retain their scalar domains before choosing a branch.
Only selectors reached in branch order need to be defined. Their checks keep
local substitution points and the full domains of unevaluated curves separate.
A locally evaluated expression such as Subs(curve, x, 1) keeps its own
scope: its obligations concern that evaluation, while the unevaluated source
curve can still have a pole elsewhere.
>>> from examples.record_review import ExponentialReview
>>> from modello.contrib.verification import Method, VerificationContext
>>> def response_method(current):
... curve = current.expression(current.symbols.caught_share, wrt=current.symbols.minutes_per_record)
... return Method(
... "response curve", lambda inner: curve, uses=("caught_share",),
... ).bind(current)
>>> measured = VerificationContext.for_model(ExponentialReview, detection_rate=1)
>>> measured.run(response_method).report.explain("caught_share/strictly_increasing").verdict
'strictly true'
Use context.run(response_method) after branching: it builds the method from
the current context on every call. Computation settings can be supplied as
additional keyword arguments to run.
Factories capturing expressions bind the returned method with
Method(...).bind(context). If a prepared method is retained for later use,
context.run(prepared) rejects a different context or SymPy assumption context
before checking its captured obligations or executing it. Generic methods
that resolve expressions from the supplied current context can remain unbound.
InferenceRule registers a trusted implication with a conclusion, named premises, source,
and version. with_rule adds it to a context. The engine recursively checks
the premises and retains them in the conclusion’s evidence. Failed premises
make a sufficient rule inapplicable; they do not refute its conclusion.
An unregistered rule conclusion remains unresolved; its proof attempt does not
evaluate unsupported native operations.
Circular rules remain unresolved. The inference-rule implementation and CAS form the
trust boundary; a citation or user assertion alone supplies no proof.
sample evaluates a finite set of points and returns a Sample.
This record is labelled numerical observation and cannot discharge a global
obligation. Points must be fully bound finite real scalars in the coordinate’s
declared domain, and their evaluated values must be fully bound, finite, and
real. Point expressions also retain their original operand domains and native
derivative premises: an unevaluated log(0)**0 cannot supply a valid point
by simplifying to one. Invalid points and unresolved symbolic values raise
ModelValidationError.
Write the record-review method’s contract
The record-review walkthrough uses
review_context() to prepare its inputs and mathematical argument. Here is
how the example connects that argument to a computation.
An Obligation names a claim. GLOBAL_MAXIMUM names the statement
\(G(s)\geq G(t)\) for every nonnegative number of checking minutes
\(t\), where \(s\) is the proposed checking minutes per record.
InferenceRule records the supporting-line argument from the walkthrough as
a trusted implication. Its premises ask the
checker to establish concavity, differentiability, a zero derivative at the
candidate, and candidate feasibility. The rule property marks this as a
custom conclusion to establish through a registered implication, rather than a
built-in property check:
GLOBAL_MAXIMUM = Obligation(
"global_maximum",
"candidate.minutes_saved_per_record",
"rule",
domain=CHECKING_MINUTES_DOMAIN,
reason="The chosen checking minutes maximize minutes saved per record over the nonnegative checking domain.",
)
STATIONARY_MAXIMUM = InferenceRule(
"concave_stationary_maximum",
GLOBAL_MAXIMUM,
(
concave(
"candidate.minutes_saved_per_record",
wrt="candidate.review.response.minutes_per_record",
domain=CHECKING_MINUTES_DOMAIN,
name="concavity",
),
continuously_differentiable(
"candidate.minutes_saved_per_record",
wrt="candidate.review.response.minutes_per_record",
domain=CHECKING_MINUTES_DOMAIN,
order=1,
name="differentiability",
),
equal_to("candidate.minutes_saved_derivative", 0, name="stationarity"),
nonnegative("candidate.review.response.minutes_per_record", name="feasibility"),
),
source="Concave supporting-line inequality; docs/examples/record-review/index.rst#why-this-is-a-global-optimum",
)
The candidate is a ReviewWorkload component. Its minutes_saved_per_record
field serves both the point evaluation and the function checks. The conclusion
concerns its minutes saved at the observed checking minutes. The rule’s shape
checks use wrt="candidate.review.response.minutes_per_record" to keep the response’s
input symbolic; its stationarity check evaluates the derivative at the observed point. The
alternative \(t\) in the mathematical statement belongs to the general
argument above, so the decision model needs no extra input or coordinate for it.
A registered implication is part of the trust boundary. The engine checks its premises; it does not prove that they imply the conclusion. A failed premise makes this argument inapplicable and leaves the conclusion unresolved.
The example’s _evaluate_plan callback reads the checking minutes per record,
minutes saved per record, total minutes per record, and the total’s second
derivative from that component. A Method pairs that callback with the
properties it needs:
review_plan = Method(
"review_plan",
_evaluate_plan,
preconditions=(GLOBAL_MAXIMUM, positive("candidate.minutes_per_record", name="positive_workload")),
uses=(
"candidate.review.response.minutes_per_record",
"candidate.minutes_saved_per_record",
"candidate.minutes_per_record",
"candidate.minutes_per_record_second_derivative",
),
)
uses names the fields read by the computation. Following their dependencies
consumes the response’s declared increase, concavity, and C2 properties.
preconditions adds the global-maximum conclusion and a positive candidate
workload. The callback executes after those premises are established; its
Python implementation is trusted too.
The convenience function registers the rule and accepts a RecordWork
component containing the entry and repair estimates, plus an ExponentialReview
response component containing the correction and error-creation rates.
Its defaults provide the walkthrough’s baseline. Each call builds a candidate
workload in a fresh context, leaving its checking minutes and staffing budget open:
def review_context(
record: RecordWork | None = None, *, response: ExponentialReview | None = None
) -> VerificationContext[ReviewPlanning, ReviewSpecification]:
"""Start a fresh context with these inputs and the stationary-point rule.
Supply record estimates and a response component, or use the baseline
with no introduced errors. Checking minutes and the staffing budget stay open.
"""
if record is None:
record = RecordWork(
"record", entry_minutes_per_record=4, error_fraction=Rational(1, 10), repair_minutes_per_error=60
)
if response is None:
response = ExponentialReview("response", detection_rate=Rational(1, 2), error_creation_rate=0)
context = VerificationContext.for_model(ReviewPlanning, "records").with_specification(
lambda symbols: ReviewSpecification(STATIONARY_MAXIMUM)
)
if type(record) is not RecordWork:
context = context.replace(context.symbols.candidate.review.record, type(record))
if type(response) is not ExponentialReview:
context = context.replace(context.symbols.candidate.review.response, type(response))
return context.observe(
{context.symbols.candidate.review.record: record, context.symbols.candidate.review.response: response}
)
Help an open proof with a checked bound
A bound can need an explicit argument even when each parameter is fixed. Continue with the same record-review model. Could any checking time save seven minutes per record? There are only six repair minutes to avoid, and checking itself costs time, so six is a uniform upper bound on minutes saved.
>>> from sympy import log
>>> from examples.record_review import CHECKING_MINUTES_DOMAIN, review_context
>>> from modello.contrib.verification import supremum_below
>>> proposed = review_context()
>>> proposed = proposed.observe({proposed.symbols.candidate.review.response.minutes_per_record: 2*log(3)})
>>> ceiling = proposed.with_obligations(supremum_below(
... proposed.symbols.candidate.minutes_saved_per_record,
... wrt=proposed.symbols.candidate.review.response.minutes_per_record,
... domain=CHECKING_MINUTES_DOMAIN,
... bound=7, name="saving_ceiling"))
>>> ceiling.explain("saving_ceiling").verdict
'unresolved'
>>> bounded = ceiling.with_bound_hint("saving_ceiling", upper=6)
>>> bounded.explain("saving_ceiling").verdict
'strictly true'
with_bound_hint proposes a certificate; it adds no assumption. The checker
establishes \(G(t)\leq6<7\) uniformly. A loose or incorrect hint cannot
refute the original bound. Here unresolved meant a proof aid was missing.
API
Deductive verification of mathematical model properties.
This module uses the core dependencies. Numerical backends and plotting are imported by the methods that use them, never by ordinary Modello or symbolic verification.
Workflow objects
Obligation is the single type for conditions. Method describes a
guarded computation; InferenceRule describes an explicitly trusted implication.
- class modello.contrib.verification.Obligation(name: str, subject: str | Basic, property: Literal['positive', 'nonnegative', 'nonzero', 'strictly_increasing', 'strictly_decreasing', 'convex', 'concave', 'continuously_differentiable', 'differentiable', 'limit', 'supremum_below', 'derivative_ratio_bound', 'equal_to', 'predicate', 'rule'], wrt: str | Symbol | None = None, domain: Set = Reals, order: int = 1, bound: Expr | None = None, expected: Expr | Callable[[Callable[[str], Expr]], Expr] | None = None, at: Expr | None = None, *, consumer: str = '', reason: str = '', source: str = '')
A named proposition to establish, with an explicit domain and motivation.
Strings select relative model paths; native expressions retain their symbol identities.
wrtselects a known independent symbol, rather than a defined quantity. Other free symbols are parameters, not quantified coordinates.atrequests differentiability in a neighborhood of a particular point.
- modello.contrib.verification.specifies(value: ValueT, *obligations: Obligation) ValueT
Return a field declaration or model subclass carrying obligations.
Property functions create the same Obligation values accepted by contexts, method preconditions, and inference-rule premises. Use the return value: the input expression, model class, and earlier verification contexts are left unchanged.
- class modello.contrib.verification.VerificationModel(*args: Any, **kwargs: Any)
Opt into automatic declaration reports, including every subclass.
Ordinary model construction is unchanged. Mathematical failures stay in the report; methods decide which established premises they need.
- class modello.contrib.verification.VerificationContext(problem, assumptions=(), obligations=(), bound_hints=(), rules=(), changes=())
Immutable definitions, observations, assumptions, and proof obligations.
Construction does not solve the model or establish its obligations.
- property specification: SpecificationT
The typed frozen dataclass naming this context’s goals and rules.
Names come from dataclass fields and tuple positions. The catalog is rebuilt from the current symbols on each immutable context update.
Nonedenotes a context without a named catalog.
- with_specification(factory: Callable[[ModelT], NewSpecificationT]) VerificationContext[ModelT, NewSpecificationT]
Declare named obligations and rules with a frozen dataclass factory.
- property model: ModelT
Read resolved fields through their declared model and component types.
This read-only namespace has the same fields as
symbols. It retains unresolved parameters and held operations, without selecting a solution or establishing proof obligations. Usesymbolsto select inputs.
- property family: SolutionFamily[ModelT]
The existing exact solution family, evaluated only on explicit demand.
- expression(subject: str | Basic, *, wrt: str | Symbol | None = None) Expr
Resolve a law, preserving an independent
wrtsymbol from observations.
- assume(*conditions) VerificationContext[ModelT, SpecificationT]
Add logical premises on a new context, retaining their native scopes.
- observe(observations: Mapping[InputKeyT, SymbolicScalar | int | float | complex | str | Decimal | Fraction | Vector | Sequence[SymbolicScalar | int | float | complex | str | Decimal | Fraction | None] | SymbolicVector | Modello | ModelVector[Modello] | Sequence[Modello | None] | ModelObservations[Modello]] | None = None, /, **inputs: SymbolicScalar | int | float | complex | str | Decimal | Fraction | Vector | Sequence[SymbolicScalar | int | float | complex | str | Decimal | Fraction | None] | SymbolicVector | Modello | ModelVector[Modello] | Sequence[Modello | None] | ModelObservations[Modello]) VerificationContext[ModelT, SpecificationT]
Bind reference-keyed observations or constructor-style inputs immutably.
- without_assumptions(*conditions: Basic, reason: str) VerificationContext[ModelT, SpecificationT]
Remove explicitly recorded assumptions, retaining why they changed.
Declaration domains and observations are unaffected. Each new report checks every dependent conclusion again under the remaining premises.
- with_obligations(*obligations: Obligation) VerificationContext[ModelT, SpecificationT]
Add proof goals without treating them as assumptions.
- without_obligations(*obligation_ids: str | Obligation, reason: str) VerificationContext[ModelT, SpecificationT]
Remove context-added goals; method and declaration obligations remain.
Change a declaration or component to change its annotations. Automatic obligations and a method’s own preconditions cannot be waived here.
- with_bound_hint(obligation_id: str | Obligation, *, upper) VerificationContext[ModelT, SpecificationT]
Propose a uniform upper bound; every check must establish it.
- with_rule(rule: InferenceRule) VerificationContext[ModelT, SpecificationT]
Register a trusted inference rule whose premises must be verified.
- verify(*, max_steps: int = 100, obligations: tuple[Obligation, ...] = ()) VerificationReport
Try bounded scalar rules; unknown does not mean a false proposition.
The budget counts proof attempts, not wall-clock time inside the CAS.
- explain(obligation_id: str | Obligation | InferenceRule) Evidence
Explain a named goal or attempt the supplied obligation or rule conclusion.
- sample(subject: str | Basic, *, wrt: str | Symbol, points) Sample
Evaluate finite points as observations, without discharging obligations.
- run(method: Method[ResultT] | Callable[[VerificationContext[ModelT, SpecificationT]], Method[ResultT]], **settings) VerificationResult[ResultT]
Run a prepared method or build one for this context before checking it.
- class modello.contrib.verification.Method(name: str, execute: Callable[..., ResultT], preconditions: tuple[Obligation, ...] = (), uses: tuple[str, ...] = (), bound_context: VerificationContext[Any, object] | None = None, bound_assumptions: frozenset[Basic] | None = None)
A guarded computation with preconditions and the model fields it reads.
- bind(context: VerificationContext[Any, object]) Method[ResultT]
Bind context-specific expressions to their full immutable context.
Rebuild a bound method after branching. Rebinding stale preconditions would not recompute the expressions that captured the earlier context.
- class modello.contrib.verification.InferenceRule(name: str, conclusion: Obligation, premises: tuple[Obligation, ...], source: str, version: str = '1')
A trusted, versioned rule whose premises are recursively checked.
Registered inference rules are part of the trust boundary, like the CAS. A bibliographic note alone does not register a rule or establish its conclusion.
Mathematical conditions
Every function below returns an Obligation and accepts the same optional
consumer, reason, and source metadata. Sign, order, shape, regularity,
and bounds are different mathematical conditions, rather than different
container types. Their mathematical meanings are explicit:
strictly_increasingandstrictly_decreasingrequire strict monotonicity on the domain. A strictly positive derivative is one sufficient certificate, rather than the definition of strict monotonicity.convexandconcaveallow linear sections. For a twice differentiable scalar function on an interval, a nonnegative second derivative is sufficient for convexity; a nonpositive second derivative is sufficient for concavity.continuously_differentiable(order=n)requires \(C^n\) regularity, with continuous derivatives through the finite order n.differentiable(order=n)only requires those derivatives to exist.supremum_below(f, b)states \(\sup_{x\in D} f(x)<b\). A checked bound hint \(M\) must establish \(f(x)\leq M<b\) uniformly on the domain.derivative_ratio_bound(f, bound=b)requires a nonzero first derivative and \(\sup_{x\in D} f(x)f''(x)/(f'(x))^2<b\). The name refers to this specific derivative ratio.equal_to(f, g)requires equality on the stated domain, including the definedness of both expressions. Algebraically equivalent expressions can establish it without having identical syntax.tends_to_zerorequires a zero limit as the coordinate tends to \(+\infty\) on the expression’s eventual domain.
- modello.contrib.verification.positive(subject: str | Basic, *, wrt=None, domain=Reals, name='positive', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.nonnegative(subject: str | Basic, *, wrt=None, domain=Reals, name='nonnegative', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.nonzero(subject: str | Basic, *, wrt=None, domain=Reals, name='nonzero', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.strictly_increasing(subject: str | Basic, *, wrt, domain=Reals, name='strictly_increasing', consumer: str = '', reason: str = '', source: str = '') Obligation
State f(x) < f(y) for every ordered pair x < y in the domain.
- modello.contrib.verification.strictly_decreasing(subject: str | Basic, *, wrt, domain=Reals, name='strictly_decreasing', consumer: str = '', reason: str = '', source: str = '') Obligation
State f(x) > f(y) for every ordered pair x < y in the domain.
- modello.contrib.verification.convex(subject: str | Basic, *, wrt, domain=Reals, name='convex', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.concave(subject: str | Basic, *, wrt, domain=Reals, name='concave', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.continuously_differentiable(subject: str | Basic, *, wrt, order=2, domain=Reals, name='continuously_differentiable', consumer: str = '', reason: str = '', source: str = '') Obligation
Require C^n regularity through the finite derivative order n.
- modello.contrib.verification.differentiable(subject: str | Basic, *, wrt, order=1, domain=Reals, at=None, name='differentiable', consumer: str = '', reason: str = '', source: str = '') Obligation
- modello.contrib.verification.tends_to_zero(subject: str | Basic, *, wrt, name='right_tail', consumer: str = '', reason: str = '', source: str = '') Obligation
State a zero limit as the coordinate tends to positive infinity.
- modello.contrib.verification.supremum_below(subject: str | Basic, bound, *, wrt, domain=Reals, name='supremum_below', consumer: str = '', reason: str = '', source: str = '') Obligation
State sup(f) < bound on the domain, with a strict uniform margin.
- modello.contrib.verification.derivative_ratio_bound(subject: str | Basic, *, wrt, bound=2, domain=Reals, name='derivative_ratio_bound', consumer: str = '', reason: str = '', source: str = '') Obligation
Bound sup(f*f’’/(f’)**2) strictly, requiring f’’ to exist and f’ != 0.
- modello.contrib.verification.equal_to(subject: str | Basic, expected: Expr | Callable[[Callable[[str], Expr]], Expr], *, wrt=None, domain=Reals, name='equal_to', consumer: str = '', reason: str = '', source: str = '') Obligation
Require equality on the domain, allowing algebraically equivalent forms.
Returned evidence and results
These records are returned by the workflow; they do not introduce additional ways to declare an obligation.
- class modello.contrib.verification.Evidence(id: str, obligation: Obligation, expression: Basic, coordinate: Symbol | None, condition: Basic | None, steps: tuple[str, ...], dependencies: tuple[str, ...] = (), witness: tuple[tuple[Symbol, Expr], ...] = (), kind: str = 'symbolic', condition_strength: str = 'sufficient', premises: tuple[Evidence, ...] = (), resolved: Obligation | None = None, hint: Expr | None = None, expected_template: Basic | None = None, source_operands: tuple[Basic, ...] = ())
One result, including guards, derivation, and validated counterexamples.
- class modello.contrib.verification.VerificationReport(model: str, evidence: tuple[Evidence, ...], assumptions: tuple[Basic, ...] = (), consistent: bool | None = True, issues: tuple[str, ...] = (), labels: tuple[tuple[Symbol, str], ...] = ())
Evidence for one immutable context; consistency is checked separately.
- explain(obligation_id: str | Obligation | InferenceRule) Evidence
Find evidence by ID, obligation, or an inference rule’s conclusion.
- class modello.contrib.verification.VerificationResult(method: 'str', data: 'ResultT', report: 'VerificationReport', settings: 'Mapping[str, Any]')
- class modello.contrib.verification.Sample(expression: Expr, coordinate: Symbol, points: tuple[Expr, ...], values: tuple[Expr, ...], kind: str = 'numerical observation')
Finite observations, never a proof of a universal claim.
- exception modello.contrib.verification.VerificationError(message: str, context: VerificationContext[Any, object], report: VerificationReport)
A blocked computation retaining its verification context and report.