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. Flow walks require concrete pipes and points, so call them on a resolved snapshot or a loaded model.
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:
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)),
)
clarifiers: [<ClarificationStage 'clarifier'>]
sludge pipes: [<Pipe 'sludge-line'>]
any fluid vs exact Mix_Fluid: 4 []
Supported filter forms:
Filter |
Matches |
|---|---|
|
any listed value |
|
regex search on strings |
|
attribute is populated / empty |
|
callable returning truthy |
|
related object of that class |
|
object’s class |
|
tuple of classes, capped at |
|
escape hatch when a property name clashes with an option |
Direct lookup accepts either a local name or a full IRI:
model["clarifier"] is model["urn:example:query#clarifier"]
True
Browse classes and enum hierarchies#
Explore ontology classes via .meta and enumeration values via enums:
print(Process.meta.tree(max_depth=1))
Process
├── Process_BiologicalProcess
├── Process_ChemicalProcess
└── Process_PhysicalProcess
# 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))
selected process: Process_ReverseOsmosis https://watermetadata.org/ontology/watr#Process-ReverseOsmosis
chilled water: <enum Water-ChilledWater>
sludge is_a Mix_Fluid: True
sludge is_a Fluid_Water: False
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).
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:
report = authored.validate()
print("ok:", report.ok, "violations:", len(report.violations))
for issue in report.issues:
print(" ", issue)
ok: True violations: 0
info: sand-filter-backwash_supply (InletConnectionPoint) [connectsThrough]: s223: `ConnectionPoint` <urn:example:query#sand-filter-backwash_supply> probably needs an association with a `Connection`, or use of `hasOptionalConnectionPoint` or `hasBoundaryConnectionPoint` qualifiers.
info: sand-filter-filtered_water (OutletConnectionPoint) [connectsThrough]: s223: `ConnectionPoint` <urn:example:query#sand-filter-filtered_water> probably needs an association with a `Connection`, or use of `hasOptionalConnectionPoint` or `hasBoundaryConnectionPoint` qualifiers.
info: sand-filter-backwash_waste (OutletConnectionPoint) [connectsThrough]: s223: `ConnectionPoint` <urn:example:query#sand-filter-backwash_waste> probably needs an association with a `Connection`, or use of `hasOptionalConnectionPoint` or `hasBoundaryConnectionPoint` qualifiers.
Pass a file path or
rdflib.Graph(model.validate("site-rules.ttl")) to validate against custom shapes; passinfer=Falseto skip SHACL-AF rules.report.issuesincludes advisory notices (such as unconnected boundary points), which do not failreport.ok; checkreport.violationsfor errors only.save()andgraph()resolve without validating; callcompile()orvalidate()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:
sheet = flowsheet(model, title="Surface-water plant")
sheet
Pass
direction="TB"for a vertical layout on long trains, orproperties=False,instruments=False,legend=Falsefor a simpler diagram.Export with
sheet.save("plant.svg")(.png,.pdf, and.dotare also supported). Readingsheet.sourceworks even without Graphviz installed.
Query with SPARQL#
For ad-hoc RDF queries beyond Python traversal, call .query() on
model.graph():
rows = model.graph().query(
"SELECT ?pump WHERE { ?pump a <https://watermetadata.org/ontology/watr#Pump> }"
)
[str(row.pump) for row in rows]
['urn:example:query#intake-pump']