Skip to main content

gcn_knowledge/
inference.rs

1// Copyright 2026 Michel Tendeng
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashMap;
5use std::path::Path;
6
7const DELTA_STRONG_CAUSAL: f32 = 0.15;
8const DELTA_CAUSAL: f32 = 0.10;
9const DELTA_ADVERSATIVE: f32 = -0.10;
10
11use gcn_ir::{
12    edge::RelationType,
13    ir::CausalIR,
14    node::{NodeId, NodeOrigin, NodeType},
15    scope::Scope,
16};
17
18use crate::KnowledgeError;
19use crate::lexicon::Lexicon;
20
21// ─────────────────────────────────────────────────────────────────────────────
22
23/// Résultat d'une opération d'enrichissement sur un `CausalIR`.
24#[derive(Debug, Clone, PartialEq)]
25pub enum InferenceNote {
26    /// Un type de nœud inféré a été corrigé par la taxonomie.
27    NodeTypeResolved {
28        node_id: NodeId,
29        from: NodeType,
30        to: NodeType,
31        rule: String,
32    },
33    /// La confiance d'une arête implicite a été recalibrée.
34    ConfidenceAdjusted {
35        from_id: NodeId,
36        to_id: NodeId,
37        from: f32,
38        to: f32,
39        rule: String,
40    },
41    /// Une arête signale une lacune causale (Concession ou Opposition).
42    CausalGapSignaled {
43        from_id: NodeId,
44        to_id: NodeId,
45        relation: RelationType,
46    },
47}
48
49// ─────────────────────────────────────────────────────────────────────────────
50
51pub struct InferenceEngine {
52    lexicon: Lexicon,
53}
54
55impl InferenceEngine {
56    /// Construit l'engine depuis un `Lexicon` déjà chargé.
57    pub fn new(lexicon: Lexicon) -> Self {
58        Self { lexicon }
59    }
60
61    /// Construit l'engine en chargeant les taxonomies depuis un répertoire.
62    pub fn from_dir(path: &Path) -> Result<Self, KnowledgeError> {
63        let lexicon = Lexicon::load_from_dir(path)?;
64        Ok(Self { lexicon })
65    }
66
67    /// Infère le `NodeType` d'un lemme depuis les taxonomies.
68    ///
69    /// Retourne `None` si le POS est hors périmètre (ex : `auxiliaire`)
70    /// ou si le lemme est inconnu.
71    pub fn infer_node_type(&self, lemma: &str, pos: &str) -> Option<NodeType> {
72        let (class_name, _entry) = self.lexicon.lookup_by_pos(pos, lemma)?;
73        class_name_to_node_type(class_name)
74    }
75
76    /// Infère le `Scope` d'un token DET ou PRON depuis les taxonomies.
77    ///
78    /// À appeler au moment du parse, quand le token est connu.
79    /// L'annotation explicite `scope` de l'entrée lexicale a priorité
80    /// sur le fallback par nom de classe.
81    pub fn infer_scope(&self, lemma: &str, pos: &str) -> Option<Scope> {
82        let (class_name, entry) = self.lexicon.lookup_by_pos(pos, lemma)?;
83        if let Some(scope_str) = &entry.scope
84            && let Some(scope) = parse_scope(scope_str)
85        {
86            return Some(scope);
87        }
88        class_name_to_scope(class_name, pos)
89    }
90
91    /// Score de confiance structurel basé sur la compatibilité des types.
92    ///
93    /// Base : `1.0` si arête explicite, `0.5` sinon.
94    /// Un bonus/malus est appliqué selon la combinaison (from, to, relation).
95    /// Résultat clampé dans `[0.1, 1.0]`.
96    pub fn score_confidence(
97        &self,
98        from: NodeType,
99        to: NodeType,
100        rel: RelationType,
101        explicit: bool,
102    ) -> f32 {
103        let base: f32 = if explicit { 1.0 } else { 0.5 };
104        let delta: f32 = match (from, to, rel) {
105            (NodeType::Processus, NodeType::EtatLocal, RelationType::Cause)
106            | (NodeType::Processus, NodeType::Processus, RelationType::Cause) => {
107                DELTA_STRONG_CAUSAL
108            }
109            (NodeType::Processus, _, RelationType::Cause) => DELTA_CAUSAL,
110            (NodeType::EtatGlobal, _, RelationType::Filter) => DELTA_STRONG_CAUSAL,
111            (_, _, RelationType::Concession | RelationType::Opposition) => DELTA_ADVERSATIVE,
112            _ => 0.0,
113        };
114        (base + delta).clamp(0.1, 1.0)
115    }
116
117    /// Enrichit un `CausalIR` en 3 passes borrow-safe et retourne les notes produites.
118    ///
119    /// - **Passe 1** : résolution des types de nœuds avec `origin == Inferred`
120    ///   via `attributes.entity` (lookup NOUN dans les taxonomies).
121    /// - **Passe 2** : snapshot `NodeId → NodeType` post-passe 1.
122    /// - **Passe 3** : recalibrage de confiance des arêtes implicites ;
123    ///   signalement des lacunes causales (Concession / Opposition).
124    pub fn enrich(&self, ir: &mut CausalIR) -> Vec<InferenceNote> {
125        let mut notes = Vec::new();
126
127        // Passe 1 — types de nœuds inférés
128        for node in &mut ir.nodes {
129            if node.origin != NodeOrigin::Inferred {
130                continue;
131            }
132            let entity = match node.attributes.entity.as_deref() {
133                Some(e) if !e.is_empty() => e,
134                _ => continue,
135            };
136            if let Some(inferred) = self.infer_node_type(entity, "NOUN")
137                && inferred != node.node_type
138            {
139                notes.push(InferenceNote::NodeTypeResolved {
140                    node_id: node.id,
141                    from: node.node_type,
142                    to: inferred,
143                    rule: format!("taxonomy_lookup:noun:{entity}"),
144                });
145                node.node_type = inferred;
146            }
147        }
148
149        // Passe 2 — snapshot post-passe 1 (évite le borrow mutable simultané)
150        let node_types: HashMap<NodeId, NodeType> =
151            ir.nodes.iter().map(|n| (n.id, n.node_type)).collect();
152
153        // Passe 3 — arêtes
154        for (src_id, dst_id, edge) in &mut ir.edges {
155            if edge.relation.signals_causal_gap() {
156                notes.push(InferenceNote::CausalGapSignaled {
157                    from_id: *src_id,
158                    to_id: *dst_id,
159                    relation: edge.relation,
160                });
161            }
162
163            if !edge.explicit {
164                let from_nt = node_types.get(src_id).copied();
165                let to_nt = node_types.get(dst_id).copied();
166                if let (Some(f), Some(t)) = (from_nt, to_nt) {
167                    let new_conf = self.score_confidence(f, t, edge.relation, false);
168                    if (new_conf - edge.confidence).abs() > 0.05 {
169                        notes.push(InferenceNote::ConfidenceAdjusted {
170                            from_id: *src_id,
171                            to_id: *dst_id,
172                            from: edge.confidence,
173                            to: new_conf,
174                            rule: "structural_compatibility".to_string(),
175                        });
176                        edge.confidence = new_conf;
177                    }
178                }
179            }
180        }
181
182        notes
183    }
184}
185
186// ─────────────────────────────────────────────────────────────────────────────
187// Helpers internes
188
189fn class_name_to_node_type(class_name: &str) -> Option<NodeType> {
190    match class_name {
191        "etat" => Some(NodeType::EtatLocal),
192        "action" => Some(NodeType::Processus),
193        "transition" => Some(NodeType::Processus),
194        "processus" => Some(NodeType::Processus),
195        "agent" | "patient" | "abstrait" | "relation" => Some(NodeType::Entite),
196        "etat_systemique" => Some(NodeType::EtatGlobal),
197        "contrainte" => Some(NodeType::Contrainte),
198        _ => None, // "auxiliaire" et autres POS non causaux
199    }
200}
201
202fn class_name_to_scope(class_name: &str, pos: &str) -> Option<Scope> {
203    match pos {
204        "DET" => match class_name {
205            "defini" | "demonstratif" | "possessif" => Some(Scope::Specific),
206            "indefini" => Some(Scope::Existential),
207            "partitif" => Some(Scope::Partial),
208            "quantitatif" => Some(Scope::Universal),
209            _ => Some(Scope::Unknown),
210        },
211        "PRON" => match class_name {
212            "personnel" | "demonstratif" | "relatif" => Some(Scope::Specific),
213            "indefini" => Some(Scope::Unknown),
214            _ => None,
215        },
216        _ => None,
217    }
218}
219
220fn parse_scope(s: &str) -> Option<Scope> {
221    match s {
222        "universal" => Some(Scope::Universal),
223        "existential" => Some(Scope::Existential),
224        "partial" => Some(Scope::Partial),
225        "null" => Some(Scope::Null),
226        "specific" => Some(Scope::Specific),
227        "unknown" => Some(Scope::Unknown),
228        _ => None,
229    }
230}
231
232// ─────────────────────────────────────────────────────────────────────────────
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use std::collections::HashMap;
238
239    use gcn_ir::{
240        CausalEdge, CausalIR, CausalNode, IrMetadata, NaturalLanguage, NodeAttributes, NodeId,
241        NodeOrigin, NodeType, RelationType, Scope, SourceLanguage, SourceSpan, TemporalRef,
242    };
243    use smallvec::SmallVec;
244
245    use crate::taxonomy::{LexicalEntry, Taxonomy, TaxonomyClass};
246
247    // ── Helpers de construction synthétique ──────────────────────────────────
248
249    fn make_entry(lemma: &str) -> LexicalEntry {
250        LexicalEntry {
251            lemma: lemma.to_string(),
252            note: None,
253            value: None,
254            kind: None,
255            anchor: None,
256            scope: None,
257            total: None,
258        }
259    }
260
261    fn make_entry_with_scope(lemma: &str, scope: &str) -> LexicalEntry {
262        LexicalEntry {
263            lemma: lemma.to_string(),
264            scope: Some(scope.to_string()),
265            note: None,
266            value: None,
267            kind: None,
268            anchor: None,
269            total: None,
270        }
271    }
272
273    fn make_class(examples: Vec<LexicalEntry>) -> TaxonomyClass {
274        TaxonomyClass {
275            description: None,
276            role: None,
277            causal_direction: None,
278            causal_effect: None,
279            dimension: None,
280            relation_type: None,
281            signals_gap: None,
282            scope: None,
283            formal: None,
284            position: None,
285            examples_fr: Some(examples),
286            examples: None,
287            subtypes: None,
288        }
289    }
290
291    fn make_taxonomy(name: &str, classes: Vec<(&str, TaxonomyClass)>) -> Taxonomy {
292        Taxonomy {
293            taxonomy: name.to_string(),
294            version: "test".to_string(),
295            description: "test".to_string(),
296            classes: classes
297                .into_iter()
298                .map(|(k, v)| (k.to_string(), v))
299                .collect(),
300            compositional_rules: None,
301        }
302    }
303
304    fn test_engine() -> InferenceEngine {
305        let mut taxonomies: HashMap<String, Taxonomy> = HashMap::new();
306
307        taxonomies.insert(
308            "verbes".to_string(),
309            make_taxonomy(
310                "verbes",
311                vec![
312                    ("etat", make_class(vec![make_entry("être")])),
313                    ("action", make_class(vec![make_entry("faire")])),
314                    ("transition", make_class(vec![make_entry("chuter")])),
315                    ("processus", make_class(vec![make_entry("baisser")])),
316                    ("auxiliaire", make_class(vec![make_entry("avoir")])),
317                ],
318            ),
319        );
320
321        taxonomies.insert(
322            "noms".to_string(),
323            make_taxonomy(
324                "noms",
325                vec![
326                    ("agent", make_class(vec![make_entry("agent")])),
327                    ("patient", make_class(vec![make_entry("marché")])),
328                    ("processus", make_class(vec![make_entry("croissance")])),
329                    ("etat_systemique", make_class(vec![make_entry("crise")])),
330                    ("abstrait", make_class(vec![make_entry("idée")])),
331                    ("relation", make_class(vec![make_entry("lien")])),
332                ],
333            ),
334        );
335
336        taxonomies.insert(
337            "determinants".to_string(),
338            make_taxonomy(
339                "determinants",
340                vec![
341                    ("defini", make_class(vec![make_entry("le")])),
342                    ("indefini", make_class(vec![make_entry("un")])),
343                    ("partitif", make_class(vec![make_entry("du")])),
344                    (
345                        "quantitatif",
346                        make_class(vec![
347                            make_entry_with_scope("tous", "universal"),
348                            make_entry_with_scope("aucun", "null"),
349                        ]),
350                    ),
351                ],
352            ),
353        );
354
355        taxonomies.insert(
356            "pronoms".to_string(),
357            make_taxonomy(
358                "pronoms",
359                vec![
360                    ("personnel", make_class(vec![make_entry("il")])),
361                    ("demonstratif", make_class(vec![make_entry("cela")])),
362                    ("relatif", make_class(vec![make_entry("qui")])),
363                    ("indefini", make_class(vec![make_entry("on")])),
364                ],
365            ),
366        );
367
368        let lex = Lexicon::from_taxonomies_for_test(taxonomies);
369        InferenceEngine::new(lex)
370    }
371
372    fn test_node(id: u32, nt: NodeType, origin: NodeOrigin) -> CausalNode {
373        CausalNode {
374            id: NodeId(id),
375            node_type: nt,
376            label: format!("node_{id}"),
377            source_span: SourceSpan::Synthetic,
378            scope: Scope::Unknown,
379            modifiers: SmallVec::new(),
380            temporal_ref: TemporalRef::Unresolved,
381            temporal_index: None,
382            origin,
383            attributes: NodeAttributes::default(),
384            parent: None,
385        }
386    }
387
388    fn test_node_with_entity(
389        id: u32,
390        nt: NodeType,
391        origin: NodeOrigin,
392        entity: &str,
393    ) -> CausalNode {
394        let mut n = test_node(id, nt, origin);
395        n.attributes.entity = Some(entity.to_string());
396        n
397    }
398
399    fn test_edge(
400        src: u32,
401        dst: u32,
402        rel: RelationType,
403        explicit: bool,
404        confidence: f32,
405    ) -> (NodeId, NodeId, CausalEdge) {
406        (
407            NodeId(src),
408            NodeId(dst),
409            CausalEdge {
410                relation: rel,
411                confidence,
412                temporal_gap: None,
413                explicit,
414                negated: false,
415                marker_token: None,
416                in_cycle: None,
417                provenance: None,
418                derivation: None,
419                joint_group_id: None,
420                third: None,
421            },
422        )
423    }
424
425    fn make_ir(nodes: Vec<CausalNode>, edges: Vec<(NodeId, NodeId, CausalEdge)>) -> CausalIR {
426        CausalIR {
427            source_lang: SourceLanguage::Natural {
428                lang: NaturalLanguage::French,
429            },
430            source_text: String::new(),
431            nodes,
432            edges,
433            cycles: vec![],
434            unresolved: vec![],
435            metadata: IrMetadata::default(),
436        }
437    }
438
439    // ── infer_node_type ──────────────────────────────────────────────────────
440
441    #[test]
442    fn infer_verb_processus() {
443        assert_eq!(
444            test_engine().infer_node_type("baisser", "VERB"),
445            Some(NodeType::Processus)
446        );
447    }
448
449    #[test]
450    fn infer_verb_action() {
451        assert_eq!(
452            test_engine().infer_node_type("faire", "VERB"),
453            Some(NodeType::Processus)
454        );
455    }
456
457    #[test]
458    fn infer_verb_etat() {
459        assert_eq!(
460            test_engine().infer_node_type("être", "VERB"),
461            Some(NodeType::EtatLocal)
462        );
463    }
464
465    #[test]
466    fn infer_verb_transition() {
467        assert_eq!(
468            test_engine().infer_node_type("chuter", "VERB"),
469            Some(NodeType::Processus)
470        );
471    }
472
473    #[test]
474    fn infer_auxiliaire_returns_none() {
475        // auxiliaire n'est pas un opérateur causal
476        assert_eq!(test_engine().infer_node_type("avoir", "VERB"), None);
477    }
478
479    #[test]
480    fn infer_noun_processus() {
481        assert_eq!(
482            test_engine().infer_node_type("croissance", "NOUN"),
483            Some(NodeType::Processus)
484        );
485    }
486
487    #[test]
488    fn infer_noun_agent_is_entite() {
489        assert_eq!(
490            test_engine().infer_node_type("agent", "NOUN"),
491            Some(NodeType::Entite)
492        );
493    }
494
495    #[test]
496    fn infer_noun_etat_systemique() {
497        assert_eq!(
498            test_engine().infer_node_type("crise", "NOUN"),
499            Some(NodeType::EtatGlobal)
500        );
501    }
502
503    #[test]
504    fn infer_unknown_lemma_returns_none() {
505        assert_eq!(test_engine().infer_node_type("zzz_inconnu", "VERB"), None);
506    }
507
508    // ── infer_scope ──────────────────────────────────────────────────────────
509
510    #[test]
511    fn infer_scope_det_defini() {
512        assert_eq!(
513            test_engine().infer_scope("le", "DET"),
514            Some(Scope::Specific)
515        );
516    }
517
518    #[test]
519    fn infer_scope_det_indefini() {
520        assert_eq!(
521            test_engine().infer_scope("un", "DET"),
522            Some(Scope::Existential)
523        );
524    }
525
526    #[test]
527    fn infer_scope_det_quantitatif_universal() {
528        // entry.scope == "universal" prend la priorité sur le fallback de classe
529        assert_eq!(
530            test_engine().infer_scope("tous", "DET"),
531            Some(Scope::Universal)
532        );
533    }
534
535    #[test]
536    fn infer_scope_det_quantitatif_null() {
537        assert_eq!(test_engine().infer_scope("aucun", "DET"), Some(Scope::Null));
538    }
539
540    #[test]
541    fn infer_scope_pron_personnel() {
542        assert_eq!(
543            test_engine().infer_scope("il", "PRON"),
544            Some(Scope::Specific)
545        );
546    }
547
548    #[test]
549    fn infer_scope_pron_indefini() {
550        assert_eq!(
551            test_engine().infer_scope("on", "PRON"),
552            Some(Scope::Unknown)
553        );
554    }
555
556    // ── score_confidence ─────────────────────────────────────────────────────
557
558    #[test]
559    fn score_explicit_action_etat_cause_clamps_to_1() {
560        // base 1.0 + bonus 0.15 = 1.15 → clamp → 1.0
561        assert_eq!(
562            test_engine().score_confidence(
563                NodeType::Processus,
564                NodeType::EtatLocal,
565                RelationType::Cause,
566                true
567            ),
568            1.0,
569        );
570    }
571
572    #[test]
573    fn score_implicit_action_etat_cause() {
574        // base 0.5 + bonus 0.15 = 0.65
575        let s = test_engine().score_confidence(
576            NodeType::Processus,
577            NodeType::EtatLocal,
578            RelationType::Cause,
579            false,
580        );
581        assert!((s - 0.65).abs() < 1e-6);
582    }
583
584    #[test]
585    fn score_implicit_concession_reduces_confidence() {
586        // base 0.5 − 0.10 = 0.40
587        let s = test_engine().score_confidence(
588            NodeType::EtatLocal,
589            NodeType::Processus,
590            RelationType::Concession,
591            false,
592        );
593        assert!((s - 0.40).abs() < 1e-6);
594    }
595
596    #[test]
597    fn score_never_below_min() {
598        let s = test_engine().score_confidence(
599            NodeType::Entite,
600            NodeType::Entite,
601            RelationType::Opposition,
602            false,
603        );
604        assert!(s >= 0.1);
605    }
606
607    // ── enrich ───────────────────────────────────────────────────────────────
608
609    #[test]
610    fn enrich_signals_causal_gap_on_concession() {
611        let e = test_engine();
612        let n1 = test_node(1, NodeType::Processus, NodeOrigin::Explicit);
613        let n2 = test_node(2, NodeType::EtatLocal, NodeOrigin::Explicit);
614        let mut ir = make_ir(
615            vec![n1, n2],
616            vec![test_edge(1, 2, RelationType::Concession, true, 1.0)],
617        );
618        let notes = e.enrich(&mut ir);
619        assert!(notes.iter().any(|n| matches!(
620            n,
621            InferenceNote::CausalGapSignaled {
622                relation: RelationType::Concession,
623                ..
624            }
625        )));
626    }
627
628    #[test]
629    fn enrich_resolves_inferred_node_type() {
630        let e = test_engine();
631        // Nœud Inferred de type Etat (incorrect), entity "croissance" → Processus
632        let n1 = test_node_with_entity(1, NodeType::EtatLocal, NodeOrigin::Inferred, "croissance");
633        let n2 = test_node(2, NodeType::Processus, NodeOrigin::Explicit);
634        let mut ir = make_ir(
635            vec![n1, n2],
636            vec![test_edge(1, 2, RelationType::Cause, true, 1.0)],
637        );
638        let notes = e.enrich(&mut ir);
639        assert!(notes.iter().any(|n| matches!(
640            n,
641            InferenceNote::NodeTypeResolved {
642                from: NodeType::EtatLocal,
643                to: NodeType::Processus,
644                ..
645            }
646        )));
647        assert_eq!(ir.nodes[0].node_type, NodeType::Processus);
648    }
649
650    #[test]
651    fn enrich_adjusts_confidence_for_implicit_edge() {
652        let e = test_engine();
653        let n1 = test_node(1, NodeType::Processus, NodeOrigin::Explicit);
654        let n2 = test_node(2, NodeType::EtatLocal, NodeOrigin::Explicit);
655        // arête implicite Action→Etat Cause, confiance initiale 0.5 → score 0.65
656        let mut ir = make_ir(
657            vec![n1, n2],
658            vec![test_edge(1, 2, RelationType::Cause, false, 0.5)],
659        );
660        let notes = e.enrich(&mut ir);
661        assert!(
662            notes
663                .iter()
664                .any(|n| matches!(n, InferenceNote::ConfidenceAdjusted { .. }))
665        );
666        let (_, _, ref updated) = ir.edges[0];
667        assert!((updated.confidence - 0.65).abs() < 1e-6);
668    }
669
670    #[test]
671    fn enrich_does_not_modify_explicit_nodes() {
672        let e = test_engine();
673        // Explicit même si entity connue → pas de modification
674        let n1 = test_node_with_entity(1, NodeType::EtatLocal, NodeOrigin::Explicit, "croissance");
675        let mut ir = make_ir(vec![n1], vec![]);
676        let notes = e.enrich(&mut ir);
677        assert!(
678            !notes
679                .iter()
680                .any(|n| matches!(n, InferenceNote::NodeTypeResolved { .. }))
681        );
682    }
683}