# Model

Python reference for `nagasim.build.Model`.

`nagasim.build.Model`

```python
Model(top = {})
```

A model written in Python; the file it produces is the model.

Every block type is a method named after it, taking the block's parameters
by name; ``a >> b`` links two blocks; ``add_resource`` and the like add an
entry to a list of the file. Keywords are the run settings (``time_limit``,
``warmup``, ``replications``, every key of ``simulation``) and the top-level
sections (``info``, ``network``, ``simulation``, ...).

Parameters
----------
**top
    Run settings and top-level sections. An unknown keyword raises
    ``TypeError`` naming the valid ones; a run setting given both as a
    keyword and inside ``simulation=`` raises too.

See Also
--------
nagasim.build.export_python : The reverse, a model file as builder code.
nagasim.modelfmt.minimal : The form ``to_dict`` returns.

Examples
--------
>>> from nagasim import build as nb
>>> m = nb.Model(time_limit=100, replications=2)
>>> m.add_resource(name="Server")
'Server'
>>> arrive = m.create(distribution=nb.Exponential(rate=1.0))
>>> serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25))
>>> _ = arrive >> serve >> m.dispose()
>>> [b["type"] for b in m.to_dict()["blocks"]]
['CREATE', 'PROCESS', 'DISPOSE']
>>> m.run(seed=0).kpi("system/Total Entities Completed") > 0
True

### `nagasim.build.Model.run`

```python
run(options = {})
```

Run the model; ``api.run_model(self.to_dict(), **options)``.

Parameters
----------
**options
    The options of `nagasim.api.run_model` (``replications``,
    ``seed``, ``warmup``, ``run_length``, ``workers``, ...).

Returns
-------
Results or None
    The KPI frames; None if no replication completed.

See Also
--------
nagasim.api.run_model : The options, in full.
nagasim.results.Results : What it returns.

Examples
--------
>>> from nagasim import build as nb
>>> m = nb.Model(time_limit=100)
>>> m.add_resource(name="Server")
'Server'
>>> arrive = m.create(distribution=nb.Exponential(rate=1.0))
>>> serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25))
>>> _ = arrive >> serve >> m.dispose()
>>> m.run(seed=0).kpi("system/Total Entities Completed") > 0
True

### `nagasim.build.Model.to_dict`

```python
to_dict()
```

Return the model as a dict, in the form ``naga fmt`` writes.

Returns
-------
dict
    The model file's content: only the keys that differ from the
    defaults, in the file's order.

See Also
--------
nagasim.build.Model.save : Writes it to a file.
nagasim.modelfmt.minimal : The function that makes this form.

Examples
--------
>>> from nagasim import build as nb
>>> m = nb.Model(time_limit=50)
>>> _ = m.create() >> m.dispose()
>>> [b["type"] for b in m.to_dict()["blocks"]]
['CREATE', 'DISPOSE']

### `nagasim.build.Model.save`

```python
save(path: str | PathLike[str])
```

Write the model to a file, and nothing else.

Parameters
----------
path : str or os.PathLike
    The model file to write (UTF-8, LF line ends).

Returns
-------
pathlib.Path
    *path*.

See Also
--------
nagasim.build.Model.to_dict : The content, as a dict.

Examples
--------
>>> import tempfile
>>> from pathlib import Path
>>> from nagasim import build as nb
>>> m = nb.Model(time_limit=50)
>>> _ = m.create() >> m.dispose()
>>> with tempfile.TemporaryDirectory() as folder:
...     m.save(Path(folder) / "model.json").name
'model.json'

### `nagasim.build.Model.definition`

```python
definition(name: str, fields: Any = {})
```

Add a submodel definition and return its canvas.

Parameters
----------
name : str
    The definition's name; an instance of it is
    ``m.submodel(definition=name, ...)``.
**fields
    The definition's keys: ``info``, ``parameters``, ``scoped``, ...

Returns
-------
Level
    A canvas with the same block methods and ``link`` as the model.

See Also
--------
nagasim.build.Model.link : Links blocks on a level.

Examples
--------
>>> from nagasim import build as nb
>>> m = nb.Model()
>>> sub = m.definition("Station")
>>> _ = sub.process("Work")
>>> m.to_dict()["submodels"]["Station"]["blocks"][0]["name"]
'Work'

### `nagasim.build.Model.link`

```python
link(source: Block | str, target: _End, fields: Any = {})
```

Link *source* to *target*; ``a >> b`` calls this.

Parameters
----------
source, target : Block or str
    The ends: blocks of this level, or block names. A block made on
    another level raises ``ValueError``.
**fields
    The link's own keys: ``delay``, ``source_port``, ``target_port``,
    ``capacity`` (with a delay, an area link).

Returns
-------
Block or str
    *target*, so links chain; a name ends a chain.

See Also
--------
nagasim.build.Model.definition : A second level to link within.

Examples
--------
>>> from nagasim import build as nb
>>> m = nb.Model()
>>> a, b = m.create(), m.dispose()
>>> m.link(a, b) is b
True
>>> m.to_dict()["links"]
[{'source': 'create_1', 'target': 'dispose_1'}]
## List builders

Each `add_*` method appends one entry to a list of the model file and returns the entry's key (its name, or its id for an order). The keywords are the entry's keys ([Model file keys](../schema.md)); an unknown keyword raises `TypeError` naming the valid ones. Each block type is a method too, named after the type in lower case (`m.process(...)`), and returns a block that `>>` links; see [Blocks](../blocks/index.md).

```python
from nagasim import build as nb
m = nb.Model()
m.add_resource(name="Server", capacity=2)     # returns 'Server'
```

| Method | Adds to | Key | What the list holds |
|---|---|---|---|
| `add_scenario` | `scenarios` | `name` | Named parameter-override sets, run and compared by `nagasim.experiments`. |
| `add_order` | `orders` | `id` | Released jobs with a due date, emitted by a CREATE block in "Orders" arrival mode. |
| `add_resource` | `resources` | `name` | Named resources: capacity, queue discipline, optional ranking expression, capacity schedule, cost fields. |
| `add_resource_set` | `resource_sets` | `name` | Named groups of resources with a selection rule, seized as one pseudo-resource. |
| `add_schedule` | `schedules` | `name` | Piecewise-constant arrival-rate or capacity schedules, optionally repeating. |
| `add_failure` | `failures` | `name` | Resource failures: uptime/downtime distribution pairs per named resource group. |
| `add_table` | `tables` | `name` | Named 1-D/2-D lookup tables read by TABLE("name", k1[, k2]) in any expression. |
| `add_sequence` | `sequences` | `name` | Named routings: ordered steps through STATION blocks, walked by a ROUTE block. |
| `add_variable` | `variables` | `name` | Model-level variables, read and written by expressions; reset to `initial` each replication. |
| `add_entity` | `entities` | `name` | Entity types: shape, colour, optional size and WIP holding cost. |
| `add_timeseries_input` | `timeseries_inputs` | `name` | Named time-series profiles read by TS("name") in any expression. |
| `add_level` | `levels` | `name` | Continuous quantities with bounds (battery energy, tank volume, an inventory position), read by LEVEL("name"). |
| `add_flow` | `flows` | `name` | Rate-based transfers between levels, re-evaluated at events. |
| `add_conversion` | `conversions` | `name` | Delayed conversions with a yield curve: feed in, product released over the following hours or days. |
| `add_fixed_cost` | `fixed_costs` | `name` | Costs of the scenario rather than of the run: capex (flagged `capex: true` for the investment case), or an annuity over a sized parameter. |
| `add_fleet` | `fleets` | `name` | Pools of vehicles that carry entities on the network; a fleet is a resource under its own name. |
| `add_motion_profile` | `motion_profiles` | `name` | How robots, people and mechanisms move: speed, acceleration, payload derating and a collaborative speed, named by a MOTION block's `profile`. |
| `add_robot` | `robots` | `name` | Robots: a structure with its dimensions, or a joint chain, with each axis's range, speed and acceleration, and the tool frame; named by a MOTION block's `robot`. |
| `add_pallet_pattern` | `pallet_patterns` | `name` | Pallet patterns: the pallet, the item, layer layouts and how they stack, and the limits that close a pallet; named by a carrier BATCH's `pattern`. |
| `add_zone` | `zones` | `name` | Safety zones: a network node and a radius that a MOTION block's or a tending group's `zone.name` binds to; a worker inside slows the robot to its collaborative speed. |
| `add_charger` | `chargers` | `name` | Chargers and battery-swap stations at network nodes, used by fleets that declare a `battery`. |
| `add_auxiliary` | `auxiliaries` | `name` | Named expressions read by AUX("name"), evaluated on read. |
| `add_delay` | `delays` | `name` | Delays read by DELAY("name"): input, delay time, kind and order. |
| `add_subscript` | `subscripts` | `name` | Dimensions: a record with "dims" is flattened into one record per element. |
| `add_agent_type` | `agent_types` | `name` | Statecharts run for every agent of a population: parameters, states, transitions. |
| `add_population` | `populations` | `name` | Agent populations: a type, a count and an initial placement. |
| `add_reality_check` | `reality_checks` | `name` | Vensim-style reality checks: a test input and a constraint the model must then satisfy. |
| `add_data_source` | `data_sources` | `name` | Declared CSV/Excel/SQLite/SQL/JSON sources model parameters can be read from. |
| `add_data_binding` | `data_bindings` | `name` | Which column, filtered and transformed how, feeds which override path. |
