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

# Build your first plant model

In this tutorial you will build a water treatment plant model from scratch.
You do not need any background in RDF or semantic web standards — we will
introduce each concept as the model calls for it.

By the end, you will know how to:

- create equipment inside a `Model`,
- connect equipment and let Plumb infer pipes and connection points,
- handle ambiguity when more than one fluid could flow,
- use a domain package with named ports to model a full treatment train, and
- validate, save, reload, query, and draw the result.

## 1. Create a model and add equipment

Every Plumb script starts with a **`Model`** — a container that holds all the
equipment and relationships in one plant.

When you create a `Model`, you give it a **namespace** such as
`"urn:example:first-plant#"`. In RDF, every object has a globally unique ID
called an **IRI** (like a URL for a piece of equipment). Plumb builds each
object's IRI automatically by combining the namespace with the short Python
name you pick.

Let's start with three plain pieces of equipment from the WaTr ontology: an
intake pump, a sedimentation tank (clarifier), and a storage tank (clearwell).

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

with Model("urn:example:first-plant#") as model:
    intake = Pump("intake-pump")
    clarifier = SedimentationTank("clarifier")
    clearwell = Tank("clearwell", has_role=[enums.values.Role_Storage])

intake.meta.instance_iri
```

Notice two things right away:

1. Everything constructed inside `with Model(...) as model:` is registered
   with that model automatically. You can look any object up later by name,
   like `model["clarifier"]`.
2. `enums.values` holds controlled vocabulary constants — here `Role_Storage`
   marks the tank as a storage tank.

In WaTr, equipment can also carry a **process** (what physical or chemical
operation it performs) and a **treatment objective** (what that operation is
meant to achieve). When an equipment class implies a process by definition,
Plumb fills it in for you:

```{code-cell} python3
list(clarifier.has_process)
```

Every `SedimentationTank` performs settling automatically.

## 2. Connect equipment and resolve the model

Next, let's describe how water moves through the three units.

In ASHRAE 223P and WaTr, connecting two pieces of equipment involves several
pieces under the hood:

- a **connection point** (an inlet or outlet port) on each piece of equipment,
- a **connection** between them (such as a `Pipe` for liquids or a `Duct` for
  air), and
- a **medium** — the substance flowing through the connection (such as
  `Fluid_Water` or `Fluid_Sludge`).

Rather than creating all of those objects by hand, you simply call
`connect(source, target)`. That records your *intention* and returns a
**connection handle** you can name or refine later.

Let's connect the intake pump to the clarifier (specifying `Fluid_Water`),
and connect the clarifier to the clearwell:

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

raw_water = connect(
    intake, clarifier, name="raw-water", medium=enums.values.Fluid_Water
)
clarified = connect(clarifier, clearwell, name="clarified-water")
```

Notice that we have not created any pipes yet, and we did not specify a
medium on `clarified-water`. Let's ask `model.check()` whether Plumb has
enough information to fill in all the missing pipes, ports, and media
uniquely:

```{code-cell} python3
model.check().status
```

`"complete"` means there is exactly one valid interpretation. Because
`raw-water` brings `Fluid_Water` into the clarifier, the solver keeps a
consistent fluid through the clarifier and into the clearwell.

Let's **resolve** the model. Calling `model.resolve()` turns your authored
objects and `connect()` intentions into a **resolved snapshot** — a frozen,
concrete model where every connection point and pipe actually exists:

```{code-cell} python3
resolved = model.resolve()
resolved.explain(clarified)
```

`explain()` shows every decision the solver made: it created an outlet on
`clarifier`, an inlet on `clearwell`, chose `Fluid-Water`, and picked a
`Pipe` because the medium is water:

```{code-cell} python3
pipe = resolved.connection(raw_water)
pipe, pipe.medium, list(pipe.connects_at)
```

Your original `model` stays clean and editable — the derived pipes and points
live only inside the `resolved` snapshot:

```{code-cell} python3
print("authored objects:", len(model))
print("resolved objects:", len(resolved))
```

## 3. Add a sludge branch — and see why named ports help

Real clarifiers have *two* outlets: clarified water goes forward to
filtration, and settled sludge leaves the bottom to a thickener.

Let's add a sludge pump and a `GravityThickener`, connect the clarifier's
sludge line with `medium=enums.values.Fluid_Sludge`, and check the model
again:

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

with model:
    sludge_pump = Pump("sludge-pump")
    thickener = GravityThickener("thickener")

connect(clarifier, sludge_pump, name="sludge-draw", medium=enums.values.Fluid_Sludge)
connect(sludge_pump, thickener, name="sludge-to-thickener")

report = model.check()
print(report.status)
for issue in report.issues:
    print(issue.message)
```

Now `report.status` is **`"underconstrained"`**! Why? Once the clarifier
carries *both* water and sludge, Plumb refuses to guess whether
`clarified-water` going to the clearwell carries water or sludge.

Telling Plumb that `clarified` carries water removes the ambiguity:

```{code-cell} python3
clarified.medium = enums.values.Fluid_Water
model.check().status
```

That works! Still, notice how easy it would be on a larger plant to mix up a
clarifier's water outlet and its sludge outlet — or a filter's production
outlet and its backwash drain.

This is where a **domain package** helps. A domain package is a small
reusable ontology compiled on top of WaTr that defines ready-made equipment
classes with fixed processes, objectives, and **named ports** — attributes
like `clarifier.clarified_water` and `clarifier.sludge`.

Plumb ships with a drinking-water domain package,
`plumb.watr.drinking_water`, with five conventional surface-water treatment
stages:

![Treatment train with sludge and filter backwash branches](../_static/treatment-train.svg)

| Stage | Class | Named ports |
| --- | --- | --- |
| Coagulation | `CoagulationStage` | `inlet`, `outlet` |
| Flocculation | `FlocculationStage` | `inlet`, `outlet` |
| Clarification | `ClarificationStage` | `inlet`, `clarified_water`, `sludge` |
| Filtration | `RapidSandFiltrationStage` | `inlet`, `filtered_water`, `backwash_supply`, `backwash_waste` |
| Disinfection | `ChlorinationStage` | `inlet`, `outlet` |

Let's build the full five-stage train using these classes.

## 4. Build, group, and validate the treatment train

We will also introduce one more concept: a **system**. Calling
`with model.system("treatment-system") as system:` groups all the equipment
created inside the block into a single S223 `System`. Calling
`system.boundary(...)` marks the ports where flow enters or leaves the
system — raw water in, finished water out, sludge out, and backwash water in
and out.

```{code-cell} python3
from plumb.watr.drinking_water import (
    ChlorinationStage,
    ClarificationStage,
    CoagulationStage,
    FlocculationStage,
    RapidSandFiltrationStage,
)

with Model("urn:example/treatment#") as train:
    with train.system("treatment-system") as system:
        coagulation = CoagulationStage("coagulation")
        flocculation = FlocculationStage("flocculation")
        clarifier = ClarificationStage("clarifier")
        sand_filter = RapidSandFiltrationStage("sand-filter")
        disinfection = ChlorinationStage("chlorination-contact")

        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, disinfection.inlet, name="filtered-water"
        )

        system.boundary(
            coagulation.inlet,
            disinfection.outlet,
            clarifier.sludge,
            sand_filter.backwash_supply,
            sand_filter.backwash_waste,
        )
```

Notice we didn't need a single `medium=` hint here — each named port already
carries its own fixed medium from the drinking-water package.

Now let's run `train.compile()`. Under the hood, `compile()` does two things:

1. **Resolves** all deferred connections into a frozen snapshot.
2. **Validates** the resulting RDF against **SHACL** — the ontology's
   official rulebook of structural constraints — raising a `ValidationError`
   if anything violates the standard.

```{code-cell} python3
compiled = train.compile()
```

No error means the entire model conforms to both WaTr and the drinking-water
rules. Let's inspect the clarifier's process, objective, and system boundary:

```{code-cell} python3
c = compiled["clarifier"]
print("processes:", [p.meta.label for p in c.has_process])
print("objectives:", [o.meta.label for o in c.has_treatment_objective])
print(
    "boundary points:",
    [(pt.owner.name, pt.label) for pt in compiled["treatment-system"].has_boundary_connection_point],
)
```

## 5. Save, load, query, and draw

Save the resolved model to a standard RDF Turtle file:

```{code-cell} python3
train.save("treatment.ttl")
```

Later — in another script, notebook, or tool — load it back with
`Model.from_graph()`. The saved file declares which ontologies it uses, so
Plumb picks the WaTr and drinking-water packages automatically:

```{code-cell} python3
loaded = Model.from_graph("treatment.ttl")
```

Every `ClarificationStage` is also a `SedimentationTank` in the ontology
hierarchy, so querying for the broader WaTr class finds it:

```{code-cell} python3
loaded.find_all(SedimentationTank)
```

You can also walk along the pipes directly. `find_all_next()` steps over
connection points and pipes and returns downstream equipment, nearest first:

```{code-cell} python3
loaded["coagulation"].find_all_next()
```

Finally, draw the plant as a process flow sheet. Unconnected system boundary
points appear automatically as feed and product terminals:

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

flowsheet(loaded, title="Conventional drinking-water treatment train")
```

## What you learned

- A **`Model`** owns a namespace and mints unique IRIs for every object.
- **`connect()`** records flow intentions; **`check()`** flags ambiguity;
  **`resolve()`** builds a frozen snapshot with concrete ports and pipes;
  **`compile()`** resolves and validates against SHACL.
- **Domain packages** provide reusable equipment with fixed processes,
  objectives, and named ports.
- **`save()`**, **`Model.from_graph()`**, **`find_all()`**,
  **`find_all_next()`**, and **`flowsheet()`** round-trip, query, and
  visualize the plant.

## Next

In [Add measurements, sensors, and controls](instrument-and-measure.md), you
will attach physical quantities with units, define reusable property sets,
and add sensors and actuators to this plant.
