Skip to content

Engine Map: How a Simulation Runs

This page is a guided tour of the code for someone who wants to maintain or refactor ECOSYS. It explains the layers, the vocabulary, and the path one request takes through the ecosys/engine/ package, and it flags the parts that are hard to read and why. It describes the code; the equations themselves are in the model reference and the conventions behind them in Scientific Decisions.

Line references such as engine/animals.py:26 are relative to ecosys/ and will drift; search for the function name if a line no longer matches.

1. Suggested reading order

  1. Sections 2–3 of this page (layers and vocabulary).
  2. EcosysEngine.integrate_on_grid (engine/api.py:64) and run_simulation (engine/assembly.py:331): together about 50 lines that show the whole pipeline.
  3. compute_single_event_concentrations (engine/concentrations.py:44): the six-stage food-chain sequence for one event.
  4. Section 2.1 below, to see which stage lives in which module.
  5. Each stage in section 5, together with its kernel file.
  6. The hotspots in section 7, once the overall shape is familiar.

Two tools help while reading: the integration tests in tests/integration/ (one file per stage, section 8) and a debugger breakpoint in compute_single_event_concentrations on the README quick-start request.

2. The layers

 SQLite parameter database (ecosys/data/*.sqlite)
        │  data/loader.py        rows → unit-bearing immutable records (ModelData)
        ▼
 ModelData ──► data/catalog.py   exact lookups by canonical string ID
        │  data/compile.py       string IDs → integer positions, dense arrays + masks
        │  foodchain.py          processing edges → ProcessingGraph (feed / food)
        ▼
 CompiledModel  (engine/context.py:122)  request-independent, compiled once per engine
        │
 SimulationRequest (domain/)     events, population, landscape, time support
        │  domain/compile.py     request → CompiledInputs (fixed units, batch shape)
        ▼
 SimulationContext (engine/context.py:180) = CompiledModel + CompiledInputs + one axis per event
        │
        │  engine/               orchestration: which kernel, in which order, on which times
        │    ├── kernels/*.py    one physical process each; Astropy units at the boundary
        │    │     └── numerics/*.py   plain-array formulas (NumPy or JAX), no units
        │    └── foodchain.py    processing/storage graph evaluation
        ▼
 SimulationResult (domain/results.py)   immutable typed result tree
        │  reporting.py          select report dates, serialize; never recalculates
        ▼
 user

Responsibilities are deliberately separated:

Layer Knows about Does not do
data/loader.py, data/records.py SQLite rows, physical units, record immutability Positions, dense arrays, equations
data/catalog.py Exact canonical-ID lookup (catalog.plant("oats")) Aliases, fuzzy matching
data/compile.py Axes, integer positions, dense arrays, applicability masks Transfer or dose equations
foodchain.py Processing-edge graphs, dependency order, storage-shifted evaluation Loading data, deciding which materials are needed
domain/ Public inputs, validation, time support, result records Physics
kernels/ One process each: deposition, soil, plants, animals, processing, dosimetry, exposure Deciding call order or time grids
numerics/ Unit-free array formulas, shared with the JAX path Units, validation, calendars
engine/ Order of stages, time grids, calendar logic, wiring kernels together — (it still mixes these; see section 7)
conventions.py Named model-policy constants (foliar horizon, root ramp, equilibrium year, animal inhalation) with their SD entries —
reporting.py Selecting and serializing finished results Recalculation

tests/test_architecture_boundaries.py enforces the import rules: only ecosys/legacy_workbook/ may read Excel, and production code never imports the exporter or the old workbook-driven implementation. ecosys/sensitivity/ (optional JAX) imports from the engine but nothing in the engine imports it.

2.1 The engine package

One module per stage, in dependency order. Each module imports only from modules above it in this list; there are no import cycles.

Module Contents
context.py compile_model, CompiledModel, SimulationContext, CompiledEventAxis, build_simulation_context; per-event helpers shared by the dose stages
calendar.py Workbook seasonal day → Gregorian date; harvest seasons
deposition.py Derived pasture and ground-shine deposition sources
soil.py Stage 2: root-zone inventory, plant-available soil, resuspension
plants.py Stage 3: plant concentrations and recurring harvest stocks
hay.py Hay preparation windows and their grass sources
sources.py Plant/hay sources evaluated once for all planned storage-shifted reads
feed.py Stage 4: plant-derived ration materials through the feed graph
animals.py Stage 5: rations, retention, every animal product
foods.py Stage 6: consumed foods through the food graph
concentrations.py Runs stages 1–6 for one event
ingestion.py Ingestion dose, seasonal consumption, food availability onsets
exposure.py Inhalation, external and skin-tissue exposure
assembly.py Complete event result, alignment, superposition, population dose
api.py EcosysEngine, chunked execution

ecosys/engine/__init__.py re-exports the public names, so from ecosys.engine import EcosysEngine, build_simulation_context works as before. Private helpers (leading underscore) are imported from their module, for example from ecosys.engine.animals import _compute_event_animals.

3. Vocabulary you need first

Canonical IDs and positions. Every entity (element, nuclide, plant, material, animal, product, pathway, age, environment…) has an exact string ID such as cs_137 or intensive_grass. data/compile.py sorts each set of IDs into an axis and gives every ID an integer position. Arrays are indexed by position; CanonicalIndexes (data/compile.py:46) converts between the two. Much of the engine's apparent complexity is bookkeeping between IDs, positions and axes.

Applicability masks. Dense arrays store missing entries as zero plus a boolean mask such as soil_transfer_applicable. A zero without its mask is not a physical zero. Code that reads a dense array should check its mask.

Plants, materials and products.

  • A plant (19 in valley) is a crop or grass grown on a field.
  • A material is anything with a concentration in Bq/kg that can be stored, processed, fed or eaten: plant materials, hay, silage, flour, milk, cheese.
  • An animal product (cow milk, beef, eggs…) is a material produced by an animal from its feed.

Every plant and product therefore also has a material position; much of the engine translates between the plant/product axes and the material axis.

Feed and food domains. Materials are processed twice: for animal feed (e.g. barley stored for winter) and for human food (e.g. milk to cheese, wheat to flour). Each domain has its own processing graph per element.

Processing graphs and edges (foodchain.py). An edge says: final material = factor × raw material, taken storage days earlier, decayed over that storage. Every final material has exactly one edge, so following edges backwards from a food gives a single chain ending at one source material (resolve_source_chain, foodchain.py:430). A self-edge (raw = final) records storage of a material under its own ID; a chain made from that material reads the source itself, so storage is not applied twice.

Query plan. Because chains depend only on the graph, every time at which a source will be read (t minus the chain's storage) is known before anything is computed. processing_source_queries (foodchain.py:497) lists them; the engine evaluates plant and hay sources once for all of them and the graph evaluator then only looks values up.

Plant categories (kernels/plants.py). Plants use one of five formulas:

Category Examples Behaviour
grass_hay intensive/extensive grass, turf Growth dilution, weathering, continuous harvest
leafy_vegetable leafy vegetables Deposit counts only within the growing/harvest window
silage_or_beet_leaf maize silage, beet leaves Direct leaf deposit plus root uptake; stock between harvests
single_harvest_translocating_crop cereals, potatoes, beets, maize cobs, fruiting vegetables Foliar activity translocated into the edible part until harvest
harvest_window_produce orchard fruit, berries, root vegetables Fresh during the harvest window, stock (averaged) afterwards

Rations and retention. Each animal eats a seasonal ration (kg/day of several feed materials, changing on calendar days). The activity in a product follows a sum of exponential retention components, scaled so that the transfer factor (day/kg) gives the long-term equilibrium product level.

Two clocks.

  • Event-relative days, axis.output_days (0 = deposition day), drive decay, weathering and transfer.
  • Absolute Gregorian dates drive the calendar: phenology, harvests, rations, seasonal consumption.

Seasonal parameters use a 365-day "canonical day of year"; 29 February maps to 1 March (SD-03). Some calendar fields are one-based and some zero-based (see engine/plants.py:331).

Support grid and interval ownership. A request carries explicit elapsed-time nodes. Concentrations are evaluated at the nodes; dose is integrated over intervals (t[i-1], t[i]], and interval i is stored at node i. Changing the nodes can change the numerical answer (SD-18). The default grid (domain/time.py:51) is daily at first, then coarser.

Event time grids. Every CompiledEventAxis carries one grid of signed event-relative days, named by axis.grid. Stages read the derived views axis.elapsed_days (clamped at zero), axis.pre_event_mask and axis.dates (Gregorian date of each node) instead of recomputing them, and switch grids with axis.on_days(days, grid=...):

axis.grid Created in Nodes
support context.py The request's integration and report nodes
animal_solver animals.py Post-event support nodes; results map back to support
hay_source hay.py Daily grass samples inside each hay-preparation window
storage_query sources.py Plant/hay query times t − storage for processing graphs
harvest_sample plants.py Harvest dates at which stored crops are sampled fresh

Results returned to the caller are always on support; the other grids are internal to one stage.

Batch axes vs semantic axes. Leading axes are batch (for example raster cells). Trailing axes have meaning: time, then cohort, plant, material, product or pathway. Most shape juggling in the engine keeps that order intact.

Events. Each deposition event is simulated independently on its own relative clock, then aligned to the shared absolute grid and summed (superposition). The model is linear in deposited activity, so this is exact.

4. One request's journey

EcosysEngine.run(request)                               engine/api.py:60
└─ integrate_on_grid
   ├─ build_simulation_context(request, compiled_model) engine/context.py:194
   │     compile_inputs (domain/compile.py), dependency-closure checks,
   │     one CompiledEventAxis per event (dates, positions, half-life)
   └─ run_simulation(context)                           engine/assembly.py:331
      ├─ for each event: compute_complete_single_event  engine/assembly.py:39
      │  ├─ compute_single_event_concentrations         engine/concentrations.py:44
      │  │   ├─ 1. deposition   compute_deposition            (kernels/deposition.py)
      │  │   ├─ 2. soil         _compute_event_soil_and_resuspension  engine/soil.py:48
      │  │   ├─ 3. plants       _compute_event_plants          engine/plants.py:257
      │  │   ├─    plan         _event_source_queries          engine/concentrations.py:30
      │  │   │                  + _plant_material_sources      engine/sources.py:33
      │  │   ├─ 4. feed         _compute_event_feed            engine/feed.py:45
      │  │   ├─ 5. animals      _compute_event_animals         engine/animals.py:26
      │  │   └─ 6. foods        _compute_event_foods           engine/foods.py:26
      │  ├─ compute_single_event_ingestion              engine/ingestion.py:127
      │  └─ compute_single_event_exposure               engine/exposure.py:145
      │       cloud inhalation, resuspension inhalation, ground external,
      │       optional cloud external
      ├─ align_event_contribution  (event clock → absolute grid)   engine/assembly.py:153
      ├─ sum per-capita doses and superpose_event_concentrations    engine/assembly.py:228
      ├─ aggregate_event_population_dose (× population counts)
      └─ SimulationResult with RunProvenance

The stage order follows the physics: deposition happens once on the event date; soil is fed by the ground deposit; plants are fed by foliar deposit and soil; animals eat plants (via feed processing); people eat plants and animal products (via food processing).

5. The stages in detail

5.1 Context (build_simulation_context, engine/context.py:194)

  • compile_model (engine/context.py:143) runs once per EcosysEngine and caches every request-independent array (CompiledModel).
  • compile_inputs converts the request to fixed-unit arrays and resolves the common batch shape.
  • validate_dependency_closure checks, before any calculation, that every ration feed and consumed food can be traced back to plants or products for this element. Missing parameters therefore fail early with a clear error.
  • CompiledEventAxis (engine/context.py:50) stores the event's positions, date, physical half-life, relative days, and age_offset_days (cohorts age on the output clock, not the event clock).

5.2 Deposition (engine/concentrations.py:44 → kernels/deposition.py)

Evaluated once, at the event date, for every surface target (ground, turf and each plant). Dry deposit = integrated air × velocity × LAI/max LAI; wet deposit = wet input × interception fraction (which depends on LAI, rain and water film). Noble gases take a separate all-zero branch (engine/concentrations.py:66).

Two derived sources are used later:

  • _pasture_deposition (engine/deposition.py:14): ground plus dry grass deposit, the source for root-zone soil.
  • _ground_shine_deposition (engine/deposition.py:24): ground plus dry turf deposit, the source for external dose.

5.3 Soil and resuspension (engine/soil.py:48 → kernels/soil.py)

Runs only with a Landscape; otherwise it returns None and soil-to-plant uptake is skipped. Root-zone activity moves between available and fixed forms and migrates away (a two-compartment solution, numerics/soil.py). Resuspension air concentration follows from the total soil inventory.

_plant_available_soil (engine/soil.py:20) repeats this per plant soil type, because each plant's rates and soil mass follow its own soil type, not the landscape's.

5.4 Plants (_compute_event_plants, engine/plants.py:257)

For each plant it combines:

  • the direct leaf term: deposit ÷ yield × weathering × decay, active for 730 days (numerics.plants.foliar_leaf, DIRECT_FOLIAR_HORIZON_DAYS, SD-06/SD-07);
  • the translocated leaf term, which replaces the direct leaf for crops and produce with a translocation curve (numerics.plants.translocated_leaf, SD-08);
  • the root uptake term: plant-available soil × transfer ÷ soil mass (_plant_soil_contribution, engine/plants.py:126), ramped in over 50 days (numerics.plants.root_ramp, ROOT_UPTAKE_RAMP_DAYS, SD-07);
  • the category formula (table in section 3), dispatched in the loop at engine/plants.py:334;
  • recurring harvests for stock-keeping categories: _recurring_harvest_values (engine/plants.py:96) replaces stock during each harvest window and decays the last harvest's stock between harvests. It needs fresh values at the harvest dates themselves. Those dates depend only on the calendar, so _harvest_schedule (engine/plants.py:68) lists them for every stored crop first, and _harvest_sample_root_uptake (engine/plants.py:161) computes their root uptake once. The fresh_at_days closure (engine/plants.py:380) combines that with _stock_plant_leaf (engine/plants.py:210), the same formulas used for the support-node values. tests/kernels/test_plant_leaf_terms.py checks that they agree.

5.5 Feed and hay (_compute_event_feed, engine/feed.py:45)

Determines which ration materials derive from plants and evaluates them through the feed processing graph. Hay is special: it is made from grass over a preparation window each summer (_hay_intervals, _compute_hay_material_sources, engine/hay.py, SD-09), so the engine evaluates grass on a separate daily grid within those windows.

Stored feed must be evaluated at earlier times (t − storage). Before the feed stage, _event_source_queries (engine/concentrations.py:30) collects every such read of the feed and food graphs, and _plant_material_sources (engine/sources.py:33) evaluates them once: the plant stage runs once on the union of all plant query times (plants are pointwise in time), and hay once per distinct query set (hay integrates grass over the queried days, so it is not pointwise). The graph evaluator reads these by exact lookup; a read that was not planned raises instead of recomputing.

5.6 Animals (_compute_event_animals, engine/animals.py:26)

  • Solver grid. Products are solved on the post-event support nodes; the ration and feed concentration are held at the left node over each interval.
  • Rations. evaluate_rations gives each animal's kg/day per feed material for each interval start date.
  • Solve. solve_animal_product (kernels/animals.py:210) propagates each retention component. It includes animal inhalation of the passing cloud, spread over the first day (SD-17), and a rolling mast window.
  • Equilibrium switch. After 1 January of the third calendar year the product switches to an equilibrium formula (_herd_equilibrium_after, engine/animals.py:295, SD-10).
  • Dependency loop. Some feeds are themselves animal products (milk replacer made from cow milk), so products are solved in dependency order by a while loop that alternates between solving products and processing feeds whose raw material is now known (engine/animals.py:203). A cycle raises ProcessingGraphError.

5.7 Foods (_compute_event_foods, engine/foods.py:26)

Every consumed material is evaluated through the food graph from plant and animal-product sources, again at storage-shifted times, reading the same planned plant sources as the feed stage. Animal products are interpolated only within their computed support and are zero before it.

5.8 Ingestion dose (compute_single_event_ingestion, engine/ingestion.py:127)

Per interval and food: mean concentration × consumption × dose coefficient × duration.

  • Consumption and dose coefficients are interpolated at the cohort's current age.
  • Consumption is multiplied by seasonal factors averaged exactly over the interval's calendar days (engine/ingestion.py:57).
  • The interval mean is the logarithmic mean of the endpoint concentrations (exact for exponential change; SD-18).
  • A stored plant food first becomes available as a step after its storage delay (_food_availability_onsets, engine/ingestion.py:95). The mean accounts for that step instead of assuming a smooth rise from zero.

5.9 Other pathways (compute_single_event_exposure, engine/exposure.py:145)

  • Cloud inhalation and optional cloud external: impulses on the event date.
  • Resuspension inhalation: integrated over intervals from the 5.3 air concentration.
  • Ground external: ground_shine_deposition with its own empirical decay components (not the root-zone soil model, SD-12), reduced by time-weighted shielding across environments.

Skin tissue dose is separate (engine/exposure.py:84) and never added to effective dose.

5.10 Alignment, superposition, population (engine/assembly.py)

Each event's result lives on its own relative clock. align_event_contribution maps it to the request's absolute grid; per-capita doses of all events are summed; concentrations are superposed; collective dose is per-capita dose × population count.

6. Key data structures

Structure Where Lifetime Holds
ModelData data/loader.py:95 Loaded once Immutable records with units
ParameterCatalog data/catalog.py:29 Per engine ID lookups over ModelData
CompiledModel engine/context.py:122 Per engine, cached Dense parameter arrays, graphs
CompiledInputs domain/compile.py:72 Per request Fixed-unit event/population/landscape arrays
SimulationContext engine/context.py:180 Per request Everything above plus event axes
CompiledEventAxis engine/context.py:50 Per event Positions, dates, relative days, half-life
SingleEventConcentrations domain/results.py Per event Deposition, soil, plants, materials, products
SingleEventResult domain/results.py Per event Concentrations plus ingestion and pathway doses
SimulationResult domain/results.py Returned Aligned, superposed tree with provenance

All are frozen dataclasses with read-only arrays: stages return new objects instead of mutating shared state. Inside a stage, local NumPy arrays are mutated freely.

7. Why the engine is hard to read

These are observations to guide a refactor, not bugs: the behaviour is covered by tests and by comparisons with the original workbook runs.

Mixed levels within a stage. The engine is now split by stage (section 2.1), but a single function still mixes orchestration, calendar arithmetic, physics that should live in kernels, and array/unit plumbing. _compute_event_plants and _compute_event_animals are both over 200 lines.

Recomputation through callbacks (resolved). Storage-shifted queries used to re-enter the engine through callbacks, and harvest sampling recomputed soil per plant and season. In a one-year soil-enabled June run, soil was evaluated 184 times and the plant stage 10 times (747 soil evaluations over three years). With the query plan and the batched harvest schedule, soil is evaluated 11 times and the plant stage twice, independent of the horizon; the run takes about half the time. tests/integration/test_source_query_plan.py guards these counts.

Physics inside orchestration (partly resolved). The fresh_at_days closure used to re-implement the leaf, translocation and root formulas inline for harvest-date sampling. Both paths now call _stock_plant_leaf, _plant_soil_contribution and the numerics.plants formulas. One deliberate difference remains: for a crop without a translocation curve, the fresh support-node value keeps the weathered leaf while harvest sampling is root-fed only. No packaged parameter set reaches this case (only the noble gases lack curves, and they skip the plant stage). Calendar and harvest logic (_recurring_harvest_values) still lives in the orchestration.

Named conventions (resolved). The 730-day foliar horizon, 50-day root ramp, third-year herd equilibrium and one-day animal inhalation were bare literals. They are now constants in ecosys/conventions.py, each citing its SD entry, and are shared by the engine, kernels, numerics and sensitivity/prepare.py.

Unit wrapping and unwrapping. Arrays are repeatedly multiplied by Astropy units to call a kernel and immediately converted back with .to_value(...). This protects the kernel boundary but adds noise to every call.

Several time grids (made explicit). Report support, the animal solver grid, daily hay source days, storage-shifted query times and harvest samples coexist. Each is now a named grid on CompiledEventAxis (section 3), created through on_days, rather than an implicit variable naming convention and three hand-built copies of the axis.

Special cases. The noble-gas branch, self-edges in processing graphs, products that are feeds (milk replacer), leap-day mapping, and one-based/zero-based calendar days each add conditionals in several places.

A second orchestration. ecosys/sensitivity/prepare.py re-implements this flow for the JAX path, as a precomputed recipe (section 9). Changes to engine calendar or feed logic must be mirrored there.

8. Where the tests pin behaviour

Tests Pin
tests/data/ Records, compilation into arrays and masks, dependency closure, database validation
tests/domain/ Requests, time support, shapes, units, results, provenance
tests/kernels/ Each process in isolation, analytic limits
tests/integration/test_event_*.py One engine stage each: deposition, soil, plants, feed, animals, foods, ingestion, exposure
tests/integration/test_complete_single_event.py, test_multiple_events.py, test_engine_api.py The assembled pipeline and superposition
tests/validation/ Comparison with preserved original-workbook runs, documented examples
tests/sensitivity/test_plan.py Every trajectory of the JAX recipe against this engine
tests_export_excel_data/ Workbook import and export

For a behaviour-preserving refactor, the full suite (python -m pytest -q tests tests_export_excel_data, about 13 minutes) is the safety net; the tests/integration and tests/validation folders are the fastest meaningful subset for engine changes.

9. How sensitivity/prepare.py relates to the engine

The JAX path cannot use callbacks, byte-keyed caches or Python-level while loops over traced values. prepare.py therefore performs the engine's orchestration once on the host and records it as a fixed list of operations (an IngestionPlan), which sensitivity/forward.py executes with NumPy or JAX.

Engine prepare.py counterpart
_compute_event_soil_and_resuspension, _plant_available_soil _Builder.soil_basis
_compute_event_plants, _harvest_schedule, _recurring_harvest_values, fresh_at_days _Builder.fresh_basis, _Builder.plant_node
_compute_hay_material_sources _Builder.hay_node
evaluate_processing_graph_at_times (feed/food) _Builder.graph_node
_compute_event_animals dependency loop product/feed loop in prepare_ingestion_problem
_food_availability_onsets onset inside prepare_ingestion_problem (both use resolve_source_chain)

prepare.py shares the conventions and numerics.plants.root_ramp with the engine. Its leaf terms stay separate: it splits them into fixed coefficients and traced weathering so that JAX can differentiate them.

Nothing in the normal pipeline uses prepare.py. Both now share the engine's planning idea: which material needs which source, at which delayed times, is resolved first (chains and query plans), and numbers are computed afterwards. The engine still evaluates concentrations directly rather than through prepare.py's recipe of operations; _Builder.graph_node keeps its own traversal because it builds shared intermediate recipe nodes.

10. Possible refactoring directions

Listed so the next step can be chosen deliberately. Each can be done in behaviour-preserving steps checked by the full suite. Steps 1–2 were checked bit for bit: every array of six fixed scenarios in two parameter sets was identical before and after. Step 3 reorders floating-point operations, so it was checked to within rounding instead; steps 4 and 5 are again bitwise.

  1. Name the conventions. Done: ecosys/conventions.py.
  2. Split engine.py by stage. Done: the ecosys/engine/ package (section 2.1), moved verbatim with signatures unchanged.
  3. Move physics out of orchestration. Done for the plant stage: the harvest-sampling closure and the main path share numerics.plants (foliar_leaf, translocated_leaf, root_ramp) and the engine helpers _stock_plant_leaf and _plant_soil_contribution. Results changed only by floating-point rounding (at most 2.7×10⁻¹⁵ relative in any concentration).
  4. Make time grids explicit. Done: CompiledEventAxis.grid, EVENT_GRIDS, the derived views elapsed_days/dates, and on_days. Bitwise unchanged, including on a fractional grid with a later event.
  5. Replace callbacks with a resolved query plan. Done: processing graphs resolve to chains (resolve_source_chain), whose reads are planned (processing_source_queries) and evaluated once (_plant_material_sources); harvest sampling is scheduled (_harvest_schedule) and its root uptake batched; the soil-only callers skip resuspension; engine and prepare.py share the chain resolution for food onsets. Bitwise unchanged.

A further step would be to let the engine execute prepare.py's recipe directly, giving a single orchestration for the reference engine and the JAX path. That changes how results are produced rather than tidying the current code, so it is a design decision, not a cleanup.