Simulator
The simulator replays a treatment schedule over a compiled dataset and writes a run directory. It reads only the compiled dataset (see Compiled dataset), and it is deterministic given a schedule: the same dataset and schedule produce the same account values.
Model
The simulator advances one year at a time. Each fragment ages by one year per step. A fragment’s
track_id gives its trajectory, and its offset is its position on that track; the account
values for a year are the area times the feature curve evaluated at the offset.
A treatment in the schedule applies to a block only when the block’s track offers that treatment at the block’s current offset (the Model II rule). Applying a treatment:
records the product yields (area times each product curve at the pre-treatment offset);
resets the fragment’s
track_idto the treatment’snew_trackand itsoffsetto the treatment’soffset.
A treatment the track does not offer is a no-op. See notes/adr/0005.
Schedule
A schedule is a CSV with the columns block_id,treatment,offset, where offset is the number of
years after the start of the simulation (offset 0 is the first simulation year). The same block may be
scheduled more than once.
ws4 simulate --dataset build/compiled --schedule schedule.csv --years 30 --out run
Outputs
File |
Contents |
|---|---|
|
|
|
|
|
The report sidecar: report digests, source metadata digests, run and dataset identifiers, and an explicit uncertainty status. See Report provenance. |
|
The dataset manifest, so a run records what it read. |
When the simulator is given a road network (the Python API, Simulator.run(..., network=...) or
route_model=...), RouteCostLedger.write also writes route_values.csv,
network_table.csv, route_table.<destination>.csv, route_cost_report.csv, and — when the
vertices table carries coordinates — used_roads.csv for the map overlay; see Roads, routes, and mills.
When the simulator is given a DHI account (Simulator.run(..., dhi_account=...) or the
--dhi-values and --dhi-metadata options), it also writes dhi_values.csv and
dhi_metadata.json; see Dynamic Habitat Index account. ws4 report adds report_dhi.csv.
When it is given a structure habitat account (structure_habitat_account=... or
--structure-values and --structure-metadata), it writes
structure_habitat_values.csv, structure_habitat_landscape.csv, and
structure_habitat_metadata.json; see Structure habitat index. ws4 report adds
report_structure_habitat.csv.
When --resilience is given with a topology, it writes resilience_metrics.csv and
resilience_metadata.json; see Resilience metrics. ws4 report adds
report_resilience.csv.
When the simulator is given a block topology (Simulator.run(..., topology_csv=...)), it also
writes:
patch_metrics.csv— per-year patch count, mean size, largest opening, and size-class distribution (see Spatial structure and constraints);patch_accounts.csv— per-year patch accounts, whenpatch_accountsare given;edge_metrics.csv— per-year edge contrast accounts, whenedge_elementsare given;spread_metrics.csv— per-year spread-connectivity accounts, whenspread_accountsandblock_coordinatesare given (see Spatial structure and constraints);spread_membership.csv— the untreated blocks of every spread compartment, with the account, compartment index, area class, block area and component area, when the same inputs are given; the largest component is index 0;spatial_violations.csv—kind,year,area_ha,limit,block_a,block_b,years(kindisopening,green_up, orcore_area), when a maximum opening size, a green-up interval, or a core-area rule is given.
Dataset integrity warnings
A compiled dataset can be internally inconsistent in a way that makes an account wrong rather than
missing. Simulator.from_dataset warns, naming the dataset and the affected labels, in two cases:
A repeated product row. The product table is keyed by
(track_id, treatment, label)and every row is recorded once per treated fragment, so two identical rows multiply the account. The builder now emits one row per key and curve; a dataset compiled before that rule carries the repeat and should be recompiled. A repeated key with different curves is a sum of components and is left alone.An area-shaped product whose curve exceeds 1.0. A label containing
AreaorTreatedshould yield a share of the block; a curve above 1.0 means the account is not hectares. This one is advisory: WS4 reports what the dataset says.
Neither warning changes a value. They exist so a multiplied account cannot pass as hectares.
API
- class ws4.sim.engine.Simulator(dataset_dir: Path)[source]
Annual-step simulator over fragments and tracks.
- Parameters:
dataset_dir (Path) – A compiled matrix dataset directory.
- classmethod from_dataset(dataset_dir: Path) Simulator[source]
Build a simulator that reads the given compiled dataset.
- Parameters:
dataset_dir (Path) – The compiled dataset directory.
- Returns:
Simulator – The simulator for that dataset.
- reset() None[source]
Restore the mutable state (tracks and offsets) to the construction state.
The static caches (curves, feature joins, treatment and product indexes) are kept, so a search can reuse one simulator across evaluations instead of reloading the dataset each time. The join is only invalidated when the tracks actually changed.
- apply_treatments(schedule: DataFrame, offset: int, route_model: RouteModel | None = None, ledger: RouteCostLedger | None = None) set[int][source]
Apply the treatments scheduled for a year and record their products.
A product is produced when its treatment is applied to a fragment on the product’s track; the yield is the fragment’s area times the product curve at the pre-treatment offset. When a route model is given, each product is sent to an eligible destination (exclusive per product per block) and the route cost is recorded.
- Parameters:
schedule (pandas.DataFrame) – The schedule, with
block_id,treatment, andoffsetcolumns.offset (int) – The simulation offset to apply.
route_model (RouteModel or None, optional) – The route model (destinations, eligibility, surplus) for routing products.
ledger (RouteCostLedger or None, optional) – The route cost ledger to record the routed products into.
- Returns:
set of int – The blocks that had at least one fragment treated.
- account_values(offset: int) list[dict[str, object]][source]
Compute the feature account values for the current state.
A feature label may appear on several tracks; the value is the sum of the area times the feature curve at the fragment’s offset, over the precomputed join. The curves are evaluated with a single integer-age table gather.
- Parameters:
offset (int) – The simulation offset to label the values with.
- Returns:
list of dict – One
{"offset", "account", "value"}record per feature account.
- block_criteria(label: str) dict[int, float][source]
Return the per-block value of a criterion label.
A feature is a level: the area-weighted mean of its curve over the block’s fragments, so a half disturbed block has a value of 0.5. A product is a flow: what the block produced in the year last applied, because a product’s curve is the window over a track’s age in which its treatment may be applied, and what it yields is produced in the year of the treatment. A product is not a feature, and asking the feature join for one returns nothing at all — which is how a harvested patch criterion once produced every cell zero. Both are the patch membership criterion of the patch accounts (see
ws4.patch.accounts).- Parameters:
label (str) – The criterion label: a feature (for example
feature.Seral.young) or a product (for exampleproduct.harvested).- Returns:
dict of int to float – The criterion value per block.
- block_criteria_series(block_id: int, events: Sequence[tuple[str, int]], label: str, years: int) dict[int, float][source]
Return one block’s area-weighted criterion value per year under a chain.
The criterion is the area-weighted mean of the label’s curve over the block’s fragments, isolated as in
block_chain(). A block’s value depends only on its own chain, so this is cacheable per(block, chain, label)and never needs the whole schedule’s state. The years are evaluated as one gather over the curve table rather than a curve call per year.- Parameters:
block_id (int) – The block.
events (sequence of (str, int)) – The treatments and the year each is applied.
label (str) – The criterion feature label.
years (int) – The horizon, in years.
- Returns:
dict of int to float – The criterion value per year.
- block_chain(block_id: int, events: Sequence[tuple[str, int]], years: int, feature_offsets: Collection[int] | None = None, accounts: Collection[str] | None = None) dict[tuple[int, str], float][source]
Return one block’s account values over a horizon under a chain of treatments.
The block’s fragments are simulated in isolation: each
(treatment, year)event is applied in its year (a no-op where the fragment’s track does not offer it), and every fragment’s offset advances one year per step. The result is(year, label) -> value, so a schedule’s account values are the empty-schedule base plus a per-block delta. A block may be treated more than once (rotations); events are applied in year order.- Parameters:
block_id (int) – The block.
events (sequence of (str, int)) – The treatments and the year each is applied.
years (int) – The horizon, in years.
feature_offsets (collection of int, optional) – Return feature cells only at these years. Products are always returned at their treatment years.
Nonereturns every feature year.accounts (collection of str, optional) – Restrict feature and product labels to these accounts.
Nonereturns all labels carried by the block’s tracks.
- Returns:
dict of (int, str) to float – The account value per year and label (non-zero entries only). Feature labels and the product labels produced by the treatments are both included.
- block_chain_products(block_id: int, events: Sequence[tuple[str, int]]) dict[tuple[int, str], float][source]
Return the product cells a treatment chain makes on a block.
The value at each event is the fragment area times the product curve at the fragment’s offset in that event’s year: the fragment ages between events and resets on each treatment. This is the product part of
block_chain()without stepping every year, so it costs O(fragments x events).- Parameters:
block_id (int) – The block.
events (sequence of (str, int)) – The treatments and the year each is applied.
- Returns:
dict of (int, str) to float – The product value per
(year, label)cell (non-zero entries only).
- block_trajectory(block_id: int, treatment: str | None, year: int, years: int) dict[tuple[int, str], float][source]
Return one block’s account values over a horizon under a single treatment.
This is
block_chain()with at most one event; see it for the semantics.- Parameters:
block_id (int) – The block.
treatment (str or None) – The treatment to apply, or None for no treatment.
year (int) – The year to apply the treatment.
years (int) – The horizon, in years.
- Returns:
dict of (int, str) to float – The account value per year and label (non-zero entries only).
- block_products(block_id: int, treatment: str, year: int) dict[str, float][source]
Return the product values a treatment makes on a block.
The value is the fragment area times the product curve at the pre-treatment offset at the treatment year (the fragment ages
yearsteps before the treatment), summed over the block’s fragments. This is the product part ofblock_trajectory()without stepping the horizon, so it costs O(fragments) rather than O(fragments x years).- Parameters:
block_id (int) – The block.
treatment (str) – The treatment to apply.
year (int) – The year the treatment is applied.
- Returns:
dict of str to float – The product value per product label (non-zero entries only).
- block_route_events(block_id: int, events: Sequence[tuple[str, int]], years: int, route_model: RouteModel) tuple[tuple[int, int, str, float, str, Route | None], ...][source]
Return one block’s routed products over a horizon under a treatment chain.
The block’s fragments are simulated in isolation (like
block_chain()), and each produced product that the route model delivers is returned as(year, block, product, volume, destination, route). The events are independent of the rest of the schedule when every road is open and no delivery target is set, which is what lets the optimizer cache and replay them.- Parameters:
block_id (int) – The block.
events (sequence of (str, int)) – The treatments and the year each is applied.
years (int) – The horizon, in years.
route_model (RouteModel) – The route model (destinations, eligibility, surplus).
- Returns:
tuple of (int, int, str, float, str, Route or None) – The routed products, in simulation order.
- block_route_chain(block_id: int, events: Sequence[tuple[str, int]], years: int, route_model: RouteModel, route_accounts: Sequence[RouteAccount]) dict[tuple[int, str], float][source]
Return one block’s route-account values over a horizon under a treatment chain.
The block’s fragments are simulated in isolation (like
block_chain()), but its produced products are routed withroute_modeland recorded into a fresh summary ledger; the ledger’s account values are returned as(year, account) -> value. This is the additive view used when no per-segment account needs the whole schedule; the optimizer replaysblock_route_events()when build or maintenance is priced.- Parameters:
block_id (int) – The block.
events (sequence of (str, int)) – The treatments and the year each is applied.
years (int) – The horizon, in years.
route_model (RouteModel) – The route model (destinations, eligibility, surplus).
route_accounts (sequence of RouteAccount) – The route accounts to resolve.
- Returns:
dict of (int, str) to float – The route account value per year and account (non-zero entries only).
- block_route_accounts(block_id: int, treatment: str | None, year: int, years: int, route_model: RouteModel, route_accounts: Sequence[RouteAccount]) dict[tuple[int, str], float][source]
Return one block’s route-account values under a single treatment.
This is
block_route_chain()with at most one event; see it for the semantics.- Parameters:
block_id (int) – The block.
treatment (str or None) – The treatment to apply, or None.
year (int) – The year to apply the treatment.
years (int) – The horizon, in years.
route_model (RouteModel) – The route model.
route_accounts (sequence of RouteAccount) – The route accounts to resolve.
- Returns:
dict of (int, str) to float – The route account value per year and account (non-zero entries only).
- simulate(schedule: DataFrame, years: int, network: RouteNetwork | None = None, route_model: RouteModel | None = None, ledger: RouteCostLedger | None = None, edge_elements: Sequence[EdgeElement] = (), edges: Sequence[tuple[int, int, float]] = (), spread_accounts: Sequence[SpreadAccount] = (), spread_edges: Sequence[tuple[int, int, float]] = (), spread_points: Mapping[int, tuple[float, float]] | None = None, dhi_account: DhiAccount | None = None, structure_habitat_account: StructureHabitatAccount | None = None, resilience: bool = False) DataFrame[source]
Replay a schedule and return the account values, without writing files.
- Parameters:
schedule (pandas.DataFrame) – The schedule, with
block_id,treatment, andoffsetcolumns.years (int) – The number of annual steps.
network (RouteNetwork or None, optional) – The road network for routing products to destinations.
route_model (RouteModel or None, optional) – The route model. When omitted but
networkis given, a default model over that network is used.ledger (RouteCostLedger or None, optional) – The route cost ledger to record routed products into.
edge_elements (sequence of EdgeElement, optional) – Edge contrast elements. When given with
edges, an edge contrast account value per element per year is added to the account values.edges (sequence of (int, int, float), optional) – The adjacency edges
(src, dst, shared_length)for the edge contrast.spread_accounts (sequence of SpreadAccount, optional) – Spread-connectivity accounts to compute per year. They need
spread_edgesandspread_points, and are appended to the account values like the edge accounts.spread_edges (sequence of (int, int, float), optional) – The topology edges with their distances
(src, dst, distance_m), which is what a spread bearing is read from.spread_points (mapping of int to tuple of float or None, optional) – The
(x, y)centroid of each block in metres.dhi_account (DhiAccount or None, optional) – Static Dynamic Habitat Index values per block. When given, the simulator records the DHI total and area-weighted mean for the blocks not yet treated. The account does not change growth.
structure_habitat_account (StructureHabitatAccount or None, optional) – Static Coops et al. (2016) structure habitat metrics per block. When given, the simulator records component means and class areas for the blocks not yet treated. The account does not change growth.
resilience (bool, optional) – When True, compute the descriptive connectivity, age-class, and fragmentation metrics from the topology and the simulated ages. Requires
edgesand does not change growth or the objective.
- Returns:
pandas.DataFrame – The account values, with
year,account, andvaluecolumns. Feature and product accounts are both included: a treatment’s products are recorded as account values in the year they are produced, so every simulated account is scoreable.
- run(schedule_csv: Path, years: int, out_dir: Path, topology_csv: Path | None = None, patch_breaks: Sequence[float] = (5.0, 10.0, 50.0), network: RouteNetwork | None = None, route_model: RouteModel | None = None, route_accounts: Sequence[RouteAccount] = (), duplicate_accounts: Sequence[DuplicateAccount] = (), product_allocations: Sequence[ProductAllocation] = (), period_width: int = 1, maintenance: MaintenanceCharge | None = None, max_opening_ha: float | None = None, min_green_up_years: int | None = None, patch_accounts: Sequence[PatchAccount] = (), patch_membership: bool = False, edge_elements: Sequence[EdgeElement] = (), spread_accounts: Sequence[SpreadAccount] = (), block_coordinates: Path | None = None, core_buffer_m: float | None = None, min_core_area_ha: float | None = None, dhi_account: DhiAccount | None = None, structure_habitat_account: StructureHabitatAccount | None = None, resilience: bool = False) DataFrame[source]
Replay a schedule for the given horizon and write the run outputs.
- Parameters:
schedule_csv (Path) – A CSV with
block_id,treatment, andoffsetcolumns.years (int) – The number of annual steps.
out_dir (Path) – Directory to write the run outputs into.
topology_csv (Path or None, optional) – A block topology edge list. When given, per-year patch metrics are written to
patch_metrics.csv.patch_breaks (sequence of float, optional) – The patch size-class upper bounds, in hectares.
network (RouteNetwork or None, optional) – The road network for routing products.
route_model (RouteModel or None, optional) – The route model (destinations, eligibility, surplus). When omitted but
networkis given, a default model over that network is used.route_accounts (sequence of RouteAccount, optional) – The route accounts to resolve into the account values.
duplicate_accounts (sequence of DuplicateAccount, optional) – The duplicate accounts to apply to the account values.
product_allocations (sequence of ProductAllocation, optional) – Master products to partition across the destinations they were routed to, with an account for whatever did not move.
period_width (int, optional) – The model’s planning-period width, in years, which is what the route cost report is folded into (default 1, one row per year).
maintenance (MaintenanceCharge or None, optional) – How a used road’s maintenance is charged. The default is the reference’s own reading; a divergence from it has to be asked for by name.
max_opening_ha (float or None, optional) – The maximum opening size. When given,
spatial_violations.csvreports the patches over it.min_green_up_years (int or None, optional) – The green-up interval. When given,
spatial_violations.csvreports the adjacent pairs disturbed within it.patch_accounts (sequence of PatchAccount, optional) – Patch account definitions. When given with a topology,
patch_accounts.csvis written.patch_membership (bool, optional) – When True and patch accounts are given,
patch_membership.csvis written as well: which blocks formed which patch, in which period.spread_accounts (sequence of SpreadAccount, optional) – Spread-connectivity accounts. When given with a topology and a coordinate table, they are computed per year, added to the account values, and written to
spread_metrics.csv.dhi_account (DhiAccount or None, optional) – Static Dynamic Habitat Index values per block. When given, the DHI accounts are added to
account_values.csvand the run-local values/metadata are written for reports and the web API.structure_habitat_account (StructureHabitatAccount or None, optional) – Static Coops et al. (2016) structure metrics per block. When given, the structure accounts are added to
account_values.csvand the run-local stand table, landscape summary, and metadata are written.resilience (bool, optional) – When True and
topology_csvis given, compute the descriptive connectivity, age-class, and fragmentation accounts and writeresilience_metrics.csvplusresilience_metadata.json.block_coordinates (Path or None, optional) – A CSV of block centroids (a block id, an
xand ay), which a spread bearing is read from. Required withspread_accounts.edge_elements (sequence of EdgeElement, optional) – Edge contrast elements. When given with a topology, an edge contrast account value per element per year is added to the account values and written to
edge_metrics.csv.core_buffer_m (float or None, optional) – The core-area buffer width, in metres. When given with
min_core_area_ha,spatial_violations.csvreports patches whose core area is below it.min_core_area_ha (float or None, optional) – The minimum core area, in hectares.
- Returns:
pandas.DataFrame – The account values, with
year,account, andvaluecolumns.
- write_patch_metrics(schedule: DataFrame, years: int, topology_csv: Path, patch_breaks: Sequence[float], out_dir: Path, max_opening_ha: float | None = None, min_green_up_years: int | None = None, patch_accounts: Sequence[PatchAccount] = (), patch_membership: bool = False, core_buffer_m: float | None = None, min_core_area_ha: float | None = None) None[source]
Replay a schedule and write per-year patch metrics and patch accounts.
- Parameters:
schedule (pandas.DataFrame) – The schedule, with
block_id,treatment, andoffsetcolumns.years (int) – The number of annual steps.
topology_csv (Path) – The block topology edge list.
patch_breaks (sequence of float) – The size-class upper bounds, in hectares, for
patch_metrics.csv.out_dir (Path) – The directory to write the outputs into.
max_opening_ha (float or None, optional) – The maximum opening size, in hectares, for the violation record.
min_green_up_years (int or None, optional) – The green-up interval, for the violation record.
patch_accounts (sequence of PatchAccount, optional) – The patch accounts to accumulate over the run.
patch_membership (bool, optional) – When True and patch accounts are given,
patch_membership.csvis written as well: which blocks formed which patch, in which period. A run wants it; a search prices the accounts alone.core_buffer_m (float or None, optional) – The core-area buffer distance, in metres.
min_core_area_ha (float or None, optional) – The minimum core area, in hectares.
- ws4.sim.curve.curve_value(curves: DataFrame, curve_id: int, x: float) float[source]
Evaluate a long-format curve at
xby linear interpolation.Values below the first point and above the last point are clamped to the endpoint values, matching the model’s interpolation contract.
- Parameters:
curves (pandas.DataFrame) – The
curvestable, withcurve_id,x, andycolumns.curve_id (int) – The curve to evaluate.
x (float) – The domain value (for example, an offset age).
- Returns:
float – The interpolated value, or
0.0when the curve has no points.