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.
Files changed (237) hide show
  1. prograph/__init__.py +36 -0
  2. prograph/__main__.py +5 -0
  3. prograph/_version.py +375 -0
  4. prograph/cli/__init__.py +1 -0
  5. prograph/cli/_iri_utils.py +124 -0
  6. prograph/cli/emit_genie_space.py +107 -0
  7. prograph/cli/generate_views.py +140 -0
  8. prograph/cli/main.py +420 -0
  9. prograph/cli/schema_inferrer.py +746 -0
  10. prograph/cli/ttl_loader.py +289 -0
  11. prograph/cli/upload_genie_space.py +84 -0
  12. prograph/config/__init__.py +27 -0
  13. prograph/config/yaml_config.py +848 -0
  14. prograph/demos/__init__.py +14 -0
  15. prograph/demos/turbofan/README.md +74 -0
  16. prograph/demos/turbofan/SCENARIO.md +209 -0
  17. prograph/demos/turbofan/__init__.py +75 -0
  18. prograph/demos/turbofan/create_tables.sql +206 -0
  19. prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
  20. prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
  21. prograph/demos/turbofan/demo.py +162 -0
  22. prograph/demos/turbofan/genie_qa_notebook.py +434 -0
  23. prograph/demos/turbofan/graph.yaml +1098 -0
  24. prograph/demos/turbofan/instance_graph_demo.py +32 -0
  25. prograph/demos/turbofan/load.py +223 -0
  26. prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
  27. prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
  28. prograph/demos/turbofan/payload-shapes.ttl +33 -0
  29. prograph/demos/turbofan/queries/example-queries.sparql +215 -0
  30. prograph/demos/turbofan/shapes.ttl +75 -0
  31. prograph/demos/turbofan/tables.py +106 -0
  32. prograph/demos/turbofan/turbofan_schema.py +393 -0
  33. prograph/demos/turbofan/validation_demo.py +153 -0
  34. prograph/describe.py +231 -0
  35. prograph/endpoint/__init__.py +12 -0
  36. prograph/endpoint/app.py +722 -0
  37. prograph/endpoint/cli.py +280 -0
  38. prograph/endpoint/credentials.py +240 -0
  39. prograph/endpoint/engines.py +418 -0
  40. prograph/endpoint/negotiate.py +101 -0
  41. prograph/endpoint/results.py +181 -0
  42. prograph/endpoint/service.py +31 -0
  43. prograph/engine.py +2718 -0
  44. prograph/execution.py +455 -0
  45. prograph/executors/__init__.py +6 -0
  46. prograph/executors/base.py +11 -0
  47. prograph/executors/databricks_sql_executor.py +51 -0
  48. prograph/executors/duckdb_executor.py +24 -0
  49. prograph/executors/mysql_executor.py +20 -0
  50. prograph/executors/oracle_executor.py +24 -0
  51. prograph/executors/pandas_executor.py +72 -0
  52. prograph/executors/postgresql_executor.py +35 -0
  53. prograph/executors/spark_executor.py +88 -0
  54. prograph/executors/sqlserver_executor.py +35 -0
  55. prograph/extras/__init__.py +1 -0
  56. prograph/extras/graphql/__init__.py +33 -0
  57. prograph/extras/graphql/execute.py +25 -0
  58. prograph/extras/graphql/schema.py +314 -0
  59. prograph/extras/instance_graph.py +559 -0
  60. prograph/genie/__init__.py +83 -0
  61. prograph/genie/databricks_uploader.py +306 -0
  62. prograph/genie/deploy.py +393 -0
  63. prograph/genie/formats.py +414 -0
  64. prograph/genie/instruction_generator.py +375 -0
  65. prograph/genie/sample_query_generator.py +256 -0
  66. prograph/genie/shacl_views.py +318 -0
  67. prograph/genie/space_emitter.py +329 -0
  68. prograph/genie/view_generator.py +628 -0
  69. prograph/genie/view_writer.py +172 -0
  70. prograph/graph/__init__.py +1 -0
  71. prograph/graph/ansi_session.py +348 -0
  72. prograph/graph/databricks_sql_graph.py +300 -0
  73. prograph/graph/drivers.py +143 -0
  74. prograph/graph/duckdb_graph.py +68 -0
  75. prograph/graph/mysql_graph.py +38 -0
  76. prograph/graph/oracle_graph.py +285 -0
  77. prograph/graph/pandas_graph.py +343 -0
  78. prograph/graph/postgresql_graph.py +644 -0
  79. prograph/graph/spark_graph.py +556 -0
  80. prograph/graph/sql_graph.py +83 -0
  81. prograph/graph/sqlserver_graph.py +72 -0
  82. prograph/hints.py +95 -0
  83. prograph/logging.py +550 -0
  84. prograph/mcp/__init__.py +29 -0
  85. prograph/mcp/__main__.py +180 -0
  86. prograph/mcp/bootstrap.py +98 -0
  87. prograph/mcp/server.py +601 -0
  88. prograph/mcp/sparql.py +397 -0
  89. prograph/mcp/tools.py +504 -0
  90. prograph/nlp/__init__.py +79 -0
  91. prograph/nlp/client.py +305 -0
  92. prograph/nlp/databricks_tools.py +369 -0
  93. prograph/nlp/graph_context.py +313 -0
  94. prograph/nlp/interface.py +652 -0
  95. prograph/nlp/prompts/__init__.py +19 -0
  96. prograph/nlp/prompts/examples.py +258 -0
  97. prograph/nlp/prompts/system.py +239 -0
  98. prograph/nlp/providers/__init__.py +14 -0
  99. prograph/nlp/providers/anthropic.py +274 -0
  100. prograph/nlp/providers/databricks.py +312 -0
  101. prograph/nlp/providers/openai.py +203 -0
  102. prograph/nlp/schema_context.py +78 -0
  103. prograph/ontology/__init__.py +53 -0
  104. prograph/ontology/alignment.py +542 -0
  105. prograph/ontology/hierarchy.py +310 -0
  106. prograph/ontology/imports.py +587 -0
  107. prograph/ontology/layer.py +991 -0
  108. prograph/ontology/skos.py +61 -0
  109. prograph/owl/__init__.py +27 -0
  110. prograph/owl/defined_classes.py +323 -0
  111. prograph/parameters.py +242 -0
  112. prograph/parser/__init__.py +1 -0
  113. prograph/parser/cypher/CypherLexer.py +836 -0
  114. prograph/parser/cypher/CypherListener.py +966 -0
  115. prograph/parser/cypher/CypherParser.py +10854 -0
  116. prograph/parser/cypher/CypherVisitor.py +543 -0
  117. prograph/parser/cypher/__init__.py +1 -0
  118. prograph/parser/sparql/SparqlLexer.py +801 -0
  119. prograph/parser/sparql/SparqlParser.py +10146 -0
  120. prograph/parser/sparql/SparqlParserListener.py +1056 -0
  121. prograph/parser/sparql/SparqlParserVisitor.py +593 -0
  122. prograph/parser/sparql/__init__.py +8 -0
  123. prograph/plan/__init__.py +3 -0
  124. prograph/plan/ir/__init__.py +1 -0
  125. prograph/plan/ir/casts.py +338 -0
  126. prograph/plan/ir/consistency.py +397 -0
  127. prograph/plan/ir/construct.py +90 -0
  128. prograph/plan/ir/cost.py +234 -0
  129. prograph/plan/ir/cypher_answer.py +1081 -0
  130. prograph/plan/ir/cypher_apoc.py +717 -0
  131. prograph/plan/ir/cypher_apoc_convert.py +505 -0
  132. prograph/plan/ir/cypher_apoc_date.py +845 -0
  133. prograph/plan/ir/cypher_apoc_map.py +496 -0
  134. prograph/plan/ir/cypher_apoc_meta.py +384 -0
  135. prograph/plan/ir/cypher_apoc_path.py +597 -0
  136. prograph/plan/ir/cypher_apoc_procedures.py +163 -0
  137. prograph/plan/ir/cypher_apoc_text.py +785 -0
  138. prograph/plan/ir/cypher_front.py +5474 -0
  139. prograph/plan/ir/cypher_functions.py +565 -0
  140. prograph/plan/ir/cypher_lists.py +935 -0
  141. prograph/plan/ir/cypher_maps.py +370 -0
  142. prograph/plan/ir/cypher_mixed.py +604 -0
  143. prograph/plan/ir/cypher_ontology.py +226 -0
  144. prograph/plan/ir/cypher_procedures.py +191 -0
  145. prograph/plan/ir/cypher_runtime_errors.py +107 -0
  146. prograph/plan/ir/cypher_temporal.py +1357 -0
  147. prograph/plan/ir/cypher_temporal_arith.py +339 -0
  148. prograph/plan/ir/cypher_values.py +546 -0
  149. prograph/plan/ir/cypher_write.py +612 -0
  150. prograph/plan/ir/dataset.py +643 -0
  151. prograph/plan/ir/dates.py +102 -0
  152. prograph/plan/ir/entry.py +992 -0
  153. prograph/plan/ir/expr.py +260 -0
  154. prograph/plan/ir/facts.py +1171 -0
  155. prograph/plan/ir/fresh.py +291 -0
  156. prograph/plan/ir/freshness.py +625 -0
  157. prograph/plan/ir/identity.py +797 -0
  158. prograph/plan/ir/java_datetime.py +265 -0
  159. prograph/plan/ir/java_regex.py +391 -0
  160. prograph/plan/ir/join_order.py +39 -0
  161. prograph/plan/ir/key_checks.py +433 -0
  162. prograph/plan/ir/keys.py +454 -0
  163. prograph/plan/ir/lower.py +5323 -0
  164. prograph/plan/ir/ops.py +619 -0
  165. prograph/plan/ir/owl_rl.py +1119 -0
  166. prograph/plan/ir/owl_rl_rules.py +725 -0
  167. prograph/plan/ir/profiles.py +694 -0
  168. prograph/plan/ir/ql.py +987 -0
  169. prograph/plan/ir/rdfs.py +342 -0
  170. prograph/plan/ir/rewrite.py +1782 -0
  171. prograph/plan/ir/saturate.py +339 -0
  172. prograph/plan/ir/semantics.py +103 -0
  173. prograph/plan/ir/slot.py +509 -0
  174. prograph/plan/ir/sparql_front.py +3418 -0
  175. prograph/plan/ir/strings.py +534 -0
  176. prograph/plan/ir/term_functions.py +274 -0
  177. prograph/plan/ir/terms.py +84 -0
  178. prograph/plan/ir/xpath_regex.py +264 -0
  179. prograph/plan/run_record.py +65 -0
  180. prograph/plan/sql/__init__.py +21 -0
  181. prograph/plan/sql/dialect.py +3726 -0
  182. prograph/plan/sql/mysql_serializer.py +103 -0
  183. prograph/plan/sql/names.py +65 -0
  184. prograph/plan/sql/oracle_serializer.py +306 -0
  185. prograph/plan/sql/pg_serializer.py +501 -0
  186. prograph/plan/sql/rel_algebra.py +781 -0
  187. prograph/plan/sql/sql_serializer.py +1419 -0
  188. prograph/plan/sql/sqlserver_serializer.py +603 -0
  189. prograph/provenance.py +222 -0
  190. prograph/r2rml/__init__.py +48 -0
  191. prograph/r2rml/catalog.py +259 -0
  192. prograph/r2rml/compile.py +372 -0
  193. prograph/r2rml/direct.py +140 -0
  194. prograph/r2rml/export.py +495 -0
  195. prograph/r2rml/model.py +180 -0
  196. prograph/r2rml/parser.py +546 -0
  197. prograph/r2rml/schema.py +120 -0
  198. prograph/read_only.py +122 -0
  199. prograph/results.py +157 -0
  200. prograph/rules/__init__.py +168 -0
  201. prograph/rules/__main__.py +32 -0
  202. prograph/schema/__init__.py +60 -0
  203. prograph/schema/change_set.py +50 -0
  204. prograph/schema/collations.py +198 -0
  205. prograph/schema/compile_schema.py +388 -0
  206. prograph/schema/context.py +845 -0
  207. prograph/schema/examples.py +234 -0
  208. prograph/schema/iri.py +817 -0
  209. prograph/schema/literals.py +94 -0
  210. prograph/schema/lpg_view.py +617 -0
  211. prograph/schema/mapping.py +1803 -0
  212. prograph/schema/maps_schema.py +40 -0
  213. prograph/schema/naming.py +77 -0
  214. prograph/schema/query_sources.py +59 -0
  215. prograph/schema/rows.py +215 -0
  216. prograph/schema/source_map.py +1103 -0
  217. prograph/schema/store_view.py +459 -0
  218. prograph/schema/types.py +569 -0
  219. prograph/schema/xsd.py +569 -0
  220. prograph/shacl/__init__.py +30 -0
  221. prograph/shacl/dqv.py +58 -0
  222. prograph/shacl/generate.py +255 -0
  223. prograph/shacl/report.py +138 -0
  224. prograph/shacl/validator.py +164 -0
  225. prograph/store.py +1737 -0
  226. prograph/utils/__init__.py +6 -0
  227. prograph/utils/exceptions.py +308 -0
  228. prograph/utils/helpers.py +126 -0
  229. prograph/warnings.py +46 -0
  230. prograph/writes.py +369 -0
  231. prograph-1.3.3.dist-info/METADATA +281 -0
  232. prograph-1.3.3.dist-info/RECORD +237 -0
  233. prograph-1.3.3.dist-info/WHEEL +5 -0
  234. prograph-1.3.3.dist-info/entry_points.txt +3 -0
  235. prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
  236. prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
  237. prograph-1.3.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,725 @@
1
+ """OWL 2 RL's rules, instantiated from an ontology's axioms (OWL 2 Profiles 4.3; docs/reference/owl-rl.md).
2
+
3
+ Each rule is read from the parsed axioms, its lists unrolled here, never looked up in the data graph: a SPARQL
4
+ group pattern that binds the conclusion's subject (and object), with every class and property a constant.
5
+ The plan answers each pattern over the saturated maps (`owl_rl.materialize`), so subClassOf, subPropertyOf,
6
+ equivalentClass, equivalentProperty, domain and range (cax-sco, cax-eqc1/2, prp-spo1, prp-eqp1/2, prp-dom,
7
+ prp-rng) feed every rule's premises without being materialized themselves.
8
+
9
+ - **Properties**: prp-inv1/2 (inverseOf), prp-symp (SymmetricProperty), prp-trp (TransitiveProperty, as the
10
+ path `p+`), prp-spo2 (propertyChainAxiom, each chain one join of its steps).
11
+ - **Classes**: every class expression is compiled so the conclusion is a named class, never a blank node:
12
+ `sub ⊑ sup` with `sub` an intersection (cls-int1), a union (cls-uni), someValuesFrom (cls-svf1; cls-svf2 for
13
+ owl:Thing), hasValue (cls-hv2) or oneOf (cls-oo), and `sup` a named class, an intersection (cls-int2),
14
+ allValuesFrom (cls-avf) or hasValue (cls-hv1). An equivalentClass to an expression is its two subsumptions;
15
+ a named class with a constructor of its own (`:C owl:intersectionOf (...)`) is equivalent to it.
16
+ - **sameAs** (`links`): prp-fp, prp-ifp, prp-key, cls-maxc2 and cls-maxqc3/4 are rules whose conclusion is a
17
+ link `subject owl:sameAs object` between two IRIs, which the fixpoint closes into components
18
+ (`identity`), never a statement; an ontology's own `a owl:sameAs b` between two IRIs is a link too. A
19
+ functional property's (or a max cardinality 1's) two literal values that are not one value is a clash
20
+ (`clashes`); `owl:differentFrom` and `owl:AllDifferent` between IRIs the ontology names are `distinct`.
21
+ - **Consistency**: cax-dw, cax-adc, prp-irp, prp-asyp, prp-pdw, prp-adp, prp-npa1/2, cls-nothing2, cls-com,
22
+ cls-maxc1, cls-maxqc1, cls-maxqc2 and dt-not-type (a range that is a datatype, prp-rng's conclusion about a
23
+ literal; a number or boolean whose lexical form is not its datatype's) derive no triple; each is a pattern whose
24
+ solutions are a contradiction (`checks`; run by `owl_rl._Run.consistency`). prp-npa2 compares its literal by
25
+ value (`same_value`).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ from dataclasses import dataclass, field
32
+ from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
33
+
34
+ from prograph.rules import home, module_home
35
+
36
+ module_home("owl-rl-rules", "OWL 2 RL's rules instantiated from an ontology's axioms, conclusions named",
37
+ terms=("OWL 2 RL", "OWL RL", "rule instance", "prp-inv", "prp-symp", "prp-trp", "prp-spo2",
38
+ "cls-svf1", "cls-svf2", "cls-avf", "cls-hv", "cls-int", "cls-uni", "cls-oo",
39
+ "class expression", "restriction", "someValuesFrom", "allValuesFrom", "hasValue",
40
+ "intersectionOf", "unionOf", "oneOf", "propertyChainAxiom", "inverseOf",
41
+ "consistency rule", "sameAs-deriving", "ontology digest"))
42
+
43
+ RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
44
+ RDFS = "http://www.w3.org/2000/01/rdf-schema#"
45
+ OWL = "http://www.w3.org/2002/07/owl#"
46
+ from prograph.schema.xsd import XSD # noqa: E402 - the datatypes' home
47
+ RDF_TYPE = RDF + "type"
48
+ THING, NOTHING = OWL + "Thing", OWL + "Nothing"
49
+ # The kinds of axiom whose RL rules derive owl:sameAs (links, `identity`).
50
+ SAME_AS_KINDS = {OWL + "sameAs": "eq-*", OWL + "FunctionalProperty": "prp-fp",
51
+ OWL + "InverseFunctionalProperty": "prp-ifp", OWL + "hasKey": "prp-key",
52
+ OWL + "maxCardinality": "cls-maxc2", OWL + "maxQualifiedCardinality": "cls-maxqc3/4"}
53
+ # Bumped when the rules compiled from one ontology change: a store materialized by older rules runs again.
54
+ RULES_VERSION = "owl-rl/3"
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Rule:
59
+ """One rule instance: `where` a SPARQL group pattern binding `subject` (a variable) and, for a property's
60
+ conclusion, `object` (a variable, or a constant term in N-Triples form with `value` its rdflib term).
61
+ The conclusion is (subject, `predicate`, object), or (subject, rdf:type, `cls`). `literal`: the object
62
+ may be a literal (a transitive or chained property's last step). `rule` the RL rule's id."""
63
+ rule: str
64
+ where: str
65
+ subject: str
66
+ predicate: str
67
+ cls: Optional[str] = None
68
+ object: Optional[str] = None
69
+ value: Any = None
70
+ literal: bool = False
71
+ axiom: str = ""
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Check:
76
+ """A consistency rule's instance: `where` binds `?x` (and maybe `?y`); a solution is a contradiction. `facts`:
77
+ the facts a solution names, a pattern over `where`'s variables (`consistency.fill`; '' for `where` itself)."""
78
+ rule: str
79
+ where: str
80
+ axiom: str
81
+ facts: str = ""
82
+ # dt-not-type from a range: (the property, the range's datatypes, whether the ontology asserts the property
83
+ # itself); a check `ql.range_holds` proves cannot fail over the maps is not run.
84
+ range: Optional[Tuple[str, Any, bool]] = None
85
+
86
+
87
+
88
+
89
+ @dataclass
90
+ class RuleSet:
91
+ """An ontology's rules (`rules`), its consistency checks (`checks`), the axioms skipped with why
92
+ (`skipped`: (kind, rule, text)), the ontology's triples the rules and checks apply (`consumed`), and the
93
+ ontology's digest."""
94
+ rules: List[Rule] = field(default_factory=list)
95
+ checks: List[Check] = field(default_factory=list)
96
+ # Rules concluding `subject owl:sameAs object` between IRIs (prp-fp, prp-ifp, prp-key, cls-maxc2,
97
+ # cls-maxqc3/4; eq-* for an ontology's own sameAs): links the fixpoint closes into components.
98
+ links: List[Rule] = field(default_factory=list)
99
+ # A clash's pattern binds ?x and one value ?v of a property ?x has at most one value of: two literal
100
+ # values that are not one value (1 and 1.0 are one) are a clash (`owl_rl._Run.inconsistent`).
101
+ clashes: List[Check] = field(default_factory=list)
102
+ # (a, b, axiom, rule): two IRIs the ontology says are different (owl:differentFrom: eq-diff1;
103
+ # owl:AllDifferent's owl:members or owl:distinctMembers: eq-diff2, eq-diff3).
104
+ distinct: List[Tuple[str, str, str, str]] = field(default_factory=list)
105
+ skipped: List[Tuple[str, str, str]] = field(default_factory=list)
106
+ consumed: Set[tuple] = field(default_factory=set)
107
+ digest: str = ""
108
+ # Skipped parts of axioms whose other part is applied (`C ≡ ∃p.D`: ∃p.D ⊑ C applied, C ⊑ ∃p.D not): the
109
+ # ontology's triple counts as applied, so these are named in a warning of their own (`entry.ontology_of`).
110
+ partial: List[str] = field(default_factory=list)
111
+
112
+
113
+ def digest(graph: Any) -> str:
114
+ """The ontology's digest: SHA-256 of its canonical N-Triples (blank nodes named canonically), and the
115
+ rules' version."""
116
+ from rdflib.compare import to_canonical_graph
117
+ lines = sorted(to_canonical_graph(graph).serialize(format="nt").splitlines())
118
+ text = RULES_VERSION + "\n" + "\n".join(x for x in lines if x.strip())
119
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
120
+
121
+
122
+ def compile_rules(graph: Any) -> RuleSet:
123
+ """The rules, checks and skipped axioms of an rdflib graph holding an ontology."""
124
+ return _Compiler(graph).run()
125
+
126
+
127
+ class _Unsupported(Exception):
128
+ """A class or property expression the RL rules do not take in this position."""
129
+
130
+
131
+ def _term(t: Any) -> str:
132
+ return t.n3()
133
+
134
+
135
+ class _Compiler:
136
+ def __init__(self, graph: Any) -> None:
137
+ from rdflib import BNode, Literal, URIRef
138
+ self.g, self.BNode, self.URIRef, self.Literal = graph, BNode, URIRef, Literal
139
+ self.out = RuleSet()
140
+ self.n = 0
141
+ self.u = lambda s: URIRef(s)
142
+
143
+ # -- reading ---------------------------------------------------------------------------------------
144
+ def one(self, s: Any, p: str) -> Any:
145
+ return self.g.value(s, self.u(p))
146
+
147
+ def items(self, head: Any) -> List[Any]:
148
+ """An RDF list's members, unrolled here; the list's own triples are consumed."""
149
+ out, seen = [], set()
150
+ nil = self.u(RDF + "nil")
151
+ while head is not None and head != nil and head not in seen:
152
+ seen.add(head)
153
+ first = self.one(head, RDF + "first")
154
+ if first is None:
155
+ raise _Unsupported("a malformed list")
156
+ out.append(first)
157
+ head = self.one(head, RDF + "rest")
158
+ return out
159
+
160
+ def fresh(self) -> str:
161
+ self.n += 1
162
+ return f"?v{self.n}"
163
+
164
+ def text(self, s: Any, p: str, o: Any) -> str:
165
+ return f"{s.n3()} <{p}> {o.n3()}"
166
+
167
+ def took(self, *triples: tuple) -> None:
168
+ for s, p, o in triples:
169
+ self.out.consumed.add((s, self.u(p) if isinstance(p, str) else p, o))
170
+
171
+ def structure(self, node: Any) -> None:
172
+ """Consume a class expression's own triples (its restriction, its list), recursively (once each: blank
173
+ nodes may reach each other in a cycle, two anonymous classes disjoint with each other)."""
174
+ if not isinstance(node, self.BNode):
175
+ return
176
+ for p, o in self.g.predicate_objects(node):
177
+ if (node, p, o) in self.out.consumed:
178
+ continue
179
+ self.out.consumed.add((node, p, o))
180
+ if str(p) in (OWL + "intersectionOf", OWL + "unionOf", OWL + "oneOf", OWL + "members",
181
+ OWL + "propertyChainAxiom"):
182
+ head = o
183
+ while isinstance(head, self.BNode):
184
+ for p2, o2 in self.g.predicate_objects(head):
185
+ self.out.consumed.add((head, p2, o2))
186
+ self.structure(self.one(head, RDF + "first"))
187
+ head = self.one(head, RDF + "rest")
188
+ elif isinstance(o, self.BNode):
189
+ self.structure(o)
190
+
191
+ # -- expressions ------------------------------------------------------------------------------------
192
+ def prop(self, node: Any) -> Tuple[str, str]:
193
+ """A property expression: ("p", iri) or ("inv", iri) for `[owl:inverseOf p]`."""
194
+ if isinstance(node, self.URIRef):
195
+ return ("p", str(node))
196
+ inner = self.one(node, OWL + "inverseOf")
197
+ if isinstance(inner, self.URIRef):
198
+ return ("inv", str(inner))
199
+ raise _Unsupported("a property expression")
200
+
201
+ def defined(self, node: Any) -> Optional[tuple]:
202
+ """The class expression a node's own constructor triples state, None where it has none."""
203
+ if self.one(node, OWL + "onProperty") is not None:
204
+ p = self.prop(self.one(node, OWL + "onProperty"))
205
+ for kind, tag in (("someValuesFrom", "some"), ("allValuesFrom", "all")):
206
+ filler = self.one(node, OWL + kind)
207
+ if filler is not None:
208
+ return (tag, p, self.expr(filler))
209
+ value = self.one(node, OWL + "hasValue")
210
+ if value is not None:
211
+ return ("value", p, value)
212
+ for kind in ("maxCardinality", "maxQualifiedCardinality"):
213
+ n = self.one(node, OWL + kind)
214
+ if n is not None:
215
+ on = self.one(node, OWL + "onClass") or self.one(node, OWL + "onDataRange")
216
+ return ("max", p, int(n.toPython()) if hasattr(n, "toPython") else -1,
217
+ self.expr(on) if on is not None else ("thing",), OWL + kind)
218
+ raise _Unsupported("a restriction of a kind outside OWL 2 RL")
219
+ for kind, tag in (("intersectionOf", "and"), ("unionOf", "or")):
220
+ head = self.one(node, OWL + kind)
221
+ if head is not None:
222
+ return (tag, tuple(self.expr(x) for x in self.items(head)))
223
+ head = self.one(node, OWL + "oneOf")
224
+ if head is not None:
225
+ return ("one", tuple(self.items(head)))
226
+ if self.one(node, OWL + "complementOf") is not None:
227
+ return ("not", self.expr(self.one(node, OWL + "complementOf")))
228
+ return None
229
+
230
+ def expr(self, node: Any) -> tuple:
231
+ if isinstance(node, self.URIRef):
232
+ iri = str(node)
233
+ if iri in (THING, RDFS + "Resource"):
234
+ return ("thing",)
235
+ if iri.startswith(XSD) or iri == RDFS + "Literal":
236
+ return ("dt", iri)
237
+ return ("named", iri)
238
+ if isinstance(node, self.BNode):
239
+ got = self.defined(node)
240
+ if got is None:
241
+ raise _Unsupported("a blank node with no class constructor")
242
+ return got
243
+ raise _Unsupported("a literal in a class position")
244
+
245
+ # -- premises: the pattern for `var ∈ ce`, alternatives (a union) ----------------------------------
246
+ def step(self, var: str, p: Tuple[str, str], other: str) -> str:
247
+ return f"{var} <{p[1]}> {other} ." if p[0] == "p" else f"{other} <{p[1]}> {var} ."
248
+
249
+ def premises(self, ce: tuple, var: str) -> List[str]:
250
+ kind = ce[0]
251
+ if kind == "named":
252
+ return [f"{var} a <{ce[1]}> ."]
253
+ if kind == "dt":
254
+ test = "isLiteral({v})" if ce[1] == RDFS + "Literal" else f"(isLiteral({{v}}) && DATATYPE({{v}}) = <{ce[1]}>)"
255
+ return [f"FILTER({test.format(v=var)})"]
256
+ if kind == "some":
257
+ y = self.fresh()
258
+ if ce[2][0] == "thing":
259
+ return [self.step(var, ce[1], y)]
260
+ return [self.step(var, ce[1], y) + " " + alt for alt in self.premises(ce[2], y)]
261
+ if kind == "value":
262
+ return [self.step(var, ce[1], _term(ce[2]))]
263
+ if kind == "and":
264
+ alts = [""]
265
+ for part in ce[1]:
266
+ alts = [a + " " + b for a in alts for b in self.premises(part, var)]
267
+ return [a.strip() for a in alts]
268
+ if kind == "or":
269
+ return [alt for part in ce[1] for alt in self.premises(part, var)]
270
+ if kind == "one":
271
+ return [f"VALUES {var} {{ {' '.join(_term(x) for x in ce[1])} }}"]
272
+ raise _Unsupported(f"{_KIND_WORDS.get(kind, kind)} as a subclass")
273
+
274
+ def premise_rule(self, ce: tuple) -> str:
275
+ return {"some": "cls-svf2" if ce[0] == "some" and ce[2][0] == "thing" else "cls-svf1",
276
+ "value": "cls-hv2", "and": "cls-int1", "or": "cls-uni", "one": "cls-oo"}.get(ce[0], "cax-sco")
277
+
278
+ # -- conclusions ---------------------------------------------------------------------------------------
279
+ def conclude(self, ce: tuple, var: str, where: str, rule: str, axiom: str) -> List[Rule]:
280
+ kind = ce[0]
281
+ if kind == "named":
282
+ if ce[1] == NOTHING:
283
+ return [] # cls-nothing2 is a check
284
+ return [Rule(rule, where, var, RDF_TYPE, cls=ce[1], axiom=axiom)]
285
+ if kind in ("thing", "dt"):
286
+ return [] # owl:Thing types nothing stored; a datatype types no IRI
287
+ if kind == "and":
288
+ # Each conjunct its own conclusion (cls-int2): one RL cannot conclude (an existential) is skipped
289
+ # alone, the others stand.
290
+ out: List[Rule] = []
291
+ for part in ce[1]:
292
+ try:
293
+ out += self.conclude(part, var, where, "cls-int2" if rule == "cax-sco" else rule, axiom)
294
+ except _MaxCardinality:
295
+ raise
296
+ except _Unsupported as why:
297
+ self.out.skipped.append((OWL + "intersectionOf", "", f"{axiom}: {why}"))
298
+ return out
299
+ if kind == "all":
300
+ y = self.fresh()
301
+ return self.conclude(ce[2], y, f"{where} {self.step(var, ce[1], y)}", "cls-avf", axiom)
302
+ if kind == "value":
303
+ p, value = ce[1], ce[2]
304
+ if p[0] == "p":
305
+ return [Rule("cls-hv1", where, var, p[1], object=_term(value), value=value, axiom=axiom)]
306
+ if isinstance(value, self.URIRef): # [inverseOf p] value v: v p var
307
+ return [Rule("cls-hv1", f"{where} BIND({_term(value)} AS ?hv)", "?hv", p[1], object=var,
308
+ axiom=axiom)]
309
+ raise _Unsupported("a literal value of an inverse property")
310
+ if kind == "max":
311
+ raise _MaxCardinality(ce)
312
+ raise _Unsupported(f"{_KIND_WORDS.get(kind, kind)} as a superclass")
313
+
314
+ def subsumption(self, sub_node: Any, sup_node: Any, axiom: str, triple: tuple) -> None:
315
+ """`sub ⊑ sup`, from one axiom's triple."""
316
+ try:
317
+ sub, sup = self.expr(sub_node), self.expr(sup_node)
318
+ if sup[0] == "max":
319
+ self.max_check(sub, sup, axiom, triple)
320
+ return
321
+ if sup[0] == "not":
322
+ self.complement_check(sub, sup, axiom)
323
+ self.consume(triple, sub_node, sup_node)
324
+ return
325
+ if sub[0] == "thing":
326
+ raise _Unsupported("owl:Thing as a subclass (it would type every term)")
327
+ if sub[0] == "named" and sup[0] == "named":
328
+ return # saturation's (cax-sco)
329
+ x = "?x"
330
+ self.n = 0
331
+ rules = []
332
+ for where in self.premises(sub, x):
333
+ rules += self.conclude(sup, x, where, self.premise_rule(sub), axiom)
334
+ self.out.rules += rules
335
+ self.consume(triple, sub_node, sup_node)
336
+ except _Unsupported as why:
337
+ self.out.skipped.append((str(triple[1]), "", f"{axiom}: {why}"))
338
+
339
+ def consume(self, triple: tuple, *nodes: Any) -> None:
340
+ self.took(triple)
341
+ for node in nodes:
342
+ self.structure(node)
343
+
344
+ # -- consistency -------------------------------------------------------------------------------------
345
+ def max_check(self, sub: tuple, sup: tuple, axiom: str, triple: tuple) -> None:
346
+ _, p, n, on, kind = sup
347
+ if n == 1:
348
+ self.max_one(sub, p, on, kind, axiom, triple)
349
+ return
350
+ if n != 0:
351
+ raise _Unsupported("a max cardinality above 1 (no OWL 2 RL rule)")
352
+ rule = "cls-maxc1" if kind == OWL + "maxCardinality" else ("cls-maxqc2" if on[0] == "thing" else "cls-maxqc1")
353
+ self.n = 0
354
+ for where in self.premises(sub, "?x"):
355
+ y = "?y"
356
+ fill = [""] if on[0] == "thing" else self.premises(on, y)
357
+ for f in fill:
358
+ self.out.checks.append(Check(rule, f"{where} {self.step('?x', p, y)} {f}", axiom))
359
+ self.took(triple)
360
+ self.structure(triple[2])
361
+
362
+ def max_one(self, sub: tuple, p: Tuple[str, str], on: tuple, kind: str, axiom: str, triple: tuple) -> None:
363
+ """`sub ⊑ ≤1 p (on)`: two `on` values of an `sub`'s p are one (cls-maxc2; cls-maxqc3, cls-maxqc4
364
+ for owl:Thing), a link between IRIs; two literal values that are not one value, a clash."""
365
+ rule = "cls-maxc2" if kind == OWL + "maxCardinality" else \
366
+ ("cls-maxqc4" if on[0] == "thing" else "cls-maxqc3")
367
+ self.n = 0
368
+ for where in self.premises(sub, "?x"):
369
+ fills = [("", "")] if on[0] == "thing" else \
370
+ [(a, b) for a in self.premises(on, "?y1") for b in self.premises(on, "?y2")]
371
+ for f1, f2 in fills:
372
+ both = f"{where} {self.step('?x', p, '?y1')} {f1} {self.step('?x', p, '?y2')} {f2}"
373
+ self.out.links.append(Rule(rule, both, "?y1", OWL + "sameAs", object="?y2", axiom=axiom))
374
+ if on[0] in ("thing", "dt"):
375
+ f = "" if on[0] == "thing" else self.premises(on, "?v")[0]
376
+ self.out.clashes.append(Check(rule, f"{where} {self.step('?x', p, '?v')} {f}", axiom,
377
+ self.step('?x', p, '?v')))
378
+ self.took(triple)
379
+ self.structure(triple[2])
380
+
381
+ def same_as_axiom(self, s: Any, p_: str, o: Any, axiom: str) -> None:
382
+ """An axiom whose RL rule derives owl:sameAs: prp-fp, prp-ifp, prp-key, or an ontology's own sameAs
383
+ or differentFrom between two IRIs."""
384
+ u = self.URIRef
385
+ if p_ == RDF_TYPE and str(o) == OWL + "FunctionalProperty":
386
+ q = self.prop(s)
387
+ self.out.links.append(Rule("prp-fp", f"{self.step('?x', q, '?y1')} {self.step('?x', q, '?y2')}",
388
+ "?y1", OWL + "sameAs", object="?y2", axiom=axiom))
389
+ if q[0] == "p":
390
+ self.out.clashes.append(Check("prp-fp", f"?x <{q[1]}> ?v .", axiom, f"?x <{q[1]}> ?v ."))
391
+ elif p_ == RDF_TYPE and str(o) == OWL + "InverseFunctionalProperty":
392
+ q = self.prop(s)
393
+ self.out.links.append(Rule("prp-ifp", f"{self.step('?x1', q, '?y')} {self.step('?x2', q, '?y')}",
394
+ "?x1", OWL + "sameAs", object="?x2", axiom=axiom))
395
+ elif p_ == OWL + "hasKey":
396
+ keys = [self.prop(k) for k in self.items(o)]
397
+ if not keys:
398
+ raise _Unsupported("a key of no property")
399
+ self.n = 0
400
+ for ce_x in self.premises(self.expr(s), "?x"):
401
+ for ce_y in self.premises(self.expr(s), "?y"):
402
+ steps = " ".join(f"{self.step('?x', k, f'?z{i}')} {self.step('?y', k, f'?z{i}')}"
403
+ for i, k in enumerate(keys))
404
+ self.out.links.append(Rule("prp-key", f"{ce_x} {ce_y} {steps}", "?x", OWL + "sameAs",
405
+ object="?y", axiom=axiom))
406
+ self._list_consumed(o)
407
+ elif p_ == OWL + "sameAs":
408
+ if not (isinstance(s, u) and isinstance(o, u)):
409
+ raise _Unsupported("owl:sameAs of a literal or a blank node (only IRIs are merged)")
410
+ self.out.links.append(Rule("eq-sym", f"VALUES (?a ?b) {{ ({s.n3()} {o.n3()}) }}", "?a",
411
+ OWL + "sameAs", object="?b", axiom=axiom))
412
+ self.took((s, u(p_), o))
413
+
414
+ def different(self, s: Any, p_: str, o: Any, axiom: str) -> None:
415
+ """owl:differentFrom between two IRIs, or an owl:AllDifferent's members: pairs no component may hold
416
+ (eq-diff2, eq-diff3)."""
417
+ u = self.URIRef
418
+ if p_ == OWL + "differentFrom":
419
+ if isinstance(s, u) and isinstance(o, u):
420
+ self.out.distinct.append((str(s), str(o), axiom, "eq-diff1"))
421
+ self.took((s, u(p_), o))
422
+ return
423
+ rule = "eq-diff2" if self.one(s, OWL + "members") is not None else "eq-diff3"
424
+ head = self.one(s, OWL + "members") or self.one(s, OWL + "distinctMembers")
425
+ if head is None:
426
+ return
427
+ members = [str(x) for x in self.items(head) if isinstance(x, u)]
428
+ for i in range(len(members)):
429
+ for j in range(i + 1, len(members)):
430
+ self.out.distinct.append((members[i], members[j], axiom, rule))
431
+ self.consume((s, u(p_), o), s)
432
+ self._list_consumed(head)
433
+
434
+ def complement_check(self, sub: tuple, sup: tuple, axiom: str) -> None:
435
+ self.n = 0
436
+ for a in self.premises(sub, "?x"):
437
+ for b in self.premises(sup[1], "?x"):
438
+ self.out.checks.append(Check("cls-com", f"{a} {b}", axiom))
439
+
440
+ def disjoint(self, rule: str, nodes: Sequence[Any], axiom: str) -> None:
441
+ exprs = [self.expr(n) for n in nodes]
442
+ for i in range(len(exprs)):
443
+ for j in range(i + 1, len(exprs)):
444
+ self.n = 0
445
+ for a in self.premises(exprs[i], "?x"):
446
+ for b in self.premises(exprs[j], "?x"):
447
+ self.out.checks.append(Check(rule, f"{a} {b}", axiom))
448
+
449
+ def class_assertion(self, s: Any, node: Any, axiom: str, triple: tuple) -> None:
450
+ """ClassAssertion(superClassExpression a) (Profiles §4.2.3): the named individual `a` in a class expression
451
+ the ontology states, read as `{a} ⊑ CE` (a VALUES of `a`), so its rules conclude about `a` as about any
452
+ member: cls-hv1 its value, cls-avf, cls-int2, the max cardinality checks and clashes, cls-com."""
453
+ sub = ("one", (s,))
454
+ try:
455
+ sup = self.expr(node)
456
+ if sup[0] == "max":
457
+ self.max_check(sub, sup, axiom, triple)
458
+ return
459
+ if sup[0] == "not":
460
+ self.complement_check(sub, sup, axiom)
461
+ else:
462
+ self.n = 0
463
+ self.out.rules += [r for where in self.premises(sub, "?x")
464
+ for r in self.conclude(sup, "?x", where, "cax-sco", axiom)]
465
+ self.consume(triple, node)
466
+ except _Unsupported as why:
467
+ self.out.skipped.append((RDF_TYPE, "", f"{axiom}: {why}"))
468
+
469
+ def range_check(self, p: str, d: str, axiom: str) -> None:
470
+ """dt-not-type after prp-rng: `p rdfs:range D`, D a datatype of OWL 2's datatype map, makes each literal
471
+ value of p a D; one outside D's value space (by value where the numbers' value spaces nest:
472
+ "1.0"^^xsd:decimal is an xsd:integer, `ql.in_range`) is a contradiction. A range that is no such datatype
473
+ (a class, rdfs:Literal, a datatype of no known namespace) checks nothing."""
474
+ from prograph.plan.ir.ql import datatypes_of, in_range
475
+ if not d.startswith(XSD) and d not in (OWL + "real", OWL + "rational", RDF + "PlainLiteral"):
476
+ return
477
+ dts = datatypes_of(d)
478
+ if dts is None:
479
+ return
480
+ stated = any(True for _ in self.g.triples((None, self.URIRef(p), None)))
481
+ self.out.checks.append(Check("dt-not-type", f"?x <{p}> ?v . FILTER(isLiteral(?v) && !({in_range('v', dts)}))",
482
+ axiom, f"?x <{p}> ?v", (p, dts, stated)))
483
+
484
+ def disjoint_props(self, rule: str, props: Sequence[Any], axiom: str) -> None:
485
+ ps = [self.prop(p) for p in props]
486
+ for i in range(len(ps)):
487
+ for j in range(i + 1, len(ps)):
488
+ self.out.checks.append(Check(rule, f"{self.step('?x', ps[i], '?y')} {self.step('?x', ps[j], '?y')}",
489
+ axiom))
490
+
491
+ # -- the run -------------------------------------------------------------------------------------------
492
+ def run(self) -> RuleSet:
493
+ g, u, out = self.g, self.u, self.out
494
+ out.digest = digest(g)
495
+ for s, p, o in sorted(g, key=lambda t: tuple(x.n3() for x in t)):
496
+ p_ = str(p)
497
+ axiom = self.text(s, p_, o)
498
+ try:
499
+ if p_ == RDFS + "subClassOf" and not (isinstance(s, self.URIRef) and isinstance(o, self.URIRef)):
500
+ self.subsumption(s, o, axiom, (s, p, o))
501
+ elif p_ == OWL + "equivalentClass" and not (isinstance(s, self.URIRef) and isinstance(o, self.URIRef)):
502
+ self.subsumption(s, o, axiom, (s, p, o))
503
+ self.subsumption(o, s, axiom, (s, p, o))
504
+ elif isinstance(s, self.URIRef) and p_ in (OWL + "intersectionOf", OWL + "unionOf", OWL + "oneOf",
505
+ OWL + "someValuesFrom", OWL + "allValuesFrom",
506
+ OWL + "hasValue"):
507
+ # A named class with a constructor of its own: equivalent to it.
508
+ self._named_definition(s, p_, axiom)
509
+ elif p_ == OWL + "inverseOf" and isinstance(s, self.URIRef) and isinstance(o, self.URIRef):
510
+ a, b = str(s), str(o)
511
+ out.rules.append(Rule("prp-inv1", f"?x <{a}> ?y .", "?y", b, object="?x", axiom=axiom))
512
+ out.rules.append(Rule("prp-inv2", f"?x <{b}> ?y .", "?y", a, object="?x", axiom=axiom))
513
+ self.took((s, p, o))
514
+ elif p_ == RDF_TYPE and str(o) == OWL + "SymmetricProperty" and isinstance(s, self.URIRef):
515
+ out.rules.append(Rule("prp-symp", f"?x <{s}> ?y .", "?y", str(s), object="?x", axiom=axiom))
516
+ self.took((s, p, o))
517
+ elif p_ == RDF_TYPE and str(o) == OWL + "TransitiveProperty" and isinstance(s, self.URIRef):
518
+ out.rules.append(Rule("prp-trp", f"?x <{s}>+ ?y .", "?x", str(s), object="?y", literal=True,
519
+ axiom=axiom))
520
+ self.took((s, p, o))
521
+ elif p_ == OWL + "propertyChainAxiom" and isinstance(s, self.URIRef):
522
+ chain = [self.prop(x) for x in self.items(o)]
523
+ vars_ = [f"?c{i}" for i in range(len(chain) + 1)]
524
+ where = " ".join(self.step(vars_[i], q, vars_[i + 1]) for i, q in enumerate(chain))
525
+ out.rules.append(Rule("prp-spo2", where, vars_[0], str(s), object=vars_[-1], literal=True,
526
+ axiom=axiom))
527
+ self.consume((s, p, o), o)
528
+ self._list_consumed(o)
529
+ elif p_ == RDF_TYPE and str(o) == OWL + "IrreflexiveProperty":
530
+ out.checks.append(Check("prp-irp", f"?x {self.step_text(s)} ?x .", axiom))
531
+ self.took((s, p, o))
532
+ elif p_ == RDF_TYPE and str(o) == OWL + "AsymmetricProperty":
533
+ out.checks.append(Check("prp-asyp", f"?x {self.step_text(s)} ?y . ?y {self.step_text(s)} ?x .",
534
+ axiom))
535
+ self.took((s, p, o))
536
+ elif p_ == OWL + "disjointWith":
537
+ self.disjoint("cax-dw", [s, o], axiom)
538
+ self.consume((s, p, o), s, o)
539
+ elif p_ == RDF_TYPE and str(o) == OWL + "AllDisjointClasses":
540
+ members = self.one(s, OWL + "members")
541
+ self.disjoint("cax-adc", self.items(members), axiom)
542
+ self.consume((s, p, o), s)
543
+ elif p_ == OWL + "propertyDisjointWith":
544
+ self.disjoint_props("prp-pdw", [s, o], axiom)
545
+ self.took((s, p, o))
546
+ elif p_ == RDF_TYPE and str(o) == OWL + "AllDisjointProperties":
547
+ self.disjoint_props("prp-adp", self.items(self.one(s, OWL + "members")), axiom)
548
+ self.consume((s, p, o), s)
549
+ elif p_ == RDF_TYPE and str(o) == OWL + "NegativePropertyAssertion":
550
+ src, prop = self.one(s, OWL + "sourceIndividual"), self.one(s, OWL + "assertionProperty")
551
+ target = self.one(s, OWL + "targetIndividual") or self.one(s, OWL + "targetValue")
552
+ if src is None or prop is None or target is None:
553
+ raise _Unsupported("an incomplete negative property assertion")
554
+ # The axiom by its parts, not its blank node.
555
+ kind = "targetIndividual" if self.one(s, OWL + "targetIndividual") is not None else "targetValue"
556
+ axiom = (f"[ a owl:NegativePropertyAssertion ; owl:sourceIndividual {src.n3()} ; "
557
+ f"owl:assertionProperty {prop.n3()} ; owl:{kind} {target.n3()} ]")
558
+ if kind == "targetIndividual":
559
+ out.checks.append(Check("prp-npa1", f"{src.n3()} {prop.n3()} {target.n3()} . BIND(1 AS ?x)",
560
+ axiom, f"{src.n3()} {prop.n3()} {target.n3()}"))
561
+ else: # the value by value: "1.0"^^xsd:decimal is the negated "1"^^xsd:integer
562
+ out.checks.append(Check("prp-npa2", f"{src.n3()} {prop.n3()} ?v . FILTER({same_value('v', target)})",
563
+ axiom, f"{src.n3()} {prop.n3()} ?v"))
564
+ self.consume((s, p, o), s)
565
+ elif p_ == OWL + "complementOf" and isinstance(s, self.URIRef):
566
+ self.complement_check(("named", str(s)), ("not", self.expr(o)), axiom)
567
+ self.consume((s, p, o), o)
568
+ elif p_ in SAME_AS_KINDS or (p_ == RDF_TYPE and str(o) in SAME_AS_KINDS):
569
+ kind = p_ if p_ in SAME_AS_KINDS else str(o)
570
+ if kind in (OWL + "maxCardinality", OWL + "maxQualifiedCardinality"):
571
+ if isinstance(s, self.URIRef) and self.one(s, OWL + "onProperty") is not None:
572
+ # A named class that is the restriction itself: its members are the restriction's.
573
+ self.max_check(("named", str(s)), self.defined(s), axiom, (s, p, o))
574
+ for p2 in ("onProperty", "onClass", "onDataRange"):
575
+ if self.one(s, OWL + p2) is not None:
576
+ self.took((s, self.u(OWL + p2), self.one(s, OWL + p2)))
577
+ continue # else read with the restriction's subsumption
578
+ self.same_as_axiom(s, p_, o, axiom)
579
+ elif p_ == OWL + "differentFrom" or (p_ == RDF_TYPE and str(o) == OWL + "AllDifferent"):
580
+ self.different(s, p_, o, axiom)
581
+ elif p_ == RDF_TYPE and str(o) == NOTHING:
582
+ self.took((s, p, o)) # an individual of owl:Nothing in the ontology: cls-nothing2 below
583
+ elif p_ == RDF_TYPE and isinstance(s, self.URIRef) and isinstance(o, self.BNode) and \
584
+ self.defined(o) is not None:
585
+ self.class_assertion(s, o, axiom, (s, p, o))
586
+ elif p_ == RDFS + "range" and isinstance(s, self.URIRef) and isinstance(o, self.URIRef):
587
+ self.range_check(str(s), str(o), axiom) # the range itself is the RDFS core's (prp-rng)
588
+ except _Unsupported as why:
589
+ out.skipped.append((p_ if p_ != RDF_TYPE else str(o), "", f"{axiom}: {why}"))
590
+ # cls-nothing2: a member of owl:Nothing.
591
+ out.checks.append(Check("cls-nothing2", f"?x a <{NOTHING}> .", f"<{NOTHING}>"))
592
+ # dt-not-type: a literal whose lexical form is not one of its datatype's (a number or a boolean ProGraph
593
+ # reads the lexical space of, `xsd.lexical_pattern`).
594
+ out.checks.append(Check("dt-not-type", f"?x ?p ?v . FILTER({ill_typed('v')})",
595
+ "a literal outside its datatype's lexical space", "?x ?p ?v"))
596
+ # One rule per (rule, pattern, conclusion): an axiom stated twice (two equivalentClass directions of
597
+ # one named pair) is one rule.
598
+ seen, rules = set(), []
599
+ for r in out.rules:
600
+ key = (r.where, r.subject, r.predicate, r.cls, r.object)
601
+ if key not in seen:
602
+ seen.add(key)
603
+ rules.append(r)
604
+ out.rules = rules
605
+ seen, links = set(), []
606
+ for r in out.links:
607
+ key = (r.where, r.subject, r.object)
608
+ if key not in seen:
609
+ seen.add(key)
610
+ links.append(r)
611
+ out.links = links
612
+ applied = {self.text(s, str(p), o) for s, p, o in out.consumed}
613
+ out.partial = [text for _, rule, text in out.skipped if not rule and text.split(": ", 1)[0] in applied]
614
+ return out
615
+
616
+ def step_text(self, p: Any) -> str:
617
+ q = self.prop(p)
618
+ if q[0] == "inv":
619
+ raise _Unsupported("an inverse property expression here")
620
+ return f"<{q[1]}>"
621
+
622
+ def _list_consumed(self, head: Any) -> None:
623
+ while isinstance(head, self.BNode):
624
+ for p2, o2 in self.g.predicate_objects(head):
625
+ self.out.consumed.add((head, p2, o2))
626
+ head = self.one(head, RDF + "rest")
627
+
628
+ def _named_definition(self, s: Any, p_: str, axiom: str) -> None:
629
+ """`:C owl:intersectionOf (...)` (or a restriction's triples on a named class): C ≡ its constructor."""
630
+ if p_ in (OWL + "someValuesFrom", OWL + "allValuesFrom", OWL + "hasValue") and \
631
+ self.one(s, OWL + "onProperty") is None:
632
+ raise _Unsupported("a restriction with no owl:onProperty")
633
+ ce = self.defined(s)
634
+ if ce is None:
635
+ return
636
+ named = ("named", str(s))
637
+ self.n = 0
638
+ rules: List[Rule] = []
639
+ try:
640
+ for where in self.premises(ce, "?x"):
641
+ rules += self.conclude(named, "?x", where, self.premise_rule(ce), axiom)
642
+ except _Unsupported:
643
+ pass # an expression RL cannot take as a subclass: only C ⊑ expression below
644
+ try:
645
+ rules += self.conclude(ce, "?x", f"?x a <{s}> .", "cax-sco", axiom)
646
+ except _Unsupported as why:
647
+ if not rules:
648
+ raise
649
+ self.out.skipped.append((p_, "", f"{axiom}: {why}"))
650
+ self.out.rules += rules
651
+ # Only the constructor's own triples are this rule's: another axiom of the class (an equivalentClass to
652
+ # a named class, which saturation applies; a hasKey, which is warned of) stays its own.
653
+ for p2, o2 in self.g.predicate_objects(s):
654
+ if str(p2) in _CONSTRUCTOR:
655
+ self.took((s, p2, o2))
656
+ self.structure(o2)
657
+ if str(p2) in (OWL + "intersectionOf", OWL + "unionOf", OWL + "oneOf"):
658
+ self._list_consumed(o2)
659
+
660
+
661
+ # A class constructor's own triples, on a named class that holds one (`_named_definition`).
662
+ _CONSTRUCTOR = {OWL + k for k in ("intersectionOf", "unionOf", "oneOf", "onProperty", "someValuesFrom",
663
+ "allValuesFrom", "hasValue")}
664
+
665
+
666
+ @home("owl-literal-value", "Two literals that are one value under OWL 2's datatype map",
667
+ terms=("value-equal literals", "same value", "1 and 1.0", "clash", "prp-npa2", "dt-diff", "functional data "
668
+ "property", "value space"))
669
+ def same_value(v: str, literal: Any) -> str:
670
+ """A SPARQL condition: `?v` is the value of `literal` (an rdflib Literal) under OWL 2's datatype map (Structural
671
+ Specification §4): a number of xsd:decimal's value space (its integer types among them) by its number, so
672
+ "1"^^xsd:integer and "1.0"^^xsd:decimal are one; an xsd:float or xsd:double only of its own datatype, by its
673
+ number with its sign (+0.0 and -0.0 are two values); any other literal by its term. The SQL form, for two
674
+ values of one subject (a clash), is `owl_rl._Run.value_key`."""
675
+ from prograph.schema import xsd
676
+ dt = str(literal.datatype) if getattr(literal, "datatype", None) is not None else None
677
+ decimals = sorted(xsd.INTEGER_DATATYPES | {xsd.DECIMAL})
678
+ if dt in decimals:
679
+ listed = ", ".join(f"<{d}>" for d in decimals)
680
+ return f"(isLiteral(?{v}) && DATATYPE(?{v}) IN ({listed}) && ?{v} = {literal.n3()})"
681
+ if dt in (xsd.DOUBLE, xsd.FLOAT):
682
+ negative = "true" if str(literal).strip().startswith("-") else "false"
683
+ return (f"(isLiteral(?{v}) && DATATYPE(?{v}) = <{dt}> && ?{v} = {literal.n3()} && "
684
+ f"STRSTARTS(STR(?{v}), \"-\") = {negative})")
685
+ return f"sameTerm(?{v}, {literal.n3()})"
686
+
687
+
688
+ def same_values(a: str, b: str) -> str:
689
+ """A SPARQL condition: `?a` and `?b` are one value under OWL 2's datatype map (`same_value`'s rule, for two
690
+ variables): both numbers of xsd:decimal's value space by their number, or both of one of xsd:float and
691
+ xsd:double by their number with their sign, or one term."""
692
+ from prograph.schema import xsd
693
+ decimals = ", ".join(f"<{d}>" for d in sorted(xsd.INTEGER_DATATYPES | {xsd.DECIMAL}))
694
+ out = [f"sameTerm(?{a}, ?{b})",
695
+ f"(isLiteral(?{a}) && isLiteral(?{b}) && DATATYPE(?{a}) IN ({decimals}) && DATATYPE(?{b}) IN ({decimals})"
696
+ f" && ?{a} = ?{b})"]
697
+ for dt in (xsd.DOUBLE, xsd.FLOAT):
698
+ out.append(f"(isLiteral(?{a}) && isLiteral(?{b}) && DATATYPE(?{a}) = <{dt}> && DATATYPE(?{b}) = <{dt}> && "
699
+ f"?{a} = ?{b} && STRSTARTS(STR(?{a}), \"-\") = STRSTARTS(STR(?{b}), \"-\"))")
700
+ return "(" + " || ".join(out) + ")"
701
+
702
+
703
+ def least_literal(a: str, b: str) -> str:
704
+ """A SPARQL expression: of two value-equal terms (`same_values`), `?b` where it is the lesser literal by term
705
+ order (its datatype IRI, then its lexical form, by code point), else `?a`: the one a match by value shows."""
706
+ return (f"IF(isLiteral(?{a}) && isLiteral(?{b}) && (STR(DATATYPE(?{b})) < STR(DATATYPE(?{a})) || "
707
+ f"(DATATYPE(?{b}) = DATATYPE(?{a}) && STR(?{b}) < STR(?{a}))), ?{b}, ?{a})")
708
+
709
+
710
+ def ill_typed(v: str) -> str:
711
+ """A SPARQL condition: `?v` is a literal of a number or boolean datatype whose lexical form is not one of that
712
+ datatype's (`xsd.lexical_pattern`: isNUMERIC is false for an ill-typed number, SPARQL 17.4.2.4)."""
713
+ from prograph.schema import xsd
714
+ numbers = sorted(xsd.INTEGER_DATATYPES | {xsd.DECIMAL, xsd.DOUBLE, xsd.FLOAT})
715
+ listed = ", ".join(f"<{d}>" for d in numbers)
716
+ return (f"isLiteral(?{v}) && ((DATATYPE(?{v}) IN ({listed}) && !isNUMERIC(?{v})) || "
717
+ f"(DATATYPE(?{v}) = <{xsd.BOOLEAN}> && !REGEX(STR(?{v}), \"^({xsd.lexical_pattern(xsd.BOOLEAN)})$\")))")
718
+
719
+
720
+ class _MaxCardinality(_Unsupported):
721
+ pass
722
+
723
+
724
+ _KIND_WORDS = {"all": "allValuesFrom", "some": "someValuesFrom", "or": "unionOf", "one": "oneOf",
725
+ "not": "complementOf", "max": "a max cardinality", "thing": "owl:Thing", "dt": "a datatype"}