# Naga: full documentation > A simulation engine for Python, built on SimPy. Every page of the site as one text file, in the order of its menu. The list of pages with a sentence each is llms.txt. --- Page: Home URL: https://thematthub.github.io/naga/index.html # Naga Naga is a simulation engine for Python, built on [SimPy](https://simpy.readthedocs.io/): you describe a system as a model file, and it runs the model and gives back an answer with its confidence interval. Python 3.11 or later; the `naga` command comes with it. ```console pip install nagasim ``` Ten lines build the textbook single-server queue, run it twenty times and set the result beside the exact answer: ```python from nagasim import build as nb lam, mu = 1.0, 1.25 # customers arrive, and are served, per minute m = nb.Model(time_limit=5500, warmup=500, replications=20) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=lam)) serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=mu)) arrive >> serve >> m.dispose() row = m.run(seed=0).kpis().set_index("metric").loc["resource/Server/Time in Queue Avg"] print(f"simulated mean wait {row['mean']:.2f} +/- {row['ci95']:.2f} minutes (95% interval)") print(f"exact, M/M/1 {lam / mu / (mu - lam):.2f} minutes") ``` ```text simulated mean wait 3.30 +/- 0.29 minutes (95% interval) exact, M/M/1 3.20 minutes ``` The simulated interval brackets the exact value, which is what a trustworthy simulator does and what the [reference models](validation/reference-models.md) page checks against known answers. It also shows the point of Naga: the same clock runs discrete-event processes, system dynamics, agents and continuous levels with exact crossing times, so one model can hold all four. ![What goes into the engine, what it does, and what comes out](img/overview.svg) The engine works in four stages: it checks the model file, runs it on one clock, proves results with replications and scenarios, and follows a live plant. What comes back is results with their law-check warnings, web pages to share (a replay and a viewer) and forecasts.
- **Python modeller** --- Build a model in code, run replications, read the results. [Learning path](learn/index.md), [Quick start](quickstart.md) and the [Python API](python-api.md) - **Planner or analyst** --- See what a finished study looks like, then compare scenarios of your own. [Worked examples](worked-examples/airport-ground-support.md), [Experiments](experiments.md) and [reading results](learn/6-results.md) - **Integrator** --- Run it from a pipeline, check files in CI, build on the formats. [Command line](reference/cli/index.md), [model file keys](reference/schema.md) and [MCP](mcp.md) - **AI agent** --- Read the site as plain text, validate against the schema, call the tools. [llms.txt](llms.txt), [llms-full.txt](https://thematthub.github.io/naga/llms-full.txt) (the whole site as one file), a Markdown copy of every page (its address with `.md`), the [JSON Schema](schema/model-v32.json) and the [agent tools](reference/tools.md)
## What you can model - **Processes and queues**: blocks (create, process, seize and release, batch, match, decide, route, transport, ...) joined by links, with resources, sets, schedules, failures, costs, expressions and submodels. - **Material handling**: path networks, vehicle fleets with batteries and chargers, conveyors, motion cycles, machines tended by mobile robots. - **Stocks and flows** (system dynamics: auxiliaries, delays, subscripts, units, XMILE and Vensim import) and **agents** (statecharts, messages, space, networks), in the same model as the processes. - **Rates**: tanks, batteries and other quantities that fill and drain continuously, with exact crossing times. ## What it does around a run - **Statistics you can defend**: independent replications, Student-t intervals, warm-up handling, reproducible random streams, checked against models with a known answer. - **Experiments**: named scenarios with paired comparisons, design of experiments, ranking-and-selection, optimisation, calibration and an investment case. - **A twin of a plant**: readers for files, SQL, REST, MQTT, OPC UA and Modbus TCP, a run that starts from the plant's state, forecasts scored against what then happened, and actions compared on the forecast. The twin reads and proposes; the one writer is `naga plc-write`, which runs only on a person's command and writes to a soft PLC on the same machine (loopback only). - **Outputs**: pandas frames, Excel, CSV, JSON, a self-contained HTML report, a recorded run to replay, and a viewer in which the engine runs in a reader's browser. ## Three ways in - **The command line**: `naga run single_server --report report.html` runs a bundled model and writes its report; `naga --help` lists every command. - **Python**: `nagasim.api.run_model` runs a file and returns pandas frames, and `nagasim.build` writes a model in code, with your editor completing every parameter. See the [Quick start](quickstart.md) and the [Python API](python-api.md). - **An agent**: an MCP server offers the same operations as tools, so an assistant can build, validate, run and explain a model. See [Use with an agent](mcp.md). Whichever way you use, the model is the same JSON file, so what one person builds in Python an agent can check and a colleague can open. ## What's new in 0.21 - **Answers that say yes or no.** A study's write-up, control room and slides open with Yes, No or Not clear yet, judged from each goal's 95% interval, and explain the terms they use. A run whose law checks fail reads "not valid" with the reason; a run that may be biased low (people still inside at the end, a cold start) keeps its numbers with that caveat. - **Studies a person checks.** `naga study confirm` records a person's own check that the model matches reality, and each option's difference from the Baseline comes with its paired 95% interval. - **The whole model is validated.** A misspelt key at any level is named with the nearest valid one, scenario override paths are checked, and a zero, negative or empty distribution value is refused before the run. - **Lean results.** `run_model` and `run_scenarios` return only the result frames that have rows, as in the snippet below; `keep_empty=True` gives every frame. `uncertainty.input_uncertainty_frame` gives input uncertainty as a table, and `naga uncertainty --out` writes it. - **Before you upgrade.** `results["store_summary"]` on a frame with no rows now raises a KeyError that names the change: use `results.get(...)`, `in`, or `keep_empty=True`. MCP clients read the structured answer instead of the text. Models with a zero or negative distribution value are refused. Bundled models give the same results as 0.20.1 (62 of 62, on two seed sets). ```python from nagasim import api results = api.run_model("single_server", replications=2, seed=0) print(sorted(results)) # only the frames that have rows print(results.get("store_summary")) # None: this model has no store ``` All releases: [What's new](whats-new.md) for the highlights, [Release notes](changelog.md) for every change. ## What it is not - **Not an editor.** There is no window, no canvas and no animation here. `naga run --player` writes one HTML file that replays a run in a browser, and `naga viewer` one in which a reader re-runs the model; those are the only pictures. Naga Studio, a desktop editor built on Naga, adds the canvas, 2D and 3D views, videos of a run and a package for a client, and opens and saves the same model files. - **Not SimPy with helpers.** You do not write generator functions. A model is data, even when Python code builds it, and what a block can do is fixed by its type and its expressions. When the logic you need is not a block, raw SimPy is the better tool: see [Coming from SimPy](coming-from/simpy.md). - **Not stable yet.** Before 1.0 the Python API may change between minor versions. Model files always migrate forward, and agent tool names and problem codes are permanent. ## Where to go | You want to | Read | |---|---| | run something in a minute | [Quick start](quickstart.md) | | see what a model looks like and what it gives | [Gallery](gallery/index.md) | | check the engine against models with a known answer | [Reference models](validation/reference-models.md) | | map what you know onto this | Coming from [SimPy](coming-from/simpy.md), [Arena](coming-from/arena.md), [AnyLogic](coming-from/anylogic.md), [Vensim](coming-from/vensim.md), [NetLogo](coming-from/netlogo.md) | | write a model file | [Model file format](model-file-format.md), [Blocks](reference/blocks/index.md) | | know what a part of a model does when it runs | [Modelling guide](modelling-guide/index.md) | | compare, search and check models | [Experiments](experiments.md), [Model assertions](model-assertions.md), [Semantic diff](semantic-diff.md) | | call it from a script or a notebook | [Python API](python-api.md) | | let an agent build and run models | [Use with an agent](mcp.md) | | give someone a model they can run in a browser | [Sharing a model](sharing-a-model.md) | | follow a plant and forecast from its state | [Digital twin](digital-twin.md) | | know what a model file can and cannot do to your machine | [Security](security.md) | An LLM agent reading this site can start from [`llms.txt`](llms.txt). Apache License 2.0. Source and issues: [github.com/TheMattHub/naga](https://github.com/TheMattHub/naga). --- Page: Learn Naga URL: https://thematthub.github.io/naga/learn/index.html # Learn Naga The learning path builds one model in six steps, and each page adds a few lines to the previous one and prints what the model does. Every script on these pages runs on its own, the output printed under it is made by running it, and the whole path takes about half an hour. 1. [One queue](1-one-queue.md) 2. [Two servers and a schedule](2-two-servers-and-a-schedule.md) 3. [A tank level](3-a-tank-level.md) 4. [Agents](4-agents.md) 5. [Replications and scenarios](5-replications-and-scenarios.md) 6. [Reading the results and the event log](6-results.md) You need Python 3.11 or later and `pip install nagasim`. To run a step, copy its script into a file such as `step1.py` and run `python step1.py`: it prints what the page shows under the script. The path starts from a queue and ends with replications, scenarios and the event log. On the way, the same model meets discrete-event processes, a schedule, a continuous level and agents. When you have finished it, the [modelling guide](../modelling-guide/index.md) explains each part in depth and the [gallery](../gallery/index.md) shows the bundled models. If you would rather start from a model file than from Python, use the [Quick start](../quickstart.md). ## If something goes wrong | What happens | Likely cause | Fix | |---|---|---| | `ModuleNotFoundError: No module named 'nagasim'` | The engine is installed in another Python. | Run `python -m pip install nagasim` with the same `python` that runs the script. | | The numbers differ from the page. | A changed seed, or an older engine. | Keep `seed=1`. If they still differ, update with `python -m pip install -U nagasim`. | | A step fails on a name the step does not define. | Each script is the whole model so far, not only the new lines. | Copy the whole script of the page, not the changed lines. | ## By goal If you know what you want to do, find it here. Each row names one page, and a row without a page is a goal the docs do not teach yet. | I want to... | Start here | |---|---| | Compare scenarios with replications | [Step 5: Replications and scenarios](../learn/5-replications-and-scenarios.md) | | How many replications do I need, and what warm-up? | [How many replications do I need, and what warm-up?](../goals/replications-and-warm-up.md) | | Build a model from an event log | [From an event log to a model in five minutes](../event-log-tutorial.md) | | Run a model from Python | [Learn Naga](../learn/index.md) | | Which decision is best? Optimise it | [Which decision is best? Optimise it](../goals/optimise-a-decision.md) | | Which inputs matter? Sensitivity and design of experiments | [Which inputs matter? Sensitivity and design of experiments](../goals/sensitivity-and-doe.md) | | Fit input distributions from data | [How do I fit input distributions from data?](../goals/fit-input-distributions.md) | | How sure am I, given my input data? Input uncertainty | [How sure am I, given my input data? Input uncertainty](../goals/input-uncertainty.md) | | Calibrate a model to data | [How do I calibrate a model to data?](../goals/calibrate-to-data.md) | | Connect live data end to end | [How do I connect live data end to end?](../goals/connect-live-data.md) | | Prove PLC logic on an emulated line | No tutorial yet | | Plan or schedule jobs | [How do I plan or schedule jobs?](../goals/plan-or-schedule-jobs.md) | | Drive a study from an AI agent | [How do I drive a study from an AI agent?](../goals/drive-a-study-from-an-ai-agent.md) | | Import a Vensim or XMILE model | [How do I import a Vensim or XMILE model?](../goals/import-vensim-xmile.md) | | Combine discrete-event, system dynamics and agents | [How do I combine event flow, system dynamics and agents?](../goals/hybrid-model.md) | | Share a viewer or a player | [How do I share a viewer or a player?](../goals/share-a-viewer-or-player.md) | | Write a plugin block | [How do I write a plugin block?](../goals/write-a-plugin-block.md) | | Check a model in continuous integration | [How do I check a model in continuous integration?](../goals/check-in-ci.md) | | Train a policy with reinforcement learning | [How do I train a policy with reinforcement learning?](../goals/train-a-policy-with-rl.md) | | Cost a model and find the cost drivers | [How do I cost a model and find the cost drivers?](../goals/cost-drivers.md) | --- Page: 1. One queue URL: https://thematthub.github.io/naga/learn/1-one-queue.html # Step 1: One queue A queue with one server is the smallest model worth running, and the rest of this path grows it. Customers arrive about once a minute, a single server takes 0.8 minutes on average to serve one, and the model runs for one eight-hour day. ```python from nagasim import build as nb m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() results = m.run(seed=1) print(results.kpi("system/Total Entities Completed"), "customers served") print(round(results.kpi("resource/Server/Time in Queue Avg"), 2), "minutes mean wait") ``` `nagasim.build` writes a model file from Python: `m.create` is the source of arrivals, `m.process` is the service, `a >> b` links two blocks, and `m.dispose()` is where customers leave. Times are exponential, so this is the textbook M/M/1 queue, and its mean wait is known exactly: 3.2 minutes. The numbers are in minutes because the model's time unit is the default. It prints: ```text 499.0 customers served 3.2 minutes mean wait ``` One run is one possible day. The mean wait it printed is close to the exact value but it is not an interval, which is why step 5 runs the day twenty times. The next step keeps this model and adds capacity that follows a schedule. Next: [Two servers and a schedule](2-two-servers-and-a-schedule.md). --- Page: 2. Two servers and a schedule URL: https://thematthub.github.io/naga/learn/2-two-servers-and-a-schedule.html # Step 2: Two servers and a schedule Real servers are not always there, so this step adds a second desk that is closed for the first four hours and open for the last four. The two desks form a resource set, and the service block now seizes the set instead of the one server. ```python from nagasim import build as nb m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Desks", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() m.add_schedule(name="afternoon", kind="capacity", points=[[240, 0], [240, 1]]) # closed 4 h, open 4 h m.add_resource(name="Second", capacity=1, capacity_schedule="afternoon") m.add_resource_set(name="Desks", members=["Server", "Second"], rule="PreferredOrder") results = m.run(seed=1) print(round(results.kpi("resource/Desks/Time in Queue Avg"), 2), "minutes mean wait at the desks") print(results["resource_summary"][["Resource", "Total Seizes", "Usage % (snapshot)"]].to_string(index=False)) ``` A schedule is a list of `[duration, value]` points, here the capacity `0` for 240 minutes and then `1` for 240 minutes. The set's `PreferredOrder` rule gives a customer the first free member in list order, so the second desk only takes work the first cannot. Only one line of step 1 changed, the one naming the resource the service block seizes. It prints: ```text 1.67 minutes mean wait at the desks Resource Total Seizes Usage % (snapshot) Server 386 67.10 Second 115 33.14 Desks 501 55.78 ``` The table shows the effect. The first desk serves most customers, and the second desk is busy a third of the half day it is open. The set's row weighs each desk by the hours it was open. The wait drops because capacity arrives when the queue is longest. Next: [A tank level](3-a-tank-level.md). --- Page: 3. A tank level URL: https://thematthub.github.io/naga/learn/3-a-tank-level.html # Step 3: A tank level A tank fills and drains continuously, which a queue model cannot say, so this step puts one in the same model. The tank starts at 20 litres, fills at 5 litres a minute and drains at 2, and a watcher customer waits for the moment it reaches 50 litres. ```python from nagasim import build as nb m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Desks", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() m.add_schedule(name="afternoon", kind="capacity", points=[[240, 0], [240, 1]]) # closed 4 h, open 4 h m.add_resource(name="Second", capacity=1, capacity_schedule="afternoon") m.add_resource_set(name="Desks", members=["Server", "Second"], rule="PreferredOrder") m.add_entity(name="Watcher") m.add_level(name="Tank", capacity=100, initial=20, thresholds=[{"value": 50, "direction": "rising", "signal": "half full"}]) m.add_flow(name="fill", to="Tank", rate="5") # litres a minute in m.add_flow(name="draw", **{"from": "Tank"}, rate="2") # and out watch = m.create(e_type="Watcher", distribution=nb.Constant(value=0.0), max_arrivals=1) watch >> m.hold(mode="Signal", signal_name="half full") >> m.dispose() results = m.run(seed=1) print(round(results.kpi("resource/Desks/Time in Queue Avg"), 2), "minutes mean wait at the desks") print(results.kpi("entity/WATCHER/Avg Time"), "minutes until the tank holds 50 litres") print((50 - 20) / (5 - 2), "minutes, worked out by hand") ``` A level has a capacity and thresholds, and a threshold fires a named signal when the level crosses its value. The watcher is an entity that waits on the signal with a HOLD block and then leaves. The time it spent in the model is therefore the instant the tank crossed. The engine solves that instant exactly instead of stepping a clock, which is why the printed time is 10.0 and not a value near it. It prints: ```text 1.67 minutes mean wait at the desks 10.0 minutes until the tank holds 50 litres 10.0 minutes, worked out by hand ``` The last line works the answer out by hand: 30 litres to go at a net 3 litres a minute is 10 minutes. The queue, the schedule and the tank all run on one clock in one model. The next step adds a fourth kind of component, agents. Next: [Agents](4-agents.md). --- Page: 4. Agents URL: https://thematthub.github.io/naga/learn/4-agents.html # Step 4: Agents An agent is a small statechart that lives in the model beside the blocks. This step adds four staff members who work, go on a break and return, and the model counts how many are in each state. ```python from nagasim import build as nb m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Desks", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() m.add_schedule(name="afternoon", kind="capacity", points=[[240, 0], [240, 1]]) # closed 4 h, open 4 h m.add_resource(name="Second", capacity=1, capacity_schedule="afternoon") m.add_resource_set(name="Desks", members=["Server", "Second"], rule="PreferredOrder") m.add_entity(name="Watcher") m.add_level(name="Tank", capacity=100, initial=20, thresholds=[{"value": 50, "direction": "rising", "signal": "half full"}]) m.add_flow(name="fill", to="Tank", rate="5") # litres a minute in m.add_flow(name="draw", **{"from": "Tank"}, rate="2") # and out watch = m.create(e_type="Watcher", distribution=nb.Constant(value=0.0), max_arrivals=1) watch >> m.hold(mode="Signal", signal_name="half full") >> m.dispose() m.add_agent_type(name="Staff", initial_state="Working", states=[{"name": "Working"}, {"name": "OnBreak"}], transitions=[{"from": "Working", "to": "OnBreak", "timeout": "EXPO(120)"}, {"from": "OnBreak", "to": "Working", "timeout": "EXPO(15)"}]) m.add_population(name="Team", type="Staff", count=4) results = m.run(seed=1) print(results["agent_summary"][["Agent State", "Avg Count", "Entries"]].to_string(index=False)) ``` An agent type lists its states and the transitions between them. A transition fires after a delay drawn from an expression, here `EXPO(120)` minutes of work and `EXPO(15)` minutes of break. A population makes four agents of the type, all starting in `Working`. Nothing in the model reads the staff yet, but they run on the same clock as the queue and the tank. It prints: ```text Agent State Avg Count Entries Team/Working 3.516323 15 Team/OnBreak 0.483677 15 ``` The summary gives the average number of agents in each state and how many times each state was entered. About one in nine of the four staff is on a break at any moment, as the two delays imply. The model now has all four kinds of component, and the next step asks how sure we can be of its numbers. Next: [Replications and scenarios](5-replications-and-scenarios.md). --- Page: 5. Replications and scenarios URL: https://thematthub.github.io/naga/learn/5-replications-and-scenarios.html # Step 5: Replications and scenarios One run is one sample, so a claim about the model needs many runs and a comparison needs the same random numbers on both sides. This step compares the model with a version whose service is faster, using twenty replications each. ```python from nagasim import build as nb, experiments m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Desks", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() m.add_schedule(name="afternoon", kind="capacity", points=[[240, 0], [240, 1]]) # closed 4 h, open 4 h m.add_resource(name="Second", capacity=1, capacity_schedule="afternoon") m.add_resource_set(name="Desks", members=["Server", "Second"], rule="PreferredOrder") m.add_entity(name="Watcher") m.add_level(name="Tank", capacity=100, initial=20, thresholds=[{"value": 50, "direction": "rising", "signal": "half full"}]) m.add_flow(name="fill", to="Tank", rate="5") # litres a minute in m.add_flow(name="draw", **{"from": "Tank"}, rate="2") # and out watch = m.create(e_type="Watcher", distribution=nb.Constant(value=0.0), max_arrivals=1) watch >> m.hold(mode="Signal", signal_name="half full") >> m.dispose() m.add_agent_type(name="Staff", initial_state="Working", states=[{"name": "Working"}, {"name": "OnBreak"}], transitions=[{"from": "Working", "to": "OnBreak", "timeout": "EXPO(120)"}, {"from": "OnBreak", "to": "Working", "timeout": "EXPO(15)"}]) m.add_population(name="Team", type="Staff", count=4) m.add_scenario(name="Faster server", overrides=[{"path": f"blocks.{serve.name}.params.dist_params.rate", "value": 1.6}]) experiment = experiments.run_scenarios(m.to_dict(), replications=20, seed=1) print(experiment.comparison(kpis=["resource/Desks/Time in Queue Avg"]) [["Scenario", "Mean", "Diff vs baseline", "Significant"]].to_string(index=False)) ``` A scenario is a name and a list of overrides, each a path into the model and a new value. `run_scenarios` runs the baseline and every scenario on common random numbers: the same random draws on each side. A difference is then the effect of the change and not of luck. It then compares each scenario with the baseline by a paired test. The `comparison` table has the mean of each, the difference, and whether that difference is significant at the 95% level. It prints: ```text Scenario Mean Diff vs baseline Significant Baseline 1.407060 0.000000 False Faster server 0.496625 -0.910435 True ``` Faster service lowers the mean wait, and the paired test calls the difference significant. This is the answer a decision needs: a number, a test of whether it is more than luck, and the comparison made fairly. The last step reads the rest of what a run returns. Next: [Reading the results and the event log](6-results.md). --- Page: 6. Reading the results URL: https://thematthub.github.io/naga/learn/6-results.html # Step 6: Reading the results and the event log Every run returns more than the headline number: summaries for each kind of component, and a log of what happened. This step runs the model twenty times and reads both. ```python from nagasim import build as nb, experiments m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Desks", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() m.add_schedule(name="afternoon", kind="capacity", points=[[240, 0], [240, 1]]) # closed 4 h, open 4 h m.add_resource(name="Second", capacity=1, capacity_schedule="afternoon") m.add_resource_set(name="Desks", members=["Server", "Second"], rule="PreferredOrder") m.add_entity(name="Watcher") m.add_level(name="Tank", capacity=100, initial=20, thresholds=[{"value": 50, "direction": "rising", "signal": "half full"}]) m.add_flow(name="fill", to="Tank", rate="5") # litres a minute in m.add_flow(name="draw", **{"from": "Tank"}, rate="2") # and out watch = m.create(e_type="Watcher", distribution=nb.Constant(value=0.0), max_arrivals=1) watch >> m.hold(mode="Signal", signal_name="half full") >> m.dispose() m.add_agent_type(name="Staff", initial_state="Working", states=[{"name": "Working"}, {"name": "OnBreak"}], transitions=[{"from": "Working", "to": "OnBreak", "timeout": "EXPO(120)"}, {"from": "OnBreak", "to": "Working", "timeout": "EXPO(15)"}]) m.add_population(name="Team", type="Staff", count=4) m.add_scenario(name="Faster server", overrides=[{"path": f"blocks.{serve.name}.params.dist_params.rate", "value": 1.6}]) results = m.run(replications=20, seed=1) kpis = results.kpis().set_index("metric") print(kpis.loc[["resource/Desks/Time in Queue Avg", "resource/Desks/Usage % (snapshot)"], ["mean", "ci95"]]) log = results["entity_log"] print(log[log["Run"] == 1].head(4)[["Entity ID", "Type", "Created At", "Exited At"]].to_string(index=False)) print(results["resource_log"].head(3)[["Resource", "time", "in_use", "queue_length", "event_type"]].to_string(index=False)) ``` `results.kpis()` gives each metric's mean over the replications with the half-width of its 95% interval, and a metric's key is `family/name` or `family/object/name`, the same keys scenarios and optimisation use. The frames `entity_log` and `resource_log` hold one row for each customer and for each request, seize and release of a resource: the event log from which every summary was computed. The log is a pandas frame, so any question about a run can be answered from it. It prints: ```text mean ci95 metric resource/Desks/Time in Queue Avg 1.40706 0.451300 resource/Desks/Usage % (snapshot) 53.65450 1.054281 Entity ID Type Created At Exited At 1 DEFAULT 0.000000 0.769548 2 WATCHER 0.000000 10.000000 3 DEFAULT 0.633443 1.431625 4 DEFAULT 0.870072 2.273541 Resource time in_use queue_length event_type Server 0.000000 1 0 request Server 0.000000 1 0 seize Server 0.633443 1 1 request ``` From here the [KPI reference](../reference/kpis.md) lists every metric and frame, the [Python API](../python-api.md) shows optimisation and calibration, and the [modelling guide](../modelling-guide/index.md) explains the parts of a model one by one. To start from the log of a real plant instead of a blank model, see [an event log to a model](../event-log-tutorial.md). --- Page: How many replications, and what warm-up? URL: https://thematthub.github.io/naga/goals/replications-and-warm-up.html # How many replications do I need, and what warm-up? > **In short** > > - **You build:** a script that finds how many [replications](../glossary.md#replication) a target [precision](../glossary.md#precision) needs, and how long a [warm-up](../glossary.md#warm-up) to set. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the model from [step 1 of the learning path](../learn/1-one-queue.md), a single [queue](../glossary.md#queue). > - **Time:** about ten minutes. One run of a model is one sample, so a result needs many runs and a stated precision. By the end you ask the engine for the replications a precision target needs. You read the [half-width](../glossary.md#half-width) it reaches. You set a warm-up from the data instead of a guess. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-replications.py`. It builds the one-queue model, asks for a precision, asks for a warm-up, and asks for the precision again with that warm-up. ```python from nagasim import api, build as nb, experiments m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # a customer a minute serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25)) arrive >> serve >> m.dispose() layout = m.to_dict() wait = "resource/Server/Time in Queue Avg" # 1. Ask for a precision instead of guessing a count: stop when the half-width is within 10% of the mean. results, report = experiments.run_until_precision(layout, wait, relative=0.10, n0=5, seed=1) print(f"{report['replications']} replications: mean wait {report['mean']:.2f} minutes, " f"half-width {report['half_width']:.2f}, target met: {report['met']}") # 2. Ask MSER-5 where the start-up bias ends, on 50 runs each twice as long as the day. long_runs = api.run_model(layout, replications=50, seed=1, run_length=1000, warmup=0) suggestion = experiments.suggest_warmup(long_runs) print(f"suggested warm-up {suggestion.warmup:.0f} minutes, reliable: {suggestion.reliable}") # 3. Run the day again, now with that warm-up, to the same precision. results, report = experiments.run_until_precision(layout, wait, relative=0.10, n0=5, seed=1, warmup=suggestion.warmup) print(f"with the warm-up: {report['replications']} replications: mean wait {report['mean']:.2f}, " f"half-width {report['half_width']:.2f}") ``` 2. Run it. ```console python goal-replications.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text 84 replications: mean wait 3.17 minutes, half-width 0.32, target met: True suggested warm-up 84 minutes, reliable: True with the warm-up: 106 replications: mean wait 3.37, half-width 0.34 ``` 3. Read the first line. `run_until_precision` runs five [replications](../glossary.md#replication) first. Then it estimates how many more it needs so that the [half-width](../glossary.md#half-width) of the [confidence interval](../glossary.md#confidence-interval) is within 10% of the mean. It keeps adding until the target is met or the cap of 200 is reached. 4. Read the second line. The model starts empty, so the first customers wait less than they would in a busy hour. `suggest_warmup` applies [MSER-5](../glossary.md#mser-5) to 50 longer runs and returns the time after which the start-up bias is gone. `reliable: True` means the answer fell in the first half of the run, so you can trust it. 5. Read the third line. The warm-up discards the empty start of each run, so every replication now measures a busy system. Here the same precision needs more replications than before, because each one now keeps less of the day. 6. Compare both means with the exact value. This queue is an M/M/1 queue, and its exact mean wait is 3.2 minutes. Both intervals hold 3.2, which is what a 95% interval should do about nineteen times in twenty. ## Check yourself - Predict, then run: halving the target to `relative=0.05` should need about four times the replications, because the half-width shrinks with the square root of the count. Change it and compare with the cap. `report["met"]` tells you whether the cap stopped the run. - Explain it back: why do you set the warm-up from long runs and then apply it to the short day? ## Done when - [ ] The script prints three lines and the first says `target met: True`. - [ ] You can say what `reliable` means and what you do when it is `False`. - [ ] You can say why a warm-up needs more replications for the same precision. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `ModuleNotFoundError: No module named 'nagasim'` | The package is not installed in the Python you ran | Run `pip install nagasim` with the same interpreter, then run the script again. | | `ValueError: unknown KPI` | The KPI key is misspelled | Copy the key from the [KPI reference](../reference/kpis.md). It has the form `resource/Server/Time in Queue Avg`. | | `target met: False` and the count equals the cap | The target needs more than `max_replications` | Relax `relative`, or pass a higher `max_replications`. Say which you chose when you report the result. | | `reliable: False` | The suggested warm-up fell in the second half of the run, so the run is too short to tell | Make the runs longer or add replications, then ask again. Do not use the suggestion as it stands. | ## Elements this page uses - Python: [`run_until_precision`](../reference/api/run_until_precision.md), [`suggest_warmup`](../reference/api/suggest_warmup.md) and [`run_model`](../reference/api/run_model.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [Exponential](../reference/distributions/exponential.md). - KPI: `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Background: [Experiments](../experiments.md#warm-up-and-the-mser-suggestion) explains MSER-5 in full. Next: [Optimise a decision](optimise-a-decision.md). --- Page: Which decision is best? Optimise it URL: https://thematthub.github.io/naga/goals/optimise-a-decision.html # Which decision is best? Optimise it > **In short** > > - **You build:** a script that searches for the number of call-centre agents with the lowest daily cost. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [replications tutorial](replications-and-warm-up.md). > - **Time:** about ten minutes. An [objective](../glossary.md#objective) such as cost has a best value over your [decision variables](../glossary.md#decision-variable), and the engine can search for it. By the end you describe one decision as a [factor](../glossary.md#factor), give the search a [budget](../glossary.md#budget) of [replications](../glossary.md#replication), and read which choice won and what the search tried. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-optimize.py`. It models a call centre where two calls arrive every minute and an agent takes two minutes per call. Agents cost 20 an hour whether busy or idle, and every caller in the system costs 0.5 a minute. More agents cost more wages and fewer waiting callers, so the total cost has a lowest point. ```python from nagasim import build as nb, optimize m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Agents", capacity=5, cost_busy=20, cost_idle=20, cost_time_unit="hours") m.add_entity(name="Call", holding_cost=0.5) # every caller in the system costs 0.5 a minute arrive = m.create(e_type="Call", distribution=nb.Exponential(rate=2.0)) # two calls a minute serve = m.process(resource_name="Agents", distribution=nb.Exponential(rate=0.5)) # 2 minutes each arrive >> serve >> m.dispose() staff = optimize.Factor(path="resources.Agents.capacity", kind="integer", low=5, high=12, name="agents") found = optimize.optimize(m.to_dict(), [staff], response="system/Total Cost", goal="min", budget=80, replications_per_point=4, seed=1) print(f"best: {found.best['agents']} agents, mean cost {found.best_mean:.0f}") tried = found.history[["agents", "Mean", "N"]].drop_duplicates("agents").sort_values("agents") tried["Mean"] = tried["Mean"].round().astype(int) print(tried.to_string(index=False)) ``` 2. Run it. ```console python goal-optimize.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text best: 6 agents, mean cost 2056 agents Mean N 5 2498 4 6 2093 4 7 2126 4 8 2254 4 9 2405 4 10 2562 4 11 2721 4 12 2880 4 ``` 3. Read the first line. It names the winner and its mean cost. The search confirms its winner with ranking and selection, a final comparison of the best few points. That step gives the winner more [replications](../glossary.md#replication) than the table shows, so its mean differs a little from the table row. 4. Read the table. Each row is one number of agents the search tried, with the mean cost over `N` replications. Cost falls as agents are added up to the winner and rises after it. The offered load is four agents' work, so five agents are busy 80% of the time. Callers queue, and holding cost dominates. 5. Look at how the decision was described. `Factor` names the [override path](../glossary.md#override-path) of the value to change, its kind (`integer`), and its low and high bound. Every point runs on the same seeds, so the difference between two points is the effect of the decision and not of luck. See [common random numbers](../glossary.md#common-random-numbers). 6. Treat the answer as advice for this model. The search never changes the model file. To keep the result, add it as a [scenario](../glossary.md#scenario) or set the value yourself. ## Check yourself - Predict, then run: if a caller in the system cost 1.0 a minute instead of 0.5, would the best number of agents be lower, the same or higher? Change `holding_cost` and compare. - Explain it back: why can the search not simply choose the largest number of agents? ## Done when - [ ] The script prints a best number of agents and a table with one row per number tried. - [ ] You can say what `budget` limits and why the winner has more replications than the table shows. - [ ] You can say what a search does not change in your model. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `ModelValidationError: override path 'resources.Agent.capacity': no resources entry named 'Agent'` | The factor's path names something the model does not have | Copy the name from the model. Here the resource is `Agents`. | | `ValueError: unknown response KPI: 'system/Nope'` | The response key is misspelled | Copy the key from the [KPI reference](../reference/kpis.md). | | `ValueError: factor 'a': high 1.0 is below low 3.0` | The bounds are the wrong way round | Swap `low` and `high`. | | The table has fewer rows than the range | The budget ran out before every value was tried, or the search did not need them | Raise `budget` to try more points. A search is not an exhaustive sweep. | ## Elements this page uses - Python: [`optimize`](../reference/api/optimize.md), with its `Factor` class, and [`Model`](../reference/api/Model.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [Exponential](../reference/distributions/exponential.md). - KPI: `Total Cost` in the [system summary](../reference/kpis.md#system). - Background: [Experiments](../experiments.md#optimization) explains the search method and its guarantee. Next: [Sensitivity and design of experiments](sensitivity-and-doe.md). --- Page: Which inputs matter? Sensitivity and DOE URL: https://thematthub.github.io/naga/goals/sensitivity-and-doe.html # Which inputs matter? Sensitivity and design of experiments > **In short** > > - **You build:** a script that ranks three inputs of a call centre by how far they move the mean wait. It then runs a [full factorial](../glossary.md#full-factorial) design to see their [effects](../glossary.md#main-effect) together. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [replications tutorial](replications-and-warm-up.md). > - **Time:** about fifteen minutes. A model has many inputs, and an experiment on all of them at once is slow. By the end you rank the inputs with a [tornado](../glossary.md#tornado) table, run a [DOE](../glossary.md#doe) over the three that matter, and read each [main effect](../glossary.md#main-effect) and the signs of an [interaction](../glossary.md#interaction). This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-doe.py`. It models a call centre with six agents. It names three [factors](../glossary.md#factor): the number of agents, the arrival rate and the service rate. The [response](../glossary.md#response) is the mean wait of a caller. ```python from nagasim import build as nb, optimize m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes m.add_resource(name="Agents", capacity=6) arrive = m.create(distribution=nb.Exponential(rate=2.0)) # two calls a minute serve = m.process(resource_name="Agents", distribution=nb.Exponential(rate=0.5)) # 2 minutes each arrive >> serve >> m.dispose() layout = m.to_dict() wait = "resource/Agents/Time in Queue Avg" factors = [ optimize.Factor(path="resources.Agents.capacity", kind="integer", low=5, high=7, name="agents"), optimize.Factor(path=f"blocks.{arrive.name}.params.dist_params.rate", low=1.6, high=2.0, name="arrival rate"), optimize.Factor(path=f"blocks.{serve.name}.params.dist_params.rate", low=0.45, high=0.55, name="service rate"), ] # One-at-a-time first: which factor moves the wait most, one run each. print(optimize.tornado(layout, factors, wait, replications=5, seed=1) [["Factor", "KPI at low", "KPI at high", "Swing"]].round(2).to_string(index=False)) # Then a full factorial, every combination of low and high, on common random numbers. design = optimize.full_factorial(factors, levels=2) result = optimize.run_design(layout, factors, design, responses=[wait], replications=5, seed=1) print(result.table[["Point", "agents", "arrival rate", "service rate", "Mean"]].round(2).to_string(index=False)) print(result.main_effects(wait)[["Factor", "Level", "Mean", "Effect", "Effect LB", "Effect UB"]].round(2).to_string(index=False)) ``` 2. Run it. ```console python goal-doe.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text Factor KPI at low KPI at high Swing agents 0.68 0.05 0.63 service rate 0.37 0.09 0.28 arrival rate 0.10 0.33 0.23 Point agents arrival rate service rate Mean 0 5 1.6 0.45 0.71 1 5 1.6 0.55 0.21 2 5 2.0 0.45 3.23 3 5 2.0 0.55 0.66 4 7 1.6 0.45 0.05 5 7 1.6 0.55 0.01 6 7 2.0 0.45 0.20 7 7 2.0 0.55 0.04 Factor Level Mean Effect Effect LB Effect UB agents 5.00 1.20 -1.12 -2.43 0.19 agents 7.00 0.08 -1.12 -2.43 0.19 arrival rate 1.60 0.25 0.79 -0.14 1.72 arrival rate 2.00 1.03 0.79 -0.14 1.72 service rate 0.45 1.05 -0.82 -1.82 0.19 service rate 0.55 0.23 -0.82 -1.82 0.19 ``` 3. Read the first table, the tornado. Each factor moves alone from its low to its high value while the other two stay in the middle of their ranges. `Swing` is the distance between the two results. The table is sorted by swing, so the first row is the input to look at first. 4. Read the second table. A full factorial runs every combination of the low and high value of each factor, so three factors give eight points. Every point runs on the same seeds, so differences between points are not luck. Point 2 has few agents, a high arrival rate and a slow service, and it waits far longer than the rest. 5. Read the third table. For each factor it gives the mean wait at its low and high level, taken over all points, and the `Effect`, the change between the two levels. `Effect LB` and `Effect UB` are the ends of a 95% interval on that change. When the interval holds zero, five replications per point cannot separate the effect from noise. 6. Compare the tables. The tornado changes one input at a time and cannot see that agents matter most when arrivals are high and service is slow. The factorial can, because point 2 sits far above the others. An average over all points, the main effect, spreads that one bad corner over every row. That is what an interaction looks like. ## Check yourself - Predict, then run: if you raise `replications` from 5 to 20, will the effect intervals get narrower or wider? Check `Effect LB` and `Effect UB`. - Explain it back: why does the tornado rank agents first while the main-effect interval for agents still holds zero? ## Done when - [ ] The script prints a tornado table with three rows, a design table with eight points and a main-effect table with six rows. - [ ] You can say what `Swing` measures and what it does not test. - [ ] You can point at the design row that shows an interaction. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `ModelValidationError: override path 'blocks.nope.params.distribution': no blocks entry named 'nope'` | The block name in a factor's path is not one the model has | Build the path from the block object, as the script does with `arrive.name`. | | `ValueError: unknown response KPI` | The response key is misspelled | Copy the key from the [KPI reference](../reference/kpis.md). | | The design has fewer points than you expect | An integer factor with a narrow range has fewer distinct levels than you asked for | Widen the range. An integer factor from 3 to 4 has two levels however many you ask for. | | Every effect interval holds zero | Too few replications for the noise | Raise `replications`, or use fewer and wider factors. | ## Elements this page uses - Python: `run_design`, `full_factorial` and `tornado` from `nagasim.optimize` (its entry point [`optimize`](../reference/api/optimize.md) is on the previous page), and [`Model`](../reference/api/Model.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [Exponential](../reference/distributions/exponential.md). - KPI: `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Background: [Experiments](../experiments.md#design-of-experiments) covers the three design types and the command line (`naga doe`). Next: [Fit input distributions from data](fit-input-distributions.md). --- Page: How do I fit input distributions from data? URL: https://thematthub.github.io/naga/goals/fit-input-distributions.html # How do I fit input distributions from data? > **In short** > > - **You build:** a script that fits candidate [distributions](../glossary.md#distribution) to 200 handling times, picks the winner, and shows what the fit changes in a [queue](../glossary.md#queue). > - **You need:** Python 3.11 or later, `pip install nagasim`, and the one-queue model from [step 1 of the learning path](../learn/1-one-queue.md). > - **Time:** about ten minutes. A model is only as good as its input distributions, and an exponential is a poor default for most real service times. By the end you run a [distribution fit](../glossary.md#distribution-fit), read its [AIC](../glossary.md#aic) and [KS test](../glossary.md#ks-test), and put the winner into a model as a distribution. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-fit.py`. The 200 handling times are drawn from a seeded lognormal, so the page can print the same numbers every time. This is a stand-in for your own data. To use a file, replace the line with `inputfit.load_column("times.csv").values`. ```python import numpy as np from nagasim import build as nb, inputfit # 200 handling times in minutes. Here they are drawn from a seeded lognormal; in a study they come from # a column of your own data: `inputfit.load_column("times.csv").values`. times = np.random.default_rng(7).lognormal(mean=-0.4, sigma=0.5, size=200) fits = inputfit.fit_candidates(times) for fit in fits[:3]: params = {name: round(float(value), 3) for name, value in fit.dist_params.items()} print(f"{fit.distribution:<15} AIC {fit.aic:6.1f} KS p-value {fit.ks_pvalue:.2f} {params}") best = inputfit.best_fit(times) print("winner:", best.distribution) def mean_wait(service): m = nb.Model(time_limit=480, warmup=0) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) arrive >> m.process(resource_name="Server", distribution=service) >> m.dispose() return m.run(replications=20, seed=1).kpi("resource/Server/Time in Queue Avg") # The same queue with the fitted distribution, and with an exponential of the same mean. print(f"fitted {best.distribution}: mean wait {mean_wait(nb.Distribution(best.distribution, best.dist_params)):.2f} minutes") print(f"exponential, same mean: mean wait {mean_wait(nb.Exponential(rate=1 / times.mean())):.2f} minutes") ``` 2. Run it. ```console python goal-fit.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text InverseGaussian AIC 53.1 KS p-value 0.77 {'mu': 0.69, 'lambda': 3.302} Lognormal AIC 53.3 KS p-value 0.76 {'mu': -0.466, 'sigma': 0.436} Erlang AIC 56.7 KS p-value 0.23 {'k': 5.0, 'rate': 7.25} winner: InverseGaussian fitted InverseGaussian: mean wait 0.89 minutes exponential, same mean: mean wait 1.43 minutes ``` 3. Read the first three lines. `fit_candidates` fits every family that suits the data and ranks them by AIC. A lower AIC is a better fit after the penalty for extra parameters. The parameters are in the engine's own naming, so you can paste them into a model. 4. Compare the first two lines. The top two families differ by less than one AIC point, which is no real difference. Pick the one you can explain to your reader. The lognormal is the usual choice for handling times, and the data were drawn from one. 5. Read the KS p-value. A high value means the sample does not contradict the fit. It is optimistic here, because the parameters were estimated from the same sample, so use it to reject a poor fit and not to prove a good one. 6. Read the last two lines. `best_fit` returns the winner, and `nb.Distribution(name, params)` turns it into a distribution the builder accepts. The same queue with an exponential of the same mean waits longer, because an exponential has more spread than these data. Matching the mean is not enough. ## Check yourself - Predict, then run: if you pass `candidates=["Exponential", "Normal"]` to `fit_candidates`, which family wins and what happens to the AIC? Try it. - Explain it back: why is a high KS p-value not proof that the fit is right? ## Done when - [ ] The script prints three ranked fits, the winner and two mean waits. - [ ] You can say why two fits within one AIC point are a tie. - [ ] You can say why matching only the mean of an input can mislead a result. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `best_fit` returns `None` | No family can be fit to the data, for instance when all values are equal | Look at the data with `inputfit.describe(values)`. Use an empirical distribution if no family fits. | | A fit of one or two values returns a strange family | There is too little data to tell families apart. One value gave `Geometric` with `p` equal to 1.0 | Collect more data. Under 30 observations, treat the choice as rough. | | The winner is a family you cannot explain | AIC ranks fit and not meaning | Choose from the top few the one that matches the process, and say so. | | `KeyError: column 'x' not found` | The column name is not in the file | The message lists the available columns. Pick one of them. | ## Elements this page uses - Python: [`best_fit`](../reference/api/best_fit.md) and `fit_candidates` from `nagasim.inputfit`, and [`Model`](../reference/api/Model.md). - Distributions: [InverseGaussian](../reference/distributions/inverse-gaussian.md), [Lognormal](../reference/distributions/lognormal.md), [Erlang](../reference/distributions/erlang.md) and [Exponential](../reference/distributions/exponential.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Background: the [Python API guide](../python-api.md) shows where fitting sits among the entry points. Next: [Run with input uncertainty](input-uncertainty.md). --- Page: How sure am I, given my input data? URL: https://thematthub.github.io/naga/goals/input-uncertainty.html # How sure am I, given my input data? Input uncertainty > **In short** > > - **You build:** a script that reports a mean wait with two intervals, one from run-to-run noise and one that adds the [input uncertainty](../glossary.md#input-uncertainty) of a [distribution](../glossary.md#distribution) fitted to 30 observations. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [fitting tutorial](fit-input-distributions.md). > - **Time:** about ten minutes. A confidence interval from many [replications](../glossary.md#replication) only covers the random draws of the model. It does not cover the error in the data the inputs were fitted to, and more replications never shrink that error. By the end you measure it with a [bootstrap](../glossary.md#bootstrap), read the wider interval, and see what share of the spread comes from the inputs. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-uncertainty.py`. The 30 handling times are drawn from a seeded lognormal, as a stand-in for your own data. The model's service time is replaced by a distribution fitted to them. ```python import numpy as np from nagasim import build as nb, uncertainty # Only 30 observed handling times, so the fit itself is uncertain. Here they are drawn from a seeded # lognormal; in a study they are your own data. times = np.random.default_rng(7).lognormal(mean=-0.4, sigma=0.5, size=30) m = nb.Model(time_limit=480, warmup=0) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25)) # replaced by the fit arrive >> serve >> m.dispose() answer = uncertainty.input_uncertainty( m.to_dict(), [{"path": f"blocks.{serve.name}.params.distribution", "values": list(times)}], kpis=["resource/Server/Time in Queue Avg"], resamples=20, replications=5, seed=1) row = answer["kpis"][0] print(f"{answer['runs']} runs: {answer['resamples_used']} resamples of the data x {answer['replications']} replications, plus the fit itself") print(f"mean wait {row['mean']:.2f} minutes") print(f"interval from run-to-run noise only: {row['run_ci'][0]:.2f} to {row['run_ci'][1]:.2f}") print(f"interval with the inputs' uncertainty: {row['input_interval'][0]:.2f} to {row['input_interval'][1]:.2f}") print(f"share of the spread that comes from the inputs: {row['input_share']:.0%}") ``` 2. Run it. ```console python goal-uncertainty.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text 105 runs: 20 resamples of the data x 5 replications, plus the fit itself mean wait 0.47 minutes interval from run-to-run noise only: 0.36 to 0.58 interval with the inputs' uncertainty: 0.22 to 0.72 share of the spread that comes from the inputs: 88% ``` 3. Read the first line. The engine fits the 30 observations once. Then it redraws the data 20 times with replacement, refits each draw in the same family, and runs the model five times on each fit. The 105 runs are 21 fits times five [replications](../glossary.md#replication). All of them use the same seeds, so the fits differ only in their inputs. 4. Read the interval from run-to-run noise. It is the usual 95% [confidence interval](../glossary.md#confidence-interval) over five replications of the point fit. It is what you would report if the fit were exact. 5. Read the interval with the inputs' uncertainty. It is wider, because it adds the spread of the 20 refits in quadrature. It always contains the first interval. 6. Read the share. It is the part of the spread of the mean that comes from the inputs. More replications shrink the rest of it. Only more data shrinks this part. A large share tells you to collect data before you run more replications. ## Check yourself - Predict, then run: if the sample has 120 observations instead of 30 (`size=120`), will the input share rise or fall? Change it and check. - Explain it back: why does the second interval contain the first? ## Done when - [ ] The script prints a run count, a mean, two intervals and a share. - [ ] You can say which of the two intervals you would report, and why. - [ ] You can say what to do when the share is large. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `ValueError: at least 2 resamples` | `resamples` is below 2 | Pass `resamples=20` or more. A few dozen make the interval steadier. | | `ModelValidationError: override path 'blocks.nope.params.distribution': no blocks entry named 'nope'` | The input's path names a block the model does not have | Build the path from the block object, as the script does with `serve.name`. | | `ValueError` naming the number of runs and `at most 2000` | `(resamples + 1) x replications` is over the limit | Lower `resamples` or `replications`. The check runs before any run starts. | | A note says the interval is rough | Fewer than 30 observations, or fewer than 20 usable resamples | Collect more data, or raise `resamples`. | ## Elements this page uses - Python: `input_uncertainty` from `nagasim.uncertainty`, [`Model`](../reference/api/Model.md) and [`best_fit`](../reference/api/best_fit.md) for the fit it repeats. - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [Exponential](../reference/distributions/exponential.md). - KPI: `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Command line: `naga uncertainty` runs the same analysis on a model file and a data file. Next: [Calibrate a model to data](calibrate-to-data.md). --- Page: How do I calibrate a model to data? URL: https://thematthub.github.io/naga/goals/calibrate-to-data.html # How do I calibrate a model to data? > **In short** > > - **You build:** a script that tunes the [service rate](../glossary.md#service-rate) of a one-server [queue](../glossary.md#queue) until the model's mean wait matches a measured 3.2 minutes. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [replications tutorial](replications-and-warm-up.md). > - **Time:** about ten minutes. A model is credible when it reproduces what the real system did. By the end you give a [calibration](../glossary.md#calibration) one [calibration target](../glossary.md#calibration-target) and one parameter to tune. Then you read how well the tuned model matches, and ask [ABC](../glossary.md#abc) which values the data allow. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-calibrate.py`. The model starts with a wrong guess of 1.0 for the service rate. The real value, which the script does not know, is 1.25 per minute, so a mean wait of 3.2 minutes is what the real system would show. ```python from nagasim import build as nb, calibrate, optimize # The model starts with a guess for the service rate. Calibration will correct it. m = nb.Model(time_limit=5000, warmup=500) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) # one customer a minute serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.0)) arrive >> serve >> m.dispose() # What you measured on the real system: customers waited 3.2 minutes on average. Accept an answer # within 0.6 minutes of that. targets = [{"kpi": "resource/Server/Time in Queue Avg", "observed": 3.2, "tolerance": 0.6}] # What may move: the service rate, anywhere from 0.9 to 2.0 customers a minute. rate = optimize.Factor(path=f"blocks.{serve.name}.params.dist_params.rate", kind="continuous", low=0.9, high=2.0, name="service rate") fit = calibrate.calibrate(m.to_dict(), targets, [rate], budget=80, replications_per_point=5, seed=1) print(f"service rate: {fit.best['service rate']:.2f} per minute, {fit.budget_used} replications used") row = fit.table.iloc[0] print(f"simulated wait {row['Simulated']:.2f} minutes against {row['Observed']:.1f} observed, pass: {fit.passed}") # Keep the tuned value as a scenario of the model. tuned = fit.as_scenario()["overrides"][0] print(f"scenario: {tuned['path']} = {tuned['value']:.2f}") # Which values are consistent with the data? Rejection ABC returns an interval for each factor. abc = calibrate.calibrate(m.to_dict(), targets, [rate], method="abc", budget=200, replications_per_point=1, seed=1) low, high = abc.posterior.iloc[0][["P5", "P95"]] print(f"90% interval for the service rate: {low:.2f} to {high:.2f}") ``` 2. Run it. ```console python goal-calibrate.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text service rate: 1.26 per minute, 80 replications used simulated wait 3.41 minutes against 3.2 observed, pass: True scenario: blocks.process_1.params.dist_params.rate = 1.26 90% interval for the service rate: 1.19 to 1.36 ``` 3. Read the first line. `calibrate` searches the service rate between 0.9 and 2.0 and spends at most 80 replications. It found 1.26, close to the real 1.25. 4. Read the second line. It compares the tuned model with your target. A target with a `tolerance` passes when the simulated mean is within that distance of the observed value. This is a verdict on the mean, so check the confidence interval in `fit.table` too, because a wide interval makes a pass weak. 5. Read the third line. `fit.as_scenario()` turns the tuned value into a [scenario](../glossary.md#scenario) with an [override path](../glossary.md#override-path). Add it to the model to keep the result. 6. Read the last line. `method="abc"` draws many parameter values and keeps the ones whose results lie nearest the target. The result is an interval, not one number. Here the data allow a service rate from 1.19 to 1.36, so the single best value hides how loosely one mean wait pins the rate. ## Check yourself - Predict, then run: if you add a second target, `observed` utilisation of 80 per cent for `resource/Server/Usage % (snapshot)`, will the ABC interval get wider or narrower? Try it. - Explain it back: why does the tuned wait differ a little from 3.2 even though the rate is almost exact? ## Done when - [ ] The script prints a tuned rate, a pass or fail line, a scenario and an interval. - [ ] You can say what the interval means that the best value alone does not. - [ ] You can say why one target rarely pins down more than one parameter. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `pass: False` although the rate is close | The simulated mean is noisy at 5 replications, so it can land outside the tolerance | Raise `replications_per_point` or `run_length`, or widen `tolerance` to what you can measure. | | The best value sits at 0.9 or 2.0 | The true value is outside the range, or the target cannot be reached | Widen the factor range, and check that the observed number comes from the same unit and period as the KPI. | | `ValueError` naming a KPI | The KPI key is misspelt | The message lists close matches. The [KPI reference](../reference/kpis.md) has every key. | | The ABC interval fills the whole range | One target says little about this parameter | Add targets of other kinds, such as utilisation, or a sample to match as a distribution. | ## Elements this page uses - Python: [`calibrate`](../reference/api/calibrate.md) from `nagasim.calibrate`, `Factor` from `nagasim.optimize`, and [`Model`](../reference/api/Model.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [Exponential](../reference/distributions/exponential.md). - KPI: `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Command line: [`naga calibrate`](../reference/cli/twin.md#naga-calibrate) runs the same search on a model file. - Background: [Digital twin](../digital-twin.md) uses calibration to keep a model matched to a plant. Next: [Connect live data end to end](connect-live-data.md). --- Page: How do I connect live data end to end? URL: https://thematthub.github.io/naga/goals/connect-live-data.html # How do I connect live data end to end? > **In short** > > - **You build:** a script that reads a line's current rates from a web service on your own machine and writes them into a model. A change in the line then moves the forecast. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [calibration tutorial](calibrate-to-data.md). No network is used. > - **Time:** about fifteen minutes. A model that holds fixed numbers goes stale, while one that reads them from the plant stays current. By the end you define a [connection](../glossary.md#connection), declare a [data source](../glossary.md#data-source), tie two parameters to it with [data bindings](../glossary.md#data-binding), and see a change in the plant change the result. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-live.py`. A small web server on `127.0.0.1` stands in for your MES or line controller. It answers every request with one row of rates. In a study you delete the server and point the connection at your own system. ```python import http.server import json import threading from nagasim import api, build as nb, databind, netguard # 1. A stand-in for the plant: a small web server on this machine that answers with what the line # reports right now. In a study this is your MES or your line controller. reading = [{"line": "press", "arrivals_per_min": 1.0, "service_per_min": 1.25}] class Plant(http.server.BaseHTTPRequestHandler): def do_GET(self): body = json.dumps(reading).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Plant) threading.Thread(target=server.serve_forever, daemon=True).start() # 2. The connections file is yours. It holds the address; the model file holds only a name. with open("connections.json", "w", encoding="utf-8") as f: json.dump({"format": 1, "connections": {"plant": { "kind": "rest", "url": f"http://127.0.0.1:{server.server_port}", "private": True, "root": "/"}}}, f) policy = netguard.NetworkPolicy(connections=netguard.load_connections("connections.json")) # 3. The model reads two of its parameters from the plant instead of holding them. m = nb.Model(time_limit=2000, warmup=200) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) serve = m.process(resource_name="Server", distribution=nb.Exponential(rate=1.0)) arrive >> serve >> m.dispose() layout = m.to_dict() layout["data_sources"] = [{"name": "line", "kind": "rest", "connection": "plant", "location": "/", "options": {"key": "line"}}] layout["data_bindings"] = [ {"name": "arrivals", "source": "line", "column": "arrivals_per_min", "transform": "value", "target": f"blocks.{arrive.name}.params.dist_params.rate"}, {"name": "service", "source": "line", "column": "service_per_min", "transform": "value", "target": f"blocks.{serve.name}.params.dist_params.rate"}, ] def wait_now(): """Read the plant, write its values into the model, and run it.""" bound, report = databind.resolve_bindings(layout, network=policy) values = {record.name: record.value for record in report.records} result = api.run_model(bound, replications=10, seed=1) return values, result.kpi("resource/Server/Time in Queue Avg") values, wait = wait_now() print(f"plant says {values}: mean wait {wait:.2f} minutes") # 4. The plant changes: the service rate drops. Read again, and the forecast moves with it. reading[0]["service_per_min"] = 1.1 values, wait = wait_now() print(f"plant says {values}: mean wait {wait:.2f} minutes") server.shutdown() ``` 2. Run it. ```console python goal-live.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text plant says {'arrivals': 1.0, 'service': 1.25}: mean wait 3.19 minutes plant says {'arrivals': 1.0, 'service': 1.1}: mean wait 8.52 minutes ``` 3. Read the connections file the script writes. It holds the address and the word `private`, which says the address is inside your network. The model file never holds an address or a password, only the name `plant`. A model you receive from someone else therefore cannot choose where your machine connects. 4. Read the data source and the two bindings. The source says which connection and which path to read. Each binding reads one column and writes it over one parameter, using the same [override path](../glossary.md#override-path) that scenarios use. The transform `value` takes the first cell. 5. Read the first output line. `resolve_bindings` read the plant, wrote 1.0 and 1.25 into a copy of the model, and left your original untouched. The mean wait is about 3.2 minutes, the exact queueing answer for these rates. 6. Read the second line. The plant's service rate fell to 1.1, so the next read produced a mean wait of about 8.5 minutes. Running the same model on the same bindings after every read is the core of a digital twin. 7. To use the same files from the command line, pass the connections file to `naga bind`, `naga watch` or `naga twin` with `--connections connections.json`. Every reader only reads. No reader can write to the plant. ## Check yourself - Predict, then run: if the plant's arrival rate rises to 1.1 and the service rate stays at 1.25, will the wait be longer or shorter than 3.2 minutes? Change `arrivals_per_min` and check. - Explain it back: why does the model name a connection and not an address? ## Done when - [ ] The script prints two lines, with the second wait clearly longer than the first. - [ ] You can say which file holds the address and which holds the name. - [ ] You can say why a failed read leaves the model's stored value in place. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `E_DATA_CONNECTION` | The source names a connection that the connections file does not define | Match the `connection` name in the model to a key in the file. | | A refusal about a private address | `private` is missing from the connection and the address is on your machine or network | Add `"private": true` for an address inside your network. | | A binding reports `E_DATA_READ` and the value does not change | The service is down or answered something other than a JSON array of objects | Open the address in a browser. Set `records` in the source options when the array sits under a key. | | `E_DATA_TYPE` on a text column | A live source never writes text into the model | Bind a number or a true/false column. | | `unknown key` in the connections file | The file allows only the documented keys | Remove the key. There is no key that turns certificate checks off. | ## Elements this page uses - Python: `resolve_bindings` from `nagasim.databind`, `NetworkPolicy` and `load_connections` from `nagasim.netguard`, [`run_model`](../reference/api/run_model.md) and [`Model`](../reference/api/Model.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - KPI: `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Command line: [`naga bind`](../reference/cli/twin.md#naga-bind) and [`naga watch`](../reference/cli/twin.md#naga-watch). - Background: [Live data](../live-data.md) covers REST, MQTT, OPC UA and Modbus, and [Digital twin](../digital-twin.md) covers the rest of the loop. Next: [Plan or schedule jobs](plan-or-schedule-jobs.md). --- Page: How do I plan or schedule jobs? URL: https://thematthub.github.io/naga/goals/plan-or-schedule-jobs.html # How do I plan or schedule jobs? > **In short** > > - **You build:** a script that sequences five jobs through a cutter and a packer with a solver, checks the plan by running it, and exports it for a planning system. > - **You need:** Python 3.11 or later, `pip install "nagasim[plan]"`, which adds the OR-Tools package, and the [optimisation tutorial](optimise-a-decision.md). > - **Time:** about ten minutes. A schedule decides which job a machine works next, and a good one keeps every job on time. By the end you hand an [order book](../glossary.md#order-book) to [CP-SAT](../glossary.md#cp-sat), read the [tardiness](../glossary.md#tardiness) it removes, and replay the plan in the simulation to confirm it. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-plan.py`. The model is the bundled `order_priority_shop`, five orders that each cut and then pack. The script gives every order one entity, so each planned start is exact, and runs the shop first-come first-served as it runs today. ```python import ortools # the optional solver: pip install "nagasim[plan]" import json from nagasim import api, cpsat, examples, planning # Five orders on a cutter and a packer. One entity per order, so each planned start is exact. shop = json.loads(examples.path("order_priority_shop").read_text(encoding="utf-8")) for order in shop["orders"]: order["quantity"] = 1 shop["resources"][0]["discipline"] = "FIFO" # the model as it runs today def lateness(layout): run = api.run_model(layout, replications=1, deterministic=True) # durations are constants here return run["order_summary"].set_index("Order")["Lateness"] today = lateness(shop) print("lateness today:", " ".join(f"{order} {late:+.0f}" for order, late in today.items())) # CP-SAT sequences the order book. Without 'ortools' installed this call raises ImportError. plan = cpsat.propose(shop, objective="weighted_tardiness", time_limit_s=5) print(f"solver: {plan.status}, tardiness {plan.objective:.0f}, makespan {plan.makespan:.0f}, " f"{len(plan.refused)} refused") # The plan is a layout. Run it to check the solver's claim against the simulation. planned = lateness(plan.layout) print("lateness planned:", " ".join(f"{order} {late:+.0f}" for order, late in planned.items())) # Hand the plan to a planning system as a CSV. log = api.run_model(plan.layout, replications=1, deterministic=True)["schedule_log"] planning.plan_export(log, "plan.csv") print(open("plan.csv", encoding="utf-8").read().splitlines()[0]) print(len(log), "operations written") ``` 2. Run it. ```console python goal-plan.py ``` You should see this. Durations are constants here, so the numbers are the same on your machine. ```text lateness today: WO-1 -7 WO-2 -15 WO-3 +1 WO-4 -20 WO-5 -18 solver: OPTIMAL, tardiness 0, makespan 12, 0 refused lateness planned: WO-1 -2 WO-2 -14 WO-3 -3 WO-4 -20 WO-5 -18 Order,Operation,Resource,Planned Start,Planned End 10 operations written ``` 3. Read the first line. Lateness is the finish time minus the due date, so a negative number is early. Today order WO-3 is 1 minute late, because it queues behind the others. 4. Read the second line. CP-SAT proved the plan optimal for weighted tardiness, and the total tardiness is 0. The makespan is 12 minutes. `refused` counts the parts of the model the solver could not plan. It is 0 here. 5. Read the third line. `propose` returns a layout with a start time for each order at each station and a `Plan` queue discipline on both machines. Running that layout is the check. Every order is on time, and WO-3 is 3 minutes early. 6. Read the last two lines. `plan_export` writes a CSV with one row per operation, which a planning system can import. The file holds the order, the operation, the resource and the planned start and end. 7. To score a plan under randomness, give the durations a spread and call `planning.plan_risk(layout, replications)`. It returns for each order the chance of finishing on time. ## Check yourself - Predict, then run: if you pass `objective="makespan"` instead, will the makespan fall below 12? Try it. - Explain it back: why do you replay the plan in the simulation when the solver already reports its result? ## Done when - [ ] The script prints lateness today, a solver line, lateness under the plan and a CSV header. - [ ] You can say which order was late today and what the plan changes for it. - [ ] You can say what `refused` tells you. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `ImportError` naming `ortools` | The optional package is not installed | Run `pip install "nagasim[plan]"`. Without it, only the solver step fails. | | `refused` lists an order | An order with more than one entity runs at a multi-unit resource or a resource set, where the replay may pack its entities differently | Use one entity per order, as the script does, or read the replay as the truth. | | The replay is later than the solver's claim | Something in the model sits outside what the solver models | Read `plan.refused`, and trust the replay. | | `status` is `FEASIBLE`, not `OPTIMAL` | The time limit stopped the search | Raise `time_limit_s`. A feasible plan is valid, only possibly not the best. | ## Elements this page uses - Python: `propose` from `nagasim.cpsat`, `plan_export` and `plan_risk` from `nagasim.planning`, and [`run_model`](../reference/api/run_model.md). - Command line: [`naga plan`](../reference/cli/plan-and-share.md#naga-plan) works on a model file. - Background: [Model file format](../model-file-format.md#orders) describes orders and sequences. Next: [Import a Vensim or XMILE model](import-vensim-xmile.md). --- Page: How do I import a Vensim or XMILE model? URL: https://thematthub.github.io/naga/goals/import-vensim-xmile.html # How do I import a Vensim or XMILE model? > **In short** > > - **You build:** a script that reads a small Vensim file into a model, lists what the reader could not translate, and checks the run against the closed-form answer. > - **You need:** Python 3.11 or later and `pip install nagasim`. A Vensim `.mdl` or XMILE file of your own is optional, because the script carries its own. > - **Time:** about ten minutes. Many [system dynamics](../glossary.md#system-dynamics) models already exist as [Vensim or XMILE](../glossary.md#vensim) files. By the end you import one and read the problem list the reader returns. Then you run the imported model like any other, so you know what carried over and what did not. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-import.py`. The Vensim text sits inside the script as a string: a [stock](../glossary.md#stock) of people that grows through a feedback loop, plus one variable that reads a spreadsheet. To import your own file, replace the string with `mdlimport.load_mdl("yourmodel.mdl")`, or use `sdimport.load_xmile` for XMILE. ```python import math from nagasim import api, mdlimport # A small Vensim file: logistic growth of a population, plus one variable the reader cannot translate. # In a study you would point `mdlimport.load_mdl` at your own file. MDL = """{UTF-8} Population = INTEG(Births, 10) ~ people ~ The stock. | Births = Growth Rate * Population * (1 - Population / Capacity) ~ people/Year ~ A flow with a feedback loop. | Growth Rate = 0.4 ~ 1/Year ~ | Capacity = 1000 ~ people ~ | Survey Result = GET XLS CONSTANTS('survey.xls', 'Sheet1', 'B2') ~ people ~ Data in a spreadsheet next to the model. | INITIAL TIME = 0 ~ Year ~ | FINAL TIME = 30 ~ Year ~ | TIME STEP = 0.25 ~ Year ~ | SAVEPER = TIME STEP ~ Year ~ | """ layout, problems = mdlimport.import_mdl(MDL) print(f"imported {len(layout['levels'])} stock, {len(layout['flows'])} flow, {len(layout['auxiliaries'])} auxiliaries") for problem in problems: print(f"{problem.severity} {problem.code}: {problem.message}") # The imported file is an ordinary model: run it. results = api.run_model(layout, replications=1) series = results["timeseries"].query("Series == 'level/Population'") print(f"population after {series['Time'].iloc[-1]:.0f} years: {series['Value'].iloc[-1]:.1f}") print(f"closed form for logistic growth: {1000 / (1 + 99 * math.exp(-0.4 * 30)):.1f}") ``` 2. Run it. ```console python goal-import.py ``` You should see this. The run has no randomness, so the numbers are the same on your machine. ```text imported 1 stock, 1 flow, 2 auxiliaries error E_SDIMPORT_UNSUPPORTED: Survey_Result: references external data (GET XLS/DIRECT ...); refused -- this reader never opens another file population after 30 years: 999.5 closed form for logistic growth: 999.4 ``` 3. Read the first line. The reader found one stock, one flow and two auxiliaries: `Growth_Rate` and `Capacity`. Vensim treats spaces and underscores as the same, so `Growth Rate` becomes `Growth_Rate`. 4. Read the problem line. The variable `Survey_Result` reads a spreadsheet with `GET XLS`. The reader never opens another file, so it leaves that variable out and reports it with a code. Nothing is dropped silently. Every construct it cannot translate comes back as a problem like this one. 5. Read the last two lines. The imported layout is an ordinary model, so `run_model` runs it. After 30 years the population is 999.5 against 999.4 from the closed-form logistic curve. The small gap is the step size of the numerical method. 6. To import from the command line, run `naga sdimport yourmodel.mdl -o model.json`. It prints the same problems and writes the model. The exit code is 1 when any problem is an error. 7. Treat every reported problem as work for you. Rewrite the variable by hand in the model file, replace a spreadsheet read with a [data binding](../glossary.md#data-binding), or accept the gap and say so in your results. ## Check yourself - Predict, then run: if you change `Growth Rate = 0.4` to `0.2`, will the population at year 30 rise or fall? Change it and check. - Explain it back: why does the reader report an untranslated variable instead of guessing it? ## Done when - [ ] The script prints a count of imported records, one problem, and two populations that agree. - [ ] You can say what the reader does with a construct it does not know. - [ ] You can say how to import a file from the command line. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `E_SDIMPORT_UNSUPPORTED` for a variable | The file uses a macro, a `GET XLS` read or a function the reader lacks | Rewrite that variable in the model file, or remove the dependence on it. | | Names look different after import | Vensim spaces became underscores | Use the underscore form in expressions. A dimension name with a space is not translated. | | Accented letters look wrong | An older `.mdl` is Windows-1252 and not UTF-8 | The reader tries UTF-8 first and then Windows-1252, so check the original file's encoding. | | `E_SDIMPORT_XML` on an XMILE file | The file is over 20 MB or has a `DOCTYPE` declaration, which is refused for safety | Remove the declaration, or export a smaller model. | | The run differs from Vensim | The time step or integration method differs | Compare `TIME STEP` and the method in both tools, then compare a few points. | ## Elements this page uses - Python: `import_mdl` from `nagasim.mdlimport`, `import_xmile` from `nagasim.sdimport`, and [`run_model`](../reference/api/run_model.md). - Command line: [`naga sdimport`](../reference/cli/build-from-data.md#naga-sdimport). - Background: [System dynamics](../system-dynamics.md#import-from-xmile-or-vensim) lists exactly which Vensim and XMILE constructs carry over. Next: [Combine event flow, system dynamics and agents](hybrid-model.md). --- Page: How do I combine events, system dynamics and agents? URL: https://thematthub.github.io/naga/goals/hybrid-model.html # How do I combine event flow, system dynamics and agents? > **In short** > > - **You build:** a script that builds a help desk with tickets, a frustration [stock](../glossary.md#stock) and a staff team that takes breaks, then compares four and five staff. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [learning path](../learn/index.md) through [step 4, agents](../learn/4-agents.md). > - **Time:** about fifteen minutes. Real systems rarely stay in one modelling style, and the engine runs all three in one model. By the end you build a [hybrid model](../glossary.md#hybrid-model) in which [agents](../glossary.md#agent) change how fast tickets are worked, the queue feeds a [stock](../glossary.md#stock), and the stock changes how fast tickets arrive. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-hybrid.py`. It builds the same help desk for a given team size, in three layers that share one clock. ```python from nagasim import build as nb def help_desk(staff): """A help desk in three layers. `staff` agents each alternate between working and a break.""" m = nb.Model(time_limit=2000, warmup=200) m.add_resource(name="Desk", capacity=staff) # Discrete events: tickets arrive, wait for a desk, and are worked. Arrivals speed up with # the SD level 'Frustration' (capped at 10), and a ticket takes longer when fewer staff are working. arrive = m.create(distribution=nb.CustomExpression( expression='EXPO(1 / (0.9 + 0.03 * min(LEVEL("Frustration"), 10)))')) work = m.process(resource_name="Desk", distribution=nb.CustomExpression( expression=f'EXPO(2.4 * {staff} / max(1, COUNT("Team", "Working")))')) arrive >> work >> m.dispose() # Agents: each staff member alternates between two states, with exponential dwell times. m.add_agent_type(name="Staff", initial_state="Working", states=[{"name": "Working"}, {"name": "OnBreak"}], transitions=[{"from": "Working", "to": "OnBreak", "timeout": "EXPO(60)"}, {"from": "OnBreak", "to": "Working", "timeout": "EXPO(15)"}]) m.add_population(name="Team", type="Staff", count=staff) # System dynamics: frustration rises with the number of tickets waiting and fades by itself. m.add_level(name="Frustration", initial=0, min=0) m.add_flow(name="annoyance", to="Frustration", rate='0.1 * NQ("Desk")') m.add_flow(name="calming", **{"from": "Frustration"}, rate='0.05 * LEVEL("Frustration")') return m for staff in (4, 5): results = help_desk(staff).run(replications=5, seed=1) print(f"{staff} staff: {results.kpi('agent/Team/Working/Avg Count'):.2f} working, " f"mean wait {results.kpi('resource/Desk/Time in Queue Avg'):.1f} minutes, " f"frustration {results.kpi('level/Frustration/Average'):.2f}") ``` 2. Run it. ```console python goal-hybrid.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text 4 staff: 3.17 working, mean wait 14.9 minutes, frustration 35.05 5 staff: 3.98 working, mean wait 0.9 minutes, frustration 1.91 ``` 3. Read the event layer. Tickets are created, wait for a desk and are worked. The arrival time and the work time are expressions, so they can read the other layers: `LEVEL("Frustration")` is a stock, and `COUNT("Team", "Working")` counts the agents in one state. 4. Read the agent layer. Each staff member alternates between `Working` and `OnBreak`, with exponential dwell times of 60 and 15 minutes. A ticket takes longer when fewer staff are working, since the mean work time is divided by the number working. 5. Read the stock layer. Frustration grows by 0.1 per waiting ticket per minute and drains by 5 per cent of itself. `NQ("Desk")` is the number of tickets waiting, so the queue feeds the stock. The arrival expression caps the stock's effect at 10, which keeps the loop from running away. 6. Read the first output line. With four staff, 3.17 of them are working on average, the mean wait is 14.9 minutes, and frustration averages 35. The loop has tipped. A long queue raises frustration, and frustration raises arrivals. 7. Read the second line. With five staff the wait drops to 0.9 minutes and frustration to 1.9. One extra person does not scale the result by a fifth. It moves the system out of the vicious circle, and only a model with all three layers shows that. ## Check yourself - Predict, then run: if you lower the cap in `min(LEVEL("Frustration"), 10)` to 5, will the four-staff wait rise or fall? Change it and check. - Explain it back: which layer carries the effect of a staff break on the wait, and which carries the effect of the wait on arrivals? ## Done when - [ ] The script prints one line for four staff and one for five. - [ ] You can name the three layers and the expression that links each pair. - [ ] You can say why the stock's effect on arrivals is capped. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | The run takes minutes and the queue grows without bound | The feedback loop has no cap, so more waiting makes more arrivals without limit | Cap the stock's effect, as in `min(LEVEL(...), 10)`, or weaken the gain. | | `unknown function 'MAX'` | Expression names are case sensitive | Use lower-case `max` and `min`. The [expression reference](../reference/functions/index.md) lists the allowed names. | | `COUNT` returns 0 | The population or state name is misspelt | Use the names given to `add_population` and the state list. | | A level does not move | The flow has no `to` or `from`, or its rate is 0 | Give a flow the level it feeds in `to`, and the level it drains in `from`. | ## Elements this page uses - Python: [`Model`](../reference/api/Model.md) with `add_level`, `add_flow`, `add_agent_type` and `add_population`, and [`Results`](../reference/api/Results.md). - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Distribution: [CustomExpression](../reference/distributions/custom-expression.md). - Expressions: `LEVEL`, `COUNT`, `NQ`, `EXPO`, `min` and `max` in the [expression reference](../reference/functions/index.md). - Background: [System dynamics](../system-dynamics.md) and [Agent-based modelling](../agent-based-modelling.md). Next: [Check a model in continuous integration](check-in-ci.md). --- Page: How do I check a model in CI? URL: https://thematthub.github.io/naga/goals/check-in-ci.html # How do I check a model in continuous integration? > **In short** > > - **You build:** a [model file](../glossary.md#model-file) with three [assertions](../glossary.md#assertion), a `naga check` run that fails the build when one is false, and the workflow file that runs it on every push. > - **You need:** Python 3.11 or later, `pip install nagasim`, and a GitHub repository for the last step. You can run the rest on your own machine. > - **Time:** about ten minutes. A model changes as people edit it, and an edit can quietly break what it was built to show. By the end you pin three claims about a [queue](../glossary.md#queue) in the model file. You read a pass, a fail and the exit code that [continuous integration](../glossary.md#continuous-integration) uses. Then you generate a workflow that runs the checks on every push. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-ci.py`. It writes `model.json` with three assertions on a one-server queue, then calls `naga check` on it, as a CI job would. The third assertion is false on purpose, so you can see a failure. ```python from nagasim import build as nb, cli # A queue with three claims about how it behaves. Each is an assertion: a KPI, a comparison and a # value, checked over the model's own replications with a confidence interval. m = nb.Model(time_limit=480, warmup=0, assertions=[ {"name": "server_not_saturated", "kpi": "resource/Server/Usage % (snapshot)", "op": "<=", "value": 95, "replications": 20}, {"name": "wait_under_five_minutes", "kpi": "resource/Server/Time in Queue Avg", "op": "<=", "value": 5, "replications": 20}, {"name": "wait_under_two_minutes", "kpi": "resource/Server/Time in Queue Avg", "op": "<=", "value": 2, "replications": 20}, ]) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) arrive >> m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25)) >> m.dispose() m.save("model.json") # What a CI job runs. The exit code is the job's verdict: 0 passes the build, 1 fails it. print("$ naga check model.json --junit report.xml") code = cli.main(["check", "model.json", "--junit", "report.xml"]) print("exit code:", code) # The workflow file that runs it on every push. print("$ naga ci-template --path models/") cli.main(["ci-template", "--path", "models/"]) ``` 2. Run it. ```console python goal-ci.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text $ naga check model.json --junit report.xml model.json: [PASS] gate opens with no errors and runs one replication [PASS] assertion server_not_saturated: ok [PASS] assertion wait_under_five_minutes: ok [FAIL] assertion wait_under_two_minutes: assertion 'wait_under_two_minutes' failed: resource/Server/Time in Queue Avg = 2.86501 [2.30459, 3.42543] <= 2.0 laws: 5 passed, 0 warning(s) exit code: 1 $ naga ci-template --path models/ # Generated by `naga ci-template`. Runs every model's assertions and # reality checks on push/PR: a merge that regresses a KPI # an assertion pins, or breaks a reality-check constraint, fails CI. # `naga check` is engine-side, so installing the engine alone is enough; # change the install step with `naga ci-template --install ""`. name: Model checks on: push: pull_request: jobs: naga-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install naga run: | pip install . - name: naga check run: | shopt -s globstar nullglob models=("models/"/**/*.json) if [ ${#models[@]} -eq 0 ]; then echo "no *.json models under models/" exit 0 fi naga check "${models[@]}" --junit naga-check.xml - name: Upload JUnit report if: always() uses: actions/upload-artifact@v4 with: name: naga-check-results path: naga-check.xml ``` 3. Read the assertions. Each one names a [KPI](../glossary.md#kpi), a comparison and a value, and runs over its own `replications`. The check computes a 95% [confidence interval](../glossary.md#confidence-interval) across them. 4. Read the three verdicts. An assertion passes when the whole interval satisfies the claim and fails when the whole interval breaks it. The first two pass. The third fails, with the mean wait at 2.87 minutes and an interval from 2.30 to 3.43 against a limit of 2. 5. Read the exit code. It is 1 because one assertion failed. A CI job treats a non-zero exit as a failed build, so a merge that makes the model break its own claim is stopped. The third verdict an assertion can have is `inconclusive`: the interval straddles the limit, so more replications are needed. It fails the build only with `--strict`. 6. Read the `laws` line. `naga check` also runs five built-in sanity checks, such as [Little's law](../glossary.md#littles-law), on the same runs. 7. Read the workflow. `naga ci-template` prints a GitHub Actions file that installs the engine, runs `naga check` on every model under `models/`, and uploads the [JUnit report](../glossary.md#junit) as a build artifact. Save it as `.github/workflows/model-checks.yml`, and put your models under `models/`. 8. Fix the failing claim. Change the third limit from 2 to 3.5, or fix the model, and run the script again. The exit code becomes 0. ## Check yourself - Predict, then run: if you lower `replications` for the third assertion from 20 to 3, will it still fail, or turn inconclusive? Try it, then run `naga check model.json --strict`. - Explain it back: why does the check judge the whole interval and not just the mean? ## Done when - [ ] The script prints two passes, one failure, exit code 1 and a workflow file. - [ ] You can say what `inconclusive` means and what `--strict` does with it. - [ ] You can say which file you commit to run the checks on every push. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `unknown KPI` in a verdict | The KPI key is misspelt | The message lists close matches. The [KPI reference](../reference/kpis.md) has every key. | | An assertion flips between runs | Its interval straddles the limit, so it is `inconclusive` or close to it | Raise `replications`, or move the limit to what you can defend. | | The CI job fails to install the engine | The default install step is `pip install .`, which installs the repository itself | Pass `--install "pip install nagasim"` to `naga ci-template` in a repository that only holds models. | | The job passes with "no models found" | No `*.json` file is under the `--path` folder | Move the models there, or pass the right `--path`. | | Exit code 2 | A file is missing or is not valid JSON | Open the file named in the message. | ## Elements this page uses - Python: [`Model`](../reference/api/Model.md) with `assertions`, and [`assert_model`](../reference/api/assert_model.md) for a pytest suite. - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - KPIs: `Usage % (snapshot)` and `Time in Queue Avg` in the [resource summary](../reference/kpis.md#resource_summary). - Command line: [`naga check`](../reference/cli/model-files.md#naga-check), [`naga ci-template`](../reference/cli/model-files.md#naga-ci-template) and [`naga verify`](../reference/cli/model-files.md#naga-verify), which checks the engine itself against queueing theory. - Background: [Model assertions and CI](../model-assertions.md) covers reality checks and path checks. Next: [Cost a model and find the cost drivers](cost-drivers.md). --- Page: How do I cost a model and find the cost drivers? URL: https://thematthub.github.io/naga/goals/cost-drivers.html # How do I cost a model and find the cost drivers? > **In short** > > - **You build:** a script that prices a call centre's day and splits the total into agents busy, agents idle and callers waiting. It then ranks the inputs by how far they move the total. > - **You need:** Python 3.11 or later, `pip install nagasim`, and the [sensitivity tutorial](sensitivity-and-doe.md). > - **Time:** about ten minutes. A total cost is only useful when you know what it is made of. By the end you put a cost on a [resource](../glossary.md#resource) and on every caller in the system, and read the split. Then you use a [tornado](../glossary.md#tornado) to see which input is the main [cost driver](../glossary.md#cost-driver). This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-cost.py`. It is the call centre of the optimisation tutorial with six agents. Read the two cost lines with care, because they use different time units. ```python from nagasim import build as nb, optimize m = nb.Model(time_limit=480, warmup=0) # one 8-hour day, in minutes # An agent costs 24 per hour while busy and 18 per hour while idle. These are quoted per hour # because `cost_time_unit` says so. m.add_resource(name="Agents", capacity=6, cost_busy=24, cost_idle=18, cost_time_unit="hours") # A caller in the system costs 0.5 per MINUTE: `holding_cost` is per model time unit, which is # minutes here, whatever `cost_time_unit` says. m.add_entity(name="Call", holding_cost=0.5) arrive = m.create(e_type="Call", distribution=nb.Exponential(rate=2.0)) # two calls a minute serve = m.process(resource_name="Agents", distribution=nb.Exponential(rate=0.5)) # 2 minutes each arrive >> serve >> m.dispose() results = m.run(replications=10, seed=1) busy = results.kpi("resource/Agents/Busy Cost") idle = results.kpi("resource/Agents/Idle Cost") holding = results.kpi("system/Total Entity Holding Cost") total = results.kpi("system/Total Cost") for name, part in (("agents busy", busy), ("agents idle", idle), ("callers waiting and served", holding)): print(f"{name:<27}{part:8.0f} {100 * part / total:3.0f}%") print(f"{'total per day':<27}{total:8.0f}") # Check the holding line by hand: 0.5 a minute for each caller in the system, for 480 minutes. wip = results.kpi("system/Avg WIP") print(f"by hand: 0.5 x {wip:.2f} callers x 480 minutes = {0.5 * wip * 480:.0f}") # Which input moves the total most? One at a time, each across a plausible range. factors = [ optimize.Factor(path="resources.Agents.capacity", kind="integer", low=5, high=7, name="agents"), optimize.Factor(path=f"blocks.{arrive.name}.params.dist_params.rate", low=1.6, high=2.0, name="arrival rate"), optimize.Factor(path="resources.Agents.cost_busy", low=20, high=28, name="busy cost"), optimize.Factor(path=f"blocks.{serve.name}.params.dist_params.rate", low=0.45, high=0.55, name="service rate"), ] print(optimize.tornado(m.to_dict(), factors, "system/Total Cost", replications=5, seed=1) [["Factor", "KPI at low", "KPI at high", "Swing"]].round(0).to_string(index=False)) ``` 2. Run it. ```console python goal-cost.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text agents busy 769 35% agents idle 287 13% callers waiting and served 1114 51% total per day 2170 by hand: 0.5 x 4.64 callers x 480 minutes = 1114 Factor KPI at low KPI at high Swing arrival rate 1813.0 2165.0 351.0 service rate 2160.0 1835.0 325.0 busy cost 1852.0 2079.0 227.0 agents 2035.0 2052.0 17.0 ``` 3. Know the two units. `cost_busy` and `cost_idle` are quoted per `cost_time_unit`, which the script sets to hours. The [holding cost](../glossary.md#holding-cost) of an entity is per model [time unit](../glossary.md#time-unit), which is minutes here. It does not follow `cost_time_unit`. A holding cost of 0.5 therefore means 0.5 per minute, and 30 per hour. 4. Read the split. A day costs 2170. Agents working cost 769, agents waiting for a call cost 287, and callers in the system cost 1114, which is more than half. The waiting callers cost more than the agents do. 5. Read the hand check. The holding cost is the price per minute times the average number of callers in the system times the 480 minutes of the day. The average is 4.64 callers, and 0.5 times 4.64 times 480 is 1114, the same figure. If your own check does not match, a unit is wrong. 6. Read the tornado. Each row moves one input from its low to its high value with the others in the middle, sorted by the swing in total cost. The arrival rate moves the total most, by 351. The service rate follows with 325, then the busy cost with 227. 7. Read the last row. The number of agents moves the total by only 17. Another agent adds idle cost but removes waiting, and the two nearly cancel. The number of agents is a poor lever here, but the arrival and service rates are strong levers. ## Check yourself - Predict, then run: if you set `holding_cost` to 0.25, will the callers' share of the day stay above half? Change it and check. - Explain it back: why does adding an agent change the total so little when it changes the wait so much? ## Done when - [ ] The script prints a three-line split, a total, a hand check and a four-row tornado. - [ ] You can say which unit `holding_cost` is in, and which unit `cost_busy` is in. - [ ] You can name the main cost driver and say what it tells you to measure better. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | The holding cost is 60 times too large or too small | `holding_cost` was read as per hour, or `cost_busy` as per minute | Holding is per model time unit. Resource costs are per `cost_time_unit`. Run the hand check. | | The total has no holding line | The entity type has no `holding_cost`, or the entities have a different `e_type` | Give the CREATE block `e_type="Call"` for the entity type that has the cost. | | `unknown section 'entities'` in the tornado | Entity settings are not override paths | Vary a resource, a block or a variable instead. | | The ranking changes between runs | Five replications leave noise in the swings | Raise `replications`, and compare swings only when they differ clearly. | ## Elements this page uses - Python: [`Model`](../reference/api/Model.md) with `add_resource` and `add_entity`, [`Results`](../reference/api/Results.md), and `Factor` and `tornado` from `nagasim.optimize`. - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - KPIs: `Busy Cost` and `Idle Cost` in the [resource summary](../reference/kpis.md#resource_summary), and `Total Entity Holding Cost` and `Total Cost` in the [system frame](../reference/kpis.md#system). - Background: [Experiments](../experiments.md) covers searches over costs, and the [model file format](../model-file-format.md) lists every cost field. Back to the [learning path](../learn/index.md#by-goal). --- Page: How do I drive a study from an AI agent? URL: https://thematthub.github.io/naga/goals/drive-a-study-from-an-ai-agent.html # How do I drive a study from an AI agent? > **In short** > > - **You build:** a short script that makes the [tool calls](../glossary.md#tool-call) an AI assistant makes: build a [queue](../glossary.md#queue), run it, and ask what happens with a second server. > - **You need:** Python 3.11 or later and `pip install nagasim`. No language model and no network are involved. > - **Time:** about ten minutes. An AI assistant works on a model through a fixed set of tools, and each tool is a plain Python function. By the end you call those functions yourself, so you know exactly what an assistant sees and what it can reach. Then you know what to connect with `naga mcp` (the [MCP](../glossary.md#mcp) server). This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-agent.py`. It opens a [workspace](../glossary.md#workspace) in the current folder, builds a one-server [queue](../glossary.md#queue) with eight edit calls, and then runs and questions it. ```python from nagasim import agent_tools from nagasim.agent_tools import call # The workspace is the folder an agent may reach. `naga mcp --root .` does the same line. agent_tools.use_workspace(agent_tools.Workspace(".")) # 1. What an agent does first: build a one-server queue, one tool call per edit. call("new_model", name="shop") call("upsert_record", model="shop", section="resources", record={"name": "Server", "capacity": 1}) call("add_block", model="shop", type="CREATE", name="arrive", params={"distribution": "Exponential", "dist_params": {"rate": 1.0}}) call("add_block", model="shop", type="PROCESS", name="serve", params={"resource_name": "Server", "distribution": "Exponential", "dist_params": {"rate": 1.25}}) call("add_block", model="shop", type="DISPOSE", name="leave") call("connect", model="shop", source="arrive", target="serve") linked = call("connect", model="shop", source="serve", target="leave") call("set_simulation_settings", model="shop", run_length=2000, warmup=200, replications=10) print("errors after the last link:", linked["errors"], " valid:", call("validate_model", model="shop")["ok"]) # 2. An error comes back as a value with a code and a hint, never as a traceback. refused = call("open_model", path="../somewhere/else.json") print("refused:", refused["error"]["code"]) # 3. Run it. The answer is a digest: each KPI with the half-width of its 95% interval. digest = call("run_model", model="shop", seed=1) wait = digest["resources"]["Server"]["Time in Queue Avg"] print(f"mean wait: {wait['mean']:.2f} +/- {wait['ci_half_width']:.2f} minutes") # 4. Ask a question without editing: what if there were two servers? The tool doubles the # replications on paired seeds until the answer is clear. asked = call("what_if", model="shop", overrides=[{"path": "resources.Server.capacity", "value": 2}], kpis=["resource/Server/Time in Queue Avg"], start=5, cap=20, seed=1) row = asked["kpis"][0] print(f"two servers: wait changes by {row['diff']:.2f} (95% interval {row['diff_lb']:.2f} to " f"{row['diff_ub']:.2f}): {row['verdict']}, after {asked['n']} replications") ``` 2. Run it. ```console python goal-agent.py ``` You should see this. The script seeds itself, so the numbers are the same on your machine. ```text errors after the last link: 0 valid: True refused: E_PATH_OUTSIDE_ROOT mean wait: 3.04 +/- 0.34 minutes two servers: wait changes by -3.01 (95% interval -3.78 to -2.24): lower, after 5 replications ``` 3. Read the first line. Each `call(name, ...)` is one tool call. The last `connect` answers with `errors: 0`, so the model is complete and `validate_model` agrees. An edit that leaves the model broken answers with the problems it introduced. Each has a stable code, so an assistant learns of a mistake at the edit and not at the run. 4. Read the second line. The script asked to open a file outside the workspace. The answer is a value, `E_PATH_OUTSIDE_ROOT`, and not a traceback. The same holds for every tool: an error carries a code, a message and a hint. 5. Read the third line. `run_model` returns a digest, not raw data. Each KPI comes with the [half-width](../glossary.md#half-width) of its 95% [confidence interval](../glossary.md#confidence-interval), here 3.04 plus or minus 0.34 minutes. 6. Read the fourth line. `what_if` runs the model and a changed copy on paired [seeds](../glossary.md#seed), without editing the model. It doubles the [replications](../glossary.md#replication) from 5 until the difference is clear or the cap is reached. Here 5 were enough: a second server cuts the wait by about 3 minutes. 7. Connect a real assistant. The tools are the same functions, published by the server. The root folder is the workspace, and the person who starts the server sets it. ```console naga mcp --root path/to/models ``` 8. Give the assistant a whole study to run. The three tools `study_start`, `study_step` and `study_status` keep the question, the model versions and the checks in a folder, so another assistant can resume it tomorrow. The assistant can build, run and compare, but it cannot vouch that the model matches reality. That check is the engine's (`study_validate`, for a single queue) or yours (`naga study confirm`, or the room's **I checked this**). See [Run a study with an assistant](../ai-study.md#who-checks-the-model). ## Check yourself - Predict, then run: change the override in `what_if` to `capacity` 3. Will the verdict say more clearly that the wait fell, and will it need more replications? - Explain it back: why can an assistant not widen its own permissions, however its prompt is worded? ## Done when - [ ] The script prints a valid model, a refusal with a code, a wait with its interval and a verdict. - [ ] You can say where the workspace stops an assistant, and who sets that limit. - [ ] You know the command that publishes the same tools to an assistant. ## If stuck | What happens | Likely cause | Fix | |---|---|---| | `E_PATH_OUTSIDE_ROOT` on a file you meant to open | The path leaves the workspace folder | Copy the file under the root, or start the server with `--root` on its folder. | | `E_AGENT_PYTHON_REFUSED` from `run_model` | The model has an agent type that runs Python | Run it yourself with `naga run`. A tool never grants that permission. | | A tool answer starts with `error` | The call was wrong, not the engine | Read `code` and `hint`. The hint names the tool that lists the valid values. | | `naga mcp` says the `mcp` package is missing | The optional extra is not installed | Run `pip install "nagasim[mcp]"`. | | The assistant picks the wrong tool | A small model struggles with so many tools | Add `--tool-picker gte` to narrow the choice. See [Pick tools with a small model](../tool-picker.md). | ## Elements this page uses - Tools: every tool is listed in the [agent tool reference](../reference/tools.md). This page calls `new_model`, `upsert_record`, `add_block`, `connect`, `set_simulation_settings`, `validate_model`, `open_model`, `run_model` and `what_if`. - Blocks: [CREATE](../reference/blocks/create.md), [PROCESS](../reference/blocks/process.md) and [DISPOSE](../reference/blocks/dispose.md). - Command line: [`naga mcp`](../reference/cli/agents.md#naga-mcp) and [`naga study`](../reference/cli/agents.md#naga-study). - Background: [Use with an agent](../mcp.md) covers permissions, and [Run a study with an assistant](../ai-study.md) covers the study folder. Next: [Share a viewer or a player](share-a-viewer-or-player.md). --- Page: How do I share a viewer or a player? URL: https://thematthub.github.io/naga/goals/share-a-viewer-or-player.html # How do I share a viewer or a player? > **In short** > > - **You build:** a [player file](../glossary.md#player-file), one HTML page that replays a recorded run in a browser. You also learn when to send a [viewer file](../glossary.md#viewer-file) instead. > - **You need:** Python 3.11 or later and `pip install nagasim`. The reader needs only a browser. > - **Time:** about ten minutes for the player. The viewer needs a 29 MB download once. A model can leave your machine as one file. By the end you write a player, check what it contains, and choose between it and the viewer for a given reader. This page has three parts: [Step by step](#step-by-step), [Check yourself](#check-yourself) and [If stuck](#if-stuck). The last section lists the [reference pages](#elements-this-page-uses) for the elements used. ## Step by step 1. Save this script as `goal-share.py`. It builds a one-server [queue](../glossary.md#queue), records the first [replication](../glossary.md#replication) with `naga run --player`, and then opens the file to see what it asks of a browser. ```python import contextlib import io from pathlib import Path from nagasim import build as nb, cli # A small model to share: a queue with one server. m = nb.Model(time_limit=240, warmup=0, replications=3) m.add_resource(name="Server") arrive = m.create(distribution=nb.Exponential(rate=1.0)) arrive >> m.process(resource_name="Server", distribution=nb.Exponential(rate=1.25)) >> m.dispose() m.save("model.json") # The recording: `naga run` plays the first replication and writes it as one HTML file. print("$ naga run model.json --player queue.html") shown = io.StringIO() with contextlib.redirect_stdout(shown): # the command also prints the KPI table; this page does not need it code = cli.main(["run", "model.json", "--player", "queue.html"]) print(shown.getvalue().splitlines()[-1]) page = Path("queue.html") text = page.read_text(encoding="utf-8") print(f"exit code {code}; {page.name} is {page.stat().st_size / 1000:.0f} KB") # What the file asks of the browser, and what it leaves out. print("loads a script from elsewhere:", "