Model lifecycle and connection resolution#

This page explains how Plumb separates what you author from the concrete RDF graph it materializes, and how the connection solver fills in pipes, ports, and media without guessing.

The five stages of a model#

generated classes → authored model → check() → resolve() → graph() / save()
                                                         └→ validate() / compile()
  1. Generate (ahead of time). The compiler reads an ontology and its SHACL shapes once and produces a plain Python package (plumb.s223, plumb.watr, plumb.brick, or your own extension). User scripts import generated classes directly — they never run the compiler.

  2. Author (mutable, validated incrementally). A Model holds the objects you create and the deferred intentions you record (connect(), .port(), model.system()). Every constructor and attribute write runs inside an atomic transaction, checks ranges and SHACL value rules, and keeps inverse relations in sync. If an edit fails midway, the model rolls back cleanly.

  3. Resolve (isolated, immutable snapshot). Calling check() runs the solver without modifying anything. Calling resolve() builds a frozen ResolvedModel snapshot containing every derived connection point, pipe or duct, and inverse link. Your authored Model is untouched, so you can keep editing it; any edit simply invalidates the cached snapshot so the next resolve() reflects the change.

  4. Validate (authoritative SHACL). validate() resolves deferred intentions, runs SHACL-AF inference rules, and checks SHACL Core shapes via shifty against every package’s bundled _shapes.ttl, mapping violations back to Python objects. compile() resolves and validates in one step. (graph() and save() resolve without validating.)

  5. Load and extend. Model.from_graph() owns a private copy of the imported RDF. Existing concrete models serialize and walk without loading the Z3 planner at all. If you later extend a loaded model with deferred connect(), .port(), or model.system() calls, resolution materializes those new intentions into a snapshot while preserving all original IRIs, blank nodes, and untouched triples.

Plain RDF ontologies such as Brick take the fast copy path without ever importing the connection solver.

How connections are resolved#

In ASHRAE 223P and WaTr, a single flow connection consists of several RDF resources: an outlet connection point on the source, an inlet connection point on the target, a Connection (such as a Pipe or Duct), matching media on all three, and inverse links between them.

Writing connect(a, b) records only the intention. Resolution uses the Z3 constraint solver to materialize the concrete graph from three inputs:

  1. Port contracts compiled from SHACL. Each class’s qualified hasConnectionPoint shapes become a structured port contract (inspect it with cls.describe_ports()):

from plumb.watr import Clarifier

print(Clarifier.describe_ports())
Clarifier port requirements
Unconditional ports:
  - direction="out" -> OutletConnectionPoint (count 2..any); medium roots: Mix-Fluid
Shape constraints:
  - all of:
    - direction="out" -> OutletConnectionPoint (count 1..any); medium roots: Fluid-Sludge
    - direction="out" -> OutletConnectionPoint (count 1..any); medium roots: Fluid-Water
  • Fixed-medium points (like an S223 Fan’s air inlet and outlet) are created eagerly when the equipment is constructed so you can label or map them right away.

  • Variable-medium points wait for resolution so adjacent connections can narrow them.

  • Shape counts are lower bounds unless a maximum is declared. Boolean sh:and, sh:or, and sh:xone layouts stay intact as solver alternatives.

  1. Your explicit hints. Anything you wrote — medium=, a named point like clarifier.sludge, a custom .port(...) (whose explicit medium overrides the class’s default domain), connection=, .pair(), or maps_to — enters as hard constraints.

  2. Property medium compatibility. If a property attached to a pipe or port declares of_medium, the solver enforces 223P’s Incompatible Medium rule: the host’s medium must be the same, an ancestor/descendant, or a mixture sharing a constituent. Properties without of_medium inherit their host’s resolved medium automatically.

Each disconnected group of equipment is solved and cached independently, so editing one branch of a large plant only re-solves that component.

Ranking valid solutions — and refusing to guess#

Among valid assignments, Z3 prefers:

  1. fewer newly materialized connection points, and then

  2. fewer medium changes across ports on the same piece of equipment when their allowed domains overlap (this is a coherence preference, not a physical conservation claim).

After finding the optimal score, Plumb probes for any other distinct solution with the same score. If one exists, Plumb raises AmbiguousModelError instead of arbitrarily picking one — for example, connecting two WaTr Pump instances with no medium hint. Contradictory constraints raise UnsatisfiableModelError with the conflicting authored facts in .core.

resolved.explain(handle) reports the exact points chosen, the resolved medium, and the strongest reason it was chosen:

from plumb import Model, connect
from plumb.watr import Pump
from plumb.watr.drinking_water import CoagulationStage

with Model("urn:example:resolution#") as model:
    pump = Pump("intake-pump")
    coagulation = CoagulationStage("coagulation")
raw_water = connect(pump, coagulation, name="raw-water")

resolved = model.resolve()
resolved.explain(raw_water)
raw-water: intake-pump-out -> coagulation-inlet
  medium: Fluid-Water (explicit port)
  - selected OutletConnectionPoint intake-pump-out
  - selected InletConnectionPoint coagulation-inlet
  - coagulation-inlet.medium = Fluid-Water

Here is the concrete Pipe RDF that Plumb generated from that single connect() call:

from rdflib import URIRef

graph = resolved.graph()
pipe = resolved.connection(raw_water)
pipe_rdf = graph.cbd(URIRef(pipe.meta.instance_iri))
pipe_rdf.namespace_manager = graph.namespace_manager
print(pipe_rdf.serialize(format="turtle"))
@prefix : <urn:example:resolution#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix s223: <http://data.ashrae.org/standard223#> .

:raw-water a s223:Pipe ;
    rdfs:label "raw-water" ;
    s223:connectsAt :coagulation-inlet,
        :intake-pump-out ;
    s223:hasMedium s223:Fluid-Water .

The resolved medium also chooses the connection subclass from the package’s policy table — Fluid-Air selects Duct, while Fluid-Water, Fluid-NaturalGas, Fluid-Oil, and WaTr’s Mix-Fluid select Pipe — unless you override it with connection=.

Why some required properties defer to validation#

A SHACL sh:minCount 1 normally becomes a required Python constructor argument, with two deliberate exceptions:

  • Class-implied defaults (such as a sedimentation tank’s settling process) are filled in automatically by the constructor.

  • Mutually required cycles defer to validation. For instance, an S223 Junction requires at least one ConnectionPoint, and every ConnectionPoint requires its owning equipment. Demoting the constructor check lets you construct Junction("j", medium=...) first and add or resolve its points afterward.

For implementation details, see docs/architecture.md in the repository.