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,542 @@
|
|
|
1
|
+
"""Ontology alignment layer for cross-ontology integration.
|
|
2
|
+
|
|
3
|
+
This module provides support for ontology alignments, enabling:
|
|
4
|
+
- Loading alignment mappings between ontologies
|
|
5
|
+
- Expanding labels across aligned ontologies
|
|
6
|
+
- Supporting queries that span multiple data sources
|
|
7
|
+
|
|
8
|
+
Alignment Relationships:
|
|
9
|
+
- owl:equivalentClass: Classes represent the same concept
|
|
10
|
+
- owl:equivalentProperty: Properties represent the same relationship
|
|
11
|
+
- rdfs:subClassOf: Source class is more specific than target class
|
|
12
|
+
- rdfs:subPropertyOf: Source property is more specific than target property
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations # `str | Path` in annotations: Python 3.9 evaluates them otherwise
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Dict, List, Optional, Set, Tuple, TYPE_CHECKING
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
import rdflib
|
|
24
|
+
from rdflib import RDF, RDFS, OWL, URIRef, Namespace
|
|
25
|
+
RDFLIB_AVAILABLE = True
|
|
26
|
+
except ImportError:
|
|
27
|
+
RDFLIB_AVAILABLE = False
|
|
28
|
+
rdflib = None
|
|
29
|
+
URIRef = None # For type hints when rdflib not installed
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from prograph.ontology.layer import OntologyLayer
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class ClassAlignment:
|
|
40
|
+
"""Alignment mapping for a class.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
source_class: Source class name (local name)
|
|
44
|
+
source_uri: Full URI of source class
|
|
45
|
+
target_class: Target class name (local name)
|
|
46
|
+
target_uri: Full URI of target class
|
|
47
|
+
alignment_type: Type of alignment ('equivalent', 'subclass')
|
|
48
|
+
source_ontology: URI/name of source ontology
|
|
49
|
+
target_ontology: URI/name of target ontology
|
|
50
|
+
confidence: Optional confidence score (0.0-1.0)
|
|
51
|
+
"""
|
|
52
|
+
source_class: str
|
|
53
|
+
source_uri: str
|
|
54
|
+
target_class: str
|
|
55
|
+
target_uri: str
|
|
56
|
+
alignment_type: str # 'equivalent' or 'subclass'
|
|
57
|
+
source_ontology: Optional[str] = None
|
|
58
|
+
target_ontology: Optional[str] = None
|
|
59
|
+
confidence: float = 1.0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class PropertyAlignment:
|
|
64
|
+
"""Alignment mapping for a property.
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
source_property: Source property name (local name)
|
|
68
|
+
source_uri: Full URI of source property
|
|
69
|
+
target_property: Target property name (local name)
|
|
70
|
+
target_uri: Full URI of target property
|
|
71
|
+
alignment_type: Type of alignment ('equivalent', 'subproperty')
|
|
72
|
+
source_ontology: URI/name of source ontology
|
|
73
|
+
target_ontology: URI/name of target ontology
|
|
74
|
+
confidence: Optional confidence score (0.0-1.0)
|
|
75
|
+
"""
|
|
76
|
+
source_property: str
|
|
77
|
+
source_uri: str
|
|
78
|
+
target_property: str
|
|
79
|
+
target_uri: str
|
|
80
|
+
alignment_type: str # 'equivalent' or 'subproperty'
|
|
81
|
+
source_ontology: Optional[str] = None
|
|
82
|
+
target_ontology: Optional[str] = None
|
|
83
|
+
confidence: float = 1.0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AlignmentLayer:
|
|
87
|
+
"""Manages ontology alignments for cross-ontology query expansion.
|
|
88
|
+
|
|
89
|
+
The AlignmentLayer enables queries to span multiple aligned ontologies
|
|
90
|
+
by expanding class and property names across alignment mappings.
|
|
91
|
+
|
|
92
|
+
Example:
|
|
93
|
+
>>> # Load IC ontology with GIST alignment
|
|
94
|
+
>>> ontology = OntologyLayer.from_owl('ic_domain.ttl')
|
|
95
|
+
>>> alignment = AlignmentLayer.from_owl('ic_gist_alignment.ttl')
|
|
96
|
+
>>> alignment.bind_to_ontology(ontology)
|
|
97
|
+
>>>
|
|
98
|
+
>>> # Expand IC class to include GIST equivalents
|
|
99
|
+
>>> alignment.expand_class('Person')
|
|
100
|
+
['Person', 'gist:Person']
|
|
101
|
+
>>>
|
|
102
|
+
>>> # Check if classes are aligned
|
|
103
|
+
>>> alignment.is_aligned('Person', 'gist:Person')
|
|
104
|
+
True
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(self):
|
|
108
|
+
if not RDFLIB_AVAILABLE:
|
|
109
|
+
raise ImportError(
|
|
110
|
+
"rdflib is required for AlignmentLayer. "
|
|
111
|
+
"Install it with: pip install rdflib"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
self._graph: rdflib.Graph = rdflib.Graph()
|
|
115
|
+
self._class_alignments: Dict[str, List[ClassAlignment]] = {}
|
|
116
|
+
self._property_alignments: Dict[str, List[PropertyAlignment]] = {}
|
|
117
|
+
self._reverse_class_map: Dict[str, List[str]] = {} # target -> sources
|
|
118
|
+
self._reverse_property_map: Dict[str, List[str]] = {}
|
|
119
|
+
self._bound_ontology: Optional['OntologyLayer'] = None
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
def from_owl(cls, path: str | Path) -> 'AlignmentLayer':
|
|
123
|
+
"""Load alignment from OWL file.
|
|
124
|
+
|
|
125
|
+
The alignment file should contain owl:equivalentClass,
|
|
126
|
+
owl:equivalentProperty, rdfs:subClassOf, or rdfs:subPropertyOf
|
|
127
|
+
statements mapping between ontologies.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
path: Path to alignment file
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
Configured AlignmentLayer instance
|
|
134
|
+
|
|
135
|
+
Example alignment file (Turtle):
|
|
136
|
+
```
|
|
137
|
+
@prefix : <http://intel.gov/ontology/ic#> .
|
|
138
|
+
@prefix gist: <https://w3id.org/semanticarts/ontology/gistCore#> .
|
|
139
|
+
|
|
140
|
+
:Person owl:equivalentClass gist:Person .
|
|
141
|
+
:Organization owl:equivalentClass gist:Organization .
|
|
142
|
+
:Target rdfs:subClassOf gist:Person .
|
|
143
|
+
:locatedIn rdfs:subPropertyOf gist:locatedIn .
|
|
144
|
+
```
|
|
145
|
+
"""
|
|
146
|
+
alignment = cls()
|
|
147
|
+
path = Path(path)
|
|
148
|
+
|
|
149
|
+
if not path.exists():
|
|
150
|
+
raise FileNotFoundError(f"Alignment file not found: {path}")
|
|
151
|
+
|
|
152
|
+
# Determine format from extension
|
|
153
|
+
format_map = {
|
|
154
|
+
'.owl': 'xml',
|
|
155
|
+
'.rdf': 'xml',
|
|
156
|
+
'.ttl': 'turtle',
|
|
157
|
+
'.n3': 'n3',
|
|
158
|
+
}
|
|
159
|
+
file_format = format_map.get(path.suffix.lower(), 'turtle')
|
|
160
|
+
|
|
161
|
+
alignment._graph.parse(str(path), format=file_format)
|
|
162
|
+
alignment._extract_alignments()
|
|
163
|
+
|
|
164
|
+
return alignment
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def from_turtle(cls, turtle_str: str) -> 'AlignmentLayer':
|
|
168
|
+
"""Create AlignmentLayer from Turtle string.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
turtle_str: Alignment in Turtle format
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
Configured AlignmentLayer instance
|
|
175
|
+
"""
|
|
176
|
+
alignment = cls()
|
|
177
|
+
alignment._graph.parse(data=turtle_str, format='turtle')
|
|
178
|
+
alignment._extract_alignments()
|
|
179
|
+
return alignment
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def from_mappings(
|
|
183
|
+
cls,
|
|
184
|
+
class_mappings: List[Tuple[str, str, str]],
|
|
185
|
+
property_mappings: Optional[List[Tuple[str, str, str]]] = None
|
|
186
|
+
) -> 'AlignmentLayer':
|
|
187
|
+
"""Create AlignmentLayer from explicit mapping lists.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
class_mappings: List of (source_class, target_class, alignment_type)
|
|
191
|
+
where alignment_type is 'equivalent' or 'subclass'
|
|
192
|
+
property_mappings: Optional list of (source_prop, target_prop, alignment_type)
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
Configured AlignmentLayer instance
|
|
196
|
+
|
|
197
|
+
Example:
|
|
198
|
+
>>> alignment = AlignmentLayer.from_mappings([
|
|
199
|
+
... ('Person', 'gist:Person', 'equivalent'),
|
|
200
|
+
... ('Target', 'gist:Person', 'subclass'),
|
|
201
|
+
... ])
|
|
202
|
+
"""
|
|
203
|
+
alignment = cls()
|
|
204
|
+
|
|
205
|
+
for source, target, align_type in class_mappings:
|
|
206
|
+
ca = ClassAlignment(
|
|
207
|
+
source_class=source,
|
|
208
|
+
source_uri=f'urn:mapping:{source}',
|
|
209
|
+
target_class=target,
|
|
210
|
+
target_uri=f'urn:mapping:{target}',
|
|
211
|
+
alignment_type=align_type
|
|
212
|
+
)
|
|
213
|
+
if source not in alignment._class_alignments:
|
|
214
|
+
alignment._class_alignments[source] = []
|
|
215
|
+
alignment._class_alignments[source].append(ca)
|
|
216
|
+
|
|
217
|
+
# Build reverse map
|
|
218
|
+
if target not in alignment._reverse_class_map:
|
|
219
|
+
alignment._reverse_class_map[target] = []
|
|
220
|
+
alignment._reverse_class_map[target].append(source)
|
|
221
|
+
|
|
222
|
+
if property_mappings:
|
|
223
|
+
for source, target, align_type in property_mappings:
|
|
224
|
+
pa = PropertyAlignment(
|
|
225
|
+
source_property=source,
|
|
226
|
+
source_uri=f'urn:mapping:{source}',
|
|
227
|
+
target_property=target,
|
|
228
|
+
target_uri=f'urn:mapping:{target}',
|
|
229
|
+
alignment_type=align_type
|
|
230
|
+
)
|
|
231
|
+
if source not in alignment._property_alignments:
|
|
232
|
+
alignment._property_alignments[source] = []
|
|
233
|
+
alignment._property_alignments[source].append(pa)
|
|
234
|
+
|
|
235
|
+
# Build reverse map
|
|
236
|
+
if target not in alignment._reverse_property_map:
|
|
237
|
+
alignment._reverse_property_map[target] = []
|
|
238
|
+
alignment._reverse_property_map[target].append(source)
|
|
239
|
+
|
|
240
|
+
return alignment
|
|
241
|
+
|
|
242
|
+
def _extract_alignments(self) -> None:
|
|
243
|
+
"""Extract alignment mappings from the RDF graph."""
|
|
244
|
+
# Extract owl:equivalentClass
|
|
245
|
+
for subj, _, obj in self._graph.triples((None, OWL.equivalentClass, None)):
|
|
246
|
+
if isinstance(subj, URIRef) and isinstance(obj, URIRef):
|
|
247
|
+
self._add_class_alignment(subj, obj, 'equivalent')
|
|
248
|
+
|
|
249
|
+
# Extract rdfs:subClassOf (used for alignment)
|
|
250
|
+
for subj, _, obj in self._graph.triples((None, RDFS.subClassOf, None)):
|
|
251
|
+
if isinstance(subj, URIRef) and isinstance(obj, URIRef):
|
|
252
|
+
# Only add if it looks like cross-ontology alignment
|
|
253
|
+
# (different namespace)
|
|
254
|
+
if self._get_namespace(str(subj)) != self._get_namespace(str(obj)):
|
|
255
|
+
self._add_class_alignment(subj, obj, 'subclass')
|
|
256
|
+
|
|
257
|
+
# Extract owl:equivalentProperty
|
|
258
|
+
for subj, _, obj in self._graph.triples((None, OWL.equivalentProperty, None)):
|
|
259
|
+
if isinstance(subj, URIRef) and isinstance(obj, URIRef):
|
|
260
|
+
self._add_property_alignment(subj, obj, 'equivalent')
|
|
261
|
+
|
|
262
|
+
# Extract rdfs:subPropertyOf
|
|
263
|
+
for subj, _, obj in self._graph.triples((None, RDFS.subPropertyOf, None)):
|
|
264
|
+
if isinstance(subj, URIRef) and isinstance(obj, URIRef):
|
|
265
|
+
if self._get_namespace(str(subj)) != self._get_namespace(str(obj)):
|
|
266
|
+
self._add_property_alignment(subj, obj, 'subproperty')
|
|
267
|
+
|
|
268
|
+
logger.info(
|
|
269
|
+
f"Extracted {len(self._class_alignments)} class alignments, "
|
|
270
|
+
f"{len(self._property_alignments)} property alignments"
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
def _add_class_alignment(
|
|
274
|
+
self,
|
|
275
|
+
source_uri: URIRef,
|
|
276
|
+
target_uri: URIRef,
|
|
277
|
+
alignment_type: str
|
|
278
|
+
) -> None:
|
|
279
|
+
"""Add a class alignment to the internal maps."""
|
|
280
|
+
source_name = self._get_local_name(source_uri)
|
|
281
|
+
target_name = self._get_local_name(target_uri)
|
|
282
|
+
|
|
283
|
+
ca = ClassAlignment(
|
|
284
|
+
source_class=source_name,
|
|
285
|
+
source_uri=str(source_uri),
|
|
286
|
+
target_class=target_name,
|
|
287
|
+
target_uri=str(target_uri),
|
|
288
|
+
alignment_type=alignment_type,
|
|
289
|
+
source_ontology=self._get_namespace(str(source_uri)),
|
|
290
|
+
target_ontology=self._get_namespace(str(target_uri))
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
if source_name not in self._class_alignments:
|
|
294
|
+
self._class_alignments[source_name] = []
|
|
295
|
+
self._class_alignments[source_name].append(ca)
|
|
296
|
+
|
|
297
|
+
# Build reverse map
|
|
298
|
+
if target_name not in self._reverse_class_map:
|
|
299
|
+
self._reverse_class_map[target_name] = []
|
|
300
|
+
self._reverse_class_map[target_name].append(source_name)
|
|
301
|
+
|
|
302
|
+
def _add_property_alignment(
|
|
303
|
+
self,
|
|
304
|
+
source_uri: URIRef,
|
|
305
|
+
target_uri: URIRef,
|
|
306
|
+
alignment_type: str
|
|
307
|
+
) -> None:
|
|
308
|
+
"""Add a property alignment to the internal maps."""
|
|
309
|
+
source_name = self._get_local_name(source_uri)
|
|
310
|
+
target_name = self._get_local_name(target_uri)
|
|
311
|
+
|
|
312
|
+
pa = PropertyAlignment(
|
|
313
|
+
source_property=source_name,
|
|
314
|
+
source_uri=str(source_uri),
|
|
315
|
+
target_property=target_name,
|
|
316
|
+
target_uri=str(target_uri),
|
|
317
|
+
alignment_type=alignment_type,
|
|
318
|
+
source_ontology=self._get_namespace(str(source_uri)),
|
|
319
|
+
target_ontology=self._get_namespace(str(target_uri))
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
if source_name not in self._property_alignments:
|
|
323
|
+
self._property_alignments[source_name] = []
|
|
324
|
+
self._property_alignments[source_name].append(pa)
|
|
325
|
+
|
|
326
|
+
# Build reverse map
|
|
327
|
+
if target_name not in self._reverse_property_map:
|
|
328
|
+
self._reverse_property_map[target_name] = []
|
|
329
|
+
self._reverse_property_map[target_name].append(source_name)
|
|
330
|
+
|
|
331
|
+
def _get_local_name(self, uri: URIRef | str) -> str:
|
|
332
|
+
"""Extract local name from URI, with prefix if available.
|
|
333
|
+
|
|
334
|
+
If a prefix is registered for the namespace, returns prefix:localname.
|
|
335
|
+
Otherwise returns just the local name.
|
|
336
|
+
"""
|
|
337
|
+
uri_str = str(uri)
|
|
338
|
+
|
|
339
|
+
# Get the local part
|
|
340
|
+
if '#' in uri_str:
|
|
341
|
+
local = uri_str.split('#')[-1]
|
|
342
|
+
ns = uri_str.rsplit('#', 1)[0] + '#'
|
|
343
|
+
else:
|
|
344
|
+
local = uri_str.rsplit('/', 1)[-1]
|
|
345
|
+
ns = uri_str.rsplit('/', 1)[0] + '/'
|
|
346
|
+
|
|
347
|
+
# Try to find a prefix for the namespace
|
|
348
|
+
for prefix, namespace in self._graph.namespaces():
|
|
349
|
+
if str(namespace) == ns and prefix:
|
|
350
|
+
return f"{prefix}:{local}"
|
|
351
|
+
|
|
352
|
+
return local
|
|
353
|
+
|
|
354
|
+
def _get_namespace(self, uri: str) -> str:
|
|
355
|
+
"""Extract namespace from URI."""
|
|
356
|
+
if '#' in uri:
|
|
357
|
+
return uri.rsplit('#', 1)[0] + '#'
|
|
358
|
+
return uri.rsplit('/', 1)[0] + '/'
|
|
359
|
+
|
|
360
|
+
def bind_to_ontology(self, ontology: 'OntologyLayer') -> None:
|
|
361
|
+
"""Bind alignment to an OntologyLayer.
|
|
362
|
+
|
|
363
|
+
This enables expand_with_ontology() to use the ontology's
|
|
364
|
+
class hierarchy in addition to alignment mappings.
|
|
365
|
+
|
|
366
|
+
Args:
|
|
367
|
+
ontology: OntologyLayer to bind to
|
|
368
|
+
"""
|
|
369
|
+
self._bound_ontology = ontology
|
|
370
|
+
|
|
371
|
+
def expand_class(
|
|
372
|
+
self,
|
|
373
|
+
class_name: str,
|
|
374
|
+
include_self: bool = True,
|
|
375
|
+
include_equivalents: bool = True,
|
|
376
|
+
include_subclasses: bool = True
|
|
377
|
+
) -> List[str]:
|
|
378
|
+
"""Expand a class name using alignment mappings.
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
class_name: Class name to expand
|
|
382
|
+
include_self: Include the original class name
|
|
383
|
+
include_equivalents: Include owl:equivalentClass targets
|
|
384
|
+
include_subclasses: Include rdfs:subClassOf targets
|
|
385
|
+
|
|
386
|
+
Returns:
|
|
387
|
+
List of aligned class names
|
|
388
|
+
"""
|
|
389
|
+
result = []
|
|
390
|
+
if include_self:
|
|
391
|
+
result.append(class_name)
|
|
392
|
+
|
|
393
|
+
alignments = self._class_alignments.get(class_name, [])
|
|
394
|
+
for alignment in alignments:
|
|
395
|
+
if include_equivalents and alignment.alignment_type == 'equivalent':
|
|
396
|
+
if alignment.target_class not in result:
|
|
397
|
+
result.append(alignment.target_class)
|
|
398
|
+
if include_subclasses and alignment.alignment_type == 'subclass':
|
|
399
|
+
if alignment.target_class not in result:
|
|
400
|
+
result.append(alignment.target_class)
|
|
401
|
+
|
|
402
|
+
return result
|
|
403
|
+
|
|
404
|
+
def expand_class_with_ontology(
|
|
405
|
+
self,
|
|
406
|
+
class_name: str,
|
|
407
|
+
include_self: bool = True
|
|
408
|
+
) -> List[str]:
|
|
409
|
+
"""Expand class using both alignment and ontology hierarchy.
|
|
410
|
+
|
|
411
|
+
Requires bind_to_ontology() to have been called.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
class_name: Class name to expand
|
|
415
|
+
include_self: Include the original class name
|
|
416
|
+
|
|
417
|
+
Returns:
|
|
418
|
+
List of expanded class names (ontology subclasses + aligned classes)
|
|
419
|
+
|
|
420
|
+
Raises:
|
|
421
|
+
RuntimeError: If no ontology is bound
|
|
422
|
+
"""
|
|
423
|
+
if self._bound_ontology is None:
|
|
424
|
+
raise RuntimeError("No ontology bound. Call bind_to_ontology() first.")
|
|
425
|
+
|
|
426
|
+
# Start with ontology expansion
|
|
427
|
+
expanded = set(self._bound_ontology.expand_labels([class_name]))
|
|
428
|
+
|
|
429
|
+
# Add alignment expansions for each class
|
|
430
|
+
for cls in list(expanded):
|
|
431
|
+
aligned = self.expand_class(cls, include_self=False)
|
|
432
|
+
expanded.update(aligned)
|
|
433
|
+
|
|
434
|
+
result = list(expanded)
|
|
435
|
+
if include_self and class_name not in result:
|
|
436
|
+
result.insert(0, class_name)
|
|
437
|
+
|
|
438
|
+
return result
|
|
439
|
+
|
|
440
|
+
def expand_property(
|
|
441
|
+
self,
|
|
442
|
+
property_name: str,
|
|
443
|
+
include_self: bool = True
|
|
444
|
+
) -> List[str]:
|
|
445
|
+
"""Expand a property name using alignment mappings.
|
|
446
|
+
|
|
447
|
+
Args:
|
|
448
|
+
property_name: Property name to expand
|
|
449
|
+
include_self: Include the original property name
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
List of aligned property names
|
|
453
|
+
"""
|
|
454
|
+
result = []
|
|
455
|
+
if include_self:
|
|
456
|
+
result.append(property_name)
|
|
457
|
+
|
|
458
|
+
alignments = self._property_alignments.get(property_name, [])
|
|
459
|
+
for alignment in alignments:
|
|
460
|
+
if alignment.target_property not in result:
|
|
461
|
+
result.append(alignment.target_property)
|
|
462
|
+
|
|
463
|
+
return result
|
|
464
|
+
|
|
465
|
+
def is_aligned(self, class1: str, class2: str) -> bool:
|
|
466
|
+
"""Check if two classes are aligned (equivalent or related).
|
|
467
|
+
|
|
468
|
+
Args:
|
|
469
|
+
class1: First class name
|
|
470
|
+
class2: Second class name
|
|
471
|
+
|
|
472
|
+
Returns:
|
|
473
|
+
True if classes are aligned
|
|
474
|
+
"""
|
|
475
|
+
if class1 == class2:
|
|
476
|
+
return True
|
|
477
|
+
|
|
478
|
+
# Check direct alignment
|
|
479
|
+
alignments = self._class_alignments.get(class1, [])
|
|
480
|
+
for alignment in alignments:
|
|
481
|
+
if alignment.target_class == class2:
|
|
482
|
+
return True
|
|
483
|
+
|
|
484
|
+
# Check reverse alignment
|
|
485
|
+
reverse = self._reverse_class_map.get(class1, [])
|
|
486
|
+
if class2 in reverse:
|
|
487
|
+
return True
|
|
488
|
+
|
|
489
|
+
return False
|
|
490
|
+
|
|
491
|
+
def get_class_alignments(self, class_name: str) -> List[ClassAlignment]:
|
|
492
|
+
"""Get all alignments for a class.
|
|
493
|
+
|
|
494
|
+
Args:
|
|
495
|
+
class_name: Class name to look up
|
|
496
|
+
|
|
497
|
+
Returns:
|
|
498
|
+
List of ClassAlignment objects
|
|
499
|
+
"""
|
|
500
|
+
return self._class_alignments.get(class_name, []).copy()
|
|
501
|
+
|
|
502
|
+
def get_equivalent_classes(self, class_name: str) -> Set[str]:
|
|
503
|
+
"""Get all classes equivalent to the given class.
|
|
504
|
+
|
|
505
|
+
Args:
|
|
506
|
+
class_name: Class name to look up
|
|
507
|
+
|
|
508
|
+
Returns:
|
|
509
|
+
Set of equivalent class names (excluding self)
|
|
510
|
+
"""
|
|
511
|
+
equivalents = set()
|
|
512
|
+
alignments = self._class_alignments.get(class_name, [])
|
|
513
|
+
for alignment in alignments:
|
|
514
|
+
if alignment.alignment_type == 'equivalent':
|
|
515
|
+
equivalents.add(alignment.target_class)
|
|
516
|
+
return equivalents
|
|
517
|
+
|
|
518
|
+
@property
|
|
519
|
+
def class_alignments(self) -> Dict[str, List[ClassAlignment]]:
|
|
520
|
+
"""Get all class alignments."""
|
|
521
|
+
return {k: v.copy() for k, v in self._class_alignments.items()}
|
|
522
|
+
|
|
523
|
+
@property
|
|
524
|
+
def property_alignments(self) -> Dict[str, List[PropertyAlignment]]:
|
|
525
|
+
"""Get all property alignments."""
|
|
526
|
+
return {k: v.copy() for k, v in self._property_alignments.items()}
|
|
527
|
+
|
|
528
|
+
@property
|
|
529
|
+
def aligned_classes(self) -> Set[str]:
|
|
530
|
+
"""Get all source classes with alignments."""
|
|
531
|
+
return set(self._class_alignments.keys())
|
|
532
|
+
|
|
533
|
+
@property
|
|
534
|
+
def aligned_properties(self) -> Set[str]:
|
|
535
|
+
"""Get all source properties with alignments."""
|
|
536
|
+
return set(self._property_alignments.keys())
|
|
537
|
+
|
|
538
|
+
def __repr__(self) -> str:
|
|
539
|
+
return (
|
|
540
|
+
f"AlignmentLayer(classes={len(self._class_alignments)}, "
|
|
541
|
+
f"properties={len(self._property_alignments)})"
|
|
542
|
+
)
|