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

# Search, walk, validate, and draw models

Find equipment by class or attribute, walk containment and flow paths,
browse ontology classes and enums, validate against SHACL shapes, and draw
flow sheets.

All search methods work identically on authored models, resolved snapshots,
and [loaded models](save-load-and-extend.md). Flow walks require concrete
pipes and points, so call them on a resolved snapshot or a loaded model.

```{code-cell} python3
from plumb import Model, connect, exact, flowsheet
from plumb.qudt import quantity_kinds, units
from plumb.watr import (
    LevelSensor,
    PhysicalSpace,
    Pipe,
    Process,
    Pump,
    SedimentationTank,
    Tank,
    enums,
)
from plumb.watr.drinking_water import (
    ClarificationStage,
    CoagulationStage,
    RapidSandFiltrationStage,
)

values = enums.values
with Model("urn:example:query#") as authored:
    with authored.system("plant") as plant:
        with PhysicalSpace("treatment-building"):
            intake = Pump("intake-pump", label="Intake pump")
            coagulation = CoagulationStage("coagulation")
            clarifier = ClarificationStage("clarifier")
            sand_filter = RapidSandFiltrationStage("sand-filter")
        holding = Tank("sludge-holding")

raw = connect(intake, coagulation.inlet, name="raw-water")
connect(coagulation.outlet, clarifier.inlet, name="coagulated-water")
settled = connect(clarifier.clarified_water, sand_filter.inlet, name="clarified-water")
connect(clarifier.sludge, holding, name="sludge-line")
plant.boundary(intake.port("river-intake", direction="in"))

raw.quantity("raw-turbidity", 18.0, unit=units.NTU, kind=quantity_kinds.Turbidity)
raw.sensor("raw-flow", kind=quantity_kinds.VolumeFlowRate, unit=units.M3_PER_DAY)
settled.sensor("settled-turbidity", kind=quantity_kinds.Turbidity, unit=units.NTU)
holding.sensor(
    "sludge-level", kind=quantity_kinds.Length, unit=units.M, sensor_class=LevelSensor
)

model = authored.resolve()
```

## Find objects by class and attribute

`find_all()` searches by semantic class hierarchy (so searching for
`SedimentationTank` finds `ClarificationStage`) and matches keyword filters
by equality or collection membership. `find()` returns the first match or
`None`.

Class and enum filters match narrower values automatically; wrap a filter in
`exact()` to opt out:

```{code-cell} python3
fluid = values.Mix_Fluid

print("clarifiers:", model.find_all(SedimentationTank))
print("sludge pipes:", model.find_all(Pipe, medium=values.Fluid_Sludge))
print(
    "any fluid vs exact Mix_Fluid:",
    len(model.find_all(Pipe, medium=fluid)),
    model.find_all(Pipe, medium=exact(fluid)),
)
```

Supported filter forms:

| Filter | Matches |
| --- | --- |
| `medium=[water, sludge]` | any listed value |
| `label=re.compile("^Intake")` | regex search on strings |
| `has_role=True` / `False` | attribute is populated / empty |
| `label=lambda s: "pump" in s` | callable returning truthy |
| `has_member=Pump` | related object of that class |
| `type=Pipe` or `type="Pipe"` | object's class |
| `find_all((Pump, Tank), limit=2)` | tuple of classes, capped at `limit` |
| `attrs={"limit": ...}` | escape hatch when a property name clashes with an option |

Direct lookup accepts either a local name or a full IRI:

```{code-cell} python3
model["clarifier"] is model["urn:example:query#clarifier"]
```

## Navigate containment and flow

- **Containment** works whichever side stores the RDF edge:
  `contents`, `descendants`, `container`, `containers`, `entity.find_all()`,
  and `entity.find_parent()`.
- **Flow walks** follow pipes and connection points breadth-first, nearest
  first: `find_next()`, `find_all_next()`, `find_previous()`,
  `find_all_previous()`, and `walk()`.

Use `through=` to restrict which connections a walk may cross (for example,
water pipes only, excluding the sludge branch):

```{code-cell} python3
building = model["treatment-building"]
print("in building:", [e.name for e in building.contents])
print("parent of clarifier:", model["clarifier"].find_parent(PhysicalSpace))

print("all downstream:", [e.name for e in model["intake-pump"].find_all_next()])
print(
    "water-only downstream:",
    [
        e.name
        for e in model["intake-pump"].find_all_next(
            through={"medium": values.Fluid_Water}
        )
    ],
)
```

`walk()` yields `Hop(entity, depth, via)` so you can inspect distances and
every pipe crossed:

```{code-cell} python3
for hop in model["intake-pump"].walk(max_hops=2):
    print(hop.depth, hop.entity.name, [step.connection.name for step in hop.via])
```

Other walk options: `descend=True` (step into containers via `maps_to`),
`include_connections=True` (yield pipes too), `max_hops=N`, and
`through=lambda crossing: ...`.

## Browse classes and enum hierarchies

Explore ontology classes via `.meta` and enumeration values via `enums`:

```{code-cell} python3
print(Process.meta.tree(max_depth=1))
```

```{code-cell} python3
# Scoped lookup within a branch by short name, Python name, or IRI
ro = Process.meta["ReverseOsmosis"]
print("selected process:", ro.__name__, ro.meta.iri)

# Browse and test enum hierarchies
water = enums.Substance.Medium.Mix.Fluid.Water
print("chilled water:", water["ChilledWater"])
print("sludge is_a Mix_Fluid:", values.Fluid_Sludge.is_a(values.Mix_Fluid))
print("sludge is_a Fluid_Water:", values.Fluid_Sludge.is_a(values.Fluid_Water))
```

For full class metadata, inspect `cls.meta.iri`, `cls.meta.label`,
`cls.meta.definition`, `cls.meta.properties`, and `pkg.REGISTRY.classes`
(or browse the interactive [Class catalog](../reference/catalog.md)).

## Validate against SHACL

`model.validate()` runs SHACL-AF inference rules and SHACL Core validation
against the shapes bundled with every package used in the model, mapping
each violation back to the Python entity that caused it.

`model.compile()` resolves and validates in one call, raising
`ValidationError` if any violation exists:

```{code-cell} python3
report = authored.validate()
print("ok:", report.ok, "violations:", len(report.violations))
for issue in report.issues:
    print(" ", issue)
```

- Pass a file path or `rdflib.Graph` (`model.validate("site-rules.ttl")`) to
  validate against custom shapes; pass `infer=False` to skip SHACL-AF rules.
- `report.issues` includes advisory notices (such as unconnected boundary
  points), which do not fail `report.ok`; check `report.violations` for
  errors only.
- `save()` and `graph()` resolve without validating; call `compile()` or
  `validate()` first when conformance is required.

## Draw a flow sheet

`flowsheet()` renders any S223 or WaTr model (authored, resolved, or loaded)
as a Graphviz process flow sheet:

```{code-cell} python3
sheet = flowsheet(model, title="Surface-water plant")
sheet
```

- Pass `direction="TB"` for a vertical layout on long trains, or
  `properties=False`, `instruments=False`, `legend=False` for a simpler
  diagram.
- Export with `sheet.save("plant.svg")` (`.png`, `.pdf`, and `.dot` are also
  supported). Reading `sheet.source` works even without Graphviz installed.

## Query with SPARQL

For ad-hoc RDF queries beyond Python traversal, call `.query()` on
`model.graph()`:

```{code-cell} python3
rows = model.graph().query(
    "SELECT ?pump WHERE { ?pump a <https://watermetadata.org/ontology/watr#Pump> }"
)
[str(row.pump) for row in rows]
```
