Model Correction#

The purpose of this tutorial is to learn how to fix a model that fails validation using BuildingMOTIF Templates to automate the correction process.

Setup#

Like the previous tutorial, we’ll create an in-memory BuildingMOTIF instance, load the model, and load some libraries. We’ll also load the manifest from the previous tutorial.

from rdflib import Namespace, URIRef
from buildingmotif import BuildingMOTIF
from buildingmotif.dataclasses import Model, Library, Template
from buildingmotif.namespaces import BRICK, RDF # import this to make writing URIs easier

# in-memory instance
bm = BuildingMOTIF("sqlite://")

# create the namespace for the building
BLDG = Namespace('urn:bldg/')

# create the building model
model = Model.create(BLDG, description="This is a test model for a simple building")

# load libraries included with the python package
constraints = Library.load(ontology_graph="constraints/constraints.ttl")

# load libraries excluded from the python package (available from the repository)
brick = Library.load(ontology_graph="../../libraries/brick/Brick-subset.ttl")
g36 = Library.load(directory="../../libraries/ashrae/guideline36")


# load tutorial 2 model and manifest
model.graph.parse("tutorial2_model.ttl", format="ttl")
manifest = Library.load(ontology_graph="tutorial2_manifest.ttl")

# assign the manifest to our model
model.update_manifest(manifest.get_shape_collection())
/opt/hostedtoolcache/Python/3.11.13/x64/lib/python3.11/site-packages/pyshacl/extras/__init__.py:46: Warning: Extra "js" is not satisfied because requirement pyduktape2 is not installed.
  warn(Warning(f"Extra \"{extra_name}\" is not satisfied because requirement {req} is not installed."))
2025-06-16 23:33:51,193 | root |  WARNING: An ontology could not resolve a dependency on https://brickschema.org/schema/1.4/Brick (Name: https://brickschema.org/schema/1.4/Brick). Check this is loaded into BuildingMOTIF
2025-06-16 23:33:51,427 | root |  WARNING: An ontology could not resolve a dependency on urn:ashrae/g36 (Name: urn:ashrae/g36). Check this is loaded into BuildingMOTIF

Model Validation#

Let’s validate the model again to see what’s causing the failure.

validation_result = model.validate()
print(f"Model is valid? {validation_result.valid}")

# print reasons
for uri, diffset in validation_result.diffset.items():
    for diff in diffset:
        print(f" - {diff.reason()}")
2025-06-16 23:33:51,836 | buildingmotif.dataclasses.shape_collection |  WARNING: Could not resolve import of urn:ashrae/g36 from Libraries (Name: urn:ashrae/g36). Trying shape collections
2025-06-16 23:33:51,842 | buildingmotif.dataclasses.shape_collection |  WARNING: Could not resolve import of urn:ashrae/g36 from Libraries. Trying shape collections
2025-06-16 23:33:51,928 | buildingmotif.dataclasses.shape_collection |  WARNING: Could not resolve import of https://brickschema.org/schema/1.4/Brick from Libraries (Name: https://brickschema.org/schema/1.4/Brick). Trying shape collections
2025-06-16 23:33:51,934 | buildingmotif.dataclasses.shape_collection |  WARNING: Could not resolve import of https://brickschema.org/schema/1.4/Brick from Libraries. Trying shape collections
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 validation_result = model.validate()
      2 print(f"Model is valid? {validation_result.valid}")
      4 # print reasons

File ~/work/BuildingMOTIF/BuildingMOTIF/buildingmotif/dataclasses/model.py:218, in Model.validate(self, shape_collections, error_on_missing_imports, shacl_engine)
    194 """Validates this model against the given list of ShapeCollections.
    195 If no list is provided, the model will be validated against the model's "manifest".
    196 If a list of shape collections is provided, the manifest will *not* be automatically
   (...)
    215 :rtype: ValidationContext
    216 """
    217 compiled_model = self.compile(shape_collections or [self.get_manifest()])
--> 218 return compiled_model.validate(error_on_missing_imports)

File ~/work/BuildingMOTIF/BuildingMOTIF/buildingmotif/dataclasses/compiled_model.py:145, in CompiledModel.validate(self, error_on_missing_imports)
    143 # aggregate shape graphs
    144 for sc in self.shape_collections:
--> 145     shapeg += sc.resolve_imports(
    146         error_on_missing_imports=error_on_missing_imports
    147     ).graph
    148 # inline sh:node for interpretability
    149 shapeg = rewrite_shape_graph(shapeg)

File ~/work/BuildingMOTIF/BuildingMOTIF/buildingmotif/dataclasses/shape_collection.py:137, in ShapeCollection.resolve_imports(self, recursive_limit, error_on_missing_imports)
    120 """Resolves `owl:imports` to as many levels as requested.
    121 
    122 By default, all `owl:imports` are recursively resolved. This limit can
   (...)
    134 :rtype: ShapeCollection
    135 """
    136 resolved_namespaces: Set[rdflib.URIRef] = set()
--> 137 resolved = _resolve_imports(
    138     self.graph,
    139     recursive_limit,
    140     resolved_namespaces,
    141     error_on_missing_imports=error_on_missing_imports,
    142 )
    143 new_sc = ShapeCollection.create()
    144 new_sc.add_graph(resolved)

File ~/work/BuildingMOTIF/BuildingMOTIF/buildingmotif/dataclasses/shape_collection.py:577, in _resolve_imports(graph, recursive_limit, seen, error_on_missing_imports)
    574             raise Exception("Could not resolve import of %s", ontology)
    575         continue
--> 577     dependency = _resolve_imports(
    578         sc_to_add.graph,
    579         recursive_limit - 1,
    580         seen,
    581         error_on_missing_imports=error_on_missing_imports,
    582     )
    583     new_g += dependency
    584 return new_g

File ~/work/BuildingMOTIF/BuildingMOTIF/buildingmotif/dataclasses/shape_collection.py:574, in _resolve_imports(graph, recursive_limit, seen, error_on_missing_imports)
    572 if sc_to_add is None:
    573     if error_on_missing_imports:
--> 574         raise Exception("Could not resolve import of %s", ontology)
    575     continue
    577 dependency = _resolve_imports(
    578     sc_to_add.graph,
    579     recursive_limit - 1,
    580     seen,
    581     error_on_missing_imports=error_on_missing_imports,
    582 )

Exception: ('Could not resolve import of %s', rdflib.term.URIRef('https://brickschema.org/schema/1.4/Brick'))

We can get this information in a few different ways, too. For example, asking for all the entities which have failed validation:

for e in validation_result.get_broken_entities():
    print(e)

We can also get all reasons a particular entity has failed validation:

for diff in validation_result.get_diffs_for_entity(BLDG["Core_ZN-PSC_AC"]):
    print(diff.reason())

Model Correction with Templates#

The model is failing because the AHU doesn’t have the minimum number of supply fans associated with it. We could add the fan explicitly by adding those triples to the model like we’ve done previously, but we can also ask BuildingMOTIF to generate new templates that explicitly prompt us for the missing information. We can also take a closer look at the first autogenerated template

# create a new library to hold these generated templates
generated_templates = Library.create("my-autogenerated-templates")

# loop through all results for the AHU
for diff in validation_result.get_diffs_for_entity(BLDG["Core_ZN-PSC_AC"]):
    diff.resolve(generated_templates)

# print some of the autogenerated template
for templ in generated_templates.get_templates():
    templ = templ.inline_dependencies()
    print(f"Name (autogenerated): {templ.name}")
    print(f"Parameters (autogenerated): {templ.parameters}")
    print("Template body (autogenerated):")
    print(templ.body.serialize())
    print('-' * 79)

In this case, the generated templates are fairly simple. They require an input for the name of the supply fan and the names of several missing points. We can loop through each of these generated templates and create the names. Here, we are creating arbitrary names for the points but in a real setting you would likely pull the equipment or point names from an external source like a Building Information Model or BACnet network[1] (see future tutorials for how to do this!) Another challenge is the fact that we already have a supply fan in the model. Here, we can take advantage of the fact that the name of the fan in the existing model are just the name of the AHU wtih the -Fan postfix. The name of the AHU is in the generated templates (see above) so we can just pull out the name of the AHU, add the postfix, and use that as the value for the name parameter.

If we just add the generated templates to the building model, we will probably pass validation but the entity names will have no significance to the building. It is highly recommended to use the template evaluation features (demonstrated below) to fill in the parameters with the “real” names of the entities as they appear in the building and/or building management system.

# use the name of the AHU from above as the base of our template names
ahu_name = "Core_ZN-PSC_AC"

# lookup for the name of the template to the name of the point or part
points_and_parts = {
    "resolve_Core_ZN-PSC_ACMixed_Air_Temperature_Sensor": "-MAT",
    "resolve_Core_ZN-PSC_ACFilter_Differential_Pressure_Sensor": "-FilterDPS",
    "resolve_Core_ZN-PSC_ACCooling_Command": "-CCmd",
    "resolve_Core_ZN-PSC_ACHeating_Command": "-HCmd",
    "resolve_Core_ZN-PSC_ACOutside_Air_Temperature_Sensor": "-OAT",
    "resolve_Core_ZN-PSC_ACSupply_Air_Temperature_Sensor": "-SAT",
    "resolve_Core_ZN-PSC_ACReturn_Air_Temperature_Sensor": "-RAT",
    "resolveCore_ZN-PSC_ACsa-fan": "-Fan", # this is an existing fan in the model!
}

for templ in generated_templates.get_templates():
    templ = templ.inline_dependencies()

    suffix = points_and_parts[templ.name]

    # we know from the exploration above that each template has
    # 1 parameter which is the name of the missing item
    param = list(templ.parameters)[0]
    bindings = {
        param: BLDG[ahu_name + suffix],
    }
    thing = templ.evaluate(bindings)
    if isinstance(thing, Template):
        # there might be other parameters on a template. Invent names for them
        _, thing = thing.fill(BLDG)
    model.add_graph(thing)

We use the same code as before to ask BuildingMOTIF if the model is now valid:

validation_result = model.validate()
print(f"Model is valid? {validation_result.valid}")
# print reasons
for uri, diffset in validation_result.diffset.items():
    for diff in diffset:
        print(f" - {diff.reason()}")

We are still not finished. The sa-fan shape has its own requirements for necessary points. Let’s use the same process above to get templates we can fill out to repair the model

generated_templates_sf = Library.create("my-autogenerated-templates-sf")
for diff in validation_result.get_diffs_for_entity(BLDG["Core_ZN-PSC_AC-Fan"]):
    diff.resolve(generated_templates_sf)

# print some of the autogenerated template
for templ in generated_templates_sf.get_templates():
    templ = templ.inline_dependencies()
    print(f"Name (autogenerated): {templ.name}")
    print(f"Parameters (autogenerated): {templ.parameters}")
    print("Template body (autogenerated):")
    print(templ.body.serialize())
    print('-' * 79)

Use the names of these templates to build a lookup table for the point and part names.

sf_name = "Core_ZN-PSC_AC-Fan"

# lookup for the name of the template to the name of the point or part
points_and_parts = {
    "resolve_Core_ZN-PSC_AC-FanFrequency_Command": "-Freq",
    "resolve_Core_ZN-PSC_AC-FanStart_Stop_Command": "-StartStop",
    "resolve_Core_ZN-PSC_AC-FanFan_Status": "-Sts",
}
for templ in generated_templates_sf.get_templates():
    templ = templ.inline_dependencies()

    suffix = points_and_parts[templ.name]

    param = list(templ.parameters)[0]
    bindings = {
        param: BLDG[sf_name + suffix],
    }
    thing = templ.evaluate(bindings)
    model.add_graph(thing)

We can re-check the validation of the model now:

validation_result = model.validate()
print(f"Model is valid? {validation_result.valid}")
print(validation_result.report.serialize())

# print reasons
for uri, diffset in validation_result.diffset.items():
    for diff in diffset:
        print(f" - {diff.reason()}")

Success! The model is valid with respect to the targeted use case, i.e. the model can support the high-performance sequences of operation for single zone VAV AHUs from ASHRAE Guideline 36. Let’s take a look at the validated model and save it for use in future tutorials.

# print model
print(model.graph.serialize())

#save model
model.graph.serialize(destination="tutorial3_model.ttl")