How do I write a plugin block?¶
In short
A plugin adds a block, a distribution or an exporter without changing the engine. By the end you write a block that inspects each entity and rejects one in five. Then you load it, wire it with the builder, and check its result against a hand calculation.
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-plugin.py. It writes the plugin fileplugins/inspect_plugin.pyand a second script,use_plugin.py, and then runs that script in a fresh Python.
import os
import subprocess
import sys
from pathlib import Path
# 1. The plugin is one Python file. It defines a block called INSPECT: wait, then send the entity
# out of port 0 (passed) or port 1 (rejected).
Path("plugins").mkdir()
Path("plugins/inspect_plugin.py").write_text('''
from nagasim.core.base_process import BaseProcess
from nagasim.core.block_spec import BlockSpec, ParamSpec
class Inspect(BaseProcess):
def __init__(self, env, block, next_process=None, minutes=1.0, reject_rate=0.1):
super().__init__(env, block, next_process)
self.minutes = minutes
self.reject_rate = reject_rate
def self_process(self, entity):
self.active_entity = entity
yield self.env.timeout(self.minutes)
self.remove_active_entity(entity)
self.forward(entity, 1 if self.rng.random() < self.reject_rate else 0)
def self_run(self, entity):
return self.env.process(self.self_process(entity))
def get_params_dict(self):
return {"minutes": self.minutes, "reject_rate": self.reject_rate}
def set_params_from_dict(self, params):
self.minutes = params.get("minutes", self.minutes)
self.reject_rate = params.get("reject_rate", self.reject_rate)
SPEC_INSPECT = BlockSpec(
type_name="INSPECT", cls=Inspect, multi_output=True,
params=(ParamSpec("minutes", float, 1.0), ParamSpec("reject_rate", float, 0.1)),
factory=lambda env, block: Inspect(env, block),
)
NAGASIM_BLOCKS = [SPEC_INSPECT]
''', encoding="utf-8")
# 2. A script that uses it. It runs in a fresh Python, as your own scripts would. The engine reads
# NAGASIM_PLUGIN_PATH and imports every file in that folder, once.
Path("use_plugin.py").write_text('''
from nagasim import api, build as nb, plugins
report = plugins.load_plugins()
print("loaded:", report.loaded, "failed:", report.failed)
# The new block is now a builder method, like the built-in ones. A rejected entity goes to a
# five-minute rework step; a passed one leaves at once.
m = nb.Model(time_limit=2000, warmup=0)
arrive = m.create(distribution=nb.Exponential(rate=0.5))
check = m.inspect(minutes=0.5, reject_rate=0.2)
rework = m.delay(distribution=nb.Constant(value=5))
arrive >> check
m.link(check, m.dispose(), source_port=0)
m.link(check, rework, source_port=1)
rework >> m.dispose()
result = api.run_model(m.to_dict(), replications=5, seed=1)
print(f"mean time in the model: {result.kpi('system/Avg Throughput Time'):.2f} minutes")
print(f"by hand: 0.5 + 0.2 x 5 = {0.5 + 0.2 * 5:.2f} minutes")
''', encoding="utf-8")
env = dict(os.environ, NAGASIM_PLUGIN_PATH=os.path.abspath("plugins"))
done = subprocess.run([sys.executable, "use_plugin.py"], env=env, capture_output=True, text=True)
print(done.stdout, end="")
print(done.stderr, end="")
- Run it.
python goal-plugin.py
You should see this. The script seeds itself, so the numbers are the same on your machine.
loaded: ['blocks:INSPECT'] failed: []
mean time in the model: 1.52 minutes
by hand: 0.5 + 0.2 x 5 = 1.50 minutes
-
Read the plugin file. A block is a class that waits, then calls
self.forward(entity, port). Port 0 is the first outgoing link and port 1 the second.INSPECTsends an entity out of port 1 with probabilityreject_rate. -
Read its spec.
BlockSpecgives the block a type name, its parameters with their defaults, andmulti_output=Truebecause it has two exits. The file ends with a list calledNAGASIM_BLOCKS, which is the name the loader looks for. -
Read how it is found. The environment variable
NAGASIM_PLUGIN_PATHnames a folder. The engine imports every.pyfile in it once, on the first run or when you callplugins.load_plugins(). The first output line showsblocks:INSPECTloaded and nothing failed. -
Read the model. The builder gained a method
m.inspect(...), named after the type in lower case. A rejected entity goes to a five-minutedelay, and a passed one leaves at once. -
Check the result by hand. An entity spends 0.5 minutes in the inspection. One in five also spends 5 minutes in rework, so the mean is 0.5 + 0.2 x 5 = 1.5 minutes. The run gives 1.52.
-
Ship it as a package when others need it. Declare the spec under the entry-point group
nagasim.blocksinpyproject.toml, andpip installloads it with no environment variable. The example in the repository underexamples/plugins/inspection_pluginshows all three kinds.
Check yourself¶
- Predict, then run: set
reject_rateto 0.5. What mean time does the hand calculation give, and does the run agree? - Explain it back: why must a plugin's type name not collide with a built-in block?
Done when¶
- [ ] The first line lists
blocks:INSPECTand an emptyfailedlist. - [ ] The run's mean time is within a few percent of the hand calculation.
- [ ] You can say how a plugin is loaded without installing it, and how it is loaded after
pip install.
If stuck¶
| What happens | Likely cause | Fix |
|---|---|---|
failed lists your file |
The file raised an error on import | Read the message next to the path, fix the file and run again. |
failed says the name redefines a built-in |
type_name matches a block that exists |
Choose a new upper-case name. |
AttributeError on m.inspect |
The plugin was not loaded | Set NAGASIM_PLUGIN_PATH before the first run, or call plugins.load_plugins(). |
| An entity never reaches the second exit | The block has no link on port 1 | Add m.link(check, other, source_port=1). |
| A shared model fails on another machine | The plugin is not installed there | Install it there, or do not share a model that depends on it. A viewer refuses plugin blocks. |
Elements this page uses¶
- Python:
Modelandrun_model. - Blocks: CREATE, DELAY and DISPOSE.
- Distributions: Exponential and Constant.
- Background: Security explains why a plugin is trusted code, and Use from Python lists
nagasim.plugins.