Metadata-Version: 2.4
Name: pysimlin
Version: 0.8.4
Summary: Python bindings for the Simlin system dynamics simulation engine
Author: The Simlin Authors
Maintainer: The Simlin Authors
License: Apache-2.0
Project-URL: Homepage, https://github.com/bpowers/simlin
Project-URL: Documentation, https://github.com/bpowers/simlin/tree/main/src/pysimlin
Project-URL: Repository, https://github.com/bpowers/simlin
Project-URL: Issues, https://github.com/bpowers/simlin/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cffi>=1.15.0
Requires-Dist: pandas>=1.5.0
Requires-Dist: numpy>=1.22.0
Requires-Dist: cattrs>=23
Provides-Extra: notebook
Requires-Dist: anywidget>=0.9; extra == "notebook"
Provides-Extra: test
Requires-Dist: pytest>=7.0.0; extra == "test"
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
Requires-Dist: pytest-xdist>=3.0.0; extra == "test"
Requires-Dist: hypothesis>=6.100.0; extra == "test"
Requires-Dist: jsonschema>=4.20.0; extra == "test"
Provides-Extra: dev
Requires-Dist: pysimlin[test]; extra == "dev"
Requires-Dist: pysimlin[notebook]; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Requires-Dist: ruff>=0.8.0; extra == "dev"
Requires-Dist: pandas-stubs>=2.0.0; extra == "dev"
Requires-Dist: types-cffi>=1.16.0; extra == "dev"
Requires-Dist: types-setuptools; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: setuptools>=70.1; extra == "dev"
Provides-Extra: notebooks
Requires-Dist: nbformat>=5.10; extra == "notebooks"
Requires-Dist: nbclient>=0.10; extra == "notebooks"
Requires-Dist: nbconvert>=7.16; extra == "notebooks"
Requires-Dist: ipykernel>=6.29; extra == "notebooks"
Requires-Dist: matplotlib>=3.8; extra == "notebooks"
Requires-Dist: pillow>=10.0; extra == "notebooks"
Provides-Extra: e2e
Requires-Dist: pysimlin[notebook]; extra == "e2e"
Requires-Dist: jupyterlab>=4.3; extra == "e2e"
Dynamic: license-file

# pysimlin

Python bindings for [Simlin](https://simlin.com), a system dynamics simulation engine.

## Features

- Load XMILE (`.stmx`, `.xmile`), Vensim (`.mdl`), sd-ai JSON, and Simlin JSON models
- Simulate with per-run parameter overrides; results as pandas DataFrames
- Loop dominance analysis ("Loops that Matter"): measure each feedback
  loop's contribution to behavior at every timestep, and find where
  dominance shifts
- Inspect model structure: variables, equations, causal links, feedback loops
- Edit models, or build them from scratch, through a transactional context manager
- Open a model file with `simlin.open()`: edits save back to the file in its
  own format, and changes other tools make to the file are picked up
- Display a model in a notebook cell to edit its diagram interactively; the
  editor writes to the model file and follows changes made to it
- Import Vensim `.vdf` binary output as DataFrames
- Generate SVG and PNG diagrams of the model's structure
- Full type hints

## Installation

```bash
pip install pysimlin                # simulate, analyze, edit, render diagrams
pip install "pysimlin[notebook]"    # + the interactive editor in notebook cells
```

The `notebook` extra adds [anywidget](https://anywidget.dev) (and through it
ipywidgets/IPython) -- a couple of dozen packages that a script, an MCP
server, or a CI install which never displays a model does not need, which
is why the bare install leaves them out. Without it everything else works;
displaying a model shows the static SVG diagram plus a warning with the
install line, and `model.widget()` raises `SimlinDependencyError`.

The distribution is named `pysimlin`; the importable package is `simlin`:

```python
import simlin
```

Requires Python 3.11+ on macOS (ARM64) or Linux (ARM64, x86_64). Depends on
numpy, pandas, cffi, and cattrs; the `notebook` extra adds anywidget.

## Quick Start

Build a logistic growth model, simulate it, and see which feedback loop
dominates when:

```python
import simlin
from simlin import Aux, Flow, Stock

project = simlin.Project.new(
    name="logistic-growth", sim_start=0, sim_stop=100, dt=0.25, time_units="years"
)

model = project.get_model()
with model.edit() as (_, patch):
    patch.upsert(Stock(name="population", initial_equation="50", inflows=["net_growth"]))
    patch.upsert(Flow(name="net_growth", equation="population * fractional_growth"))
    patch.upsert(Aux(
        name="fractional_growth",
        equation="max_growth_rate * (1 - population / carrying_capacity)",
    ))
    patch.upsert(Aux(name="max_growth_rate", equation="0.08"))
    patch.upsert(Aux(name="carrying_capacity", equation="10000"))

run = model.run()
print(f"final population: {run.results['population'].iloc[-1]:.0f}")

for loop in run.loops:
    print(f"{loop.id} ({loop.polarity}): average importance {loop.average_importance():.2f}")

for period in run.dominant_periods:
    print(f"t=[{period.start_time:.0f}, {period.end_time:.0f}] dominated by {period.dominant_loops}")
```

Output:

```
final population: 9359
b1 (B): average importance 0.34
r1 (R): average importance 0.66
t=[0, 67] dominated by ('r1',)
t=[67, 100] dominated by ('b1',)
```

The model has two feedback loops: the reinforcing compounding loop `r1`
(`population -> net_growth -> population`) and the balancing crowding loop
`b1` through `fractional_growth`. `run()` simulates with loop analysis
enabled, scoring every loop's contribution to behavior at every timestep.
The reinforcing loop dominates the first two-thirds of the run; as
population approaches the carrying capacity, the balancing loop takes over
-- the handoff at t=67 is the inflection point of the S-curve.

Loop ids (`r1`, `b1`) are stable identifiers assigned from the model's
structure; the polarity in parentheses is classified from the run's actual
behavior. The two usually agree, but they are independent claims: a loop
whose sign genuinely depends on parameter values (initialize `population`
above `carrying_capacity` and the compounding loop acts balancing) keeps
its structural id while the runtime polarity reports what the run really
did.

Every model is also a diagram. `render_svg()` draws the stock-and-flow
structure, computing a layout automatically for a model that doesn't
already carry one (`render_png()` is the bitmap sibling; in a notebook,
`model.diagram()` shows the same picture inline; nothing is persisted --
`project.auto_layout()` writes a layout into the model):

```python
from pathlib import Path

Path("logistic-growth.svg").write_bytes(project.render_svg())
```

<img src="https://raw.githubusercontent.com/bpowers/simlin/main/src/pysimlin/docs/logistic-growth.svg"
     width="431" alt="Stock-and-flow diagram of the logistic growth model">


## Examples

Complete, runnable programs live in
[`examples/`](https://github.com/bpowers/simlin/tree/main/src/pysimlin/examples):

- [`edit_existing_model.py`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/examples/edit_existing_model.py)
  loads an XMILE model, changes a flow's equation, and verifies the change
  alters behavior.
- [`population_model.py`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/examples/population_model.py)
  builds a model from scratch and validates the shape of its output.
- [`notebook_editor.ipynb`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/examples/notebook_editor.ipynb)
  opens a model file in a notebook, edits it in the interactive editor and
  from Python, and follows a change made by another tool -- the workflow for
  collaborating on a model with Claude Code.
- [`colab_quickstart.ipynb`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/examples/colab_quickstart.ipynb)
  is the same in Google Colab: `%pip install "pysimlin[notebook]"`, build and open a model,
  display the editor, simulate.

All of them run in CI on pull requests and pushes to `main` (the Colab notebook's `%pip` cell excepted).

## API Reference

Method-level documentation lives in the docstrings (`help(simlin.Model)`,
etc.); this section is a guided tour. Its examples continue with the
`model` built in Quick Start.

### Loading Models

`simlin.load()` reads a model file, auto-detecting the format from its
extension:

<!-- pysimlin-test: skip -->
```python
model = simlin.load("model.stmx")     # XMILE (.stmx, .xmile, .xml)
model = simlin.load("model.mdl")      # Vensim
model = simlin.load("model.sd.json")  # Simlin JSON (SD-AI JSON is detected by content)
project = model.project               # the containing Project
```

`load()` reads the file into memory. `simlin.open()` takes the same files
but keeps the model attached to the file, writing edits back and noticing
external changes; see [Editing and Saving Models](#editing-and-saving-models).

To start from nothing, create a project with `simlin.Project.new()` and add
variables with `model.edit()`, as in Quick Start.

### Working with Models

```python
from simlin import VARTYPE_STOCK, VARTYPE_FLOW, VARTYPE_AUX

names = model.get_var_names()                          # all variables
stocks = model.get_var_names(type_mask=VARTYPE_STOCK)  # just stocks

var = model.get_variable("population")   # Stock | Flow | Aux | Module | None
spec = model.time_spec                   # start, stop, dt, units

deps = model.get_incoming_links("net_growth")  # direct inputs of one variable
for link in model.get_links():                 # every causal link, with polarity
    print(link)                                # e.g. "fractional_growth --+--> net_growth"

print(model.explain("population"))
# population is a stock with initial value 50, increased by net_growth, ...

# Audit a model you loaded but didn't write: issues, or an empty tuple
for issue in model.check():
    print(f"{issue.severity}: {issue.message}")
```

### Model Editing

`model.edit()` opens a transaction: `current` maps variable names to their
definitions, and `patch` collects changes. Edits are validated and applied
together when the `with` block exits. An edit that would introduce a
circular dependency, an invalid equation, or a new unit error raises and
the model is unchanged, with the message naming the offending variable. A
completed `edit()` block needs no follow-up `check()` -- an accepted edit
is a valid model:

<!-- pysimlin-test: expect-error -->
```python
with model.edit() as (_, patch):
    patch.upsert(Aux(name="broken", equation="no_such_var * 2"))
```

Variables are frozen dataclasses -- the same `Stock`/`Flow`/`Aux` objects
everywhere, whether you read them or write them. To change one, derive an
updated copy with `dataclasses.replace` and `upsert` it:

```python
from dataclasses import replace

# Change an equation
with model.edit() as (current, patch):
    patch.upsert(replace(current["carrying_capacity"], equation="12000"))

# Add a harvest outflow: create the flow, then attach it to the stock
with model.edit() as (current, patch):
    patch.upsert(Flow(name="harvest", equation="population * harvest_fraction"))
    patch.upsert(Aux(name="harvest_fraction", equation="0.01"))
    stock = current["population"]
    patch.upsert(replace(stock, outflows=[*stock.outflows, "harvest"]))
```

### Editing and Saving Models

`simlin.load()` reads a file into memory; `simlin.open()` keeps the model
attached to its file. A file-backed model knows its `path` and format
(XMILE for `.stmx`/`.xmile`, Vensim for `.mdl`, Simlin JSON for `.sd.json`),
and every accepted edit is written straight back to that file, in that
format, with an atomic tempfile-and-rename write. `revision` counts accepted
changes; `dirty` says whether the file lags the in-memory model. To give an
in-memory project a file, `save_as()` it first (the suffix picks the format):

```python
import tempfile
from pathlib import Path

workdir = Path(tempfile.mkdtemp())
model_path = workdir / "logistic-growth.stmx"
project.save_as(model_path)

model = simlin.open(model_path)
print(model.path.name, model.revision, model.dirty)   # logistic-growth.stmx 0 False

with model.edit() as (current, patch):
    patch.upsert(replace(current["max_growth_rate"], equation="0.1"))

print(model.revision, model.dirty)   # 1 False: already written back to disk
print(simlin.load(model_path).get_variable("max_growth_rate").equation)   # 0.1
```

A variable added through `edit()` also gets a diagram element (existing
elements keep their positions) whenever there is a diagram to keep in step,
for two reasons: on any file-backed model, so the saved file stays openable
and draws correctly in Simlin, Stella, or `model.diagram()`; and on an
in-memory model that has a view -- one you displayed, or laid out with
`project.auto_layout()` -- so an editor showing it keeps up with what Python
adds. An in-memory model built from scratch has no view until you display it
or call `project.auto_layout()`; `model.diagram()` draws it with a transient
layout either way.

Every write regenerates the whole file from the in-memory model; it is not
a byte-preserving edit of what was there. For XMILE and Simlin JSON that is
the same document. For Vensim `.mdl` the file is re-emitted from Simlin's
model, so the first save of a Vensim-authored file shows a whole-file diff:
formatting is normalised, identifier casing is normalised, spaces
in unit names become `_`, and constructs Simlin does not carry are dropped:
unit ranges such as `[0,?]` silently, a non-negativity flag or a discrete
lookup with a `RuntimeWarning` (once per distinct message per project).
Keep the original under version control if that diff matters.

Pass `autosave=False` to batch changes: edits then set `dirty` and stay in
memory until `model.save()`. With autosave on (the default), `dirty` is only
ever true after a failed or refused write (disk full, permissions, or the
conflict below): the write raises and the in-memory change is kept until a
later `save()` succeeds.

Two suffixes are read-only: `.vpm` (a packaged Vensim model, read as MDL
text) and `.proto` (a schema suffix accepted for protobuf input). A model
opened from one is backed without write permission -- `model.writable` is
`False`, `autosave` is off and cannot be turned on for that path, edits (and
the diagram layout a display adds to a sketch-less model) stay in memory
with `dirty` set, and `save()` refuses -- so the packaged file is never
regenerated as plain MDL or as a binary blob. `project.save_as("x.mdl")`
keeps the changes and, since you never turned autosave off, autosaves from
there on. The path you open is anchored to an absolute one at that moment
(`model.path` reports it), so a later `%cd` or `os.chdir()` never moves
where autosave writes or what is watched.

`save()` never silently overwrites someone else's work. If the file changed
on disk since the model last read or wrote it, `save()` raises and leaves
both file and model as they are; `model.reload()` takes the on-disk version
(discarding local changes) and `model.project.save(force=True)` overwrites
it with yours. Likewise an `edit()` block whose model changed underneath it
(a reload from disk landed, or another thread edited) is rejected unapplied
-- re-run the block against the current contents.

The file is the shared truth between you and any other tool that edits it,
such as Claude Code rewriting equations in the file, or the `simlin` MCP
server. By default an opened model polls its file every half second (a
plain stdlib thread; pass `watch=False` to disable, `model.project.watch()`
to control it): an external change is loaded in place, `revision`
advances, cached results such as `base_case` are dropped, and the next
`model.run()` reflects it. Your own saves are recognised by content hash
and never round-trip as external changes; a file rewritten with unparsable
contents is not loaded (a `RuntimeWarning` names the problem and the last
good model stays); `model.reload()` forces a re-read and returns whether
anything changed. Subscribe to all of this with `on_change`:

```python
def announce(event):
    print(f"revision {event.revision} from {event.source}")   # edit | widget | disk | reload

unsubscribe = model.project.on_change(announce)
with model.edit() as (_, patch):
    patch.upsert(Aux(name="observed_growth", equation="net_growth / population"))
unsubscribe()
```

`model.reload()` returns `False` here -- the file holds exactly what we
wrote:

```python
print(model.reload())   # False
```

### Interactive Editing in Notebooks

A model displayed as a cell's value is the Simlin diagram editor, live.
`pip install "pysimlin[notebook]"` is all it needs: the editor and its
engine ship inside the wheel as an [anywidget](https://anywidget.dev), so
there is no extension to install and no sidecar process (anywidget rather
than a homegrown stack because it is what makes one widget render on every
host: VS Code's kernel needs `import ipywidgets`, marimo needs
`anywidget.AnyWidget`). Without the extra a displayed model shows its SVG
diagram and a `RuntimeWarning` with the install line in the displaying
cell's output; the model's plain-text repr in the same output carries the
line too (Python shows a given warning once per source location, so a
re-run of the same cell may not repeat it). It is verified on JupyterLab 4
(an automated browser journey runs in CI on pull requests and pushes to `main`) and expected to work
wherever anywidget does -- Notebook 7, VS Code, Google Colab, marimo --
with the checklist and the honest status of each host in
[`docs/notebook-hosts.md`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/docs/notebook-hosts.md)
([`examples/colab_quickstart.ipynb`](https://github.com/bpowers/simlin/blob/main/src/pysimlin/examples/colab_quickstart.ipynb)
is the two-minute Colab start; Colab itself is not yet verified -- if the
editor does not appear there, set `SIMLIN_WIDGET_ASSET=inline` before
`import simlin` and please report which worked). Static renderers get the
SVG diagram in the same output. Displaying a model that has no diagram yet
(one built from scratch with `edit()`, or a sketch-less `.mdl`) lays it out
first -- a committed change like `project.auto_layout()`, so `revision`
advances and a file-backed project WRITES THE FILE with the layout, even
for a `read_only=True` display: a Vensim `.mdl` without a sketch is
regenerated with one the first time it is shown.

<!-- pysimlin-test: skip -->
```python
model            # the last expression in a cell: shows the editor

widget = model.widget(height=500, theme="dark")   # or keep a handle
display(widget)
```

The file on disk is the single source of truth, so every collaborator sees
the same model:

- Each edit made in the editor (a new variable, an equation, a moved
  element) is written to `model.path` in its own format as soon as the
  kernel handles it -- immediately, even while a long cell runs, on
  ipykernel 7 (JupyterLab 4.4+); when the current cell finishes on older
  kernels -- and always before the next cell runs; `model.revision`
  advances and `model.run()` reflects it.
- `model.edit()` in a cell updates the editor in place with a short
  "Updated from Python" notice; an external write to the file (Claude Code
  editing it, the `simlin` MCP server, `git checkout`) does the same with
  "Updated on disk", and `model.reload()` with "Reloaded from disk". The
  editor's undo history resets on such remounts (its own edits never
  remount).
- The same model displayed in two cells stays consistent: an edit in one
  appears in the other.
- An edit made against a version the kernel has since moved past is
  rejected with a notice and never written; the editor reloads from the
  current model. If an edit is applied but the file cannot be written
  (disk full, permissions), the editor keeps it, a notice says so, and
  `model.dirty` is set until `model.save()` succeeds.
- `model.selection` is the tuple of variable names selected in the editor,
  so a cell can ask what the human is looking at:

```python
print(model.selection)   # () until something is selected in a displayed editor
```

`on_change` subscribers see editor saves as `source == "widget"`. With
`read_only=True` the editor shows the diagram without accepting edits;
`theme` is `"auto"` (follow the notebook), `"light"`, or `"dark"`.

Practical notes:

- **Widget lifetime.** Each display creates a kernel-side widget that stays
  subscribed to the model until it is closed (`widget.close()`, or
  `simlin.ModelWidget.close_all()`, which closes every model editor and no
  other widget); re-running a display cell leaves the previous one alive,
  which is harmless but worth knowing in long sessions.
- **Reopening a notebook.** JupyterLab shows "model not found" in place of
  a widget when a notebook is reopened without a running kernel or saved
  widget state; re-run the display cell. Hosts that save widget state into
  the notebook file (Colab does by default; JupyterLab does not) store the
  widget's JS module, about 1.5 MB, per displayed widget.
- **Static export.** The SVG in the same output is what nbconvert, GitHub,
  or a viewer without a kernel shows -- whenever the notebook carries no
  saved widget state. Plainly: the DEFAULT `jupyter nbconvert --to html
  --execute` stores that state and exports the widget itself, which in the
  exported page has no kernel to ask for its engine and so shows "Loading
  the Simlin engine..." and then a timeout message, not the diagram; pass
  `--ExecutePreprocessor.store_widget_state=False` to get the SVG diagram
  in the export (`make export-check` in `src/pysimlin` exercises both arms).
- **Asset delivery.** If the saved-state size is a concern, or the
  front-end cannot receive binary comm messages, set `SIMLIN_WIDGET_ASSET`
  **before** `import simlin`: `inline` embeds the engine wasm into the
  module (works everywhere, largest output), or an `http(s)://` URL loads
  the module from a server you run.
- **Very large models** display but cannot be edited from the editor: each
  edit travels browser-to-kernel as the whole project in JSON, and a Jupyter
  server drops websocket messages above 10 MiB (tornado's
  `websocket_max_message_size`) by closing the connection. The editor
  therefore refuses to send an edit whose snapshot, as it rides in the
  message (JSON-escaped), exceeds 8 MiB (`model.widget(max_snapshot_bytes=...)`
  sets the cap) with the notice "Edit not saved: the model is too large for
  the notebook connection ..." instead of hanging, and displaying such a
  model emits a `RuntimeWarning` up front. For scale, C-LEARN (911
  variables) is 1.4 MiB. Editing from Python is unaffected. To edit models
  that large in the editor, raise both limits:
  `jupyter lab --ServerApp.tornado_settings='{"websocket_max_message_size": 104857600}'`
  and `max_snapshot_bytes` at or below about 80% of that.

### Running Simulations

```python
# Simulate to the end of the configured time range
run = model.run()

# Override constants for a single run (parameters only, not computed variables)
run = model.run(overrides={"max_growth_rate": 0.12})

# The no-overrides run, computed once and cached
base = model.base_case
```

`run()` performs loop analysis by default; pass `analyze_loops=False` to
skip it when you only need the time series. Simulations are deterministic,
so runs are reproducible and diffable. To change the time range or `dt`,
update the project's sim specs first (`model.project.set_sim_specs()`).

For step-by-step control -- inspecting state mid-run, or intervening at a
specific time -- use `model.simulate()`:

```python
with model.simulate() as sim:
    sim.run_to(50.0)
    sim.set_value("max_growth_rate", 0.12)  # intervene at t=50
    sim.run_to_end()
    run = sim.get_run()
```

### Accessing Results

`Run.results` is a pandas DataFrame: the index is simulation time, with one
column per variable. Arrayed variables appear as one column per element
(`"stock[element]"`).

```python
df = run.results
print(df["population"].describe())
print(df.tail())

spec = run.time_spec       # start/stop/dt of this run
changed = run.overrides    # overrides used for this run
```

### Importing Vensim Data Files (VDF)

Vensim saves simulation output in a binary `.vdf` format. `simlin.load_vdf`
reads one directly (no model file needed) and returns a DataFrame shaped
exactly like `Run.results`. Simulation runs, sensitivity runs, and imported
dataset files are auto-detected from the file magic.

<!-- pysimlin-test: skip -->
```python
import pandas as pd

df = simlin.load_vdf("Current.vdf")
print(df["water_level"].iloc[-1])

# Compare a Vensim run against a Simlin re-simulation. The two frames
# have independent time indexes, so align on the shared time points.
run = simlin.load("model.mdl").run(analyze_loops=False)
comparison = pd.DataFrame(
    {"vensim": df["water_level"], "simlin": run.results["water_level"]}
).dropna()
```

### Model Interventions

Compare scenarios by running with different overrides:

```python
import pandas as pd

scenarios = {
    f"growth={rate}": model.run(overrides={"max_growth_rate": rate}).results["population"]
    for rate in [0.04, 0.08, 0.12]
}
print(pd.DataFrame(scenarios).tail())
```

### Feedback Loop Analysis

Every `run()` scores each feedback loop's contribution to model behavior at
every timestep, using the Loops that Matter method (Schoenberg, Eberlein &
Rahmandad, 2020):

- `run.loops` -- every feedback loop, with runtime polarity and a
  `behavior_time_series`: the loop's signed share, in [-1, 1], of the total
  loop activity in its part of the model at each timestep.
- `loop.average_importance()` / `loop.max_importance()` -- reductions of
  the absolute value of that series, in [0, 1]. Comparable across loops in
  the same cycle partition (see below), so they rank loops by dominance.
- `run.dominant_periods` -- contiguous intervals in which one set of
  same-polarity loops explains the majority of behavior.
- `run.ltm_mode` -- `"exhaustive"`, `"discovery"`, or `"disabled"` (see the
  next section).

```python
run = model.run()

most = max(run.loops, key=lambda loop: loop.average_importance() or 0)
print(f"most influential: {most.id}: {' -> '.join(most.variables)}")

for period in run.dominant_periods:
    print(f"t=[{period.start_time:g}, {period.end_time:g}]: {period.dominant_loops}")
```

Importance is normalized within a loop's *cycle partition* -- a group of
stocks connected by feedback. Models with several independent feedback
subsystems have several partitions, and scores are only comparable between
loops in the same one (`loop.partition` indexes `model.loop_partitions`); a
loop alone in its partition scores exactly 1 by construction.

For loop structure without simulating, use `model.loops`: the same loops
with structural polarity and no behavior series.

#### Loop Polarity

- **R (reinforcing)** -- amplifies change: every loop score positive.
- **B (balancing)** -- counteracts change: every loop score negative.
- **Rux / Bux (mostly reinforcing / mostly balancing)** -- mixed-sign
  scores with one side dominating; `loop.polarity_confidence` carries the
  ratio `|r - |b|| / (r + |b|)` (Schoenberg & Eberlein, 2020), and
  classification requires confidence >= 0.99.
- **U (undetermined)** -- mixed-sign scores with no dominant side.

```python
from simlin import LoopPolarity

reinforcing = [l for l in run.loops if l.polarity == LoopPolarity.REINFORCING]
balancing = [l for l in run.loops if l.polarity == LoopPolarity.BALANCING]
```

### Loop Discovery for Large Models

The surfaces above enumerate every feedback loop, which is only tractable
for smaller models. Past a size gate the engine switches to *discovery*
mode: `run()` emits a `RuntimeWarning`, `run.ltm_mode` reports
`"discovery"`, and `run.loops` is empty. For these models, call
`Model.analyze()` -- an explicit, timeout-guarded search for the loops that
drive behavior:

<!-- pysimlin-test: skip -->
```python
model = simlin.load("wrld3-03.mdl")   # World3: 311 variables
analysis = model.analyze(timeout=30.0)

if analysis.truncated:
    print("timeout elapsed; results are partial")

if not analysis.enumeration_complete:
    print("loops below are a sample, not every loop the model has")

for loop in analysis.loops[:3]:
    chain = " -> ".join(loop.variables[:3])
    print(f"{loop.id} ({loop.polarity}) importance {loop.average_importance():.3f}: {chain} ...")
```

Output for World3, the *Limits to Growth* model
([`test/metasd/WRLD3-03/wrld3-03.mdl`](https://github.com/bpowers/simlin/tree/main/test/metasd/WRLD3-03)
in the Simlin repository), where discovery finds 200 loops across 15
feedback-coupled stocks in under a second:

```
b51 (B) importance 0.052: population_0_to_14 -> maturation_14_to_15 -> population_15_to_44 ...
r55 (R) importance 0.033: persistent_pollution -> persistent_pollution_index -> land_fertility_degredation_rate ...
b24 (B) importance 0.031: persistent_pollution -> persistent_pollution_index -> land_fertility_degredation_rate ...
```

`analysis.loops` is ranked most-important-first, except that loops with no
competition in their cycle partition sort last (their relative score is 1
by construction and says nothing). `analysis.partitions` describes the
partitions; on models with more than one, compare loops within a partition,
as above. `analysis.dominant_periods` is also available, but with hundreds
of loops the per-timestep dominant sets are fine-grained -- ranking by
`average_importance()` and reading the top loops' variable chains is
usually the more legible summary.

Three fields say how complete that list is.
`analysis.enumeration_complete` distinguishes an EXACT analysis -- the engine
enumerated every loop that could ever score and picked from that whole set --
from a SAMPLED one, where a budget cut the enumeration short and a
shortest-path search stood in for it; a loop missing from a sampled analysis
is not evidence the model lacks it. `analysis.universe_loops` is how large
that enumerated universe was (`None` when sampled, which is a different claim
from `0`), and `analysis.retained_loops` is how many loops cleared the
importance filter before the report cap. On a model like World3 both run to
thousands against the 200 loops reported, which is what tells you the list is
a ranked prefix rather than the whole story.

Two details worth knowing: the `timeout` bounds only the discovery sweep --
the model is first compiled and simulated with loop instrumentation, and
that time is not counted against it; and if there are specific loops you
always want scored, pin them by name with `patch.set_loop_name()` inside
`model.edit()`.

### Link Scores

Loop scores are built from link scores: with loop analysis enabled, every
causal link is scored at every timestep. `average_relative_score()` gives
the fraction of the target's change attributable to that input, in
[-1, 1] -- use it to rank the inputs of one variable:

```python
with model.simulate(enable_ltm=True) as sim:
    sim.run_to_end()
    links = sim.get_links()

inputs = [ln for ln in links if ln.to_var == "net_growth"]
inputs.sort(key=lambda ln: abs(ln.average_relative_score() or 0), reverse=True)
for ln in inputs:
    print(f"{ln}: {ln.average_relative_score():.2f}")
```

The normalization is per target, so relative scores answer "which of this
variable's inputs matters most" -- not "which link matters most globally".
A link into a target with a single scored input reads 1 by construction.
(The raw `link.score` series is normalized differently for each target and
is not comparable across targets at all.)

### Model Export

```python
xmile_bytes = project.to_xmile()        # XMILE XML
json_bytes = project.serialize_json()   # Simlin JSON
```

To save to a file, prefer `project.save_as(path)` (or `save()` on a
file-backed project): it picks the format from the suffix and writes
atomically.

### Error Handling

`project.get_errors()` reports compilation problems for the whole project;
`model.check()` presents the same information per model.

```python
from simlin import SimlinImportError, ErrorCode

for error in project.get_errors():
    print(f"{error.code.name} in {error.model_name}/{error.variable_name}: {error.message}")
```

Loading a malformed file raises `SimlinImportError`:

<!-- pysimlin-test: skip -->
```python
try:
    model = simlin.load("model.stmx")
except SimlinImportError as e:
    print(f"import failed: {e}")
    if e.code == ErrorCode.XML_DESERIALIZATION:
        print("invalid XML")
```

## Complete Example

Load a model from a file and compare a policy against the baseline:

<!-- pysimlin-test: skip -->
```python
import matplotlib.pyplot as plt
import simlin

model = simlin.load("population_model.stmx")
baseline = model.base_case
policy = model.run(overrides={"birth_rate": 0.03})

fig, ax = plt.subplots()
ax.plot(baseline.results.index, baseline.results["population"], label="baseline")
ax.plot(policy.results.index, policy.results["population"], label="policy")
ax.set_xlabel("time")
ax.set_ylabel("population")
ax.legend()
plt.show()
```

## License

Apache License 2.0

## Development

pysimlin is developed in the
[Simlin monorepo](https://github.com/bpowers/simlin) (`src/pysimlin`).
