Skip to content

Package tour

The README.md next to each subpackage, collected on one page. On GitHub the same files show when you open the folder.

tango_core package

tango_core simulates a geothermal project over its lifetime and tells you what its energy costs. You describe the system in one YAML file: which reservoir, which wells, which surface plant, how they connect, and the economic assumptions. tango_core turns that file into Python objects, solves them together year by year, and prices the result as a levelized cost of electricity or heat (LCOE/LCOH).

This page explains how the package does that. Read it before opening any module. For more detailed diagrams, see docs/architecture/ and docs/runtime/.

How a run moves through the package

%%{init: {"theme":"base","themeVariables":{"primaryColor":"#FFFFFF","primaryTextColor":"#202124","primaryBorderColor":"#DADCE0","lineColor":"#5F6368","secondaryColor":"#F8F9FA","tertiaryColor":"#F8F9FA","clusterBkg":"#F8F9FA","clusterBorder":"#DADCE0","edgeLabelBackground":"#FFFFFF"},"flowchart":{"curve":"basis","nodeSpacing":40,"rankSpacing":64,"useMaxWidth":true}} }%%
flowchart TB
  yaml["config.yml<br/>written by you"]:::human
  wf["workflows/<br/>Workflow<br/>validate · build"]:::code
  orch["orchestrators/<br/>time loop ·<br/>iterate until closed"]:::code
  circ["components/<br/>well · reservoir · surface<br/>pass Streams in a circuit"]:::code
  econ["components/economic/<br/>CAPEX · OPEX · LCOE<br/>once, at the end"]:::econ
  out["results_export.py<br/>YAML + CSV"]:::code

  yaml --> wf --> orch
  orch <-->|"each timestep"| circ
  orch -->|"after the last step"| econ --> out

  classDef well  fill:#F3EDF9,stroke:#7D4FB0,color:#7D4FB0,font-size:15px
  classDef res   fill:#FBEAE7,stroke:#D2402C,color:#D2402C,font-size:15px
  classDef surf  fill:#E8F0FA,stroke:#2F6FBF,color:#2F6FBF,font-size:15px
  classDef econ  fill:#E0F2F1,stroke:#007B83,color:#007B83,font-size:15px
  classDef code  fill:#FFFFFF,stroke:#DADCE0,color:#202124,font-size:15px
  classDef err   fill:#FCE8E6,stroke:#D93025,color:#D93025,font-size:15px
  classDef out   fill:#FFFFFF,stroke:#9AA0A6,color:#5F6368,stroke-dasharray:4 3,font-size:15px
  classDef human fill:#202124,stroke:#9AA0A6,color:#FFFFFF,font-size:15px
  1. Load. Workflow.from_file reads the YAML file. Pydantic schemas in core/specs.py validate each block. A bad value stops the run here with a ConfigError that names the offending field.
  2. Build. Each entry under components: names a type and a variant. components/registry.py maps that pair to a class, for example ("reservoir", "lumped") → LumpedReservoir, and the class is built straight from the YAML. The object holds exactly what the file says (object == config).
  3. Choose how to solve. When sim_config.injection_mode is set, the workflow picks SystemBCIteration, which iterates every timestep until the circuit closes. Every shipped example sets it. Without it, the workflow picks SystemDirect, which makes one pass per timestep.
  4. Step through time. SimConfig.time_stepping_for() gives the run's subsystems and their time grids, which split the run into sync intervals (see time stepping); with the num_tsteps/dt_years shorthand, every step is its own interval. For each interval, the components are solved in circuit order: injection well → reservoir → production well(s) → surface plant → back to the injection well, each subsystem through its own steps. Each component turns its inlet Stream into an outlet Stream.
  5. Price it. After the last timestep, the economics component reads the solved components and their histories once and computes CAPEX, OPEX and LCOE. It never feeds back into the physics.
  6. Save. results_export.write_results writes the config with every solved value (reloadable), a per-step CSV and an economics CSV.

The ideas you need

Component. A component is one physical part of the system. Every component subclasses core/component.py::Component and implements solve(inlet) -> None, which sets self.outlet. Wells, the reservoir and the surface plant are components. Economics is a component too, but it has no inlet or outlet.

Stream. A Stream (core/stream.py) carries the three quantities that cross a component boundary: temperature, pressure and mass flow rate, in SI units. Components never call each other. The orchestrator takes one component's outlet and hands it to the next component as its inlet.

Circuit. The config wires components by index: each has a component_idx and names its prev and next. The last component's next points back to the first, so fluid that leaves the plant re-enters the injection well. The AGS system has no reservoir component and the CPG system has no pump, so the circuit differs from system to system.

Why it iterates. The injection well needs the injection enthalpy before it can be solved. That enthalpy only exists once the surface plant downstream has been solved. SystemBCIteration therefore guesses it and solves the whole circuit. It compares what comes back with the guess, corrects the guess with Aitken relaxation, and repeats up to 20 times until the difference is below 1 kJ/kg. In manual-fracking-check mode it then checks the converged timestep against the fracking limits. Diagram: BC iteration.

State that cannot be read stale. Anything that changes from one timestep to the next lives in a LockedState (core/locked_state.py). It allows one write per solve and raises an error on a read before that write or on a second write in the same solve. This turns "used last iteration's value by mistake" into an immediate error instead of a wrong number. During iteration, each component also snapshots its state at the start of the timestep and restores it before every attempt.

Economics is one central component. The wells, reservoir and plant hold no cost logic. components/economic/doublet.py::DoubletEconomicComponent reads all of them after the last timestep and prices them by category: wells (one drilling-cost formula per well section), the surface plant (per TESPy node: turbine and generator, injection pump, cooler/condenser), surface pipes, and fixed permitting and exploration costs. It then computes OPEX and LCOE from the run-averaged net power. The reservoir is not costed, and neither is a direct-heat exchanger. Costing each component inside the component itself is not implemented.

History. After each timestep, every component appends its state to a matching history (*History), and the step itself to time_history. Economics and the CSV export read these histories, not just the final value, and weight each entry by the length of its step.

The folders

Path What it holds Read it when
core/ Building blocks: Component, Stream, LockedState, the config schemas, the error types, fluid properties (CoolProp), the secant and Aitken solvers You need to know what a component is or why a run raised an error
components/ The physics and the economics: lumped and numerical wells, the lumped reservoir, the TESPy surface plant, the doublet economics, and the registry You change a physical model or add one
orchestrators/ The time loop (SystemDirect) and the iteration that closes the circuit (SystemBCIteration) A run is slow or does not converge
workflows/ Workflow: YAML in, validated objects and an orchestrator out You add a config block or call tango_core from Python
cli.py tango_core run, validate, init You use the command line
results_export.py Writes <name>.yml, .smry.csv, .econ.csv You need the output files
pymoo_api.py Multi-objective optimization (NSGA-II). Each candidate design is one full Workflow run, in parallel You optimize a design
surrogate_api.py Samples many runs, trains ML surrogates on them, optimizes on the surrogate, then re-checks the best designs with real runs Full runs are too slow to optimize directly
utils.py print_datetime for sweep logs —

Each module imports only from modules below it in this order: core ← components ← orchestrators ← workflows ← the CLI and the optimization modules. core imports from nowhere else in tango_core. The one exception is core/specs.py, which uses the reservoir's well-pattern helper.

Where to start reading

  1. templates/hydro_sf_electric.yml: the flagship config. Its header comment draws the circuit.
  2. workflows/workflow.py Workflow.__init__: how that file becomes objects.
  3. orchestrators/system_direct.py run: the time loop.
  4. orchestrators/system_bc_iteration.py run_interval and _converge_injection_enthalpy: the iteration.
  5. One component end to end, for example components/reservoir/lumped.py LumpedReservoir.solve.

Changing it

  1. A new physical model. Add a component class and register it. The steps and rules are in components/AGENTS.md.
  2. A new config block or option. Add a pydantic schema in core/specs.py and read it in Workflow.
  3. A new injection mode. Add an InjectionPolicy value and handle it in SystemBCIteration.run_interval.
  4. A new outer loop (sweep, optimizer). Build on Workflow(cfg).run(), the way pymoo_api.py does. Do not reach into the orchestrator.

The rules for any change are the TANGO commandments.

tango_core.core

core holds the building blocks every other subpackage is made of. It knows nothing about any particular well, reservoir or plant. It defines what a component is, how values travel between components, how the config is validated, and what can go wrong. Most of its rules exist to stop a silent wrong number. A value read too early, a copy that drifts out of sync or an unconverged result all become an immediate error instead.

The ideas you need

A component is a pydantic model with a solve. Component is both a pydantic BaseModel and an abstract class. Its fields are the YAML keys, so a component is built straight from its config block (from_dict) and can be written back out unchanged. A subclass declares its config fields, computes derived values in init(), and implements solve(inlet), which must set self.outlet. Unknown YAML keys are rejected (extra="forbid").

A Stream is the only thing that crosses a boundary. It carries temperature (K), pressure (Pa) and mass flow rate (kg/s), nothing else. Components never call each other. An orchestrator passes one component's outlet to the next one's solve(inlet).

Mutable values are guarded. Every value that changes during a run is a LockedState. It must be written exactly once per solve. Reading it before that write, or writing it twice, raises a LockedStateError (StaleAccessError, FreshAccessError, DoubleWriteError). The orchestrator calls mark_all_stale() before every solve to open the next write. These values live in the component's state dataclass. After each timestep, record() appends them to a matching *History, so the whole time series is kept.

Config and errors are typed. The top-level config blocks are pydantic schemas: Common, Layout, SimConfig and Description. Common is built once and shared by reference with every component, so all components see the same fluid and rock properties. Every failure tango raises deliberately is a TangoError subclass. That is how tango_core tells a config error (exit 1) from a simulation error (exit 2).

Read these first

  1. component.py, Component: the class docstring explains the solve lifecycle, and snapshot_convergence_state shows what an iteration restores.
  2. locked_state.py, LockedState: the write-once guard.
  3. stream.py, Stream: the three quantities on the wire.
  4. specs.py, SimConfig: timesteps (the num_tsteps/dt_years shorthand or time_stepping, expanded by time_stepping.py), injection_mode, and the checks between them (check_injection_mode_requirements).

Reference

Module Holds
component.py Component: from_dict, init, solve, snapshot_convergence_state, restore_convergence_state
stream.py Stream, StreamHistory
locked_state.py LockedState
state_methods.py StateMethods: mark_all_stale, record
orchestrator.py Orchestrator, the interface the orchestrators implement
specs.py Common, Layout, SimConfig, Description
policies.py InjectionPolicy, MainProduct, ProjectMaturity, ComponentRole
errors.py TangoError and its subclasses, such as ConvergenceError, ConfigError, FrackingViolationError, CoolPropError
fluid_state.py, fluid_utils.py FluidState over CoolProp; friction, hydrostatics, fracking_flow
accelerators.py, numerics.py aitken_relax; secant_solve with PUMP_BOOST_TOL_PA = 1.0, PUMP_BOOST_MAX_ITER = 20
constants.py, economic_constants.py, physics_models.py, init_protocol.py Physical and cost constants, model enums, the Init protocol

The rules behind these classes are the TANGO commandments.

tango_core.components

components is where the physics and the money live. Each physical part of a geothermal system (an injection well, the reservoir, a production well, the surface plant) is one class here. So is the economics that prices them. The config picks the parts. This package makes them interchangeable: any well can sit in any circuit, as long as it speaks the same interface.

The ideas you need

What a component must do. Subclass the base for its kind (WellComponent, ReservoirComponent, SurfaceComponent or EconomicComponent). Then implement solve(inlet): read the inlet Stream and write self.outlet and self.state. The base classes hold the fields every component of that kind shares. One example is injection_pressure on the surface plant, which the auto-pressure loop adjusts.

Inlet and outlet are Streams. A component never calls its neighbor. It sees one inlet Stream (T, P, ṁ) and produces one outlet Stream. The orchestrator wires each outlet to the component named by next.

State and history. Values that change during a run live in a *State dataclass, each one a LockedState. Every *State field has a list twin in a *History class that is appended after each timestep. LumpedReservoirState and LumpedReservoirHistory in reservoir/lumped.py are the simplest pair to read.

The registry. registry.py maps each YAML (type, variant) pair to a class. One example is ("production_well_with_pump", "numerical") → NumericalProductionWellWithPump. A new class appears in configs only after it gets an entry here.

Economics is one central component. The wells, reservoir and plant hold no cost logic. DoubletEconomicComponent runs once, after the last timestep. It reads the solved components and their histories and prices them by category:

  • wells: one drilling-cost formula per well section;
  • surface plant nodes: turbine and generator, injection pump, cooler/condenser;
  • surface pipes;
  • fixed permitting and exploration costs.

It then computes OPEX and LCOE from the run-averaged net power. The reservoir is not costed. A direct-heat exchanger is not costed either, so a pure direct-heat plant reports a surface-plant CAPEX of 0.

External simulators (CMG, MOOSE and others) would enter as new ReservoirComponent or WellComponent implementations. None exists yet.

Read these first

  1. reservoir/lumped.py, LumpedReservoir: a complete component in one file; start with its solve.
  2. well/numerical.py, NumericalWell: a marched well. _march is one explicit pass over the cells.
  3. surface/graph.py, GraphSurface: the plant as a TESPy network built from the config's power_plant nodes and edges.
  4. economic/doublet.py, DoubletEconomicComponent.solve: the cost categories, in order.

Reference

Subpackage Base class Implementations
well/ WellComponent (base.py) lumped.py: LumpedInjectionWell, LumpedProductionWell, LumpedProductionWellWithPump. numerical.py: NumericalWell, NumericalInjectionWell, NumericalProductionWell, NumericalProductionWellWithPump
reservoir/ ReservoirComponent (base.py) lumped.py: LumpedReservoir. wellpattern_impedance.py: WellPattern
surface/ SurfaceComponent (base.py) graph.py: GraphSurface
economic/ EconomicComponent (base.py) doublet.py: DoubletEconomicComponent
registry.py — COMPONENT_REGISTRY

To add a component, follow components/AGENTS.md.

tango_core.orchestrators

An orchestrator runs the component circuit through time. Each timestep it solves the components in order and passes each outlet to the next component. After the last timestep it runs the economics once. The hard part is that the circuit is a closed loop: the plant's outlet is the injection well's inlet. One pass is therefore not a consistent answer, and the loop must iterate until it closes.

The ideas you need

Why the circuit iterates. The loop is cut at the injection well (component_idx 0), which is solved first. It needs an injection enthalpy, but that enthalpy only exists once the surface plant, last in line, has been solved. SystemBCIteration guesses the enthalpy and solves every component in order. It reads the enthalpy the plant returns, corrects the guess with Aitken relaxation and repeats. It stops when the returned enthalpy and the guess differ by less than 1 kJ/kg, or raises ConvergenceError after 20 attempts. On the very first timestep the guess comes from the surface conditions.

One attempt starts from the same place. Before the loop starts, each component's state is snapshotted (a deep copy). Every attempt restores that snapshot, then calls mark_all_stale() and solve(inlet) on each component in turn. Each attempt thus asks the same question: given last timestep's state, what does this timestep look like with this guess? Attempts never build on each other's leftovers.

manual-fracking-check checks the fracking limit; nothing adjusts the boundary to meet it. Injecting too hard fractures the reservoir. Two quantities can cause it: wellhead pressure and mass flow. Once a timestep has converged, manual-fracking-check checks both thresholds and raises FrackingViolationError if either is exceeded. It never caps the value silently. To find an operating point below the limit, use an applications/opt_*/ search, which treats that error as an infeasible design.

SystemDirect is the plain case. Without sim_config.injection_mode, the workflow uses SystemDirect: one pass per sync interval, no iteration. SystemBCIteration subclasses it and overrides run_interval, where the iteration lives, and run.

A pass covers one sync interval. With a single subsystem, a sync interval is one timestep. With several subsystems (sim_config.time_stepping), each subsystem takes its own steps through the interval in circuit order, and a stream into another subsystem is converted to the receiver's steps by its sync rule. See time stepping. Every shipped template sets injection_mode.

Read these first

  1. system_direct.py, SystemDirect.run: the time loop.
  2. system_bc_iteration.py, run_interval: the dispatch on injection_mode.
  3. system_bc_iteration.py, _converge_injection_T: the attempt loop and the snapshot restore.
  4. system_bc_iteration.py, _converge_injection_pressure: the outer loop around it.

Reference

Class Key methods
SystemDirect (system_direct.py) _next_inlet, _record_outlet, _solve_interval, run_interval, record, finalize (economics), run
SystemBCIteration (system_bc_iteration.py) _check_fracking, _seed_circuit_inlet, run_interval, _converge_injection_pressure, _converge_injection_flow, _converge_injection_T
Constant (system_bc_iteration.py) Value
DEFAULT_MAX_ITER_NO_FRACK 200
DEFAULT_TOLERANCE 1e-3
DEFAULT_MAX_INNER_ITER 20
_DT_SURFACE_TOL 0.5 K

Diagram: boundary-condition iteration. Deep dive: injection-enthalpy convergence.

tango_core.workflows

Workflow is the one object a caller needs. It takes a YAML config, turns it into validated components and the right orchestrator, and runs them. It can also write the config back out with every solved value. The command-line tool, the optimizers and every script in applications/ go through it. Nothing outside it builds components or orchestrators by hand.

The ideas you need

All validation happens before anything runs. Workflow.__init__ validates common, layout, sim_config and description against the pydantic schemas in core/specs.py. It builds the economic block, then every entry under components: through COMPONENT_REGISTRY. Any failure is raised as a ConfigError before the first timestep. For a closed loop, it also requires at least one pressure source (a pumped well or a pump node in the plant), because a pump-less loop has nothing to drive circulation.

Shared values have one source. common is built once and handed to every component by reference. A final identity check (is, not ==) proves they all hold the same object. well_spacing, well_pattern, and target_extraction_pressure are copied from their single source into each component that declares them. A component's own YAML block may not set any of these.

One key chooses the orchestrator. If sim_config.injection_mode is set, the workflow uses SystemBCIteration, which iterates each timestep until the circuit closes. If it is absent, it uses SystemDirect, which makes one pass.

The config goes both ways. to_dict, to_str and to_file rebuild the config from the live objects, including solved state. The output can be loaded again. This is how results_export.write_results saves a run.

Read these first

  1. workflow.py, Workflow.__init__: load, validate, build, choose.
  2. workflow.py, _build_components: the registry lookup and the shared-value threading.
  3. workflow.py, _check_loop_has_pressure_source: the closed-loop check.

Reference

Name Does
Workflow The class. Its docstring has a usage example
from_file, from_str Parse YAML (yaml.safe_load), then construct
to_dict, to_str, to_file Write the live config back out
run Delegate to the orchestrator
_check_common_identity Every component shares the one Common
_build_economic_component The economic: block
_build_components The components: block

How the config maps to objects, as a diagram: config to objects.