API reference
- class modello.Modello(name: str, **value_map: SymbolicScalar | int | float | complex | str | Decimal | Fraction | Modello)
Build a symbolic model, solving its named children together with it.
Define quantities and their relationships as class attributes. Pass known scalar values and component instances as constructor keyword arguments. The model and its components are solved together; omitted inputs remain symbolic unless the supplied equations determine them.
namelabels an instance’s symbols. Separate constructions and separate components have independent unknowns, even when their names are the same. Solved quantities are exposed as normal Python attributes. Create a new instance to solve with different inputs.Inputs and errors
Scalar inputs can be Python numbers, decimals, fractions, SymPy expressions, or expression strings. The
ScalarValueannotation describes these inputs;SymbolicScalarprovides the expression protocol for static typing. Components accept instances of their declared model class, including subclasses with the same field paths.Scalar expressions can use the model class’s quantities or a parent’s component paths. Other SymPy symbols remain external parameters.
Unknown keyword names, invalid scalar values, and incompatible component types raise
modello.errors.ModelInputError, also aTypeError. No accepted solver candidates or multiple candidates raisemodello.errors.SolutionCountError; a backend exception raisesmodello.errors.SolverBackendError. Both aremodello.errors.ModelSolveErrorandValueErrorsubclasses. Symbol assumptions help select candidates; assumptions about external symbolic parameters may remain undecided. A supplied component is constructed first in its own context. Parent observations can impose additional constraints, so successful child construction does not establish consistency of the parent.Solve failures retain a frozen
problemsnapshot with actual symbol identities, aliases, origins, equations, inputs, and solver candidates. Backend solver exceptions are chained as the cause. Diagnostic analysis runs only when explicitly invoked. A zero candidate count is not itself a proof of inconsistency. See Debugging a model for symbolic results, redundant observations, conflicting constraints, and ambiguous solutions.Component copies and methods
A parent copies the declared quantities of each supplied component and its descendants. It can complete symbolic inputs without changing the source. Copies have the declared component type and its methods. Ordinary instance attributes and extra fields of a supplied subclass belong to the source.
Express relationships as class attributes and use methods for additional behavior. Component copies are filled from the parent’s solution; custom
__init__and__new__methods run when an input instance is explicitly constructed, and are not called again for those copies.Inheritance
A subclass inherits its parent’s quantities and relationships. Replacing a component updates inherited expressions by matching field paths. When a replacement changes the available fields or their aliases, redefine the expressions that use the changed fields too.
When multiple model bases define the same quantity, the later base supplies that quantity. Methods follow Python’s normal method resolution order.
- modello.inspect_model(model: type[_ModelT], name: str, /, **value_map: SymbolicScalar | int | float | complex | str | Decimal | Fraction | Modello) ModelProblem[_ModelT]
Prepare the constructor’s actual problem without invoking the solver.
Supply the same scalar values and typed component instances as a normal construction. The snapshot retains all aliases, constraint origins, and whole-argument observation groups, including copied component values.
Supply the same typed inputs as construction. Preparing a snapshot does not invoke the solver. Component instances supplied as inputs have already been constructed separately. See Diagnostic guarantees and reference for the structured snapshot, report types, and guarantees.
problem.symbolsexposes a read-only symbol tree with the model’s component types. Use its attributes to write conditions and select outputs whenproblem.solutions()explores a joint solution family; see Explore a solution family.
- modello.component(model: type[_ModelT]) _ModelT
Declare a named child with its instance type in a model class body.
Use
child = component(Child), then supply aChildinstance when constructing the parent model.Use
child = component(Child)in a model class body, then supply aChildinstance when constructing the parent. Child attributes retain their model instance types for editors and type checkers. Constructor keyword names and compatible component classes are checked at runtime.See Nested models for a walkthrough.
- class modello.InstanceDummy(name=None, dummy_index=None, **assumptions)
A symbol that is rebound independently for each model instance.
Declare an independent quantity with optional SymPy assumptions, such as
positive=Trueorreal=True. Each model instance receives its own symbol for an unresolved quantity.- bound(model_name: str) BoundInstanceDummy
Return a fresh symbol with this symbol’s assumptions.
- class modello.BoundInstanceDummy(name=None, dummy_index=None, **assumptions)
A symbol belonging to a particular model instance.
- class modello.SymbolicScalar(*args, **kwargs)
A scalar expression accepted by the constructor’s input annotations.
- class modello.SymbolicCondition(*args, **kwargs)
A symbolic relation or Boolean accepted by solution-family refinement.
Extension annotations
Extensions can attach metadata to declarations without changing their values,
symbols, assumptions, aliases, or equations. Subclass Annotation and use
annotate inside a model class body:
from dataclasses import dataclass
from modello import Annotation, InstanceDummy, Modello, annotate, component
@dataclass(frozen=True)
class Unit(Annotation):
symbol: str
class Panel(Modello):
width = annotate(InstanceDummy("width", positive=True), Unit("m"))
area = annotate(width**2, Unit("m²"))
class Project(Modello):
panel = component(Panel)
assert Unit.for_model(Project)["panel.width"].symbol == "m"
assert Panel.__modello_annotations__[Unit]["area"].symbol == "m²"
assert Panel("case", width=3).area == 9
The class collector unwraps each declaration before subsequent expressions use
it. Helpers preserve the declared value’s static type, including typed
components. Use annotate around an entire assigned value; it is a class-body
declaration helper rather than a general symbolic expression wrapper. Ordinary
Python attributes keep their ordinary behaviour when annotated.
Model.__modello_annotations__ groups metadata by its exact annotation
class, then relative dotted attribute path. Both mapping levels are read-only.
The empty path "" stores model-level metadata. annotate_model supports
extension decorators and returns the original class. Decorate a component
before declaring models that contain it, so its metadata is included in their
compiled registries.
Several annotation types can decorate one field, with one declaration per exact
type in each class scope. Duplicate types in a call, stacked helpers, repeated
field annotations, and repeated model decorators raise
ModelDefinitionError, even when the metadata is identical. A rejected model
annotation leaves its registry intact.
Inheritance preserves metadata by field name. A subclass has a new declaration scope and may explicitly replace an inherited annotation as a whole. Later model bases take precedence for each annotation type. A plain field reassignment retains its annotations, including the common pattern of declaring an assumed symbol and then assigning its defining expression. Aliases have separate named metadata while retaining their shared symbol.
Nested components contribute scoped paths automatically. Replacing a component rebuilds its descendant metadata from the replacement class, dropping obsolete paths. A label attached directly to the containing component declaration stays with that named field. Each model has its own registry mappings.
This mechanism has no dependency on a particular extension. For example,
modello.gui implements FieldInfo(Annotation) and the gui helper;
importing and using core annotations does not import the GUI or Flask.
- class modello.Annotation
Base for extension metadata; it never participates in model equations.
Subclasses usually declare immutable metadata with a frozen dataclass.
for_modelprovides a typed view of the registry for this exact class.
- modello.annotate(value: _ValueT, *annotations: Annotation) _ValueT
Attach metadata to a value assigned in a Modello class body.
The class namespace unwraps the value before subsequent expressions use it. The value’s static type is preserved, like
component(Model). Stacked declarations retain different annotation types; duplicate instances of the same exact type raise ModelDefinitionError. This is a declaration helper, not a wrapper for arithmetic outside a model class body.
- modello.annotate_model(model: type[_ModelT], *annotations: Annotation) type[_ModelT]
Attach model-level metadata at the registry’s empty path.
Extension decorators can call this after a class has been created. The class itself is returned, preserving its identity and type. Repeating an annotation type on the same class raises ModelDefinitionError; a subclass can refine inherited metadata in its own declaration scope.
Errors
Catch ModelloError for Modello’s validation and construction failures, or
ModelSolveError for failed solves. These classes are available from
modello and modello.errors. Existing TypeError and ValueError
handlers still apply. Ordinary key and attribute lookups retain their Python
KeyError and AttributeError behaviour.
ModelloError
├── ModelInputError (also TypeError)
├── ModelValidationError (also ValueError)
│ ├── ModelDefinitionError
│ ├── SolutionSelectionError
│ └── UnresolvedSolutionError
└── ModelSolveError (also ValueError)
├── SolutionCountError
└── SolverBackendError
SolutionCountError.solution_count is the number of retained solver
candidates. returned_count counts the captured candidates before domain
filtering; these are available through problem.candidates, including rejected
proposals. Each candidate can contain symbolic expressions representing a family
of numerical answers. Neither count establishes how many mathematical solutions
the model has, and a zero retained count alone does not prove inconsistency.
SolverBackendError.backend_error retains the original exception, also
available as __cause__; solution_count is None. The recorded problem
is available for both failure types. Handle failures through these attributes
rather than parsing exception messages. Constructing or printing an error does
not launch diagnostic analysis.
For example, case SolutionCountError(solution_count=0) selects a zero-count
failure. Positional case SolutionCountError(0) is supported too.
case SolverBackendError(backend_error=NotImplementedError()) selects a
particular backend exception type. See Debugging a model for a complete workflow.
The solution-family guide describes the selection errors and
their retained families, counts, and candidate checks.
- class modello.errors.ModelloError
Base for Modello’s validation and model-construction failures.
- class modello.errors.ModelInputError
A constructor, declaration, or diagnostic input has an invalid type.
- class modello.errors.ModelValidationError
An argument or model operation violates a Modello requirement.
- class modello.errors.ModelDefinitionError
A model declaration contains incompatible fields or references.
- class modello.errors.ModelSolveError(problem: ModelProblem, count: int | None, candidates: tuple[Candidate, ...] = ())
A solve failure retaining its problem; analysis is explicitly opt-in.
solution_countcounts retained solver candidates, not numeric points.Nonemeans the backend failed before a count was available.
- class modello.errors.SolutionCountError(problem: ModelProblem, solution_count: int, candidates: tuple[Candidate, ...] = ())
Construction retained zero or several candidates instead of one.
A zero count alone does not establish inconsistency. Domain filtering can reject candidates that remain available in
problem.candidates.
- class modello.errors.SolverBackendError(problem: ModelProblem, backend_error: Exception)
The joint solver raised; its original exception is also the cause.