prograph 1.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prograph/__init__.py +36 -0
- prograph/__main__.py +5 -0
- prograph/_version.py +375 -0
- prograph/cli/__init__.py +1 -0
- prograph/cli/_iri_utils.py +124 -0
- prograph/cli/emit_genie_space.py +107 -0
- prograph/cli/generate_views.py +140 -0
- prograph/cli/main.py +420 -0
- prograph/cli/schema_inferrer.py +746 -0
- prograph/cli/ttl_loader.py +289 -0
- prograph/cli/upload_genie_space.py +84 -0
- prograph/config/__init__.py +27 -0
- prograph/config/yaml_config.py +848 -0
- prograph/demos/__init__.py +14 -0
- prograph/demos/turbofan/README.md +74 -0
- prograph/demos/turbofan/SCENARIO.md +209 -0
- prograph/demos/turbofan/__init__.py +75 -0
- prograph/demos/turbofan/create_tables.sql +206 -0
- prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
- prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
- prograph/demos/turbofan/demo.py +162 -0
- prograph/demos/turbofan/genie_qa_notebook.py +434 -0
- prograph/demos/turbofan/graph.yaml +1098 -0
- prograph/demos/turbofan/instance_graph_demo.py +32 -0
- prograph/demos/turbofan/load.py +223 -0
- prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
- prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
- prograph/demos/turbofan/payload-shapes.ttl +33 -0
- prograph/demos/turbofan/queries/example-queries.sparql +215 -0
- prograph/demos/turbofan/shapes.ttl +75 -0
- prograph/demos/turbofan/tables.py +106 -0
- prograph/demos/turbofan/turbofan_schema.py +393 -0
- prograph/demos/turbofan/validation_demo.py +153 -0
- prograph/describe.py +231 -0
- prograph/endpoint/__init__.py +12 -0
- prograph/endpoint/app.py +722 -0
- prograph/endpoint/cli.py +280 -0
- prograph/endpoint/credentials.py +240 -0
- prograph/endpoint/engines.py +418 -0
- prograph/endpoint/negotiate.py +101 -0
- prograph/endpoint/results.py +181 -0
- prograph/endpoint/service.py +31 -0
- prograph/engine.py +2718 -0
- prograph/execution.py +455 -0
- prograph/executors/__init__.py +6 -0
- prograph/executors/base.py +11 -0
- prograph/executors/databricks_sql_executor.py +51 -0
- prograph/executors/duckdb_executor.py +24 -0
- prograph/executors/mysql_executor.py +20 -0
- prograph/executors/oracle_executor.py +24 -0
- prograph/executors/pandas_executor.py +72 -0
- prograph/executors/postgresql_executor.py +35 -0
- prograph/executors/spark_executor.py +88 -0
- prograph/executors/sqlserver_executor.py +35 -0
- prograph/extras/__init__.py +1 -0
- prograph/extras/graphql/__init__.py +33 -0
- prograph/extras/graphql/execute.py +25 -0
- prograph/extras/graphql/schema.py +314 -0
- prograph/extras/instance_graph.py +559 -0
- prograph/genie/__init__.py +83 -0
- prograph/genie/databricks_uploader.py +306 -0
- prograph/genie/deploy.py +393 -0
- prograph/genie/formats.py +414 -0
- prograph/genie/instruction_generator.py +375 -0
- prograph/genie/sample_query_generator.py +256 -0
- prograph/genie/shacl_views.py +318 -0
- prograph/genie/space_emitter.py +329 -0
- prograph/genie/view_generator.py +628 -0
- prograph/genie/view_writer.py +172 -0
- prograph/graph/__init__.py +1 -0
- prograph/graph/ansi_session.py +348 -0
- prograph/graph/databricks_sql_graph.py +300 -0
- prograph/graph/drivers.py +143 -0
- prograph/graph/duckdb_graph.py +68 -0
- prograph/graph/mysql_graph.py +38 -0
- prograph/graph/oracle_graph.py +285 -0
- prograph/graph/pandas_graph.py +343 -0
- prograph/graph/postgresql_graph.py +644 -0
- prograph/graph/spark_graph.py +556 -0
- prograph/graph/sql_graph.py +83 -0
- prograph/graph/sqlserver_graph.py +72 -0
- prograph/hints.py +95 -0
- prograph/logging.py +550 -0
- prograph/mcp/__init__.py +29 -0
- prograph/mcp/__main__.py +180 -0
- prograph/mcp/bootstrap.py +98 -0
- prograph/mcp/server.py +601 -0
- prograph/mcp/sparql.py +397 -0
- prograph/mcp/tools.py +504 -0
- prograph/nlp/__init__.py +79 -0
- prograph/nlp/client.py +305 -0
- prograph/nlp/databricks_tools.py +369 -0
- prograph/nlp/graph_context.py +313 -0
- prograph/nlp/interface.py +652 -0
- prograph/nlp/prompts/__init__.py +19 -0
- prograph/nlp/prompts/examples.py +258 -0
- prograph/nlp/prompts/system.py +239 -0
- prograph/nlp/providers/__init__.py +14 -0
- prograph/nlp/providers/anthropic.py +274 -0
- prograph/nlp/providers/databricks.py +312 -0
- prograph/nlp/providers/openai.py +203 -0
- prograph/nlp/schema_context.py +78 -0
- prograph/ontology/__init__.py +53 -0
- prograph/ontology/alignment.py +542 -0
- prograph/ontology/hierarchy.py +310 -0
- prograph/ontology/imports.py +587 -0
- prograph/ontology/layer.py +991 -0
- prograph/ontology/skos.py +61 -0
- prograph/owl/__init__.py +27 -0
- prograph/owl/defined_classes.py +323 -0
- prograph/parameters.py +242 -0
- prograph/parser/__init__.py +1 -0
- prograph/parser/cypher/CypherLexer.py +836 -0
- prograph/parser/cypher/CypherListener.py +966 -0
- prograph/parser/cypher/CypherParser.py +10854 -0
- prograph/parser/cypher/CypherVisitor.py +543 -0
- prograph/parser/cypher/__init__.py +1 -0
- prograph/parser/sparql/SparqlLexer.py +801 -0
- prograph/parser/sparql/SparqlParser.py +10146 -0
- prograph/parser/sparql/SparqlParserListener.py +1056 -0
- prograph/parser/sparql/SparqlParserVisitor.py +593 -0
- prograph/parser/sparql/__init__.py +8 -0
- prograph/plan/__init__.py +3 -0
- prograph/plan/ir/__init__.py +1 -0
- prograph/plan/ir/casts.py +338 -0
- prograph/plan/ir/consistency.py +397 -0
- prograph/plan/ir/construct.py +90 -0
- prograph/plan/ir/cost.py +234 -0
- prograph/plan/ir/cypher_answer.py +1081 -0
- prograph/plan/ir/cypher_apoc.py +717 -0
- prograph/plan/ir/cypher_apoc_convert.py +505 -0
- prograph/plan/ir/cypher_apoc_date.py +845 -0
- prograph/plan/ir/cypher_apoc_map.py +496 -0
- prograph/plan/ir/cypher_apoc_meta.py +384 -0
- prograph/plan/ir/cypher_apoc_path.py +597 -0
- prograph/plan/ir/cypher_apoc_procedures.py +163 -0
- prograph/plan/ir/cypher_apoc_text.py +785 -0
- prograph/plan/ir/cypher_front.py +5474 -0
- prograph/plan/ir/cypher_functions.py +565 -0
- prograph/plan/ir/cypher_lists.py +935 -0
- prograph/plan/ir/cypher_maps.py +370 -0
- prograph/plan/ir/cypher_mixed.py +604 -0
- prograph/plan/ir/cypher_ontology.py +226 -0
- prograph/plan/ir/cypher_procedures.py +191 -0
- prograph/plan/ir/cypher_runtime_errors.py +107 -0
- prograph/plan/ir/cypher_temporal.py +1357 -0
- prograph/plan/ir/cypher_temporal_arith.py +339 -0
- prograph/plan/ir/cypher_values.py +546 -0
- prograph/plan/ir/cypher_write.py +612 -0
- prograph/plan/ir/dataset.py +643 -0
- prograph/plan/ir/dates.py +102 -0
- prograph/plan/ir/entry.py +992 -0
- prograph/plan/ir/expr.py +260 -0
- prograph/plan/ir/facts.py +1171 -0
- prograph/plan/ir/fresh.py +291 -0
- prograph/plan/ir/freshness.py +625 -0
- prograph/plan/ir/identity.py +797 -0
- prograph/plan/ir/java_datetime.py +265 -0
- prograph/plan/ir/java_regex.py +391 -0
- prograph/plan/ir/join_order.py +39 -0
- prograph/plan/ir/key_checks.py +433 -0
- prograph/plan/ir/keys.py +454 -0
- prograph/plan/ir/lower.py +5323 -0
- prograph/plan/ir/ops.py +619 -0
- prograph/plan/ir/owl_rl.py +1119 -0
- prograph/plan/ir/owl_rl_rules.py +725 -0
- prograph/plan/ir/profiles.py +694 -0
- prograph/plan/ir/ql.py +987 -0
- prograph/plan/ir/rdfs.py +342 -0
- prograph/plan/ir/rewrite.py +1782 -0
- prograph/plan/ir/saturate.py +339 -0
- prograph/plan/ir/semantics.py +103 -0
- prograph/plan/ir/slot.py +509 -0
- prograph/plan/ir/sparql_front.py +3418 -0
- prograph/plan/ir/strings.py +534 -0
- prograph/plan/ir/term_functions.py +274 -0
- prograph/plan/ir/terms.py +84 -0
- prograph/plan/ir/xpath_regex.py +264 -0
- prograph/plan/run_record.py +65 -0
- prograph/plan/sql/__init__.py +21 -0
- prograph/plan/sql/dialect.py +3726 -0
- prograph/plan/sql/mysql_serializer.py +103 -0
- prograph/plan/sql/names.py +65 -0
- prograph/plan/sql/oracle_serializer.py +306 -0
- prograph/plan/sql/pg_serializer.py +501 -0
- prograph/plan/sql/rel_algebra.py +781 -0
- prograph/plan/sql/sql_serializer.py +1419 -0
- prograph/plan/sql/sqlserver_serializer.py +603 -0
- prograph/provenance.py +222 -0
- prograph/r2rml/__init__.py +48 -0
- prograph/r2rml/catalog.py +259 -0
- prograph/r2rml/compile.py +372 -0
- prograph/r2rml/direct.py +140 -0
- prograph/r2rml/export.py +495 -0
- prograph/r2rml/model.py +180 -0
- prograph/r2rml/parser.py +546 -0
- prograph/r2rml/schema.py +120 -0
- prograph/read_only.py +122 -0
- prograph/results.py +157 -0
- prograph/rules/__init__.py +168 -0
- prograph/rules/__main__.py +32 -0
- prograph/schema/__init__.py +60 -0
- prograph/schema/change_set.py +50 -0
- prograph/schema/collations.py +198 -0
- prograph/schema/compile_schema.py +388 -0
- prograph/schema/context.py +845 -0
- prograph/schema/examples.py +234 -0
- prograph/schema/iri.py +817 -0
- prograph/schema/literals.py +94 -0
- prograph/schema/lpg_view.py +617 -0
- prograph/schema/mapping.py +1803 -0
- prograph/schema/maps_schema.py +40 -0
- prograph/schema/naming.py +77 -0
- prograph/schema/query_sources.py +59 -0
- prograph/schema/rows.py +215 -0
- prograph/schema/source_map.py +1103 -0
- prograph/schema/store_view.py +459 -0
- prograph/schema/types.py +569 -0
- prograph/schema/xsd.py +569 -0
- prograph/shacl/__init__.py +30 -0
- prograph/shacl/dqv.py +58 -0
- prograph/shacl/generate.py +255 -0
- prograph/shacl/report.py +138 -0
- prograph/shacl/validator.py +164 -0
- prograph/store.py +1737 -0
- prograph/utils/__init__.py +6 -0
- prograph/utils/exceptions.py +308 -0
- prograph/utils/helpers.py +126 -0
- prograph/warnings.py +46 -0
- prograph/writes.py +369 -0
- prograph-1.3.3.dist-info/METADATA +281 -0
- prograph-1.3.3.dist-info/RECORD +237 -0
- prograph-1.3.3.dist-info/WHEEL +5 -0
- prograph-1.3.3.dist-info/entry_points.txt +3 -0
- prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
- prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
- prograph-1.3.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,991 @@
|
|
|
1
|
+
"""OntologyLayer for semantic reasoning and query expansion.
|
|
2
|
+
|
|
3
|
+
This module provides the main OntologyLayer class that loads OWL/RDFS
|
|
4
|
+
ontologies and integrates with ProGraph's query pipeline.
|
|
5
|
+
|
|
6
|
+
An owl:imports is read from a local file, never fetched from the network; one not resolved raises
|
|
7
|
+
ImportResolutionError unless on_unsupported="ignore".
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations # `str | Path` in annotations: Python 3.9 evaluates them otherwise
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, List, Optional, Set, Any, TYPE_CHECKING
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import rdflib
|
|
19
|
+
from rdflib import RDF, RDFS, OWL, Namespace, URIRef
|
|
20
|
+
from rdflib.namespace import NamespaceManager
|
|
21
|
+
RDFLIB_AVAILABLE = True
|
|
22
|
+
except ImportError:
|
|
23
|
+
RDFLIB_AVAILABLE = False
|
|
24
|
+
rdflib = None
|
|
25
|
+
URIRef = None # For type hints when rdflib not installed
|
|
26
|
+
|
|
27
|
+
from prograph.ontology.hierarchy import ClassHierarchy
|
|
28
|
+
from prograph.rules import module_home
|
|
29
|
+
|
|
30
|
+
module_home("class-hierarchy", "The class hierarchy (query time)",
|
|
31
|
+
terms=("subclass", "rdfs:subClassOf", "class hierarchy", "class IRI", "get_superclasses"))
|
|
32
|
+
|
|
33
|
+
module_home("subproperty-hierarchy", "The sub-property hierarchy (query time)",
|
|
34
|
+
terms=("subPropertyOf", "sub-property", "property hierarchy", "prp-spo1"))
|
|
35
|
+
|
|
36
|
+
# The OWL property kinds that are object properties (OWL 2 RDF mapping:
|
|
37
|
+
# each is declared with owl:ObjectProperty's meaning).
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from prograph.schema import GraphSchema
|
|
40
|
+
if not RDFLIB_AVAILABLE:
|
|
41
|
+
from rdflib import URIRef # noqa: F401 - for type checking only
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _on_unsupported(value: str) -> str:
|
|
48
|
+
"""`on_unsupported`, checked: one of `profiles.ON_UNSUPPORTED`."""
|
|
49
|
+
from prograph.plan.ir.profiles import ON_UNSUPPORTED
|
|
50
|
+
if value not in ON_UNSUPPORTED:
|
|
51
|
+
raise ValueError(f"on_unsupported is one of {', '.join(ON_UNSUPPORTED)}, not {value!r}")
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class OntologyBindingError(Exception):
|
|
56
|
+
"""Raised when ontology binding to schema fails."""
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class PropertyMetadata:
|
|
62
|
+
"""Metadata about an ontology property.
|
|
63
|
+
|
|
64
|
+
Attributes:
|
|
65
|
+
name: Local name of the property
|
|
66
|
+
uri: Full URI of the property
|
|
67
|
+
domain: Set of class names valid as subject
|
|
68
|
+
range: Set of class names valid as object
|
|
69
|
+
is_symmetric: Property where P(a,b) implies P(b,a)
|
|
70
|
+
is_transitive: Property where P(a,b) and P(b,c) implies P(a,c)
|
|
71
|
+
is_functional: Property with at most one value per subject
|
|
72
|
+
inverse_of: Name of inverse property, if defined
|
|
73
|
+
super_properties: Parent properties (rdfs:subPropertyOf)
|
|
74
|
+
equivalent_properties: Properties declared equivalent via
|
|
75
|
+
``owl:equivalentProperty``. Symmetric: if A is declared
|
|
76
|
+
equivalent to B, both records reference each other.
|
|
77
|
+
property_chain: For properties defined by an
|
|
78
|
+
``owl:propertyChainAxiom``, the ordered list of property
|
|
79
|
+
local names whose composition produces this property.
|
|
80
|
+
Example: ``monitors`` with chain ``[monitors, isPartOf]``
|
|
81
|
+
means ``monitors ∘ isPartOf → monitors``.
|
|
82
|
+
None when the property has no chain axiom.
|
|
83
|
+
"""
|
|
84
|
+
name: str
|
|
85
|
+
uri: str
|
|
86
|
+
domain: Set[str] = field(default_factory=set)
|
|
87
|
+
range: Set[str] = field(default_factory=set)
|
|
88
|
+
is_symmetric: bool = False
|
|
89
|
+
is_transitive: bool = False
|
|
90
|
+
is_functional: bool = False
|
|
91
|
+
inverse_of: Optional[str] = None
|
|
92
|
+
super_properties: Set[str] = field(default_factory=set)
|
|
93
|
+
equivalent_properties: Set[str] = field(default_factory=set)
|
|
94
|
+
property_chain: Optional[List[str]] = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class OntologyLayer:
|
|
98
|
+
"""Semantic layer that provides ontology-based reasoning.
|
|
99
|
+
|
|
100
|
+
OntologyLayer loads OWL/RDFS ontologies and provides:
|
|
101
|
+
- Class hierarchy expansion (subClassOf reasoning)
|
|
102
|
+
- Property domain/range validation
|
|
103
|
+
- Query rewriting for semantic expansion
|
|
104
|
+
|
|
105
|
+
Usage:
|
|
106
|
+
>>> ontology = OntologyLayer.from_owl('domain.owl')
|
|
107
|
+
>>> ontology.bind_to_schema(graph_schema) # Optional validation
|
|
108
|
+
>>>
|
|
109
|
+
>>> # Query expansion
|
|
110
|
+
>>> ontology.expand_labels(['Person'])
|
|
111
|
+
['Person', 'Employee', 'Manager', 'Customer']
|
|
112
|
+
>>>
|
|
113
|
+
>>> # Check hierarchy
|
|
114
|
+
>>> ontology.get_subclasses('Message')
|
|
115
|
+
{'Message', 'Post', 'Comment'}
|
|
116
|
+
|
|
117
|
+
Integration with ProGraph:
|
|
118
|
+
>>> engine = ProGraph(
|
|
119
|
+
... backend='spark',
|
|
120
|
+
... schema=schema,
|
|
121
|
+
... ontology=ontology, # Enables query expansion
|
|
122
|
+
... dataframes={...}
|
|
123
|
+
... )
|
|
124
|
+
>>> # MATCH (m:Message) automatically expands to MATCH (m:Message|Post|Comment)
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(self):
|
|
128
|
+
if not RDFLIB_AVAILABLE:
|
|
129
|
+
raise ImportError(
|
|
130
|
+
"rdflib is required for OntologyLayer. "
|
|
131
|
+
"Install it with: pip install rdflib"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
self._graph: rdflib.Graph = rdflib.Graph()
|
|
135
|
+
self._class_hierarchy: ClassHierarchy = ClassHierarchy()
|
|
136
|
+
self._properties: Dict[str, PropertyMetadata] = {}
|
|
137
|
+
self._namespace_prefixes: Dict[str, Namespace] = {}
|
|
138
|
+
self._bound_schema: Optional['GraphSchema'] = None
|
|
139
|
+
self._is_loaded: bool = False
|
|
140
|
+
self._imported_ontologies: List[str] = []
|
|
141
|
+
self._failed_imports: List[str] = []
|
|
142
|
+
# owl:sameAs equivalence groups: IRI -> canonical IRI
|
|
143
|
+
self._same_as: Dict[str, str] = {}
|
|
144
|
+
self._same_as_groups: Dict[str, Set[str]] = {} # canonical -> {all IRIs}
|
|
145
|
+
# owl:equivalentClass, class -> set of equivalent classes
|
|
146
|
+
# (symmetric; each key maps to all its equivalents, excluding self)
|
|
147
|
+
self._equivalent_classes: Dict[str, Set[str]] = {}
|
|
148
|
+
# The class hierarchy by IRI (`subclass_iris`): each class IRI's
|
|
149
|
+
# direct rdfs:subClassOf children, and the class IRIs of each local
|
|
150
|
+
# name. `_class_hierarchy` is keyed by local name, where two classes
|
|
151
|
+
# of one name in different namespaces are one.
|
|
152
|
+
self._class_iris: Set[str] = set()
|
|
153
|
+
self._children_by_iri: Dict[str, Set[str]] = {}
|
|
154
|
+
self._iris_by_name: Dict[str, Set[str]] = {}
|
|
155
|
+
# What an engine does with axioms its OWL profile does not answer (`profiles.check`):
|
|
156
|
+
# "error" (raise OWLProfileError) or "ignore" (drop them; engine.ontology_report() lists them).
|
|
157
|
+
self.on_unsupported = "error"
|
|
158
|
+
|
|
159
|
+
@classmethod
|
|
160
|
+
def from_owl(
|
|
161
|
+
cls,
|
|
162
|
+
path: str | Path,
|
|
163
|
+
cache_dir: Optional[str | Path] = None,
|
|
164
|
+
imports: Optional[Dict[str, str | Path]] = None,
|
|
165
|
+
on_unsupported: str = "error",
|
|
166
|
+
) -> 'OntologyLayer':
|
|
167
|
+
"""Load ontology from OWL/RDFS file.
|
|
168
|
+
|
|
169
|
+
Supported formats (auto-detected by extension):
|
|
170
|
+
- .owl, .rdf: RDF/XML format
|
|
171
|
+
- .ttl: Turtle format
|
|
172
|
+
- .n3: N3 format
|
|
173
|
+
- .nt: N-Triples format
|
|
174
|
+
- .jsonld: JSON-LD format
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
path: Path to ontology file
|
|
178
|
+
cache_dir: Directory of well-known ontologies' files the user put
|
|
179
|
+
there (nothing is downloaded). If None, uses
|
|
180
|
+
~/.prograph/ontology_cache
|
|
181
|
+
imports: ``{import IRI: file path}``: where each named
|
|
182
|
+
``owl:imports`` is read from, before any catalog.
|
|
183
|
+
on_unsupported: what an engine does with the axioms its OWL
|
|
184
|
+
profile does not answer (outside the W3C profile, or inside
|
|
185
|
+
it and not built yet): ``"error"`` (default) raises
|
|
186
|
+
:class:`~prograph.utils.exceptions.OWLProfileError` when the
|
|
187
|
+
engine is built, naming each axiom; ``"ignore"`` drops them
|
|
188
|
+
and ``engine.ontology_report()`` lists what was dropped.
|
|
189
|
+
Loading never fails for profile reasons: the profile is the
|
|
190
|
+
engine's (``ProGraph(..., profile=)``). The same setting
|
|
191
|
+
decides an ``owl:imports`` that cannot be resolved (below).
|
|
192
|
+
|
|
193
|
+
An ``owl:imports`` is read from a local file and never fetched from
|
|
194
|
+
the network: from ``imports=``, from a ``catalog-v001.xml`` beside
|
|
195
|
+
this file (the OASIS XML Catalog Protege writes), from
|
|
196
|
+
an ``owl:Ontology`` of that IRI already in the graph, from a
|
|
197
|
+
``file://`` IRI, or from a file beside this one named as the imported
|
|
198
|
+
IRI's last path segment. An import not resolved raises
|
|
199
|
+
:class:`~prograph.ontology.imports.ImportResolutionError` naming it
|
|
200
|
+
and how to map it; ``on_unsupported="ignore"`` loads the ontology
|
|
201
|
+
without it (``failed_imports`` lists it). A catalog or ``imports=``
|
|
202
|
+
entry that names a missing file is always an error.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
Configured OntologyLayer instance
|
|
206
|
+
|
|
207
|
+
Raises:
|
|
208
|
+
FileNotFoundError: If the file doesn't exist
|
|
209
|
+
ValueError: If the format cannot be determined
|
|
210
|
+
ImportResolutionError: If an owl:imports is not resolved and
|
|
211
|
+
on_unsupported is "error"
|
|
212
|
+
|
|
213
|
+
Example:
|
|
214
|
+
>>> # parts.ttl beside ic_domain.ttl holds its owl:imports
|
|
215
|
+
>>> ontology = OntologyLayer.from_owl('ic_domain.ttl')
|
|
216
|
+
>>> print(ontology.imported_ontologies)
|
|
217
|
+
['http://example.org/parts.ttl']
|
|
218
|
+
"""
|
|
219
|
+
ontology = cls()
|
|
220
|
+
path = Path(path)
|
|
221
|
+
|
|
222
|
+
if not path.exists():
|
|
223
|
+
raise FileNotFoundError(f"Ontology file not found: {path}")
|
|
224
|
+
|
|
225
|
+
# Determine format from extension
|
|
226
|
+
format_map = {
|
|
227
|
+
'.owl': 'xml',
|
|
228
|
+
'.rdf': 'xml',
|
|
229
|
+
'.ttl': 'turtle',
|
|
230
|
+
'.n3': 'n3',
|
|
231
|
+
'.nt': 'nt',
|
|
232
|
+
'.jsonld': 'json-ld'
|
|
233
|
+
}
|
|
234
|
+
file_format = format_map.get(path.suffix.lower())
|
|
235
|
+
if file_format is None:
|
|
236
|
+
raise ValueError(
|
|
237
|
+
f"Unknown ontology format for extension: {path.suffix}. "
|
|
238
|
+
f"Supported: {list(format_map.keys())}"
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
from prograph.ontology.imports import parse_file
|
|
242
|
+
parse_file(ontology._graph, path)
|
|
243
|
+
|
|
244
|
+
ontology.on_unsupported = _on_unsupported(on_unsupported)
|
|
245
|
+
ontology._resolve_imports(
|
|
246
|
+
base_path=path.parent,
|
|
247
|
+
cache_dir=Path(cache_dir) if cache_dir else None,
|
|
248
|
+
imports=imports,
|
|
249
|
+
source=path,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
ontology._extract_ontology()
|
|
253
|
+
ontology._is_loaded = True
|
|
254
|
+
return ontology
|
|
255
|
+
|
|
256
|
+
def saturation_report(self):
|
|
257
|
+
"""What 1.0 does with this ontology (`prograph.plan.ir.saturate.SaturationReport`): the
|
|
258
|
+
axiom kinds applied to the maps (subClassOf, subPropertyOf, the equivalences, domain and
|
|
259
|
+
range) and the kinds not applied, each with a count and examples."""
|
|
260
|
+
from prograph.plan.ir.saturate import read_ontology
|
|
261
|
+
return read_ontology(self._graph).report
|
|
262
|
+
|
|
263
|
+
def _resolve_imports(
|
|
264
|
+
self,
|
|
265
|
+
base_path: Optional[Path] = None,
|
|
266
|
+
cache_dir: Optional[Path] = None,
|
|
267
|
+
imports: Optional[Dict[str, str | Path]] = None,
|
|
268
|
+
source: Optional[Path] = None,
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Resolve owl:imports statements in the loaded ontology from local files; an import not resolved
|
|
271
|
+
raises `ImportResolutionError` unless ``on_unsupported`` is "ignore". Nothing is fetched.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
base_path: Base path for resolving relative imports
|
|
275
|
+
cache_dir: Directory of well-known ontologies' files
|
|
276
|
+
imports: {IRI: file path}, before any catalog
|
|
277
|
+
source: the ontology file loaded (named in the error)
|
|
278
|
+
"""
|
|
279
|
+
from prograph.ontology.imports import ImportResolver, OntologyCache
|
|
280
|
+
|
|
281
|
+
if not any(True for _ in self._graph.objects(predicate=rdflib.OWL.imports)):
|
|
282
|
+
return
|
|
283
|
+
cache = OntologyCache(cache_dir) if cache_dir else OntologyCache()
|
|
284
|
+
resolver = ImportResolver(
|
|
285
|
+
cache=cache,
|
|
286
|
+
imports=imports,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
imported, failed = resolver.resolve_imports(
|
|
290
|
+
self._graph,
|
|
291
|
+
base_path=base_path
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
self._imported_ontologies = imported
|
|
295
|
+
self._failed_imports = failed
|
|
296
|
+
|
|
297
|
+
if imported:
|
|
298
|
+
logger.info(f"Resolved {len(imported)} imports: {imported}")
|
|
299
|
+
if failed and self.on_unsupported == "error":
|
|
300
|
+
from prograph.ontology.imports import ImportResolutionError
|
|
301
|
+
where = f"catalog-v001.xml beside {source}" if source else "a catalog-v001.xml beside the file"
|
|
302
|
+
raise ImportResolutionError(
|
|
303
|
+
"owl:imports not resolved: " + ", ".join(failed) + f". An import is never fetched from the "
|
|
304
|
+
f"network. To map it, add it to {where} (<uri name=\"IRI\" uri=\"path\"/>), or pass "
|
|
305
|
+
"imports={IRI: path}; or put the imported ontology's file beside the ontology (named as the "
|
|
306
|
+
"IRI's last path segment), or add its triples to the graph (an owl:Ontology of that IRI); or "
|
|
307
|
+
"load with on_unsupported='ignore' to leave the import out (OntologyLayer.failed_imports then "
|
|
308
|
+
"lists it).",
|
|
309
|
+
imports=tuple(failed))
|
|
310
|
+
if failed:
|
|
311
|
+
logger.warning(f"Ignoring {len(failed)} unresolved imports: {failed}")
|
|
312
|
+
|
|
313
|
+
@classmethod
|
|
314
|
+
def from_rdflib_graph(cls, graph: 'rdflib.Graph', on_unsupported: str = "error",
|
|
315
|
+
imports: Optional[Dict[str, str | Path]] = None) -> 'OntologyLayer':
|
|
316
|
+
"""Create OntologyLayer from existing rdflib Graph.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
graph: Pre-populated rdflib Graph
|
|
320
|
+
on_unsupported: as for :meth:`from_owl`
|
|
321
|
+
imports: as for :meth:`from_owl`
|
|
322
|
+
|
|
323
|
+
Returns:
|
|
324
|
+
Configured OntologyLayer instance
|
|
325
|
+
"""
|
|
326
|
+
ontology = cls()
|
|
327
|
+
ontology.on_unsupported = _on_unsupported(on_unsupported)
|
|
328
|
+
ontology._graph = graph
|
|
329
|
+
ontology._resolve_imports(imports=imports)
|
|
330
|
+
ontology._extract_ontology()
|
|
331
|
+
ontology._is_loaded = True
|
|
332
|
+
return ontology
|
|
333
|
+
|
|
334
|
+
@classmethod
|
|
335
|
+
def from_turtle(cls, turtle_str: str, on_unsupported: str = "error",
|
|
336
|
+
imports: Optional[Dict[str, str | Path]] = None) -> 'OntologyLayer':
|
|
337
|
+
"""Create OntologyLayer from Turtle string.
|
|
338
|
+
|
|
339
|
+
Useful for testing or programmatic ontology creation.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
turtle_str: Ontology in Turtle format
|
|
343
|
+
on_unsupported: as for :meth:`from_owl`
|
|
344
|
+
imports: as for :meth:`from_owl`
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
Configured OntologyLayer instance
|
|
348
|
+
"""
|
|
349
|
+
ontology = cls()
|
|
350
|
+
ontology.on_unsupported = _on_unsupported(on_unsupported)
|
|
351
|
+
ontology._graph.parse(data=turtle_str, format='turtle')
|
|
352
|
+
ontology._resolve_imports(imports=imports)
|
|
353
|
+
ontology._extract_ontology()
|
|
354
|
+
ontology._is_loaded = True
|
|
355
|
+
return ontology
|
|
356
|
+
|
|
357
|
+
def _extract_ontology(self) -> None:
|
|
358
|
+
"""Extract class hierarchy and property metadata from the RDF graph."""
|
|
359
|
+
self._extract_namespaces()
|
|
360
|
+
self._extract_classes()
|
|
361
|
+
self._extract_properties()
|
|
362
|
+
self._extract_same_as()
|
|
363
|
+
self._class_hierarchy.build_closures()
|
|
364
|
+
|
|
365
|
+
def _extract_namespaces(self) -> None:
|
|
366
|
+
"""Extract namespace prefixes from the graph."""
|
|
367
|
+
for prefix, namespace in self._graph.namespaces():
|
|
368
|
+
if prefix:
|
|
369
|
+
self._namespace_prefixes[prefix] = Namespace(namespace)
|
|
370
|
+
|
|
371
|
+
def _extract_classes(self) -> None:
|
|
372
|
+
"""Extract OWL/RDFS classes and their hierarchy."""
|
|
373
|
+
# Find all classes (owl:Class or rdfs:Class)
|
|
374
|
+
for class_uri in self._graph.subjects(RDF.type, OWL.Class):
|
|
375
|
+
if isinstance(class_uri, URIRef):
|
|
376
|
+
class_name = self._get_local_name(class_uri)
|
|
377
|
+
self._class_hierarchy.add_class(class_name, str(class_uri))
|
|
378
|
+
|
|
379
|
+
for class_uri in self._graph.subjects(RDF.type, RDFS.Class):
|
|
380
|
+
if isinstance(class_uri, URIRef):
|
|
381
|
+
class_name = self._get_local_name(class_uri)
|
|
382
|
+
self._class_hierarchy.add_class(class_name, str(class_uri))
|
|
383
|
+
|
|
384
|
+
# Extract subClassOf relationships
|
|
385
|
+
for child_uri, _, parent_uri in self._graph.triples((None, RDFS.subClassOf, None)):
|
|
386
|
+
if isinstance(child_uri, URIRef) and isinstance(parent_uri, URIRef):
|
|
387
|
+
child_name = self._get_local_name(child_uri)
|
|
388
|
+
parent_name = self._get_local_name(parent_uri)
|
|
389
|
+
self._class_hierarchy.add_subclass_relation(child_name, parent_name)
|
|
390
|
+
self._children_by_iri.setdefault(str(parent_uri), set()).add(str(child_uri))
|
|
391
|
+
self._class_iris.update((str(child_uri), str(parent_uri)))
|
|
392
|
+
|
|
393
|
+
for kind in (OWL.Class, RDFS.Class):
|
|
394
|
+
for class_uri in self._graph.subjects(RDF.type, kind):
|
|
395
|
+
if isinstance(class_uri, URIRef):
|
|
396
|
+
self._class_iris.add(str(class_uri))
|
|
397
|
+
for iri in self._class_iris:
|
|
398
|
+
self._iris_by_name.setdefault(self._get_local_name(URIRef(iri)), set()).add(iri)
|
|
399
|
+
|
|
400
|
+
# Extract owl:equivalentClass declarations (symmetric).
|
|
401
|
+
for a_uri, _, b_uri in self._graph.triples((None, OWL.equivalentClass, None)):
|
|
402
|
+
if isinstance(a_uri, URIRef) and isinstance(b_uri, URIRef):
|
|
403
|
+
a = self._get_local_name(a_uri)
|
|
404
|
+
b = self._get_local_name(b_uri)
|
|
405
|
+
if a == b:
|
|
406
|
+
continue
|
|
407
|
+
self._equivalent_classes.setdefault(a, set()).add(b)
|
|
408
|
+
self._equivalent_classes.setdefault(b, set()).add(a)
|
|
409
|
+
|
|
410
|
+
def _extract_properties(self) -> None:
|
|
411
|
+
"""Extract OWL/RDFS properties and their characteristics."""
|
|
412
|
+
# Find all object properties
|
|
413
|
+
for prop_uri in self._graph.subjects(RDF.type, OWL.ObjectProperty):
|
|
414
|
+
if isinstance(prop_uri, URIRef):
|
|
415
|
+
self._extract_property(prop_uri)
|
|
416
|
+
|
|
417
|
+
# Also check for rdfs:Property
|
|
418
|
+
for prop_uri in self._graph.subjects(RDF.type, RDF.Property):
|
|
419
|
+
if isinstance(prop_uri, URIRef):
|
|
420
|
+
self._extract_property(prop_uri)
|
|
421
|
+
|
|
422
|
+
# Property chains can declare a property without any owl:ObjectProperty
|
|
423
|
+
# type assertion. Pick those up via the chain axiom as the trigger.
|
|
424
|
+
for prop_uri in self._graph.subjects(OWL.propertyChainAxiom, None):
|
|
425
|
+
if isinstance(prop_uri, URIRef):
|
|
426
|
+
self._extract_property(prop_uri)
|
|
427
|
+
|
|
428
|
+
# A property axiom implies a property even without a type assertion:
|
|
429
|
+
# both ends of rdfs:subPropertyOf, and anything typed transitive or
|
|
430
|
+
# symmetric. Skipping them left `ex:closelyKnows rdfs:subPropertyOf
|
|
431
|
+
# ex:knows` unexpanded and prp-spo1 silent. Datatype
|
|
432
|
+
# properties stay out, as before.
|
|
433
|
+
implied = set()
|
|
434
|
+
for sub, sup in self._graph.subject_objects(RDFS.subPropertyOf):
|
|
435
|
+
implied.update((sub, sup))
|
|
436
|
+
for kind in (OWL.TransitiveProperty, OWL.SymmetricProperty):
|
|
437
|
+
implied.update(self._graph.subjects(RDF.type, kind))
|
|
438
|
+
for prop_uri in implied:
|
|
439
|
+
if (isinstance(prop_uri, URIRef)
|
|
440
|
+
and (prop_uri, RDF.type, OWL.DatatypeProperty) not in self._graph):
|
|
441
|
+
self._extract_property(prop_uri)
|
|
442
|
+
|
|
443
|
+
# Reflect equivalent properties symmetrically, if the OWL file
|
|
444
|
+
# only declares one direction (A owl:equivalentProperty B), make
|
|
445
|
+
# sure B's metadata also records A. Same for inverseOf.
|
|
446
|
+
self._reflect_symmetric_property_axioms()
|
|
447
|
+
|
|
448
|
+
def _reflect_symmetric_property_axioms(self) -> None:
|
|
449
|
+
"""Ensure equivalentProperty and inverseOf relations are bidirectional.
|
|
450
|
+
|
|
451
|
+
OWL semantics: ``owl:equivalentProperty`` is symmetric and
|
|
452
|
+
``owl:inverseOf`` declares a paired inverse. Some ontology files
|
|
453
|
+
only assert one direction, so we fix up the metadata after the
|
|
454
|
+
initial extraction pass.
|
|
455
|
+
"""
|
|
456
|
+
# Snapshot the equivalence/inverse claims, then apply reflections.
|
|
457
|
+
equiv_pairs = []
|
|
458
|
+
inverse_pairs = []
|
|
459
|
+
for name, md in self._properties.items():
|
|
460
|
+
for other in md.equivalent_properties:
|
|
461
|
+
equiv_pairs.append((name, other))
|
|
462
|
+
if md.inverse_of:
|
|
463
|
+
inverse_pairs.append((name, md.inverse_of))
|
|
464
|
+
|
|
465
|
+
for a, b in equiv_pairs:
|
|
466
|
+
if b in self._properties:
|
|
467
|
+
self._properties[b].equivalent_properties.add(a)
|
|
468
|
+
|
|
469
|
+
for a, b in inverse_pairs:
|
|
470
|
+
if b in self._properties and self._properties[b].inverse_of is None:
|
|
471
|
+
self._properties[b].inverse_of = a
|
|
472
|
+
|
|
473
|
+
def _parse_rdf_list(self, node) -> List:
|
|
474
|
+
"""Materialize an ``rdf:List`` into a Python list of nodes.
|
|
475
|
+
|
|
476
|
+
Returns an empty list when ``node`` is ``rdf:nil`` or not a valid
|
|
477
|
+
list. Used by ``owl:propertyChainAxiom`` parsing.
|
|
478
|
+
"""
|
|
479
|
+
if node is None or node == RDF.nil:
|
|
480
|
+
return []
|
|
481
|
+
from rdflib.collection import Collection
|
|
482
|
+
try:
|
|
483
|
+
return list(Collection(self._graph, node))
|
|
484
|
+
except Exception:
|
|
485
|
+
return []
|
|
486
|
+
|
|
487
|
+
def _extract_property(self, prop_uri: URIRef) -> None:
|
|
488
|
+
"""Extract metadata for a single property."""
|
|
489
|
+
prop_name = self._get_local_name(prop_uri)
|
|
490
|
+
|
|
491
|
+
if prop_name in self._properties:
|
|
492
|
+
return # Already processed
|
|
493
|
+
|
|
494
|
+
metadata = PropertyMetadata(
|
|
495
|
+
name=prop_name,
|
|
496
|
+
uri=str(prop_uri)
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
# Extract domain
|
|
500
|
+
for domain_uri in self._graph.objects(prop_uri, RDFS.domain):
|
|
501
|
+
if isinstance(domain_uri, URIRef):
|
|
502
|
+
metadata.domain.add(self._get_local_name(domain_uri))
|
|
503
|
+
|
|
504
|
+
# Extract range
|
|
505
|
+
for range_uri in self._graph.objects(prop_uri, RDFS.range):
|
|
506
|
+
if isinstance(range_uri, URIRef):
|
|
507
|
+
metadata.range.add(self._get_local_name(range_uri))
|
|
508
|
+
|
|
509
|
+
# Check for symmetric property
|
|
510
|
+
if (prop_uri, RDF.type, OWL.SymmetricProperty) in self._graph:
|
|
511
|
+
metadata.is_symmetric = True
|
|
512
|
+
|
|
513
|
+
# Check for transitive property
|
|
514
|
+
if (prop_uri, RDF.type, OWL.TransitiveProperty) in self._graph:
|
|
515
|
+
metadata.is_transitive = True
|
|
516
|
+
|
|
517
|
+
# Check for functional property
|
|
518
|
+
if (prop_uri, RDF.type, OWL.FunctionalProperty) in self._graph:
|
|
519
|
+
metadata.is_functional = True
|
|
520
|
+
|
|
521
|
+
# Check for inverse property
|
|
522
|
+
for inverse_uri in self._graph.objects(prop_uri, OWL.inverseOf):
|
|
523
|
+
if isinstance(inverse_uri, URIRef):
|
|
524
|
+
metadata.inverse_of = self._get_local_name(inverse_uri)
|
|
525
|
+
|
|
526
|
+
# Check for super properties
|
|
527
|
+
for super_uri in self._graph.objects(prop_uri, RDFS.subPropertyOf):
|
|
528
|
+
if isinstance(super_uri, URIRef):
|
|
529
|
+
metadata.super_properties.add(self._get_local_name(super_uri))
|
|
530
|
+
|
|
531
|
+
# Check for equivalent properties (owl:equivalentProperty)
|
|
532
|
+
for equiv_uri in self._graph.objects(prop_uri, OWL.equivalentProperty):
|
|
533
|
+
if isinstance(equiv_uri, URIRef):
|
|
534
|
+
metadata.equivalent_properties.add(self._get_local_name(equiv_uri))
|
|
535
|
+
|
|
536
|
+
# Check for property chain axiom (owl:propertyChainAxiom)
|
|
537
|
+
# The chain is an rdf:List of property URIs.
|
|
538
|
+
for chain_node in self._graph.objects(prop_uri, OWL.propertyChainAxiom):
|
|
539
|
+
chain = self._parse_rdf_list(chain_node)
|
|
540
|
+
if chain:
|
|
541
|
+
metadata.property_chain = [
|
|
542
|
+
self._get_local_name(p) for p in chain
|
|
543
|
+
if isinstance(p, URIRef)
|
|
544
|
+
]
|
|
545
|
+
# OWL allows multiple chain axioms per property, but our
|
|
546
|
+
# PropertyMetadata stores a single chain. Common practice
|
|
547
|
+
# is one chain per property; warn or accept the first.
|
|
548
|
+
break
|
|
549
|
+
|
|
550
|
+
self._properties[prop_name] = metadata
|
|
551
|
+
|
|
552
|
+
def _extract_same_as(self) -> None:
|
|
553
|
+
"""Extract owl:sameAs equivalences from the RDF graph.
|
|
554
|
+
|
|
555
|
+
Builds a union-find structure mapping each IRI to a canonical
|
|
556
|
+
representative. Queries for any IRI in a sameAs group will
|
|
557
|
+
resolve to the same canonical entity.
|
|
558
|
+
"""
|
|
559
|
+
# Collect all sameAs pairs
|
|
560
|
+
pairs = []
|
|
561
|
+
for subj, _, obj in self._graph.triples((None, OWL.sameAs, None)):
|
|
562
|
+
if isinstance(subj, URIRef) and isinstance(obj, URIRef):
|
|
563
|
+
pairs.append((str(subj), str(obj)))
|
|
564
|
+
|
|
565
|
+
if not pairs:
|
|
566
|
+
return
|
|
567
|
+
|
|
568
|
+
# Build equivalence groups using union-find
|
|
569
|
+
parent: Dict[str, str] = {}
|
|
570
|
+
|
|
571
|
+
def find(x: str) -> str:
|
|
572
|
+
while parent.get(x, x) != x:
|
|
573
|
+
parent[x] = parent.get(parent[x], parent[x])
|
|
574
|
+
x = parent[x]
|
|
575
|
+
return x
|
|
576
|
+
|
|
577
|
+
def union(a: str, b: str) -> None:
|
|
578
|
+
ra, rb = find(a), find(b)
|
|
579
|
+
if ra != rb:
|
|
580
|
+
parent[ra] = rb
|
|
581
|
+
|
|
582
|
+
for a, b in pairs:
|
|
583
|
+
if a not in parent:
|
|
584
|
+
parent[a] = a
|
|
585
|
+
if b not in parent:
|
|
586
|
+
parent[b] = b
|
|
587
|
+
union(a, b)
|
|
588
|
+
|
|
589
|
+
# Build canonical mapping and groups
|
|
590
|
+
for iri in parent:
|
|
591
|
+
canonical = find(iri)
|
|
592
|
+
self._same_as[iri] = canonical
|
|
593
|
+
if canonical not in self._same_as_groups:
|
|
594
|
+
self._same_as_groups[canonical] = set()
|
|
595
|
+
self._same_as_groups[canonical].add(iri)
|
|
596
|
+
|
|
597
|
+
def _get_local_name(self, uri: URIRef) -> str:
|
|
598
|
+
"""Extract local name from a URI.
|
|
599
|
+
|
|
600
|
+
Args:
|
|
601
|
+
uri: Full URI reference
|
|
602
|
+
|
|
603
|
+
Returns:
|
|
604
|
+
Local name (part after # or last /)
|
|
605
|
+
"""
|
|
606
|
+
uri_str = str(uri)
|
|
607
|
+
# Try fragment identifier first
|
|
608
|
+
if '#' in uri_str:
|
|
609
|
+
return uri_str.split('#')[-1]
|
|
610
|
+
# Fall back to path component
|
|
611
|
+
return uri_str.rsplit('/', 1)[-1]
|
|
612
|
+
|
|
613
|
+
def bind_to_schema(
|
|
614
|
+
self,
|
|
615
|
+
schema: 'GraphSchema',
|
|
616
|
+
strict: bool = False
|
|
617
|
+
) -> List[str]:
|
|
618
|
+
"""Bind ontology to a GraphSchema instance.
|
|
619
|
+
|
|
620
|
+
This enables:
|
|
621
|
+
- Validation that schema labels exist in ontology
|
|
622
|
+
- Warnings for unmapped ontology classes
|
|
623
|
+
|
|
624
|
+
Args:
|
|
625
|
+
schema: GraphSchema to bind to
|
|
626
|
+
strict: If True, raise error for unmapped labels.
|
|
627
|
+
If False, return warnings as list.
|
|
628
|
+
|
|
629
|
+
Returns:
|
|
630
|
+
List of warning messages for unmapped items
|
|
631
|
+
|
|
632
|
+
Raises:
|
|
633
|
+
OntologyBindingError: If strict=True and there are unmapped labels
|
|
634
|
+
"""
|
|
635
|
+
warnings = []
|
|
636
|
+
|
|
637
|
+
# Check that each schema label exists in ontology
|
|
638
|
+
schema_labels = {m.label for m in schema.node_mappings if m.label is not None}
|
|
639
|
+
ontology_classes = self._class_hierarchy.classes
|
|
640
|
+
|
|
641
|
+
for label in schema_labels:
|
|
642
|
+
if label not in ontology_classes:
|
|
643
|
+
msg = f"Schema label '{label}' not found in ontology"
|
|
644
|
+
if strict:
|
|
645
|
+
raise OntologyBindingError(msg)
|
|
646
|
+
warnings.append(msg)
|
|
647
|
+
|
|
648
|
+
# Check for ontology classes without schema mappings
|
|
649
|
+
for ont_class in ontology_classes:
|
|
650
|
+
if ont_class not in schema_labels:
|
|
651
|
+
# This is informational - not all ontology classes need mappings
|
|
652
|
+
pass
|
|
653
|
+
|
|
654
|
+
self._bound_schema = schema
|
|
655
|
+
return warnings
|
|
656
|
+
|
|
657
|
+
@property
|
|
658
|
+
def bound_schema(self) -> Optional['GraphSchema']:
|
|
659
|
+
"""The schema `bind_to_schema` bound, or None."""
|
|
660
|
+
return self._bound_schema
|
|
661
|
+
|
|
662
|
+
def get_subclasses(self, class_name: str, include_self: bool = True) -> Set[str]:
|
|
663
|
+
"""Get all subclasses of a class (transitive closure).
|
|
664
|
+
|
|
665
|
+
Args:
|
|
666
|
+
class_name: The parent class name (local name, not full URI)
|
|
667
|
+
include_self: Whether to include the class itself
|
|
668
|
+
|
|
669
|
+
Returns:
|
|
670
|
+
Set of class names including all descendants
|
|
671
|
+
|
|
672
|
+
Example:
|
|
673
|
+
>>> ontology.get_subclasses('Person')
|
|
674
|
+
{'Person', 'Employee', 'Manager', 'Customer', 'Agent'}
|
|
675
|
+
"""
|
|
676
|
+
return self._class_hierarchy.get_all_subclasses(class_name, include_self)
|
|
677
|
+
|
|
678
|
+
def subclass_iris(self, iri: str, include_self: bool = True) -> Set[str]:
|
|
679
|
+
"""Every class IRI under class `iri` by rdfs:subClassOf, at any
|
|
680
|
+
depth (RDFS rule rdfs11: subclassing is transitive), read by IRI:
|
|
681
|
+
a class of the same local name in another namespace is another
|
|
682
|
+
class (RDF 1.1 Concepts 3.2). The one home of the class hierarchy
|
|
683
|
+
at query time (`docs/architecture/rules.md`, "The class hierarchy
|
|
684
|
+
(query time)"). With `include_self` the class itself is in the set
|
|
685
|
+
(`rdfs:subClassOf*`); without it only a class reached by one step
|
|
686
|
+
or more is (`+`), the class itself only through a cycle. An IRI
|
|
687
|
+
the ontology does not hold has no subclasses."""
|
|
688
|
+
found: Set[str] = set()
|
|
689
|
+
frontier = list(self._children_by_iri.get(iri, ()))
|
|
690
|
+
while frontier:
|
|
691
|
+
current = frontier.pop()
|
|
692
|
+
if current not in found:
|
|
693
|
+
found.add(current)
|
|
694
|
+
frontier.extend(self._children_by_iri.get(current, ()))
|
|
695
|
+
if include_self:
|
|
696
|
+
found.add(iri)
|
|
697
|
+
return found
|
|
698
|
+
|
|
699
|
+
def holds_class(self, iri: str) -> bool:
|
|
700
|
+
"""Whether `iri` is a class of this ontology: typed owl:Class or
|
|
701
|
+
rdfs:Class, or at either end of an rdfs:subClassOf."""
|
|
702
|
+
return iri in self._class_iris
|
|
703
|
+
|
|
704
|
+
def class_iris_named(self, name: str) -> Set[str]:
|
|
705
|
+
"""The IRIs of this ontology's classes whose local name is `name`:
|
|
706
|
+
how a label with no class IRI of the ontology's binds to its classes
|
|
707
|
+
(by local name, `docs/guides/owl-and-ontology.md`)."""
|
|
708
|
+
return set(self._iris_by_name.get(name, ()))
|
|
709
|
+
|
|
710
|
+
def get_superclasses(self, class_name: str, include_self: bool = True) -> Set[str]:
|
|
711
|
+
"""Get all superclasses of a class (transitive closure).
|
|
712
|
+
|
|
713
|
+
Args:
|
|
714
|
+
class_name: The class name
|
|
715
|
+
include_self: Whether to include the class itself
|
|
716
|
+
|
|
717
|
+
Returns:
|
|
718
|
+
Set of all ancestor class names
|
|
719
|
+
"""
|
|
720
|
+
return self._class_hierarchy.get_all_superclasses(class_name, include_self)
|
|
721
|
+
|
|
722
|
+
def get_subproperties(self, property_name: str, include_self: bool = True) -> Set[str]:
|
|
723
|
+
"""Every sub-property of a property (transitive closure): the
|
|
724
|
+
properties whose rdfs:subPropertyOf chain reaches it, as
|
|
725
|
+
`get_subclasses` is for classes (RDFS: rdfs:subPropertyOf is
|
|
726
|
+
transitive, rule rdfs5). The one home for the property hierarchy at
|
|
727
|
+
query time (docs/architecture/rules.md); a cycle stops the walk.
|
|
728
|
+
|
|
729
|
+
Example:
|
|
730
|
+
>>> ontology.get_subproperties('rel') # c1 < rel, c2 < c1
|
|
731
|
+
{'rel', 'c1', 'c2'}
|
|
732
|
+
"""
|
|
733
|
+
found: Set[str] = {property_name}
|
|
734
|
+
frontier = [property_name]
|
|
735
|
+
while frontier:
|
|
736
|
+
current = frontier.pop()
|
|
737
|
+
for name, meta in self.properties.items():
|
|
738
|
+
if name not in found and current in (meta.super_properties or ()):
|
|
739
|
+
found.add(name)
|
|
740
|
+
frontier.append(name)
|
|
741
|
+
if not include_self:
|
|
742
|
+
found.discard(property_name)
|
|
743
|
+
return found
|
|
744
|
+
|
|
745
|
+
def is_subclass_of(self, child: str, parent: str) -> bool:
|
|
746
|
+
"""Check if child is a (transitive) subclass of parent.
|
|
747
|
+
|
|
748
|
+
Args:
|
|
749
|
+
child: Potential subclass name
|
|
750
|
+
parent: Potential superclass name
|
|
751
|
+
|
|
752
|
+
Returns:
|
|
753
|
+
True if child is equal to or subclass of parent
|
|
754
|
+
"""
|
|
755
|
+
return self._class_hierarchy.is_subclass_of(child, parent)
|
|
756
|
+
|
|
757
|
+
def expand_labels(self, labels: List[str]) -> List[str]:
|
|
758
|
+
"""Expand a list of labels to include all subclasses.
|
|
759
|
+
|
|
760
|
+
Args:
|
|
761
|
+
labels: Original labels from query (e.g., ['Person'])
|
|
762
|
+
|
|
763
|
+
Returns:
|
|
764
|
+
Expanded labels (e.g., ['Person', 'Employee', 'Manager', ...])
|
|
765
|
+
Order: original labels first, then alphabetically sorted subclasses
|
|
766
|
+
|
|
767
|
+
Example:
|
|
768
|
+
>>> ontology.expand_labels(['Person'])
|
|
769
|
+
['Person', 'Agent', 'Employee', 'Manager']
|
|
770
|
+
"""
|
|
771
|
+
expanded = set()
|
|
772
|
+
for label in labels:
|
|
773
|
+
if label in self._class_hierarchy:
|
|
774
|
+
expanded.update(self.get_subclasses(label))
|
|
775
|
+
else:
|
|
776
|
+
# Unknown label - keep as-is
|
|
777
|
+
expanded.add(label)
|
|
778
|
+
|
|
779
|
+
# Return in consistent order: input labels first, then sorted additions
|
|
780
|
+
result = []
|
|
781
|
+
for label in labels:
|
|
782
|
+
if label in expanded:
|
|
783
|
+
result.append(label)
|
|
784
|
+
expanded.discard(label)
|
|
785
|
+
|
|
786
|
+
result.extend(sorted(expanded))
|
|
787
|
+
return result
|
|
788
|
+
|
|
789
|
+
def expand_labels_for_schema(self, labels: List[str]) -> List[str]:
|
|
790
|
+
"""Expand labels, but only include those with schema mappings.
|
|
791
|
+
|
|
792
|
+
Only returns labels that have NodeMappings in the bound schema.
|
|
793
|
+
This avoids expanding to classes that have no data.
|
|
794
|
+
|
|
795
|
+
Args:
|
|
796
|
+
labels: Original labels from query
|
|
797
|
+
|
|
798
|
+
Returns:
|
|
799
|
+
Expanded labels filtered to those with schema mappings
|
|
800
|
+
|
|
801
|
+
Raises:
|
|
802
|
+
RuntimeError: If no schema is bound
|
|
803
|
+
"""
|
|
804
|
+
if self._bound_schema is None:
|
|
805
|
+
raise RuntimeError("No schema bound. Call bind_to_schema() first.")
|
|
806
|
+
|
|
807
|
+
schema_labels = {m.label for m in self._bound_schema.node_mappings if m.label is not None}
|
|
808
|
+
expanded = self.expand_labels(labels)
|
|
809
|
+
return [l for l in expanded if l in schema_labels]
|
|
810
|
+
|
|
811
|
+
def validate_relationship(
|
|
812
|
+
self,
|
|
813
|
+
rel_type: str,
|
|
814
|
+
start_label: str,
|
|
815
|
+
end_label: str
|
|
816
|
+
) -> bool:
|
|
817
|
+
"""Validate that a relationship is valid per ontology domain/range.
|
|
818
|
+
|
|
819
|
+
Args:
|
|
820
|
+
rel_type: Relationship type name
|
|
821
|
+
start_label: Starting node label
|
|
822
|
+
end_label: Ending node label
|
|
823
|
+
|
|
824
|
+
Returns:
|
|
825
|
+
True if valid, or if no constraints are defined for the relationship
|
|
826
|
+
"""
|
|
827
|
+
if rel_type not in self._properties:
|
|
828
|
+
return True # No constraints defined
|
|
829
|
+
|
|
830
|
+
prop = self._properties[rel_type]
|
|
831
|
+
|
|
832
|
+
# Check domain (valid start labels)
|
|
833
|
+
if prop.domain:
|
|
834
|
+
valid_start = False
|
|
835
|
+
for domain_class in prop.domain:
|
|
836
|
+
if self.is_subclass_of(start_label, domain_class):
|
|
837
|
+
valid_start = True
|
|
838
|
+
break
|
|
839
|
+
if not valid_start:
|
|
840
|
+
return False
|
|
841
|
+
|
|
842
|
+
# Check range (valid end labels)
|
|
843
|
+
if prop.range:
|
|
844
|
+
valid_end = False
|
|
845
|
+
for range_class in prop.range:
|
|
846
|
+
if self.is_subclass_of(end_label, range_class):
|
|
847
|
+
valid_end = True
|
|
848
|
+
break
|
|
849
|
+
if not valid_end:
|
|
850
|
+
return False
|
|
851
|
+
|
|
852
|
+
return True
|
|
853
|
+
|
|
854
|
+
def get_property(self, prop_name: str) -> Optional[PropertyMetadata]:
|
|
855
|
+
"""Get metadata for a property.
|
|
856
|
+
|
|
857
|
+
Args:
|
|
858
|
+
prop_name: Local name of the property
|
|
859
|
+
|
|
860
|
+
Returns:
|
|
861
|
+
PropertyMetadata or None if not found
|
|
862
|
+
"""
|
|
863
|
+
return self._properties.get(prop_name)
|
|
864
|
+
|
|
865
|
+
def get_properties_for_class(self, class_name: str) -> Set[str]:
|
|
866
|
+
"""Get all properties valid for a class (including inherited).
|
|
867
|
+
|
|
868
|
+
This includes:
|
|
869
|
+
- Properties with this class in their domain
|
|
870
|
+
- Properties inherited from superclasses
|
|
871
|
+
|
|
872
|
+
Args:
|
|
873
|
+
class_name: The class name
|
|
874
|
+
|
|
875
|
+
Returns:
|
|
876
|
+
Set of property names valid for the class
|
|
877
|
+
"""
|
|
878
|
+
valid_props = set()
|
|
879
|
+
superclasses = self.get_superclasses(class_name)
|
|
880
|
+
|
|
881
|
+
for prop_name, prop_meta in self._properties.items():
|
|
882
|
+
if not prop_meta.domain:
|
|
883
|
+
# No domain restriction - valid for any class
|
|
884
|
+
valid_props.add(prop_name)
|
|
885
|
+
elif prop_meta.domain & superclasses:
|
|
886
|
+
# Domain includes this class or an ancestor
|
|
887
|
+
valid_props.add(prop_name)
|
|
888
|
+
|
|
889
|
+
return valid_props
|
|
890
|
+
|
|
891
|
+
@property
|
|
892
|
+
def classes(self) -> Set[str]:
|
|
893
|
+
"""Get all class names in the ontology."""
|
|
894
|
+
return self._class_hierarchy.classes
|
|
895
|
+
|
|
896
|
+
@property
|
|
897
|
+
def properties(self) -> Dict[str, PropertyMetadata]:
|
|
898
|
+
"""Get all property metadata."""
|
|
899
|
+
return self._properties.copy()
|
|
900
|
+
|
|
901
|
+
@property
|
|
902
|
+
def hierarchy(self) -> ClassHierarchy:
|
|
903
|
+
"""Get the class hierarchy index."""
|
|
904
|
+
return self._class_hierarchy
|
|
905
|
+
|
|
906
|
+
@property
|
|
907
|
+
def imported_ontologies(self) -> List[str]:
|
|
908
|
+
"""Get list of successfully imported ontology URIs."""
|
|
909
|
+
return self._imported_ontologies.copy()
|
|
910
|
+
|
|
911
|
+
@property
|
|
912
|
+
def failed_imports(self) -> List[str]:
|
|
913
|
+
"""Get list of ontology URIs that failed to import."""
|
|
914
|
+
return self._failed_imports.copy()
|
|
915
|
+
|
|
916
|
+
@property
|
|
917
|
+
def rdf_graph(self) -> 'rdflib.Graph':
|
|
918
|
+
"""Get the underlying rdflib Graph.
|
|
919
|
+
|
|
920
|
+
Useful for advanced queries or debugging.
|
|
921
|
+
"""
|
|
922
|
+
return self._graph
|
|
923
|
+
|
|
924
|
+
# ========== owl:sameAs Entity Resolution ==========
|
|
925
|
+
|
|
926
|
+
def resolve_same_as(self, iri: str) -> str:
|
|
927
|
+
"""Resolve an IRI to its canonical equivalent via owl:sameAs.
|
|
928
|
+
|
|
929
|
+
If the IRI is part of an owl:sameAs group, returns the canonical
|
|
930
|
+
IRI for that group. Otherwise returns the input IRI unchanged.
|
|
931
|
+
|
|
932
|
+
Args:
|
|
933
|
+
iri: The IRI to resolve
|
|
934
|
+
|
|
935
|
+
Returns:
|
|
936
|
+
The canonical IRI for the sameAs group, or the original IRI
|
|
937
|
+
"""
|
|
938
|
+
return self._same_as.get(iri, iri)
|
|
939
|
+
|
|
940
|
+
def get_same_as_group(self, iri: str) -> Set[str]:
|
|
941
|
+
"""Get all IRIs equivalent to the given IRI via owl:sameAs.
|
|
942
|
+
|
|
943
|
+
Args:
|
|
944
|
+
iri: Any IRI in the equivalence group
|
|
945
|
+
|
|
946
|
+
Returns:
|
|
947
|
+
Set of all equivalent IRIs (including the input).
|
|
948
|
+
Returns a single-element set if no sameAs declarations exist.
|
|
949
|
+
"""
|
|
950
|
+
canonical = self._same_as.get(iri, iri)
|
|
951
|
+
return self._same_as_groups.get(canonical, {iri})
|
|
952
|
+
|
|
953
|
+
def are_same(self, iri1: str, iri2: str) -> bool:
|
|
954
|
+
"""Check if two IRIs are declared owl:sameAs.
|
|
955
|
+
|
|
956
|
+
Args:
|
|
957
|
+
iri1: First IRI
|
|
958
|
+
iri2: Second IRI
|
|
959
|
+
|
|
960
|
+
Returns:
|
|
961
|
+
True if the IRIs are in the same owl:sameAs group
|
|
962
|
+
"""
|
|
963
|
+
return self.resolve_same_as(iri1) == self.resolve_same_as(iri2)
|
|
964
|
+
|
|
965
|
+
@property
|
|
966
|
+
def same_as_groups(self) -> Dict[str, Set[str]]:
|
|
967
|
+
"""Get all owl:sameAs equivalence groups.
|
|
968
|
+
|
|
969
|
+
Returns:
|
|
970
|
+
Dict mapping canonical IRIs to sets of equivalent IRIs
|
|
971
|
+
"""
|
|
972
|
+
return {k: v.copy() for k, v in self._same_as_groups.items()}
|
|
973
|
+
|
|
974
|
+
def get_equivalent_classes(self, class_name: str) -> Set[str]:
|
|
975
|
+
"""Return classes declared ``owl:equivalentClass`` to the given one.
|
|
976
|
+
|
|
977
|
+
Result excludes the input class itself. Symmetric, if A is
|
|
978
|
+
declared equivalent to B in the OWL file, both A and B record
|
|
979
|
+
the relation. Returns an empty set if the class has no
|
|
980
|
+
equivalents (or doesn't exist in the ontology).
|
|
981
|
+
"""
|
|
982
|
+
return set(self._equivalent_classes.get(class_name, set()))
|
|
983
|
+
|
|
984
|
+
def __repr__(self) -> str:
|
|
985
|
+
imports_str = ""
|
|
986
|
+
if self._imported_ontologies:
|
|
987
|
+
imports_str = f", imports={len(self._imported_ontologies)}"
|
|
988
|
+
return (
|
|
989
|
+
f"OntologyLayer(classes={len(self._class_hierarchy)}, "
|
|
990
|
+
f"properties={len(self._properties)}{imports_str})"
|
|
991
|
+
)
|