From cf60edd2fcefac7b4102fe5b41bcc8aaf58c53aa Mon Sep 17 00:00:00 2001 From: Tommaso Barbato Date: Thu, 5 Nov 2026 17:22:34 +0100 Subject: [PATCH] Fix datatype ranges and preserve every facet value Datatype restrictions overwrote the base datatype and each preceding facet, leaving only the final operator and value in the generated documentation. Keep the base datatype separate from ordered facet/value pairs and render every constraint. Preserve the existing single-value accessor for callers that use it. Add regression tests for inclusive and exclusive bounds, reversed facet order, zero, patterns, and complete ranges in static index and resource pages. --- lode/models/datatypeRestriction.py | 28 +++++-- lode/reader/logic/owl_logic.py | 7 +- lode/viewer/owl_viewer.py | 19 ++--- tests/test_datatype_restrictions.py | 113 ++++++++++++++++++++++++++++ 4 files changed, 146 insertions(+), 21 deletions(-) create mode 100644 tests/test_datatype_restrictions.py diff --git a/lode/models/datatypeRestriction.py b/lode/models/datatypeRestriction.py index 5f04de2..59f60c8 100644 --- a/lode/models/datatypeRestriction.py +++ b/lode/models/datatypeRestriction.py @@ -2,27 +2,39 @@ from .restriction import Restriction class DatatypeRestriction(Restriction): - """A datatype narrowed by an XSD facet, such as a pattern or a minimum value.""" + """A datatype narrowed by XSD facet/value pairs, such as numeric bounds.""" def __init__(self, **kwargs): - """Create a datatype restriction with no datatype and no facet value.""" + """Create a datatype restriction with no base datatype or facets.""" super().__init__(**kwargs) - self.applies_on_concept = None # Datatype (from owl:onDatatype) string (xsd:pattern, xsd:minInclusive, ...) - self.has_restriction_value = None # Literal (the corresponding value e.g. 0.0) + self.applies_on_concept = None # Datatype from owl:onDatatype + self.has_facets = [] # Ordered (facet operator, Literal) pairs + self.has_restriction_value = None # Last value, for single-facet callers def get_applies_on_concept(self): - """Return applies_on_concept (the datatype, or the facet string).""" + """Return the base datatype.""" return self.applies_on_concept def set_applies_on_concept(self, datatype): - """Set applies_on_concept (the datatype, or the facet string).""" + """Set the base datatype without changing its facets.""" self.applies_on_concept = datatype + def set_has_facet(self, constraint, value): + """Add a facet/value pair, preserving its association and list order.""" + pair = (constraint, value) + if pair not in self.has_facets: + self.has_facets.append(pair) + self.set_has_restriction_value(value) + + def get_has_facets(self): + """Return a copy of all facet/value pairs.""" + return list(self.has_facets) + def set_has_restriction_value(self, string): """Set has_restriction_value (the literal value of the facet).""" self.has_restriction_value = string def get_has_restriction_value(self): - """Return has_restriction_value (the literal value of the facet).""" - return self.has_restriction_value \ No newline at end of file + """Return the last facet value; use get_has_facets() for all constraints.""" + return self.has_restriction_value diff --git a/lode/reader/logic/owl_logic.py b/lode/reader/logic/owl_logic.py index f80af02..e5ecdaa 100644 --- a/lode/reader/logic/owl_logic.py +++ b/lode/reader/logic/owl_logic.py @@ -741,7 +741,7 @@ def handle_disjoint_union(self, instance, uri, predicate, obj, setter=None): logger.warning("disjointUnion failed for %s", uri, exc_info=True) def handle_datatype_restriction(self, instance, uri, predicate, obj, setter=None): - """Handle owl:withRestrictions on a datatype: set the datatype and one facet value per facet. + """Handle owl:withRestrictions: preserve the base datatype and every facet/value pair. Facet nodes (e.g. xsd:minInclusive) are cached and tracked, so phase 6 does not turn them into Statements. @@ -769,9 +769,8 @@ def handle_datatype_restriction(self, instance, uri, predicate, obj, setter=None str(XSD.maxLength): "maxLength", } manchester_facet = FACET_MAP.get(str(facet_pred), str(facet_pred)) - instance.set_applies_on_concept(manchester_facet) literal = self._create_literal(facet_val) - instance.set_has_restriction_value(literal) + instance.set_has_facet(manchester_facet, literal) # Register facet node in cache keyed to the parent DatatypeRestriction # and mark all its triples as mapped, so phase6 does not create @@ -1101,4 +1100,4 @@ def _uri_in_axiom_members(self, axiom_node, uri_ref): if first == uri_ref: return True node = self.graph.value(node, RDF.rest) - return False \ No newline at end of file + return False diff --git a/lode/viewer/owl_viewer.py b/lode/viewer/owl_viewer.py index 91aa2a4..39a86a9 100644 --- a/lode/viewer/owl_viewer.py +++ b/lode/viewer/owl_viewer.py @@ -158,9 +158,8 @@ def _get(instance, prop_name, default=None): parts.extend(self._parse_restriction(resource, language, _seen)) elif obj_type == "DatatypeRestriction": - concept = _get(obj, 'applies_on_concept') # Datatype(xsd:string) - constraint = _get(obj, 'has_constraint') # "pattern" - value = _get(obj, 'has_restriction_value') # Literal("[0-9]+") + concept = _get(obj, 'applies_on_concept') + facets = _get(obj, 'has_facets', []) # Safely check if the is_inverse flag is True is_inv = obj.get_is_inverse() if hasattr(obj, 'get_is_inverse') else getattr(obj, 'is_inverse', False) @@ -168,12 +167,14 @@ def _get(instance, prop_name, default=None): parts.append({'text': 'inverse of ', 'link': None, 'type': 'Text'}) parts.extend(self._parse_restriction(concept, language, _seen)) - if constraint: - parts.append({'text': f' with {constraint} ', 'link': None, 'type': 'Text'}) - else: - parts.append({'text': ' restricted by ', 'link': None, 'type': 'Text'}) - - parts.extend(self._parse_restriction(value, language, _seen)) + if facets: + parts.append({'text': '[', 'link': None, 'type': 'Text'}) + for i, (constraint, value) in enumerate(facets): + if i > 0: + parts.append({'text': ', ', 'link': None, 'type': 'Text'}) + parts.append({'text': f'{constraint} ', 'link': None, 'type': 'Text'}) + parts.extend(self._parse_restriction(value, language, _seen)) + parts.append({'text': ']', 'link': None, 'type': 'Text'}) return parts diff --git a/tests/test_datatype_restrictions.py b/tests/test_datatype_restrictions.py new file mode 100644 index 0000000..41e4533 --- /dev/null +++ b/tests/test_datatype_restrictions.py @@ -0,0 +1,113 @@ +"""Offline regressions for datatype facets in the reader and generated HTML.""" +from html.parser import HTMLParser + +import pytest +from rdflib import Graph, Namespace +from rdflib.compare import isomorphic +from rdflib.namespace import XSD + +from lode.builder import build_html +from lode.models import Datatype, DatatypeRestriction +from lode.reader import Reader + + +EX = Namespace("http://example.org/ranges#") +CASES = [ + ("actOrder", "integer", "[ xsd:minInclusive 1 ] [ xsd:maxInclusive 3 ]", + "integer[>= 1, <= 3]"), + ("stageOrder", "integer", "[ xsd:minInclusive 1 ] [ xsd:maxInclusive 17 ]", + "integer[>= 1, <= 17]"), + ("fitScore", "integer", "[ xsd:minInclusive -1 ] [ xsd:maxInclusive 4 ]", + "integer[>= -1, <= 4]"), + ("reversed", "integer", "[ xsd:maxInclusive 4 ] [ xsd:minInclusive -1 ]", + "integer[<= 4, >= -1]"), + ("exclusive", "decimal", "[ xsd:minExclusive 0.5 ] [ xsd:maxExclusive 9.5 ]", + "decimal[> 0.5, < 9.5]"), + ("zero", "integer", "[ xsd:minInclusive 0 ]", "integer[>= 0]"), + ("pattern", "string", '[ xsd:pattern "[0-9]+" ] [ xsd:minLength 1 ]', + "string[pattern [0-9]+, minLength 1]"), +] + + +@pytest.fixture +def range_reader(tmp_path): + declarations = "\n".join( + f"ex:{name} a owl:DatatypeProperty ; rdfs:range [ a rdfs:Datatype ; " + f"owl:onDatatype xsd:{datatype} ; owl:withRestrictions ( {facets} ) ] ." + for name, datatype, facets, _ in CASES + ) + path = tmp_path / "ranges.ttl" + path.write_text(""" + @prefix ex: . + @prefix owl: . + @prefix rdfs: . + @prefix xsd: . + a owl:Ontology . + """ + declarations, encoding="utf-8") + reader = Reader() + reader.load_instances(str(path), "owl") + return reader + + +@pytest.mark.parametrize("name,datatype,expected", + [(name, datatype, expected) for name, datatype, _, expected in CASES], + ids=[case[0] for case in CASES]) +def test_range_preserves_datatype_and_every_facet(range_reader, name, datatype, + expected): + viewer = range_reader.get_viewer() + data = viewer.get_view_data(str(EX[name])) + rendered = data["entities"][0]["relations"]["range"][0] + + assert rendered["text"] == expected + assert rendered["parts"][0]["link"] == str(XSD[datatype]) + + restrictions = { + instance for instances in range_reader._instance_cache.values() + for instance in instances if isinstance(instance, DatatypeRestriction) + } + assert len(restrictions) == len(CASES) + for restriction in restrictions: + assert isinstance(restriction.get_applies_on_concept(), Datatype) + + +class _RestrictionText(HTMLParser): + """Read visible restriction blocks without matching the hidden RDF snippets.""" + + def __init__(self, html): + super().__init__() + self.depth = 0 + self.blocks = [] + self.feed(html) + + def handle_starttag(self, tag, attrs): + if tag == "div": + if self.depth: + self.depth += 1 + elif "restriction-block" in dict(attrs).get("class", "").split(): + self.depth = 1 + self.blocks.append("") + + def handle_endtag(self, tag): + if tag == "div" and self.depth: + self.depth -= 1 + + def handle_data(self, text): + if self.depth: + self.blocks[-1] += text + + +def test_static_index_and_resource_pages_show_complete_ranges(range_reader, tmp_path): + out = tmp_path / "site" + build_html(range_reader.get_viewer(), out, reader=range_reader) + + def compact(text): + return "".join(text.split()) + + index = _RestrictionText((out / "index.html").read_text(encoding="utf-8")) + for name, _, _, expected in CASES: + page = out / "resources" / "ex" / f"{name}.html" + resource = _RestrictionText(page.read_text(encoding="utf-8")) + assert compact(expected) in [compact(block) for block in index.blocks] + assert compact(expected) in [compact(block) for block in resource.blocks] + + assert isomorphic(Graph().parse(out / "index.ttl"), range_reader.get_main_graph())