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,61 @@
1
+ """SKOS core semantics for ProGraph's reasoner.
2
+
3
+ `SKOS <https://www.w3.org/TR/skos-reference/>`_ is how ontologists model
4
+ taxonomies and thesauri (broader/narrower/related concepts). ProGraph *consumes*
5
+ SKOS the same way it consumes OWL: you bring the concept scheme, ProGraph
6
+ materializes the entailments.
7
+
8
+ The catch is that SKOS's hierarchy semantics live in the SKOS vocabulary itself,
9
+ not in your concept scheme. `skos:broader` is *not* transitive, the transitive
10
+ version is `skos:broaderTransitive`, of which `skos:broader` is a sub-property.
11
+ So "every concept under Vehicle" only closes if those axioms are present.
12
+
13
+ Every one of the SKOS relational axioms below maps onto a rule ProGraph already
14
+ implements, sub-property (`prp-spo1`), transitivity (`prp-trp`), inverse
15
+ (`prp-inv`), symmetry (`prp-symp`), so no SKOS-specific reasoning is needed.
16
+ Prepend :data:`SKOS_CORE` to your concept scheme (or use :func:`with_skos`) and
17
+ the reasoner does the rest: `skos:broader` edges close into
18
+ `skos:broaderTransitive`, `skos:narrower` is derived as the inverse, and
19
+ `skos:related` is symmetric.
20
+
21
+ Example::
22
+
23
+ from prograph.ontology import OntologyLayer, with_skos
24
+ from prograph.store import Store
25
+ ontology = OntologyLayer.from_turtle(with_skos(open("my_thesaurus.ttl").read()))
26
+ # Transitive properties are outside OWL 2 QL: the SKOS core is reasoned under profile "rl".
27
+ engine = ProGraph(schema=schema, ontology=ontology, connection=con, store=Store(con), profile="rl")
28
+ """
29
+ from __future__ import annotations
30
+
31
+ # The SKOS relational axioms ProGraph's OWL 2 RL reasoner can act on. These are
32
+ # the W3C SKOS Reference axioms S18–S27 restated in OWL, the subset within
33
+ # ProGraph's profile (annotation/label properties are documentation, not rules).
34
+ SKOS_CORE = """
35
+ @prefix skos: <http://www.w3.org/2004/02/skos/core#> .
36
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
37
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
38
+
39
+ # Hierarchical: broader/narrower are sub-properties of their transitive forms.
40
+ skos:broaderTransitive a owl:ObjectProperty, owl:TransitiveProperty .
41
+ skos:narrowerTransitive a owl:ObjectProperty, owl:TransitiveProperty .
42
+ skos:broader a owl:ObjectProperty ; rdfs:subPropertyOf skos:broaderTransitive .
43
+ skos:narrower a owl:ObjectProperty ; rdfs:subPropertyOf skos:narrowerTransitive .
44
+
45
+ # narrower is the inverse of broader (and likewise for the transitive forms).
46
+ skos:narrower owl:inverseOf skos:broader .
47
+ skos:narrowerTransitive owl:inverseOf skos:broaderTransitive .
48
+
49
+ # Associative: related is symmetric.
50
+ skos:related a owl:ObjectProperty, owl:SymmetricProperty .
51
+ """
52
+
53
+
54
+ def with_skos(concept_scheme_ttl: str) -> str:
55
+ """Prepend the SKOS core semantics to a concept-scheme Turtle string, so
56
+ ProGraph's reasoner materializes broader/narrower closures and the related
57
+ symmetry. Returns Turtle ready for :meth:`OntologyLayer.from_turtle`."""
58
+ return SKOS_CORE + "\n" + concept_scheme_ttl
59
+
60
+
61
+ __all__ = ["SKOS_CORE", "with_skos"]
@@ -0,0 +1,27 @@
1
+ """Defined classes.
2
+
3
+ The defined-class parser (:func:`parse_defined_classes`) that Genie's views
4
+ read. Reasoning lives in ``prograph.plan.ir``: OWL 2 QL by rewriting
5
+ (``profile="ql"``) and OWL 2 RL materialization into the owned store
6
+ (``profile="rl"``).
7
+
8
+ User guide: ``docs/guides/owl-and-ontology.md``.
9
+ """
10
+
11
+ from prograph.owl.defined_classes import (
12
+ DataRangeConstraint,
13
+ DefinedClass,
14
+ DefinedClassConstraint,
15
+ InversePropertyConstraint,
16
+ MinCardinalityConstraint,
17
+ parse_defined_classes,
18
+ )
19
+
20
+ __all__ = [
21
+ "DefinedClass",
22
+ "DataRangeConstraint",
23
+ "MinCardinalityConstraint",
24
+ "InversePropertyConstraint",
25
+ "DefinedClassConstraint",
26
+ "parse_defined_classes",
27
+ ]
@@ -0,0 +1,323 @@
1
+ """Parser for OWL defined-class restrictions used by RL+ extensions.
2
+
3
+ Phase 2's RL+ profile supports three specific defined-class patterns
4
+ the turbofan ontology uses. This module extracts those patterns from
5
+ the ontology's underlying rdflib graph and exposes them as typed
6
+ dataclasses the reasoner can act on.
7
+
8
+ Supported patterns
9
+ ==================
10
+
11
+ **Data-range restriction** (e.g., ``HighWearComponent``)::
12
+
13
+ :HighWearComponent owl:equivalentClass [
14
+ owl:intersectionOf (
15
+ :Component
16
+ [ owl:onProperty :wearIndex ;
17
+ owl:someValuesFrom [ owl:onDatatype xsd:decimal ;
18
+ owl:withRestrictions ( [ xsd:minInclusive 0.7 ] ) ]
19
+ ]
20
+ )
21
+ ] .
22
+
23
+ **Cardinality constraint** (e.g., ``CriticalPathComponent``)::
24
+
25
+ :CriticalPathComponent owl:equivalentClass [
26
+ owl:intersectionOf (
27
+ :Component
28
+ [ owl:onProperty :propagatesTo ; owl:minCardinality 2 ]
29
+ )
30
+ ] .
31
+
32
+ **Inverse-property someValuesFrom** (e.g., ``MonitoredComponent``)::
33
+
34
+ :MonitoredComponent owl:equivalentClass [
35
+ owl:intersectionOf (
36
+ :Component
37
+ [ owl:onProperty [ owl:inverseOf :monitors ] ;
38
+ owl:someValuesFrom :Sensor ]
39
+ )
40
+ ] .
41
+
42
+ Other restriction shapes are silently ignored, they're outside the
43
+ RL+ scope. A future phase would handle them via a full OWL 2 DL
44
+ reasoner; we explicitly hold the line at these three for the demo.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ from dataclasses import dataclass
50
+ from decimal import Decimal
51
+ from typing import TYPE_CHECKING, List, Optional, Union
52
+
53
+ if TYPE_CHECKING:
54
+ from prograph.ontology import OntologyLayer
55
+
56
+
57
+ # ──────────────────────────────────────────────────────────────────────────
58
+ # Constraint data model
59
+ # ──────────────────────────────────────────────────────────────────────────
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class DataRangeConstraint:
64
+ """``[ owl:onProperty :p ; owl:someValuesFrom [ datatype + range ] ]``.
65
+
66
+ Only inclusive bounds are stored; ``owl:withRestrictions`` may
67
+ declare any of ``xsd:minInclusive``, ``xsd:maxInclusive``,
68
+ ``xsd:minExclusive``, ``xsd:maxExclusive``, at least one must be set.
69
+ """
70
+ property_name: str
71
+ min_inclusive: Optional[float] = None
72
+ max_inclusive: Optional[float] = None
73
+ min_exclusive: Optional[float] = None
74
+ max_exclusive: Optional[float] = None
75
+
76
+ def satisfied_by(self, value) -> bool:
77
+ """True if ``value`` (numeric) falls inside this constraint."""
78
+ if value is None:
79
+ return False
80
+ try:
81
+ v = float(value)
82
+ except (TypeError, ValueError):
83
+ return False
84
+ if self.min_inclusive is not None and v < self.min_inclusive:
85
+ return False
86
+ if self.max_inclusive is not None and v > self.max_inclusive:
87
+ return False
88
+ if self.min_exclusive is not None and v <= self.min_exclusive:
89
+ return False
90
+ if self.max_exclusive is not None and v >= self.max_exclusive:
91
+ return False
92
+ return True
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class MinCardinalityConstraint:
97
+ """``[ owl:onProperty :p ; owl:minCardinality N ]``.
98
+
99
+ Entity satisfies iff it has at least ``min_count`` distinct edges of
100
+ property ``p`` originating from it. ``owl:minCardinality 0`` is
101
+ trivially satisfied and out of scope for RL+ (no useful inference).
102
+ """
103
+ property_name: str
104
+ min_count: int
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class InversePropertyConstraint:
109
+ """``[ owl:onProperty [owl:inverseOf :p] ; owl:someValuesFrom :C ]``.
110
+
111
+ Entity satisfies iff some instance of ``target_class`` has an edge
112
+ via property ``p`` *to* this entity. In LPG terms: there's a row in
113
+ the rel table for ``p`` where target = this entity and source has
114
+ type ``target_class``.
115
+ """
116
+ property_name: str
117
+ target_class: str
118
+
119
+
120
+ DefinedClassConstraint = Union[
121
+ DataRangeConstraint,
122
+ MinCardinalityConstraint,
123
+ InversePropertyConstraint,
124
+ ]
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class DefinedClass:
129
+ """A class whose membership is computed from a restriction.
130
+
131
+ Entities don't directly carry this label in the asserted data;
132
+ the RL+ reasoner materializes membership based on the constraint.
133
+ """
134
+ name: str
135
+ base_class: str
136
+ constraint: DefinedClassConstraint
137
+
138
+
139
+ # ──────────────────────────────────────────────────────────────────────────
140
+ # Parser
141
+ # ──────────────────────────────────────────────────────────────────────────
142
+
143
+
144
+ def parse_defined_classes(ontology: "OntologyLayer") -> List[DefinedClass]:
145
+ """Extract every defined class with a supported restriction pattern.
146
+
147
+ Walks ``ontology._graph`` for ``owl:equivalentClass`` declarations
148
+ whose object is a blank-node intersection containing a named base
149
+ class plus one of the three supported restriction shapes.
150
+
151
+ Unsupported restrictions are silently dropped. To audit what was
152
+ skipped, parse the ontology with a higher log level enabled.
153
+ """
154
+ import rdflib
155
+ from rdflib.namespace import OWL, RDF, RDFS, XSD
156
+
157
+ graph = ontology._graph
158
+ results: List[DefinedClass] = []
159
+
160
+ for cls_uri, _, defn_node in graph.triples((None, OWL.equivalentClass, None)):
161
+ if not isinstance(cls_uri, rdflib.URIRef):
162
+ continue
163
+ if not isinstance(defn_node, rdflib.BNode):
164
+ # A plain class-to-class equivalentClass, already handled by
165
+ # cax-eqc; not a defined class with a restriction.
166
+ continue
167
+
168
+ # The blank node should be owl:Class with owl:intersectionOf list.
169
+ intersection_node = graph.value(defn_node, OWL.intersectionOf)
170
+ if intersection_node is None:
171
+ continue
172
+
173
+ members = _parse_rdf_list(graph, intersection_node)
174
+ if not members:
175
+ continue
176
+
177
+ base_class = None
178
+ restriction_node = None
179
+ for m in members:
180
+ if isinstance(m, rdflib.URIRef):
181
+ base_class = ontology._get_local_name(m)
182
+ elif isinstance(m, rdflib.BNode):
183
+ if (m, RDF.type, OWL.Restriction) in graph:
184
+ restriction_node = m
185
+ if base_class is None or restriction_node is None:
186
+ continue
187
+
188
+ constraint = _parse_restriction(ontology, graph, restriction_node)
189
+ if constraint is None:
190
+ continue
191
+
192
+ results.append(DefinedClass(
193
+ name=ontology._get_local_name(cls_uri),
194
+ base_class=base_class,
195
+ constraint=constraint,
196
+ ))
197
+
198
+ return results
199
+
200
+
201
+ def _parse_restriction(ontology, graph, restriction_node) -> Optional[DefinedClassConstraint]:
202
+ """Identify which of the three supported restriction shapes this is."""
203
+ import rdflib
204
+ from rdflib.namespace import OWL, RDF, RDFS, XSD
205
+
206
+ on_property = graph.value(restriction_node, OWL.onProperty)
207
+ if on_property is None:
208
+ return None
209
+
210
+ # Detect inverse property expression: blank-node with owl:inverseOf.
211
+ is_inverse = False
212
+ if isinstance(on_property, rdflib.BNode):
213
+ inverse_target = graph.value(on_property, OWL.inverseOf)
214
+ if inverse_target is None or not isinstance(inverse_target, rdflib.URIRef):
215
+ return None
216
+ property_name = ontology._get_local_name(inverse_target)
217
+ is_inverse = True
218
+ elif isinstance(on_property, rdflib.URIRef):
219
+ property_name = ontology._get_local_name(on_property)
220
+ else:
221
+ return None
222
+
223
+ # Cardinality constraint: owl:minCardinality on the restriction.
224
+ min_card_lit = graph.value(restriction_node, OWL.minCardinality)
225
+ if min_card_lit is not None:
226
+ try:
227
+ n = int(min_card_lit)
228
+ except (TypeError, ValueError):
229
+ return None
230
+ if n <= 0:
231
+ return None # trivially satisfied; skip
232
+ if is_inverse:
233
+ return None # we don't support inverse + cardinality
234
+ return MinCardinalityConstraint(property_name=property_name, min_count=n)
235
+
236
+ # someValuesFrom variant, either a named class or a datatype range.
237
+ svf = graph.value(restriction_node, OWL.someValuesFrom)
238
+ if svf is None:
239
+ return None
240
+
241
+ # Inverse + someValuesFrom + named class → InversePropertyConstraint.
242
+ if is_inverse and isinstance(svf, rdflib.URIRef):
243
+ target = ontology._get_local_name(svf)
244
+ return InversePropertyConstraint(
245
+ property_name=property_name,
246
+ target_class=target,
247
+ )
248
+
249
+ # someValuesFrom + datatype restriction → DataRangeConstraint.
250
+ if not is_inverse and isinstance(svf, rdflib.BNode):
251
+ if (svf, RDF.type, RDFS.Datatype) not in graph:
252
+ return None
253
+ return _parse_data_range(graph, property_name, svf)
254
+
255
+ return None
256
+
257
+
258
+ def _parse_data_range(graph, property_name, datatype_node) -> Optional[DataRangeConstraint]:
259
+ """Parse owl:withRestrictions facets into a DataRangeConstraint."""
260
+ import rdflib
261
+ from rdflib.namespace import OWL, XSD
262
+
263
+ restrictions_list_node = graph.value(datatype_node, OWL.withRestrictions)
264
+ if restrictions_list_node is None:
265
+ return None
266
+
267
+ facets = _parse_rdf_list(graph, restrictions_list_node)
268
+ bounds = {
269
+ "min_inclusive": None,
270
+ "max_inclusive": None,
271
+ "min_exclusive": None,
272
+ "max_exclusive": None,
273
+ }
274
+
275
+ for facet_node in facets:
276
+ if not isinstance(facet_node, rdflib.BNode):
277
+ continue
278
+ for pred, obj in graph.predicate_objects(facet_node):
279
+ if obj is None:
280
+ continue
281
+ try:
282
+ val = float(obj)
283
+ except (TypeError, ValueError):
284
+ continue
285
+ if pred == XSD.minInclusive:
286
+ bounds["min_inclusive"] = val
287
+ elif pred == XSD.maxInclusive:
288
+ bounds["max_inclusive"] = val
289
+ elif pred == XSD.minExclusive:
290
+ bounds["min_exclusive"] = val
291
+ elif pred == XSD.maxExclusive:
292
+ bounds["max_exclusive"] = val
293
+
294
+ if all(v is None for v in bounds.values()):
295
+ return None
296
+
297
+ return DataRangeConstraint(
298
+ property_name=property_name,
299
+ **bounds,
300
+ )
301
+
302
+
303
+ def _parse_rdf_list(graph, node) -> list:
304
+ """Materialize an rdf:List into a Python list of nodes."""
305
+ import rdflib
306
+ from rdflib.namespace import RDF
307
+ if node is None or node == RDF.nil:
308
+ return []
309
+ from rdflib.collection import Collection
310
+ try:
311
+ return list(Collection(graph, node))
312
+ except Exception:
313
+ return []
314
+
315
+
316
+ __all__ = [
317
+ "DataRangeConstraint",
318
+ "MinCardinalityConstraint",
319
+ "InversePropertyConstraint",
320
+ "DefinedClass",
321
+ "DefinedClassConstraint",
322
+ "parse_defined_classes",
323
+ ]
prograph/parameters.py ADDED
@@ -0,0 +1,242 @@
1
+ """Query parameters: the one way a caller's value enters a query (decided 2026-11-11).
2
+
3
+ `engine.execute(query, parameters={"p": IRI("http://ex/p/1"), "name": "Ann"})` binds the SPARQL
4
+ variables `?p` and `?name` to RDF terms before the query runs, as Jena's initial bindings do: where the
5
+ query reads the variable it reads the constant (a pattern, an OPTIONAL's FILTER, MINUS, a sub-select),
6
+ and one VALUES row joined with the top-level group keeps the variable in the answers (sparql_front,
7
+ `params` and `bound`). The value never becomes query text, so no quoting rule applies to it: a value
8
+ holding SPARQL is a string.
9
+
10
+ What a parameter holds, and the term it is (`term_of`):
11
+
12
+ - `IRI("http://...")` or an rdflib `URIRef`: an IRI, used as written (not resolved against BASE);
13
+ - `Literal(value, datatype=..., lang=...)` or an rdflib `Literal`: that literal;
14
+ - a `str`: an xsd:string literal, never an IRI;
15
+ - a `bool`, `int`, finite `float`, `Decimal`, `date` or `datetime`: xsd:boolean, xsd:integer, xsd:double,
16
+ xsd:decimal (in its canonical form, as R2RML writes a DECIMAL column), xsd:date, xsd:dateTime (a
17
+ datetime's offset kept when it has one).
18
+
19
+ Anything else (None, a list, a map, a blank node, a NaN) is `ParameterError`, naming the parameter, as
20
+ is a name that is no variable of the query. Names are written `x`, `?x` or `$x`.
21
+
22
+ What cannot be a parameter: a predicate or class written in the query's text, a path, a graph name in
23
+ FROM. Those are the query's own terms; to choose among them, check a caller's choice first.
24
+
25
+ Cypher (`cypher_values`): `$name` is the caller's value, read where the query reads it as a literal
26
+ written there is read (a constant of the plan, lowered as the serializer writes any constant; never
27
+ query or SQL text). A Cypher value is not an RDF term: None is null, a bool, an int of 64 bits, a
28
+ float, a str (never an IRI), a list or a str-keyed map of such values, and a date, time, datetime or
29
+ timedelta (a date, a local or offset time, a local date-time or a date-time at an offset or zone, a
30
+ duration). A name the query does not read is ignored; one it reads that the call does
31
+ not give is the query's ParameterMissing.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import datetime
37
+ import decimal
38
+ import math
39
+ from dataclasses import dataclass
40
+ from typing import Any, Dict, Mapping, Optional
41
+
42
+ from prograph.rules import module_home
43
+ from prograph.schema import xsd
44
+ from prograph.schema.xsd import XSD # noqa: F401 (re-exported: Literal(..., datatype=XSD + "short"))
45
+
46
+ module_home("query-values", "Query values",
47
+ terms=("parameters", "bind a value", "query parameter", "initial bindings", "setBinding",
48
+ "$name", "ParameterMissing"))
49
+
50
+
51
+
52
+ class IRI(str):
53
+ """A parameter value that is an IRI, not a string. It is used as written: an IRI parameter is
54
+ absolute and is not resolved against the query's BASE."""
55
+
56
+ def __repr__(self) -> str:
57
+ return f"IRI({str(self)!r})"
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Literal:
62
+ """A parameter value that is a literal of a given datatype or language tag: `Literal("12",
63
+ datatype=xsd.INTEGER)`, `Literal("chat", lang="fr")`. A non-str value is written as its
64
+ Python type's literal first and then given the datatype."""
65
+ value: Any
66
+ datatype: Optional[str] = None
67
+ lang: Optional[str] = None
68
+
69
+
70
+ class ParameterError(ValueError):
71
+ """A parameter ProGraph cannot bind: a value of a kind it does not take, or a name that is no
72
+ variable of the query."""
73
+
74
+ def __init__(self, name: str, message: str):
75
+ self.name = name
76
+ super().__init__(f"Query parameter {name!r}: {message}")
77
+
78
+
79
+ def name_of(name: Any) -> str:
80
+ """A parameter's variable name, without its `?` or `$`."""
81
+ if not isinstance(name, str) or not name.lstrip("?$"):
82
+ raise ParameterError(str(name), "a parameter name is a variable's name, such as 'x' or '?x'")
83
+ return name[1:] if name[0] in "?$" else name
84
+
85
+
86
+ def _lexical(name: str, value: Any, decimal_text: Optional[str] = None) -> tuple:
87
+ """(lexical form, datatype) of a Python value; a Decimal's under the schema's `decimal_text`."""
88
+ if isinstance(value, bool):
89
+ return ("true" if value else "false"), xsd.BOOLEAN
90
+ if isinstance(value, int):
91
+ return str(value), xsd.INTEGER
92
+ if isinstance(value, float):
93
+ if not math.isfinite(value):
94
+ raise ParameterError(name, f"{value!r} is not a finite number")
95
+ # The canonical form, as R2RML writes a DOUBLE column's values (R2RML 10.2): 2.0 is the
96
+ # term "2.0E0", which the mapped 2.0 is; "2.0"^^xsd:double is another term and matches nothing.
97
+ return xsd.canonical_lexical(value, xsd.DOUBLE), xsd.DOUBLE
98
+ if isinstance(value, decimal.Decimal):
99
+ if not value.is_finite():
100
+ raise ParameterError(name, f"{value!r} is not a finite number")
101
+ if decimal_text == "database":
102
+ # The value's own text, as the database writes a DECIMAL of its scale (`decimal_text:
103
+ # database`, sparql_front.held_under): Decimal("1.50") is "1.50", as a NUMERIC(6,2)'s 1.50.
104
+ return format(value, "f"), xsd.DECIMAL
105
+ # The canonical form (XSD 1.1 3.3.3.2), as R2RML writes a DECIMAL column's values
106
+ # (R2RML 10.2): Decimal("1.50") is the term "1.5", Decimal("2.00") the term "2".
107
+ return xsd.canonical_lexical(value, xsd.DECIMAL), xsd.DECIMAL
108
+ if isinstance(value, datetime.datetime):
109
+ # The canonical form, as R2RML writes a TIMESTAMP column's values: no trailing zeros in the
110
+ # fraction ("10:00:00.5", not "10:00:00.500000").
111
+ return xsd.canonical_lexical(value, xsd.DATETIME), xsd.DATETIME
112
+ if isinstance(value, datetime.date):
113
+ return value.isoformat(), xsd.DATE
114
+ if isinstance(value, str):
115
+ return value, xsd.STRING
116
+ if value is None:
117
+ raise ParameterError(name, "None binds nothing: leave the parameter out to leave it unbound")
118
+ raise ParameterError(name, f"a {type(value).__name__} value cannot be a parameter")
119
+
120
+
121
+ def term_of(name: str, value: Any, decimal_text: Optional[str] = None):
122
+ """The RDF term a parameter's value is (the module's text); a Decimal's text under the schema's
123
+ `decimal_text` (canonical by default, `1.5`; under `database` its own text, `1.50`)."""
124
+ from prograph.plan.ir.terms import IRITerm, LiteralTerm
125
+ try:
126
+ import rdflib
127
+ except ImportError: # pragma: no cover - rdflib is a dependency
128
+ rdflib = None
129
+ if isinstance(value, IRI):
130
+ return IRITerm(str(value))
131
+ if rdflib is not None:
132
+ if isinstance(value, rdflib.URIRef):
133
+ return IRITerm(str(value))
134
+ if isinstance(value, rdflib.Literal):
135
+ return LiteralTerm(str(value), str(value.datatype) if value.datatype else None, value.language)
136
+ if isinstance(value, rdflib.BNode):
137
+ raise ParameterError(name, "a blank node cannot be a parameter")
138
+ if isinstance(value, Literal):
139
+ if value.lang is not None:
140
+ return LiteralTerm(str(value.value), None, value.lang)
141
+ lexical, datatype = (value.value, None) if isinstance(value.value, str) \
142
+ else _lexical(name, value.value, decimal_text)
143
+ return LiteralTerm(lexical, value.datatype or datatype)
144
+ lexical, datatype = _lexical(name, value, decimal_text)
145
+ return LiteralTerm(lexical, datatype)
146
+
147
+
148
+ def bindings(parameters: Optional[Mapping[str, Any]], decimal_text: Optional[str] = None) -> Dict[str, Any]:
149
+ """The call's parameters as {variable name: RDF term}, a Decimal's text under the schema's
150
+ `decimal_text`."""
151
+ if parameters is None:
152
+ return {}
153
+ if not isinstance(parameters, Mapping):
154
+ raise TypeError("parameters must be a mapping of variable name to value")
155
+ out: Dict[str, Any] = {}
156
+ for name, value in parameters.items():
157
+ var = name_of(name)
158
+ if var in out:
159
+ raise ParameterError(str(name), "given twice")
160
+ out[var] = term_of(var, value, decimal_text)
161
+ return out
162
+
163
+
164
+ _INT64 = (-(1 << 63), (1 << 63) - 1)
165
+
166
+
167
+ def cypher_value(name: str, value: Any) -> Any:
168
+ """A caller's Python value as the Cypher value a literal of it is in the plan (the module's text):
169
+ a scalar as itself, a list and a map element by element, a temporal as `cypher_temporal`'s value."""
170
+ # Subclasses (numpy scalars, a str that overrides its methods) are read as the exact builtin type.
171
+ if value is None or isinstance(value, bool):
172
+ return None if value is None else bool(value)
173
+ if isinstance(value, str):
174
+ return str.__str__(value)
175
+ if isinstance(value, int):
176
+ if not _INT64[0] <= value <= _INT64[1]:
177
+ raise ParameterError(name, f"{value} is past a Cypher INTEGER's 64 bits")
178
+ return int(value)
179
+ if isinstance(value, float):
180
+ return float(value)
181
+ if isinstance(value, decimal.Decimal):
182
+ raise ParameterError(name, "a Decimal has no Cypher type: pass an int or a float")
183
+ if isinstance(value, (list, tuple)):
184
+ return [cypher_value(name, v) for v in value]
185
+ if isinstance(value, Mapping):
186
+ out = {}
187
+ for k, v in value.items():
188
+ if not isinstance(k, str):
189
+ raise ParameterError(name, f"a map's key {k!r} is not a string")
190
+ out[k] = cypher_value(name, v)
191
+ return out
192
+ from prograph.plan.ir import cypher_temporal as T
193
+ if isinstance(value, datetime.datetime):
194
+ local = T.CypherLocalDateTime(_nanos(value.replace(tzinfo=None) - datetime.datetime(1970, 1, 1)))
195
+ if value.tzinfo is None:
196
+ return local
197
+ offset = value.utcoffset()
198
+ if offset is None:
199
+ raise ParameterError(name, "a datetime whose tzinfo gives no offset")
200
+ seconds = int(offset.total_seconds())
201
+ zone = getattr(value.tzinfo, "key", None) # a zoneinfo.ZoneInfo's name; an offset alone has none
202
+ return T.CypherDateTime(local.nanos - seconds * 1_000_000_000, seconds, zone)
203
+ if isinstance(value, datetime.date):
204
+ return T.CypherDate((value - datetime.date(1970, 1, 1)).days)
205
+ if isinstance(value, datetime.time):
206
+ nanos = ((value.hour * 60 + value.minute) * 60 + value.second) * 1_000_000_000 + value.microsecond * 1000
207
+ if value.tzinfo is None:
208
+ return T.CypherLocalTime(nanos)
209
+ offset = value.utcoffset()
210
+ if offset is None:
211
+ raise ParameterError(name, "a time whose tzinfo gives no offset")
212
+ return T.CypherTime(nanos, int(offset.total_seconds()))
213
+ if isinstance(value, datetime.timedelta):
214
+ # Days and seconds kept apart, as a Cypher duration holds them (a timedelta has no months); a
215
+ # negative one is its magnitude's parts negated (-1 second is PT-1S, not Python's -1 day + 86399 s).
216
+ sign, size = (-1, -value) if value < datetime.timedelta(0) else (1, value)
217
+ return T._duration(0, sign * size.days, sign * size.seconds, sign * size.microseconds * 1000)
218
+ raise ParameterError(name, f"a {type(value).__name__} value cannot be a Cypher parameter")
219
+
220
+
221
+ def _nanos(delta: datetime.timedelta) -> int:
222
+ return ((delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds) * 1000
223
+
224
+
225
+ def cypher_values(parameters: Optional[Mapping[str, Any]]) -> Dict[str, Any]:
226
+ """The call's parameters as {name: Cypher value}; a name written `x` or `$x`."""
227
+ if parameters is None:
228
+ return {}
229
+ if not isinstance(parameters, Mapping):
230
+ raise TypeError("parameters must be a mapping of parameter name to value")
231
+ out: Dict[str, Any] = {}
232
+ for name, value in parameters.items():
233
+ if not isinstance(name, str) or not name.lstrip("$"):
234
+ raise ParameterError(str(name), "a parameter name is a name, such as 'x' or '$x'")
235
+ key = name[1:] if name[0] == "$" else name
236
+ if key in out:
237
+ raise ParameterError(str(name), "given twice")
238
+ out[key] = cypher_value(key, value)
239
+ return out
240
+
241
+
242
+ __all__ = ["IRI", "Literal", "ParameterError", "bindings", "term_of", "name_of", "cypher_values", "XSD"]
@@ -0,0 +1 @@
1
+ """Parser module for graph query languages."""