Elffuss BraidHub

kikocis/utopia public

dev · 22.1 KiBRawPermalink
1//! 本体自己的自洽性:**不碰事实,只看定义**。
2//!
3//! 与 [`crate::check`] 是两件事。那一层问「事实与定义抵触吗」,这一层问
4//! 「定义自己站得住吗」。分开不是分类癖:一个自相矛盾的本体会让事实层的
5//! 结论全部可疑——若某个谓词同时声明了 symmetric 与 asymmetric,那么据它
6//! 报出来的每一条反对称违规都建立在一个本来就不成立的前提上。所以这一层
7//! 的结论要**排在前面**给人看。
8//!
9//! 便宜也是理由:输入只有几千行本体,不用扫账本。
10//!
11//! **同样是「没声明就不查」。** 这里查的每一条都对应本体里写下来的东西,
12//! 没有一条是我们替用户假设的。
13
14use crate::Axioms;
15use std::collections::{HashMap, HashSet};
16use uuid::Uuid;
17
18/// 类层级上溯的深度上限。与 [`crate::MAX_DEPTH`] 同一个理由:本体里可以有环
19/// (建表时只挡得住自环,`A → B → A` 拦不住),没有上限就不终止。
20pub const MAX_ANCESTRY: usize = 32;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
23pub enum Defect {
24 /// 同一个谓词既声明 symmetric 又声明 asymmetric。
25 ///
26 /// OWL 里这两者只能同时对**空**属性成立——一旦有一条边 `A p B`,对称说
27 /// `B p A` 必须成立,反对称说它必须不成立。所以但凡这个谓词上有事实,
28 /// 声明就一定错了一个。
29 SymmetricAndAsymmetric,
30 /// 传递 + 函数性。OWL 2 DL 明文禁止(函数性属性不得声明为传递),
31 /// 因为两者一起会让推理跳出可判定的片段。
32 ///
33 /// 直觉上也讲得通:函数性说「主语侧只有一个值」,传递说「顺着链一直推」,
34 /// 而链上第二跳就给同一个主语推出了第二个值。
35 TransitiveAndFunctional,
36 /// subClassOf 绕成了环。建表时的 CHECK 只挡得住 `A → A`。
37 ///
38 /// 环意味着环上所有类互为子类,即它们其实是同一个类——而它们有各自的
39 /// 标签、描述、属性,界面上也各画一行。
40 SubclassCycle,
41 /// 一个类跟自己的祖先声明了互斥 → 这个类**永远不可能有实例**。
42 /// 它继承了祖先的身份,又声明与之互斥。
43 DisjointWithAncestor,
44 /// 一个类的两个祖先互相互斥 → 同上,不可满足。
45 /// 多父继承下这个形状不罕见:两支各自合理,合起来就矛盾了。
46 InheritsDisjoint,
47 /// 一个谓词声明自己是自己的逆。**等价于 symmetric**——推理照跑,
48 /// 只是读的人要多想一步。提示改写成 `symmetric` 更直白
49 InverseOfItself,
50 /// `p⁻¹ = q` 而 `q⁻¹ = r`,两边指得不一样。
51 ///
52 /// 载入公理时只补空缺、不覆盖人写的(**人写的优先于推出来的**),
53 /// 所以这个矛盾不会被悄悄抹平,留到这里报。
54 InverseNotMutual,
55 /// subPropertyOf 绕成了环。与 [`Defect::SubclassCycle`] 同形:
56 /// 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实。
57 SubPropertyCycle,
58}
59
60impl Defect {
61 pub fn as_str(self) -> &'static str {
62 match self {
63 Defect::SymmetricAndAsymmetric => "symmetric_and_asymmetric",
64 Defect::TransitiveAndFunctional => "transitive_and_functional",
65 Defect::SubclassCycle => "subclass_cycle",
66 Defect::DisjointWithAncestor => "disjoint_with_ancestor",
67 Defect::InheritsDisjoint => "inherits_disjoint",
68 Defect::InverseOfItself => "inverse_of_itself",
69 Defect::InverseNotMutual => "inverse_not_mutual",
70 Defect::SubPropertyCycle => "sub_property_cycle",
71 }
72 }
73}
74
75/// 本体里的一处自相矛盾。
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct OntologyDefect {
78 pub kind: Defect,
79 /// 出问题的那个对象:谓词(前两类)或类(后三类)
80 pub subject: Uuid,
81 /// 另一方:互斥的那个类。前两类与环没有第二方
82 pub other: Option<Uuid>,
83 /// 环的路径(按类排列),或从类到那个祖先的路径。其余为空
84 pub path: Vec<Uuid>,
85}
86
87/// 量一遍本体自己。
88///
89/// `parents` 是 `(子, 父)` 对,`disjoint` 是互斥对——**导入侧已经把对称性
90/// 展开成两行**,所以这里两个方向都会看到,去重靠有序键。
91pub fn check_ontology(
92 axioms: &HashMap<Uuid, Axioms>,
93 parents: &[(Uuid, Uuid)],
94 disjoint: &[(Uuid, Uuid)],
95) -> Vec<OntologyDefect> {
96 let mut out = Vec::new();
97
98 // ---- 谓词上的两处自相矛盾。**排序后再报**:HashMap 的遍历顺序每次不同,
99 // 而同一个本体两次检查出来的结果该是同一份
100 let mut preds: Vec<(&Uuid, &Axioms)> = axioms.iter().collect();
101 preds.sort_by_key(|(id, _)| **id);
102 for (&pred, ax) in preds {
103 if ax.symmetric && ax.asymmetric {
104 out.push(OntologyDefect {
105 kind: Defect::SymmetricAndAsymmetric,
106 subject: pred,
107 other: None,
108 path: Vec::new(),
109 });
110 }
111 if ax.transitive && (ax.functional || ax.inverse_functional) {
112 out.push(OntologyDefect {
113 kind: Defect::TransitiveAndFunctional,
114 subject: pred,
115 other: None,
116 path: Vec::new(),
117 });
118 }
119 // 自己是自己的逆 = 对称。**不是错,是绕远路**——推理照跑,
120 // 但读本体的人得自己想一步才明白。提示改用 `symmetric` 更直白
121 if ax.inverse_of == Some(pred) {
122 out.push(OntologyDefect {
123 kind: Defect::InverseOfItself,
124 subject: pred,
125 other: None,
126 path: Vec::new(),
127 });
128 }
129 // 逆 + 反对称:`A p B` 推出 `B p A`(自己的逆),而反对称说这不成立。
130 // 与 symmetric+asymmetric 同一个矛盾,换了个写法进来
131 if ax.inverse_of == Some(pred) && ax.asymmetric {
132 out.push(OntologyDefect {
133 kind: Defect::SymmetricAndAsymmetric,
134 subject: pred,
135 other: None,
136 path: Vec::new(),
137 });
138 }
139 // 两边各自声明了逆,却指向不同的谓词。**不在载入时悄悄改一致**
140 // (`reasoning::axioms` 那边只补空缺,不覆盖人写的),所以在这里报
141 if let Some(inv) = ax.inverse_of {
142 if let Some(back) = axioms.get(&inv).and_then(|a| a.inverse_of) {
143 if back != pred {
144 out.push(OntologyDefect {
145 kind: Defect::InverseNotMutual,
146 subject: pred,
147 other: Some(inv),
148 path: vec![pred, inv, back],
149 });
150 }
151 }
152 }
153 }
154
155 // ---- subPropertyOf 成环。与 subClassOf 的环是同一个形状:
156 // 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实
157 {
158 let parent_of: HashMap<Uuid, Uuid> = axioms
159 .iter()
160 .filter_map(|(id, ax)| ax.sub_property_of.map(|p| (*id, p)))
161 .collect();
162 let mut starts: Vec<Uuid> = parent_of.keys().copied().collect();
163 starts.sort();
164 let mut reported: HashSet<Uuid> = HashSet::new();
165 for start in starts {
166 if reported.contains(&start) {
167 continue;
168 }
169 let mut seen: Vec<Uuid> = Vec::new();
170 let mut cur = start;
171 for _ in 0..MAX_ANCESTRY {
172 if seen.contains(&cur) {
173 // 环上每个成员都标记过,整条环只报一次
174 for m in &seen {
175 reported.insert(*m);
176 }
177 out.push(OntologyDefect {
178 kind: Defect::SubPropertyCycle,
179 subject: start,
180 other: None,
181 path: seen.clone(),
182 });
183 break;
184 }
185 seen.push(cur);
186 match parent_of.get(&cur) {
187 Some(&p) => cur = p,
188 None => break,
189 }
190 }
191 }
192 }
193
194 let up = adjacency(parents);
195 out.extend(subclass_cycles(&up));
196 out.extend(unsatisfiable(&up, disjoint));
197 out
198}
199
200/// 子 → 父的邻接表。同一对重复声明只留一次。
201fn adjacency(parents: &[(Uuid, Uuid)]) -> HashMap<Uuid, Vec<Uuid>> {
202 let mut up: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
203 for &(child, parent) in parents {
204 let slot = up.entry(child).or_default();
205 if !slot.contains(&parent) {
206 slot.push(parent);
207 }
208 }
209 // 排序保证同一份本体每次算出同一条路径
210 for v in up.values_mut() {
211 v.sort();
212 }
213 up
214}
215
216/// subClassOf 的环。每个环只报一次,键取环上类的有序集合。
217fn subclass_cycles(up: &HashMap<Uuid, Vec<Uuid>>) -> Vec<OntologyDefect> {
218 let mut reported: HashSet<Vec<Uuid>> = HashSet::new();
219 let mut out = Vec::new();
220 let mut starts: Vec<Uuid> = up.keys().copied().collect();
221 starts.sort();
222 for start in starts {
223 let mut path = Vec::new();
224 let mut on_path = HashSet::new();
225 climb(
226 start,
227 start,
228 up,
229 &mut path,
230 &mut on_path,
231 &mut reported,
232 &mut out,
233 );
234 }
235 out
236}
237
238fn climb(
239 start: Uuid,
240 at: Uuid,
241 up: &HashMap<Uuid, Vec<Uuid>>,
242 path: &mut Vec<Uuid>,
243 on_path: &mut HashSet<Uuid>,
244 reported: &mut HashSet<Vec<Uuid>>,
245 out: &mut Vec<OntologyDefect>,
246) {
247 if path.len() >= MAX_ANCESTRY {
248 return;
249 }
250 let Some(ups) = up.get(&at) else {
251 return;
252 };
253 for &parent in ups {
254 if parent == start && !path.is_empty() {
255 // 回到起点:这是一个环。`path` 此刻是 start 之后的那几个类
256 let mut ring = vec![start];
257 ring.extend(path.iter().copied());
258 let mut key = ring.clone();
259 key.sort();
260 key.dedup();
261 if reported.insert(key) {
262 out.push(OntologyDefect {
263 kind: Defect::SubclassCycle,
264 subject: start,
265 other: None,
266 path: ring,
267 });
268 }
269 continue;
270 }
271 if on_path.contains(&parent) || parent == start {
272 // 别处的环,等它自己那一轮报;这里只是别走进去
273 continue;
274 }
275 path.push(parent);
276 on_path.insert(parent);
277 climb(start, parent, up, path, on_path, reported, out);
278 on_path.remove(&parent);
279 path.pop();
280 }
281}
282
283/// 不可满足的类:它的祖先集合里出现了一对互斥。
284///
285/// 两种形状分开报,因为**给人的话不一样**:跟自己的祖先互斥是「这条 disjoint
286/// 声明写反了」,而两个祖先互斥是「这个类不该同时挂在这两支下」。
287fn unsatisfiable(up: &HashMap<Uuid, Vec<Uuid>>, disjoint: &[(Uuid, Uuid)]) -> Vec<OntologyDefect> {
288 let pairs: HashSet<(Uuid, Uuid)> = disjoint.iter().copied().collect();
289 if pairs.is_empty() {
290 return Vec::new();
291 }
292 let mut out = Vec::new();
293 let mut classes: Vec<Uuid> = up.keys().copied().collect();
294 classes.sort();
295 for class in classes {
296 let anc = ancestors(class, up);
297 // 一、跟自己的祖先互斥
298 for &a in &anc {
299 if pairs.contains(&(class, a)) {
300 out.push(OntologyDefect {
301 kind: Defect::DisjointWithAncestor,
302 subject: class,
303 other: Some(a),
304 path: Vec::new(),
305 });
306 }
307 }
308 // 二、两个祖先互相互斥。有序对去重,否则展开成两行的 disjoint 会报两遍
309 let mut sorted: Vec<Uuid> = anc.iter().copied().collect();
310 sorted.sort();
311 for (i, &a) in sorted.iter().enumerate() {
312 for &b in &sorted[i + 1..] {
313 if pairs.contains(&(a, b)) {
314 out.push(OntologyDefect {
315 kind: Defect::InheritsDisjoint,
316 subject: class,
317 other: Some(b),
318 path: vec![a],
319 });
320 }
321 }
322 }
323 }
324 out
325}
326
327/// 一个类的全部祖先(不含自己)。有环也不会转不出来——`seen` 挡住。
328fn ancestors(class: Uuid, up: &HashMap<Uuid, Vec<Uuid>>) -> HashSet<Uuid> {
329 let mut seen = HashSet::new();
330 let mut queue = vec![(class, 0usize)];
331 while let Some((at, depth)) = queue.pop() {
332 if depth >= MAX_ANCESTRY {
333 continue;
334 }
335 let Some(ups) = up.get(&at) else {
336 continue;
337 };
338 for &parent in ups {
339 if parent != class && seen.insert(parent) {
340 queue.push((parent, depth + 1));
341 }
342 }
343 }
344 seen
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 fn c(i: u8) -> Uuid {
352 Uuid::from_bytes([i; 16])
353 }
354 fn kinds(v: &[OntologyDefect]) -> Vec<Defect> {
355 let mut k: Vec<Defect> = v.iter().map(|d| d.kind).collect();
356 k.sort();
357 k
358 }
359 fn ax(f: impl Fn(&mut Axioms)) -> HashMap<Uuid, Axioms> {
360 let mut a = Axioms::default();
361 f(&mut a);
362 HashMap::from([(c(99), a)])
363 }
364
365 #[test]
366 fn a_property_cannot_be_both_symmetric_and_asymmetric() {
367 let a = ax(|a| {
368 a.symmetric = true;
369 a.asymmetric = true;
370 });
371 let d = check_ontology(&a, &[], &[]);
372 assert_eq!(kinds(&d), vec![Defect::SymmetricAndAsymmetric]);
373 assert_eq!(d[0].subject, c(99));
374 }
375
376 #[test]
377 fn either_one_alone_is_fine() {
378 assert!(check_ontology(&ax(|a| a.symmetric = true), &[], &[]).is_empty());
379 assert!(check_ontology(&ax(|a| a.asymmetric = true), &[], &[]).is_empty());
380 // 传递 + 反对称是**正常的**——它正是环检测有意义的前提
381 let both = ax(|a| {
382 a.transitive = true;
383 a.asymmetric = true;
384 });
385 assert!(check_ontology(&both, &[], &[]).is_empty());
386 }
387
388 #[test]
389 fn transitive_and_functional_is_forbidden_by_owl2() {
390 let a = ax(|a| {
391 a.transitive = true;
392 a.functional = true;
393 });
394 assert_eq!(
395 kinds(&check_ontology(&a, &[], &[])),
396 vec![Defect::TransitiveAndFunctional]
397 );
398 // 反函数性同理
399 let b = ax(|a| {
400 a.transitive = true;
401 a.inverse_functional = true;
402 });
403 assert_eq!(
404 kinds(&check_ontology(&b, &[], &[])),
405 vec![Defect::TransitiveAndFunctional]
406 );
407 }
408
409 #[test]
410 fn subclass_of_can_form_a_ring() {
411 let none = HashMap::new();
412 // 1 → 2 → 3 → 1
413 let ring = [(c(1), c(2)), (c(2), c(3)), (c(3), c(1))];
414 let d = check_ontology(&none, &ring, &[]);
415 assert_eq!(kinds(&d), vec![Defect::SubclassCycle], "三个类绕成一圈");
416 assert_eq!(d.len(), 1, "同一个环只报一次,不是每个类各报一次");
417 assert_eq!(d[0].path.len(), 3, "路径要带上环上全部三个类");
418 }
419
420 #[test]
421 fn a_tree_is_not_a_ring() {
422 let none = HashMap::new();
423 // 多父也不是环:4 同时挂在 2 与 3 下
424 let tree = [(c(1), c(2)), (c(1), c(3)), (c(4), c(2)), (c(4), c(3))];
425 assert!(check_ontology(&none, &tree, &[]).is_empty());
426 }
427
428 #[test]
429 fn a_class_disjoint_with_its_own_ancestor_can_never_exist() {
430 let none = HashMap::new();
431 let parents = [(c(1), c(2)), (c(2), c(3))];
432 // 导入侧把 disjoint 的对称性展开成两行,这里照样给两行
433 let dis = [(c(1), c(3)), (c(3), c(1))];
434 let d = check_ontology(&none, &parents, &dis);
435 assert_eq!(kinds(&d), vec![Defect::DisjointWithAncestor]);
436 assert_eq!(d[0].subject, c(1));
437 assert_eq!(d[0].other, Some(c(3)), "指出跟哪个祖先互斥——人要去改那一条");
438 }
439
440 #[test]
441 fn two_disjoint_ancestors_make_a_class_unsatisfiable() {
442 let none = HashMap::new();
443 // 1 同时是 2 与 3 的子类,而 2 与 3 互斥
444 let parents = [(c(1), c(2)), (c(1), c(3))];
445 let dis = [(c(2), c(3)), (c(3), c(2))];
446 let d = check_ontology(&none, &parents, &dis);
447 assert_eq!(kinds(&d), vec![Defect::InheritsDisjoint]);
448 assert_eq!(d.len(), 1, "展开成两行的 disjoint 不该报两遍");
449 assert_eq!(d[0].subject, c(1));
450 }
451
452 #[test]
453 fn disjoint_between_unrelated_branches_is_the_point_of_disjoint() {
454 let none = HashMap::new();
455 // 2 与 3 互斥,而 1 只挂在 2 下、4 只挂在 3 下——这正是 disjoint 的正常用法
456 let parents = [(c(1), c(2)), (c(4), c(3))];
457 let dis = [(c(2), c(3)), (c(3), c(2))];
458 assert!(check_ontology(&none, &parents, &dis).is_empty());
459 }
460
461 #[test]
462 fn a_ring_does_not_hang_the_ancestor_walk() {
463 let none = HashMap::new();
464 let ring = [(c(1), c(2)), (c(2), c(1))];
465 let dis = [(c(1), c(2)), (c(2), c(1))];
466 // 环 + 互斥同时存在:既要报环,也不能在上溯时转不出来
467 let d = check_ontology(&none, &ring, &dis);
468 assert!(d.iter().any(|x| x.kind == Defect::SubclassCycle));
469 assert!(d.iter().any(|x| x.kind == Defect::DisjointWithAncestor));
470 }
471
472 #[test]
473 fn nothing_declared_means_nothing_reported() {
474 assert!(check_ontology(&HashMap::new(), &[], &[]).is_empty());
475 // 类层级齐全但一条 disjoint 都没有 → 没有判据
476 let parents = [(c(1), c(2)), (c(2), c(3))];
477 assert!(check_ontology(&HashMap::new(), &parents, &[]).is_empty());
478 }
479}
480
481#[cfg(test)]
482mod inverse_and_sub_property_tests {
483 use super::*;
484
485 fn c(i: u8) -> Uuid {
486 Uuid::from_bytes([i; 16])
487 }
488 fn kinds(v: &[OntologyDefect]) -> Vec<Defect> {
489 let mut k: Vec<Defect> = v.iter().map(|d| d.kind).collect();
490 k.sort();
491 k
492 }
493 fn only(id: Uuid, a: Axioms) -> HashMap<Uuid, Axioms> {
494 HashMap::from([(id, a)])
495 }
496
497 /// 自己是自己的逆 —— 合法但绕远路,提示改用 symmetric。
498 #[test]
499 fn a_predicate_that_is_its_own_inverse_should_just_say_symmetric() {
500 let a = Axioms {
501 inverse_of: Some(c(1)),
502 ..Default::default()
503 };
504 let d = check_ontology(&only(c(1), a), &[], &[]);
505 assert_eq!(kinds(&d), vec![Defect::InverseOfItself]);
506 }
507
508 /// 自己的逆 + 反对称 = 与 symmetric+asymmetric 同一个矛盾,换了个写法。
509 #[test]
510 fn its_own_inverse_and_asymmetric_is_the_same_contradiction_in_disguise() {
511 let a = Axioms {
512 inverse_of: Some(c(1)),
513 asymmetric: true,
514 ..Default::default()
515 };
516 let d = check_ontology(&only(c(1), a), &[], &[]);
517 assert!(
518 kinds(&d).contains(&Defect::SymmetricAndAsymmetric),
519 "**要报成同一类**:读的人不该因为写法不同就以为是两回事"
520 );
521 }
522
523 /// 互指一致 —— 干净,什么都不该报。
524 #[test]
525 fn a_mutual_pair_is_clean() {
526 let ax = HashMap::from([
527 (
528 c(1),
529 Axioms {
530 inverse_of: Some(c(2)),
531 ..Default::default()
532 },
533 ),
534 (
535 c(2),
536 Axioms {
537 inverse_of: Some(c(1)),
538 ..Default::default()
539 },
540 ),
541 ]);
542 assert!(check_ontology(&ax, &[], &[]).is_empty());
543 }
544
545 /// `p⁻¹ = q` 而 `q⁻¹ = r` —— 两边指得不一样。
546 ///
547 /// **载入公理时只补空缺不覆盖**,所以这个矛盾不会被悄悄抹平;
548 /// 它必须在这里被报出来,否则没有任何地方会提。
549 #[test]
550 fn an_inverse_that_does_not_point_back_is_reported() {
551 let ax = HashMap::from([
552 (
553 c(1),
554 Axioms {
555 inverse_of: Some(c(2)),
556 ..Default::default()
557 },
558 ),
559 (
560 c(2),
561 Axioms {
562 inverse_of: Some(c(3)),
563 ..Default::default()
564 },
565 ),
566 ]);
567 let d = check_ontology(&ax, &[], &[]);
568 let one = d
569 .iter()
570 .find(|x| x.kind == Defect::InverseNotMutual)
571 .expect("该报 InverseNotMutual");
572 assert_eq!(one.subject, c(1));
573 assert_eq!(one.other, Some(c(2)));
574 assert_eq!(one.path, vec![c(1), c(2), c(3)], "路径要说清指到哪去了");
575 }
576
577 /// subPropertyOf 成环。
578 #[test]
579 fn a_sub_property_ring_is_a_single_predicate_wearing_three_hats() {
580 let mk = |parent: u8| Axioms {
581 sub_property_of: Some(c(parent)),
582 ..Default::default()
583 };
584 let ax = HashMap::from([(c(1), mk(2)), (c(2), mk(3)), (c(3), mk(1))]);
585 let d = check_ontology(&ax, &[], &[]);
586 let ring: Vec<&OntologyDefect> = d
587 .iter()
588 .filter(|x| x.kind == Defect::SubPropertyCycle)
589 .collect();
590 assert_eq!(ring.len(), 1, "**整条环只报一次**,不是每个成员报一遍");
591 assert_eq!(ring[0].path.len(), 3);
592 }
593
594 /// 一条不成环的链不该被误报。
595 #[test]
596 fn a_chain_that_ends_is_not_a_ring() {
597 let ax = HashMap::from([
598 (
599 c(1),
600 Axioms {
601 sub_property_of: Some(c(2)),
602 ..Default::default()
603 },
604 ),
605 (
606 c(2),
607 Axioms {
608 sub_property_of: Some(c(3)),
609 ..Default::default()
610 },
611 ),
612 ]);
613 assert!(check_ontology(&ax, &[], &[]).is_empty());
614 }
615}