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

# Build equipment, connections, and layouts

This guide is a task-oriented reference for authoring equipment, attributes,
flow connections, spaces, systems, and assemblies. If you are new to Plumb,
start with [Build your first plant model](../tutorials/first-model.md).

## Create objects and set attributes

Objects created inside `with model:` join that `Model` automatically.
Omitted names are numbered per class (`pump_1`, `pump_2`, ...), and objects
created outside a `with` block accept `model=`:

```{code-cell} python3
from plumb import Model
from plumb.watr import DomainSpace, Pump, Tank, enums

model = Model("urn:example:build#")
with model:
    intake = Pump("intake-pump")
    spare = Pump()
clearwell = Tank("clearwell", model=model)

intake.name, spare.name, clearwell.meta.instance_iri
```

Every object exposes `name`, `type`, `label`, and `comment`. Ontology
properties follow two rules:

- **Required properties** (`sh:minCount >= 1`) are required keyword
  arguments, unless the class fixes a default value.
- **Single-valued properties** (`sh:maxCount 1`) are plain attributes;
  **multi-valued properties** are live set-like collections with `add()`,
  `remove()`, and `clear()` (assignment takes an iterable). Both validate
  ranges and keep inverse relations in sync immediately.

```{code-cell} python3
clearwell.label = "Clearwell"
clearwell.has_role.add(enums.values.Role_Storage)

try:
    DomainSpace("zone", model=model)
except TypeError as error:
    print("missing required argument:", error)
```

An ontology property whose name collides with the `Entity` API (such as
`contains`, `walk`, `sensor`, or `actuator`) gets a trailing underscore
(e.g. `contains_`).

## Set WaTr processes, objectives, and roles

In WaTr, a unit records what it does (`has_process`), what it is for
(`has_treatment_objective`), and its role in the plant (`has_role`).

- **Processes and objectives** are ontology classes passed directly as
  values. When an equipment class implies a default (like `GravityThickener`
  settling to thicken), the constructor fills it in.
- Supplying a more specific subclass replaces the default rather than
  duplicating it.
- **Roles** are enum values from `enums.values`.

```{code-cell} python3
from plumb.watr import (
    GravityThickener,
    MediaFiltrationUnit,
    Process_RapidSandFiltration,
    SedimentationTank,
    TreatmentObjective_Clarification,
)

with model:
    thickener = GravityThickener("thickener", has_role=[enums.values.Role_Primary])
    clarifier = SedimentationTank(
        "clarifier", has_treatment_objective=[TreatmentObjective_Clarification]
    )
    sand_filter = MediaFiltrationUnit(
        "sand-filter", has_process=[Process_RapidSandFiltration]
    )

print("thickener defaults:", list(thickener.has_process), list(thickener.has_treatment_objective))
print("narrowed filter:", list(sand_filter.has_process))
```

## Inspect a class's port requirements

Before connecting an unfamiliar equipment class, call `describe_ports()` to
see its SHACL port contract — the directions (`"in"`, `"out"`, `"bi"`),
counts, allowed media, and any named points:

```{code-cell} python3
from plumb.watr.drinking_water import ClarificationStage

print(Pump.describe_ports())
print()
print(ClarificationStage.describe_ports())
```

The same data is available programmatically on `cls.meta.port_contract`.

## Connect equipment and disambiguate

`connect(source, target)` records a flow intention and returns a
`ConnectionHandle`. (`a >> b` records the same intention and returns `b` for
chaining.) Call `model.check()` to verify whether the solver finds one unique
interpretation:

- **`complete`**: one unique assignment exists (`report.complete` is `True`).
- **`underconstrained`**: several valid assignments remain — add a hint.
- **`unsatisfiable`**: constraints contradict — `report.issues` lists the
  conflicting authored facts.

```{code-cell} python3
from plumb import connect
from plumb.watr.drinking_water import RapidSandFiltrationStage

values = enums.values
with Model("urn:example:residuals#") as residuals:
    stage_clarifier = ClarificationStage("clarifier")
    stage_filter = RapidSandFiltrationStage("sand-filter")
    sludge_pump = Pump("sludge-pump")
    sludge_thickener = GravityThickener("thickener")

sludge = connect(stage_clarifier, sludge_pump, name="sludge-draw")
print("before hint:", residuals.check().status)

sludge.medium = values.Fluid_Sludge
connect(sludge_pump, sludge_thickener, name="sludge-to-thickener")
connect(stage_clarifier.clarified_water, stage_filter.inlet, name="clarified-water")
print("after hints:", residuals.check().status)
```

Ways to guide the solver when a model is underconstrained:

| Hint | Example |
| --- | --- |
| Medium on the connection | `connect(a, b, medium=values.Fluid_Sludge)` or `handle.medium = ...` |
| Named point from a domain class | `connect(clarifier.clarified_water, sand_filter.inlet)` |
| Explicit custom port | `equipment.port("dosing", direction="in", medium=...)` |
| Specific connection class | `connect(a, b, connection=Pipe)` or `handle.connection_class = Pipe` |
| Fresh port on bare equipment | `connect(source, mixer, ports="new")` |

Note that `Tank(..., medium=[...])` sets `s223:hasMedium` on the tank itself
and does *not* constrain its connections; put `medium=` on the connection or
port instead.

## Edit connection handles and pair ports

A `ConnectionHandle`'s identity fields — `source`, `target`, `name`, and
`identifier` — are **read-only** after `connect()`. All descriptive fields
(`medium`, `connection_class`, `label`, `comment`, and generated connection
properties such as `has_role`) can be edited directly or with
`handle.assign(...)`:

```{code-cell} python3
sludge.label = "Clarifier sludge draw"
sludge.has_role.add(values.Role_Primary)

resolved = residuals.resolve()
resolved.explain(sludge)
```

When two ports carry the same stream *through* a device (such as one side of
a heat or pressure exchanger), pair them with `.pair()` so they share one
medium and record `s223:pairedConnectionPoint`:

```python
feed_in = exchanger.port("feed-in", direction="in")
feed_out = exchanger.port("feed-out", direction="out")
feed_in.pair(feed_out)
```

Custom ports created with `.port()` also expose editable `.label`, `.medium`,
`.maps_to`, and `.roles` — and resolve even when not connected to another
piece of equipment.

## Group into spaces, systems, and assemblies

- **Spaces** (`PhysicalSpace`, `DomainSpace`): open a space with `with` (or
  call `space.contains(child)`). Equipment receives `has_physical_location`;
  nested spaces use `contains_`. Pass `via="property_name"` to pick a
  predicate explicitly when more than one applies.
- **Systems** (`model.system(name)`): collect equipment created in a `with`
  block into an S223 `System`. Connections crossing into or out of the system
  automatically add boundary points on resolution, and `system.boundary(...)`
  marks unconnected feed/product terminals explicitly.
- **Equipment inside equipment**: nest `with` blocks and link internal
  points to outer container ports with `maps_to`.

```{code-cell} python3
from plumb.s223 import AirHandlingUnit, Chiller, PhysicalSpace
from plumb.s223.hvac import AirWaterCoolingCoil

with Model("urn:example:layout#") as layout:
    with PhysicalSpace("mech-room") as room:
        with AirHandlingUnit("ahu") as ahu:
            coil = AirWaterCoolingCoil("cooling-coil")
        chiller = Chiller("chiller")

chw_in = ahu.port("chw-in", direction="in")
chw_out = ahu.port("chw-out", direction="out")
coil.water_inlet.maps_to = chw_in
coil.water_outlet.maps_to = chw_out
connect(chiller, chw_in, name="chw-supply")
connect(chw_out, chiller, name="chw-return")

snap = layout.resolve()
snap["chw-in"].medium, snap["chiller"].find_all_next(descend=True)
```

See [Model a building HVAC system (S223)](../tutorials/building-air-and-water.md)
for a complete walk-through of `maps_to` and descending walks.
