Coverage for lode / reader / modules.py: 94%

96 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1# modules.py - RDF graph enrichment modules 

2"""Enrichment modules: load external documents and add them to the graph of the 

3documented ontology. 

4 

5Three modules, activated by `apply` (imported or closure, then partial_import on top of them): 

6 

7 imported direct owl:imports (depth 1) 

8 closure transitive closure of owl:imports (depth N) 

9 partial_import only the definitions of the external terms declared with 

10 rdfs:isDefinedBy, taken from their "home" ontology (1-hop dereferencing) 

11 

12Two ways of loading an external document, shared by the modules: 

13 

14 formal import declared with owl:imports; its own owl:imports are followed 

15 (_load_formal_import, used by imported and closure) 

16 informal import a document reached by dereferencing a mentioned IRI; loaded alone, 

17 its imports are not followed (_load_informal_import, used by 

18 partial_import) 

19 

20Provenance. The graph received is a ProvenanceGraph: one named graph per source 

21document, named after the ontology IRI declared in the document (owl:Ontology or 

22skos:ConceptScheme), falling back to the URL it was loaded from. Modules never build 

23contexts by hand: every document enters through ProvenanceGraph.add_document, so each 

24triple stays in the graph of the document that asserts it. 

25 

26Every external document is loaded with `load_document`, without modules: no implicit 

27recursion, and the same security checks as the main document. 

28 

29Contract: every apply_* modifies the graph in place and returns (graph, visited), 

30where visited is the set of sources loaded successfully. 

31""" 

32from rdflib import Graph, OWL, URIRef, BNode, RDF, RDFS, XSD 

33from urllib.parse import urldefrag 

34from typing import Optional 

35 

36from lode.helpers.rdf import iri_namespace, iri_stem 

37from lode.provenance_graph import ProvenanceGraph 

38from lode.reader.loader import load_document 

39 

40import logging 

41logger = logging.getLogger(__name__) 

42 

43# Core vocabularies: never treated as external terms to dereference. 

44_SKIP_NS = (str(RDF), str(RDFS), str(OWL), str(XSD)) 

45 

46# ---------------------------------------------------------- 

47# DOCUMENT LOADERS: formal / informal imports 

48# ---------------------------------------------------------- 

49 

50def _load_formal_import(graph: ProvenanceGraph, source: str, depth: int, 

51 max_depth: Optional[int], visited: set) -> None: 

52 """Load a formally imported document (owl:imports) into its own named graph and 

53 follow its owl:imports, depth-first, down to max_depth (None = no limit). 

54 

55 `visited` prevents cycles and documents imported by several ontologies: each one 

56 is loaded only once. An unreachable document does not stop loading: it is 

57 reported and skipped, together with its imports.""" 

58 if source in visited: 

59 return 

60 if max_depth is not None and depth > max_depth: 

61 return 

62 

63 visited.add(source) 

64 

65 # Reuse load_document for the whole load (content negotiation, formats, security). 

66 # Modules are not propagated: each imported ontology is loaded as-is, and the 

67 # recursion over imports is handled by this function. 

68 try: 

69 imported_graph = load_document(source) 

70 except Exception as e: 

71 logger.warning("Formal import failed for %s: %s", source, e) 

72 return 

73 

74 logger.info("Formal import: %d triples from %s", len(imported_graph), source) 

75 # Context = ontology IRI declared in the document (fallback: source) 

76 graph.add_document(imported_graph, source) 

77 

78 for nested_uri in list(imported_graph.objects(None, OWL.imports)): 

79 _load_formal_import(graph, str(nested_uri), depth + 1, max_depth, visited) 

80 

81 

82def _load_informal_import(source: str, target: ProvenanceGraph, visited: set, failed: set, 

83 homes: dict, name: Optional[str] = None) -> None: 

84 """Load a single document reached by dereferencing an IRI (informal import) into 

85 its own named graph of `target`. Its owl:imports are not followed. 

86 

87 Records the outcome: success -> visited + homes[source] (name of its named graph); 

88 error -> failed (never retried).""" 

89 

90 if source in visited or source in failed: 

91 return 

92 try: 

93 g = load_document(source) 

94 except Exception as e: 

95 failed.add(source) 

96 logger.warning("Informal import failed for %s: %s: %s", source, type(e).__name__, e) 

97 return 

98 visited.add(source) 

99 logger.info("Informal import: %d triples from %s", len(g), source) 

100 homes[source] = target.add_document(g, name or source) 

101 

102# ---------------------------------------------------------- 

103# IMPORTED / CLOSURE MODULES (formal imports) 

104# ---------------------------------------------------------- 

105 

106def _expand_formal_imports(graph: ProvenanceGraph, max_depth: Optional[int]): 

107 """Load every owl:imports of the graph, down to max_depth (None = no limit).""" 

108 visited: set = set() 

109 for uri in list(graph.objects(None, OWL.imports)): 

110 _load_formal_import(graph, str(uri), depth=1, max_depth=max_depth, visited=visited) 

111 return graph, visited 

112 

113 

114def apply_imported(graph: ProvenanceGraph): 

115 """Add the directly imported ontologies (depth 1).""" 

116 return _expand_formal_imports(graph, max_depth=1) 

117 

118 

119def apply_closure(graph: ProvenanceGraph): 

120 """Add the full transitive closure of owl:imports (depth N, max_depth=None).""" 

121 return _expand_formal_imports(graph, max_depth=None) 

122 

123# ---------------------------------------------------------- 

124# PARTIAL IMPORT MODULE (informal imports) 

125# 

126# Only terms declared with rdfs:isDefinedBy are considered. 

127#---------------------------------------------------------- 

128# 

129# Boundary: an external term receives 

130# - what the documented ontology says about it, in the main graph, and 

131# - ALL the triples of its "home" graph (types included), in the home graph. 

132# No per-predicate priority here: both sources are kept with their provenance; 

133# conflicting types become punned entities in the Reader, and the Viewer decides 

134# what to show. Redefinitions in third-party ontologies are NOT copied. 

135# If the home cannot be reached, the term receives no external definition. 

136 

137def _namespace(term) -> str: 

138 """Namespace of an IRI, without the trailing separator: 

139 'http://ex.org/onto#T' -> 'http://ex.org/onto', 'http://ex.org/voc/t' -> 'http://ex.org/voc'.""" 

140 return iri_stem(iri_namespace(term)) 

141 

142 

143def _home(term, homes: dict): 

144 """Home graph of the term, or None. Criteria, in order: 

145 

146 1. a loaded ontology whose IRI matches the term's namespace; 

147 2. a document downloaded from a URL in the same namespace (vocabularies without 

148 owl:Ontology, e.g. DC Terms: a single download for all its terms; or BIBO, 

149 whose namespace .../bibo/status matches the downloaded URL); 

150 3. the document obtained by dereferencing the term itself (ontology IRI that 

151 differs from the namespace, e.g. a versioned IRI or a purl redirect). 

152 

153 `homes` maps every successfully downloaded source to the name of its named graph.""" 

154 ns = _namespace(term) 

155 for ctx in homes.values(): 

156 if iri_stem(ctx) == ns: 

157 return ctx 

158 for source, ctx in homes.items(): 

159 if iri_stem(source) == ns or _namespace(source) == ns: 

160 return ctx 

161 return homes.get(urldefrag(str(term))[0]) 

162 

163 

164def _namespace_failed(term, failed: set) -> bool: 

165 """True if a URL in the same namespace has already failed: avoids retrying, term 

166 by term, a vocabulary that answers with HTML or does not answer at all.""" 

167 ns = _namespace(term) 

168 return any(iri_stem(f) == ns or _namespace(f) == ns for f in failed) 

169 

170 

171def apply_partial_import(graph: ProvenanceGraph): 

172 """Dereference (1 hop) the external IRIs described by the documented ontology and 

173 declared with rdfs:isDefinedBy, and add ONLY their definition, taken from their 

174 home ontology (not the redefinitions in other ontologies). 

175 

176 Without rdfs:isDefinedBy a term stays a plain external link and nothing is 

177 downloaded for it. owl:imports documents are not loaded here: that is the job 

178 of the imported/closure modules.""" 

179 # 1. External terms: IRIs mentioned in the graph, excluding the import IRIs, the 

180 # core vocabularies and the ontology's own terms. 

181 import_iris = set(graph.objects(None, OWL.imports)) 

182 own = tuple(iri_stem(o) for o in graph.subjects(RDF.type, OWL.Ontology)) 

183 mentioned = {t for triple in graph for t in triple if isinstance(t, URIRef)} - import_iris 

184 external = {t for t in mentioned 

185 if not str(t).startswith(_SKIP_NS) and not (own and str(t).startswith(own))} 

186 

187 # 2. Keep only terms declared with rdfs:isDefinedBy: the explicit signal that the 

188 # term has a home worth downloading; other terms stay plain external links. 

189 described = set(graph.subjects(RDFS.isDefinedBy, None)) & external 

190 

191 # 3. Load into a separate graph (one named graph per document): one attempt per 

192 # namespace not covered yet. 

193 fetched = ProvenanceGraph() 

194 visited, failed, homes = set(), set(), {} # homes: source -> loaded ontology IRI 

195 for term in described: 

196 if _home(term, homes) is None and not _namespace_failed(term, failed): 

197 doc, frag = urldefrag(str(term)) 

198 # Slash IRIs dereference the term itself: name the graph after the 

199 # namespace, not after the first term fetched (e.g. dcterms:created). 

200 _load_informal_import(doc, fetched, visited, failed, homes, 

201 name=doc if frag else iri_namespace(term)) 

202 

203 # 4. Headers of external ontologies (owl:Ontology) are not terms to document. 

204 described -= set(fetched.subjects(RDF.type, OWL.Ontology)) 

205 

206 # 5. Copy the whole home description, into the home's named graph. 

207 seen: set = set() 

208 for term in described: 

209 home = _home(term, homes) 

210 if home is not None: # home unreachable: no external definition 

211 _copy_description(fetched, term, graph, seen, ctx=home) 

212 return graph, visited 

213 

214 

215def _copy_description(src: ProvenanceGraph, node, dst: ProvenanceGraph, seen: set, 

216 ctx=None) -> None: 

217 """Copy into `dst` the triples of `src` whose subject is `node`, in the same named graph. 

218 

219 ctx restricts the copy to a single graph (the home); None = all graphs. 

220 Blank nodes (restrictions, lists) are copied in full and stay in their parent's 

221 context; `seen` prevents cycles and repeated copies.""" 

222 if node in seen: 

223 return 

224 seen.add(node) 

225 for _, p, o, c in src.quads((node, None, None, ctx)): 

226 dst.graph(c).add((node, p, o)) 

227 if isinstance(o, BNode): 

228 _copy_description(src, o, dst, seen, ctx=c) 

229 

230 

231# ---------------------------------------------------------- 

232# ENTRY POINT 

233# ---------------------------------------------------------- 

234 

235def apply(graph: ProvenanceGraph, *, imported=None, closure=None, partial_import=None): 

236 """Apply the requested modules to `graph` and return (graph, imported_uris). 

237 

238 Formal imports come first (imported, else closure); partial_import then runs on top of 

239 them, so it only dereferences terms the imports did not already bring in. The returned 

240 IRIs are the documents that were loaded, so the viewer can keep the original model 

241 metadata. 

242 """ 

243 imported_uris: set = set() 

244 if imported: 

245 graph, imported_uris = apply_imported(graph) 

246 elif closure: 

247 graph, imported_uris = apply_closure(graph) 

248 if partial_import: 

249 graph, visited = apply_partial_import(graph) 

250 imported_uris = set(imported_uris or ()) | visited 

251 return graph, imported_uris