Add measurements, sensors, and controls#
In Build your first plant model you modeled equipment and connectivity. Real plants also have design parameters (tank volumes, raw water quality), instruments measuring streams (turbidity meters, flow meters), and actuators controlling pumps and valves.
In this tutorial you will extend the drinking-water plant by:
attaching physical quantities with dimension-checked units,
grouping repeated measurements into a reusable property schema,
using a pre-compiled schema from a domain package, and
adding sensors and actuators and drawing them on a flow sheet.
1. Set up the plant#
Let’s start with the five treatment stages from Tutorial 1, plus an intake pump, a clearwell, a high-service pump, sludge thickening, and filter backwash.
from plumb import Model, connect, flowsheet
from plumb.watr import GravityThickener, LevelSensor, Pump, Tank, enums
from plumb.watr.drinking_water import (
ChlorinationStage,
ClarificationStage,
CoagulationStage,
FlocculationStage,
RapidSandFiltrationStage,
)
values = enums.values
with Model("urn:example:surface-water#") as model:
with model.system("plant") as plant:
intake = Pump("raw-water-pump")
coagulation = CoagulationStage("coagulation")
flocculation = FlocculationStage("flocculation")
clarifier = ClarificationStage("clarifier")
sand_filter = RapidSandFiltrationStage("sand-filter")
chlorination = ChlorinationStage("chlorine-contact")
clearwell = Tank("clearwell", has_role=[values.Role_Storage])
high_service = Pump("high-service-pump")
sludge_pump = Pump("sludge-pump")
thickener = GravityThickener("thickener")
backwash_pump = Pump("backwash-pump")
backwash_tank = Tank("backwash-recovery", has_role=[values.Role_Backwash])
# Main drinking-water train
raw_water = connect(intake, coagulation.inlet, name="raw-water")
connect(coagulation.outlet, flocculation.inlet, name="coagulated-water")
connect(flocculation.outlet, clarifier.inlet, name="flocculated-water")
connect(clarifier.clarified_water, sand_filter.inlet, name="clarified-water")
connect(sand_filter.filtered_water, chlorination.inlet, name="filtered-water")
connect(chlorination.outlet, clearwell, name="disinfected-water")
finished = connect(clearwell, high_service, name="finished-water")
# Sludge and backwash branches
connect(clarifier.sludge, sludge_pump, name="sludge-draw", medium=values.Fluid_Sludge)
connect(sludge_pump, thickener, name="sludge-to-thickener", medium=values.Fluid_Sludge)
connect(clearwell, backwash_pump, name="backwash-draw")
connect(backwash_pump, sand_filter.backwash_supply, name="backwash-supply")
connect(sand_filter.backwash_waste, backwash_tank, name="spent-backwash")
# Custom ports where the plant connects to the outside world
plant.boundary(
intake.port("raw-water-suction", direction="in"),
high_service.port("distribution", direction="out"),
thickener.port("thickened-sludge", direction="out", medium=values.Fluid_Sludge),
thickener.port("thickener-supernatant", direction="out", medium=values.Fluid_Water),
)
model.check().status
'complete'
Notice intake.port("raw-water-suction", direction="in"): calling .port()
declares a custom connection point with a stable name when you want a port
that the ontology shapes do not define on their own.
2. Attach a single physical quantity#
In Plumb, physical measurements use QUDT — a standard catalog of
quantity kinds (what is measured, such as Volume or Turbidity) and
units (how it is measured, such as M3 or NTU), imported from
plumb.qudt.
Call .quantity() on any piece of equipment, port, or connection handle to
attach one value. Let’s record the nominal volume of the clearwell:
from plumb.qudt import QuantityAmount as Q, quantity_kinds, units
volume = clearwell.quantity(
"clearwell-volume",
5_000,
unit=units.M3,
kind=quantity_kinds.Volume,
has_aspect=[values.Aspect_Nominal],
)
volume, volume.has_value, volume.has_unit
(<QuantifiableProperty 'clearwell-volume'>, 5000.0, <term M3>)
has_aspect=[values.Aspect_Nominal] marks this as a design/nominal value
rather than a live reading.
Because every QUDT unit and quantity kind carries its physical dimensions, Plumb catches unit mismatches immediately:
try:
clearwell.quantity("bad-volume", 5, unit=units.KiloGM, kind=quantity_kinds.Volume)
except ValueError as error:
print(error)
bad-volume: unit and quantity kind are incompatible
3. Group repeated quantities into a property schema#
Calling .quantity() once works well for a single tank volume. But raw
water entering a plant is described by a whole bundle of measurements — flow
rate, turbidity, organic carbon, and temperature — often reused across many
streams or scenarios.
A PropertySchema lets you define that bundle once as a typed Python
class. Each field uses quantity_field() to declare its quantity kind,
default unit, medium, optional bounds, and optional default value:
from plumb import PropertySchema, quantity_field
class InfluentQuality(PropertySchema):
"""Raw surface-water quality at the plant intake."""
flow_rate: float | Q = quantity_field(
kind=quantity_kinds.VolumeFlowRate,
unit=units.M3_PER_DAY,
label="Raw-water flow",
of_medium=values.Water_Freshwater,
aspects=(values.Aspect_Nominal,),
minimum=0,
)
turbidity: float | Q = quantity_field(
kind=quantity_kinds.Turbidity,
unit=units.NTU,
label="Raw-water turbidity",
of_medium=values.Water_Freshwater,
aspects=(values.Aspect_Nominal,),
minimum=0,
)
organic_carbon: float | Q = quantity_field(
kind=quantity_kinds.MassConcentration,
unit=units.MilliGM_PER_L,
label="Total organic carbon",
of_medium=values.Water_Freshwater,
of_substance=values.Constituent_OrganicCarbon,
aspects=(values.Aspect_Nominal,),
minimum=0,
)
temperature: float | Q = quantity_field(
kind=quantity_kinds.Temperature,
unit=units.DEG_C,
label="Raw-water temperature",
of_medium=values.Water_Freshwater,
aspects=(values.Aspect_Nominal,),
default=12.0,
)
When you instantiate InfluentQuality, bare numbers take the field’s
default unit, omitted fields take their default, and Q(value, unit) lets
you pass an explicit compatible unit without converting it. Bounds and units
are validated right away:
raw = InfluentQuality(
flow_rate=40_000, turbidity=Q(18.0, units.NTU), organic_carbon=3.5
)
raw
InfluentQuality(flow_rate=40000, turbidity=QuantityAmount(value=18.0, unit=<term NTU>), organic_carbon=3.5, temperature=12.0)
Now attach all four properties to the raw_water pipe in one atomic call
with apply_properties():
influent = raw_water.apply_properties(raw)
dict(influent)
{'flow_rate': <QuantifiableProperty 'raw-water-flow-rate'>,
'turbidity': <QuantifiableProperty 'raw-water-turbidity'>,
'organic_carbon': <QuantifiableProperty 'raw-water-organic-carbon'>,
'temperature': <QuantifiableProperty 'raw-water-temperature'>}
Each field becomes a separate S223 property attached to the stream, keeping
its unit, medium (Water_Freshwater), and substance (Constituent_OrganicCarbon):
influent["organic_carbon"].has_value, influent["organic_carbon"].of_substance
(3.5, <enum Constituent-OrganicCarbon>)
4. Reuse schemas compiled from a domain package#
Writing a PropertySchema in Python is great inside a single script. When a
whole team or multiple tools share the same equipment and property sets,
they can be compiled from SHACL into a domain package (such as
plumb.watr.asm2d for activated-sludge wastewater reactors).
You use a compiled schema the exact same way — and .describe() prints its
fields, units, defaults, and provenance:
from plumb.watr.asm2d import AerobicDesign, AerobicStage, OxygenOutletState
print(AerobicDesign.describe())
Aerobic basin volume in m³ (default 1333) and oxygen transfer coefficient KLa in h⁻¹.
volume: Volume [Cubic Meter; http://qudt.org/vocab/unit/M3] default=1333.0 — https://watermetadata.org/plumb/asm2d#AerobicVolumeShape
aspects=Nominal; property_class=QuantifiableProperty
oxygen_transfer_coefficient: frequency [Reciprocal Hour; http://qudt.org/vocab/unit/PER-HR] required — https://watermetadata.org/plumb/asm2d#OxygenTransferCoefficientShape
aspects=Nominal; property_class=QuantifiableProperty
Apply one design object across two stages — each stage receives its own independent properties:
with Model("urn:example:two-stages#") as reactors:
first = AerobicStage("first")
second = AerobicStage("second")
design = AerobicDesign(oxygen_transfer_coefficient=Q(10.0, units.PER_HR))
first.apply_properties(design)
second.apply_properties(design)
# You can apply schemas to named ports too:
oxygen = OxygenOutletState(oxygen_concentration=Q(2.0, units.GM_PER_M3))
first.outlet.apply_properties(oxygen)
reactors["first-volume"].has_value, reactors["second-volume"].has_value
(1333.0, 1333.0)
5. Add sensors and actuators#
So far every property has been a static design value. To model live instrumentation and control, Plumb distinguishes two more kinds of properties:
Sensors observe an observable property. Calling
.sensor()on a piece of equipment, a named port, or a connection handle creates both the observable property (<name>-value) and the most specific sensor class for that quantity kind (such asFlowSensor,TurbidityMeter, orConcentrationSensor).Actuators command an actuatable property. Calling
.actuator()on a piece of equipment creates both the command property (<name>-command) and anActuatorlinked to the equipment.
Let’s instrument our surface-water plant:
# Flow meter on the raw-water pipe -> FlowSensor
raw_water.sensor(
"raw-water-flow", kind=quantity_kinds.VolumeFlowRate, unit=units.M3_PER_DAY
)
# Turbidimeter on the sand filter's filtered-water port -> TurbidityMeter
sand_filter.filtered_water.sensor(
"filter-effluent-turbidity", kind=quantity_kinds.Turbidity, unit=units.NTU
)
# Chlorine analyzer on the finished-water pipe -> ConcentrationSensor
finished.sensor(
"chlorine-residual",
kind=quantity_kinds.MassConcentration,
unit=units.MilliGM_PER_L,
of_substance=values.Constituent_ChlorineResidual,
)
# Level sensor on the clearwell: Length has no unique sensor class, so name it
clearwell.sensor(
"clearwell-level",
kind=quantity_kinds.Length,
unit=units.M,
sensor_class=LevelSensor,
)
<LevelSensor 'clearwell-level'>
You can also add actuators for both numeric setpoints (a frequency command) and discrete states (an on/off enumeration command):
high_service.actuator(
"high-service-speed", kind=quantity_kinds.Frequency, unit=units.HZ
)
high_service.actuator(
"high-service-start", kind=values.Binary_OnOff, value=values.OnOff_Off
)
list(high_service.actuated_by_property)
[<QuantifiableActuatableProperty 'high-service-speed-command'>,
<EnumeratedActuatableProperty 'high-service-start-command'>]
6. Compile and draw the instrumented plant#
Now resolve and validate the entire plant:
resolved = model.compile()
When we attached the chlorine analyzer to the finished connection handle,
no pipe existed yet. Inside the resolved snapshot, Plumb has placed the
sensor directly on the concrete pipe, and its observed property has
inherited the pipe’s resolved medium (Fluid-Water):
analyzer = resolved["chlorine-residual"]
analyzer.has_observation_location, analyzer.observes.of_medium
(<Pipe 'finished-water'>, <enum Fluid-Water>)
Draw the result. Sensors appear as ISA-style instrument bubbles (FT, AT,
LT) beside the stream or tank they observe, and actuators appear as dashed
ZC boxes beside the pump they command:
flowsheet(resolved, title="Instrumented surface-water treatment plant")
What you learned#
QUDT supplies dimension-checked
quantity_kindsandunits;.quantity()attaches one value to equipment, a port, or a connection.PropertySchema+quantity_field()group repeated quantities with defaults, bounds, andQuantityAmount(Q(...));apply_properties()attaches them atomically..sensor()creates an observable property and picks the right sensor class;.actuator()creates a command property and anActuator.
Next#
In Model a building HVAC system (S223), you
will use the same API on an ASHRAE 223P building system with rooms,
equipment inside equipment, and mapped ports (maps_to).