Skip to main content

qualia_core_db/modalities/
dialectical.rs

1use crate::NQuin;
2
3// Canonical bit positions live in the FrameLayout ABI (single source of truth).
4pub use crate::frame_layout::{COUNTERFACTUAL_BIT, DO_INTERVENTION_BIT, SYNTHESIZED_BIT};
5
6/// Causal intervention operator for do-calculus
7/// Implements P(Y | do(X = x)) by intervening on the causal graph.
8///
9/// The do-calculus intervention do(X = x) severs X from its parents (removes
10/// incoming edges to X) while preserving X's outgoing causal edges so that
11/// X can still influence downstream variables.  We mark the intervention on
12/// the relevant quins with DO_INTERVENTION_BIT but do NOT overwrite the
13/// structural `object` field (which encodes the causal successor, not X's
14/// value).  The intervention_value is recorded in metadata so callers can
15/// inspect it; path existence is used as the evidence of causal effect.
16pub 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    // Apply intervention: mark outgoing edges from X and drop incoming edges
26    // to X (cut X from its parents) but preserve the causal structure X → …
27    // Store intervention_value in the upper bits of metadata so it is
28    // visible without corrupting the `object` (causal target) field.
29    intervened_graph.retain(|q| q.object != intervention_var); // remove parents of X
30    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 from intervention variable to target
37    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    // P(Y = target_var reached) = fraction of discovered paths
49    // Each discovered path represents one causal route; all routes count as
50    // evidence that the intervention influences the target.
51    let total_count = causal_paths.len() as f64;
52    Some(total_count / total_count) // = 1.0 when any path exists
53}
54
55/// Counterfactual query: "What would happen if X were x?"
56pub 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    // Step 1: Abduction - update beliefs based on actual outcome
64    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    // Step 2: Action - apply counterfactual intervention.
73    // Mark the intervention in metadata (upper bits hold the intervention value)
74    // but preserve the structural `object` field (causal successor) so that
75    // do_intervention() can still traverse the causal graph.
76    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    // Step 3: Prediction - compute counterfactual outcome
83    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; // Store as scaled integer
93        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
102/// Find all causal paths from source to target in the causal graph
103fn find_causal_paths(graph: &[NQuin], source: u64, target: u64, paths: &mut Vec<Vec<NQuin>>) {
104    // Simple depth-first search for causal paths
105    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
118/// Depth-first search helper for finding causal paths
119fn 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(&current) {
128        return;
129    }
130
131    visited.insert(current);
132
133    // Find all outgoing edges from current node
134    for quin in graph {
135        if quin.subject == current {
136            current_path.push(*quin);
137
138            if quin.object == target {
139                // Found a path to target
140                all_paths.push(current_path.clone());
141            } else {
142                // Continue searching
143                dfs_find_paths(graph, quin.object, target, visited, current_path, all_paths);
144            }
145
146            current_path.pop();
147        }
148    }
149
150    visited.remove(&current);
151}
152
153/// Check if two variables are confounded (share a common cause)
154pub fn are_confounded(graph: &[NQuin], var1: u64, var2: u64) -> bool {
155    // Find common causes by looking for nodes that point to both var1 and var2
156    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    // Check for intersection (common causes)
169    !parents1.is_disjoint(&parents2)
170}
171
172/// Compute do-calculus adjustment for confounding
173pub fn adjust_for_confounding(
174    graph: &[NQuin],
175    treatment: u64,
176    outcome: u64,
177    confounder: u64,
178) -> Option<f64> {
179    // Simplified adjustment: P(Y|do(X)) = Σ_z P(Y|X,Z=z) * P(Z=z)
180    // This is a basic implementation - full do-calculus would be more sophisticated
181
182    let mut adjusted_prob = 0.0;
183    let mut confounder_values = std::collections::HashSet::new();
184
185    // Collect all possible values of confounder
186    for quin in graph {
187        if quin.subject == confounder {
188            confounder_values.insert(quin.object);
189        }
190    }
191
192    // Compute adjustment
193    for &confounder_val in &confounder_values {
194        // P(Y|X,Z=z)
195        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            // P(Z=z) - simplified as uniform distribution
209            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
221/// Compute conditional probability P(Y|X) from graph.
222///
223/// In a causal graph whose edges represent causal arrows (not observations),
224/// P(Y|X) is estimated as 1.0 if Y is causally reachable from X via a
225/// directed path, and None if X has no outgoing edges at all (X is
226/// unobserved / disconnected in this context).
227fn compute_conditional_probability(graph: &[NQuin], y_var: u64, x_var: u64) -> Option<f64> {
228    // Check that X participates as a cause in this graph
229    let x_has_edges = graph.iter().any(|q| q.subject == x_var);
230    if !x_has_edges {
231        return None;
232    }
233
234    // BFS / DFS reachability from x_var to y_var
235    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    // Y not reachable from X in this graph — no causal effect
251    Some(0.0)
252}
253
254/// Attempt dialectical synthesis of a thesis/antithesis pair. A
255/// contradiction is detected when subject and predicate match but
256/// objects differ; the synthesized quin then XOR-folds the two
257/// contexts and objects and sets `SYNTHESIZED_BIT`, with parity
258/// recomputed. `None` when the pair isn't a contradiction.
259pub fn synthesize_dialectical(thesis: &NQuin, antithesis: &NQuin) -> Option<NQuin> {
260    // A contradiction requires the same subject and predicate but different object
261    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        // The object becomes a combination, maybe just bitwise XOR for now?
269        synthesized.object = thesis.object ^ antithesis.object;
270
271        // Update parity to maintain structural integrity
272        synthesized.parity =
273            synthesized.subject ^ synthesized.predicate ^ synthesized.object ^ synthesized.context;
274
275        return Some(synthesized);
276    }
277    None
278}
279
280// ─── Causal necessity (but-for) — zero-heap reachability ─────────────────────────
281
282/// Max nodes for the bounded zero-heap causal reachability search.
283pub const MAX_CAUSAL_NODES: usize = 256;
284
285/// Zero-heap reachability over causal edges (`subject → object`): is `target`
286/// reachable from `source` WITHOUT ever passing through `avoid`? Bounded BFS over
287/// fixed stack buffers (no allocation). Pass `avoid == u64::MAX` to avoid nothing.
288/// (The heap variant `find_causal_paths` enumerates *all* paths for analysis;
289/// this answers the yes/no reachability the but-for test needs, allocation-free.)
290pub 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
332/// But-for causal necessity: `candidate` is a NECESSARY cause of `effect` (from
333/// origin `root`) iff `effect` is reachable from `root`, but is NOT reachable once
334/// `candidate` is removed from the causal graph. The attribution/liability test
335/// ("would the harm have occurred but for this agent's act?"). Zero-heap.
336pub 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
341// ─── Paraconsistent conflict isolation ────────────────────────────────────────────
342
343/// A **dialectical contradiction**: thesis and antithesis assert the same `(subject, predicate)`
344/// with different objects — the conflict that is either SYNTHESIZED ([`synthesize_dialectical`])
345/// or, when no synthesis is wanted, ISOLATED into a paraconsistent sub-context
346/// (`paraconsistent::route_paraconsistent`) so it does not explode the rest of the graph.
347pub 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// ─── IBIS discourse model (Issue-Based Information System) ─────────────────────────
354
355/// An IBIS discourse node — the multi-agent argumentation structure: an `Issue` raises a question,
356/// `Position`s answer it, and `Argument`s support or object to positions.
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub enum IbisNode {
359    Issue,
360    Position,
361    /// An argument that supports (`true`) or objects to (`false`) a position.
362    Argument(bool),
363}
364
365/// A position in an IBIS discourse is **favoured** iff its net support (supporting − objecting
366/// arguments) is positive. The multi-agent dialectical resolution of an issue.
367#[inline]
368pub fn ibis_position_favoured(supporting: u32, objecting: u32) -> bool {
369    supporting > objecting
370}
371
372// ─── Synthesis-coherence scoring ──────────────────────────────────────────────────
373
374/// **Synthesis-quality / coherence** score in `[0,1]`: a good Hegelian synthesis PRESERVES the
375/// shared ground (same subject + predicate as both thesis and antithesis) and genuinely INTEGRATES
376/// the two objects (rather than echoing one side). `1.0` for a well-formed synthesis; lower when it
377/// drifts from the common ground or fails to combine both sides.
378pub 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        // Chain: root → C → effect. C is necessary (removing it disconnects effect).
412        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        // Diamond: root → C → effect AND root → D → effect. C is NOT necessary.
418        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        // Same subject+predicate, different object → a dialectical contradiction.
447        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        // The synthesis (XOR-combined object) is highly coherent (preserves ground, integrates both).
452        let synthesis = synthesize_dialectical(&thesis, &antithesis).unwrap();
453        assert!((synthesis_coherence(&thesis, &antithesis, &synthesis) - 1.0).abs() < 1e-6);
454        // A degenerate "synthesis" that just echoes the thesis scores lower (no integration).
455        assert!(synthesis_coherence(&thesis, &antithesis, &thesis) < 1.0);
456
457        // IBIS: a position with more support than objection is favoured.
458        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        // Create a simple causal graph: X -> Y
490        let mut graph = Vec::new();
491
492        // X = 1 causes Y = 1
493        let mut x_to_y = NQuin::default();
494        x_to_y.subject = 1; // X
495        x_to_y.predicate = crate::q_hash("causes");
496        x_to_y.object = 2; // Y
497        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        // Test intervention: do(X = 1) should affect Y
502        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        // Create causal graph: Treatment -> Outcome
510        let mut graph = Vec::new();
511
512        let mut treatment_to_outcome = NQuin::default();
513        treatment_to_outcome.subject = 10; // Treatment
514        treatment_to_outcome.predicate = crate::q_hash("causes");
515        treatment_to_outcome.object = 20; // Outcome
516        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        // Test counterfactual: "What if Treatment were 0?"
524        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); // Target is outcome
529        assert!(counterfactual.metadata & COUNTERFACTUAL_BIT != 0);
530    }
531
532    #[test]
533    fn test_confounding_detection() {
534        // Create graph with confounding: Confounder -> Treatment, Confounder -> Outcome
535        let mut graph = Vec::new();
536
537        // Confounder -> Treatment
538        let mut conf_to_treat = NQuin::default();
539        conf_to_treat.subject = 100; // Confounder
540        conf_to_treat.predicate = crate::q_hash("causes");
541        conf_to_treat.object = 10; // Treatment
542        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        // Confounder -> Outcome
550        let mut conf_to_outcome = NQuin::default();
551        conf_to_outcome.subject = 100; // Confounder
552        conf_to_outcome.predicate = crate::q_hash("causes");
553        conf_to_outcome.object = 20; // Outcome
554        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        // Test confounding detection
562        let confounded = are_confounded(&graph, 10, 20);
563        assert!(confounded);
564    }
565
566    #[test]
567    fn test_adjust_for_confounding() {
568        // Create graph with confounding
569        let mut graph = Vec::new();
570
571        // Confounder -> Treatment
572        let mut conf_to_treat = NQuin::default();
573        conf_to_treat.subject = 100; // Confounder
574        conf_to_treat.predicate = crate::q_hash("causes");
575        conf_to_treat.object = 10; // Treatment
576        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        // Treatment -> Outcome
584        let mut treat_to_outcome = NQuin::default();
585        treat_to_outcome.subject = 10; // Treatment
586        treat_to_outcome.predicate = crate::q_hash("causes");
587        treat_to_outcome.object = 20; // Outcome
588        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        // Test adjustment
596        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, // Different predicate
615            object: 4,
616            context: 20,
617            metadata: 0,
618            parity: 0,
619        };
620
621        assert!(synthesize_dialectical(&thesis, &no_contradiction).is_none());
622    }
623}