Python and Node.js
Simulations can also be written in Python or in JavaScript/TypeScript. The cppmodel packages on PyPI and npm wrap the same CppModel library as the C and C++ APIs: every run fetches the inputs and parameters set for it in your workspace and records its execution there, and the results look the same as those of a C or C++ simulation.
This is useful for plant models, test scenarios and quick experiments, or for teams whose tooling is already in Python or Node.js. The code under test can still be C: call it from Python with ctypes or cffi, or from Node.js with an FFI library.
Installation
pip install cppmodel # Python 3.9 or later
npm install cppmodel # Node.js 18 or later
The packages contain the CppModel library for Linux (x86_64 and aarch64, glibc 2.28 or later), Windows (x64 and ARM64) and macOS 11 or later (Apple silicon and Intel). Nothing needs compiling or installing besides the package.
A simulation
Both examples simulate a heater: the controller under test switches it on below the set point.
Python
import sys
import cppmodel
class Heater(cppmodel.Simulation):
def init(self):
self.temperature = 20.0
def step(self, time_ms):
setpoint = self.inputs.get("Setpoint", 22.0) # input, with its fallback
gain = self.parameters.get("HeaterGain", 0.05) # parameter, with its fallback
heater_on = self.temperature < setpoint # the controller under test
self.temperature += gain if heater_on else -0.01
self.outputs["Temperature"] = self.temperature
self.outputs["HeaterOn"] = heater_on
self.outputs["CppModel.Step"] = time_ms
self.outputs["CppModel.StepResult"] = self.temperature < setpoint + 1.0
with Heater("Heater (Python)", total_time_ms=60_000, step_ms=100) as simulation:
sys.exit(simulation.run())
Node.js
import { Simulation } from 'cppmodel';
class Heater extends Simulation {
init() {
this.temperature = 20.0;
}
step(timeMs) {
const setpoint = this.inputs.get('Setpoint', 22.0); // input, with its fallback
const gain = this.parameters.get('HeaterGain', 0.05); // parameter, with its fallback
const heaterOn = this.temperature < setpoint; // the controller under test
this.temperature += heaterOn ? gain : -0.01;
this.outputs
.set('Temperature', this.temperature)
.set('HeaterOn', heaterOn)
.set('CppModel.Step', timeMs)
.set('CppModel.StepResult', this.temperature < setpoint + 1.0);
}
}
const simulation = new Heater('Heater (Node)', 60_000, 100);
process.exitCode = simulation.run();
simulation.close();
require('cppmodel') works too, and TypeScript types are included.
How a run works
The constructor takes the same three settings as a C simulation: the name in the workspace, the total time and the step time, both in milliseconds. run() fetches the pending inputs and parameters, calls init(), then step() for every step from 0 up to and including the total time, then finalize(), and records the execution in the workspace.
run() returns 0 when every step passed, otherwise the CppModel.Step of the first step whose CppModel.StepResult was 0. Use it as the exit code, as above, and the script works as a test in CI, just like a C simulation (see Adding verification).
An exception raised in init(), step() or finalize() aborts the run, records nothing and comes out of run().
Instead of subclassing, you can pass the functions in. They get the simulation as their first argument:
def ramp(sim, time_ms):
sim.outputs["Ramp"] = time_ms
sim = cppmodel.Simulation("Ramp", total_time_ms=1000, step_ms=100, step=ramp)
sim.run()
const sim = new Simulation('Ramp', 1000, 100, {
step: (sim, timeMs) => sim.outputs.set('Ramp', timeMs),
});
sim.run();
Inputs, outputs and parameters
| Python | Node.js | Meaning |
|---|---|---|
sim.inputs.get(name, fallback) | sim.inputs.get(name, fallback) | The input's value at the current step, or fallback, which is recorded as its value |
sim.outputs[name] = value | sim.outputs.set(name, value) | Sets an output. It holds until it is set again and is recorded every step |
sim.parameters.get(name, fallback) | sim.parameters.get(name, fallback) | The parameter from the workspace, or fallback, which is reported so it appears in the workspace |
sim.results() | sim.results() | The execution as recorded: inputs, outputs, parameters, and the verification outcomes and requirements when there are any |
Inputs and outputs are numbers; booleans become 1 and 0. Parameters keep their JSON type: numbers, booleans, strings, lists and objects.
Steps and input profiles
The packages schedule a test as a sequence of steps and input profiles, as in C and C++. A step is a function and its duration, a nested input profile run whole, or an inputs step that reads an input document during the step:
class MotorStarter(cppmodel.Simulation):
def __init__(self):
start = cppmodel.InputProfile((self.press_start, 100), (self.release_start, 200))
self.test = cppmodel.InputProfile(
(self.reset, 200),
start, # nested, run whole
(self.press_stop, 100),
cppmodel.InputProfile.inputs("inputs/guard-flicker.json", self.motor_stops),
(None, 500), # only waits
)
super().__init__("Motor starter", self.test.duration(10), 10)
def step(self, time_ms):
self.outputs["CppModel.StepResult"] = self.run_input_profile(self.test, time_ms)
import { InputProfile, Simulation } from 'cppmodel';
class MotorStarter extends Simulation {
constructor() {
const start = new InputProfile([[(t) => pressStart(t), 100], [(t) => releaseStart(t), 200]]);
const test = new InputProfile([
[(t) => reset(t), 200],
start, // nested, run whole
[(t) => pressStop(t), 100],
InputProfile.inputs('inputs/guard-flicker.json', (t) => motorStops(t)),
[null, 500], // only waits
]);
super('Motor starter', test.duration(10), 10);
this.test = test;
}
step(timeMs) {
this.outputs.set('CppModel.StepResult', this.runInputProfile(this.test, timeMs));
}
}
run_input_profile() (Node.js: runInputProfile()) records the running step's number as CppModel.Step, so a failed run's result is the number of the first failing step.
Verification rules and requirements
The packages have the same verification rules as the C and C++ APIs. Create each rule once, in the constructor, and update the step rules in step(). Signal rules read an output by name after every step by themselves. A failing rule sets CppModel.StepResult to 0 at the steps where it fails, so the simulation doesn't need to set it.
from cppmodel import verify
class Zone(cppmodel.Simulation):
def __init__(self):
super().__init__("Zone", total_time_ms=3_600_000, step_ms=1000)
self.valve_range = verify.Always(self, "valve range")
self.smoke = verify.Response(self, "smoke stops fan", deadline_s=2, hold_s=60)
self.step_response = verify.Settle(self, "setpoint step", band=0.5, settle_limit_s=1800, stay_s=600)
self.modes = verify.Mode(self, "modes").allow(OFF, STARTUP).allow(STARTUP, RUN).dwell(STARTUP, max_s=30)
verify.Rate(self, "temperature rate", "Zone.T", max_rate=0.01) # reads the output by itself
self.verify_requirement("ZONE-SAF-001") # this run verifies the requirement
def step(self, time_ms):
...
self.valve_range(verify.between(valve, 0, 100))
self.smoke(smoke, not fan and valve == 0)
self.step_response(temperature, setpoint)
self.modes(mode)
if smoke:
self.verify_requirement("ZONE-SAF-004") # verified at these steps
import { Simulation, verify } from 'cppmodel';
class Zone extends Simulation {
constructor() {
super('Zone', 3_600_000, 1000);
this.valveRange = new verify.Always(this, 'valve range');
this.smoke = new verify.Response(this, 'smoke stops fan', 2, 60);
this.stepResponse = new verify.Settle(this, 'setpoint step', 0.5, 1800, 600);
this.modes = new verify.Mode(this, 'modes').allow(OFF, STARTUP).allow(STARTUP, RUN).dwell(STARTUP, null, 30);
new verify.Rate(this, 'temperature rate', 'Zone.T', 0.01); // reads the output by itself
this.verifyRequirement('ZONE-SAF-001'); // this run verifies the requirement
}
step(timeMs) {
// ...
this.valveRange.update(verify.between(valve, 0, 100));
this.smoke.update(smoke, !fan && valve === 0);
this.stepResponse.update(temperature, setpoint);
this.modes.update(mode);
if (smoke) this.verifyRequirement('ZONE-SAF-004'); // verified at these steps
}
}
| Python | Node.js |
|---|---|
Always(sim, name, debounce_s=0) | Always(sim, name, debounceS) |
Response(sim, name, deadline_s, hold_s=0) | Response(sim, name, deadlineS, holdS) |
Settle(sim, name, band, settle_limit_s, stay_s, overshoot_limit=None) | Settle(sim, name, band, settleLimitS, stayS, overshootLimit) |
Mode(sim, name), with .allow(from, to) and .dwell(mode, min_s, max_s) | Mode(sim, name), with .allow(from, to) and .dwell(mode, minS, maxS) |
Oscillation(sim, name, signal, amplitude, duration_s, active=None) | Oscillation(sim, name, signal, amplitude, durationS, active) |
Wear(sim, name, signal, max_reversals_per_h, max_travel_per_h, deadband, active) | Wear(sim, name, signal, {maxReversalsPerHour, maxTravelPerHour, deadband, active}) |
Rate(sim, name, signal, max_rate, active) | Rate(sim, name, signal, maxRate, active) |
Energy(sim, name, signal, factor, budget, active) | Energy(sim, name, signal, factor, budget, active) |
Percent(sim, name, signal, min_percent, active) | Percent(sim, name, signal, minPercent, active) |
- Conditions carry a margin:
at_most,at_least,between,nearandimpliesin Python, combined with&,|and~;verify.atMost,atLeast,between,near,and,or,notandimpliesin Node.js. A plain boolean has no margin. - Checking a rule:
rule.passedandrule.margingive its verdict so far. - Outcomes: each rule's outcome is printed when the run ends and stored in the execution's
verificationfield:sim.results()["verification"]in Python,sim.results().verificationin Node.js. - Requirements:
sim.verify_requirement(id)(Node.js:sim.verifyRequirement(id)) in the constructor orinit()covers the whole run, and instep()covers that step. The IDs are recorded in the execution'srequirementsfield and incppmodel-requirements.json. See Requirements.
Structured Text (VirtualPLC)
PLC code in IEC 61131-3 Structured Text runs in a Python or JavaScript simulation through VirtualPlc, the library's Structured Text interpreter. The plant model is your script, and the controller under test is the .st files:
class Tank(cppmodel.Simulation):
def init(self):
self.plc = cppmodel.VirtualPlc("Tank.st") # loads and starts
self.level = 50.0
def step(self, time_ms):
self.plc["Level"] = self.level # the PLC's inputs
self.plc.cycle(time_ms) # the tasks due at this time
valve = self.plc["Valve"] # its outputs
self.level += (0.8 if valve else 0.0) - 0.3
self.outputs["Level"] = self.level
import { Simulation, VirtualPlc } from 'cppmodel';
let plc, level;
const sim = new Simulation('Tank (ST)', 60000, 100, {
init: () => {
plc = new VirtualPlc('Tank.st'); // loads and starts
level = 50;
},
step: (s, timeMs) => {
plc.set('Level', level).cycle(timeMs); // the PLC's inputs, the tasks due
const valve = plc.get('Valve'); // its outputs
level += (valve ? 0.8 : 0) - 0.3;
s.outputs.set('Level', level);
},
});
sim.run();
plc.variables() lists the PLC's inputs, outputs, locals and globals. A syntax error, or a fault while cycling, raises (throws) a CppModelError with Status.PROGRAM and the .st file and line.
Workspace access
Every run signs in to your workspace, the same way as a C or C++ simulation:
- For scripts and CI, set
CPPMODEL_USERNAMEandCPPMODEL_PASSWORD, andCPPMODEL_LOGIN_TIMEOUT=0so a missing login fails at once. - Without credentials, the first run prints a sign-in link and waits 60 seconds for you to sign in. Jupyter doesn't show that link, so use credentials in notebooks.
See Command Line and Environment for the full list.
Things to know
- Fingerprint: each execution records a
CppModel.BinaryFingerprintof the simulation's code, so the workspace can tell runs of the same code from runs of changed code. It is the fingerprint of the file that defines the simulation. Setsim.fingerprint_file(Node.js:sim.fingerprintFile) to use another file. When that file is in a git repository, the run also records the commit asCppModel.GitHash(see What a run records). - Node.js runs are synchronous.
run()blocks the event loop until the simulation has finished. That is fine for scripts and tests; in a server, run simulations in a worker thread. - Cleanup: in Python, use the simulation as a context manager (
with ... as simulation). In Node.js, callclose()when you're done. - Errors: a failing library call raises
cppmodel.CppModelErrorin Python and throws aCppModelErrorin Node.js. - Local runs: the
--inputsand--resultsoptions work for scripts too, for examplepython heater.py --inputs candidate.json --results out.json. - Persistent simulations are available in C and C++ only.
License
The packages contain the CppModel library, which is proprietary software of Control Edge AB, used under the CppModel Terms of Service, and third-party components under their own licenses.