Skip to content

SHACL to entities

app.shacl_to_entities

Project SHACL property shapes into EntityShape descriptors.

The descriptors drive both SPARQL generation and GeoJSON decoding. shacl_to_filters walks the same shapes to build the filter panel.

BUILTIN_PATHS = {GEO.lat, GEO.long, COMPASS.name} module-attribute

Paths the pin query binds itself, so they are never projected.

DISPLAY_ONLY = {SCHEMA.url, SCHEMA.image, COMPASS.description, COMPASS.location, SKOS.altLabel, COMPASS.relatedOrganization, COMPASS.wpEntityTagId} module-attribute

Paths shown on a pin but never offered as a filter.

EntityShape

Bases: BaseModel

One property descriptor projected from SHACL (not an instance).

targets_map_entity(g, node_shape)

Report whether node_shape targets a compass:MapEntity subclass.

Shapes targeting anything else (the SKOS tag vocabularies, for instance) only validate the generated Turtle and stay out of the map projection.

Parameters:

Name Type Description Default
g Graph

Merged ontology graph (shapes + data + vocab).

required
node_shape Node

Shape to classify.

required

Returns:

Type Description
bool

True when any sh:targetClass is a compass:MapEntity subclass.

Source code in src/backend/app/shacl_to_entities.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def targets_map_entity(g: Graph, node_shape: Node) -> bool:
    """Report whether *node_shape* targets a ``compass:MapEntity`` subclass.

    Shapes targeting anything else (the SKOS tag vocabularies, for instance)
    only validate the generated Turtle and stay out of the map projection.

    Args:
        g: Merged ontology graph (shapes + data + vocab).
        node_shape: Shape to classify.

    Returns:
        ``True`` when any ``sh:targetClass`` is a ``compass:MapEntity`` subclass.
    """
    return any(
        (target, RDFS.subClassOf, COMPASS.MapEntity) in g
        for target in g.objects(node_shape, SH.targetClass)
    )

map_property_shapes(g)

Yield every sh:property IRI of every NodeShape targeting a map entity class.

Parameters:

Name Type Description Default
g Graph

Merged ontology graph (shapes + data + vocab).

required

Yields:

Type Description
URIRef

URIRef property-shape subjects, de-duplicated.

Source code in src/backend/app/shacl_to_entities.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def map_property_shapes(g: Graph) -> Iterator[URIRef]:
    """Yield every sh:property IRI of every NodeShape targeting a map entity class.

    Args:
        g: Merged ontology graph (shapes + data + vocab).

    Yields:
        ``URIRef`` property-shape subjects, de-duplicated.
    """
    seen: set[URIRef] = set()
    for node_shape in g.subjects(SH.targetClass, None):
        if not targets_map_entity(g, node_shape):
            continue
        for prop_shape in g.objects(node_shape, SH.property):
            if isinstance(prop_shape, URIRef) and prop_shape not in seen:
                seen.add(prop_shape)
                yield prop_shape

get_definition(g, subject, lang)

Return a non-blank skos:definition in lang, falling back to English.

Unlike :func:get_label, there is no fallback to any other language.

Parameters:

Name Type Description Default
g Graph

Ontology graph.

required
subject URIRef

Concept whose definition is sought.

required
lang str

BCP 47 language tag.

required

Returns:

Type Description
str | None

The definition, or None when none is defined in either language.

Source code in src/backend/app/shacl_to_entities.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def get_definition(g: Graph, subject: URIRef, lang: str) -> str | None:
    """Return a non-blank ``skos:definition`` in *lang*, falling back to English.

    Unlike :func:`get_label`, there is no fallback to any other language.

    Args:
        g: Ontology graph.
        subject: Concept whose definition is sought.
        lang: BCP 47 language tag.

    Returns:
        The definition, or ``None`` when none is defined in either language.
    """
    definitions = [
        d for d in g.objects(subject, SKOS.definition) if isinstance(d, RDFLiteral)
    ]
    for wanted in (lang, "en"):
        for definition in definitions:
            if definition.language == wanted and str(definition).strip():
                return str(definition)
    return None

get_label(g, subject, predicate, lang)

Return a label in lang, falling back to English, then any available label.

Parameters:

Name Type Description Default
g Graph

Ontology graph.

required
subject URIRef

Resource whose label is sought.

required
predicate URIRef

Preferred label predicate (e.g. sh:name, rdfs:label).

required
lang str

BCP 47 language tag.

required

Returns:

Type Description
str

Best-matching label string, or the subject's local name as last resort.

Source code in src/backend/app/shacl_to_entities.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def get_label(g: Graph, subject: URIRef, predicate: URIRef, lang: str) -> str:
    """Return a label in *lang*, falling back to English, then any available label.

    Args:
        g: Ontology graph.
        subject: Resource whose label is sought.
        predicate: Preferred label predicate (e.g. ``sh:name``, ``rdfs:label``).
        lang: BCP 47 language tag.

    Returns:
        Best-matching label string, or the subject's local name as last resort.
    """
    candidates = list(g.objects(subject, predicate))
    if predicate != SKOS.prefLabel:
        candidates += list(g.objects(subject, SKOS.prefLabel))

    for wanted in (lang, "en"):
        for label in candidates:
            if isinstance(label, RDFLiteral) and label.language == wanted:
                return str(label)
    if candidates:
        return str(candidates[0])
    return local_name(str(subject))

get_entity_shapes_from_shacl(g)

Project SHACL property shapes into EntityShape descriptors for query and decode.

Parameters:

Name Type Description Default
g Graph

Merged ontology graph.

required

Returns:

Type Description
list[EntityShape]

One EntityShape per filterable/display property (builtins skipped).

Source code in src/backend/app/shacl_to_entities.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def get_entity_shapes_from_shacl(g: Graph) -> list[EntityShape]:
    """Project SHACL property shapes into EntityShape descriptors for query and decode.

    Args:
        g: Merged ontology graph.

    Returns:
        One ``EntityShape`` per filterable/display property (builtins skipped).
    """
    shapes: list[EntityShape] = []

    for prop_shape in map_property_shapes(g):
        path = g.value(prop_shape, SH.path)
        if path is None or path in BUILTIN_PATHS:
            continue

        datatype = g.value(prop_shape, SH.datatype)
        max_count = g.value(prop_shape, SH.maxCount)
        one_per_language = (
            datatype == RDF.langString
            and str(g.value(prop_shape, SH.uniqueLang)).lower() == "true"
        )
        is_multi = not one_per_language and (max_count is None or int(max_count) != 1)
        is_iri = (
            g.value(prop_shape, SH.nodeKind) == SH.IRI
            or g.value(prop_shape, SH["class"]) is not None
            or g.value(prop_shape, SH["in"]) is not None
        )
        category = _infer_category(datatype, is_iri)

        shapes.append(
            EntityShape(
                id=local_name(str(path)),
                path_iri=str(path),
                category=category,
                is_multi=is_multi,
                filter_type=_infer_filter_type(path, category, datatype),
                datatype=str(datatype) if datatype else None,
            )
        )

    return shapes

_infer_category(datatype, is_iri)

Map SHACL datatype / IRI-ness to a SPARQL binding category.

Parameters:

Name Type Description Default
datatype Node | None

sh:datatype value, or None.

required
is_iri bool

True when the property values are IRIs (class, nodeKind, or sh:in).

required

Returns:

Type Description
PropertyCategory

Category string consumed by the SPARQL builder and GeoJSON translator.

Source code in src/backend/app/shacl_to_entities.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def _infer_category(datatype: Node | None, is_iri: bool) -> PropertyCategory:
    """Map SHACL datatype / IRI-ness to a SPARQL binding category.

    Args:
        datatype: ``sh:datatype`` value, or ``None``.
        is_iri: True when the property values are IRIs (class, nodeKind, or sh:in).

    Returns:
        Category string consumed by the SPARQL builder and GeoJSON translator.
    """
    if is_iri:
        return "iri_with_label"
    if datatype == XSD.anyURI:
        return "uri_literal"
    if datatype == XSD.boolean:
        return "boolean"
    if datatype in (XSD.string, RDF.langString):
        return "lang_literal"
    return "simple_literal"

_infer_filter_type(path, category, datatype)

Choose the filter widget for a property, or none if display-only.

Parameters:

Name Type Description Default
path Node

Property path URIRef.

required
category PropertyCategory

Inferred PropertyCategory.

required
datatype Node | None

sh:datatype value, or None.

required

Returns:

Type Description
FilterType

Filter widget type used by the panel, or none.

Source code in src/backend/app/shacl_to_entities.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def _infer_filter_type(
    path: Node, category: PropertyCategory, datatype: Node | None
) -> FilterType:
    """Choose the filter widget for a property, or ``none`` if display-only.

    Args:
        path: Property path URIRef.
        category: Inferred ``PropertyCategory``.
        datatype: ``sh:datatype`` value, or ``None``.

    Returns:
        Filter widget type used by the panel, or ``none``.
    """
    if path in DISPLAY_ONLY or category == "uri_literal":
        return "none"
    if category == "iri_with_label":
        return "multiselect"
    if datatype in FILTER_BY_DATATYPE:
        return FILTER_BY_DATATYPE[datatype]
    return "multiselect" if category == "lang_literal" else "none"