tensorlogic-quantrs-hooks 0.1.0

Probabilistic graphical model and message-passing interoperability for QuantRS2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Variable Elimination algorithm for exact inference.
//!
//! Variable Elimination is a classic exact inference algorithm that eliminates
//! variables one by one from the factor graph. The complexity depends on the
//! elimination order.

use scirs2_core::ndarray::ArrayD;
use std::collections::{HashMap, HashSet};

use crate::error::{PgmError, Result};
use crate::factor::Factor;
use crate::graph::FactorGraph;

/// Variable elimination algorithm for exact inference.
///
/// Computes marginal probabilities by eliminating variables in a specific order.
pub struct VariableElimination {
    /// Elimination order (if None, uses min-degree heuristic)
    pub elimination_order: Option<Vec<String>>,
}

impl Default for VariableElimination {
    fn default() -> Self {
        Self::new()
    }
}

impl VariableElimination {
    /// Create a new variable elimination algorithm.
    pub fn new() -> Self {
        Self {
            elimination_order: None,
        }
    }

    /// Create with a specific elimination order.
    pub fn with_order(order: Vec<String>) -> Self {
        Self {
            elimination_order: Some(order),
        }
    }

    /// Compute marginal for a single query variable.
    pub fn marginalize(&self, graph: &FactorGraph, query_var: &str) -> Result<ArrayD<f64>> {
        // Check if query variable exists
        let query_node = graph
            .get_variable(query_var)
            .ok_or_else(|| PgmError::VariableNotFound(query_var.to_string()))?;

        // Get all factors as a working set
        let mut factors: Vec<Factor> = graph
            .factor_ids()
            .filter_map(|id| graph.get_factor(id).cloned())
            .collect();

        // If no factors, return uniform distribution
        if factors.is_empty() {
            let uniform = ArrayD::from_elem(
                vec![query_node.cardinality],
                1.0 / query_node.cardinality as f64,
            );
            return Ok(uniform);
        }

        // Determine elimination order
        let all_vars: HashSet<String> = graph.variable_names().cloned().collect();
        let vars_to_eliminate: Vec<String> =
            all_vars.into_iter().filter(|v| v != query_var).collect();

        let order = if let Some(ref custom_order) = self.elimination_order {
            custom_order
                .iter()
                .filter(|v| vars_to_eliminate.contains(v))
                .cloned()
                .collect()
        } else {
            self.compute_elimination_order(graph, &vars_to_eliminate)?
        };

        // Eliminate variables one by one
        for var in &order {
            factors = self.eliminate_variable(&factors, var)?;
        }

        // Multiply remaining factors and marginalize to query variable
        let mut result = self.multiply_all_factors(&factors)?;

        // If result contains more than just the query variable, marginalize others
        let vars_to_remove: Vec<String> = result
            .variables
            .iter()
            .filter(|v| *v != query_var)
            .cloned()
            .collect();

        for var in vars_to_remove {
            result = result.marginalize_out(&var)?;
        }

        // Normalize
        result.normalize();

        Ok(result.values)
    }

    /// Compute marginals for all variables.
    pub fn marginalize_all(&self, graph: &FactorGraph) -> Result<HashMap<String, ArrayD<f64>>> {
        let mut marginals = HashMap::new();

        for var_name in graph.variable_names() {
            let marginal = self.marginalize(graph, var_name)?;
            marginals.insert(var_name.clone(), marginal);
        }

        Ok(marginals)
    }

    /// Eliminate a single variable from a set of factors.
    fn eliminate_variable(&self, factors: &[Factor], var: &str) -> Result<Vec<Factor>> {
        // Find all factors containing this variable
        let (containing, not_containing): (Vec<Factor>, Vec<Factor>) = factors
            .iter()
            .cloned()
            .partition(|f| f.variables.contains(&var.to_string()));

        if containing.is_empty() {
            // Variable not in any factor, nothing to eliminate
            return Ok(factors.to_vec());
        }

        // Multiply all factors containing the variable
        let mut product = containing[0].clone();
        for factor in &containing[1..] {
            product = product.product(factor)?;
        }

        // Marginalize out the variable
        let marginalized = product.marginalize_out(var)?;

        // Combine with factors that didn't contain the variable
        let mut result = not_containing;
        if !marginalized.variables.is_empty() {
            result.push(marginalized);
        }

        Ok(result)
    }

    /// Multiply all factors together.
    fn multiply_all_factors(&self, factors: &[Factor]) -> Result<Factor> {
        if factors.is_empty() {
            return Err(PgmError::InvalidGraph("No factors to multiply".to_string()));
        }

        let mut result = factors[0].clone();
        for factor in &factors[1..] {
            result = result.product(factor)?;
        }

        Ok(result)
    }

    /// Compute elimination order using min-degree heuristic.
    ///
    /// Chooses variables in order of fewest connections (smallest induced clique size).
    fn compute_elimination_order(
        &self,
        graph: &FactorGraph,
        vars: &[String],
    ) -> Result<Vec<String>> {
        // Simple heuristic: eliminate variables in the order they appear
        // More sophisticated: use min-degree, min-fill, or max-cardinality search
        let mut order = vars.to_vec();

        // Sort by number of factors containing each variable
        order.sort_by_key(|v| {
            graph
                .get_adjacent_factors(v)
                .map(|factors| factors.len())
                .unwrap_or(0)
        });

        Ok(order)
    }

    /// Compute joint probability for a specific assignment.
    pub fn joint_probability(
        &self,
        graph: &FactorGraph,
        assignment: &HashMap<String, usize>,
    ) -> Result<f64> {
        let mut prob = 1.0;

        for factor_id in graph.factor_ids() {
            if let Some(factor) = graph.get_factor(factor_id) {
                // Build index for this factor
                let mut indices = Vec::new();
                for var in &factor.variables {
                    if let Some(&value) = assignment.get(var) {
                        indices.push(value);
                    } else {
                        return Err(PgmError::VariableNotFound(var.clone()));
                    }
                }

                prob *= factor.values[indices.as_slice()];
            }
        }

        Ok(prob)
    }

    /// Compute MAP (Maximum A Posteriori) assignment using variable elimination.
    pub fn map(&self, graph: &FactorGraph) -> Result<HashMap<String, usize>> {
        // Get all factors
        let mut factors: Vec<Factor> = graph
            .factor_ids()
            .filter_map(|id| graph.get_factor(id).cloned())
            .collect();

        // Get elimination order (all variables)
        let all_vars: Vec<String> = graph.variable_names().cloned().collect();
        let order = if let Some(ref custom_order) = self.elimination_order {
            custom_order.clone()
        } else {
            self.compute_elimination_order(graph, &all_vars)?
        };

        let mut assignment = HashMap::new();

        // Eliminate variables using MAX instead of SUM
        for var in order.iter().rev() {
            // Find factors containing this variable
            let (containing, not_containing): (Vec<Factor>, Vec<Factor>) = factors
                .iter()
                .cloned()
                .partition(|f| f.variables.contains(&var.to_string()));

            if containing.is_empty() {
                continue;
            }

            // Multiply factors
            let mut product = containing[0].clone();
            for factor in &containing[1..] {
                product = product.product(factor)?;
            }

            // Find max value for this variable
            let var_node = graph
                .get_variable(var)
                .ok_or_else(|| PgmError::VariableNotFound(var.clone()))?;

            let mut max_val = f64::NEG_INFINITY;
            let mut max_idx = 0;

            for val in 0..var_node.cardinality {
                let reduced = product.reduce(var, val)?;
                let prob: f64 = reduced.values.iter().product();

                if prob > max_val {
                    max_val = prob;
                    max_idx = val;
                }
            }

            assignment.insert(var.clone(), max_idx);

            // Reduce factor to this assignment
            let reduced = product.reduce(var, max_idx)?;
            factors = not_containing;
            if !reduced.variables.is_empty() {
                factors.push(reduced);
            }
        }

        Ok(assignment)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::Array;

    #[test]
    fn test_variable_elimination_single_variable() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);

        // Add uniform factor
        let factor = Factor::uniform("P(x)".to_string(), vec!["x".to_string()], 2);
        graph.add_factor(factor).expect("unwrap");

        let ve = VariableElimination::new();
        let marginal = ve.marginalize(&graph, "x").expect("unwrap");

        assert_eq!(marginal.len(), 2);
        let sum: f64 = marginal.iter().sum();
        assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);
    }

    #[test]
    fn test_variable_elimination_chain() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("y".to_string(), "Binary".to_string(), 2);

        // P(x)
        let px_values = Array::from_shape_vec(vec![2], vec![0.6, 0.4])
            .expect("unwrap")
            .into_dyn();
        let px = Factor::new("P(x)".to_string(), vec!["x".to_string()], px_values).expect("unwrap");
        graph.add_factor(px).expect("unwrap");

        // P(y|x)
        let pyx_values = Array::from_shape_vec(vec![2, 2], vec![0.9, 0.1, 0.2, 0.8])
            .expect("unwrap")
            .into_dyn();
        let pyx = Factor::new(
            "P(y|x)".to_string(),
            vec!["x".to_string(), "y".to_string()],
            pyx_values,
        )
        .expect("unwrap");
        graph.add_factor(pyx).expect("unwrap");

        let ve = VariableElimination::new();
        let marginal_y = ve.marginalize(&graph, "y").expect("unwrap");

        assert_eq!(marginal_y.len(), 2);
        let sum: f64 = marginal_y.iter().sum();
        assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);
    }

    #[test]
    fn test_marginalize_all() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("y".to_string(), "Binary".to_string(), 2);

        let ve = VariableElimination::new();
        let marginals = ve.marginalize_all(&graph).expect("unwrap");

        assert_eq!(marginals.len(), 2);
        assert!(marginals.contains_key("x"));
        assert!(marginals.contains_key("y"));
    }

    #[test]
    fn test_joint_probability() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("y".to_string(), "Binary".to_string(), 2);

        // Add factors
        let px_values = Array::from_shape_vec(vec![2], vec![0.6, 0.4])
            .expect("unwrap")
            .into_dyn();
        let px = Factor::new("P(x)".to_string(), vec!["x".to_string()], px_values).expect("unwrap");
        graph.add_factor(px).expect("unwrap");

        let pyx_values = Array::from_shape_vec(vec![2, 2], vec![0.9, 0.1, 0.2, 0.8])
            .expect("unwrap")
            .into_dyn();
        let pyx = Factor::new(
            "P(y|x)".to_string(),
            vec!["x".to_string(), "y".to_string()],
            pyx_values,
        )
        .expect("unwrap");
        graph.add_factor(pyx).expect("unwrap");

        let mut assignment = HashMap::new();
        assignment.insert("x".to_string(), 0);
        assignment.insert("y".to_string(), 1);

        let ve = VariableElimination::new();
        let prob = ve.joint_probability(&graph, &assignment).expect("unwrap");

        // P(x=0, y=1) = P(x=0) * P(y=1|x=0) = 0.6 * 0.1 = 0.06
        assert_abs_diff_eq!(prob, 0.06, epsilon = 1e-6);
    }

    #[test]
    fn test_custom_elimination_order() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("y".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("z".to_string(), "Binary".to_string(), 2);

        let order = vec!["x".to_string(), "y".to_string()];
        let ve = VariableElimination::with_order(order);

        let marginal = ve.marginalize(&graph, "z").expect("unwrap");
        assert_eq!(marginal.len(), 2);
    }

    #[test]
    fn test_map_inference() {
        let mut graph = FactorGraph::new();
        graph.add_variable_with_card("x".to_string(), "Binary".to_string(), 2);
        graph.add_variable_with_card("y".to_string(), "Binary".to_string(), 2);

        // Add biased factors
        let px_values = Array::from_shape_vec(vec![2], vec![0.3, 0.7])
            .expect("unwrap")
            .into_dyn();
        let px = Factor::new("P(x)".to_string(), vec!["x".to_string()], px_values).expect("unwrap");
        graph.add_factor(px).expect("unwrap");

        let pyx_values = Array::from_shape_vec(vec![2, 2], vec![0.8, 0.2, 0.1, 0.9])
            .expect("unwrap")
            .into_dyn();
        let pyx = Factor::new(
            "P(y|x)".to_string(),
            vec!["x".to_string(), "y".to_string()],
            pyx_values,
        )
        .expect("unwrap");
        graph.add_factor(pyx).expect("unwrap");

        let ve = VariableElimination::new();
        let map_assignment = ve.map(&graph).expect("unwrap");

        assert!(map_assignment.contains_key("x"));
        assert!(map_assignment.contains_key("y"));
    }
}