# Results

Python reference for `nagasim.results.Results`.

`nagasim.results.Results`

```python
Results()
```

What a run returns: KPI frames by name, with notebook conveniences.

A ``dict[str, pd.DataFrame]`` (the KPI frames that have rows, each with a
"Run" column; ``"system"`` is always there), so ``results["system"]`` works
as on any dict; a frame the run left empty is absent, so test for it with
``"store_summary" in results`` or ``results.get("store_summary")``. The methods
add the mean over runs, a plot and an Excel workbook. Made by
`nagasim.api.run_model`, ``Model.run`` and the experiment functions (which keep
every frame of a scenario, empty or not).

See Also
--------
nagasim.api.run_model : Makes it.
nagasim.build.Model : ``Model.run`` returns it.
nagasim.experiments.flatten_kpis : The 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, seed=0)
>>> sorted(results["system"].columns)
['Metric', 'Run', 'Value']
>>> results.kpi("system/Total Entities Completed") > 0
True

### `nagasim.results.Results.kpi`

```python
kpi(key: str)
```

Return the mean over runs of one KPI.

Parameters
----------
key : str
    The KPI's "family/name" key, for example ``"system/Avg Queue
    Length"``.

Returns
-------
float
    The mean over runs. The spread is in `Results.kpis`.

Raises
------
KeyError
    If *key* is not a KPI of these results (the message names it).

See Also
--------
Results.kpis : All KPIs, with spread.

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, seed=0)
>>> results.kpi("system/Total Entities Completed") > 0
True

### `nagasim.results.Results.interval`

```python
interval(key: str)
```

Return one KPI's mean with its 95% interval over runs.

Parameters
----------
key : str
    The KPI's "family/name" key, as in `Results.kpi`.

Returns
-------
Interval
    ``(mean, half_width, n)``; the half-width is NaN with one replication. It is the
    ``ci95`` of `Results.kpis` and of ``naga run --json``.

Raises
------
KeyError
    If *key* is not a KPI of these results (the message names it).

See Also
--------
Results.kpi : The mean alone.
Results.kpis : Every KPI, with its interval.

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=3, run_length=200, seed=0)
>>> results.interval("system/Total Entities Completed").n
3

### `nagasim.results.Results.kpis`

```python
kpis()
```

Return the KPIs as one table: mean, spread and interval over runs.

Built from the stable "family/name" keys of
`nagasim.experiments.flatten_kpis`, such as ``"system/Avg Queue
Length"`` or ``"resource/Server/Usage % (snapshot)"``.

Returns
-------
pandas.DataFrame
    Columns ``metric``, ``mean``, ``std`` and ``ci95`` (the 95%
    half-width), one row per KPI.

See Also
--------
Results.kpi : One KPI's mean.
nagasim.experiments.flatten_kpis : One row per KPI and run.

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, seed=0)
>>> list(results.kpis().columns)
['metric', 'mean', 'std', 'ci95']

### `nagasim.results.Results.checks`

```python
checks()
```

Return the law checks of this run, computed once and kept.

The checks of `nagasim.laws.checks` (utilisation, offered load,
Little's law, flow conservation, censoring, initial bias), judged with
the warm-up the run used. They are shown, never enforced: a check that
cannot be computed gives an empty `RunChecks` with a ``note``, never an
exception.

Returns
-------
RunChecks
    ``.partial`` holds the warnings, ``.passed`` counts the rest.
    Results not made by `nagasim.api.run_model` (built by hand, loaded
    back) have no layout: ``note == "no layout"`` and no checks.

See Also
--------
nagasim.laws.checks : The checks themselves, on any layout and results.
Results.kpis : The KPI table the checks qualify.

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, seed=0)
>>> results.checks().passed > 0
True

### `nagasim.results.Results.frame`

```python
frame(name: str)
```

Return the KPI frame *name*; an alias for ``results[name]``.

Parameters
----------
name : str
    A frame name, such as ``"system"`` or ``"resource_summary"``.

Returns
-------
pandas.DataFrame
    The frame, one row per metric and run. A frame the run left empty is
    absent and raises KeyError (D1321).

See Also
--------
Results.kpis : The mean over runs, one row per KPI.

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, seed=0)
>>> list(results.frame("system").columns)
['Metric', 'Value', 'Run']

### `nagasim.results.Results.plot`

```python
plot(key: str, ax = None, kw = {})
```

Plot one KPI or one time series.

A KPI key gives a bar of the mean with a 95% interval whisker over
runs; a ``timeseries`` series (a level, an auxiliary, a flow) gives a
line over time. Whichever *key* matches is drawn.

Parameters
----------
key : str
    A KPI key such as ``"system/Avg Queue Length"``, or a series name
    such as ``"level/Tank"``.
ax : matplotlib.axes.Axes, optional
    Where to draw; a new figure when omitted.
**kw
    Passed to matplotlib's ``bar`` or ``plot``.

Returns
-------
matplotlib.axes.Axes
    The axes drawn on.

Raises
------
KeyError
    If *key* is neither a KPI key nor a series of these results.
ImportError
    If matplotlib (not a core dependency) is missing; the message says
    how to install it.

See Also
--------
Results.kpis : The numbers behind the bar.

Examples
--------
>>> import matplotlib
>>> matplotlib.use("Agg")
>>> 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, seed=0)
>>> ax = results.plot("system/Total Entities Completed")
>>> ax.get_ylabel()
'system/Total Entities Completed'

### `nagasim.results.Results.to_excel`

```python
to_excel(path)
```

Write the results as an Excel workbook, one sheet per frame.

Parameters
----------
path : str or os.PathLike
    The ``.xlsx`` file to write.

Returns
-------
None

See Also
--------
Results.frame : One frame, as a DataFrame.

Examples
--------
>>> import tempfile
>>> from pathlib import Path
>>> 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, seed=0)
>>> with tempfile.TemporaryDirectory() as folder:
...     results.to_excel(Path(folder) / "results.xlsx")
...     (Path(folder) / "results.xlsx").is_file()
True

### `nagasim.results.Results.not_recorded`

```python
not_recorded(name: str)
```

Return the error for data this run's log level did not record (D1395).

Parameters
----------
name : str
    A frame (``"entity_log"``), a ``"frame.column"`` or a KPI key
    (``"resource/Server/Queue Len P95"``, ``"timeseries/system/WIP/max"``).

Returns
-------
NotRecordedError or None
    The error whose message names the level to re-run at, or None when the
    run recorded *name* (or it never existed, or no level was named).

See Also
--------
nagasim.api.run_model : Its ``log_level`` argument sets the level.

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), run_length=200, seed=0, log_level="kpi")
>>> results.log_level
'kpi'
>>> print(results.not_recorded("entity_log"))
'entity_log' was not recorded: this run was at level kpi; re-run with log_level='full'
>>> results.not_recorded("system") is None
True
