Coverage for lode / profiles / owl / checks.py: 79%

92 statements  

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

1# OWL checks.py 

2"""OWL warning checks. All functions take `reader` as first arg and push via reader.add_warning().""" 

3 

4from rdflib import URIRef, BNode 

5from rdflib.namespace import OWL 

6from lode.models import ( 

7 Concept, Datatype, DatatypeRestriction, 

8 Relation, Attribute, Annotation, 

9 TruthFunction, PropertyConceptRestriction, 

10) 

11 

12 

13# for integrity tests 

14def has_warning(reader, code: str, subject=None) -> bool: 

15 """Check if a warning with given code (and optional subject) was raised.""" 

16 for w in reader.warnings: 

17 if w['code'] != code: 

18 continue 

19 if subject is None or w['subject'] == str(subject): 

20 return True 

21 return False 

22 

23# ==================================================================== 

24# PIPELINE-TIME (called inline from OwlReader during specific phases) 

25# ==================================================================== 

26 

27def flag_malformed_restrictions(reader, classified): 

28 """Warn about BNodes that mix several restriction axioms (not valid OWL 2 DL). 

29 

30 Warnings are grouped by the parent resource that holds the malformed BNodes. 

31 """ 

32 axiom_preds = { 

33 p for p, cfg in reader._property_mapping.items() 

34 if isinstance(cfg.get('inferred_class'), type) 

35 and issubclass(cfg['inferred_class'], PropertyConceptRestriction) 

36 } 

37 by_parent = {} # parent_uri -> set of axiom predicates seen 

38 for bnode in classified: 

39 axioms = set(reader.graph.predicates(subject=bnode)) & axiom_preds 

40 if len(axioms) <= 1: 

41 continue 

42 parents = sorted({ 

43 str(s) for s in reader.graph.subjects(object=bnode) 

44 if isinstance(s, URIRef) 

45 }) 

46 parent_key = parents[0] if parents else '<anonymous>' 

47 by_parent.setdefault(parent_key, set()).update(axioms) 

48 

49 for parent, axioms in by_parent.items(): 

50 names = sorted(p.n3(reader.graph.namespace_manager) for p in axioms) 

51 reader.add_warning('malformed_restriction', parent, 

52 f"OWL 2 DL: malformed restrictions on {parent} ({', '.join(names)})") 

53 

54def empty_truth_function(reader, entity, bnode, operator): 

55 """Warn that a truth function has an empty operand list and was ignored.""" 

56 ident = entity.get_has_identifier() 

57 reader.add_warning('empty_truth_function', ident, 

58 f'§8.1.1: Truth Function ({ident}, {operator}) is empty — ignored (collection BNode: {bnode})') 

59 

60def singleton_truth_function(reader, entity, bnode, operator): 

61 """Warn that a truth function has a single operand, which usually points to an ontology mistake.""" 

62 ident = entity.get_has_identifier() 

63 reader.add_warning('singleton_truth_function', ident, 

64 f'§8.1.1: TruthFunction ({ident}, {operator}) has a single element — ontology should be checked (collection BNode: {bnode})') 

65 

66 

67# ==================================================================== 

68# POST-PIPELINE (single entry point) 

69# ==================================================================== 

70 

71def run_post_checks(reader): 

72 """Single sweep over cache + config-driven sweep.""" 

73 for uri, entities in list(reader.entities.items()): 

74 for entity in list(entities): 

75 _check_orphan_restriction(reader, entity, uri) 

76 _check_inverse_multiplicity(reader, entity, uri) 

77 # _check_self_inverse(reader, entity, uri) 

78 _check_empty_truth_function_post(reader, entity, uri) 

79 _check_property_hierarchy(reader, entity, uri) 

80 _check_class_datatype_hierarchy(reader, entity, uri) 

81 if isinstance(uri, URIRef): 

82 _check_punning_conflicts(reader, uri, entities) 

83 _check_config_mismatches(reader) 

84 

85 

86def _check_orphan_restriction(reader, entity, uri): 

87 """Warn about a restriction with no property; an anonymous one without owl:onProperty is also removed.""" 

88 if not isinstance(entity, PropertyConceptRestriction): 

89 return 

90 if entity.get_applies_on_property() is not None: 

91 return 

92 if isinstance(uri, BNode) and (uri, OWL.onProperty, None) not in reader.graph: 

93 reader.add_warning('orphan_restriction', uri, 

94 f'Orphan {type(entity).__name__}: no owl:onProperty in graph, removed') 

95 reader.entities[uri].discard(entity) 

96 else: 

97 reader.add_warning('missing_on_property', uri, 

98 f'{type(entity).__name__} has owl:onProperty but applies_on_property is None') 

99 

100def _check_inverse_multiplicity(reader, entity, uri): 

101 """Warn about a relation declared inverse of more than one relation.""" 

102 if not isinstance(entity, Relation): 

103 return 

104 inv = entity.get_is_inverse_of() 

105 if isinstance(inv, list) and len(inv) > 1: 

106 ids = ', '.join(i.get_has_identifier() for i in inv) 

107 reader.add_warning('multiple_inverse_of', uri, 

108 f'§9.2.4: Relation {uri} has {len(inv)} owl:inverseOf declarations ({ids})') 

109 

110# def _check_self_inverse(reader, entity, uri): 

111# if not isinstance(entity, Relation): 

112# return 

113# inv = entity.get_is_inverse_of() 

114# candidates = inv if isinstance(inv, list) else ([inv] if inv else []) 

115# if any(c is entity for c in candidates): 

116# reader.add_warning('self_inverse', uri, 

117# f'§6.1.1: Relation {uri} is inverse of itself') 

118 

119def _check_empty_truth_function_post(reader, entity, uri): 

120 """Warn about a truth function that still has no concepts after the whole read.""" 

121 if isinstance(entity, TruthFunction) and len(entity.get_applies_on_concept()) == 0: 

122 reader.add_warning('empty_restriction', uri, 

123 f'{type(entity).__name__} has empty applies_on_concept') 

124 

125def _check_property_hierarchy(reader, entity, uri): 

126 """Warn when a property is a sub property of a property of a different kind (relation, attribute, annotation).""" 

127 if not isinstance(entity, (Relation, Attribute, Annotation)): 

128 return 

129 for sup in (entity.get_is_sub_property_of() or []): 

130 if sup is not None and not isinstance(sup, type(entity)): 

131 reader.add_warning('property_type_mismatch_hierarchy', uri, 

132 f'§5.8.1: {type(entity).__name__} {uri} subPropertyOf ' 

133 f'{type(sup).__name__} {sup.get_has_identifier()}') 

134 

135def _check_class_datatype_hierarchy(reader, entity, uri): 

136 """Warn when a class is a subclass of a datatype, or the other way round.""" 

137 if not isinstance(entity, (Concept, Datatype)) or isinstance(entity, DatatypeRestriction): 

138 return 

139 for sup in (entity.get_is_sub_concept_of() or []): 

140 if sup is not None and not isinstance(sup, type(entity)): 

141 reader.add_warning('class_datatype_mismatch_hierarchy', uri, 

142 f'§5.8.1: {type(entity).__name__} {uri} subClassOf ' 

143 f'{type(sup).__name__} {sup.get_has_identifier()}') 

144 

145def _check_punning_conflicts(reader, uri, entities): 

146 """Warn about an IRI used as both class and datatype, or as several property kinds (illegal punning).""" 

147 types = {type(i) for i in entities} 

148 if Concept in types and Datatype in types: 

149 reader.add_warning('class_datatype_conflict', uri, 

150 f'§5.8.1: {uri} has both Concept and Datatype in cache') 

151 prop_types = types & {Relation, Attribute, Annotation} 

152 if len(prop_types) > 1: 

153 reader.add_warning('property_type_conflict', uri, 

154 f'§5.8.1: {uri} has multiple property types: {sorted(t.__name__ for t in prop_types)}') 

155 

156def _check_config_mismatches(reader): 

157 """Warn when the subject of a mapped predicate was not given one of the classes the config expects.""" 

158 for pred, cfg in reader._property_mapping.items(): 

159 target_classes = cfg.get('target_classes', []) 

160 if not target_classes: 

161 continue 

162 target_tuple = tuple(target_classes) 

163 expected = [c.__name__ for c in target_classes] 

164 for uri in reader.graph.subjects(pred, None): 

165 if not isinstance(uri, URIRef): 

166 continue 

167 entities = reader.entities.get(uri, set()) 

168 if entities and not any(isinstance(i, target_tuple) for i in entities): 

169 actual = [type(i).__name__ for i in entities] 

170 reader.add_warning('config_type_mismatch', uri, 

171 f'{uri} subject of {pred} (expected {expected}) got {actual}')