Coverage for target/native-coverage/profiles/ed7d3b207b2343278478d0be29776579/project/.venv/lib/python3.13/site-packages/owlrl_turbo/_closure.py: 100%

149 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-12-01 11:12 +0000

1"""The owlrl class interface over the native inference runtime.""" 

2 

3import json 

4 

5from rdflib import URIRef 

6from rdflib.graph import Dataset as RDFLibDataset 

7from rdflib.graph import Graph 

8from rdflib_turbo import Dataset, StoreDataset 

9from rdflib_turbo import Graph as NativeGraph 

10from rdflib_turbo._native import NativeStore 

11from rdflib_turbo._operations import _encode 

12from rdflib_turbo._reads import _INPUT_TERMS, _TERM_FACTORIES 

13 

14 

15def _destination(graph, destination): 

16 if isinstance(graph, (NativeGraph, StoreDataset)): 

17 graph._inference_scope(destination) 

18 if isinstance(graph, StoreDataset): 

19 graph.default_union = True 

20 if destination is None: 

21 return graph.default_graph if isinstance(graph, StoreDataset) else graph 

22 if isinstance(destination, Graph): 

23 return destination 

24 return NativeGraph(store=graph.store, identifier=destination, bind_namespaces="none") 

25 if getattr(graph, "_turbo_native_graph", False): 

26 raise TypeError("Expected a native Graph or StoreDataset instance") 

27 if not isinstance(graph, Graph): 

28 raise TypeError("Expected rdflib_turbo.Dataset or an RDFLib Graph/Dataset") 

29 multigraph = isinstance(graph, RDFLibDataset) 

30 if graph.context_aware and not multigraph: 

31 raise NotImplementedError("Convert context-aware graphs to rdflib.Dataset first") 

32 if multigraph: 

33 graph.default_union = True 

34 if destination is None: 

35 return graph.default_graph if multigraph else graph 

36 if isinstance(destination, (str, URIRef)): 

37 if not multigraph: 

38 raise ValueError("IRI destinations require a Dataset") 

39 # Match RDFLib's identifier normalization and preserve explicit blank 

40 # nodes without registering an empty destination before inference runs. 

41 return graph.get_context(destination) 

42 if not isinstance(destination, Graph): 

43 raise TypeError("Expected an RDFLib Graph or IRI destination") 

44 if destination.store is not graph.store: 

45 raise ValueError("The source and destination graphs must share the same backing store") 

46 return destination 

47 

48 

49def _bind_diagnostics(graph, messages): 

50 if messages: 

51 graph.bind("err", "http://www.daml.org/2002/03/agents/agent-ont#") 

52 

53 

54def _expand(graph, mode, destination, axioms=False, daxioms=False, prior_error_messages=None): 

55 options = { 

56 "axiomatic_triples": axioms, 

57 "datatype_axioms": daxioms, 

58 "prior_error_messages": prior_error_messages, 

59 } 

60 target = _destination(graph, destination) 

61 if isinstance(graph, (NativeGraph, StoreDataset)): 

62 graph.infer(inference=mode, destination=target, **options) 

63 return graph.last_inference 

64 multigraph = isinstance(graph, RDFLibDataset) 

65 if not multigraph and target.identifier != graph.identifier: 

66 return _expand_graph_pair(graph, target, mode, axioms, daxioms, prior_error_messages) 

67 expanded = Dataset.from_rdflib(graph) 

68 changes = expanded._capture_changes( 

69 inference=mode, 

70 destination=target.identifier if multigraph else None, 

71 **options, 

72 ) 

73 try: 

74 _publish_changes(graph, changes) 

75 _bind_diagnostics(target, changes.outcome.error_messages) 

76 if multigraph: 

77 graph.default_union = True 

78 return changes.outcome 

79 finally: 

80 changes.close() 

81 

82 

83def _expand_graph_pair(source, target, mode, axioms, daxioms, prior_error_messages): 

84 """Import only these two physical endpoints into one unpublished owner.""" 

85 

86 def records(): 

87 for graph in (source, target): 

88 for subject, predicate, obj in graph: 

89 yield subject, predicate, obj, graph.identifier 

90 

91 owner = NativeStore.from_records( 

92 records(), (source.identifier, target.identifier), _INPUT_TERMS 

93 ) 

94 changes = None 

95 try: 

96 changes = owner._infer_changes( 

97 mode, 

98 (json.dumps(_encode(source.identifier)), json.dumps(_encode(target.identifier))), 

99 _TERM_FACTORIES, 

100 options=(axioms, daxioms), 

101 prior_error_messages=prior_error_messages, 

102 ) 

103 _publish_changes( 

104 source, changes, endpoints={source.identifier: source, target.identifier: target} 

105 ) 

106 _bind_diagnostics(target, changes.outcome.error_messages) 

107 return changes.outcome 

108 finally: 

109 try: 

110 if changes is not None: 

111 changes.close() 

112 finally: 

113 owner.close() 

114 

115 

116def _publish_changes(graph, changes, *, endpoints=None): 

117 """Stream only final changed facts; never export the whole closure.""" 

118 multigraph = isinstance(graph, RDFLibDataset) 

119 for next_batch, remove in ((changes.next_removals, True), (changes.next_additions, False)): 

120 while True: 

121 rows, done = next_batch() 

122 for subject, predicate, obj, context in rows: 

123 if endpoints is not None: 

124 if context not in endpoints: 

125 raise RuntimeError("Unexpected inference delta outside the graph pair") 

126 target = endpoints[context] 

127 elif multigraph: 

128 target = graph.default_graph if context is None else graph.graph(context) 

129 elif context is None: 

130 target = graph 

131 else: 

132 raise RuntimeError("Unexpected named delta for an ordinary Graph") 

133 operation = target.remove if remove else target.add 

134 operation((subject, predicate, obj)) 

135 if done: 

136 break 

137 

138 

139class _Semantics: 

140 _mode: str 

141 

142 def __init__(self, graph, axioms, daxioms, rdfs=False, destination=None): 

143 self.graph = graph 

144 self.destination = _destination(graph, destination) 

145 self.axioms = axioms 

146 self.daxioms = daxioms 

147 self.rdfs = rdfs 

148 self.error_messages = [] 

149 

150 def add_error(self, message): 

151 """Append a newly discovered message without replacing caller-owned history.""" 

152 if message not in self.error_messages: 

153 self.error_messages.append(message) 

154 

155 def closure(self): 

156 outcome = _expand( 

157 self.graph, 

158 self._mode, 

159 self.destination, 

160 self.axioms, 

161 self.daxioms, 

162 prior_error_messages=self.error_messages, 

163 ) 

164 self.error_messages[:] = outcome.error_messages 

165 

166 

167class RDFS_Semantics(_Semantics): 

168 """Native RDFS closure over the supplied graph scope.""" 

169 

170 _mode = "rdfs" 

171 

172 

173class OWLRL_Semantics(_Semantics): 

174 """Native OWL-RL closure over the supplied graph scope.""" 

175 

176 _mode = "owlrl" 

177 

178 

179class RDFS_OWLRL_Semantics(OWLRL_Semantics, RDFS_Semantics): 

180 """Combined RDFS and OWL-RL closure.""" 

181 

182 _mode = "both" 

183 

184 def __init__(self, graph, axioms, daxioms, rdfs=True, destination=None): 

185 super().__init__(graph, axioms, daxioms, rdfs=True, destination=destination) 

186 

187 

188def return_closure_class(owl_closure, rdfs_closure, owl_extras, trimming=False): 

189 """Select built-in native semantics; unsupported extensions fail explicitly. 

190 

191 As in owlrl, extras are ignored when OWL closure is disabled. Trimming only 

192 applies to extension semantics and does not alter the three built-in modes. 

193 """ 

194 if owl_closure: 

195 if owl_extras: 

196 raise NotImplementedError("Native OWL extension semantics are not implemented") 

197 return RDFS_OWLRL_Semantics if rdfs_closure else OWLRL_Semantics 

198 return RDFS_Semantics if rdfs_closure else None 

199 

200 

201def _validate_closure_class(closure_class): 

202 if closure_class is not None: 

203 if not isinstance(closure_class, type): 

204 raise ValueError("The closure type argument must be a class reference") 

205 if closure_class not in (RDFS_Semantics, OWLRL_Semantics, RDFS_OWLRL_Semantics): 

206 raise NotImplementedError("Custom closure class execution is not supported") 

207 

208 

209class DeductiveClosure: 

210 """Apply supported native semantics using owlrl's in-place class interface. 

211 

212 Constructor options requiring unimplemented native configuration fail 

213 explicitly. This does not install modules under the original owlrl name. 

214 """ 

215 

216 improved_datatype_generic = False 

217 

218 def __init__( 

219 self, 

220 closure_class, 

221 improved_datatypes=True, 

222 rdfs_closure=False, 

223 axiomatic_triples=False, 

224 datatype_axioms=False, 

225 ): 

226 _validate_closure_class(closure_class) 

227 self.closure_class = closure_class 

228 self.improved_datatypes = improved_datatypes 

229 self.rdfs_closure = rdfs_closure 

230 self.axiomatic_triples = axiomatic_triples 

231 self.datatype_axioms = datatype_axioms 

232 

233 def expand(self, graph, destination=None): 

234 _validate_closure_class(self.closure_class) 

235 if self.closure_class is not None: 

236 self.closure_class( 

237 graph, 

238 self.axiomatic_triples, 

239 self.datatype_axioms, 

240 rdfs=self.rdfs_closure, 

241 destination=destination, 

242 ).closure() 

243 

244 @staticmethod 

245 def use_improved_datatypes_conversions(): 

246 raise NotImplementedError( 

247 "Process-global RDFLib datatype conversion changes are not supported" 

248 ) 

249 

250 @staticmethod 

251 def use_rdflib_datatypes_conversions(): 

252 raise NotImplementedError( 

253 "Process-global RDFLib datatype conversion changes are not supported" 

254 )