Core¶
Base classes, state guards, streams, specs and numerics every component builds on.
tango_core.core.component
¶
Component base class for tango.
Components are Pydantic models — the instantiated object is 1:1 with the YAML input file. All fields, including runtime state, history, and derived quantities, are public Pydantic fields so that solved models can be serialized and restored.
Two classes:
Component: what every component shares — YAML config fields,state/history, serde, and convergence snapshot/restore.FlowComponent(Component): a component the working fluid flows through (wells, reservoir, surface plant). Adds theoutletStream andsolve(inlet, step) -> Stream, which returns that outlet so the orchestrator can pass it straight to the next component. The economic component is a plainComponent: it has no fluid inlet or outlet.
Fields that are absent from YAML (state, history, outlet, derived quantities)
use default_factory and are populated when init() runs or, in the case of
state/history/outlet, when solve()/record() run. inlet is NOT a
field — see FlowComponent.solve()'s docstring for why.
Serialization design¶
model_dump() returns all fields, including state, history, and (for a
FlowComponent) outlet.
This allows a solved model to be saved and later restored via from_dict().
Round-trip test pattern (config-only, skip_init=True)::
comp1 = MyComponent.from_dict(d, skip_init=True)
json1 = comp1.model_dump()
comp2 = MyComponent.model_validate(json1)
json2 = comp2.model_dump()
assert json1 == json2
skip_init=True leaves derived fields at their defaults (zero / empty list)
and is used for serde round-trip tests. Derived fields that are pure
functions of the inputs may be excluded from serialization (e.g.
NumericalWell's), so a restored model that will be solved again needs
init().
History / save_interval¶
save_interval: int | None = 1
None— never record history1— record every timestep (default)n > 1— record every n-th timestep
The orchestrator calls each component's record_step(step) once per
accepted step. It checks save_interval and, if due, appends the step to
time_history and calls record(step.index) (inherited from
StateMethods — see core/state_methods.py), which pushes every
(state, history) pair returned by _state_history_pairs() (state/
history, plus outlet/outlet_history for a FlowComponent).
time_history is therefore the time axis of every other history list on
the same component: entry i of each belongs to the same step.
Frozen config fields¶
Every field that is genuinely YAML config — set once at construction and
never reassigned by init()/solve()/the orchestrator afterward — is
declared Field(frozen=True) in each concrete Component subclass
(component_idx/save_interval here on the base class; geometry,
physics-model selections, etc. in each subclass). This mirrors Common
(core/specs.py): the only supported way to change one of these values
is the dict-modify-then-reinstantiate pattern (Workflow.to_dict() →
mutate the copy → Workflow(cfg)), never live attribute assignment —
see Workflow's class docstring for a worked example.
This is deliberately NOT applied to every field. Some fields are plain
Pydantic fields (not LockedState-wrapped) that are legitimately
reassigned during the simulation itself, not by a user tweaking config —
freezing these would break init()/solve(), not protect anything:
FlowComponent.outlet— reassigned bysolve()every timestep.state/history— the object itself is never reassigned (its fields mutate internally instead), so freezing the container field would add nothing.SurfaceComponent.injection_pressure— the BC-iteration guess, explicitly updated in place bySystemBCIterationevery convergence pass (see its docstring).- A handful of subclass-specific "derived, computed once by
init()" fields that happen to be plain floats rather thanLockedState, e.g.NumericalWell.cell_length/relative_roughness/T_randLumpedReservoir.T_initial/rock_volume/rock_C_v— these are pure functions of frozen config fields, computed exactly once ininit()and never reassigned bysolve(), so there is nothing for write-once enforcement to protect and no reason for them to live instate(next paragraph) either. See each class's own comments for why.
Every field that IS reassigned by solve() — every call, or only some
calls, doesn't matter — belongs in state, not as a bare Component
field, no matter whether it also happens to be a pure function of already-
restored inputs (e.g. LumpedReservoir's p1/p2/p3) or a
genuine cross-timestep accumulator that depends on its own prior value
(e.g. LumpedReservoir.energy_extracted/ever_solved,
NumericalWell.state.t_d). state is restored in full before every
re-solve (next paragraph) precisely so this one rule has no exceptions to
track per-field: anything solve() writes is protected the same way,
accumulator or not.
Component
¶
Bases: BaseModel, ABC, StateMethods
Abstract base for every tango component.
Subclass this (usually through FlowComponent) and declare
YAML-configuration fields as normal Pydantic fields. Override init()
to compute derived quantities. record(timestep) (inherited from
StateMethods) already appends to history generically — override
_state_history_pairs() instead if a subclass has more
(state, history)-shaped pairs to push than state/history.
The orchestrator calls mark_all_stale() immediately before every
solve() call — solve() itself does not do this. A component fresh
from construction already starts with a stale state (each field's
default_factory marks it stale), so the very first solve() call
needs no explicit mark_all_stale() first; every subsequent call does.
Callers invoking solve() directly (bypassing an orchestrator — tests,
scratch scripts) must call mark_all_stale() themselves before any
call after the first.
component_idx = Field(frozen=True)
class-attribute
instance-attribute
¶
Circuit index. 0 is the circuit entry (injection well, solved first).
The BC checkpoint (surface) is identified separately via bc_checkpoint_idx
in sim_config.
save_interval = Field(default=1, frozen=True)
class-attribute
instance-attribute
¶
Timestep interval at which record() appends state to history.
None disables history recording entirely. Default 1 records
every timestep (matches the original record_history=True behavior).
time_history = Field(default_factory=TimeHistory)
class-attribute
instance-attribute
¶
Time axis of this component's recorded history: the step behind each
recorded entry (see record_step).
keeps_external_state = False
class-attribute
¶
Whether part of this component's memory across steps lives outside
state, in an external simulator that only accept_timestep()
commits. Such a component can take only one step per sync interval,
since a step cannot be accepted before the interval has converged.
from_dict(config, skip_init=False)
classmethod
¶
Instantiate from a merged YAML config dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Merged dict of common + layout + component-specific fields. |
required |
skip_init
|
bool
|
If |
False
|
init()
¶
Compute derived quantities from validated input fields.
Called by from_dict() unless skip_init=True. Override in
subclasses to pre-compute geometry constants, look-up tables, etc.
snapshot_convergence_state()
¶
Deep-copy state — the only thing that must not leak across a within-timestep re-solve.
Used by orchestrators that re-solve a component more than once for the same calendar timestep (e.g. an injection-temperature convergence loop): restore this snapshot before every re-solve so each attempt starts from "state as committed at the end of the previous timestep," not from whatever the last attempt left behind (whether that's an unconverged re-solve's own output, or a stale read of a cross-timestep accumulator via last attempt's leftovers).
Scope: self.state only. Every field a component's solve()
writes — whether recomputed from scratch each call or a genuine
cross-timestep accumulator that depends on its own prior value —
lives in state by convention (see the class docstring's "Frozen
config fields" section); nothing outside state is ever mutated
by solve(). A FlowComponent's inlet/outlet are
excluded implicitly (they aren't part of state) because they must
evolve iteration-to-iteration during a convergence loop — restoring
them would prevent any loop from moving. history is excluded the same way — only
record() touches it, once per timestep after any convergence
loop finishes, never during it.
restore_convergence_state(snapshot)
¶
Write a fresh deep copy of a snapshot_convergence_state() snapshot back onto self.state.
Deep-copies again at restore time, not just at snapshot time — the
snapshot must stay pristine across repeated restores within the
same timestep, so a solve() call's in-place mutation of what
was handed out on one attempt must not corrupt what the next
attempt reads back.
record_step(step)
¶
Record this component's state for an accepted step, with the step itself.
Appends step to time_history whenever record() pushes
state, so the two stay aligned under save_interval thinning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
TimeStep
|
The step that was just accepted. |
required |
hold_step_record(step)
¶
Keep a copy of what record_step(step) would record, to record once the interval converges.
A subsystem that takes several steps in one sync interval solves
them all before the interval is accepted, and may solve them again
on the next pass of a convergence loop. Its earlier steps' states
are overwritten by the later ones, so each is copied here after it
solves; record_held_steps records the copies from the pass that
is accepted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
TimeStep
|
The step that was just solved. |
required |
discard_held_steps()
¶
Drop the held records, at the start of each pass over a sync interval.
record_held_steps()
¶
Record the held copies in step order, then drop them; called once the interval is accepted.
accept_timestep()
¶
Commit the timestep whose final solve just ran; called once per timestep, before record().
An orchestrator may solve a component several times for the same
timestep (see snapshot_convergence_state) and only the last of
those solves is kept. Components whose cross-timestep memory lives
entirely in state need nothing here. A component that delegates
to an external simulator holding its own state overrides this to
tell that simulator to keep its last trial solve. Default: no-op.
FlowComponent
¶
Bases: Component
Abstract base for a component the working fluid flows through: wells, reservoir, surface plant.
The orchestrator passes inlet directly into solve(inlet, step) — it is
NOT a stored field (see solve()'s docstring for why). solve()
writes outlet, which IS a stored field, and returns it; the
orchestrator hands the returned Stream to the next component.
outlet = Field(default_factory=Stream)
class-attribute
instance-attribute
¶
Downstream stream — written by solve(), once per call, same
write-once-per-solve pattern as state (outlet's fields are
LockedState-wrapped — see core/stream.py). There is no
corresponding inlet field: see solve()'s docstring.
outlet_history = Field(default_factory=StreamHistory)
class-attribute
instance-attribute
¶
Per-timestep history of outlet — pushed alongside state's own
history every record() call (see _state_history_pairs()).
TANGO Commandment: every *State-shaped attribute (outlet
included) needs a *History analog.
solve(inlet, step)
abstractmethod
¶
Compute this component's outlet from inlet over step, store it in outlet, and return it.
inlet is passed as an explicit call parameter — never a stored
field — and the outlet comes back as the return value, so that the
whole hand-off reads at one place: the orchestrator's wiring code
(outlet = component.solve(self._next_inlet(component), step), then
self._record_outlet(component, outlet), tracked in
SystemDirect._pending_inlets). That one site tells you exactly
which upstream component a given component's input causally depends
on, for a given pass.
step is the interval being solved over, also passed per call:
a component with memory across steps (a well's dimensionless time,
a reservoir's extracted energy, an external simulator's clock)
advances it by step.dt, and a component without such memory
ignores it. No component stores a step length of its own.
Every concrete solve() records inlet into its own
state.T_inlet/P_inlet/mass_rate (LockedState-
protected, restored by restore_convergence_state()), the durable
record of "what this component's inlet was, this solve"; the
parameter itself is transient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inlet
|
Stream
|
The stream entering this component. |
required |
step
|
TimeStep
|
The step being solved over. |
required |
Returns:
| Type | Description |
|---|---|
Stream
|
|
Stream
|
it past the next |
Stream
|
|
Stream
|
overwrites them. |
tango_core.core.orchestrator
¶
Orchestrator ABC for tango.
Orchestrator
¶
Bases: ABC
Abstract base for all tango orchestrators.
Owns the component graph and executes components in the correct order within each sync interval. Concrete subclasses: SystemDirect (single-pass, no BC concept) and SystemBCIteration (subclasses SystemDirect, adding injection-pressure/mass-rate BC iteration governed by InjectionPolicy).
components
abstractmethod
property
¶
Named components, keyed by the name used in the input file.
run_interval(i)
abstractmethod
¶
Execute one sync interval: every subsystem's steps up to the next sync time.
With a single subsystem, an interval is one timestep (see
tango_core.core.time_stepping).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
int
|
Zero-based sync interval index. |
required |
run()
abstractmethod
¶
Execute the full simulation across all timesteps.
tango_core.core.stream
¶
Stream — fluid connection between tango components.
Stream(mass_rate=_ls(), P=_ls(), h=_ls())
dataclass
¶
Bases: StateMethods
Carries mass flow rate and the two thermodynamic properties (pressure, specific enthalpy) that actually cross a component boundary.
SI units throughout: pressures in Pa, specific enthalpies in J/kg, mass flow rates in kg/s.
Enthalpy, not temperature, is the stream variable -- the same choice Modelica's fluid connectors make. It's intensive on a per-mass basis, it's what each component's energy balance works in, and (h, P) fixes the state everywhere, including inside the two-phase dome where (T, P) doesn't. Passing temperature instead made every component rebuild h from (T, P), and near a fluid's critical point that rebuild is badly conditioned: with a tabular CoolProp backend, near-critical CO2 lost up to 17 kJ/kg crossing a single component boundary. A component that needs temperature derives it locally from (h, P) with its own fluid and backend.
Deliberately narrow: every field here is one every component's
solve() both writes (outlet) and reads (inlet) — see the
3-line block at the top of every concrete solve(). Fields that are
computed at the outlet condition but never read back by anything
(rho, mu) or never touched by any component at all (port)
were removed rather than carried here as dead weight — each
component still computes its own density/viscosity locally wherever
the physics needs them (e.g. state.rho/state.mu, evaluated at
whatever state that component's own calculation needs, not necessarily
the outlet condition); Stream just isn't the place those live if
nothing downstream reads them off the wire. Revisit if a future
consumer (e.g. an external-tool adapter, a cavitation check) actually
needs outlet-condition fluid properties propagated between components.
Every scalar field is LockedState-wrapped, structurally identical to
a component's own state dataclass (see TANGO Commandment on
LockedState placement in CONTRIBUTING.md) — a Stream instance is
never a bare, freely-reassignable container of raw floats. frozen=True
for the same Layer-3 reason every *State class uses it (see
core/locked_state.py's module docstring): it blocks
stream.h = LockedState(...) from silently replacing the wrapper and
discarding its status, while leaving stream.h.update(...) fully
functional.
Stream() (the bare default constructor) leaves every field STALE —
matching every other *State dataclass's convention: a genuinely
usable, immediately-get_fresh()-able value requires an explicit
write. Use Stream.fresh(...) instead wherever a Stream needs to carry
real, immediately-readable data (orchestrator wiring, test fixtures).
Deliberately does NOT carry a fluid_name (or any other fluid-identity
field): every component that needs one already holds a reference to the
Workflow's single shared Common instance (core/specs.py), which
is where fluid_name lives. Duplicating it here as per-timestep,
per-stream state would just be a second, unvalidated copy that could
drift from Common — exactly the risk this design avoids (see
docs/tango_tasks.md's fluid-identity review). If a future component
needs to represent a genuine fluid boundary (e.g. a secondary/ORC loop
physically separate from the geofluid loop), that calls for an explicit
typed marker on the boundary component, not a field here.
mass_rate = field(default_factory=_ls)
class-attribute
instance-attribute
¶
Mass flow rate crossing the component boundary (kg/s).
P = field(default_factory=_ls)
class-attribute
instance-attribute
¶
Pressure at the component boundary (Pa).
h = field(default_factory=_ls)
class-attribute
instance-attribute
¶
Specific enthalpy at the component boundary (J/kg).
fresh(*, h=0.0, P=0.0, mass_rate=0.0)
classmethod
¶
Construct a Stream with every field already FRESH — immediately usable.
Stream()'s own default constructor leaves every field stale
(see class docstring); this factory is for the common case of
needing a Stream that already carries real data, readable right
away via get_fresh() — the core mechanism the orchestrator's
wiring layer (SystemDirect/SystemBCIteration) uses to build
every inlet it constructs, not just a test-fixture convenience.
Never used inside a component's own solve(), which writes its
own outlet fields via .update() individually, same as any
other state field.
StreamHistory(mass_rate=list(), P=list(), h=list())
dataclass
¶
Per-timestep history of a Stream (TANGO Commandment: every
*State-shaped class — Stream included — must have a *History
analog with a matching field for each attribute). No exceptions needed
here: every Stream field is LockedState-wrapped, solve-cycle
state (see Stream's own docstring for the fields deliberately
excluded from the class entirely, rather than excluded from history).
mass_rate = field(default_factory=list)
class-attribute
instance-attribute
¶
Per-timestep mass flow rate (kg/s).
P = field(default_factory=list)
class-attribute
instance-attribute
¶
Per-timestep pressure (Pa).
h = field(default_factory=list)
class-attribute
instance-attribute
¶
Per-timestep specific enthalpy (J/kg).
record(stream)
¶
Append one timestep snapshot.
tango_core.core.locked_state
¶
LockedState — single-value wrapper that enforces one update per timestep.
Motivation¶
Any multi-component simulation can accidentally read or write a state variable
at the wrong point in the solve order — reading a value before its upstream
dependency has been updated, or writing it twice in the same timestep. These
bugs are hard to catch by inspection because the code looks correct; the error
is in which loop level it runs inside. LockedState catches them immediately
at the call site rather than letting them propagate silently into results. The
risk is especially acute in iterative solvers that mix a convergence loop
(repeated passes until a boundary condition is satisfied) with a timestep loop
(advancing the simulation forward in time).
LockedState addresses this by embedding the enforcement in the data itself
rather than relying on caller discipline. Any solver — existing or future —
that tries to write a state variable twice in the same timestep receives an
immediate DoubleWriteError at the call site. This is the solver-neutral
property: the constraint travels with the variable, not with the caller, so new
orchestrators and new convergence strategies cannot accidentally violate it.
The overhead is a single enum comparison on each read/write — negligible relative to any CoolProp or TESPy call.
Bypass prevention¶
In a language with real module-private fields, the compiler could enforce this contract directly — code outside the defining module simply couldn't name the internal fields. Python has no equivalent mechanism; every attribute is reachable at runtime. We use three layers to make bypass obvious rather than impossible:
Layer 1 — __slots__: prevents attribute addition. A caller cannot
do ls.value = x (no slot named value); Python raises AttributeError
immediately. This eliminates the most common accidental bypass — mis-spelling
the API method and inadvertently creating a shadow attribute.
Layer 2 — double-underscore name mangling on __value and __status:
Python mangles any identifier of the form __name (two leading underscores,
at most one trailing) inside a class body to _ClassName__name. The
__slots__ declaration is subject to the same mangling, so the actual slot
names stored on the class are _LockedState__value and
_LockedState__status. The practical effect on callers outside the class:
ls.__value = x— Python mangles this tols._CallerModule__value(orls.__valueat module top-level, which mangles differently again); neither name matches the real slot →AttributeError.ls._value = x— no slot named_valueexists at all →AttributeError.
The only remaining bypass route is the deliberately ugly
ls._LockedState__value = x. Anyone who types that knows exactly what the
mangled name convention means and is making a conscious choice to circumvent a
documented safety mechanism. That is a meaningful barrier: it eliminates all
accidental bypasses and transforms any intentional bypass into an
unambiguous red flag in code review.
Layer 3 — @dataclass(frozen=True) on every containing state class:
prevents state.T = LockedState(350.0), which would silently replace the
whole wrapper object, discarding its status and losing any pending fresh value.
frozen=True raises FrozenInstanceError on attribute re-assignment
while leaving all method calls (state.T.update(...), state.T.mark_stale())
fully functional. Every state dataclass in tango that holds LockedState
fields must use frozen=True::
@dataclass(frozen=True)
class ReservoirState:
T_outlet: LockedState[float] = field(default_factory=lambda: LockedState(300.0))
energy_extracted: LockedState[float] = field(default_factory=lambda: LockedState(0.0))
What is still NOT prevented¶
ls._LockedState__value = x works at the Python runtime level and always
will — Python's name mangling is a renaming convention, not true access
control. We do not try to block this with __setattr__ overrides because
doing so would force every internal write inside update(), __init__(),
etc. to use object.__setattr__(self, '_LockedState__value', x) — a
significant readability and maintenance cost for zero practical benefit, since
anyone reaching through name mangling by definition understands what they
are doing.
Each state variable in a component's state dataclass is a LockedState
instance::
from dataclasses import dataclass, field
from tango_core.core.locked_state import LockedState
@dataclass(frozen=True)
class ReservoirState:
T_outlet: LockedState[float] = field(default_factory=lambda: LockedState(300.0))
energy_extracted: LockedState[float] = field(default_factory=lambda: LockedState(0.0))
A new LockedState starts fresh — the initial value is authoritative for
the 0th timestep. Immediately before each solve() call, the orchestrator
calls component.mark_all_stale() (core/component.py), which cascades
down to mark_stale() on every state field (or check_and_reset() for
combined validate-and-advance) — components no longer call this on
themselves. During solve(), update() writes the new value and
re-marks it fresh. get_fresh() / get_stale() assert the expected
status before returning the value.
Status semantics¶
fresh — the value has been computed for the current timestep.
- get_fresh() succeeds.
- get_stale() raises FreshAccessError.
- update() raises DoubleWriteError.
stale — the value has not yet been computed for the current timestep; it
holds the result from the previous timestep (or the initial value).
- get_stale() succeeds.
- get_fresh() raises StaleAccessError.
- update() succeeds and marks fresh.
Lifecycle per timestep::
state.T_outlet.mark_stale() # ① advance to new timestep
prev = state.T_outlet.get_stale() # ② read previous value during solve
state.T_outlet.update(prev + delta) # ③ write new value, marks fresh
cur = state.T_outlet.get_fresh() # ④ read current value (post-solve)
state.T_outlet.check_and_reset() # ⑤ validate fresh, then mark stale
# (alternative to explicit ①)
LockedState(initial_value)
¶
Bases: Generic[T]
Single-value wrapper that enforces exactly one update() per timestep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_value
|
T
|
The value held on construction. Status starts fresh
(the initial value is authoritative; call |
required |
Initialize with initial_value; status starts fresh.
is_fresh()
¶
Return True if the value has been updated this timestep.
is_stale()
¶
Return True if the value has not yet been updated this timestep.
get_fresh()
¶
Return the value, asserting it is fresh.
Raises:
| Type | Description |
|---|---|
StaleAccessError
|
The value has not been updated this timestep. |
get_stale()
¶
Return the value, asserting it is stale (i.e. from the previous timestep).
Raises:
| Type | Description |
|---|---|
FreshAccessError
|
The value has already been updated this timestep. |
update(value)
¶
Write a new value and mark fresh.
Raises:
| Type | Description |
|---|---|
DoubleWriteError
|
The value has already been updated this timestep. |
increment(delta)
¶
Add delta to the current value and mark fresh.
For accumulator-style state (e.g. cumulative extracted energy) that
must be updated by += rather than whole-value replacement, while
still enforcing the same "exactly once per timestep" contract as
update(). Only meaningful for a T that supports +.
Raises:
| Type | Description |
|---|---|
DoubleWriteError
|
The value has already been updated this timestep. |
mark_stale()
¶
Mark as stale, opening the write slot for the next timestep.
mark_fresh()
¶
Assert stale, then mark fresh WITHOUT writing a new value.
For the case where a value is being treated as already-current by
some other means (e.g. restored from a snapshot/reconstruction that
doesn't go through the normal solve() write path) and just
needs its write-once guard opened up for reading, not recomputed.
Distinct from update(), which requires (and consumes) a new
value. StateMethods.mark_fresh() (core/state_methods.py)
calls this recursively; LockedState itself has no dependency on
that module.
Raises:
| Type | Description |
|---|---|
FreshAccessError
|
The value is already fresh — mirrors
|
check_and_reset()
¶
Assert fresh, then mark stale.
Combines end-of-timestep validation with advance: verifies that
update() was called during the solve, then resets for the next
timestep. Raises StaleAccessError if the value was never updated.
__repr__()
¶
Return a string showing the value and current status.
__get_pydantic_core_schema__(source_type, handler)
classmethod
¶
Teach pydantic v2 to treat LockedState as a transparent wrapper.
Serialization: LockedState(v) → v (just the raw value).
Validation/deserialization: plain v → LockedState(v) starting
fresh (readable immediately via get_fresh(), same as any
newly-constructed LockedState — see __init__).
This means that in any YAML/JSON save file, a LockedState[float]
field appears as a bare float with no value/status keys — the
LockedState wrapper is invisible to the serialized format.
tango_core.core.state_methods
¶
StateMethods — mixin providing recursive state-lifecycle operations.
Any class that either IS a *State/Stream-shaped leaf (its own
fields are LockedState) or CONTAINS such state (Component, which
holds state/outlet) inherits this mixin. Recursion targets are
found generically — by isinstance check against LockedState or
StateMethods — never by field name ("state") or class name
("...State"). This one mechanism (inheriting StateMethods) serves
as both "this class participates in state tracking" and "here is where
recursion should continue," with no separate naming convention or
field-attribute marker needed.
The lifecycle operations provided:
mark_fresh/check_and_reset— recursive freshness tracking, one set of names covering every nestedLockedState/StateMethodsfield.record(timestep)— pushes(state, history)pairs, honoringsave_intervalwhen present. Matches tango's existing name (every concreteComponent.record()already did this by hand before this mixin existed — see_state_history_pairs()).set_cumulative/reset_cumulative— no automatic derivation is possible here: accumulating a rate × dt into a running total needs physics-specific knowledge of which field is the rate and which is the total. The mixin's default only recurses; a leaf class with a genuine accumulator (e.g.LumpedReservoirState.energy_extracted) overrides it with real physics.
StateMethods
¶
Mixin providing recursive state-lifecycle operations. See module docstring.
mark_all_stale()
¶
Recursively mark every LockedState field stale.
Called by the orchestrator immediately before each solve() —
see Component.mark_all_stale()'s own docstring for the
write-slot lifecycle this opens.
mark_fresh()
¶
Recursively force every LockedState field fresh, without writing a new value.
See LockedState.mark_fresh()'s own docstring for when this is
the right call instead of update().
check_and_reset()
¶
Recursively assert every LockedState field is fresh, then mark it stale.
End-of-timestep validation: raises if any field was never written this cycle, catching a silently-skipped update rather than letting it carry a stale value into the next timestep unnoticed.
set_cumulative(dt)
¶
Update this instance's cumulative (rate × dt) fields, then recurse.
No-op at this level — see module docstring's SetCumulative
section. A leaf class with a genuine accumulator overrides this to
do the actual increment() call(s); this base implementation
only propagates to nested StateMethods fields, so overriding
classes should call super().set_cumulative(dt) too
(or recurse themselves) to keep propagation working.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
Length of the step being accumulated over (s). |
required |
reset_cumulative()
¶
Reset this instance's cumulative fields to zero, then recurse.
No-op at this level — see set_cumulative(). A leaf class with a
genuine accumulator overrides this to zero it (used when
re-running from t=0 without reconstructing the component).
is_recorded(timestep)
¶
Return whether record(timestep) pushes anything.
Honors self.save_interval if the attribute exists (None
disables recording entirely; otherwise records every Nth
timestep).
record(timestep)
¶
Push every (state, history) pair due this timestep (see is_recorded).
tango_core.core.specs
¶
Validated schemas for the top-level common:/layout:/sim_config: YAML blocks.
Every Component subclass is already its own schema (Pydantic fields,
extra="forbid") — these three classes give the same guarantee to the
top-level blocks. Unknown keys raise at load time rather than being
silently accepted and never read by anything.
economic: is deliberately NOT covered here: it's not a top-level
schema in the same sense as common:/layout:/sim_config: — it's
validated as a Component subclass in its own right
(DoubletEconomicComponent, components/economic/doublet.py), the same
way components: entries are, via Workflow._build_economic_component().
Common
¶
Bases: BaseModel
Schema for the common: YAML block — shared fluid/rock parameters.
A single Common instance is shared BY REFERENCE across every
component that needs it (Pydantic does not copy nested model fields on
construction — verified: well.common is reservoir.common is
True when both are built from the same instance). Frozen (whole
model): these values must stay fixed for a Workflow's lifetime. See
workflows/workflow.py for when it's fine to change them anyway
(rebuild a new Workflow from a modified dict).
fluid_name
instance-attribute
¶
Working fluid as a CoolProp fluid name, e.g. H2O or CO2.
rock_density
instance-attribute
¶
Rock density (kg/m3).
rock_cp
instance-attribute
¶
Rock specific heat capacity (J/(kg K)).
rock_k
instance-attribute
¶
Rock thermal conductivity (W/(m K)).
thermal_gradient
instance-attribute
¶
Geothermal gradient (K/m).
surface_temperature
instance-attribute
¶
Surface temperature (K): the ambient air temperature for cooling, and the top of the linear geotherm.
surface_pressure
instance-attribute
¶
Ambient surface pressure (Pa).
coolprop_backend = COOLPROP_BACKEND
class-attribute
instance-attribute
¶
CoolProp equation-of-state backend for all fluid-property lookups
(core/fluid_state.py's CoolPropBackend). Defaults to exact
HEOS; the faster tabulated BICUBIC&HEOS is unreliable near phase
boundaries (see its docstring).
saturation_margin = Field(default=0.05, ge=0.0, lt=1.0)
class-attribute
instance-attribute
¶
Minimum relative distance (fraction) between a well cell's pressure and the fluid's saturation pressure at that cell's temperature.
The well models assume single-phase flow, so a cell whose pressure lies
within saturation_margin * p_sat(T) of p_sat(T), on either side,
or inside the vapor-liquid dome, raises SaturationError. Only applies
below the fluid's critical temperature, where a saturation pressure
exists. 0 rejects only states that are actually two-phase.
The 5% default is engineering judgement: no published standard gives a margin to saturation for wells in this form. Related practice that motivated it: pump suction NPSH margin ratios of 1.1-1.3 (ANSI/HI 9.6.1, application-dependent), the margin to the saturation line kept at supercritical-CO2 compressor inlets (sized case by case, e.g. by inlet Mach number), and dense-phase CO2 pipelines operated well above their phase-change pressure.
check_rock_density(density)
classmethod
¶
Validate that rock_density is a physically plausible value.
rock_density is in kg/m^3 (SI, no unit suffix needed).
Hard check (raises ValueError): outside 1000-4000 kg/m^3 —
roughly water's density on the low end to the densest common
reservoir rock (e.g. basalt, ~3000 kg/m^3) with margin on the high
end. A value outside this range is almost certainly a units
mistake or a typo, not a real reservoir rock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_rock_heat_capacity(heat_capacity)
classmethod
¶
Validate that rock_cp (specific heat capacity) is plausible.
rock_cp is in J/(kg*K) (SI, no unit suffix needed).
Hard check (raises ValueError): outside 500-1500 J/(kgK) —
the typical range for common reservoir rock types (e.g. granite
~790, sandstone ~920, limestone ~880 J/(kgK)), with margin. A
value outside this range is almost certainly a units mistake or a
typo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
heat_capacity
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_rock_k(conductivity)
classmethod
¶
Validate that rock_k (thermal conductivity) is plausible.
rock_k is in W/(m*K) (SI, no unit suffix needed).
Hard check (raises ValueError): outside 0.1-6.0 W/(mK) —
the typical range for common reservoir rock types (e.g. shale
~1.5, sandstone ~3, quartzite ~6 W/(mK)), with margin. A value
outside this range is almost certainly a units mistake or a typo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conductivity
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_thermal_gradient(gradient)
classmethod
¶
Validate that thermal_gradient is positive and plausible.
thermal_gradient is in K/m (SI, no unit suffix needed) — e.g.
a real-world "35 degC/km" site is entered here as 0.035, NOT
35. The warning threshold below is stated in K/km (a more
intuitive unit for this quantity) purely for the log message, so
it converts gradient (K/m) to K/km via * 1000 before
comparing — do not compare gradient directly against a
K/km-scaled number, that silently makes the check unreachable for
any real input.
Hard check (raises ValueError): non-positive. A geothermal
reservoir requires a positive temperature gradient with depth by
definition.
Soft check (logs a warning, does NOT raise): equivalent to
200 K/km (> 0.2 K/m). Real geothermal gradients are typically 0.02-0.1 K/m (20-100 degC/km); anything above 200 K/km is either an exceptional site or, more likely, a units mistake (e.g. a K/km value entered directly instead of being converted to K/m).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradient
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_surface_temperature(te)
classmethod
¶
Validate that surface_temperature is a physically plausible value.
surface_temperature (and this validator's te parameter) is
in Kelvin — SI, so no unit suffix on the field name per this repo's
unit-suffix-naming convention (see CONTRIBUTING.md). The
error/warning messages below additionally show the Celsius
equivalent purely for human readability; the value itself is
always handled and returned in Kelvin, never converted.
Hard check (raises ValueError, construction fails): outside
204-330 K (-69.15 to 58.85 degC). This is a wide envelope around
the extremes of naturally-occurring ambient surface conditions on
Earth, with margin — a value outside it is almost certainly a
units mistake (e.g. a Celsius value entered where Kelvin is
expected) or a typo, not a real site's ambient temperature.
Soft check (logs a warning, does NOT raise — construction still succeeds): above 315 K (41.85 degC) or below 278 K (4.85 degC). Still physically plausible, but unusual enough for a geothermal site's ambient/surface temperature that it's worth a second look at the input rather than a hard failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
te
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_surface_pressure(pressure)
classmethod
¶
Validate that surface_pressure is a physically plausible value.
surface_pressure is in Pa (SI, no unit suffix needed).
Hard check (raises ValueError): outside 90000-108400 Pa —
roughly the range of sea-level-adjusted atmospheric pressure
recorded on Earth (extreme low/high weather systems), which also
comfortably covers any inhabited-elevation geothermal site. A
value outside this range is almost certainly a units mistake
(e.g. a kPa or bar value entered directly) or a typo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pressure
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Layout
¶
Bases: BaseModel
Schema for the layout: YAML block — well-field geometry.
well_spacing
instance-attribute
¶
Distance between the injection and production wells (m); for closed-loop AGS configs, the horizontal loop length.
well_pattern = None
class-attribute
instance-attribute
¶
Consumed by LumpedReservoir. Typed as WellPattern itself
(not str) so Pydantic's own enum coercion — via WellPattern's
case-insensitive _missing_ hook — validates/rejects the raw YAML
string before check_well_pattern below ever runs; that validator
only adds the "recognized but not yet implemented" check Pydantic's
own coercion can't. None for configs with no well-pattern-dependent
reservoir impedance (e.g. AGS_direct_heat.yml, which has no
reservoir component at all).
well_pattern_dimens = None
class-attribute
instance-attribute
¶
Not yet consumed — TODO add to wellpattern_impedance.py calculations
check_well_spacing(spacing)
classmethod
¶
Validate that well_spacing is a physically plausible value.
well_spacing is in m (SI, no unit suffix needed). Despite the
name, this field does double duty: for doublet/multi-well
reservoir patterns it's the true well-to-well spacing consumed by
LumpedReservoir via WellPattern; for closed-loop AGS
configs with no reservoir component at all (e.g.
AGS_direct_heat.yml), it's repurposed as the horizontal loop
length instead. The range below is wide enough to cover both uses.
Hard check (raises ValueError): outside 100-50000 m. A value
outside this range is almost certainly a units mistake or a typo,
not a real well spacing or loop length.
Soft check (logs a warning, does NOT raise): above 2000 m. Still plausible (long AGS loops legitimately run to several km), but unusual enough to be worth a second look.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spacing
|
float
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
check_well_pattern(pattern)
classmethod
¶
Validate that well_pattern names a pattern with an implemented formula.
By the time this runs, pattern is already either None or a
real WellPattern member — Pydantic coerces (or rejects) the raw
YAML string via WellPattern's own case-insensitive _missing_
hook as part of validating the field's WellPattern | None type,
before any field_validator sees it (field validators default to
mode="after", i.e. after type coercion). This validator only
adds the one check Pydantic's own enum coercion can't: rejecting a
real, recognized pattern that has no analytic impedance formula
implemented yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
WellPattern | None
|
Already-validated |
required |
Returns:
| Type | Description |
|---|---|
WellPattern | None
|
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
SimConfig
¶
Bases: BaseModel
Schema for the sim_config: YAML block.
num_tsteps = None
class-attribute
instance-attribute
¶
Number of timesteps in the run. Shorthand, together with
dt_years, for one fixed grid shared by every component; give either
the shorthand or time_stepping, not both.
dt_years = None
class-attribute
instance-attribute
¶
Length of one timestep (years), the shorthand's step. The one time
input not in seconds; it is converted to seconds once, in _shorthand(),
and nothing downstream sees years.
time_stepping = None
class-attribute
instance-attribute
¶
Per-subsystem time grids and the sync rules between them (see
tango_core.core.time_stepping), instead of the num_tsteps/
dt_years shorthand.
target_extraction_pressure
instance-attribute
¶
Minimum required extraction pressure at the surface inlet (Pa) — the
SINGLE shared source of this value. Threaded to any component
declaring a field of this exact name (SurfaceComponent,
pump-bearing production wells) via _build_components's
layout_extras mechanism, the same way well_spacing/dt_years
already are. Previously duplicated as two independently-set,
unvalidated copies (SurfaceComponent.target_extraction_pressure and
each pump-bearing well's own pump_target_pressure_megapascals) with
nothing enforcing they matched — a real Rule 5 ("shared via reference,
not separate copies that can drift") violation. See
docs/archive/bugs-fixed-in-tango.md.
injection_mode = None
class-attribute
instance-attribute
¶
Absent selects SystemDirect (no BC iteration); present selects SystemBCIteration.
mass_rate = None
class-attribute
instance-attribute
¶
Mass flow rate (kg/s), used every timestep. Required whenever injection_mode is present.
bc_checkpoint_idx = None
class-attribute
instance-attribute
¶
Required when injection_mode is present.
end
property
¶
Project lifetime (s): where the run's grids end.
check_dt_years(dt)
classmethod
¶
Validate that dt_years (timestep size) is positive.
dt_years is in years (this field is the one deliberate
exception to the "no unit suffix on SI fields" convention — years
is the natural, human-scale unit for a geothermal timestep, not
seconds).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float | None
|
Candidate |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
reject_removed_injection_modes(value)
classmethod
¶
Explain the removed automatic modes instead of a bare "invalid enum value".
Raises:
| Type | Description |
|---|---|
ValueError
|
|
check_time_steps_given_once()
¶
Require exactly one of the num_tsteps/dt_years shorthand and time_stepping.
Returns:
| Type | Description |
|---|---|
SimConfig
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Both are given, neither is, the shorthand is only
half given, or |
time_stepping_for(component_names)
¶
The run's TimeStepping: the configured block, or the shorthand as one subsystem.
The shorthand becomes a single subsystem, all, holding every
component on one fixed grid of num_tsteps steps of dt_years,
so the orchestrators have one code path for both.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component_names
|
list[str]
|
Every circuit component's name, as keyed under
|
required |
check_injection_mode_requirements()
¶
Require bc_checkpoint_idx and mass_rate whenever injection_mode is set.
injection_mode absent means SystemDirect (no BC iteration),
which needs neither.
Returns:
| Type | Description |
|---|---|
SimConfig
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Description
¶
Bases: BaseModel
Schema for the optional top-level description: YAML block.
Entirely optional — a config that omits description: is unaffected
(see Workflow.__init__); this only validates the block when it's
present. Meant to answer, for whoever reads this config next without
any other context:
summary— one line, whatever makes this file's purpose recognizable in a directory listing (required if the block is present at all; the whole point of the block is defeated by an empty one-liner).author/date— optional attribution/provenance: who wrote this config and when. Deliberately plain, unvalidated strings (e.g."2026-09"or"Chad Baker"are both fine) rather than a strictly-typed date/name field — this is documentation, not a data field anything downstream computes from, so validating its format would add friction without adding safety.description— free text answering What (what physical system is being modeled, e.g. "double-flash power plant, Triemli site"), Why (why this particular run/config exists, e.g. "baseline for the opt_hydro_df_electric search"), and How (components, models, assumptions, whether there's an optimization loop, compute requirements) — whatever of those is relevant; not all three sections are mandatory for every config.
Example::
description:
summary: Baseline single-flash config for the Triemli site
author: Chad Baker
date: "2026-09-18"
description: >
Manual mass-flow-rate single-flash system, the unmodified
starting point for studies of the Triemli site.
summary
instance-attribute
¶
One-line purpose of the config.
author = None
class-attribute
instance-attribute
¶
Who wrote the config.
date = None
class-attribute
instance-attribute
¶
When the config was written, as free text.
description = ''
class-attribute
instance-attribute
¶
Free text: what is modeled, why the config exists and how.
tango_core.core.policies
¶
Injection control policies for tango BC iteration.
InjectionPolicy
¶
Bases: StrEnum
Whether each timestep is checked against the reservoir's fracking limit.
The reservoir has one fracking limit: its pressure must stay below
hydrostatic_P × (1 + overpressure%/100), i.e. at most
ΔP_allowed = hydrostatic_P × overpressure% / 100 above hydrostatic.
MANUAL_FRACKING_CHECK tests that limit two ways, since either can
exceed it:
- Pressure — the injection well's outlet pressure (wellhead pressure plus hydrostatic head minus friction) is above the limit.
- Flow — the mass rate is above the rate whose Darcy pressure rise
across the reservoir equals
ΔP_allowed:
fracking_flow = 2πhk · ΔP_allowed / (μ · ln(re/rw))
Mass flow rate and injection wellhead pressure are always taken from the config; the policy only decides whether the result is checked.
No automatic modes. Earlier versions also had auto-pressure,
auto-flow and auto-both, which iterated the injection pressure
and/or flow rate toward a fracking threshold inside each timestep. They
were removed in October 2026: a fracking-limited operating point is only
one point of the real question (which pressure and flow give the best
LCOE/power trade-off), the iteration proved brittle (auto-pressure
could cycle without converging), and auto-both was never
implemented. To find good operating points, run the multi-objective
searches in applications/opt_*/, which use manual-fracking-check
and treat a fracking violation as an infeasible design.
YAML field: sim_config.injection_mode (kebab-case string, e.g.
injection_mode: manual-fracking-check).
__new__(value, doc='')
¶
Construct an enum member with an optional per-member docstring.
MainProduct
¶
Bases: StrEnum
Which output an EconomicComponent treats as the plant's primary product.
Determines the denominator in the levelized-cost calculation: net
electric power for ELECTRICITY (LCOE), net thermal power for
HEAT (LCOH). Both use the same formula —
CAPEX * (CRF + F_OM) / (product_power * W_TO_KW * CF * YEAR_TO_HOUR)
— only the power term differs, so this does not need a second enum
per formula, just a branch on which surface-component output to sum.
YAML field: economic.main_product (e.g. main_product: heat).
A real enum rather than a raw string comparison, to avoid the
silent-failure modes a stringly-typed field invites — see
docs/archive/bugs-fixed-in-tango.md's "== \"yes\" string-comparison
trap" section for an example of that failure mode.
ProjectMaturity
¶
Bases: StrEnum
Whether a geothermal project's wells already exist (BROWN_FIELD)
or must still be drilled/permitted/explored (GREEN_FIELD).
GREEN_FIELD includes injection-well, permitting, and exploration
CAPEX; BROWN_FIELD zeroes all three (existing infrastructure reused,
only production wells/surface plant/pipes are new spend) — a real
~30%+ swing on total CAPEX, not a cosmetic distinction.
YAML field: economic.project_maturity.
A real enum for the same reason as MainProduct, above.
ComponentRole
¶
Bases: StrEnum
Tags a graph-surface TESPy node's output for aggregation into plant totals.
Deliberately explicit per-node rather than inferred from TESPy component
type: a SimpleHeatExchanger might be a condenser you reject heat
through (not a product) or a district-heating exchanger whose output
is the product — inferring from type alone would silently misclassify
one of them. A node with no role is still solved as part of the network,
just not summed into either total.
solve() sums -P.val (uniformly negated, no per-type branch) over
NET_ELECTRIC nodes and -Q.val over NET_THERMAL nodes, writing
state.net_power_W/state.net_thermal_W. The uniform negation
happens to land on the physically correct sign for every node type
without a branch, because TESPy's own raw sign convention already
differs by type — confirmed empirically (hydro_df_electric.yml's
topology): Turbine.P.val is negative (generates/removes energy),
Compressor.P.val is positive (consumes/adds energy) — so negating
both makes a turbine add to net power and a pump subtract from it, with
no isinstance check needed. Do not assume this sign is a stable
physical constant if porting a cost or power formula from elsewhere
that reads raw P.val directly — it's a wiring-convention artifact
of how each TESPy network happens to be built, not a TESPy-wide
guarantee; verify the sign for the specific network being ported
rather than assuming it matches. EconomicComponent.main_product
(see MainProduct above) picks which of the two totals feeds LCOE/LCOH.
YAML field: power_plant.nodes.<name>.role (optional; omit for
internal-only components like valves, separators, condensers).
tango_core.core.fluid_state
¶
FluidState — thin CoolProp wrapper for tango.
A thin wrapper around CoolProp's AbstractState, covering PT/HP/PS
construction, in-place update, and the property accessors used by the
discretized wellbore models and isentropic-efficiency pump/compressor
calcs. Extend as additional components need more CoolProp input pairs
(PQ, QT, ...).
Every CoolProp failure is wrapped as CoolPropError (see core/errors.py)
so callers can identify a property-lookup failure without parsing traceback
strings or catching CoolProp's own exception type directly.
COOLPROP_BACKEND = CoolPropBackend.HEOS
module-attribute
¶
Default CoolProp backend for common.coolprop_backend (see
core/specs.py's Common model) when a YAML config doesn't set it
explicitly. Anywhere else a fluid backend needs naming explicitly (e.g.
TESPy's Connection.set_attr(fluid=...) in components/surface/graph.py)
should read it from common.coolprop_backend, not this constant directly,
so a config's override is actually honored.
CoolPropBackend
¶
Bases: StrEnum
Selects which CoolProp equation-of-state backend tango uses for fluid property lookups.
YAML field: common.coolprop_backend (defaults to HEOS if
omitted — see BICUBIC_HEOS's docstring for why the faster tabular
backend is not the default).
BICUBIC_HEOS = 'BICUBIC&HEOS'
class-attribute
instance-attribute
¶
BICUBIC-tabulated HEOS: interpolates properties from a table instead of solving the equation of state, roughly halving CoolProp call time versus raw HEOS, with ~3e-5 relative error away from phase boundaries. Not the default because its (P, T) lookups are unreliable near phase boundaries, and TESPy trusts them without checking:
- Near the critical point the table cells are coarse (CoolProp's docs cite ~14 K cell width for CO2): a fixed 315 K CO2 target solved to ~305.3 K at a nearby operating point.
- Just below saturation, a (P, T) flash can return an enthalpy on the
wrong side of the saturation curve. For R245fa 1 K below saturation it
returns 343.7 kJ/kg at 0.14 MPa and 257.5 kJ/kg at 0.145 MPa against
the exact 229.6 and 230.8 kJ/kg, so a
subcooling_Kcondenser outlet comes out as a two-phase mixture and its pump compresses wet vapor, while the TESPy solve still reports convergence. Errors depend on where the pressure falls in the table, so a pressure that works says nothing about its neighbors.
Use only for a system known to stay well away from phase boundaries,
after checking its results against HEOS.
HEOS = 'HEOS'
class-attribute
instance-attribute
¶
Raw (non-tabulated) HEOS — solves the actual equation of state
directly, no interpolation-table error, at roughly 1.4-2.2x the runtime
of BICUBIC_HEOS for the templates. Default.
FluidState(fluid_name, backend=COOLPROP_BACKEND)
¶
Wraps a CoolProp AbstractState for one fluid, at a configurable backend.
Construct an uninitialized state for fluid_name; call an update_/with_ method next.
P
property
¶
Pressure (Pa).
T
property
¶
Temperature (K).
H
property
¶
Specific enthalpy (J/kg).
S
property
¶
Specific entropy (J/(kg·K)).
rho
property
¶
Density (kg/m³).
mu
property
¶
Dynamic viscosity (Pa·s).
cp
property
¶
Isobaric specific heat capacity (J/(kg·K)).
T_critical
property
¶
Critical temperature (K) of the fluid.
is_two_phase
property
¶
Whether the state lies inside the vapor-liquid dome (0 < quality < 1).
with_PT(fluid_name, P, T, backend=COOLPROP_BACKEND)
staticmethod
¶
Construct a FluidState from pressure (Pa) and temperature (K).
with_HP(fluid_name, H, P, backend=COOLPROP_BACKEND)
staticmethod
¶
Construct a FluidState from specific enthalpy (J/kg) and pressure (Pa).
with_PS(fluid_name, P, S, backend=COOLPROP_BACKEND)
staticmethod
¶
Construct a FluidState from pressure (Pa) and specific entropy (J/(kg·K)).
Used for isentropic-efficiency pump/compressor models: the isentropic outlet state at a target pressure, given the inlet state's entropy.
with_PQ(fluid_name, P, Q, backend=COOLPROP_BACKEND)
staticmethod
¶
Construct a saturated FluidState from pressure (Pa) and vapor mass fraction Q (0 = liquid, 1 = vapor).
copy(other)
staticmethod
¶
Construct a new FluidState with the same fluid, backend, and (P, T) as other.
update_PT(P, T)
¶
Update this state in place from pressure (Pa) and temperature (K).
update_HP(H, P)
¶
Update this state in place from specific enthalpy (J/kg) and pressure (Pa).
update_PQ(P, Q)
¶
Update this state in place to saturation at pressure (Pa), with vapor mass fraction Q.
update_PS(P, S)
¶
Update this state in place from pressure (Pa) and specific entropy (J/(kg·K)).
saturation_pressure(T)
¶
Saturation (bubble-point) pressure (Pa) at temperature T, below the critical temperature.
tango_core.core.fluid_utils
¶
Shared hydraulic and fluid-property utilities for tango.
All functions are stateless, SI units throughout, and intentionally single-purpose so they can be reused across well, reservoir, and surface components without copy-pasting formulas.
Unit conventions¶
- Pressures : Pa
- Temperatures: K
- Lengths : m
- Mass flows : kg/s
- Densities : kg/m³
- Viscosities : Pa·s
- Velocities : m/s
pipe_area(diameter)
¶
Cross-sectional flow area of a circular pipe (m²).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diameter
|
float
|
Inner diameter (m). |
required |
mean_velocity(mass_rate, rho, diameter)
¶
Mean flow velocity in a full circular pipe (m/s).
v = ṁ / (ρ · A)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mass_rate
|
float
|
Mass flow rate (kg/s). |
required |
rho
|
float
|
Fluid density (kg/m³). |
required |
diameter
|
float
|
Pipe inner diameter (m). |
required |
reynolds_number(mass_rate, diameter, mu)
¶
Reynolds number for internal pipe flow (dimensionless).
Re = 4ṁ / (π·D·μ)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mass_rate
|
float
|
Mass flow rate (kg/s). |
required |
diameter
|
float
|
Pipe inner diameter (m). |
required |
mu
|
float
|
Dynamic viscosity (Pa·s). |
required |
friction_factor_darcy(Re, diameter, roughness)
¶
Darcy–Weisbach friction factor via Swamee–Jain explicit approximation.
Laminar (Re < 2300) : f = 64 / Re Transition (2300 ≤ Re < 4000): laminar value used conservatively Turbulent (Re ≥ 4000) : Swamee–Jain (explicit Colebrook–White)
References:¶
Colebrook (1939) and Swamee & Jain (1976); see docs/SOURCES.md#colebrook1939 and docs/SOURCES.md#swameejain1976. (Error < 3 % vs. iterative Colebrook–White for Re 5×10³–10⁸, ε/D 10⁻⁶–10⁻².)
Human review needed: before using results that depend on this function for engineering decisions, verify against a trusted reference implementation or published table.
TODO: implement proper laminar–turbulent blending in transition regime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Re
|
float
|
Reynolds number (dimensionless). |
required |
diameter
|
float
|
Pipe inner diameter (m). |
required |
roughness
|
float
|
Absolute pipe-wall roughness (m). |
required |
friction_factor_haaland(Re, diameter, roughness)
¶
Darcy–Weisbach friction factor via the Haaland explicit approximation.
1/sqrt(f) = -1.8 log10[ (r/3.7)^1.11 + 6.9/Re ], r = roughness / diameter
Use this (not friction_factor_darcy's Swamee–Jain approximation)
for the discretized wellbore models, which are pinned to this variant.
Reference:¶
Haaland (1983); see docs/SOURCES.md#haaland1983.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Re
|
float
|
Reynolds number (dimensionless). |
required |
diameter
|
float
|
Pipe inner diameter (m). |
required |
roughness
|
float
|
Absolute pipe-wall roughness (m). |
required |
pressure_drop_friction(friction_factor, length, diameter, rho, velocity)
¶
Frictional pressure loss via Darcy–Weisbach (Pa), always ≥ 0.
ΔP_f = f · (L/D) · (ρ·v²/2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
friction_factor
|
float
|
Darcy friction factor (dimensionless). |
required |
length
|
float
|
Pipe segment length (m). |
required |
diameter
|
float
|
Pipe inner diameter (m). |
required |
rho
|
float
|
Fluid density (kg/m³). |
required |
velocity
|
float
|
Mean flow velocity (m/s). |
required |
hydrostatic_pressure(rho, delta_depth, gravity=GRAVITY)
¶
Hydrostatic pressure difference over a vertical depth interval (Pa).
ΔP_hydro = ρ · g · Δdepth (positive for downward Δdepth)
This is a change in depth, not an absolute depth from surface. Pass the well-segment length for a single-segment wellbore model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rho
|
float
|
Fluid density (kg/m³). |
required |
delta_depth
|
float
|
Vertical depth interval (m), positive downward. |
required |
gravity
|
float
|
Gravitational acceleration (m/s²) — defaults to
core/constants.py's GRAVITY; pass the calling component's own
|
GRAVITY
|
heat_loss_zhang_2011(dL, rock_k, t_d, delta_T)
¶
Transient conductive heat loss for one wellbore cell (W).
Q_loss = 2π · dL · k_rock · β(t_d) · ΔT
where β is a dimensionless heat-transfer-efficiency coefficient for the surrounding rock — large at small t_d (only the rock immediately at the wellbore wall has been thermally disturbed, so it still conducts heat to/from the wellbore readily) and shrinking as t_d grows (the thermally-disturbed zone widens, so further exchange must conduct through progressively more already-equilibrated, effectively more insulating rock), based on dimensionless time t_d:
β = (π·t_d)^-0.5 + 0.5 - 0.25·(t_d/π)^0.5 + 0.125·t_d, t_d ≤ 2.8
β = 2 / (ln(4·t_d) - 2γ) - 2γ / (ln(4·t_d) - 2γ)², t_d > 2.8
where γ is the Euler-Mascheroni constant (core/constants.py's
EULER_CONSTANT — EULER_CONSTANT_X2 is 2γ). (Zhang et al.'s
own Eq. 2 shows γ, not 2γ, in the second term's numerator —
not a discrepancy: they keep a 2k/r₀ prefactor outside their
f2, whereas β here already folds that factor of 2 in, since
Q_loss = 2π·k_rock·β·ΔT applies it directly. Algebraically
identical, just factored differently.)
References:¶
β and its two-regime piecewise form (Eqs. 1–2) originate with Zhang et al. (2011); see docs/SOURCES.md#zhang2011. This implementation's exact form matches Eqs. S65–S66 of Adams et al. (2021), Supplemental Information §S6; see docs/SOURCES.md#adams2021gengeo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dL
|
float
|
Axial cell length (m). |
required |
rock_k
|
float
|
Surrounding rock thermal conductivity (W/(m·K)). |
required |
t_d
|
float
|
Dimensionless time (dimensionless). |
required |
delta_T
|
float
|
Temperature difference, fluid minus far-field rock (K). |
required |
fluid_density(fluid_name, T, P, backend=COOLPROP_BACKEND)
¶
Fluid density (kg/m³) via CoolProp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fluid_name
|
str
|
CoolProp fluid name (e.g. |
required |
T
|
float
|
Temperature (K). |
required |
P
|
float
|
Pressure (Pa). |
required |
backend
|
str
|
CoolProp backend (see |
COOLPROP_BACKEND
|
fluid_viscosity(fluid_name, T, P, backend=COOLPROP_BACKEND)
¶
Fluid dynamic viscosity (Pa·s) via CoolProp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fluid_name
|
str
|
CoolProp fluid name (e.g. |
required |
T
|
float
|
Temperature (K). |
required |
P
|
float
|
Pressure (Pa). |
required |
backend
|
str
|
CoolProp backend (see |
COOLPROP_BACKEND
|
fluid_enthalpy(fluid_name, T, P, backend=COOLPROP_BACKEND)
¶
Fluid specific enthalpy (J/kg) via CoolProp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fluid_name
|
str
|
CoolProp fluid name (e.g. |
required |
T
|
float
|
Temperature (K). |
required |
P
|
float
|
Pressure (Pa). |
required |
backend
|
str
|
CoolProp backend (see |
COOLPROP_BACKEND
|
fluid_cp(fluid_name, T, P, backend=COOLPROP_BACKEND)
¶
Fluid isobaric specific heat capacity (J/(kg·K)) via CoolProp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fluid_name
|
str
|
CoolProp fluid name (e.g. |
required |
T
|
float
|
Temperature (K). |
required |
P
|
float
|
Pressure (Pa). |
required |
backend
|
str
|
CoolProp backend (see |
COOLPROP_BACKEND
|
target_reservoir_pressure(hydro_static_pressure, over_pressure_percentage)
¶
Pressure-induced fracking threshold at the reservoir inlet (Pa).
target_reservoir_P = hydro_static_pressure × (1 + over_pressure_percentage / 100)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hydro_static_pressure
|
float
|
Nominal hydrostatic pressure at reservoir
depth (Pa) — |
required |
over_pressure_percentage
|
float
|
Allowed over-pressure as a percentage of
hydrostatic pressure (%) — |
required |
fracking_flow(thickness, permeability, hydro_static_pressure, over_pressure_percentage, well_spacing, wellbore_diameter, mu, rho)
¶
Flow-induced fracking threshold mass rate (kg/s).
q = 2·π·h·k·ΔP / (μ · ln(r_res / r_well)) (volumetric flow, m³/s) ΔP = over_pressure_percentage / 100 × hydro_static_pressure r_res = well_spacing / 2 (effective reservoir radius) r_well = wellbore_diameter / 2 (wellbore radius) m = ρ · q (mass flow, kg/s)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
thickness
|
float
|
Reservoir thickness (m) — |
required |
permeability
|
float
|
Reservoir permeability (m²) —
|
required |
hydro_static_pressure
|
float
|
Nominal hydrostatic pressure at reservoir
depth (Pa) — |
required |
over_pressure_percentage
|
float
|
Allowed over-pressure as a percentage of
hydrostatic pressure (%) —
|
required |
well_spacing
|
float
|
Injector-to-producer spacing (m) — half of this is
used as the effective reservoir radius |
required |
wellbore_diameter
|
float
|
Injection well diameter (m) —
|
required |
mu
|
float
|
Fluid dynamic viscosity (Pa·s) at the injection well outlet —
see |
required |
rho
|
float
|
Fluid density (kg/m³) at the injection well outlet — see
|
required |
tango_core.core.physics_models
¶
Selectable physics-model enums and dispatch functions for tango.
Several physical phenomena have multiple competing correlations in the
literature (e.g. friction factor, wellbore heat loss). Rather than hardcoding
one choice per component, each such phenomenon gets a StrEnum (selectable
via a YAML spec field, default matching whatever was already implemented) and
a dispatch function here that maps the enum value to the underlying formula
in core/fluid_utils.py.
To add a new variant of an existing model: add the formula to
fluid_utils.py, add an enum member here, and add a branch to the
corresponding dispatch function. To add an entirely new selectable model
(e.g. a future reservoir-flow model choice): follow this same pattern with a
new enum + dispatch function, rather than hardcoding the choice in the
component.
FrictionModel
¶
Bases: StrEnum
Selects which Darcy-Weisbach friction-factor correlation to use.
HAALAND = 'haaland'
class-attribute
instance-attribute
¶
Haaland (1983) explicit approximation (docs/SOURCES.md#haaland1983). Default; the discretized wellbore models are pinned to this variant.
SWAMEE_JAIN = 'swamee-jain'
class-attribute
instance-attribute
¶
Swamee-Jain (1976) explicit approximation (docs/SOURCES.md#swameejain1976) — see fluid_utils.friction_factor_darcy's docstring for the "human review needed" caveat.
HeatTransferModel
¶
Bases: StrEnum
Selects which wellbore radial heat-loss correlation to use.
ZHANG_2011 = 'zhang-2011'
class-attribute
instance-attribute
¶
Zhang et al. (2011) transient conductive heat-loss correlation (dimensionless-time beta). Default.
See docs/SOURCES.md#zhang2011 and fluid_utils.heat_loss_zhang_2011.
NONE = 'none'
class-attribute
instance-attribute
¶
Perfectly insulated wellbore — zero heat loss. Matches the simplification used by LumpedInjectionWell / LumpedProductionWell.
compute_friction_factor(model, Re, diameter, roughness)
¶
Dispatch to the friction-factor formula selected by model.
compute_heat_loss(model, *, dL, rock_k, t_d, delta_T)
¶
Dispatch to the wellbore heat-loss formula selected by model (W).
tango_core.core.numerics
¶
Small, dependency-free numerical root-finding helpers for tango.
Kept separate from any one component so multiple components can share the same convergence contract (real tolerance check, no fixed iteration count) without duplicating the loop itself.
secant_solve(residual, x0, x1, tol, max_iter, error_context)
¶
Find a root of residual via the secant method.
Evaluates residual(x0)/residual(x1) first — if x1 already
satisfies tol, returns immediately without computing a third point.
Otherwise iterates the standard secant update
x_{n+1} = x_n - f(x_n) * (x_n - x_{n-1}) / (f(x_n) - f(x_{n-1}))
until convergence or max_iter is exhausted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residual
|
Callable[[float], float]
|
|
required |
x0
|
float
|
First initial guess. |
required |
x1
|
float
|
Second initial guess (should differ meaningfully from |
required |
tol
|
float
|
Convergence tolerance on |
required |
max_iter
|
int
|
Maximum number of ADDITIONAL evaluations beyond the initial
|
required |
error_context
|
str
|
Prefix for the |
required |
Raises:
| Type | Description |
|---|---|
ConvergenceError
|
If |
tango_core.core.accelerators
¶
Defines series acceleration functions and classes that can be imported into difference functions
Keeping with the modular philosophy of Tango, however once tango is in production this may be deemed an unecessary module (i.e. just code the aitkens function where it is needed!)
aitken_relax(iteration, x_tilde, x_prev, r_prev, delta_prev, init_relax=1, min_relax=0.001, max_relax=1000)
¶
Scalar Aitken (Irons-Tuck) relaxation for a fixed-point iteration x_tilde = f(x_prev).
Inputs
iteration : 0-based counter within this fixed-point loop x_tilde : raw, un-relaxed new value g(x_prev) x_prev : previously accepted (already relaxed) value r_prev : residual from the previous call (None on iteration 0) delta_prev : relaxation factor used on the previous call (None on iteration 0) init_relax : relaxation factor to use before there's any history bounds : (min, max) magnitude clip on the relaxation factor
Outputs
x_new: aitkens series term r_new: residual of x_tilde (x_n+1) and x_prev (x_n) entered delta_prev: previous update delta
Example
no_iters = 10
r_prev = None delta_prev = None
x_np1 = f(x_n)
for i in range(no_iters): x_new, r_prev, delta_prev = aitken(iteration=i,x_tilde=x_np1,x_prev=x_n,r_prev=r_prev,delta_prev=delta_prev,init_relax=1,bounds=(0.001,1000)) x_n = x_np1 x_np1 = f(x_new) #Feeding the result of Aitken's straight back into the fixed point function is technically called Steffensen's method
Reference See Aitken's Method wikipedia: https://en.wikipedia.org/wiki/Aitken%27s_delta-squared_process
tango_core.core.errors
¶
Custom exceptions for tango.
TangoError
¶
Bases: Exception
Base class for all tango errors.
ConvergenceError
¶
Bases: TangoError
Raised when an iterative solver fails to converge within its iteration budget.
ComponentSolveError
¶
Bases: TangoError
Raised when a component's solve() encounters an unrecoverable error.
SaturationError
¶
Bases: TangoError
Raised when a fluid state unexpectedly enters or approaches a two-phase region.
The well models assume single-phase flow (their friction and heat-loss correlations don't apply to a boiling mixture), so a well cell whose state falls inside the vapor-liquid dome raises this instead of silently marching on with mixture properties.
WellPressureCollapseError
¶
Bases: TangoError
Raised when a well's pressure falls to zero or below while marching along it.
The flow can't be pushed (or lifted) through the well at this mass rate:
friction and the hydrostatic column take more pressure than the well's
inlet provides. An infeasible design, not a bug. A hot liquid usually
hits SaturationError first, on its way down through its saturation
pressure; this covers a cell step that jumps straight past it, and
fluids above their critical temperature, which have no saturation
pressure.
ConfigError
¶
Bases: TangoError
Raised when an input configuration is invalid or inconsistent.
InertParameterError
¶
Bases: ConfigError
Raised when an optimization decision variable has no effect on any objective or constraint.
Perturbing the parameter up and down from its baseline left every
objective and constraint unchanged, so the search would spend a whole
dimension on it for nothing. Usually a ParamSpec.apply that writes a
config field nothing reads, or a field that is inert for this topology.
A ConfigError, so an optimizer never mistakes it for an infeasible
design.
FrackingViolationError
¶
Bases: TangoError
Raised when injection would exceed a hydraulic-fracking threshold.
Covers both mechanisms InjectionPolicy distinguishes (see
core/policies.py): flow-induced (mass rate too high) and
pressure-induced (wellhead pressure too high after hydrostatic head and
friction losses). Catch this specifically to distinguish "the reservoir
would be damaged by this injection schedule" from any other simulation
failure (e.g. a fluid-property lookup error or non-convergence).
Deliberately raised rather than silently capping the offending value down to a safe threshold: a silent correction would let a caller mistake a corrected-but-different run for the one they actually asked for, with no signal that anything was adjusted. Surfacing it as an explicit, specifically-typed error keeps that decision visible and in the caller's hands.
InvalidPowerStateError
¶
Bases: TangoError
Raised when a component reports a power value that is physically invalid.
Covers two known-fragile spots near a design's feasibility boundary:
a passive downhole pump reporting negative power draw (pump_power_watts
< 0 — a pump cannot generate power), and a surface plant reporting
negative net electric output for a timestep (net_power_W < 0 fed into
an averaged economic calculation). Both were observed silently producing
a deceptively low LCOE (a negative pump term was fed into
DoubletEconomicComponent._read_net_power unclamped, flipping a
subtraction into an addition) rather than an explicit failure. Deliberately
raised rather than clamped to zero, for the same reason as
FrackingViolationError: a silent correction would let a caller mistake
a corrected-but-different run for the one they actually asked for.
ValveCannotRaisePressureError
¶
Bases: InvalidPowerStateError
Raised when a circulation valve would have to raise pressure to meet its target.
A valve is passive and can only drop pressure; the plant's natural
driving force falls short, so a pump is needed there. For a PumpOrValve
node, GraphSurface retries with the node as a pump on this error. Other
InvalidPowerStateError cases (e.g. a different pump in the plant
reporting negative power) are not about the circulation device and are
raised as they are.
NegativeNetPowerError
¶
Bases: InvalidPowerStateError
Raised when a power plant with a turbine is a net consumer of electricity.
The turbine's output no longer covers the plant's own pump load, e.g.
once the reservoir has cooled. GraphSurface.record() checks it once
per timestep on the converged state, not on every solve: the
injection-enthalpy iteration's first passes start from a cold seed and
can be briefly negative before the loop converges.
NegativeNetThermalError
¶
Bases: InvalidPowerStateError
Raised when a heat plant delivers no heat: its net thermal output is negative.
The produced fluid has cooled so far (e.g. once the reservoir is
depleted) that the heat exchangers tagged role: net_thermal would
have to heat it instead of taking heat from it. Such a plant has
nothing to sell, so the design is infeasible. GraphSurface checks it
once per timestep, on the converged state.
PassivePressureRiseError
¶
Bases: InvalidPowerStateError
Raised when a passive surface-plant component raises its fluid's pressure.
Heat exchangers, valves, separators, mixers and cycle closers do no
work, so pressure can only fall (or stay level) across them. TESPy
solves such a network anyway when a component has a fixed absolute
outlet pressure above what actually arrives at its inlet: the
component compresses the fluid for free, and the pump work that rise
would really cost is never charged. A subclass of
InvalidPowerStateError because the result is the same kind of
error, uncharged work, and so that an optimizer treats it as an
infeasible design point.
CoolingLimitError
¶
Bases: TangoError
Raised when a surface-plant component cools its fluid below what the site can reject heat to.
Heat rejected to the environment needs a heat sink colder than the fluid
leaving the cooler or condenser by at least the approach temperature, so
no outlet can be colder than surface_temperature +
approach_temperature. TESPy solves a fixed outlet state below that
limit without complaint, as if free refrigeration were available, which
overstates the turbine's expansion and the plant's output. Treated as an
infeasible design by an optimizer.
CoolPropError
¶
Bases: TangoError
Wraps a CoolProp failure raised by our own direct property lookup.
Callers at any layer of the stack can except CoolPropError to know
immediately that a fluid-property lookup is in the error chain, rather
than catching a bare ValueError or CoolProp's own internal exception
type. See core/fluid_state.py for where this is raised.
For a CoolProp failure that surfaces through TESPy (TESPy calls
CoolProp internally during its network solve), use
TESPyCoolPropError instead — it subclasses both this class and
TESPyError so it's catchable either way.
TESPyError
¶
Bases: TangoError
Wraps a failure raised by the TESPy network solver itself.
Use this for TESPy failures unrelated to fluid-property lookups (e.g.
network non-convergence, infeasible component specification). If the
root cause is a CoolProp property lookup failing inside a TESPy solve,
raise TESPyCoolPropError instead so it's still catchable as a
CoolProp-rooted error.
GraphSurface raises the subclasses TESPyConvergenceError (the
solve didn't converge) and TESPyCoolPropError (a property lookup
failed inside the solve).
TESPyConvergenceError
¶
Bases: TESPyError, ConvergenceError
Raised when a TESPy network solve returns without converging.
TESPy's Network.solve() returns normally when it stops short of its
convergence tolerance, leaving outlet values that may be wrong. A
subclass of ConvergenceError too, so an optimizer treats it as an
infeasible design point.
TESPyCoolPropError
¶
Bases: TESPyError, CoolPropError
Wraps a CoolProp failure that surfaced through a TESPy network solve.
Inherits from both TESPyError and CoolPropError so callers can
catch either: except TESPyError to catch any TESPy-related failure,
or except CoolPropError to catch any CoolProp-rooted failure
regardless of whether it was raised directly or via TESPy.
LockedStateError
¶
Bases: TangoError
Base class for all LockedState contract violations.
StaleAccessError
¶
Bases: LockedStateError
Raised by LockedState.get_fresh() when the field has not been set yet this timestep.
FreshAccessError
¶
Bases: LockedStateError
Raised by LockedState.get_stale() when the field has already been updated this timestep.
DoubleWriteError
¶
Bases: LockedStateError
Raised by LockedState.set() when the field has already been set once this timestep.
tango_core.core.constants
¶
Physical constants and SI prefix scalars for tango.
Unit conversions should be expressed as named constants imported from here, not as magic numbers inline. For example::
p_megapascals = p_pascals * PA_TO_MPA
p_kilopascals = p_megapascals * MEGA_TO_KILO
SI prefix multipliers¶
KILO = 1e3 (k) MEGA = 1e6 (M) GIGA = 1e9 (G) MILLI = 1e-3 (m) MICRO = 1e-6 (μ)
Derived ratio scalars (convenient shorthand)¶
MEGA_TO_KILO = 1e3 (e.g. MPa → kPa) PA_TO_MPA = 1e-6 MPA_TO_PA = 1e6 PA_TO_KPA = 1e-3 PA_TO_BAR = 1e-5 BAR_TO_PA = 1e5 W_TO_KW = 1e-3 W_TO_MW = 1e-6 KJ_PER_KG_TO_J_PER_KG = 1e3 J_PER_KG_TO_KJ_PER_KG = 1e-3
Temperature offsets (additive, not multiplicative)¶
C_TO_K_OFFSET = 273.15 (degC + C_TO_K_OFFSET -> K) K_TO_C_OFFSET = -273.15 (K + K_TO_C_OFFSET -> degC)
Time¶
YEAR_TO_HOUR = 8760.0 (hours per 365-day year)
GRAVITY = 9.81
module-attribute
¶
Gravitational acceleration (m/s²), rounded to 9.81.
This is a default: well and reservoir components have their own gravity
field, which overrides it, since gravity varies regionally by up to about
0.5%. The standard value (ISO 80000-3) is 9.80665; the golden LCOE values
in the regression tests are computed with 9.81.
YEAR_TO_SECOND = 31536000.0
module-attribute
¶
Seconds per (365-day) year. Used in dimensionless-time calculations (e.g. wellbore heat-loss models).
MEGA_TO_KILO = 1000.0
module-attribute
¶
Multiply a value in mega-units to get kilo-units (e.g. MPa → kPa).
PA_TO_MPA = 1e-06
module-attribute
¶
Multiply Pa to get MPa.
MPA_TO_PA = 1000000.0
module-attribute
¶
Multiply MPa to get Pa.
PA_TO_KPA = 0.001
module-attribute
¶
Multiply Pa to get kPa.
PA_TO_BAR = 1e-05
module-attribute
¶
Multiply Pa to get bar.
BAR_TO_PA = 100000.0
module-attribute
¶
Multiply bar to get Pa.
W_TO_KW = 0.001
module-attribute
¶
Multiply W to get kW.
W_TO_MW = 1e-06
module-attribute
¶
Multiply W to get MW.
KJ_PER_KG_TO_J_PER_KG = 1000.0
module-attribute
¶
Multiply kJ/kg to get J/kg.
J_PER_KG_TO_KJ_PER_KG = 0.001
module-attribute
¶
Multiply J/kg to get kJ/kg.
C_TO_K_OFFSET = 273.15
module-attribute
¶
Add to a temperature in degC to get K.
K_TO_C_OFFSET = -273.15
module-attribute
¶
Add to a temperature in K to get degC.
YEAR_TO_HOUR = 8760.0
module-attribute
¶
Hours per (365-day) year. Used by DoubletEconomicComponent's LCOE formula (annual operational hours).
EULER_CONSTANT = 0.5772156649015329
module-attribute
¶
The Euler-Mascheroni constant γ, to float64 precision. Used by
fluid_utils.heat_loss_zhang_2011's wellbore heat-loss β correlation
for t_d > 2.8 (Zhang et al. 2011, Eq. 2; docs/SOURCES.md#zhang2011 —
see that function's docstring), whose coefficient is exactly 2γ
(EULER_CONSTANT_X2, below).
EULER_CONSTANT_X2 = EULER_CONSTANT * 2.0
module-attribute
¶
2γ — see EULER_CONSTANT.
tango_core.core.economic_constants
¶
Hardcoded cost-model constants for DoubletEconomicComponent.
Every CAPEX formula that uses these constants (DoubletEconomicComponent,
components/economic/doublet.py) multiplies by a
Producer Price Index (PPI) value and an installation/contingency multiplier
pair (X_IC, X_PC), both looked up from two real tables
(data/PPI_Table.xlsx, data/cost_multiplier_table.xlsx — since
removed as dead weight once their values were baked in below) at a
"cost year" derived from the simulation's start_date.
tango_core has no calendar/start_date concept at all (SimConfig
only has times in seconds since the start of operation), so there's no dynamic year to look up
against. This module hardcodes the 2019 row of both tables — as named
constants, pulled directly from the real tables before their removal
(verified via pandas.read_excel("data/PPI_Table.xlsx", header=1) and
pandas.read_excel("data/cost_multiplier_table.xlsx")).
This is a deliberate, documented Phase-1 simplification: no PPI-table/ interpolation machinery is ported, so cost-year sensitivity isn't supported. If tango ever gains a calendar concept, revisit this module to look values up dynamically instead of hardcoding one year.
PPI_PIPE = 2.09238776837996
module-attribute
¶
Pipe PPI (surface gathering pipes).
PPI_T_G = 1.40640096618358
module-attribute
¶
Turbine-generator PPI.
PPI_HX = 1.79679450486548
module-attribute
¶
2-stream heat exchanger PPI (preheater/boiler/recuperator).
PPI_PUMP = 1.61687986934336
module-attribute
¶
Pump PPI (injection pump).
PPI_PE = 1.79364076125576
module-attribute
¶
Process-equipment PPI (cooler/condenser BAC regression).
PPI_O_AND_G = 2.19543973941368
module-attribute
¶
Oil & gas well PPI (well CAPEX).
PPI_PERMIT = 1.83976992604766
module-attribute
¶
Permitting (legal services) PPI.
PPI_O_AND_G_S = 1.43740902474527
module-attribute
¶
O&G support-activities PPI (exploration CAPEX).
X_IC_WELLS = 1.05
module-attribute
¶
Installation-cost multiplier for wells/exploration.
X_PC_WELLS = 1.15
module-attribute
¶
Project-contingency multiplier for wells/exploration.
X_IC_SURFACE = 1.12
module-attribute
¶
Installation-cost multiplier for the surface plant/pipes.
X_PC_SURFACE = 1.15
module-attribute
¶
Project-contingency multiplier for the surface plant/pipes.
PERMITTING_BASE_COST_USD = 665700.0
module-attribute
¶
Base permitting cost (USD, before PPI/multiplier scaling), H2O/non-CO2.
EXPLORATION_BASE_COST_USD = 508000.0
module-attribute
¶
Base exploration cost (USD, before PPI/multiplier scaling), H2O/non-CO2.
TEC_MULTIPLIER = 1.39
module-attribute
¶
Total Equipment Cost = TEC_MULTIPLIER * sum(primary equipment costs).
BEC_MARKUP = 1.0 + 0.58 + 0.11 + 0.0 + 0.04
module-attribute
¶
Bare Erected Cost = TEC * BEC_MARKUP (site prep, buildings, engineering, ...).
tango_core.core.init_protocol
¶
Init Protocol for post-deserialization initialization.
Init
¶
Bases: Protocol
Protocol for objects that require post-deserialization initialization.
Component.from_dict() calls self.init() after constructing any
object that implements this protocol, allowing derived fields to be computed
from the validated input state.
init()
¶
Initialize computed fields after deserialization.