# run_model

Python reference for `nagasim.api.run_model`.

`nagasim.api.run_model`

```python
run_model(path, replications: int | None = None, seed: int = 0, warmup: float | None = None, run_length: float | None = None, workers: int | str = 1, on_progress = None, should_stop = None, trace = None, bind_data: bool = False, base_dir = None, network = None, confine_to = None, feed = None, controllers: dict | None = None, pool = None, logic: str | ModuleType | None = None, record_logs: bool | None = None, deterministic: bool | None = None, pace: float | None = None, keep_empty: bool = False, log_level: str | None = None)
```

Run replications of a model and return its KPI frames.

Replication ``r`` is seeded with ``seed + r``, so a run is reproducible.

Parameters
----------
path : str or dict
    A model file path, the name of a bundled model (``"single_server"``; a file at that
    path wins), or an already-loaded layout dict (nothing is written to
    disk for a dict).
replications, warmup, run_length : optional
    Fall back to the model's own ``simulation`` section when left None; an
    explicit value (0 included) always wins. A warm-started model (a non-empty
    ``initial_state``) defaults its warm-up to 0, because the initial state is
    the history a warm-up would otherwise build. A model with no run length
    and no other way to stop raises `ModelValidationError`, as it would
    otherwise run forever.
seed : int, default 0
    Seed of replication 0.
workers : int or "auto", default 1
    More than 1 spreads the replications over a process pool; the output is
    identical to a sequential run. ``"auto"`` times replication 0 first and
    switches to a pool only when at least 3 more replications remain and that
    one took 1 s or more.
on_progress : callable, optional
    ``on_progress(done, total)`` after each completed replication.
should_stop : callable, optional
    Polled between replications and during one; on an interruption only the
    completed replications are returned.
trace : TraceRecorder, optional
    Subscribed to replication 0 only, which then runs in this process.
bind_data : bool, default False
    Resolve the model's data bindings once, before the first replication, so
    every replication runs on the same bound values. The `BindingReport`
    comes back as the extra ``"data_inputs"`` frame; a binding that fails is
    a row with its problem, never an exception.
base_dir : path, optional
    What a source's relative ``location`` resolves against (default: the
    model file's folder).
network : NetworkPolicy, optional
    The caller's `netguard.NetworkPolicy`. Without one a ``sql`` or
    ``json_url`` source is refused, whatever the model file says.
confine_to : path, optional
    The one directory a file-backed source may be read from.
feed : Feed, optional
    The caller's open `live.Feed`; live sources are answered from it, in this
    process.
controllers : dict, optional
    ``{policy name: Controller}`` for every policy-mode DECIDE block. With
    ``workers != 1`` they must be picklable.
logic : str or module, optional
    The module LOGIC blocks take their classes from first, by dotted name (on
    ``sys.path``) or as an imported module; a class it lacks still comes from
    ``nagasim.core.custom_logic``. Only the caller names it, never the model
    file. With ``workers != 1`` each worker imports it again by name.
pool : ProcessPoolExecutor, optional
    A pool the caller owns and reuses across calls (see `scenario_pool`), so
    a study pays the process start-up once. Results are identical. Build it
    with `new_pool`, so a worker that never starts raises instead of hanging.
record_logs : bool, optional
    False switches the per-event logs off: the log frames have no rows, so
    they are left out (see *keep_empty*), and every summary statistic is
    untouched. None keeps the model's own setting (default: on).
deterministic : bool, optional
    True makes every distribution sample its mean, chance branches use
    largest-remainder allocation and replications are forced to 1. None keeps
    the model's own ``simulation.deterministic`` (default: off).
pace : float, optional
    Keep pace with the wall clock: *pace* model seconds per wall second
    (1 = real time, 60 = one model minute per second), converted from the
    model's time unit. An event already behind the wall clock runs at once
    and is counted, never raised. The results are an unpaced run's; the
    result's ``.pace`` is ``{"paced", "late_events", "max_lag_s"}``.
    Replications run one after another (``workers`` must be 1). Nothing is
    fed into or read out of the running model.
keep_empty : bool, default False
    Also return the frames with no rows (D1321): by default only the frames
    that have rows come back, plus ``"system"`` always and ``"data_inputs"``
    when *bind_data* asked for it. True returns every frame the engine
    builds, each with its columns; the KPI reference generator uses it.
log_level : str, optional
    What the run records (D1395): ``"kpi"`` (the summary frames only), ``"series"`` (plus
    ``"timeseries"`` and ``"dashboard"``) or ``"full"`` (plus the entity, resource and store
    logs), or a profile: ``"study"`` (kpi), ``"explore"`` and ``"replay"`` (full). It beats the
    model's own ``simulation.log_level``, ``record_logs`` and ``timeseries_points`` (never
    raising the latter). A frame it leaves out raises `NotRecordedError` naming the level to
    re-run at. None (the default) keeps the model's settings: full unless it says otherwise.
    Not together with *record_logs*.

Returns
-------
Results or None
    A `Results` (a ``dict[str, pandas.DataFrame]``) of the KPI frames
    concatenated over the completed replications, each tagged with a ``Run``
    column, with ``.kpis()``, ``.kpi(key)``, ``.plot(key)`` and
    ``.to_excel(path)`` on top. Only frames with rows are returned (a single
    server gets about 7), so test for an optional one with
    ``"store_summary" in results`` or ``results.get("store_summary")``.
    None if no replication completed.

See Also
--------
nagasim.experiments.run_scenarios : Several variants of one model, compared.
nagasim.experiments.run_until_precision : Replicate until an interval is tight enough.
nagasim.experiments.flatten_kpis : The KPI frames as one long table.

Examples
--------
>>> from pathlib import Path
>>> import nagasim
>>> from nagasim import api
>>> path = Path(nagasim.__file__).parent / "models" / "single_server.json"
>>> results = api.run_model(str(path), replications=2, run_length=200, warmup=20, seed=0)
>>> sorted(int(r) for r in results["system"]["Run"].unique())
[0, 1]
>>> results.kpi("system/Total Entities Completed") > 0
True
