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. 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, declare a data source, tie two parameters to it with data bindings, and see a change in the plant change the result.
This page has three parts: Step by step, Check yourself and If stuck. The last section lists the reference pages for the elements used.
Step by step¶
- Save this script as
goal-live.py. A small web server on127.0.0.1stands 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.
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()
- Run it.
python goal-live.py
You should see this. The script seeds itself, so the numbers are the same on your machine.
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
-
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 nameplant. A model you receive from someone else therefore cannot choose where your machine connects. -
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 that scenarios use. The transform
valuetakes the first cell. -
Read the first output line.
resolve_bindingsread 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. -
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.
-
To use the same files from the command line, pass the connections file to
naga bind,naga watchornaga twinwith--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_minand 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_bindingsfromnagasim.databind,NetworkPolicyandload_connectionsfromnagasim.netguard,run_modelandModel. - Blocks: CREATE, PROCESS and DISPOSE.
- KPI:
Time in Queue Avgin the resource summary. - Command line:
naga bindandnaga watch. - Background: Live data covers REST, MQTT, OPC UA and Modbus, and Digital twin covers the rest of the loop.
Next: Plan or schedule jobs.