1use crate::NQuin;
2
3pub use crate::frame_layout::{COUNTERFACTUAL_BIT, DO_INTERVENTION_BIT, SYNTHESIZED_BIT};
5
6pub fn do_intervention(
17 graph: &[NQuin],
18 intervention_var: u64,
19 intervention_value: u64,
20 target_var: u64,
21) -> Option<f64> {
22 let mut causal_paths = Vec::new();
23 let mut intervened_graph = graph.to_vec();
24
25 intervened_graph.retain(|q| q.object != intervention_var); for quin in &mut intervened_graph {
31 if quin.subject == intervention_var {
32 quin.metadata = DO_INTERVENTION_BIT | (intervention_value << 32);
33 }
34 }
35
36 find_causal_paths(
38 &intervened_graph,
39 intervention_var,
40 target_var,
41 &mut causal_paths,
42 );
43
44 if causal_paths.is_empty() {
45 return None;
46 }
47
48 let total_count = causal_paths.len() as f64;
52 Some(total_count / total_count) }
54
55pub fn counterfactual_query(
57 actual_graph: &[NQuin],
58 factual_outcome: u64,
59 counterfactual_intervention: u64,
60 intervention_value: u64,
61 target_var: u64,
62) -> Option<NQuin> {
63 let mut updated_graph = actual_graph.to_vec();
65 for quin in &mut updated_graph {
66 if quin.subject == target_var {
67 quin.object = factual_outcome;
68 quin.metadata |= COUNTERFACTUAL_BIT;
69 }
70 }
71
72 for quin in &mut updated_graph {
77 if quin.subject == counterfactual_intervention {
78 quin.metadata |= DO_INTERVENTION_BIT | (intervention_value << 32);
79 }
80 }
81
82 if let Some(counterfactual_prob) = do_intervention(
84 &updated_graph,
85 counterfactual_intervention,
86 intervention_value,
87 target_var,
88 ) {
89 let mut result = NQuin::default();
90 result.subject = target_var;
91 result.predicate = crate::q_hash("has_counterfactual_probability");
92 result.object = (counterfactual_prob * 1000.0) as u64; result.metadata = COUNTERFACTUAL_BIT;
94 result.parity = result.subject ^ result.predicate ^ result.object ^ result.context;
95
96 Some(result)
97 } else {
98 None
99 }
100}
101
102fn find_causal_paths(graph: &[NQuin], source: u64, target: u64, paths: &mut Vec<Vec<NQuin>>) {
104 let mut visited = std::collections::HashSet::new();
106 let mut current_path = Vec::new();
107
108 dfs_find_paths(
109 graph,
110 source,
111 target,
112 &mut visited,
113 &mut current_path,
114 paths,
115 );
116}
117
118fn dfs_find_paths(
120 graph: &[NQuin],
121 current: u64,
122 target: u64,
123 visited: &mut std::collections::HashSet<u64>,
124 current_path: &mut Vec<NQuin>,
125 all_paths: &mut Vec<Vec<NQuin>>,
126) {
127 if visited.contains(¤t) {
128 return;
129 }
130
131 visited.insert(current);
132
133 for quin in graph {
135 if quin.subject == current {
136 current_path.push(*quin);
137
138 if quin.object == target {
139 all_paths.push(current_path.clone());
141 } else {
142 dfs_find_paths(graph, quin.object, target, visited, current_path, all_paths);
144 }
145
146 current_path.pop();
147 }
148 }
149
150 visited.remove(¤t);
151}
152
153pub fn are_confounded(graph: &[NQuin], var1: u64, var2: u64) -> bool {
155 let mut parents1 = std::collections::HashSet::new();
157 let mut parents2 = std::collections::HashSet::new();
158
159 for quin in graph {
160 if quin.object == var1 {
161 parents1.insert(quin.subject);
162 }
163 if quin.object == var2 {
164 parents2.insert(quin.subject);
165 }
166 }
167
168 !parents1.is_disjoint(&parents2)
170}
171
172pub fn adjust_for_confounding(
174 graph: &[NQuin],
175 treatment: u64,
176 outcome: u64,
177 confounder: u64,
178) -> Option<f64> {
179 let mut adjusted_prob = 0.0;
183 let mut confounder_values = std::collections::HashSet::new();
184
185 for quin in graph {
187 if quin.subject == confounder {
188 confounder_values.insert(quin.object);
189 }
190 }
191
192 for &confounder_val in &confounder_values {
194 let mut filtered_graph = graph.to_vec();
196 for quin in &mut filtered_graph {
197 if quin.subject == treatment {
198 quin.metadata |= DO_INTERVENTION_BIT;
199 }
200 if quin.subject == confounder {
201 quin.object = confounder_val;
202 }
203 }
204
205 if let Some(p_y_given_x_z) =
206 compute_conditional_probability(&filtered_graph, outcome, treatment)
207 {
208 let p_z = 1.0 / confounder_values.len() as f64;
210 adjusted_prob += p_y_given_x_z * p_z;
211 }
212 }
213
214 if adjusted_prob > 0.0 {
215 Some(adjusted_prob)
216 } else {
217 None
218 }
219}
220
221fn compute_conditional_probability(graph: &[NQuin], y_var: u64, x_var: u64) -> Option<f64> {
228 let x_has_edges = graph.iter().any(|q| q.subject == x_var);
230 if !x_has_edges {
231 return None;
232 }
233
234 let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
236 let mut frontier: Vec<u64> = vec![x_var];
237 while let Some(current) = frontier.pop() {
238 if current == y_var {
239 return Some(1.0);
240 }
241 if visited.insert(current) {
242 for quin in graph {
243 if quin.subject == current && !visited.contains(&quin.object) {
244 frontier.push(quin.object);
245 }
246 }
247 }
248 }
249
250 Some(0.0)
252}
253
254pub fn synthesize_dialectical(thesis: &NQuin, antithesis: &NQuin) -> Option<NQuin> {
260 if thesis.subject == antithesis.subject
262 && thesis.predicate == antithesis.predicate
263 && thesis.object != antithesis.object
264 {
265 let mut synthesized = *thesis;
266 synthesized.context = thesis.context ^ antithesis.context;
267 synthesized.metadata |= SYNTHESIZED_BIT;
268 synthesized.object = thesis.object ^ antithesis.object;
270
271 synthesized.parity =
273 synthesized.subject ^ synthesized.predicate ^ synthesized.object ^ synthesized.context;
274
275 return Some(synthesized);
276 }
277 None
278}
279
280pub const MAX_CAUSAL_NODES: usize = 256;
284
285pub fn reachable_avoiding(graph: &[NQuin], source: u64, target: u64, avoid: u64) -> bool {
291 if source == avoid {
292 return false;
293 }
294 if source == target {
295 return true;
296 }
297 let mut stack = [0u64; MAX_CAUSAL_NODES];
298 let mut slen = 1usize;
299 stack[0] = source;
300 let mut visited = [0u64; MAX_CAUSAL_NODES];
301 let mut vlen = 1usize;
302 visited[0] = source;
303
304 while slen > 0 {
305 slen -= 1;
306 let node = stack[slen];
307 for q in graph {
308 if q.subject != node || q.object == avoid {
309 continue;
310 }
311 if q.object == target {
312 return true;
313 }
314 let mut seen = false;
315 for &v in visited.iter().take(vlen) {
316 if v == q.object {
317 seen = true;
318 break;
319 }
320 }
321 if !seen && vlen < MAX_CAUSAL_NODES && slen < MAX_CAUSAL_NODES {
322 visited[vlen] = q.object;
323 vlen += 1;
324 stack[slen] = q.object;
325 slen += 1;
326 }
327 }
328 }
329 false
330}
331
332pub fn is_necessary_cause(graph: &[NQuin], root: u64, candidate: u64, effect: u64) -> bool {
337 reachable_avoiding(graph, root, effect, u64::MAX)
338 && !reachable_avoiding(graph, root, effect, candidate)
339}
340
341pub fn is_dialectical_contradiction(thesis: &NQuin, antithesis: &NQuin) -> bool {
348 thesis.subject == antithesis.subject
349 && thesis.predicate == antithesis.predicate
350 && thesis.object != antithesis.object
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub enum IbisNode {
359 Issue,
360 Position,
361 Argument(bool),
363}
364
365#[inline]
368pub fn ibis_position_favoured(supporting: u32, objecting: u32) -> bool {
369 supporting > objecting
370}
371
372pub fn synthesis_coherence(thesis: &NQuin, antithesis: &NQuin, synthesis: &NQuin) -> f32 {
379 let mut score = 0.0f32;
380 if synthesis.subject == thesis.subject && synthesis.subject == antithesis.subject {
381 score += 0.4;
382 }
383 if synthesis.predicate == thesis.predicate && synthesis.predicate == antithesis.predicate {
384 score += 0.3;
385 }
386 if synthesis.object != thesis.object && synthesis.object != antithesis.object {
387 score += 0.3;
388 }
389 score
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 fn edge(cause: u64, effect: u64) -> NQuin {
397 let mut q = NQuin {
398 subject: cause,
399 predicate: crate::q_hash("causal:causes"),
400 object: effect,
401 context: 0,
402 metadata: 0,
403 parity: 0,
404 };
405 q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
406 q
407 }
408
409 #[test]
410 fn but_for_causal_necessity() {
411 let chain = [edge(1, 2), edge(2, 3)];
413 assert!(
414 is_necessary_cause(&chain, 1, 2, 3),
415 "C is a necessary cause in a chain"
416 );
417 let diamond = [edge(1, 2), edge(2, 4), edge(1, 3), edge(3, 4)];
419 assert!(
420 !is_necessary_cause(&diamond, 1, 2, 4),
421 "C is not necessary when an alternative path exists"
422 );
423 assert!(
424 reachable_avoiding(&diamond, 1, 4, u64::MAX),
425 "effect is reachable normally"
426 );
427 }
428
429 #[test]
430 fn dialectical_contradiction_ibis_and_coherence() {
431 let mk = |s: u64, p: u64, o: u64| {
432 let mut q = NQuin {
433 subject: s,
434 predicate: p,
435 object: o,
436 context: 0,
437 metadata: 0,
438 parity: 0,
439 };
440 q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
441 q
442 };
443 let (subj, pred) = (crate::q_hash("policy:borders"), crate::q_hash("stance"));
444 let thesis = mk(subj, pred, crate::q_hash("open"));
445 let antithesis = mk(subj, pred, crate::q_hash("closed"));
446 assert!(is_dialectical_contradiction(&thesis, &antithesis));
448 let agree = mk(subj, pred, crate::q_hash("open"));
449 assert!(!is_dialectical_contradiction(&thesis, &agree));
450
451 let synthesis = synthesize_dialectical(&thesis, &antithesis).unwrap();
453 assert!((synthesis_coherence(&thesis, &antithesis, &synthesis) - 1.0).abs() < 1e-6);
454 assert!(synthesis_coherence(&thesis, &antithesis, &thesis) < 1.0);
456
457 assert!(ibis_position_favoured(3, 1));
459 assert!(!ibis_position_favoured(1, 1));
460 assert_eq!(IbisNode::Argument(true), IbisNode::Argument(true));
461 }
462
463 #[test]
464 fn test_synthesize_dialectical() {
465 let thesis = NQuin {
466 subject: 1,
467 predicate: 2,
468 object: 3,
469 context: 10,
470 metadata: 0,
471 parity: 0,
472 };
473 let antithesis = NQuin {
474 subject: 1,
475 predicate: 2,
476 object: 4,
477 context: 20,
478 metadata: 0,
479 parity: 0,
480 };
481
482 let syn = synthesize_dialectical(&thesis, &antithesis).unwrap();
483 assert_eq!(syn.context, 10 ^ 20);
484 assert!(syn.metadata & SYNTHESIZED_BIT != 0);
485 }
486
487 #[test]
488 fn test_do_intervention() {
489 let mut graph = Vec::new();
491
492 let mut x_to_y = NQuin::default();
494 x_to_y.subject = 1; x_to_y.predicate = crate::q_hash("causes");
496 x_to_y.object = 2; x_to_y.context = 100;
498 x_to_y.parity = x_to_y.subject ^ x_to_y.predicate ^ x_to_y.object ^ x_to_y.context;
499 graph.push(x_to_y);
500
501 let result = do_intervention(&graph, 1, 1, 2);
503 assert!(result.is_some());
504 assert!(result.unwrap() > 0.0);
505 }
506
507 #[test]
508 fn test_counterfactual_query() {
509 let mut graph = Vec::new();
511
512 let mut treatment_to_outcome = NQuin::default();
513 treatment_to_outcome.subject = 10; treatment_to_outcome.predicate = crate::q_hash("causes");
515 treatment_to_outcome.object = 20; treatment_to_outcome.context = 200;
517 treatment_to_outcome.parity = treatment_to_outcome.subject
518 ^ treatment_to_outcome.predicate
519 ^ treatment_to_outcome.object
520 ^ treatment_to_outcome.context;
521 graph.push(treatment_to_outcome);
522
523 let result = counterfactual_query(&graph, 1, 10, 0, 20);
525 assert!(result.is_some());
526
527 let counterfactual = result.unwrap();
528 assert_eq!(counterfactual.subject, 20); assert!(counterfactual.metadata & COUNTERFACTUAL_BIT != 0);
530 }
531
532 #[test]
533 fn test_confounding_detection() {
534 let mut graph = Vec::new();
536
537 let mut conf_to_treat = NQuin::default();
539 conf_to_treat.subject = 100; conf_to_treat.predicate = crate::q_hash("causes");
541 conf_to_treat.object = 10; conf_to_treat.context = 300;
543 conf_to_treat.parity = conf_to_treat.subject
544 ^ conf_to_treat.predicate
545 ^ conf_to_treat.object
546 ^ conf_to_treat.context;
547 graph.push(conf_to_treat);
548
549 let mut conf_to_outcome = NQuin::default();
551 conf_to_outcome.subject = 100; conf_to_outcome.predicate = crate::q_hash("causes");
553 conf_to_outcome.object = 20; conf_to_outcome.context = 301;
555 conf_to_outcome.parity = conf_to_outcome.subject
556 ^ conf_to_outcome.predicate
557 ^ conf_to_outcome.object
558 ^ conf_to_outcome.context;
559 graph.push(conf_to_outcome);
560
561 let confounded = are_confounded(&graph, 10, 20);
563 assert!(confounded);
564 }
565
566 #[test]
567 fn test_adjust_for_confounding() {
568 let mut graph = Vec::new();
570
571 let mut conf_to_treat = NQuin::default();
573 conf_to_treat.subject = 100; conf_to_treat.predicate = crate::q_hash("causes");
575 conf_to_treat.object = 10; conf_to_treat.context = 400;
577 conf_to_treat.parity = conf_to_treat.subject
578 ^ conf_to_treat.predicate
579 ^ conf_to_treat.object
580 ^ conf_to_treat.context;
581 graph.push(conf_to_treat);
582
583 let mut treat_to_outcome = NQuin::default();
585 treat_to_outcome.subject = 10; treat_to_outcome.predicate = crate::q_hash("causes");
587 treat_to_outcome.object = 20; treat_to_outcome.context = 401;
589 treat_to_outcome.parity = treat_to_outcome.subject
590 ^ treat_to_outcome.predicate
591 ^ treat_to_outcome.object
592 ^ treat_to_outcome.context;
593 graph.push(treat_to_outcome);
594
595 let adjusted = adjust_for_confounding(&graph, 10, 20, 100);
597 assert!(adjusted.is_some());
598 assert!(adjusted.unwrap() >= 0.0);
599 }
600
601 #[test]
602 fn test_no_contradiction() {
603 let thesis = NQuin {
604 subject: 1,
605 predicate: 2,
606 object: 3,
607 context: 10,
608 metadata: 0,
609 parity: 0,
610 };
611
612 let no_contradiction = NQuin {
613 subject: 1,
614 predicate: 3, object: 4,
616 context: 20,
617 metadata: 0,
618 parity: 0,
619 };
620
621 assert!(synthesize_dialectical(&thesis, &no_contradiction).is_none());
622 }
623}