Scenario experiment workflows
This tutorial runs a small scenario grid through the Rust kernel and verifies the meaning of its results. The inputs are synthetic. The comparison represents the effect of the supplied model assumptions; it is not an estimated causal effect of a real policy.
Learning outcomes
Section titled “Learning outcomes”After completing the example, you can specify baseline, intervention, competition and substitution scenarios; interpret their distinct outputs; preserve scenario order in a Polars table; and replay a saved artifact against the same native runtime. You will also distinguish scientific replay equality from incidental timestamps and execution durations.
Prerequisites
Section titled “Prerequisites”Use the source-built Innovate 0.7 development package and its pinned Python 3.15.2 and Polars environment. Follow the installation guide before running the example. The native extension must support the scenario operations and Kairos ABM engine used below; missing capabilities are errors. This example uses no remote service or downloaded dataset.
You should be comfortable with Python mappings, cumulative adoption and the distinction between a simulated path and an empirical estimate. Each of the four scenarios uses two observation times; the stochastic scenarios use 100 agents.
Choose an outcome and comparison before running a real experiment. In this example, only the baseline and pause scenarios form an intervention comparison; competition and replacement demonstrate separate model contracts.
| Scenario | Observation times, in years | Fixed inputs | Result to interpret |
|---|---|---|---|
| Baseline | 0 and 5 | 100 agents; innovation p = 0.2 per year; imitation q = 0 |
One simulated adoption path |
| Pause innovation | 0 and 5 | The same population, seed and starting state; innovation reduced by 0.2 at time 0 |
Alternative minus baseline at matched times |
| Two products | 0 and 5 | 200 potential adopters; 100 initially allocated 25:75; zero growth and interaction rates | Two unchanged product levels |
| Replacement | 0 and 2 | A fixed pool of 100 incumbent adopters; replacement hazard 0.5 per year |
Incumbent and entrant levels whose sum remains 100 |
The common specification has a five-year horizon. The replacement example asks
for output only through year two; it does not implicitly simulate a five-year
endpoint for the comparison. reference_year labels the time origin rather than
converting the numeric time coordinates into dates.
-
Use the checked-in
examples/native_scenarios.pyfrom the same revision as the installed package. -
Run it with the interpreter where that native package is installed:
Terminal window .venv-native/bin/python examples/native_scenarios.py -
Check that every assertion passes and the final JSON matches the next section. An assertion or native-operation error fails the exercise; do not suppress it.
"""Check native synthetic scenarios, artifact round trips and deterministic replay.
Reuse the scenario payloads from the maintained tutorial. JSON and Arrow outputare written to a temporary directory and removed when the example exits. Theexample uses no external datasets, services or host-language numerical fallback."""
import jsonimport mathimport tempfilefrom pathlib import Path
import polars as pl
import innovate
def main() -> None: """Execute four synthetic scenarios and check their scientific invariants.""" common = { "description": "Synthetic scenario example", "time_horizon": 5, "time_unit": "year", "reference_year": 2026, } policy = { "id": "pause-innovation", "model_key": "bass", "specification": { **common, "scenario_type": "intervention", "name": "Pause innovation", "market_size": 100, "initial_adoption": 0, "intervention_type": "innovation_delta", "intervention_start_time": 0, "intervention_magnitude": -0.2, }, "simulation": { "inputs": {"time": [0, 5]}, "parameters": {"p": 0.2, "q": 0}, "simulation_options": { "engine": "kairos_abm", "seed": 42, "population": 100, }, }, } baseline = { **policy, "id": "baseline", "specification": { **common, "scenario_type": "baseline", "name": "Baseline", "market_size": 100, "initial_adoption": 0, }, } competition = { "id": "two-products", "model_key": "multi_product", "specification": { **common, "scenario_type": "competition", "name": "Two products", "market_size": 200, "initial_adoption": 0.5, "num_competitors": 2, "competitor_names": ["A", "B"], "market_share_initial": [0.25, 0.75], }, "simulation": { "inputs": {"time": [0, 5]}, "parameters": { "p1": 0, "p2": 0, "q1": 0, "q2": 0, "m1": 100, "m2": 100, "alpha_1_2": 0, "alpha_2_1": 0, }, }, } substitution = { "id": "replacement", "model_key": "fixed_pool_replacement", "specification": { **common, "scenario_type": "substitution", "name": "Fixed-pool replacement", "market_size": 200, "initial_adoption": 0.5, "incumbent_name": "A", "entrant_name": "B", "substitution_rate": 0.5, }, "simulation": {"inputs": {"time": [0, 2]}}, }
response = innovate.execute( "execute_scenario_grid", scenarios=[baseline, policy, competition, substitution], comparisons=[{"baseline": "baseline", "alternative": "pause-innovation"}], apply_specifications=True, include_execution_metadata=True, ) executions = response["result"]["executions"] for row in executions: if row["error"] is not None: raise RuntimeError(row["error"])
assert executions[1]["result"]["counts"] == [0, 0] comparison = response["result"]["comparisons"][0] if comparison["error"] is not None: raise RuntimeError(comparison["error"]) baseline_final = executions[0]["result"]["values"][-1] assert baseline_final > 0 assert comparison["result"]["difference"][-1] == -baseline_final assert executions[2]["result"]["rows"] == [[25, 75], [25, 75]] incumbent, entrant = executions[3]["result"]["rows"][-1] assert math.isclose(incumbent, 100 * math.exp(-1)) assert math.isclose(incumbent + entrant, 100)
with tempfile.TemporaryDirectory(prefix="innovate-scenario-example-") as directory: json_path = Path(directory) / "scenario-grid.json" arrow_path = Path(directory) / "scenario-executions.arrow" json_path.write_text(json.dumps(response, indent=2, allow_nan=False), encoding="utf-8") assert json.loads(json_path.read_text(encoding="utf-8")) == response innovate.scenario_executions(response).write_ipc(arrow_path) table = pl.read_ipc(arrow_path) assert table["scenario_id"].to_list() == ["baseline", "pause-innovation", "two-products", "replacement"] saved_rows = [json.loads(value) for value in table["execution_json"]] assert saved_rows == executions
replayed = 0 for row in saved_rows: imported = innovate.execute("import_scenario_artifact", artifact=row["artifact"])["result"] if not imported["replay_available"]: raise RuntimeError(imported["replay_reason"]) request = imported["artifact"]["replay_request"] replay = innovate.execute(request["operation"], **request["payload"]) assert replay["result"]["executions"][0]["result"] == row["result"] replayed += 1
assert len(executions) == replayed == 4 print( json.dumps( { "policy_counts": executions[1]["result"]["counts"], "replacement_total": round(incumbent + entrant, 6), "replayed": replayed, "scenario_ids": table["scenario_id"].to_list(), }, sort_keys=True, ) )
if __name__ == "__main__": main()Each grid entry supplies a scenario ID, model key, specification and simulation
payload. apply_specifications=True translates the supported specification
fields into model inputs. Omitting that option validates specifications and
executes the supplied simulation payloads without applying their changes.
The script writes the complete response to JSON and the ordered execution table to Arrow IPC inside a temporary directory. It reads both back, checks equality, then replays all four scientific results. The temporary files are removed after the checks, so repeated runs do not overwrite user files.
Expected results
Section titled “Expected results”The final output contract is imported from the same manifest used by the example runner. The runner checks the actual output and observes execution of outcome assertions; the displayed code comes directly from the executable file.
{"policy_counts": [0, 0], "replacement_total": 100.0, "replayed": 4, "scenario_ids": ["baseline", "pause-innovation", "two-products", "replacement"]}The intervention’s adopter counts remain zero at both observation times. The
competition scenario retains the initial allocation of 25 and 75 adopters.
The replacement scenario conserves 100 adopters. The script also checks that
the incumbent population at time two is 100 × exp(-1), independently of the
native implementation’s calculation, and that all four artifacts replay.
Interpretation
Section titled “Interpretation”For the intervention, the baseline innovation coefficient is p = 0.2 and the
intervention changes it by −0.2 from time zero. With zero imitation and no
initial adopters, the intervention has no mechanism for adoption. The negative
endpoint difference therefore equals the baseline endpoint’s magnitude.
The baseline simulation uses a fixed seed, but its positive count is not used
as an empirical estimate or printed as a universal expected number.
Competition begins with 100 adopters drawn from a potential market of 200,
split 25:75 between products. Zero diffusion and cross-product rates isolate
allocation from subsequent growth. Substitution uses a replacement rate of
0.5 over two time units, so the analytic incumbent fraction is exp(-1).
These deliberately simple limits make an implementation error easier to detect.
Here substitution_rate = 0.5 is translated into a continuous replacement hazard.
It is not a 50% one-year replacement probability: under this model that probability
is 1 − exp(−0.5), approximately 39.35%. The units and the hazard-to-probability
conversion follow from the specified exponential survival equation.
JSON preserves the complete response. The Polars table preserves row order and
stores nested results in execution_json. A replay request resolves the inputs
for one scenario; retain the original grid response separately if you need its
cross-scenario comparisons.
Check your understanding
Section titled “Check your understanding”- Why is the intervention contrast nonpositive in this fixture, and what would prevent that conclusion in a different scenario?
- Calculate incumbent and entrant levels at year two. Why do they sum to 100 when the specification’s potential market is 200?
- Would ranking the replacement result at year two against the baseline result at year five answer the intervention question?
Compare your answers
- The intervention removes the only adoption mechanism: innovation becomes zero, imitation is already zero and there are no initial adopters. Its zero endpoint minus the positive baseline endpoint is negative. That argument does not apply when another adoption mechanism or initial state is present.
- The incumbent level is
100 * exp(−1), approximately 36.787944, and the entrant level is approximately 63.212056. The fixed pool is the initial adoption fraction0.5multiplied by the potential market of 200. This example transfers that pool; it does not recruit the remaining market. - No. Those outputs differ in model, time and outcome meaning. Use an explicitly defined comparison with compatible outcomes and matched evaluation times.
Limitations
Section titled “Limitations”These synthetic invariants test bounded execution, serialization and replay. They do not establish parameter identifiability, general model accuracy, uncertainty calibration or the causal effect of an intervention. A fixed seed is not a statistical validation study, and two observation times do not assess the entire time path.
For an empirical policy effect, specify the target population, intervention, comparator, outcome and time horizon, then justify identification assumptions. For example, exchangeability, positivity and consistency have substantive requirements beyond a well-formed request; see Cole and Hernán (2008). This simulation example does not establish those assumptions.
Replay compares scientific results using the same runtime. Timestamps and elapsed times can vary, and this example does not claim bitwise reproducibility across all platforms or future versions. Preserve the package revision and runtime identity alongside real project artifacts. Consult the native migration guide for current release gates and unsupported operations.