tg_model.model¶
Public modeling API: elements, definition context, refs, and expression helpers.
Everything here is definition-time (define(cls, model)): symbolic refs,
declarations recorded on ModelDefinitionContext,
and helpers such as sum_attributes() for unitflow-safe roll-ups.
See also
tg_model.executionConfigure (instantiate) and evaluate compiled models.
- class tg_model.model.AttributeRef(owner_type, path, kind, target_type=None, metadata=None)[source]¶
Bases:
RefReference to a declared attribute or parameter (value slot at configure time).
For
attribute()expr=, passing another slot’s ref compiles as an identity passthrough. Usesymwhen you need that slot inside unitflowExprarithmetic (for exampleother.sym + …).- Parameters:
owner_type (type)
path (tuple[str, ...])
kind (str)
target_type (type | None)
metadata (dict[str, Any] | None)
- property sym: Any¶
Canonical unitflow symbol for this reference (cached per ref identity).
- Returns:
Unitflow symbol with
unitfrom declaration metadata.- Return type:
Symbol
- Raises:
ValueError – If
metadatahas nounit(symbols cannot be constructed).
- kind¶
- metadata¶
- owner_type¶
- path¶
- target_type¶
- class tg_model.model.Element[source]¶
Bases:
objectAbstract base for all model element types.
Subclasses implement
define()to record structure; compilation produces a cached dict artifact consumed by instantiation and graph compilation.Notes
compile()is idempotent per class. Use_reset_compilation()only in tests.- classmethod define(model)[source]¶
Declare this type’s structure (override in subclasses).
- Parameters:
model (ModelDefinitionContext) – Definition-time recorder passed by the compiler.
- Return type:
None
- class tg_model.model.ModelDefinitionContext(owner_type, *, symbol_owner=None, symbol_path_prefix=())[source]¶
Bases:
objectRecords declarations during
define(cls, model)(themodelargument).Framework-controlled: only recording is allowed until
freeze(). All declaration names share one namespace per owner type; duplicates raiseModelDefinitionError.For
Requirement,symbol_ownerandsymbol_path_prefixthread the configured root type and path prefix sorequirement_input()buildsAttributeRefpaths the graph compiler resolves afterallocate()inputs=bindings.- Parameters:
owner_type (type)
symbol_owner (type | None)
symbol_path_prefix (tuple[str, ...])
- owner_type¶
The
Elementsubclass whosedefine()is running.- Type:
type
- symbol_owner¶
Root type used as
AttributeRef.owner_typefor threaded requirement inputs.- Type:
type
- symbol_path_prefix¶
Prefix of requirement-block names under the root (internal threading).
- Type:
tuple[str, …]
- nodes¶
Declarations keyed by local name.
- Type:
dict[str, NodeDecl]
- edges¶
Structural and semantic edges (
connect,allocate,references, …).- Type:
list[dict]
- behavior_transitions¶
Recorded state-machine transitions (Phase 6).
- Type:
list[dict]
- part() PartRef[source]¶
- part(name: str, part_type: type) PartRef
Declare a child part, or return a ref to this block as the configured root.
No arguments — does not register a child. Returns a
PartRefto this block: the parent you are defining indefine(). All othermodel.part(name, Type)calls in the samedefine()become children of that parent atinstantiate()time (same rootPartInstanceowns them). Two arguments — register a composed child part and return its ref.- Parameters:
- Returns:
Root ref (empty path) or child ref.
- Return type:
- Raises:
ModelDefinitionError – On wrong arity (only one of
name/part_type), duplicate name, or frozen context.
Examples
Typical root + child pattern:
rocket = model.part() tank = model.part("tank", TankType) model.allocate(req, rocket)
- root_block()[source]¶
Return a ref to this type as the configured structural root (empty path).
- Returns:
path=()andtarget_type=self.owner_type.- Return type:
Notes
Same as
part()with no arguments. Preferpart()when mixing root and child declarations in one call style.See also
- owner_part()[source]¶
Alias of
root_block()(historical name).- Returns:
Same as
root_block().- Return type:
- port(name, direction, **metadata)[source]¶
Declare a structural port on this part or system.
- Parameters:
name (str) – Local port name (unique in this type’s node namespace).
direction (str) – Flow direction label (e.g.
in,out,inout— project convention).**metadata – Additional port metadata stored on the compiled node.
- Returns:
Reference for use in
connect().- Return type:
- Raises:
ModelDefinitionError – On duplicate
nameor if the context is frozen.
- attribute(name, *, expr=None, computed_by=None, **metadata)[source]¶
Declare an attribute (bindable/computed value slot).
Root
Systemtypes may not declare attributes. KeepSystem.define()focused on composition and top-level parameters; move derived values into an ownedPartor requirement package.- Parameters:
name (str) – Local attribute name.
expr (Any | None) – Optional unitflow expression or
RollupDeclfor derived values.computed_by (Any | None) – Optional
ExternalComputeBindingfor external computation.**metadata (Any) – Must include
unit=(and any other declaration metadata) for symbol construction.
- Returns:
Reference for constraints, expressions, and graph compilation.
- Return type:
- Raises:
ModelDefinitionError – On duplicate name, frozen context, or when called from
System.define().
Notes
Chaining
a + b + cis left-associative; usea + (b + c),.sym, orsum_attributes()to avoid mixedExpr/AttributeReferrors.
- parameter(name, **metadata)[source]¶
Declare an externally bindable parameter (input slot at evaluation time).
- Parameters:
name (str) – Local parameter name.
**metadata – Typically includes
unit=for quantity inputs.
- Returns:
kind='parameter'reference.- Return type:
- Raises:
ModelDefinitionError – On duplicate name, frozen context, or when called from
System.define().
- parameter_ref(root_block_type, name)[source]¶
Call
parameter_ref()(same resolution rules and errors).- Parameters:
root_block_type (type)
name (str)
- Return type:
- attribute_ref(root_block_type, name)[source]¶
Call
attribute_ref()(same resolution rules and errors).- Parameters:
root_block_type (type)
name (str)
- Return type:
- requirement_ref(root_block_type, path)[source]¶
Call
requirement_ref()(same resolution rules and errors).- Parameters:
root_block_type (type)
path (tuple[str, ...])
- Return type:
- citation(name, **metadata)[source]¶
Declare an external provenance node (standards, reports, URIs, clauses).
- Parameters:
name (str) – Citation node name.
**metadata – Free-form citation fields (URI, clause id, revision, …).
- Returns:
kind='citation'forreferences()edges.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
Notes
v0 does not execute citations in the evaluator; they support export and traceability hooks.
- requirement(name, text, *, expr=None, **metadata)[source]¶
Declare a requirement (human
textplus optional executable acceptance).- Parameters:
name (str) – Requirement node name.
text (str) – Human-readable statement (not evaluated).
expr (Any | None) – Optional boolean acceptance expression (same family as
constraint()).**metadata (Any) – Additional requirement metadata.
- Returns:
kind='requirement'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
Notes
With
expr=, symbols must resolve against theallocate()target subtree at compile time, and anallocateedge must exist. Preferrequirement_input()andrequirement_accept_expr()insideRequirementwhen acceptance should use only requirement-local inputs bound viaallocate(..., inputs=).
- requirement_input(requirement, name, **metadata)[source]¶
Advanced / rare — leaf reqcheck input slot on
requirement.Warning
For new requirement packages, use ``model.parameter`` at package scope instead.
requirement_inputis a low-level helper for INCOSE-style leaf acceptance rows wired viaallocate(..., inputs=...). See theRequirementclass docstring.Registers a value-bearing symbol under the configured root (threaded
symbol_owner/symbol_path_prefix). Bind each input withallocate()inputs={name: part_ref.…}.- Parameters:
requirement (Ref) –
kind='requirement'ref declared in this block.name (str) – Input slot name (referenced in acceptance expressions).
**metadata – Forwarded to the internal parameter declaration (e.g.
unit=).
- Returns:
Symbol for use in
requirement_accept_expr()(kind='parameter'onsymbol_owner).- Return type:
- Raises:
ModelDefinitionError – If not inside a requirement block,
requirementis wrong, inputs conflict withrequirement(..., expr=), or names duplicate.
- requirement_attribute(requirement, name, *, expr, **metadata)[source]¶
Advanced / rare — derived value on a leaf
requirement.Warning
For new requirement packages, use ``model.attribute`` at package scope instead.
requirement_attributeis a low-level helper for INCOSE-style leaf acceptance rows. See theRequirementclass docstring.Registers a requirement-local attribute whose value is computed from an expression (typically over
requirement_input()symbols, otherrequirement_attributesymbols declared earlier in the samedefine(), and root parameters). Useunit=inmetadatasoAttributeRef.symcan be built.Unlike
requirement_input(), attributes are not wired viaallocate()inputs=; they are evaluated from theirexpr=and materialized as value slots on the configured root for graph compilation.- Parameters:
requirement (Ref) –
kind='requirement'ref declared in this block.name (str) – Attribute name (must not collide with a
requirement_inputname on the same requirement).expr (Any) – Scalar expression (same family as
attribute()expr=).**metadata (Any) – Must include
unit=(and any other declaration metadata).
- Returns:
kind='attribute'symbol for use inrequirement_accept_expr()or in laterrequirement_attributecalls.- Return type:
- Raises:
ModelDefinitionError – If not in a block,
requirementis wrong, names collide,expris missing, or acceptance was already set viarequirement_accept_expr.
- requirement_accept_expr(requirement, *, expr)[source]¶
Advanced / rare — set executable acceptance for a leaf
requirement.Warning
For new requirement packages, use ``model.constraint`` at package scope instead.
requirement_accept_expris a low-level helper for INCOSE-style leaf acceptance rows. See theRequirementclass docstring.- Parameters:
requirement (Ref) – Requirement ref from this block (single-segment path only).
expr (Any) – Boolean expression over requirement input symbols (and unitflow quantities).
- Raises:
ModelDefinitionError – If not in a block, ref is invalid, path is not a single segment, or acceptance was already set via
requirement(..., expr=)or a prior call.- Return type:
None
- requirement_package(name, package_type)[source]¶
Declare a nested composable requirements package (
Requirement).- Parameters:
name (str) – Package name in this owner’s namespace.
package_type (type) – Subclass of
Requirement.
- Returns:
Dot-access ref to nested requirements.
- Return type:
- Raises:
ModelDefinitionError – If
package_typeis not a composable requirement, on duplicate name, or frozen context.
Notes
Compiles
package_typeeagerly sorequirement_ref()and sibling dot access work within the samedefine()call. The internal node kind remainsrequirement_blockfor artifact compatibility.Inside
package_type.define(), package-levelparameter(),attribute(), andconstraint()are allowed whenRequirementcompile policy permits them.
- constraint(name, *, expr, **metadata)[source]¶
Declare a constraint (boolean check over realized slot values).
Root
Systemtypes may not declare constraints. Put executable checks on the owningPartor requirement package so the top-level system stays structural.- Parameters:
name (str) – Constraint name (appears in
ConstraintResult).expr (Any) – Boolean expression over
AttributeRef/ unitflow symbols.**metadata (Any) – Extra metadata attached to the compiled node.
- Returns:
kind='constraint'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name, frozen context, or when called from
System.define().
- state(name, *, initial=False, **metadata)[source]¶
Declare a discrete behavioral state (state machine vertex).
- Parameters:
name (str) – State name (used in
transition()and runtime state string).initial (bool, default False) – Mark the initial state for this part type (exactly one should be initial).
**metadata – Optional extra state metadata.
- Returns:
kind='state'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
- event(name, **metadata)[source]¶
Declare a discrete behavioral event (state machine stimulus).
- Parameters:
name (str) – Event name string used with
dispatch_event().**metadata – Optional event metadata.
- Returns:
kind='event'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
- action(name, *, effect=None, **metadata)[source]¶
Declare a named action (callable side effect on a part instance).
- Parameters:
name (str) – Action name referenced by transitions, sequences, decisions, etc.
effect (callable, optional) –
(RunContext, PartInstance) -> Noneexecuted under behavior subtree scope.**metadata – Stored on the compiled action node if
effectis omitted (legacy inline hook).
- Returns:
kind='action'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
- guard(name, *, predicate, **metadata)[source]¶
Declare a reusable guard for decisions and transitions.
- Parameters:
name (str) – Guard name.
predicate (Any) –
(RunContext, PartInstance) -> boolevaluated under behavior subtree scope.**metadata (Any) – Optional metadata.
- Returns:
kind='guard'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
- merge(name, *, then_action=None, **metadata)[source]¶
Declare a merge node (shared continuation after branching).
- Parameters:
name (str) – Merge node name.
then_action (str, optional) – Action name to run when
dispatch_merge()fires.**metadata – Optional metadata.
- Returns:
kind='merge'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
Notes
When
decision()usesmerge_point=to this merge,dispatch_decision()runs the continuation automatically; do not also calldispatch_merge()for that path.
- item_kind(name, **metadata)[source]¶
Declare an item kind label for inter-part flows (
emit_item()).- Parameters:
name (str) – Kind / event name carried across connections.
**metadata – Optional metadata.
- Returns:
kind='item_kind'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
- decision(name, *, branches, default_action=None, merge_point=None, **metadata)[source]¶
Declare an exclusive decision (first matching guard wins).
- Parameters:
name (str) – Decision node name.
branches (list[tuple[Ref | None, str]]) – Each entry is
(guard_ref or None, action_name).Noneguard is unconditional.default_action (str, optional) – Action name when no branch matches.
merge_point (Ref, optional) –
kind='merge'ref for automatic continuation (seemerge()).**metadata – Extra metadata.
- Returns:
kind='decision'.- Return type:
- Raises:
ModelDefinitionError – On malformed branches, wrong ref kinds/owners, unknown merge, duplicate name, or frozen context.
Notes
Runtime API:
dispatch_decision().
- fork_join(name, *, branches, then_action=None, **metadata)[source]¶
Declare a fork/join activity region (serial branch execution in v0).
- Parameters:
name (str) – Block name.
branches (list[list[str]]) – Each inner list is one branch: action names run in order within the branch.
then_action (str, optional) – Action name after all branches complete.
**metadata – Extra metadata.
- Returns:
kind='fork_join'.- Return type:
- Raises:
ModelDefinitionError – On empty/malformed
branches, duplicate name, or frozen context.
Notes
v0 runs branches serially in list order; see
dispatch_fork_join().
- sequence(name, *, steps, **metadata)[source]¶
Declare a linear sequence of action names (in-order execution).
- Parameters:
name (str) – Sequence node name.
steps (list[str]) – Non-empty list of declared action names.
**metadata – Extra metadata.
- Returns:
kind='sequence'.- Return type:
- Raises:
ModelDefinitionError – On empty/non-string steps, duplicate name, or frozen context.
See also
tg_model.execution.behavior.dispatch_sequence
- transition(from_state, to_state, on, *, when=None, guard=None, effect=None)[source]¶
Record one state-machine transition for this part type.
- Parameters:
from_state (Ref) –
kind='state'refs on this type.to_state (Ref) –
kind='state'refs on this type.on (Ref) –
kind='event'ref.when (callable, optional) –
(RunContext, PartInstance) -> boolinline guard (mutually exclusive withguard=).guard (Ref, optional) –
kind='guard'ref (mutually exclusive withwhen=).effect (str, optional) – Declared action name run after the state advances.
- Raises:
ModelDefinitionError – If both
whenandguardare set, refs have wrong kinds/owners, or context is frozen.- Return type:
None
Notes
Determinism: at most one transition per
(from_state, event)(checked at compile time).
- scenario(name, *, expected_event_order, initial_behavior_state=None, expected_final_behavior_state=None, expected_interaction_order=None, expected_item_kind_order=None, **metadata)[source]¶
Declare a behavioral scenario contract (partial trace checks).
- Parameters:
name (str) – Scenario node name.
expected_event_order (list[Ref]) – Event refs in expected firing order for the scenario owner type.
initial_behavior_state (str, optional) – Expected
from_stateof the first transition onpart_pathunder validation.expected_final_behavior_state (str, optional) – Expected discrete state after the trace (needs
ctxin validation).expected_interaction_order (list[tuple[str, str]], optional) –
(relative_part_path, event_name)pairs from this type’s root for global ordering checks.expected_item_kind_order (list[str], optional) – Expected
ItemFlowStepitem_kindsequence.**metadata – Extra scenario metadata.
- Returns:
kind='scenario'.- Return type:
- Raises:
ModelDefinitionError – If event refs are wrong, duplicate name, or frozen context.
See also
tg_model.execution.behavior.validate_scenario_trace
- solve_group(name, *, equations, unknowns, givens, **metadata)[source]¶
Declare a coupled equation solve group (requires SciPy at evaluation).
- Parameters:
name (str) – Solve group name.
equations (list) – Scalar expressions (same count as
unknowns) compiled to residuals.unknowns (list[AttributeRef]) – Attributes to solve for.
givens (list[AttributeRef]) – Bound inputs to the solver.
**metadata – Extra metadata.
- Returns:
kind='solve_group'.- Return type:
- Raises:
ModelDefinitionError – On duplicate name or frozen context.
Notes
Execution uses
scipy.optimize; seetg_model.execution.solve_groups.
- allocate(requirement_ref, target_ref, *, inputs=None)[source]¶
Declare an allocation from a requirement to a model element.
Optional
inputsmapsrequirement_input()names to part parameter/attribute refs. Required when acceptance uses only requirement-local symbols.- Parameters:
requirement_ref (Ref) –
kind='requirement'ref being allocated.target_ref (Ref) – Part or root ref that supplies values for acceptance (per compiler rules).
inputs (dict[str, AttributeRef], optional) – Maps input name →
AttributeRefon the allocated subtree.
- Raises:
ModelDefinitionError – If context is frozen or
inputsvalues are notAttributeRef.- Return type:
None
- allocate_to_system(requirement_ref)[source]¶
Preferred shorthand for
allocate(requirement_ref, root_block()).- Parameters:
requirement_ref (Ref) – Requirement to allocate to this type’s structural system/root block.
- Raises:
ModelDefinitionError – Same as
allocate().- Return type:
None
- allocate_to_root(requirement_ref)[source]¶
Compatibility alias for
allocate_to_system().- Parameters:
requirement_ref (Ref) – Requirement to allocate to this type’s structural root.
- Raises:
ModelDefinitionError – Same as
allocate().- Return type:
None
- connect(source, target, carrying=None)[source]¶
Declare a structural connection between two ports.
- Parameters:
source (PortRef) – Port refs declared on (possibly different) composed types under one configured root.
target (PortRef) – Port refs declared on (possibly different) composed types under one configured root.
carrying (str, optional) – When set,
emit_item()only uses this binding ifitem_kindmatches.
- Raises:
ModelDefinitionError – If either endpoint is not a
PortRef, or context is frozen.- Return type:
None
- parts()[source]¶
Return the internal selector token for “all child parts” in roll-up expressions.
- Returns:
The sentinel
"ALL_PARTS"understood by roll-up compilation.- Return type:
str
See also
tg_model.model.declarations.values.RollupBuilder.sum
- link_external_routes(binding, routes)[source]¶
Wire
output_routeson anExternalComputeBinding.Call after declaring attributes so
AttributeReftargets exist.- Parameters:
binding (ExternalComputeBinding) – Binding created for this type.
routes (dict[str, AttributeRef]) – External output name → attribute slot ref.
- Raises:
ModelDefinitionError – If
bindingis not anExternalComputeBinding.- Return type:
None
- class tg_model.model.Part[source]¶
Bases:
ElementStructural part in a hierarchy (may own child parts, ports, values, behavior).
- class tg_model.model.PartRef(owner_type, path, kind, target_type=None, metadata=None)[source]¶
Bases:
RefReference to a declared part; dot access chains into the child compiled type.
- Raises:
AttributeError – If
target_typeis missing, the type is not compiled, or the member does not exist.- Parameters:
owner_type (type)
path (tuple[str, ...])
kind (str)
target_type (type | None)
metadata (dict[str, Any] | None)
- kind¶
- metadata¶
- owner_type¶
- path¶
- target_type¶
- class tg_model.model.PortRef(owner_type, path, kind, target_type=None, metadata=None)[source]¶
Bases:
RefReference to a declared port.
Use with
tg_model.model.definition_context.ModelDefinitionContext.connect().- Parameters:
owner_type (type)
path (tuple[str, ...])
kind (str)
target_type (type | None)
metadata (dict[str, Any] | None)
- kind¶
- metadata¶
- owner_type¶
- path¶
- target_type¶
- class tg_model.model.Ref(owner_type, path, kind, target_type=None, metadata=None)[source]¶
Bases:
objectSymbolic reference to one declared model element.
- Parameters:
owner_type (type) – Type whose compiled artifact owns this path (often the configured root).
path (tuple[str, ...]) – Declaration names from that owner (
()for the root part ref).kind (str) – Node kind (
requirement,constraint,event, …).target_type (type, optional) – Composed type for
part/requirement_blockrefs.metadata (dict, optional) – Declaration metadata copied from compile records.
- owner_type¶
- path¶
- kind¶
- target_type¶
- metadata¶
- property local_name: str¶
Dotted path string for this ref (
a.b.c).
- class tg_model.model.Requirement[source]¶
Bases:
ElementComposable requirements package — use ``parameter`` / ``attribute`` / ``constraint``.
DEFAULT PATTERN (always start here): Inside
define(cls, model), declaremodel.parameter,model.attribute, andmodel.constraintat package scope — the same value/check authoring surface asPart(unlikeSystem, which is restricted to structural composition and top-level parameters). Usemodel.requirement(id, text)for leaf traceability statements,model.citationfor provenance,model.referencesfor edges, andmodel.allocatefor structural allocation. This is the standard, recommended API for all new requirement packages.Register on a
PartorSystemviarequirement_package(); navigate withRequirementRefdot access.Advanced (rare — leaf reqcheck only):
requirement_input,requirement_attribute, andrequirement_accept_exprare low-level helpers for INCOSE-style executable acceptance on a single leafmodel.requirement(...), wired throughallocate(..., inputs=...). Use them only when you needsummarize_requirement_satisfactionper-requirement rows. Do not use them as the default pattern. If your check can be a package-levelconstraint, use that instead.Notes
Package-level
parameter,attribute, andconstraintnodes becomeValueSlot/ graph nodes under the configured root (dot access e.g.configured_root.pkg.param_name); expressions are validated duringcompile(). Package-level slots do not yet supportcomputed_by=orRollupDeclin graph compilation; every packageconstraintmust supplyexpr=(including constant expressions with no symbols).
- class tg_model.model.RequirementRef(owner_type, path, kind, target_type=None, metadata=None)[source]¶
Bases:
RefReference to a declared composable requirement package (dot access like
PartRef).- Raises:
AttributeError – If the package type is not compiled yet, the member is missing, or the kind cannot be projected (only requirement subtree kinds are allowed).
- Parameters:
owner_type (type)
path (tuple[str, ...])
kind (str)
target_type (type | None)
metadata (dict[str, Any] | None)
- kind¶
- metadata¶
- owner_type¶
- path¶
- target_type¶
- class tg_model.model.System[source]¶
Bases:
ElementTop-level system element for composition and top-level input parameters.
System.define()is intentionally structural: compose child parts, declare ports/requirements/citations as needed, and keep mission or scenario inputs as top-levelparameter(...)declarations. Derived values and executable checks belong on ownedPartinstances or requirement packages, not on the rootSystemitself.- classmethod instantiate()[source]¶
Build a
ConfiguredModelfor this root type.Delegates to
instantiate()— same behavior and no extra compilation path.- Returns:
Frozen topology for graph compile and evaluation. A new instance on every call; there is no shared singleton configured model.
- Return type:
Notes
Call this on a concrete
Systemsubclass that implementsElement.define()for your program root. That is the same requirement as passing that class toinstantiate().The base
Systemtype itself is not a valid configured root;System.instantiate()fails the same way asinstantiate(System).Configured roots that are
Partsubclasses still useinstantiate()only (no class method onPart).See also
tg_model.execution.configured_model.instantiate
- tg_model.model.as_expr_leaf(x)[source]¶
Promote
AttributeRefto unitflow expr leaf.- Parameters:
x (Any) – Attribute ref or already-expression value.
- Returns:
x.symfor refs; otherwisex.- Return type:
Any
Notes
Use when hand-building sums so
expr + AttributeRefnever hits unitflow’s_promote.
- tg_model.model.attribute_ref(root_block_type, name)[source]¶
Return a reference to an attribute on the configured (or compiling) root type.
Same resolution order as
parameter_ref(), but the named node must bekind='attribute'. Use when a nestedRequirement(or part) should derive package slots from an allowed root-block attribute, such as a configured rootPart. RootSystemtypes may not declareattribute(...); move those derived values into an owned part or requirement package instead.- Parameters:
root_block_type (type)
name (str)
- Return type:
- tg_model.model.parameter_ref(root_block_type, name)[source]¶
Return a reference to a parameter on the configured (or compiling) root type.
Use inside nested
define()to point at mission / scenario parameters on the root without globals—e.g. forExternalComputeBindinginputs or constraint expressions.- Parameters:
root_block_type (type) – The root
System/Partsubclass that owns the parameter declaration.name (str) – Parameter declaration name on
root_block_type.
- Returns:
Symbolic ref (
kind='parameter') for graph compilation and expressions.- Return type:
- Raises:
ModelDefinitionError – If the node is missing, is not a parameter, or
root_block_typeis neither compiling nor compiled.
Notes
Resolution order:
If
root_block_typeis fully compiled, read from the cached artifact.If mid-compile, read from the active definition context; declare parameters on the root before child
model.part(...)types that call this function.
- tg_model.model.requirement_ref(root_block_type, path)[source]¶
Return a
Refto a requirement under the root type.pathis declaration names from the root (e.g.("mission", "range")for requirementrangeinside packagemission). Use from nestedPart.define()when dot notation from aPartRefis not available.- Parameters:
root_block_type (type) – Configured root type owning the requirement subtree.
path (tuple[str, ...]) – Non-empty path of segments: intermediate steps are composable requirement packages (internal compiled kind
requirement_block); the last segment is a leaf requirement.
- Returns:
kind='requirement'ref with metadata from the compiled declaration.- Return type:
- Raises:
ModelDefinitionError – If
pathis empty, a segment is missing, kinds along the path are wrong, or the root is neither compiling nor compiled.
Notes
Resolution matches
parameter_ref(): prefer the compiled root artifact; while compiling, the first segment comes from the active context and nested segments from compiled composable-requirement artifacts (eager compile when registering viaModelDefinitionContext.requirement_package()).
- tg_model.model.sum_attributes(*terms)[source]¶
Sum two or more attribute refs and/or expressions (associative-safe).
Avoids the Python
a + b + cleft-association trap with mixedAttributeRefandExpr.- Parameters:
*terms (Any) – Two or more refs and/or unitflow expressions.
- Returns:
Left-folded unitflow expression after
as_expr_leaf()on each term.- Return type:
Any
- Raises:
ValueError – If fewer than two terms are passed.
Examples
model.attribute("total_kg", unit=kg, expr=sum_attributes(a, b, c))