---
file_format: mystnb
kernelspec:
  name: python3
---

# Model a building HVAC system (S223)

Plumb uses the exact same API for building systems modeled with **ASHRAE
223P** (`plumb.s223`).

This tutorial builds a realistic air-handling unit (AHU) that brings air
across a damper, a chilled-water cooling coil, and a supply fan — served by
an external chiller and feeding a downstream zone damper. Along the way you
will learn two concepts that come up whenever equipment lives inside spaces
or larger assemblies:

- **containment** (`with` blocks) — placing equipment in rooms and parts
  inside assemblies, and
- **port mapping (`maps_to`)** — linking an outer assembly's ports to the
  internal parts behind them so flow walks can cross or enter the assembly.

## 1. Place equipment inside a room and an AHU

Opening an object with Python's `with` statement makes it the active
**container**. Everything created inside that block attaches to the
container using the ontology's containment rule for that pair of classes:

- equipment inside a `PhysicalSpace` gets `has_physical_location`, and
- equipment inside another piece of equipment gets `contains_` (the
  trailing underscore avoids colliding with the `.contains()` helper).

Let's place an `AirHandlingUnit` and a `Chiller` inside a mechanical room,
and place an outside-air `Damper`, an `AirWaterCoolingCoil`, and a supply
`Fan` inside the AHU:

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

with Model("urn:example:hvac#") as model:
    with PhysicalSpace("mech-room") as mech_room:
        with AirHandlingUnit("ahu") as ahu:
            oa_damper = Damper("outside-air-damper")
            coil = AirWaterCoolingCoil("cooling-coil")
            fan = Fan("supply-fan")
        chiller = Chiller("chiller")
    zone_damper = Damper("zone-damper")

print("in mechanical room:", [e.name for e in mech_room.contents])
print("inside AHU:", [e.name for e in ahu.contents])
```

Notice that `ahu` and `chiller` live in `mech_room`, while `oa_damper`,
`coil`, and `fan` live inside `ahu`.

## 2. Connect the air and water loops — and map the AHU's ports

Inside the AHU, air flows through the damper, across the coil's air side,
and through the supply fan. Outside the AHU, supply air goes from the AHU
to the zone damper:

```{code-cell} python3
damper_to_coil = connect(oa_damper, coil.air_inlet, name="mixed-air")
coil_to_fan = connect(coil.air_outlet, fan, name="cooled-air")
supply_duct = connect(ahu, zone_damper, name="supply-duct")
```

Notice how an AHU works in ASHRAE 223P: external ducts and pipes connect to
the **AHU's outer boundary**, not directly to the internal parts hidden
inside it. That raises a question: how do we say which internal part's port
sits behind each of the AHU's outer ports?

That is what **`maps_to`** expresses. Because `AirHandlingUnit`, `Damper`,
and `Fan` have fixed air ports, Plumb created `ahu-in`, `ahu-out`,
`outside-air-damper-in`, and `supply-fan-out` eagerly when those objects
were constructed. Let's map the internal air endpoints onto the AHU's outer
air ports:

```{code-cell} python3
model["outside-air-damper-in"].maps_to = model["ahu-in"]
model["supply-fan-out"].maps_to = model["ahu-out"]
```

What about chilled water? An `AirHandlingUnit`'s own SHACL shape only lists
air ports, not chilled-water ports. We can declare two custom ports on the
AHU with `.port()`, map the coil's water ports onto them, and connect the
chiller to those outer AHU ports:

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

chw_supply = connect(chiller, chw_in, name="chw-supply")
chw_return = connect(chw_out, chiller, name="chw-return")
```

Notice we never gave `chw_in` or `chw_out` a `medium=`. Because
`coil.water_inlet` carries `Fluid-Water`, `maps_to` requires both ports to
share the same medium and direction (an inlet maps to an inlet; an outlet
maps to an outlet).

## 3. Resolve and inspect

Let's check and resolve the model:

```{code-cell} python3
print("status:", model.check().status)
resolved = model.resolve()

for handle in (damper_to_coil, supply_duct, chw_supply):
    conn = resolved.connection(handle)
    print(f"{conn.name:12s} -> {conn.type:4s} ({conn.medium})")
```

The air connections automatically became `Duct` objects with `Fluid-Air`,
and the chilled-water connection became a `Pipe` with `Fluid-Water` — and
the AHU's outer `chw-in` port inherited `Fluid-Water` from the coil:

```{code-cell} python3
resolved["chw-in"].medium, resolved["cooling-coil-water_inlet"].maps_to
```

## 4. Walk across and inside containers

Now let's query the resolved model to trace where air and water come from.

By default, `find_all_previous()` treats an assembly like the AHU as a
single box — and follows *all* connections entering it (both air ducts and
chilled-water pipes). Pass `through={"medium": enums.values.Fluid_Air}` to
stay strictly on the air path:

```{code-cell} python3
from plumb.s223 import enums

zone = resolved["zone-damper"]
print("all upstream:", zone.find_all_previous())
print("air-only upstream:", zone.find_all_previous(through={"medium": enums.values.Fluid_Air}))
```

Pass `descend=True` to step *inside* containers through their `maps_to`
ports. Using `walk()` shows each hop's distance from the starting equipment:

```{code-cell} python3
for hop in zone.walk(
    "upstream", through={"medium": enums.values.Fluid_Air}, descend=True
):
    print(hop.depth, hop.entity.name)
```

Starting from the chiller, `through={"medium": enums.values.Fluid_Water}`
with `descend=True` steps through the AHU's `chw-in` port straight to the
internal cooling coil:

```{code-cell} python3
resolved["chiller"].find_all_next(
    through={"medium": enums.values.Fluid_Water}, descend=True
)
```

And if a walk *starts* inside a container (for example, at `supply-fan`), it
automatically exits through `maps_to` without needing `descend=True`:

```{code-cell} python3
resolved["supply-fan"].find_all_next()
```

Containment navigation answers the complementary question — what holds a
given piece of equipment:

```{code-cell} python3
resolved["supply-fan"].find_parent(AirHandlingUnit), resolved["supply-fan"].find_parent(PhysicalSpace)
```

## 5. Validate and draw

Validate the full air + chilled-water model against ASHRAE 223P and the HVAC
domain shapes:

```{code-cell} python3
report = model.validate()
print("conforms:", report.ok, "issues:", len(report.issues))
```

```{code-cell} python3
from plumb import flowsheet

flowsheet(resolved, title="AHU with chilled-water cooling coil")
```

## What you learned

- **`with` blocks** express containment for both spaces (`PhysicalSpace`) and
  assemblies (`AirHandlingUnit`).
- **`maps_to`** links an internal part's point to its container's outer port,
  propagating medium and direction across the boundary.
- The solver automatically picks **`Duct`** for air and **`Pipe`** for water.
- **`walk(..., descend=True)`** steps inside assemblies via `maps_to`, while
  **`find_parent()`** walks containment upward.

## Next

- Need a quick recipe for a specific task? Browse the
  [How-to guides](../how-to/build-and-connect.md).
- Want to understand how Plumb's lifecycle and Z3 solver work under the
  hood? Read [Model lifecycle and connection resolution](../explanation/how-plumb-works.md).
- For a larger HVAC example, see `examples/s223/ahu/s223_quickstart.py` and
  `examples/s223/cooling_coil/cooling_coil.py`.
