---
file_format: mystnb
kernelspec:
  name: python3
mystnb:
  execution_in_temp: true
---

# Quantities, property sets, sensors, and actuators

Attach physical quantities, reusable property schemas, sensors, and actuators
to equipment, ports, named points, and connection handles. For a narrative
walk-through, see
[Add measurements, sensors, and controls](../tutorials/instrument-and-measure.md).

```{code-cell} python3
from plumb import Model, PropertySchema, connect, flowsheet, quantity_field
from plumb.qudt import QuantityAmount as Q, quantity_kinds, units
from plumb.watr import LevelSensor, Property, Pump, Tank, enums
from plumb.watr.drinking_water import (
    ChlorinationStage,
    CoagulationStage,
    RapidSandFiltrationStage,
)

values = enums.values
with Model("urn:example:measure#") as model:
    intake = Pump("intake-pump")
    coagulation = CoagulationStage("coagulation")
    sand_filter = RapidSandFiltrationStage("sand-filter")
    chlorination = ChlorinationStage("chlorine-contact")
    clearwell = Tank("clearwell")
    high_service = Pump("high-service-pump")

raw_water = connect(intake, coagulation.inlet, name="raw-water")
connect(coagulation.outlet, sand_filter.inlet, name="coagulated-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")
```

## Attach a single quantity

Call `.quantity()` on equipment, a port, a named point, or a connection
handle. Units and quantity kinds come from `plumb.qudt` and are checked for
dimensional compatibility immediately:

```{code-cell} python3
volume = clearwell.quantity(
    "clearwell-volume",
    5_000,
    unit=units.M3,
    kind=quantity_kinds.Volume,
    has_aspect=[values.Aspect_Nominal],
)
toc = raw_water.quantity(
    "raw-organic-carbon",
    3.5,
    unit=units.MilliGM_PER_L,
    kind=quantity_kinds.MassConcentration,
    of_medium=values.Water_Freshwater,
    of_substance=values.Constituent_OrganicCarbon,
)
volume.has_value, toc.of_medium, toc.of_substance
```

Pass `capability=` to pick the S223 property class:

| `capability=` | S223 class | Typical use |
| --- | --- | --- |
| `"static"` (default) | `QuantifiableProperty` | Fixed design value |
| `"observable"` | `QuantifiableObservableProperty` | Measured value (`.sensor()` creates one automatically) |
| `"actuatable"` | `QuantifiableActuatableProperty` | Writable setpoint (`.actuator()` creates one automatically) |

### How `of_medium` interacts with connection resolution

ASHRAE 223P requires a property's `of_medium` to be compatible with the
medium of the pipe, port, or equipment it describes:

- If you **omit** `of_medium`, resolution copies the host's resolved medium
  onto the property automatically.
- If you **specify** `of_medium`, the solver enforces compatibility and
  reports an unsatisfiable conflict if the stream carries an incompatible
  medium (for example, `Fluid_Air` on a water pipe).

### When no QUDT quantity kind fits

Use a plain S223 `Property` with a literal value and attach it to
`has_property`:

```{code-cell} python3
permeability = Property(
    "water-permeability",
    label="Water permeability coefficient [m/(Pa·s)]",
    has_value=4.2e-12,
    has_aspect=[values.Aspect_Nominal],
    model=model,
)
coagulation.has_property.add(permeability)
```

> **Scope note:** S223 and WaTr model one nominal, untimed value per
> property. Distinguishing multiple operating scenarios or time-series
> samples requires a companion ontology.

## Define and apply a reusable property set

Subclass `PropertySchema` and declare fields with `quantity_field()` to
bundle quantities with defaults, bounds, and unit validation into a frozen,
keyword-only dataclass:

```{code-cell} python3
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,
    )
    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,
    )


influent = raw_water.apply_properties(
    InfluentQuality(flow_rate=40_000, turbidity=Q(18.0, units.NTU))
)
dict(influent)
```

- Bare numbers take the field's default unit; `QuantityAmount` (`Q(...)`)
  keeps its own compatible unit without conversion.
- Properties are named `<subject>-<field>` (override with `prefix=`). If any
  name collides, `apply_properties()` rolls back atomically.
- Compiled domain packages (such as `plumb.watr.asm2d.AerobicDesign`) use
  the exact same `apply_properties()` and `.describe()` API. Move a Python
  schema to SHACL when other tools or models need to share it — see
  [Write and compile a domain package](create-a-domain-package.md).

## Add sensors and actuators

### Sensors

Call `.sensor()` on the equipment, named point, port, or connection handle
being observed. Plumb creates an observable `<name>-value` property and
selects the most specific sensor class for the quantity kind (`FlowSensor`,
`TurbidityMeter`, `ConcentrationSensor`, `TemperatureSensor`,
`PressureSensor`, `ConductivitySensor`, and so on):

```{code-cell} python3
# Automatic sensor class selection on a named point and a connection handle
turbidimeter = sand_filter.filtered_water.sensor(
    "filter-effluent-turbidity", kind=quantity_kinds.Turbidity, unit=units.NTU
)
analyzer = finished.sensor(
    "chlorine-residual",
    kind=quantity_kinds.MassConcentration,
    unit=units.MilliGM_PER_L,
    of_substance=values.Constituent_ChlorineResidual,
)

# Explicit sensor_class= when the kind has no unique sensor subclass
level = clearwell.sensor(
    "clearwell-level",
    kind=quantity_kinds.Length,
    unit=units.M,
    sensor_class=LevelSensor,
)

# Enumerated (non-numeric) status observation
running = high_service.sensor("high-service-running", kind=values.Binary_OnOff)

turbidimeter, analyzer, level, running.observes
```

When attached to a connection handle or port, `has_observation_location`
automatically updates to the concrete pipe or point when the model resolves.

### Actuators

Call `.actuator()` on a piece of equipment to create an actuatable
`<name>-command` property and an `Actuator` linked via `actuates` and
`actuated_by_property`. Both numeric setpoints and discrete enumeration
commands work:

```{code-cell} python3
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)
```

### Building a sensor manually

`.sensor()` is shorthand for creating the observable property and linking
the sensor directly. Both `has_observation_location` and
`has_reference_location` accept deferred handles, ports, and named points:

```python
from plumb.watr import TurbidityMeter

reading = finished.quantity(
    "finished-turbidity-value",
    0.1,
    unit=units.NTU,
    kind=quantity_kinds.Turbidity,
    capability="observable",
)
TurbidityMeter(
    "finished-turbidity",
    has_observation_location=finished,
    observes=reading,
)
```

Compile and draw to verify all properties and instruments land cleanly:

```{code-cell} python3
resolved = model.compile()
flowsheet(resolved, title="Instrumented plant")
```
