Skip to main content

gcn_knowledge/
inference.rs

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