API reference¶
Generated from the docstrings (DOC-001).
Base and layout¶
anywidget_instruments_industrial.InstrumentWidget ¶
Bases: InstrumentWidget
Base class of every industrial widget: one bundle serves them all.
See :class:anywidget_instruments.InstrumentWidget for the common traits.
anywidget_instruments_industrial.Panel ¶
Bases: GridBox
Arrange widgets in a grid; any ipywidgets widget can be mixed in.
Panel([Knob(label="Gain"), LED(label="Run")], columns=2)
anywidget_instruments_industrial.batch ¶
batch() -> Iterator[None]
Group widget updates; their callbacks run by priority when the block exits.
with ai.batch(): ... level.value = 3.2 ... estop.value = True # estop callbacks run first
anywidget_instruments_industrial.set_default_style ¶
set_default_style(style: str) -> None
Set the style used by every widget created afterwards.
Existing widgets are not modified; change their style trait instead.
anywidget_instruments_industrial.get_default_style ¶
get_default_style() -> str
Return the style applied to newly created widgets.
anywidget_instruments_industrial.set_theme ¶
set_theme(theme: str) -> None
Switch every open widget, and the widgets created afterwards, to theme.
"light" and "dark" force the palette whatever the host;
"system" follows the host or operating system color scheme whatever
the style; "auto" lets the style decide (the "system" style
follows the host, the others stay light) (STYLE-007, STYLE-008).
anywidget_instruments_industrial.get_default_theme ¶
get_default_theme() -> str
Return the theme applied to newly created widgets.
anywidget_instruments_industrial.theme_switch ¶
theme_switch(label: str = 'Theme', **kwargs: Any) -> Any
A :class:ThemeSwitch (light / system / dark) for every widget.
Put it at the top of a notebook or app::
ai.theme_switch()
In marimo the page follows the switch as well (STYLE-008).
anywidget_instruments_industrial.ThemeSwitch ¶
Bases: InstrumentWidget
Three-position switch for the theme of every widget: light, system, dark.
Selecting a position calls :func:anywidget_instruments_industrial.set_theme;
"system" follows the host or operating system color scheme. With
page_theme (the default) the notebook page follows the switch too,
where the host allows it (marimo); other hosts keep their own theme
setting (STYLE-008). value is "auto" until a position is chosen.
Usually built with :func:anywidget_instruments_industrial.theme_switch.
anywidget_instruments_industrial.set_heartbeat ¶
set_heartbeat(interval: float) -> None
Set the heartbeat interval in seconds for every widget; 0 disables it.
Views flag data as stale after about three missed heartbeats. Increase the interval if long GIL-holding computations cause false stale indications.
anywidget_instruments_industrial.get_heartbeat ¶
get_heartbeat() -> float
Heartbeat interval in seconds (0 = stale detection disabled).
Numeric¶
anywidget_instruments_industrial.NumericWidget ¶
Bases: InstrumentWidget
Base class of every numeric widget.
Scale: min, max, step, unit, scale ("linear"/"log"),
ticks (major intervals), minor_ticks (subdivisions per interval).
Display: format is a printf-like spec: %.2f fixed, %.3e scientific,
%.3g general, %.3n engineering (exponent multiple of 3),
%.3s SI prefix (m, µ, k, M ...), and for registers %X / %x
hexadecimal, %b binary, %o octal, with an optional zero-padded
width such as %04X (IND-110); values are then typed in that base.
Input (API-014): in control mode the value can be set on the drawing (drag,
wheel, arrow keys) or typed in the value field (entry=True, the
default). Typed values are snapped to step; a value outside
[min, max] is rejected, or clamped when coerce is set (NUM-010).
Alarms: lolo, lo, hi, hihi, deadband; the resulting level
is published in alarm_level. show_limits draws them on the scale.
Discrete positions (IND-118): value_labels names values, as
[{"value": 0, "label": "OFF"}, ...] or {0: "OFF", 1: "LOW", 2: "HIGH"}.
The scale then shows the labels instead of numbers, the readout shows the
label of the current value, and the label can be typed in the value field.
Engineering scaling: set raw_min, raw_max, eng_min, eng_max and
call :meth:set_raw with the raw reading.
anywidget_instruments_industrial.Knob ¶
anywidget_instruments_industrial.Dial ¶
anywidget_instruments_industrial.Gauge ¶
Bases: _PeakMixin
Circular or semi-circular gauge with needle and colored ranges (NUM-103).
ranges is a list of {"from": float, "to": float, "color": css_color}.
setpoint (None by default) is drawn as a second, dashed pointer
with a hollow marker, next to the needle of the value (IND-116).
anywidget_instruments_industrial.Meter ¶
Bases: _PeakMixin
Analog needle meter with a sector scale (NUM-104).
setpoint (None by default) is drawn as a second, dashed pointer
(IND-116).
anywidget_instruments_industrial.VUMeter ¶
Bases: _PeakMixin
Segmented bar graph with peak-hold marker (NUM-105).
anywidget_instruments_industrial.Tank ¶
anywidget_instruments_industrial.Thermometer ¶
anywidget_instruments_industrial.FillSlide ¶
anywidget_instruments_industrial.SevenSegment ¶
anywidget_instruments_industrial.Compass ¶
anywidget_instruments_industrial.compute_alarm_level ¶
compute_alarm_level(value: float, *, lolo: float | None = None, lo: float | None = None, hi: float | None = None, hihi: float | None = None, deadband: float = 0.0, previous: str = 'normal') -> str
Return the alarm level of value.
Entering a more severe level is immediate. Leaving a level requires the
value to move back beyond that level's limit by at least deadband
(ALARM-003). A non-finite value keeps the previous level.
anywidget_instruments_industrial.eng_scale ¶
eng_scale(raw: float, raw_min: float, raw_max: float, eng_min: float, eng_max: float) -> float
Linear conversion of a raw value (e.g. 4-20 mA, ADC counts) to engineering units.
Boolean¶
anywidget_instruments_industrial.BooleanWidget ¶
Bases: InstrumentWidget
Base class of Boolean widgets.
mechanical_action defines how a control reacts to the pointer:
switch_*: the value toggles and is kept (switch_until_releasedholds the non-default value only while pressed);latch_*: the value changes and is kept until the kernel reads it with :meth:read_latched, then returns todefault_state. Withlatch_timeout> 0 an unread latch expires and fireslatch_expired.
anywidget_instruments_industrial.LED ¶
anywidget_instruments_industrial.ToggleSwitch ¶
anywidget_instruments_industrial.RockerSwitch ¶
anywidget_instruments_industrial.SlideSwitch ¶
anywidget_instruments_industrial.PushButton ¶
Bases: BooleanWidget
Push button with a text (or emoji/icon) caption (BOOL-006, BOOL-015).
color is the cap color (IEC 60073: green to start, red to stop...),
shape is "rect" or "round" (panel operator).
Illuminated push button: set lamp to True / False to give the
button a built-in lamp, lit or not, in lamp_color (lamp_blink to
flash it). The lamp is feedback set by the program (for example START lit
while the machine runs), independent of the button value; None
(the default) means no lamp.
anywidget_instruments_industrial.EmergencyStop ¶
Bases: BooleanWidget
Red mushroom emergency stop button (BOOL-012).
Pressing it latches value to True; only :meth:reset brings it back
to False. Its callbacks have the highest priority: inside a batch
(every front-end update, or :func:anywidget_instruments_industrial.batch) they run
before any other pending widget callback (BOOL-013).
Warnings
This widget draws an emergency stop; it is not an emergency stop device (ISO 13850, IEC 60204-1) and must never be the means of stopping a machine. See the safety notice of the documentation (DOC-007).
Graphs¶
anywidget_instruments_industrial.GraphWidget ¶
Bases: InstrumentWidget
Base class of graphs and charts.
Cursors (CHART-104)
cursors is a list of {"x": float, "name": str, "color": str} in
x-axis units. The user drags them on the plot; cursor_values holds,
for each cursor, {"name", "x", "values"} with the (interpolated)
values under it, recomputed by the kernel.
Annotations (CHART-105)
annotations is a list of {"x", "y", "text", "color"} in data
coordinates.
Zoom (CHART-106)
Zoom tool in the toolbar (drag a rectangle), mouse wheel on the time
axis, double-click to restore the full view.
Export (CHART-107)
With export=True the toolbar offers CSV, PNG and SVG downloads.
anywidget_instruments_industrial.WaveformChart ¶
Bases: GraphWidget
Scrolling multi-trace chart fed from the kernel with :meth:append.
Samples are kept in a circular buffer of history points per trace and
sent to the front end as binary float32 buffers (never JSON lists).
update_mode:
* "strip": continuous scroll, newest data on the right;
* "scope": fill from left to right, then clear and restart;
* "sweep": a moving cursor overwrites the oldest data.
traces optionally describes each trace:
{"name": str, "color": css_color, "width": float, "visible": bool,
"axis": "left" | "right"}.
Axes (IND-117): y_scale="log" makes the Y axis logarithmic (values
<= 0 are not drawn); traces with "axis": "right" are drawn against a
secondary axis on the right, ranged by y2_min / y2_max or by
their data with autoscale_y2, in y2_unit.
total_samples
property
¶
total_samples: int
Number of samples appended since creation or the last :meth:clear.
append ¶
append(samples: Any) -> None
Append samples: a scalar, a 1-D array or a 2-D (n_points, n_traces) array.
For a single-trace chart a 1-D array holds consecutive points; for a multi-trace chart it holds one sample per trace.
anywidget_instruments_industrial.IntensityChart ¶
Bases: GraphWidget
Scrolling 2-D color map: spectrogram / waterfall (CHART-101).
Each call to :meth:append adds one or more rows (e.g. spectra of
n_bins values). Time runs along x (dt per row), bins along y,
mapped to [y_min, y_max]. Colors map [z_min, z_max] (or the
data range with autoscale_z) through colormap.
value summarizes the latest row: {"rows", "min", "max", "argmax"}.
anywidget_instruments_industrial.DigitalWaveformGraph ¶
Bases: GraphWidget
Logic timing diagram with bus grouping (CHART-102).
set_data takes an (n_samples, n_lines) array of 0/1 values, or
integers plus n_bits (line k = bit k). lines names the lines and
buses groups them: {"name": "D", "lines": [7, 6, ..., 0]} (MSB
first); bus values are displayed in hexadecimal.
anywidget_instruments_industrial.MixedSignalGraph ¶
Bases: DigitalWaveformGraph
Analog traces and digital lines on a shared time axis (CHART-103).
Use :meth:set_analog with an (n_samples, n_traces) array and
:meth:set_data for the logic lines.
anywidget_instruments_industrial.unpack_bits ¶
unpack_bits(values: Any, n_bits: int) -> np.ndarray
Integers → (n, n_bits) array of 0/1, column k = bit k (LSB first).
Specialized displays¶
anywidget_instruments_industrial.PolarPlot ¶
Bases: _SeriesWidget
Magnitude/angle data sets on polar axes (SPEC-002).
angle_unit is "deg" or "rad"; zero sets where angle 0 is
("E" mathematical convention or "N" compass convention) and
direction the positive sense. r_max=None scales to the data.
plot ¶
plot(magnitude: Any, angle: Any, name: str = '', color: str = '', style: str = 'line', replace: bool = True) -> int
Add (or replace, by name) a data set; style is line, markers or both.
anywidget_instruments_industrial.SmithChart ¶
Bases: _SeriesWidget
Smith chart of impedances or reflection coefficients (SPEC-003).
Impedances are normalized to z0 (ohms) and stored as reflection
coefficients Γ = (z - z0) / (z + z0) in value (re/im lists).
anywidget_instruments_industrial.RadarChart ¶
Bases: _SeriesWidget
Multi-axis (spider) chart (SPEC-004).
axes names the axes; ranges optionally gives [min, max] per
axis (default [0, max of data]).
anywidget_instruments_industrial.PictureControl ¶
Bases: InstrumentWidget
A canvas on which Python code draws primitives.
Drawing commands issued during one cell execution are batched and
rendered in a single frame. Call :meth:flush to send them earlier (for
example inside a long-running loop). Coordinates are CSS pixels, origin
top-left. In control mode, clicks are reported in value ({"x", "y",
"button"}) and to :meth:on_click callbacks (SPEC-006).
arc ¶
arc(cx: float, cy: float, r: float, start: float, end: float, stroke: str | None = 'currentColor', fill: str | None = None, width: float = 1.0) -> PictureControl
Arc from start to end degrees, clockwise from 3 o'clock.
image ¶
image(x: float, y: float, data: Any, w: float | None = None, h: float | None = None) -> PictureControl
Draw an image: PNG/JPEG bytes or a (H, W[, 3|4]) uint8 array.
on_click ¶
on_click(callback: Callback) -> Callback
Register callback(event) with event = {"x", "y", "button"}.
Supervisory objects¶
anywidget_instruments_industrial.ProcessObject ¶
Bases: InstrumentWidget
Base of Valve, Pump and Motor.
In control mode, clicking the object opens a faceplate (SCADA-009) with
its commands and an auto/manual switch. Commands are delivered to
:meth:on_command callbacks as {"command": name}; the object state
(value) is feedback from the process and is not changed by a command,
unless simulate=True (handy for teaching and simulations).
anywidget_instruments_industrial.Valve ¶
Bases: ProcessObject
On/off or control valve (SCADA-001).
value: "open", "closed", "transit" or "fault".
position: optional opening in % for control valves (feedback).
For a control valve (position set), the faceplate also takes a
position demand in manual mode, with a slider or a typed value (API-014):
:meth:on_command callbacks receive {"command": "position", "value": %}.
demand_position ¶
demand_position(percent: float) -> None
Position demand (0 to 100 %) as if the operator used the faceplate.
anywidget_instruments_industrial.Pump ¶
anywidget_instruments_industrial.Motor ¶
anywidget_instruments_industrial.Pipe ¶
Bases: InstrumentWidget
Pipe segment: straight, elbow, tee or cross, rotated by 0/90/180/270° (SCADA-004).
value is True while the fluid flows; with flow_animation a moving
pattern shows flow_direction ("forward" or "reverse").
Unrotated shapes: straight = left→right, elbow = left→bottom,
tee = left→right plus a branch to the bottom, cross = all four sides.
anywidget_instruments_industrial.SynopticCanvas ¶
Bases: InstrumentWidget
Place widgets and pipe runs at absolute coordinates on a background (SCADA-010).
Children are rendered through the host widget manager (Jupyter). Pipe runs are polylines drawn by the canvas itself, with optional flow animation::
syn = SynopticCanvas(size=(600, 300), background=png_bytes)
syn.add(Tank(label="T1"), x=40, y=40)
run = syn.add_pipe([(100, 200), (300, 200), (300, 120)], flow=True)
syn.set_flow(run, False)
anywidget_instruments_industrial.AlarmIndicator ¶
Bases: InstrumentWidget
Single alarm annunciator.
value is the alarm state. Use :meth:activate, :meth:clear and
:meth:acknowledge (or the ACK button in control mode) to drive it.
Warnings
Presents alarms; it is not an alarm management system nor a safety function. Critical alarms need independent annunciation. See the safety notice of the documentation (DOC-007).
anywidget_instruments_industrial.AlarmBanner ¶
Bases: InstrumentWidget
List of active alarms with timestamp, source, priority and message (SCADA-006).
value is the list of alarms that are not back to normal, each a dict
{"id", "timestamp", "source", "priority", "message", "state"}, sorted
by priority then time on the front end. Acknowledgements from the ACK
buttons call :meth:on_acknowledge callbacks with the alarm id (SCADA-007).
Warnings
Presents alarms; it is not an alarm management system nor a safety function. Critical alarms need independent annunciation. See the safety notice of the documentation (DOC-007).
raise_alarm ¶
raise_alarm(alarm_id: str, message: str = '', source: str = '', priority: str = 'high', timestamp: datetime | None = None) -> None
Activate an alarm (or re-activate a cleared one).
on_acknowledge ¶
on_acknowledge(callback: Callback) -> Callback
Register callback(event) called with event["alarm_id"].
anywidget_instruments_industrial.alarm_transition ¶
alarm_transition(state: str, event: str) -> str
ISA-18.2 alarm state after event (activate, clear, acknowledge).
Industrial operator objects¶
anywidget_instruments_industrial.AnalogIndicator ¶
Bases: NumericWidget
High-performance analog bar indicator (IND-001 .. IND-003, ISA-101).
The value is a pointer on a neutral grey scale. normal_lo and
normal_hi shade the normal operating range, alarm limits are marked on
the scale and target marks the desired value. Color appears only while
an alarm level is active, so that an abnormal situation stands out.
anywidget_instruments_industrial.SelectorSwitch ¶
Bases: InstrumentWidget
Rotary selector with 2 to 5 labelled positions (IND-010 .. IND-013).
value is the label of the selected position. With keyed=True and
locked=True the front end cannot move it (key switch); the kernel still
can. Positions listed in spring_return go back to default_position
when the operator releases the switch.
anywidget_instruments_industrial.StackLight ¶
Bases: InstrumentWidget
Signal tower with 1 to 5 tiers (IND-020 .. IND-022, IEC 60073 colors).
tiers lists the tier colors from top to bottom and labels their
meaning; value holds the state of each tier ("off", "on",
"blink"). buzzer shows a sounding indicator (no sound is played).
light = StackLight(tiers=["red", "amber", "green"], labels=["Fault", "Warning", "Run"]) light.set("green", "on")
set ¶
set(tier: int | str, state: str) -> None
Set a tier (index, or color of the first tier with that color) to state.
anywidget_instruments_industrial.PID ¶
Positional PID controller, standard (ISA) form (IND-033).
output = kp * (e + 1/ti * ∫e dt - td * d(pv)/dt)
action="reverse": the output rises when PV falls below SP (heating, level filled by an inlet valve);"direct": it rises when PV rises above SP (cooling).- The derivative acts on the measurement, so setpoint steps cause no kick.
ti=0disables the integral action; the integral term then acts as a fixed bias (manual reset).- Anti-windup: the integral term is clamped so that the output never
leaves
[out_min, out_max]. - Mode changes are bumpless (IND-034): in
MANthe controller tracks the manual output, andAUTO/CASresume from it.
pid = PID(kp=2.0, ti=10.0, sp=50.0) op = pid.step(pv=48.0, dt=0.1)
Warnings
For teaching, simulation and prototyping; a real process needs a validated controller and independent protection. See the safety notice of the documentation (DOC-007).
anywidget_instruments_industrial.PIDFaceplate ¶
Bases: InstrumentWidget
Operator faceplate of a control loop (IND-030 .. IND-034).
Shows the tag, the process value (PV), setpoint (SP) and output (OP) as
bars and values, and the mode. The operator may change SP in AUTO,
OP in MAN and neither in CAS (IND-031); entries are clamped and,
with confirm_delta, large changes need a confirmation (IND-032).
Attach a :class:PID as controller and call :meth:step with each
new measurement: the faceplate keeps the controller's setpoint, output
and mode in step with the operator's actions.
loop = PIDFaceplate(tag="TIC-101", unit="°C", pv_max=150, controller=PID(kp=2, ti=30)) op = loop.step(pv=72.4, dt=0.5)
Warnings
For teaching, simulation and prototyping; a real process needs a validated controller and independent protection. See the safety notice of the documentation (DOC-007).
step ¶
step(pv: float, dt: float) -> float
Record a new measurement and, with a controller, compute the output.
operator_set ¶
operator_set(field: str, value: Any, *, confirmed: bool = False) -> bool
Apply an operator entry with the faceplate rules (IND-031, IND-032).
Returns True when the entry was applied.
anywidget_instruments_industrial.Annunciator ¶
Bases: InstrumentWidget
Grid of alarm windows following an ISA-18.1 sequence (IND-040 .. IND-043).
windows lists (tag, text) pairs or dicts {"tag", "text",
"color"}; value holds the state of every window. Drive the process
side with :meth:set; the operator's Silence, Acknowledge, Reset and Test
buttons call :meth:silence, :meth:acknowledge, :meth:reset and set
test (lamp test), and :meth:on_action callbacks receive each action.
With first_out=True the first window to alarm is marked until reset
(IND-042). horn is True while an alert or ringback is not silenced;
the library never plays sound.
Warnings
Presents alarms; it is not an alarm management system nor a safety function. Critical alarms need independent annunciation. See the safety notice of the documentation (DOC-007).
add_window ¶
add_window(tag: str, text: str = '', color: str = 'amber') -> None
Add an alarm window (IND-040).
reset ¶
reset() -> None
Reset windows whose condition has cleared (sequences M and R) and the first-out mark.
on_action ¶
on_action(callback: Callback) -> Callback
Register callback(event); event["name"] is the operator action.
anywidget_instruments_industrial.annunciator_transition ¶
annunciator_transition(state: str, active: bool, event: str, sequence: str = 'A') -> str
ISA-18.1 window state after event (IND-041).
event is "process" (the process condition is now active),
"acknowledge" or "reset".
A(automatic reset): alert (fast flash) → acknowledged (steady) → normal as soon as the condition clears.M(manual reset): an acknowledged window stays lit after the condition clears, until the operator resets it.R(ringback): when an acknowledged condition clears, the window flashes slowly (ringback) until the operator resets it.
An alert is locked in: a condition that clears before acknowledgement keeps the window flashing until it is acknowledged.
anywidget_instruments_industrial.AlarmList ¶
Bases: InstrumentWidget
Alarm summary table (IND-050 .. IND-053).
value lists the alarms, each a dict {"id", "timestamp", "source",
"priority", "message", "state", "shelved_until", "suppressed",
"out_of_service"}. The front end sorts and filters them (by priority,
state and text) and offers ACK, Shelve and Unshelve actions.
Shelving hides an alarm for a limited time (shelve_durations lists the
choices, in seconds) and unshelves it automatically (IND-051). Expiry runs
on a timer thread; where threads are not available (Pyodide), it happens
on the next call to any method, or to :meth:refresh.
Warnings
Presents alarms; it is not an alarm management system nor a safety function. Critical alarms need independent annunciation. See the safety notice of the documentation (DOC-007).
on_event ¶
on_event(callback: Callback) -> Callback
Register callback(event) for operator actions (IND-053).
event["name"] is "acknowledge", "shelve" or "unshelve" and
event["alarm_id"] the alarm; shelving events carry "seconds".
raise_alarm ¶
raise_alarm(alarm_id: str, message: str = '', source: str = '', priority: str = 'high', timestamp: datetime | None = None) -> None
The alarm condition became active.
suppress ¶
suppress(alarm_id: str, suppressed: bool = True, *, message: str = '', source: str = '', priority: str = 'high') -> None
Suppressed by design (for example a unit shut down) (IND-052).
out_of_service ¶
out_of_service(alarm_id: str, oos: bool = True, *, message: str = '', source: str = '', priority: str = 'high') -> None
Out of service (for example an instrument under maintenance) (IND-052).
acknowledge ¶
acknowledge(alarm_id: str) -> bool
Acknowledge one alarm; returns True if its state changed.
shelve ¶
shelve(alarm_id: str, seconds: float) -> None
Shelve an alarm for seconds (at most max_shelve) (IND-051).
anywidget_instruments_industrial.StateMachine ¶
Bases: InstrumentWidget
Machine state model with operator commands (IND-060 .. IND-063).
value is the current state. The operator (or the kernel, with
:meth:command) issues commands; only those valid in the current state
are accepted and offered (IND-061). Acting states such as Starting
end when the kernel calls :meth:state_complete (IND-062).
machine is the model: ISA-TR88.00.02 (PackML) by default, one of the
names of :data:STATE_MODELS ("gemma" for GEMMA, IND-064; "isa88" for
the ISA-88 / IEC 61512-1 procedural states, IND-065), or a custom dict
{"states": [{"name", "x", "y", "acting", "title", "group"}],
"transitions": [[from, command, to], ...], "initial": name,
"global_commands": [...]} where the command "SC" marks the
completion of an acting state (IND-063). A state title is shown under
its name and states of the same group share a shaded zone; commands
of global_commands (valid from most states, such as Stop and Abort)
are summarized in a note instead of drawn as arrows (IND-066).
Warnings
Enforces a state model in software; it is not a safety function and does not replace the machine's control system. See the safety notice of the documentation (DOC-007).
path_to ¶
path_to(state: str) -> list[str] | None
Shortest sequence of commands ("SC" for a completion) leading to state.
[] when already there, None when state cannot be reached.
command ¶
command(command: str) -> bool
Apply command if it is valid in the current state; return True if applied.
state_complete ¶
state_complete() -> bool
End the current acting state (IND-062); return True if the state changed.
Trends, instruments and compact indicators¶
anywidget_instruments_industrial.TrendChart ¶
Bases: GraphWidget
Trend of one or more named pens against wall-clock time (IND-070 .. IND-075).
pens lists the pens as dicts: {"name", "unit", "min", "max",
"color", "lolo", "lo", "hi", "hihi", "setpoint", "format"}; only
name is required. Each pen has its own scale (min .. max);
the vertical axis shows the scale of the selected pen (click its legend
entry) and the other pens are drawn on their own scales. Alarm limits and
the setpoint are drawn as reference lines (IND-073).
Feed it with :meth:add or :meth:add_many; times are Unix timestamps
in seconds (time.time(), the default). In live mode the chart shows
the last span seconds; browsing the history (arrows, zoom) freezes the
view until the Live button is pressed (IND-072). Each pen keeps at most
history samples (IND-074).
trend = TrendChart(pens=[{"name": "LT-101", "unit": "m", "min": 0, "max": 4}]) trend.add("LT-101", 2.4)
add ¶
add(pen: str, value: Any, time: Any = None) -> None
Add samples to pen: a scalar or an array, at time (default: now).
time is a Unix timestamp in seconds, or an array of timestamps of
the same length as value.
add_many ¶
add_many(values: Mapping[str, Any], time: Any = None) -> None
Add one sample (or arrays) to several pens at once, e.g. {"LT-101": 2.4}.
data ¶
data(pen: str) -> tuple[np.ndarray, np.ndarray]
Buffered (times, values) of pen in chronological order.
anywidget_instruments_industrial.Transmitter ¶
Bases: NumericWidget
Field transmitter shown as an instrument bubble (IND-080 .. IND-083).
The bubble carries the tag (for example "LT-101": function letters
above the line, loop number below, in the manner of ISA-5.1); the measured
value and its unit are shown beside it. status is the device status:
"ok", "failure", "check" (function check), "out_of_spec"
or "maintenance" (maintenance required), the categories of NAMUR
NE 107, each shown by its own symbol and text as well as color (IND-081).
While the status is "failure" the value is marked invalid (IND-082).
Alarm limits (lo, hi ...) work as on the other numeric widgets.
lt = Transmitter(2.4, tag="LT-101", unit="m", max=4, hi=3.2) lt.status = "maintenance"
anywidget_instruments_industrial.EventLog ¶
Bases: InstrumentWidget
Chronological journal of events, newest first (IND-090 .. IND-093).
:meth:log appends an event with a timestamp, a source, a
category ("operator", "state", "alarm" or "system")
and a message; at most max_events are kept. The operator filters the
log by category and text and downloads it as CSV.
:meth:connect records every change of the named traits of another
widget, an audit trail of operator actions (IND-093)::
log = EventLog()
log.connect(setpoint_knob, category="operator")
log.log("Pump P-101 started", source="P-101", category="state")
Events are dicts {"id", "time", "source", "category", "message"},
time in Unix seconds.
log ¶
log(message: str, source: str = '', category: str = 'system', time: float | None = None) -> dict[str, Any]
Append an event (IND-091) and return it.
connect ¶
connect(widget: Any, names: str | Iterable[str] = 'value', category: str = 'operator', source: str | None = None) -> None
Record each change of the traits names of widget.
source defaults to the widget label (or tag, or class name).
anywidget_instruments_industrial.DeviationIndicator ¶
Bases: InstrumentWidget
Centre-zero bar of the deviation between a value and its setpoint (IND-100).
The bar runs from -span to +span around the setpoint; the band
±tolerance is shaded. Inside the tolerance the bar is grey; outside it
is drawn in the alarm color and labelled HIGH or LOW (ISA-101: color for
abnormal situations only).
dev = DeviationIndicator(52.3, setpoint=50, tolerance=1.5, span=5, unit="°C") dev.deviation, dev.out_of_tolerance (2.299999999999997, True)
anywidget_instruments_industrial.Sparkline ¶
Bases: _HistoryMixin, InstrumentWidget
Compact trend of the last history values, without axes (IND-101).
Shows the last value and marks the minimum (hollow dot) and the maximum
(filled dot) of the kept values. Feed it with :meth:append; values
travel as binary float32 buffers.
spark = Sparkline(history=60, unit="m", format="%.2f") spark.append(2.31)
anywidget_instruments_industrial.BarGraph ¶
Bases: InstrumentWidget
Group of aligned bars on a shared scale (IND-102, ISA-101).
bars describes each bar: {"label", "normal_lo", "normal_hi",
"lolo", "lo", "hi", "hihi"} (only label is required); value
holds one value per bar. Bars are grey, with the normal band shaded and
the limits marked; a bar in alarm is drawn in the alarm color and
labelled with its level. alarm_levels gives the level of each bar.
zones = BarGraph(bars=["Z1", "Z2", {"label": "Z3", "hi": 80}], unit="°C", max=100) zones.value = [62.0, 64.5, 83.1] zones.alarm_levels ['normal', 'normal', 'hi']
anywidget_instruments_industrial.KPITile ¶
Bases: _HistoryMixin, InstrumentWidget
Key performance indicator tile (IND-103).
Shows value with its unit, the target and the difference to
the target with its direction (▲ / ▼) and whether it is on the good side
(higher_is_better). With show_sparkline the last history
values appended with :meth:append are drawn as a sparkline.
tile = KPITile(oee(0.9, 0.95, 0.99) * 100, unit="%", target=85, label="OEE")
anywidget_instruments_industrial.oee ¶
oee(availability: float, performance: float, quality: float) -> float
Overall equipment effectiveness: availability * performance * quality.
Each factor is a fraction between 0 and 1 (in the manner of ISO 22400); the result is a fraction too (multiply by 100 for percent).
round(oee(0.9, 0.95, 0.99), 4) 0.8465
anywidget_instruments_industrial.NumericEntry ¶
Bases: NumericWidget
Numeric keypad with a display, for touch panels (IND-104).
The operator types a value on the keys (or the keyboard): Enter commits
it after the range check of the numeric widgets (NUM-010), Escape
discards it. Where confirm_delta is set, a change larger than
confirm_delta asks for a confirmation (a second Enter). The kernel
rejects values outside min .. max as for every numeric control.
sp = NumericEntry(2.2, min=0, max=4, unit="m", label="Level setpoint")
Registers, recipes and plant structure¶
anywidget_instruments_industrial.BitField ¶
Bases: InstrumentWidget
A status or fault word shown as a row of indicators, one per bit (IND-111).
value is the word, an integer in [0, 2**bits); bit 0 is the least
significant bit. labels[k] names bit k (bits without a label are
shown dimmed) and colors[k] gives its on color (default on_color).
The bits are drawn most significant first, as a register is written, unless
msb_first is False; the word is also shown in hexadecimal.
In control mode, clicking a bit (or Space / Enter on it) toggles that bit and sends the new word (IND-112).
status = BitField(0x0013, bits=8, labels=["Ready", "Running", "", "", "Fault"]) status.bit(4) True status.active_labels() ['Ready', 'Running', 'Fault']
anywidget_instruments_industrial.RecipeTable ¶
Bases: InstrumentWidget
A table of typed columns whose rows the operator edits (IND-113, IND-114).
columns describes the columns: {"name", "title", "type", "unit",
"min", "max", "step", "format", "choices", "readonly", "default"} with
type one of "number" (unit, limits, step, display format),
"choice" (one of choices), "bool" or "text"; only name
is required, and a string is a number column of that name. value is
the list of rows, each a dict keyed by column name.
In control mode the operator edits the cells: each edit is checked
against its column (the numeric rules of NUM-010) in the front end and
again here; a rejected edit leaves the row unchanged and shows the reason.
With row_edit the operator can also add and delete rows (at most
max_rows). Clicking a column title sorts the displayed rows (IND-114);
value keeps its order.
Examples:
>>> recipe = RecipeTable(
... columns=[{"name": "step", "type": "text"},
... {"name": "temp", "title": "Temperature", "unit": "°C", "min": 20, "max": 90},
... {"name": "agitator", "type": "choice", "choices": ["off", "slow", "fast"]}],
... value=[{"step": "Heat", "temp": 65, "agitator": "slow"}])
>>> recipe.set_cell(0, "temp", 70)
>>> recipe.value[0]["temp"]
70.0
set_cell ¶
set_cell(row: int, column: str, value: Any) -> None
Set one cell, checked against its column (ValueError if invalid).
add_row ¶
add_row(row: Mapping[str, Any] | None = None) -> int
Append a row (missing cells get their column default); returns its index.
on_edit ¶
on_edit(callback: Callback) -> Callback
Register callback(event) for operator edits.
event: {"action": "edit" | "add" | "delete", "row", "column", "value"}.
anywidget_instruments_industrial.XYGraph ¶
Bases: GraphWidget
Data sets of (x, y) pairs with arbitrary spacing (IND-115).
Characteristic curves (pump, valve, I-V), scatter plots, Lissajous
figures, measurements at irregular points. Each data set is drawn as a
"line", "markers", "both", "step" (a value held until the
next x) or "bar" (bars from y = 0), with its color and line width.
The axes follow the data unless x_min / x_max / y_min /
y_max are set. The pairs travel as float64 binary buffers.
Cursors (CHART-104) read the value of every data set at their x, by linear interpolation between its points sorted by x.
Examples:
>>> import numpy as np
>>> g = XYGraph(x_unit="m³/h", unit="m", label="Pump P-101")
>>> q = np.linspace(0, 120, 13)
>>> g.plot(q, 42 - 0.002 * q**2, name="Head")
0
>>> g.plot([30, 60, 90], [40.5, 35.0, 26.3], name="Measured", style="markers")
1
>>> round(g.values_at(60)[0], 1)
34.8
plot ¶
plot(x: Any, y: Any, name: str = '', color: str = '', style: str = 'line', width: float = 1.5, replace: bool = True) -> int
Add a data set, or replace the one of the same name; returns its index.
anywidget_instruments_industrial.EquipmentTree ¶
Bases: InstrumentWidget
A hierarchy of equipment with a status per node (IND-119).
nodes is a list of nested dicts {"label", "id", "level", "status",
"children"}: a plant model such as enterprise / site / area / unit /
equipment module (IEC 62264, IEC 61512), or any other hierarchy. Only
label is required; a node without id gets the path of labels from
the root. level is shown next to the label; status is one of
:data:NODE_STATUSES and is shown as a symbol and a word, not only a
color. A collapsed node also shows the most severe status below it.
The operator expands and collapses nodes (expanded, the ids of the
open nodes) and selects one (value, its id, "" for none), with the
mouse or the keyboard (arrows, Home, End, Enter). Observe value with
:meth:on_change to follow the selection.
Examples:
>>> tree = EquipmentTree(
... nodes=[
... {"label": "Plant", "level": "site", "children": [
... {"label": "Mixing", "level": "area", "children": [
... {"label": "Mixer M-101", "level": "unit", "status": "running"},
... {"label": "Pump P-102", "level": "equipment", "status": "alarm"},
... ]},
... ]},
... ],
... )
>>> tree.rollup("Plant")
'alarm'
>>> tree.select("Plant/Mixing/Pump P-102")
>>> tree.expanded
['Plant', 'Plant/Mixing']
SVG faceplates¶
anywidget_instruments_industrial.SvgPanel ¶
Bases: InstrumentWidget
A front panel drawn in a vector editor, animated from Python (IND-120 .. IND-126).
svg is an SVG document, sanitized like skins (no scripts, no external
resources). Elements whose label (the object label of a vector editor,
stored as inkscape:label) or data-awi attribute reads
awi:<role>=<name> followed by ;<option>=<value> pairs are bound to
value[<name>]; other elements are decoration (IND-121).
Indicator roles (IND-122): text (format, unit), rotate
(min, max, from, to in degrees, pivot cx, cy or
the rotation center set in the editor, else the element center),
scale (min, max, edge: the edge that stays in place),
show (eq: shown when the value equals it, else when true),
state (shows the child whose case name equals the value),
color (on, off, eq).
Control roles, in control mode (IND-123): button (toggles a Boolean),
momentary (true while pressed), set (value: writes it),
step (step, min, max: one step up with a click or the
arrow keys, down with Shift+click); each step value also gets an
entry field (IND-124). The kernel refuses a step value outside its
limits, as for numeric widgets (NUM-010).
problems lists the elements with an unknown role or an invalid option
(IND-125). :meth:template loads a drawing shipped with the package
(IND-126).
Examples:
>>> svg = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 60">
... <text x="10" y="30" data-awi="awi:text=vout;format=%.2f;unit=V">0</text>
... <circle cx="80" cy="30" r="10" data-awi="awi:button=run"/>
... </svg>'''
>>> panel = SvgPanel(svg, label="Power supply")
>>> panel["vout"] = 12.0
>>> panel.names()
['run', 'vout']
Utilities¶
anywidget_instruments_industrial.sanitize_svg ¶
sanitize_svg(source: str) -> str
Return a sanitized copy of the SVG document source.
Raises ValueError if source is not well-formed SVG.