Skip to main content

gcn_knowledge/
inference.rs

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