Python API#
paperboat binds the C++ engine (paperboat._engine, nanobind). The engine does
everything a backend does; Python provides only the domain’s own code, as subclasses of
the classes below. A class’s attributes define it (what the UI shows), its methods
are what the engine calls. The classes a backend passes become the domain’s package
(named after the descriptor’s domain), so the palette has them without the descriptor
listing them.
Install: nothing to do with a paperboat package (.tar.gz, .zip): it ships the
module in lib/paperboat/python and paperboat run / check put it on PYTHONPATH for
the backend process. To import paperboat in a process the CLI did not start (an IDE, a
service), install the wheel instead. It is
built for CPython 3.11 and, through the stable ABI (abi3), for every CPython from 3.12 on; the
interpreter is the backend’s .venv, else $PAPERBOAT_PYTHON, else python3. Elsewhere:
pip install a release wheel, or pip install ./python (or npm run build:python and
PYTHONPATH=python while developing). Never implement a framework feature here: add it to the
engine and bind it.
API Quick Reference#
Category |
Symbol |
Description |
|---|---|---|
Ports & Definitions |
Input/output port with data type, dimensions, and unit annotations. |
|
Label and engineering unit for an ordered vector channel. |
||
Factory helper constructing typed vector ports with named channels. |
||
Parameter declaration (number, key, enum dropdown, file). |
||
Association between a station object and its Flow linked block. |
||
Blocks |
Base computational block evaluated each clock step. |
|
Signal generator computing \(f(t)\) from time and parameters. |
||
Telemetry instrument piping data to Board scopes and readouts. |
||
Step flow node executing sequential procedural actions. |
||
Step block that runs for a configured duration before moving to next. |
||
Station & Geometry |
Physical domain entity with properties, links, and visual shapes. |
|
3D/2D visual scene shape rendered on the Station page. |
||
|
3D and 2D visual geometry entity factory functions. |
|
Models & Solvers |
Continuous plant differential equation ODE model. |
|
Step a differential equation solver forward by \(\Delta t\). |
||
Configured numerical ODE integrator (e.g. RK4). |
||
Runtime context providing simulation time |
||
Domain & Server |
Global domain-level state spanning multiple blocks. |
|
Opaque data handle passed across flow wires. |
||
Programmatically defined domain backend. |
||
Launch the WebSocket/HTTP server on a designated port. |
Definitions#
- class paperboat.Port(id, type='signal', unit='', dimension=None, components=())#
A port with a type other than
"signal":Port("points", "points"),Port("in", "step"). Plain strings are signal ports. A"vector"port carries an ordered list of numbers on one wire.dimensiondeclares a fixed length;componentscan name the entries and their units.
- class paperboat.VectorComponent(id, unit='')#
One ordered vector component’s label and optional unit. A component can also be written as a name or
(name, unit)pair.
- paperboat.vector_port(id, dimension=None, components=())#
Make a vector
Port. For example:outputs = [vector_port("state", components=[("x", "m"), ("angle", "rad")])]The port’s ordered components travel together; names are descriptive, while known dimensions and units are checked on the wire. Use
paperboat.Vector(an alias forlist[float]) to annotate a block’s numeric vector values.
- class paperboat.Param(default, type='number', options=())#
A param (or property) whose type its default doesn’t say:
Param("Space", "key"),Param("data/a.png", "file"),Param("fast", "enum", ["slow", "fast"])(a dropdown: the block gets the name). Plain defaults say it: a number (number), a bool (boolean, a checkbox, 1.0 or 0.0 to the block), text (text).Param("Kp", "variable")names a project variable (a picker in the UI): the block gets the name, to pass toctx.variableorctx.set_variable.
- class paperboat.Linked(inputs=(), outputs=(), kind='probe', label='')#
A station object’s linked block: the block on the Flow page through which a flow acts on it.
Blocks#
- class paperboat.Block(params)#
A signal block: outputs from inputs, once per pass.
- description: str#
One line in plain words: what it does. Shown on its card in the block browser.
- flows: list[str]#
The flow types it works in; empty: every type (#9).
- view: dict#
How the UI draws the block, a hint (absent: the normal card). Keys, all optional:
compact(a small plate with bare port dots and a caption),glyph(a few characters drawn as text; a curve is aview.icon) andvalue(an expression of the params for the caption, such as"{k}").
- ports_from: str#
The name of a text param that decides the block’s inputs: one per sign character in its value (
"+-+": idsa,b,c; at most 26);inputsis only the default.
- inputs_from: str#
The name of a text param whose expression’s free names are the block’s inputs (“f”).
- outputs_from: str#
The name of a text param of names (
"x v theta", space- or comma-separated) that are the block’s outputs, in order;outputsis only the default. The first vector input gets one component per name, and aunitsparam gives their units by position.
- elementwise: bool#
Truefor a block written for one number that should also work on vectors: its signal ports then take a vector wire too. With a vector of N in, the engine makes N instances of the class (each with its ownself.paramsand state), gives each its element (and every number input whole), and gathers each output into a vector of N;stepstill sees floats. With only numbers in, nothing changes. A block that needs the whole vector declaresvector_port()ports instead and gets a list.
- cacheable: bool | None#
Truefor a block whose outputs depend on nothing but its params, its inputs and the variables it reads throughctx.variable()(no clock, keys,ctx.state, randomness, files or side effects). A backend withmode="once"then reuses its outputs from the last run while none of those changed. DefaultNone: called every run.
- feedthrough: bool#
Falsefor a block whose outputs this step don’t depend on its inputs this step (an integrator, a delay). Implementcurrent();stepthen takes the inputs after the pass, and a feedback loop may pass through the block. DefaultTrue.
- current() dict#
A block without feedthrough: what it outputs now, from its state alone.
- type: str#
Its id in the catalog. Required.
- label: str#
Shown on the block (default:
type).
- kind: str#
"source","probe","function"(default) or"monitor".
- class paperboat.Generator(params)#
A signal f(t): implement
value(t).tis the block’s inputtwhen wired (a step’sprogress), else the run clock; the engine does that and outputsy.- value(t) float#
- class paperboat.Monitor(params)#
A
Blockthat shows its input on the Dashboard.kind = "monitor",inputs = ["in"].- instrument: str#
"graph"(default),"display"or"image".
- step(ctx, inputs) dict#
Optional: return
{"value": …}to show something other than the input.
- class paperboat.Step(params)#
A block on a Step flow’s path. Same definition attributes as
Block;inputsdefault to[Port("in", "step")],outputsto[Port("next", "step")].- enter(ctx, inputs)#
A path arrived.
- tick(ctx, inputs) str#
Each clock step while the path is here: the step output to leave by, or
""to stay.
- may_start() bool#
For a hat (step outputs, no step input): whether it may still start a path.
- ends_run() bool#
- current() dict#
Its signal outputs now (ports of a type other than
step), such as a progress; read a clock step later.
- class paperboat.Timed(params)#
A step that does its work over
seconds(a param it must have; default 1). The engine follows the optionalcurveinput (0–1; the first frame stays at 0) when wired, evenly otherwise, ends at 1, and outputsprogress. Ports:in,curve→next,progress.- begin(ctx, inputs)#
A path arrived.
- advance(ctx, start, end)#
Move the work from progress
starttoend.
Station objects#
- class paperboat.StationObject(props)#
A thing on the Station: owns its state and properties (edited on the Station page only).
- type: str#
- label: str#
- role: str#
"body"(default) or"joint".
- links: list[str]#
Slots naming other station objects (
["a", "b"]).
- read() dict#
The linked block’s outputs, from the current state.
- step(ctx, inputs)#
Advance one clock step under the linked block’s inputs.
- entities(id, z) list#
Its shapes (
paperboat.scenebuilders, or protocol entity dicts), ids prefixed withid + "/", at depthz.
- link(slot, other)#
Another station object fills one of its slots, once, before a run (
otherisNonefor a toolkit object, which Python can’t reach).
Models, solvers and scenes#
Bound from the engine’s toolkit (C++: Model, paperboat::solve,
paperboat::scene), so a domain writes its equations and its look, not its stepping.
- class paperboat.Model(props)#
A
StationObjectthat is a system of differential equations: it gives its initial state andderivatives(), and the engine’s solver advances it each clock step.- solver: str#
"rk4"(default),"rk45","rk2","euler","discrete", or the implicit"cvode"and"ida"(SUNDIALS, for stiff systems). Asolverprop (Param("rk4", "enum", paperboat.solve.names())) wins, so the user can pick one on the Station page.
- x: list[float]#
The state now, kept current by the engine: use it in
read()andentities().
- initial() list[float]#
The state when a run starts.
- derivatives(t, x, inputs) list[float]#
dx/dtat timetin statex, under the linked block’s inputs (a dict; unwired ones absent). For"discrete", the next state.
class Mass(paperboat.Model):
type, label = "mass", "Mass on a spring"
props = {"k": 4.0, "x0": 1.0}
block = paperboat.Linked(inputs=["force"], outputs=["x", "v"])
def initial(self):
return [self.props["x0"], 0.0]
def derivatives(self, t, x, inputs):
return [x[1], inputs.get("force", 0.0) - self.props["k"] * x[0]]
def read(self):
return {"x": self.x[0], "v": self.x[1]}
def entities(self, id, z):
return [paperboat.scene.rect(f"{id}/mass", self.x[0], 0, 0.4, 0.4, "#2f5d62", z=z),
paperboat.scene.spring(f"{id}/spring", (-2, 0), (self.x[0] - 0.2, 0))]
- solve.step(solver, f, x, t, dt) list[float]#
One step with a fresh solver:
xadvanced fromttot + dtunderf(t, x).xand whatfreturns may be any sequence of numbers (a list, a tuple, a numpy array).
- class solve.Solver(name='rk4', rtol=1e-6, atol=1e-9, max_steps=100000)#
A solver kept between steps (
rk45carries its step size,cvodeandidatheir history: keep one rather than callingsolve.step()each time).step(f, x, t, dt)returns the new state. An unknown name raisesValueErrornaming the solvers.- restart()#
Forget what it carries between steps: call it after the equations change.
- solve.names() list[str]#
rk4,rk45,rk2,euler,discrete, thencvodeandidawhen the engine is built with SUNDIALS (the default).
- paperboat.ode(f, x0, solver='rk4', **options) ODE#
Bootstrap an ODE system \(dx/dt = f(t, x)\) with a built-in solver (
"rk4","rk45","rk2","euler","discrete","cvode"or"ida"). Returns anODEinstance whose state is advanced byode.step(dt)orode.step(t, dt).
- class paperboat.ODE#
- x#
- Current state vector (list or numpy array, preserving input array type).
- t#
- Current simulation time.
- solver#
- Name of the active solver algorithm.
- step(t_or_dt, dt=None)#
Advance the ODE state by one step. Supports calling as
step(dt)orstep(t, dt).
- restart()#
Forget the solver’s history: call it after the equations change.
Convenience solver constructors are also available directly on paperboat.solve:
solve.ode, solve.rk4, solve.rk45, solve.rk2, solve.euler, solve.discrete,
solve.cvode and solve.ida.
The scene builders return Entity objects; entities() may return them,
dicts, or lists of them (a spring), mixed. Points are (x, y) or (x, y, z).
- scene.rect(id, x, y, width, height, color='#888888', angle=0, z=0)#
- scene.circle(id, x, y, radius, color='#888888', z=0)#
- scene.box(id, pos, size, color='#888888', rot=None)#
- scene.sphere(id, pos, radius, color='#888888')#
- scene.line(id, a, b, color='#888888')#
- scene.image(id, pos, width, height, src)#
- scene.rod(id, a, b, thickness, color='#888888')#
A bar from
atob.
- class paperboat.Entity#
One shape:
id,shape,pos,size,rot,color,scale,to,src, each settable.
Domain state#
- class paperboat.DomainState#
What a domain’s blocks share during a run. The engine makes one per run (from
Backend.state), steps it after each clocked pass and draws it.- entities() list[dict]#
- patch() list[dict]#
The entities that change (default: all).
- step(ctx) str | None#
Advance after a clocked pass; a message ends the run.
- summary() str | None#
Logged when a run ends.
What a block sees#
- class paperboat.Context#
Passed to every call. Valid during the call only.
- t#
The run clock, s.
- dt#
The clock step, s.
- keys#
The set of keys held down in the UI (
KeyboardEvent.codevalues).
- state#
The domain state for this run, or
None.
- node#
The id of the block (or station object) being called.
- variable(name)#
A project variable’s value now: a number, a boolean as 1.0 or 0.0, text;
Noneif there is none of that name.
- set_variable(name, value)#
Set a
tunablevariable (#166), as an autotuner or a calibration does: a number (orbool) for a number or boolean variable, text for an enum, text or file one. It takes effect at the end of the pass; formulas and params bound to it follow, and the UI keeps the value in the project. ReturnsFalse, with a warning in the Console, if refused (unknown, not tunable, a formula, the wrong type, out of range).
- log(text, level='info')#
Write a line to the Console (
info,warn,error), tagged with this block.
- progress(fraction)#
How far a long step has got, 0 to 1: the UI shows it on the block.
- metric(series, y, x=None, unit='')#
A point of a series that isn’t on the run clock (a solver’s residual against its iteration):
yagainstx, or against the series’ next index (0, 1, 2…) without it.unitis y’s. Sent as ametricevent.
- monitor_state(state, value, port='')#
What this monitor says now:
"ok","warn"or"trip", and the value that put it there. Call it every step; the UI hears of a change only (monitor.state).
- frame(shapes=None, field=None, view=None)#
A live picture (
frame):shapesas the protocol’sFrameShapedicts ({"t": "circle", "p": [[x, y]], "r": 0.1, "fill": "signal"}),fielda dict{"w", "h", "v", "min"?, "max"?}(vrow by row from the top,Nonefor no value),view[xmin, ymin, xmax, ymax](y up). At most ~20 a second per block are sent, always the last.
- class paperboat.Handle#
Opaque data on a wire (an image…): pass it along as is.
kindnames what it holds.
Serving#
- class paperboat.Backend#
- engine: str#
Its name in
hello.
- descriptor: pathlib.Path#
- objects#
A list of classes: the domain’s
StationObjectclasses.
- state: Callable[[], DomainState] | None#
A fresh domain state per run.
- mode: str#
"clock"(default) or"once".
- dt: float#
- duration: float#
- emit_every: int#
- speed: float#
Times real time (0: as fast as it can). The defaults here are what the UI shows; a user may change
durationandspeedper run, andspeedduring one (run.speed, handled by the engine’s run loop).
- view: dict | None#
The scene’s camera hint.
- port: int#
- paperboat.serve(backend)#
The engine’s command line: serve on
--port Nuntil Ctrl+C, or with--runrun the starter once headless, print each protocol message as a JSON line and exit (0 when done).