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,694 @@
1
+ """Which W3C OWL 2 profiles an ontology's axioms fit, and which of them ProGraph answers under the engine's
2
+ profile (docs/guides/owl-and-ontology.md, "Profiles").
3
+
4
+ Two notions, kept apart:
5
+
6
+ - **The W3C profile** an axiom belongs to (OWL 2 Profiles §3 for QL, §4 for RL), read from its RDF form
7
+ (OWL 2 Mapping to RDF Graphs §3): a subclass axiom fits OWL 2 QL when its subclass is a QL subclass
8
+ expression and its superclass a QL superclass expression, and so on. `AxiomFit.profiles`.
9
+ - **Whether ProGraph answers it today** under 'ql' or 'rl' (`AxiomFit.answered`), from the code that applies
10
+ axioms: under 'ql' the maps' saturation (`saturate.read_ontology`), the QL closure (`ql.read`'s `consumed`:
11
+ every OWL 2 QL axiom kind) and the RDFS core (`rdfs.close`); under 'rl' the saturation, the RDFS core and every
12
+ axiom OWL 2 RL's rules apply (`owl_rl_rules.compile_rules`'s `consumed`, less its one-direction `partial`).
13
+
14
+ An engine refuses an axiom its profile does not answer (`check`): outside the profile ("outside OWL 2 QL"), or
15
+ inside it and not built yet ("not answered under profile 'ql' yet"), each by name. Plain RDFS vocabulary (an
16
+ axiom with no OWL term in it) is never refused: the RDFS core answers it under both profiles, also where it is
17
+ outside the W3C profile (a range of xsd:double, outside OWL 2 QL's datatype map: under 'ql' read as RDFS, the
18
+ report says so). `on_unsupported="ignore"` drops the refused axioms instead: none is reasoned with (`kept_graph`, the graph OWL 2
19
+ RL's rules are compiled from; saturation applies none of them anyway), their triples stay in the default graph as
20
+ the ontology states them, and `ontology_report()` lists them."""
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass, field
25
+ from typing import Any, Dict, FrozenSet, Iterable, List, Optional, Set, Tuple
26
+
27
+ from prograph.rules import module_home
28
+
29
+ module_home("owl-profile-fit", "Which W3C OWL 2 profiles an ontology's axioms fit, and which the engine answers",
30
+ terms=("OWL 2 QL", "OWL 2 RL", "OWL profile", "profile check", "axiom outside the profile",
31
+ "not answered yet", "ontology_report", "on_unsupported", "OWLProfileError",
32
+ "W3C profile", "plain RDFS", "dropped axioms"))
33
+
34
+ RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
35
+ RDFS = "http://www.w3.org/2000/01/rdf-schema#"
36
+ OWL = "http://www.w3.org/2002/07/owl#"
37
+ from prograph.schema.xsd import XSD # noqa: E402 - the datatypes' home
38
+ RDF_TYPE = RDF + "type"
39
+ THING, NOTHING = OWL + "Thing", OWL + "Nothing"
40
+ ON_UNSUPPORTED = ("error", "ignore")
41
+ PROFILES = ("ql", "rl")
42
+ SHOWN = 20
43
+ FILLER_NOTE = "filler used for consistency checks only; unnamed individuals are never returned"
44
+
45
+ # The axioms each profile answers today, in words: what `saturate.read_ontology`, `rdfs.close` and
46
+ # `owl_rl_rules.compile_rules` apply (kept beside them; `tests/test_ontology_report.py` checks each word).
47
+ BUILT = {
48
+ "ql": ("every OWL 2 QL axiom, by rewriting: rdfs:subClassOf, owl:equivalentClass, rdfs:subPropertyOf, "
49
+ "owl:equivalentProperty, rdfs:domain and rdfs:range, with owl:inverseOf properties and someValuesFrom "
50
+ "restrictions where OWL 2 QL allows them (a named filler is read for the consistency checks only); owl:inverseOf, symmetric and reflexive properties; "
51
+ "intersectionOf and complementOf as a superclass; and the consistency checks (owl:disjointWith, "
52
+ "owl:AllDisjointClasses, owl:propertyDisjointWith, owl:AllDisjointProperties, asymmetric properties, "
53
+ "owl:differentFrom and owl:AllDifferent, a data property's range); the RDFS vocabulary (the RDFS core); "
54
+ "class and property assertions"),
55
+ "rl": ("all of ql's, and OWL 2 RL's rules: owl:inverseOf, symmetric, transitive, functional and "
56
+ "inverse-functional properties, property chains, owl:hasKey, owl:sameAs, owl:differentFrom and "
57
+ "owl:AllDifferent, someValuesFrom, allValuesFrom and hasValue restrictions, intersectionOf, unionOf "
58
+ "and oneOf, max cardinality 0 and 1, and the consistency checks (owl:disjointWith, "
59
+ "owl:AllDisjointClasses, owl:propertyDisjointWith, owl:AllDisjointProperties, irreflexive and "
60
+ "asymmetric properties, owl:complementOf, negative property assertions)"),
61
+ }
62
+
63
+ # Declarations: no axiom (OWL 2 Mapping to RDF Graphs, Table 7).
64
+ _DECLARED = {OWL + k for k in ("Class", "ObjectProperty", "DatatypeProperty", "AnnotationProperty",
65
+ "NamedIndividual", "Ontology", "Restriction",
66
+ # OWL 1's vocabulary kept for backward compatibility (OWL 2 Mapping to RDF Graphs,
67
+ # Table 2): a declaration (owl:DeprecatedClass and owl:DeprecatedProperty with an
68
+ # owl:deprecated annotation besides).
69
+ "DeprecatedClass", "DeprecatedProperty", "OntologyProperty", "DataRange")} | \
70
+ {RDFS + "Class", RDFS + "Datatype", RDF + "Property", RDF + "List"}
71
+ _ANNOTATIONS = {RDFS + k for k in ("label", "comment", "seeAlso", "isDefinedBy")} | \
72
+ {OWL + k for k in ("versionInfo", "versionIRI", "priorVersion", "backwardCompatibleWith",
73
+ "incompatibleWith", "deprecated", "imports")}
74
+ # A class expression's (or a list's, or a reified axiom's) own triples: part of the axiom that reaches it.
75
+ _PARTS = {OWL + k for k in ("onProperty", "onProperties", "someValuesFrom", "allValuesFrom", "hasValue",
76
+ "hasSelf", "minCardinality", "maxCardinality", "cardinality",
77
+ "minQualifiedCardinality", "maxQualifiedCardinality", "qualifiedCardinality",
78
+ "onClass", "onDataRange", "intersectionOf", "unionOf", "complementOf", "oneOf",
79
+ "inverseOf", "onDatatype", "withRestrictions", "datatypeComplementOf", "members",
80
+ "distinctMembers", "sourceIndividual", "assertionProperty", "targetIndividual",
81
+ "targetValue", "annotatedSource", "annotatedProperty", "annotatedTarget")} | \
82
+ {RDF + "first", RDF + "rest", RDF_TYPE}
83
+ _AXIOM_TYPES = {OWL + k for k in ("AllDisjointClasses", "AllDisjointProperties", "AllDifferent",
84
+ "NegativePropertyAssertion")}
85
+ _REIFIED = {OWL + "Axiom", OWL + "Annotation"}
86
+ _DEFINITION = {OWL + k for k in ("intersectionOf", "unionOf", "oneOf", "complementOf", "onProperty",
87
+ "someValuesFrom", "allValuesFrom", "hasValue", "hasSelf", "minCardinality",
88
+ "maxCardinality", "cardinality", "minQualifiedCardinality",
89
+ "maxQualifiedCardinality", "qualifiedCardinality", "onClass", "onDataRange")}
90
+ # OWL 2 Profiles §3.2 and §4.2: datatypes outside each profile's datatype map.
91
+ _NOT_QL_DT = {XSD + k for k in ("double", "float", "nonPositiveInteger", "positiveInteger", "negativeInteger",
92
+ "long", "int", "short", "byte", "unsignedLong", "unsignedInt", "unsignedShort",
93
+ "unsignedByte", "language", "boolean",
94
+ # Not in §3.2.1's list either: the dates and times other than xsd:dateTime(Stamp).
95
+ "date", "time", "gYear", "gYearMonth", "gMonth", "gMonthDay", "gDay", "duration",
96
+ "dayTimeDuration", "yearMonthDuration")}
97
+ _NOT_RL_DT = {OWL + "real", OWL + "rational"}
98
+ # The top and bottom properties: outside OWL 2 RL (Profiles 4.2.1).
99
+ _TOPS = {OWL + k for k in ("topObjectProperty", "bottomObjectProperty", "topDataProperty", "bottomDataProperty")}
100
+ _TOP_NOT_RL = "a top or bottom property: OWL 2 RL has none (Profiles 4.2.1)"
101
+ _CHARACTERISTIC = { # a property characteristic: (in words, in QL, in RL)
102
+ OWL + "FunctionalProperty": ("a functional property", False, True),
103
+ OWL + "InverseFunctionalProperty": ("an inverse-functional property", False, True),
104
+ OWL + "TransitiveProperty": ("a transitive property", False, True),
105
+ OWL + "SymmetricProperty": ("a symmetric property", True, True),
106
+ OWL + "AsymmetricProperty": ("an asymmetric property", True, True),
107
+ OWL + "ReflexiveProperty": ("a reflexive property", True, False),
108
+ OWL + "IrreflexiveProperty": ("an irreflexive property", False, True),
109
+ }
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class AxiomFit:
114
+ """One axiom of an ontology: its short Turtle form (`axiom`), its subject's IRI ('' for a blank node),
115
+ what it is in words (`kind`), the W3C OWL 2 profiles it fits (`profiles`: of 'ql', 'rl') with why it is
116
+ outside each other one (`why`), and the profiles ProGraph answers it under today (`answered`)."""
117
+ axiom: str
118
+ subject: str
119
+ kind: str
120
+ profiles: FrozenSet[str]
121
+ why: Tuple[Tuple[str, str], ...] = ()
122
+ answered: FrozenSet[str] = frozenset()
123
+ rdfs: bool = False
124
+ triples: FrozenSet[Any] = field(default=frozenset(), compare=False, repr=False)
125
+ note: str = "" # a caveat on how an answered axiom is read (`C ⊑ ∃p.D`: `FILLER_NOTE`)
126
+
127
+ def status(self, profile: str) -> str:
128
+ """Under `profile`: 'answered', 'outside the profile' (the W3C profile has no such axiom; never for
129
+ plain RDFS), or 'not answered yet' (inside the profile, not built)."""
130
+ if profile not in self.profiles and not self.rdfs:
131
+ return "outside the profile"
132
+ return "answered" if profile in self.answered else "not answered yet"
133
+
134
+ def reason(self, profile: str) -> str:
135
+ """Why `profile` refuses it, in words ('' where it answers it)."""
136
+ status = self.status(profile)
137
+ if status == "answered":
138
+ return ""
139
+ other = [p for p in PROFILES if p != profile][0]
140
+ if status == "outside the profile":
141
+ why = dict(self.why).get(profile, "")
142
+ if why.endswith(f"is not in OWL 2 {profile.upper()}"):
143
+ why = "" # the kind says it already
144
+ text = f"outside OWL 2 {profile.upper()}" + (f" ({why})" if why else "")
145
+ if other in self.profiles:
146
+ text += f"; needs profile '{other}'" + ("" if other in self.answered else
147
+ f" (not answered under '{other}' yet either)")
148
+ else:
149
+ text += f"; outside OWL 2 {other.upper()} too: neither profile"
150
+ if profile == "rl" and why == "owl:Thing as a superclass" and self.axiom.endswith(" owl:Thing") and \
151
+ self.kind in ("a class assertion", "a subclass axiom", "a domain", "a range"):
152
+ text += ("; OWL 2 RL's grammar has no owl:Thing there, and the axiom adds nothing (everything is an "
153
+ "owl:Thing): remove it, or load the ontology with on_unsupported='ignore'")
154
+ return text
155
+ text = f"in OWL 2 {profile.upper()}, not answered under profile '{profile}' yet"
156
+ if other in self.answered:
157
+ text += f"; profile '{other}' answers it"
158
+ return text
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class OntologyReport:
163
+ """Which W3C OWL 2 profiles an ontology fits and which of its axioms an engine answers: every axiom
164
+ (declarations and annotations aside) with its profiles and status under `profile`, the axioms that
165
+ profile refuses (`refused`), and those `on_unsupported="ignore"` dropped (`dropped`)."""
166
+ profile: str
167
+ on_unsupported: str
168
+ axioms: Tuple[AxiomFit, ...] = ()
169
+
170
+ @property
171
+ def fits(self) -> str:
172
+ """The W3C profiles the whole ontology fits: 'both', 'ql', 'rl' or 'neither'."""
173
+ ql = all("ql" in a.profiles for a in self.axioms)
174
+ rl = all("rl" in a.profiles for a in self.axioms)
175
+ return "both" if ql and rl else "ql" if ql else "rl" if rl else "neither"
176
+
177
+ @property
178
+ def refused(self) -> Tuple[AxiomFit, ...]:
179
+ """The axioms `profile` does not answer: outside it, or not answered there yet."""
180
+ return tuple(a for a in self.axioms if a.status(self.profile) != "answered")
181
+
182
+ @property
183
+ def dropped(self) -> Tuple[AxiomFit, ...]:
184
+ """The refused axioms `on_unsupported="ignore"` dropped (empty under "error", which raises)."""
185
+ return self.refused if self.on_unsupported == "ignore" else ()
186
+
187
+ def outside(self, profile: str) -> Tuple[AxiomFit, ...]:
188
+ """The axioms outside the W3C profile `profile` ('ql' or 'rl'), plain RDFS included."""
189
+ return tuple(a for a in self.axioms if profile not in a.profiles)
190
+
191
+ def summary(self) -> str:
192
+ fits = {"both": "OWL 2 QL and OWL 2 RL", "neither": "neither OWL 2 QL nor OWL 2 RL"}.get(
193
+ self.fits, f"OWL 2 {self.fits.upper()} only")
194
+ text = (f"{len(self.axioms)} axioms; the ontology fits {fits}. Under profile '{self.profile}': "
195
+ f"{len(self.axioms) - len(self.refused)} answered, {len(self.refused)} not")
196
+ if self.dropped:
197
+ text += " (dropped: on_unsupported='ignore')"
198
+ noted = [a for a in self.axioms if a.note]
199
+ if noted:
200
+ text += ". Notes: " + "; ".join(f"{a.axiom} ({a.note})" for a in noted[:3]) + \
201
+ (f" and {len(noted) - 3} more" if len(noted) > 3 else "")
202
+ for profile in PROFILES:
203
+ out = self.outside(profile)
204
+ if out:
205
+ text += f". Outside OWL 2 {profile.upper()}: " + "; ".join(
206
+ f"{a.axiom} ({dict(a.why).get(profile, a.kind)}"
207
+ f"{f'; under {profile} read as RDFS' if a.rdfs else ''})" for a in out[:3]) + \
208
+ (f" and {len(out) - 3} more" if len(out) > 3 else "")
209
+ return text
210
+
211
+ def message(self) -> str:
212
+ """The refusal's text: each refused axiom by name, what it is and why, and what the profile answers."""
213
+ shown = self.refused[:SHOWN]
214
+ lines = [f"the ontology has {len(self.refused)} axiom{'s' if len(self.refused) != 1 else ''} profile "
215
+ f"'{self.profile}' does not answer:"]
216
+ lines += [f" {a.axiom}: {a.kind}: {a.reason(self.profile)}" for a in shown]
217
+ if len(self.refused) > SHOWN:
218
+ lines.append(f" and {len(self.refused) - SHOWN} more (this error's report, OWLProfileError.report.refused, "
219
+ f"lists them all)")
220
+ lines.append(f"Under profile '{self.profile}' ProGraph answers {BUILT[self.profile]}.")
221
+ lines.append("Pick the profile the axioms need (profile='ql' or 'rl'), or load the ontology with "
222
+ "on_unsupported='ignore' to drop them (the engine's ontology_report() then lists what was "
223
+ "dropped). OWLProfileError.report gives every axiom's profiles and why.")
224
+ return "\n".join(lines)
225
+
226
+
227
+ # -- reading an ontology's axioms --------------------------------------------------------------------------------
228
+
229
+
230
+ def axioms(graph: Any, consumed: Optional[Set[tuple]] = None, partial: Iterable[str] = ()) -> List[AxiomFit]:
231
+ """Every axiom of an rdflib graph, declarations and annotations aside, with its W3C profiles and the
232
+ profiles ProGraph answers it under (`consumed` and `partial`: `owl_rl_rules.RuleSet`'s, for 'rl'; for 'ql'
233
+ the triples `ql.read` reads)."""
234
+ from prograph.plan.ir import ql
235
+ return _Reader(graph, consumed if consumed is not None else set(), set(partial), ql.read(graph).consumed).run()
236
+
237
+
238
+ def report(graph: Any, profile: str, on_unsupported: str = "error") -> OntologyReport:
239
+ """The `OntologyReport` of an rdflib graph under `profile`."""
240
+ from prograph.plan.ir.owl_rl_rules import compile_rules
241
+ rules = compile_rules(graph)
242
+ return OntologyReport(profile, on_unsupported, tuple(axioms(graph, rules.consumed, rules.partial)))
243
+
244
+
245
+ def check(graph: Any, profile: str, on_unsupported: str = "error") -> OntologyReport:
246
+ """The report, after refusing what `profile` does not answer (`OWLProfileError`, naming each axiom) unless
247
+ `on_unsupported` is "ignore"."""
248
+ if on_unsupported not in ON_UNSUPPORTED:
249
+ raise ValueError(f"on_unsupported is one of {', '.join(ON_UNSUPPORTED)}, not {on_unsupported!r}")
250
+ got = report(graph, profile, on_unsupported)
251
+ if got.refused and on_unsupported == "error":
252
+ from prograph.utils.exceptions import OWLProfileError
253
+ raise OWLProfileError(got.message(), report=got)
254
+ return got
255
+
256
+
257
+ def kept_graph(graph: Any, got: OntologyReport) -> Any:
258
+ """`graph` without the triples of the axioms `got` dropped (the graph itself where none were)."""
259
+ if not got.dropped:
260
+ return graph
261
+ import rdflib
262
+ # A triple a kept axiom reaches too (a blank node two axioms share) stays.
263
+ kept = set().union(*(a.triples for a in got.axioms if a not in got.dropped))
264
+ gone = set().union(*(a.triples for a in got.dropped)) - kept
265
+ out = rdflib.Graph()
266
+ for t in graph:
267
+ if t not in gone:
268
+ out.add(t)
269
+ return out
270
+
271
+
272
+ class _Reader:
273
+ def __init__(self, graph: Any, consumed: Set[tuple], partial: Set[str], ql: Any = frozenset()) -> None:
274
+ from rdflib import BNode, Literal, URIRef
275
+ self.g, self.BNode, self.Literal, self.URIRef = graph, BNode, Literal, URIRef
276
+ self.consumed, self.partial, self.ql = consumed, partial, ql
277
+ self.partial_axioms = {t.split(": ", 1)[0] for t in partial}
278
+ self.inner = {o for o in graph.objects() if isinstance(o, BNode)}
279
+ self.annotation_props = {str(s) for s in graph.subjects(URIRef(RDF_TYPE), URIRef(OWL + "AnnotationProperty"))}
280
+ self.datatypes = {str(s) for s in graph.subjects(URIRef(RDF_TYPE), URIRef(RDFS + "Datatype"))}
281
+
282
+ def one(self, s: Any, p: str) -> Any:
283
+ return self.g.value(s, self.URIRef(p))
284
+
285
+ # -- the RDF form of class and property expressions -----------------------------------------------------
286
+ def items(self, head: Any) -> List[Any]:
287
+ out, seen = [], set()
288
+ while head is not None and str(head) != RDF + "nil" and head not in seen:
289
+ seen.add(head)
290
+ first = self.one(head, RDF + "first")
291
+ if first is None:
292
+ return out
293
+ out.append(first)
294
+ head = self.one(head, RDF + "rest")
295
+ return out
296
+
297
+ def is_datarange(self, node: Any) -> bool:
298
+ if isinstance(node, self.URIRef):
299
+ s = str(node)
300
+ return s.startswith(XSD) or s in (RDFS + "Literal", RDF + "PlainLiteral", RDF + "langString",
301
+ RDF + "XMLLiteral", OWL + "real", OWL + "rational") \
302
+ or s in self.datatypes
303
+ return isinstance(node, self.BNode) and (
304
+ (node, self.URIRef(RDF_TYPE), self.URIRef(RDFS + "Datatype")) in self.g
305
+ or self.one(node, OWL + "onDatatype") is not None
306
+ or self.one(node, OWL + "datatypeComplementOf") is not None)
307
+
308
+ def ce(self, node: Any, own: bool = False) -> tuple:
309
+ """A class expression: ('named', iri), ('thing',), ('nothing',), ('dt', range), ('some', data, filler),
310
+ ('all', data, filler), ('value',), ('self',), ('card', kind, n, filler), ('and', parts), ('or', parts),
311
+ ('not', part), ('one',), ('bad', why). `own`: a named class read through its own constructor triples."""
312
+ if isinstance(node, self.URIRef) and not own:
313
+ s = str(node)
314
+ if s in (THING,):
315
+ return ("thing",)
316
+ if s == NOTHING:
317
+ return ("nothing",)
318
+ if self.is_datarange(node):
319
+ return ("dt", self.datarange(node))
320
+ return ("named", s)
321
+ if not isinstance(node, (self.BNode, self.URIRef)):
322
+ return ("bad", "a literal where a class is expected")
323
+ if self.is_datarange(node):
324
+ return ("dt", self.datarange(node))
325
+ on = self.one(node, OWL + "onProperty")
326
+ if on is not None:
327
+ if isinstance(on, self.BNode) and self.one(on, OWL + "inverseOf") is None:
328
+ return ("bad", "a property expression that is not a property or its inverse")
329
+ for kind in ("someValuesFrom", "allValuesFrom"):
330
+ filler = self.one(node, OWL + kind)
331
+ if filler is not None:
332
+ data = self.is_datarange(filler)
333
+ return ("some" if kind[0] == "s" else "all", data,
334
+ ("dt", self.datarange(filler)) if data else self.ce(filler))
335
+ if self.one(node, OWL + "hasValue") is not None:
336
+ return ("value",)
337
+ if self.one(node, OWL + "hasSelf") is not None:
338
+ return ("self",)
339
+ for kind in ("minCardinality", "maxCardinality", "cardinality", "minQualifiedCardinality",
340
+ "maxQualifiedCardinality", "qualifiedCardinality"):
341
+ n = self.one(node, OWL + kind)
342
+ if n is not None:
343
+ filler = self.one(node, OWL + "onClass")
344
+ data_on = self.one(node, OWL + "onDataRange")
345
+ fill = self.ce(filler) if filler is not None else \
346
+ ("dt", self.datarange(data_on)) if data_on is not None else None
347
+ try:
348
+ count = int(n.toPython())
349
+ except (TypeError, ValueError):
350
+ count = -1
351
+ return ("card", kind.replace("Qualified", "").replace("Cardinality", "") or "exact", count, fill)
352
+ return ("bad", "a restriction with no constructor")
353
+ if self.one(node, OWL + "onProperties") is not None:
354
+ return ("bad", "an n-ary data restriction")
355
+ for kind, tag in (("intersectionOf", "and"), ("unionOf", "or")):
356
+ head = self.one(node, OWL + kind)
357
+ if head is not None:
358
+ parts = tuple(self.ce(x) for x in self.items(head))
359
+ # One operand is that operand (the OWL 2 test cases' profile declarations read it so).
360
+ return parts[0] if len(parts) == 1 else (tag, parts)
361
+ if self.one(node, OWL + "complementOf") is not None:
362
+ return ("not", self.ce(self.one(node, OWL + "complementOf")))
363
+ if self.one(node, OWL + "oneOf") is not None:
364
+ return ("one",)
365
+ return ("bad", "a blank node with no class constructor")
366
+
367
+ def datarange(self, node: Any) -> Tuple[str, ...]:
368
+ """('ok' | a reason the range is outside a profile, the datatypes it names...)."""
369
+ if isinstance(node, self.URIRef):
370
+ return ("ok", str(node))
371
+ if self.one(node, OWL + "onDatatype") is not None:
372
+ return ("a datatype restriction", str(self.one(node, OWL + "onDatatype")))
373
+ if self.one(node, OWL + "datatypeComplementOf") is not None:
374
+ return ("a datatype complement",)
375
+ if self.one(node, OWL + "oneOf") is not None:
376
+ return ("an enumeration of literals",)
377
+ if self.one(node, OWL + "unionOf") is not None:
378
+ return ("a union of data ranges",)
379
+ head = self.one(node, OWL + "intersectionOf")
380
+ if head is not None:
381
+ parts = [self.datarange(x) for x in self.items(head)]
382
+ bad = next((p[0] for p in parts if p[0] != "ok"), None)
383
+ return (bad or "ok",) + tuple(d for p in parts for d in p[1:])
384
+ return ("a data range of no known form",)
385
+
386
+ # -- the profiles' grammars (OWL 2 Profiles §3.2.3 and §4.2.3), each a reason or '' --------------------
387
+ def anonymous(self, *nodes: Any) -> str:
388
+ """Why OWL 2 QL refuses an assertion about a blank node (Profiles 3.2.1: no anonymous individuals)."""
389
+ return "an anonymous individual (OWL 2 QL has none)" if any(isinstance(n, self.BNode) for n in nodes) else ""
390
+
391
+ def _dt(self, r: Tuple[str, ...], profile: str) -> str:
392
+ if r[0] != "ok":
393
+ return r[0]
394
+ bad = _NOT_QL_DT if profile == "ql" else _NOT_RL_DT
395
+ named = [d for d in r[1:] if d in bad]
396
+ return f"the datatype <{named[0]}>" if named else ""
397
+
398
+ def ql_sub(self, c: tuple) -> str:
399
+ k = c[0]
400
+ if k in ("named", "thing", "nothing"):
401
+ return ""
402
+ if k == "some":
403
+ if c[1]:
404
+ return self._dt(c[2][1], "ql")
405
+ return "" if c[2][0] == "thing" else "someValuesFrom a class other than owl:Thing as a subclass"
406
+ return self._what(c, "as a subclass")
407
+
408
+ def ql_super(self, c: tuple) -> str:
409
+ k = c[0]
410
+ if k in ("named", "thing", "nothing"):
411
+ return ""
412
+ if k == "and":
413
+ return next((w for w in map(self.ql_super, c[1]) if w), "")
414
+ if k == "not":
415
+ return self.ql_sub(c[1]) and "a complement of an expression that is not a QL subclass expression"
416
+ if k == "some":
417
+ if c[1]:
418
+ return self._dt(c[2][1], "ql")
419
+ return "" if c[2][0] in ("named", "thing", "nothing") else \
420
+ "someValuesFrom a class expression as a superclass"
421
+ return self._what(c, "as a superclass")
422
+
423
+ def rl_sub(self, c: tuple) -> str:
424
+ k = c[0]
425
+ if k in ("named", "nothing", "value", "one"):
426
+ return ""
427
+ if k == "thing":
428
+ return "owl:Thing as a subclass"
429
+ if k in ("and", "or"):
430
+ return next((w for w in map(self.rl_sub, c[1]) if w), "")
431
+ if k == "some":
432
+ if c[1]:
433
+ return self._dt(c[2][1], "rl")
434
+ return "" if c[2][0] == "thing" else self.rl_sub(c[2])
435
+ return self._what(c, "as a subclass")
436
+
437
+ def rl_super(self, c: tuple) -> str:
438
+ k = c[0]
439
+ if k in ("named", "nothing", "value"):
440
+ return ""
441
+ if k == "thing":
442
+ return "owl:Thing as a superclass"
443
+ if k == "and":
444
+ return next((w for w in map(self.rl_super, c[1]) if w), "")
445
+ if k == "not":
446
+ return self.rl_sub(c[1]) and "a complement of an expression that is not an RL subclass expression"
447
+ if k == "all":
448
+ return self._dt(c[2][1], "rl") if c[1] else self.rl_super(c[2])
449
+ if k == "card" and c[1] == "max" and c[2] in (0, 1):
450
+ fill = c[3]
451
+ if fill is None or fill[0] == "thing": # owl:onClass owl:Thing is allowed (Profiles 4.2.3)
452
+ return ""
453
+ return self._dt(fill[1], "rl") if fill[0] == "dt" else self.rl_sub(fill)
454
+ return self._what(c, "as a superclass")
455
+
456
+ def rl_equiv(self, c: tuple) -> str:
457
+ k = c[0]
458
+ if k in ("named", "nothing", "value"):
459
+ return ""
460
+ if k == "thing":
461
+ return "owl:Thing in an equivalence"
462
+ if k == "and":
463
+ return next((w for w in map(self.rl_equiv, c[1]) if w), "")
464
+ return self._what(c, "in an equivalence")
465
+
466
+ @staticmethod
467
+ def _what(c: tuple, where: str) -> str:
468
+ k = c[0]
469
+ if k == "bad":
470
+ return c[1]
471
+ words = {"some": "someValuesFrom", "all": "allValuesFrom", "value": "hasValue", "self": "hasSelf",
472
+ "and": "intersectionOf", "or": "unionOf", "not": "complementOf", "one": "oneOf",
473
+ "dt": "a data range", "thing": "owl:Thing"}
474
+ if k == "card":
475
+ return f"{c[1]} cardinality {c[2]} {where}"
476
+ return f"{words.get(k, k)} {where}"
477
+
478
+ # -- one axiom -----------------------------------------------------------------------------------------
479
+ def fit(self, kind: str, ql: str, rl: str) -> Tuple[str, FrozenSet[str], Tuple[Tuple[str, str], ...]]:
480
+ profiles = frozenset(p for p, w in (("ql", ql), ("rl", rl)) if not w)
481
+ return kind, profiles, tuple((p, w) for p, w in (("ql", ql), ("rl", rl)) if w)
482
+
483
+ def classify(self, s: Any, p: str, o: Any, main: List[tuple]) -> Optional[tuple]:
484
+ """(kind, profiles, why) of the axiom stated by (s, p, o); None for a declaration or an annotation."""
485
+ U = self.URIRef
486
+ if p == RDF_TYPE:
487
+ t = str(o)
488
+ if t == THING and isinstance(s, self.BNode) and s in self.inner and \
489
+ self.one(s, OWL + "onProperty") is None and not any(
490
+ str(q) in _DEFINITION for q in self.g.predicates(s)):
491
+ pass # an anonymous individual typed owl:Thing: a class assertion, below
492
+ elif t in _DECLARED or t in _REIFIED or (isinstance(s, self.BNode) and s in self.inner):
493
+ return None
494
+ if t in _CHARACTERISTIC:
495
+ words, ql, rl = _CHARACTERISTIC[t]
496
+ if isinstance(s, self.BNode) and self.one(s, OWL + "inverseOf") is None:
497
+ return self.fit(words, "a property expression", "a property expression")
498
+ return self.fit(words, "" if ql else f"{words} is not in OWL 2 QL",
499
+ "" if rl else f"{words} is not in OWL 2 RL")
500
+ if t == OWL + "AllDisjointClasses":
501
+ cs = [self.ce(x) for x in self.items(self.one(s, OWL + "members"))]
502
+ return self.fit("disjoint classes", next((w for w in map(self.ql_sub, cs) if w), ""),
503
+ next((w for w in map(self.rl_sub, cs) if w), ""))
504
+ if t == OWL + "AllDisjointProperties":
505
+ return self.fit("disjoint properties", "", "")
506
+ if t == OWL + "AllDifferent":
507
+ return self.fit("different individuals", "", "")
508
+ if t == OWL + "NegativePropertyAssertion":
509
+ return self.fit("a negative property assertion", "a negative property assertion is not in OWL 2 QL", "")
510
+ if t not in (THING, NOTHING) and (t.startswith(OWL) or t.startswith(RDFS) or t.startswith(RDF)):
511
+ if t.startswith(OWL):
512
+ return self.fit(f"a type of owl:{t[len(OWL):]}", "not an OWL 2 QL axiom", "not an OWL 2 RL axiom")
513
+ return None
514
+ c = self.ce(o)
515
+ return self.fit("a class assertion", self.anonymous(s) or (
516
+ "" if c[0] in ("named", "thing", "nothing") else "a class assertion to a class expression"),
517
+ self.rl_super(c))
518
+ if p in (RDFS + "subClassOf", OWL + "equivalentClass", OWL + "disjointWith"):
519
+ a, b = self.ce(s), self.ce(o)
520
+ if p == OWL + "equivalentClass" and a[0] == "dt" and b[0] == "dt":
521
+ # DatatypeDefinition, in both profiles' Axiom production; its data range must be the profile's.
522
+ return self.fit("a datatype definition", self._dt(a[1], "ql") or self._dt(b[1], "ql"),
523
+ self._dt(a[1], "rl") or self._dt(b[1], "rl"))
524
+ if a[0] == "dt" or b[0] == "dt":
525
+ return self.fit("a data range as a class", "a data range where a class is expected",
526
+ "a data range where a class is expected")
527
+ if p == RDFS + "subClassOf":
528
+ return self.fit("a subclass axiom", self.ql_sub(a) or self.ql_super(b),
529
+ self.rl_sub(a) or self.rl_super(b))
530
+ if p == OWL + "equivalentClass":
531
+ return self.fit("an equivalence of classes", self.ql_sub(a) or self.ql_sub(b),
532
+ self.rl_equiv(a) or self.rl_equiv(b))
533
+ return self.fit("disjoint classes", self.ql_sub(a) or self.ql_sub(b), self.rl_sub(a) or self.rl_sub(b))
534
+ if p in _DEFINITION and isinstance(s, U):
535
+ # A named class with a constructor of its own: equivalent to it (Mapping to RDF Graphs, Table 15).
536
+ c = self.ce(s, own=True)
537
+ return self.fit("an equivalence of classes", self.ql_sub(c), self.rl_equiv(c))
538
+ if p == OWL + "disjointUnionOf":
539
+ return self.fit("a disjoint union", "a disjoint union is not in OWL 2 QL",
540
+ "a disjoint union is not in OWL 2 RL")
541
+ if p == OWL + "propertyChainAxiom":
542
+ return self.fit("a property chain", "a property chain is not in OWL 2 QL", "")
543
+ if p == OWL + "hasKey":
544
+ return self.fit("a key", "a key is not in OWL 2 QL", self.rl_sub(self.ce(s)))
545
+ if p == OWL + "sameAs":
546
+ return self.fit("individual equality", "owl:sameAs is not in OWL 2 QL", "")
547
+ if p == OWL + "differentFrom":
548
+ return self.fit("different individuals", "", "")
549
+ if p in (RDFS + "subPropertyOf", OWL + "equivalentProperty", OWL + "inverseOf", OWL + "propertyDisjointWith"):
550
+ if isinstance(s, self.BNode) and p == OWL + "inverseOf" and s in self.inner:
551
+ return None
552
+ words = {RDFS + "subPropertyOf": "a subproperty axiom", OWL + "equivalentProperty":
553
+ "an equivalence of properties", OWL + "inverseOf": "inverse properties",
554
+ OWL + "propertyDisjointWith": "disjoint properties"}[p]
555
+ return self.fit(words, "", "")
556
+ if p in (RDFS + "domain", RDFS + "range"):
557
+ words = "a domain" if p == RDFS + "domain" else "a range"
558
+ if p == RDFS + "range" and self.is_datarange(o):
559
+ r = self.datarange(o)
560
+ return self.fit(words, self._dt(r, "ql"), self._dt(r, "rl"))
561
+ c = self.ce(o)
562
+ return self.fit(words, self.ql_super(c), self.rl_super(c))
563
+ if p in (OWL + "topObjectProperty", OWL + "bottomObjectProperty", OWL + "topDataProperty",
564
+ OWL + "bottomDataProperty"):
565
+ return self.fit("an assertion of a top or bottom property", "", _TOP_NOT_RL)
566
+ if p.startswith(OWL):
567
+ return self.fit(f"a triple of owl:{p[len(OWL):]}", f"owl:{p[len(OWL):]} states no OWL 2 QL axiom here",
568
+ f"owl:{p[len(OWL):]} states no OWL 2 RL axiom here")
569
+ if p.startswith(RDFS) or p.startswith(RDF):
570
+ return self.fit("an RDFS triple", "", "")
571
+ # A property assertion.
572
+ dt = str(o.datatype) if isinstance(o, self.Literal) and o.datatype is not None else ""
573
+ return self.fit("a property assertion", self.anonymous(s, o) or (self._dt(("ok", dt), "ql") if dt else ""),
574
+ self._dt(("ok", dt), "rl") if dt else "")
575
+
576
+ def answered(self, s: Any, p: str, o: Any, main: List[tuple], rdfs: bool) -> FrozenSet[str]:
577
+ """The profiles ProGraph answers this axiom under, from the code: 'ql' where the maps' saturation, the
578
+ RDFS core or the QL closure (`ql.read`: its triples read whole) applies it, 'rl' where the first two hold
579
+ or OWL 2 RL's rules consume its triples whole."""
580
+ from prograph.plan.ir.saturate import _READ
581
+ U = self.URIRef
582
+ ql = rdfs or (p in _READ and isinstance(s, U) and isinstance(o, U)) or \
583
+ (p == RDF_TYPE and isinstance(s, U) and isinstance(o, U) and
584
+ (not str(o).startswith(OWL) or str(o) == THING)) or \
585
+ (not p.startswith((OWL, RDFS, RDF)) and isinstance(s, U) and not isinstance(o, self.BNode))
586
+ text = f"{s.n3()} <{p}> {o.n3()}"
587
+ rl = ql or (all(t in self.consumed for t in main) and text not in self.partial_axioms)
588
+ ql = ql or all(t in self.ql for t in main)
589
+ return frozenset(x for x, ok in (("ql", ql), ("rl", rl)) if ok)
590
+
591
+ # -- the run ---------------------------------------------------------------------------------------------
592
+ def reach(self, node: Any, into: Set[tuple]) -> None:
593
+ todo = [node]
594
+ while todo:
595
+ n = todo.pop()
596
+ if not isinstance(n, self.BNode):
597
+ continue
598
+ for p, o in self.g.predicate_objects(n):
599
+ t = (n, p, o)
600
+ if t not in into:
601
+ into.add(t)
602
+ todo.append(o)
603
+
604
+ def is_rdfs(self, triples: Iterable[tuple]) -> bool:
605
+ """No OWL term in the axiom: plain RDFS vocabulary, never outside a profile."""
606
+ return not any(isinstance(x, self.URIRef) and str(x).startswith(OWL) for t in triples for x in t)
607
+
608
+ def filled_existential(self, triples: Iterable[tuple]) -> str:
609
+ """`FILLER_NOTE` for a superclass existential with a named filler (`C ⊑ ∃p.D`), '' for any other axiom."""
610
+ U = self.URIRef
611
+ for s, p, o in triples:
612
+ if str(p) == OWL + "someValuesFrom" and isinstance(o, U) and str(o) not in (THING, NOTHING) and \
613
+ not str(o).startswith(XSD):
614
+ return FILLER_NOTE
615
+ return ""
616
+
617
+ def run(self) -> List[AxiomFit]:
618
+ U = self.URIRef
619
+ out: List[AxiomFit] = []
620
+ done_definitions: Set[Any] = set()
621
+ for s, pred, o in sorted(self.g, key=lambda t: tuple(x.n3() for x in t)):
622
+ p = str(pred)
623
+ if p in _ANNOTATIONS or p in self.annotation_props:
624
+ continue
625
+ if isinstance(s, self.BNode):
626
+ if s in self.inner and p not in (RDFS + "subClassOf", OWL + "equivalentClass", OWL + "disjointWith"):
627
+ continue # part of the expression or list that reaches it
628
+ if p in _PARTS and not (p == RDF_TYPE and str(o) in _AXIOM_TYPES | set(_CHARACTERISTIC)):
629
+ if p != RDF_TYPE or str(o) in _DECLARED | _REIFIED:
630
+ continue
631
+ if (s, U(RDF_TYPE), U(OWL + "Axiom")) in self.g or (s, U(RDF_TYPE), U(OWL + "Annotation")) in self.g:
632
+ continue # a reified axiom's annotations
633
+ if p in _DEFINITION and isinstance(s, U):
634
+ if s in done_definitions:
635
+ continue
636
+ done_definitions.add(s)
637
+ main = [(s, q, x) for q, x in self.g.predicate_objects(s) if str(q) in _DEFINITION]
638
+ else:
639
+ main = [(s, pred, o)]
640
+ got = self.classify(s, p, o, main)
641
+ if got is None:
642
+ continue
643
+ kind, profiles, why = got
644
+ triples: Set[tuple] = set(main)
645
+ for t in main:
646
+ self.reach(t[2], triples)
647
+ if isinstance(s, self.BNode):
648
+ self.reach(s, triples)
649
+ tops = sorted({str(x) for t in triples for x in t if str(x) in _TOPS})
650
+ if tops and "rl" in profiles:
651
+ profiles = profiles - {"rl"}
652
+ why = why + (("rl", _TOP_NOT_RL),)
653
+ # A range outside OWL 2 QL's datatype map (Profiles §3.2.1: xsd:double, xsd:float, xsd:boolean ...) is
654
+ # outside the W3C profile but plain RDFS: under 'ql' the RDFS core reads it (`AxiomFit.status`).
655
+ rdfs = self.is_rdfs(triples)
656
+ answered = self.answered(s, p, o, main, rdfs)
657
+ out.append(AxiomFit(self.turtle(main, s), str(s) if isinstance(s, U) else "", kind, profiles, why,
658
+ answered, rdfs, frozenset(triples),
659
+ self.filled_existential(triples) if "ql" in profiles else ""))
660
+ return out
661
+
662
+ # -- the short Turtle form ------------------------------------------------------------------------------
663
+ def term(self, x: Any, depth: int = 0, leave: Any = ()) -> str:
664
+ """`x` in short Turtle; a blank node's triples inline, those in `leave` (the axiom's own) aside."""
665
+ if isinstance(x, self.URIRef):
666
+ s = str(x)
667
+ for ns, prefix in ((OWL, "owl:"), (RDFS, "rdfs:"), (RDF, "rdf:"), (XSD, "xsd:")):
668
+ if s.startswith(ns) and s[len(ns):].replace("_", "").isalnum():
669
+ return prefix + s[len(ns):]
670
+ return f"<{s}>"
671
+ if isinstance(x, self.Literal):
672
+ dt = str(x.datatype) if x.datatype is not None else ""
673
+ if dt == XSD + "integer" and str(x).lstrip("+-").isdigit():
674
+ return str(x) # Turtle's short form
675
+ if dt.startswith(XSD):
676
+ return f'"{x}"^^xsd:{dt[len(XSD):]}'
677
+ return x.n3()
678
+ if depth > 3:
679
+ return "[ ... ]"
680
+ if self.one(x, RDF + "first") is not None:
681
+ return "( " + " ".join(self.term(i, depth + 1) for i in self.items(x)) + " )"
682
+ parts = [f"{'a' if str(p) == RDF_TYPE else self.term(p)} {self.term(o, depth + 1)}"
683
+ for p, o in sorted(self.g.predicate_objects(x), key=lambda t: (t[0].n3(), t[1].n3()))
684
+ if (x, p, o) not in leave]
685
+ return "[ " + " ; ".join(parts) + " ]" if parts else "[]"
686
+
687
+ def turtle(self, main: List[tuple], s: Any) -> str:
688
+ if isinstance(s, self.BNode) and len(main) == 1 and str(main[0][1]) == RDF_TYPE:
689
+ text = self.term(s)
690
+ else:
691
+ subject = self.term(s, leave=set(main))
692
+ text = subject + " " + " ; ".join(
693
+ f"{'a' if str(p) == RDF_TYPE else self.term(p)} {self.term(o)}" for _, p, o in main)
694
+ return text if len(text) <= 300 else text[:297] + "..."