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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Linear-chain Conditional Random Fields (CRFs).
//!
//! Linear-chain CRFs are a special case of CRFs where the output variables form a chain.
//! This structure enables efficient inference and learning using dynamic programming.
//!
//! # Applications
//!
//! - Sequence labeling (POS tagging, NER, etc.)
//! - Speech recognition
//! - Bioinformatics (protein sequence analysis)
//!
//! # Algorithm
//!
//! Given input sequence x = (x₁, ..., xₙ) and output sequence y = (y₁, ..., yₙ):
//!
//! ```text
//! P(y|x) = (1/Z(x)) × exp(Σᵢ Σₖ λₖ fₖ(yᵢ₋₁, yᵢ, x, i))
//! ```
//!
//! Where:
//! - fₖ are feature functions
//! - λₖ are learned weights
//! - Z(x) is the partition function
//!
//! # References
//!
//! - Lafferty et al., "Conditional Random Fields: Probabilistic Models for Segmenting
//!   and Labeling Sequence Data" (2001)

use crate::{Factor, FactorGraph, PgmError, Result};
use scirs2_core::ndarray::{Array1, Array2};

/// Feature function for linear-chain CRF.
///
/// Features can be:
/// - Transition features: depend on (yᵢ₋₁, yᵢ, x, i)
/// - Emission features: depend on (yᵢ, x, i)
pub trait FeatureFunction: Send + Sync {
    /// Compute feature value for a transition.
    ///
    /// # Arguments
    /// * `prev_label` - Previous output label (None for first position)
    /// * `curr_label` - Current output label
    /// * `input_sequence` - Input sequence
    /// * `position` - Current position in sequence
    fn compute(
        &self,
        prev_label: Option<usize>,
        curr_label: usize,
        input_sequence: &[usize],
        position: usize,
    ) -> f64;

    /// Get feature name/description.
    fn name(&self) -> &str;
}

/// Linear-chain CRF for sequence labeling.
///
/// This specialized CRF structure enables efficient inference using
/// the forward-backward algorithm and Viterbi decoding.
pub struct LinearChainCRF {
    /// Number of states (labels)
    num_states: usize,
    /// Feature functions with their weights
    features: Vec<(Box<dyn FeatureFunction>, f64)>,
    /// Transition weights matrix: [from_state, to_state]
    transition_weights: Option<Array2<f64>>,
    /// Emission weights matrix: [state, observation]
    emission_weights: Option<Array2<f64>>,
}

impl LinearChainCRF {
    /// Create a new linear-chain CRF.
    pub fn new(num_states: usize) -> Self {
        Self {
            num_states,
            features: Vec::new(),
            transition_weights: None,
            emission_weights: None,
        }
    }

    /// Add a feature function with its weight.
    pub fn add_feature(&mut self, feature: Box<dyn FeatureFunction>, weight: f64) {
        self.features.push((feature, weight));
    }

    /// Set transition weights directly.
    ///
    /// This is useful when you have pre-trained weights.
    pub fn set_transition_weights(&mut self, weights: Array2<f64>) -> Result<()> {
        if weights.shape() != [self.num_states, self.num_states] {
            return Err(PgmError::DimensionMismatch {
                expected: vec![self.num_states, self.num_states],
                got: weights.shape().to_vec(),
            });
        }
        self.transition_weights = Some(weights);
        Ok(())
    }

    /// Set emission weights directly.
    pub fn set_emission_weights(&mut self, weights: Array2<f64>) -> Result<()> {
        if weights.shape()[0] != self.num_states {
            return Err(PgmError::DimensionMismatch {
                expected: vec![self.num_states, weights.shape()[1]],
                got: weights.shape().to_vec(),
            });
        }
        self.emission_weights = Some(weights);
        Ok(())
    }

    /// Compute feature scores for a sequence.
    fn compute_feature_scores(&self, input_sequence: &[usize], position: usize) -> Array2<f64> {
        let mut scores = Array2::zeros((self.num_states, self.num_states));

        // Transition features (from prev_state to curr_state)
        for prev_state in 0..self.num_states {
            for curr_state in 0..self.num_states {
                let mut score = 0.0;

                // Compute weighted feature sum
                for (feature, weight) in &self.features {
                    let feat_val =
                        feature.compute(Some(prev_state), curr_state, input_sequence, position);
                    score += weight * feat_val;
                }

                scores[[prev_state, curr_state]] = score;
            }
        }

        scores
    }

    /// Compute emission scores for a position.
    fn compute_emission_scores(&self, input_sequence: &[usize], position: usize) -> Array1<f64> {
        let mut scores = Array1::zeros(self.num_states);

        for state in 0..self.num_states {
            let mut score = 0.0;

            // Emission features
            for (feature, weight) in &self.features {
                let feat_val = feature.compute(None, state, input_sequence, position);
                score += weight * feat_val;
            }

            // Add pre-trained emission weights if available
            if let Some(ref emission_weights) = self.emission_weights {
                if position < input_sequence.len() {
                    let obs = input_sequence[position];
                    if obs < emission_weights.shape()[1] {
                        score += emission_weights[[state, obs]];
                    }
                }
            }

            scores[state] = score;
        }

        scores
    }

    /// Viterbi algorithm for finding the most likely label sequence.
    ///
    /// Returns the optimal label sequence and its score.
    pub fn viterbi(&self, input_sequence: &[usize]) -> Result<(Vec<usize>, f64)> {
        if input_sequence.is_empty() {
            return Err(PgmError::InvalidGraph("Empty input sequence".to_string()));
        }

        let seq_len = input_sequence.len();

        // Viterbi table: [position, state] -> max score
        let mut viterbi_table = Array2::zeros((seq_len, self.num_states));

        // Backpointer table: [position, state] -> previous state
        let mut backpointers = Array2::zeros((seq_len, self.num_states));

        // Initialize first position
        let emission_scores = self.compute_emission_scores(input_sequence, 0);
        for state in 0..self.num_states {
            viterbi_table[[0, state]] = emission_scores[state];
        }

        // Forward pass
        for t in 1..seq_len {
            let emission_scores = self.compute_emission_scores(input_sequence, t);
            let transition_scores = if let Some(ref weights) = self.transition_weights {
                weights.clone()
            } else {
                self.compute_feature_scores(input_sequence, t)
            };

            for curr_state in 0..self.num_states {
                let mut max_score = f64::NEG_INFINITY;
                let mut best_prev_state = 0;

                for prev_state in 0..self.num_states {
                    let score = viterbi_table[[t - 1, prev_state]]
                        + transition_scores[[prev_state, curr_state]]
                        + emission_scores[curr_state];

                    if score > max_score {
                        max_score = score;
                        best_prev_state = prev_state;
                    }
                }

                viterbi_table[[t, curr_state]] = max_score;
                backpointers[[t, curr_state]] = best_prev_state as f64;
            }
        }

        // Find best final state
        let mut best_final_state = 0;
        let mut best_final_score = f64::NEG_INFINITY;
        for state in 0..self.num_states {
            let score = viterbi_table[[seq_len - 1, state]];
            if score > best_final_score {
                best_final_score = score;
                best_final_state = state;
            }
        }

        // Backward pass to reconstruct path
        let mut path = vec![0; seq_len];
        path[seq_len - 1] = best_final_state;

        for t in (1..seq_len).rev() {
            path[t - 1] = backpointers[[t, path[t]]] as usize;
        }

        Ok((path, best_final_score))
    }

    /// Forward algorithm for computing marginal probabilities.
    ///
    /// Returns forward probabilities: α[t, s] = P(y₁...yₜ = s, x₁...xₜ)
    pub fn forward(&self, input_sequence: &[usize]) -> Result<Array2<f64>> {
        if input_sequence.is_empty() {
            return Err(PgmError::InvalidGraph("Empty input sequence".to_string()));
        }

        let seq_len = input_sequence.len();
        let mut alpha = Array2::zeros((seq_len, self.num_states));

        // Initialize first position
        let emission_scores = self.compute_emission_scores(input_sequence, 0);
        for state in 0..self.num_states {
            alpha[[0, state]] = emission_scores[state].exp();
        }

        // Normalize initial position
        let init_sum: f64 = alpha.row(0).sum();
        if init_sum > 0.0 {
            for state in 0..self.num_states {
                alpha[[0, state]] /= init_sum;
            }
        }

        // Forward pass
        for t in 1..seq_len {
            let emission_scores = self.compute_emission_scores(input_sequence, t);
            let transition_scores = if let Some(ref weights) = self.transition_weights {
                weights.clone()
            } else {
                self.compute_feature_scores(input_sequence, t)
            };

            for curr_state in 0..self.num_states {
                let mut sum = 0.0;

                for prev_state in 0..self.num_states {
                    sum += alpha[[t - 1, prev_state]]
                        * (transition_scores[[prev_state, curr_state]]
                            + emission_scores[curr_state])
                            .exp();
                }

                alpha[[t, curr_state]] = sum;
            }

            // Normalize to prevent underflow
            let row_sum: f64 = alpha.row(t).sum();
            if row_sum > 0.0 {
                for state in 0..self.num_states {
                    alpha[[t, state]] /= row_sum;
                }
            }
        }

        Ok(alpha)
    }

    /// Backward algorithm for computing marginal probabilities.
    ///
    /// Returns backward probabilities: β[t, s] = P(yₜ₊₁...yₙ | yₜ = s, xₜ₊₁...xₙ)
    pub fn backward(&self, input_sequence: &[usize]) -> Result<Array2<f64>> {
        if input_sequence.is_empty() {
            return Err(PgmError::InvalidGraph("Empty input sequence".to_string()));
        }

        let seq_len = input_sequence.len();
        let mut beta = Array2::zeros((seq_len, self.num_states));

        // Initialize last position
        for state in 0..self.num_states {
            beta[[seq_len - 1, state]] = 1.0;
        }

        // Backward pass
        for t in (0..seq_len - 1).rev() {
            let emission_scores = self.compute_emission_scores(input_sequence, t + 1);
            let transition_scores = if let Some(ref weights) = self.transition_weights {
                weights.clone()
            } else {
                self.compute_feature_scores(input_sequence, t + 1)
            };

            for curr_state in 0..self.num_states {
                let mut sum = 0.0;

                for next_state in 0..self.num_states {
                    sum += beta[[t + 1, next_state]]
                        * (transition_scores[[curr_state, next_state]]
                            + emission_scores[next_state])
                            .exp();
                }

                beta[[t, curr_state]] = sum;
            }

            // Normalize to prevent overflow
            let row_sum: f64 = beta.row(t).sum();
            if row_sum > 0.0 {
                for state in 0..self.num_states {
                    beta[[t, state]] /= row_sum;
                }
            }
        }

        Ok(beta)
    }

    /// Compute marginal probabilities for each position.
    ///
    /// Returns: P(yₜ = s | x) for all t and s
    pub fn marginals(&self, input_sequence: &[usize]) -> Result<Array2<f64>> {
        let alpha = self.forward(input_sequence)?;
        let beta = self.backward(input_sequence)?;

        let seq_len = input_sequence.len();
        let mut marginals = Array2::zeros((seq_len, self.num_states));

        for t in 0..seq_len {
            for state in 0..self.num_states {
                marginals[[t, state]] = alpha[[t, state]] * beta[[t, state]];
            }

            // Normalize
            let row_sum: f64 = marginals.row(t).sum();
            if row_sum > 0.0 {
                for state in 0..self.num_states {
                    marginals[[t, state]] /= row_sum;
                }
            }
        }

        Ok(marginals)
    }

    /// Convert to factor graph representation.
    pub fn to_factor_graph(&self, input_sequence: &[usize]) -> Result<FactorGraph> {
        let mut graph = FactorGraph::new();
        let seq_len = input_sequence.len();

        // Add variables for each position
        for t in 0..seq_len {
            graph.add_variable_with_card(format!("y_{}", t), "Label".to_string(), self.num_states);
        }

        // Add emission factors
        for t in 0..seq_len {
            let emission_scores = self.compute_emission_scores(input_sequence, t);
            let emission_potentials = emission_scores.mapv(|x| x.exp());

            let factor = Factor::new(
                format!("emission_{}", t),
                vec![format!("y_{}", t)],
                emission_potentials.into_dyn(),
            )?;

            graph.add_factor(factor)?;
        }

        // Add transition factors
        for t in 1..seq_len {
            let transition_scores = if let Some(ref weights) = self.transition_weights {
                weights.clone()
            } else {
                self.compute_feature_scores(input_sequence, t)
            };

            let transition_potentials = transition_scores.mapv(|x| x.exp());

            let factor = Factor::new(
                format!("transition_{}", t),
                vec![format!("y_{}", t - 1), format!("y_{}", t)],
                transition_potentials.into_dyn(),
            )?;

            graph.add_factor(factor)?;
        }

        Ok(graph)
    }
}

/// Simple identity feature: always returns 1.0
pub struct IdentityFeature {
    name: String,
}

impl IdentityFeature {
    pub fn new(name: String) -> Self {
        Self { name }
    }
}

impl FeatureFunction for IdentityFeature {
    fn compute(
        &self,
        _prev_label: Option<usize>,
        _curr_label: usize,
        _input_sequence: &[usize],
        _position: usize,
    ) -> f64 {
        1.0
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Transition feature: fires when transitioning from one state to another.
pub struct TransitionFeature {
    from_state: usize,
    to_state: usize,
    name: String,
}

impl TransitionFeature {
    pub fn new(from_state: usize, to_state: usize) -> Self {
        Self {
            from_state,
            to_state,
            name: format!("transition_{}_{}", from_state, to_state),
        }
    }
}

impl FeatureFunction for TransitionFeature {
    fn compute(
        &self,
        prev_label: Option<usize>,
        curr_label: usize,
        _input_sequence: &[usize],
        _position: usize,
    ) -> f64 {
        if let Some(prev) = prev_label {
            if prev == self.from_state && curr_label == self.to_state {
                return 1.0;
            }
        }
        0.0
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Emission feature: fires when a specific label is paired with a specific observation.
pub struct EmissionFeature {
    state: usize,
    observation: usize,
    name: String,
}

impl EmissionFeature {
    pub fn new(state: usize, observation: usize) -> Self {
        Self {
            state,
            observation,
            name: format!("emission_{}_{}", state, observation),
        }
    }
}

impl FeatureFunction for EmissionFeature {
    fn compute(
        &self,
        _prev_label: Option<usize>,
        curr_label: usize,
        input_sequence: &[usize],
        position: usize,
    ) -> f64 {
        if curr_label == self.state
            && position < input_sequence.len()
            && input_sequence[position] == self.observation
        {
            return 1.0;
        }
        0.0
    }

    fn name(&self) -> &str {
        &self.name
    }
}

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

    #[test]
    fn test_linear_chain_crf_creation() {
        let crf = LinearChainCRF::new(3);
        assert_eq!(crf.num_states, 3);
        assert_eq!(crf.features.len(), 0);
    }

    #[test]
    fn test_add_feature() {
        let mut crf = LinearChainCRF::new(2);
        let feature = Box::new(IdentityFeature::new("test".to_string()));
        crf.add_feature(feature, 1.0);
        assert_eq!(crf.features.len(), 1);
    }

    #[test]
    fn test_viterbi_simple() {
        let mut crf = LinearChainCRF::new(2);

        // Set simple transition weights favoring 0->0 and 1->1
        let transition_weights = Array::from_shape_vec(
            vec![2, 2],
            vec![1.0, -1.0, -1.0, 1.0], // Prefer staying in same state
        )
        .expect("unwrap")
        .into_dimensionality::<scirs2_core::ndarray::Ix2>()
        .expect("unwrap");
        crf.set_transition_weights(transition_weights)
            .expect("unwrap");

        // Simple input sequence
        let input_sequence = vec![0, 0, 0];

        // Run Viterbi
        let (path, _score) = crf.viterbi(&input_sequence).expect("unwrap");

        assert_eq!(path.len(), 3);
        // With positive weights on diagonal, should prefer staying in state 0
    }

    #[test]
    fn test_forward_backward() {
        let mut crf = LinearChainCRF::new(2);

        // Set uniform transition weights
        let transition_weights = Array::from_shape_vec(vec![2, 2], vec![0.0, 0.0, 0.0, 0.0])
            .expect("unwrap")
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .expect("unwrap");
        crf.set_transition_weights(transition_weights)
            .expect("unwrap");

        let input_sequence = vec![0, 1];

        // Run forward
        let alpha = crf.forward(&input_sequence).expect("unwrap");
        assert_eq!(alpha.shape(), &[2, 2]);

        // Run backward
        let beta = crf.backward(&input_sequence).expect("unwrap");
        assert_eq!(beta.shape(), &[2, 2]);

        // Check normalization
        for t in 0..2 {
            let sum: f64 = alpha.row(t).sum();
            assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);
        }
    }

    #[test]
    fn test_marginals() {
        let mut crf = LinearChainCRF::new(2);

        let transition_weights = Array::from_shape_vec(vec![2, 2], vec![0.0, 0.0, 0.0, 0.0])
            .expect("unwrap")
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .expect("unwrap");
        crf.set_transition_weights(transition_weights)
            .expect("unwrap");

        let input_sequence = vec![0, 1];

        let marginals = crf.marginals(&input_sequence).expect("unwrap");

        assert_eq!(marginals.shape(), &[2, 2]);

        // Each row should sum to 1
        for t in 0..2 {
            let sum: f64 = marginals.row(t).sum();
            assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);
        }
    }

    #[test]
    fn test_transition_feature() {
        let feature = TransitionFeature::new(0, 1);

        // Should fire when transitioning from 0 to 1
        let val = feature.compute(Some(0), 1, &[0, 1], 1);
        assert_abs_diff_eq!(val, 1.0, epsilon = 1e-10);

        // Should not fire for other transitions
        let val = feature.compute(Some(0), 0, &[0, 1], 1);
        assert_abs_diff_eq!(val, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_emission_feature() {
        let feature = EmissionFeature::new(0, 5);

        // Should fire when state=0 and observation=5
        let val = feature.compute(None, 0, &[5, 3], 0);
        assert_abs_diff_eq!(val, 1.0, epsilon = 1e-10);

        // Should not fire for different observation
        let val = feature.compute(None, 0, &[3, 5], 0);
        assert_abs_diff_eq!(val, 0.0, epsilon = 1e-10);

        // Should not fire for different state
        let val = feature.compute(None, 1, &[5, 3], 0);
        assert_abs_diff_eq!(val, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_to_factor_graph() {
        let mut crf = LinearChainCRF::new(2);

        let transition_weights = Array::from_shape_vec(vec![2, 2], vec![0.5, 0.5, 0.5, 0.5])
            .expect("unwrap")
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .expect("unwrap");
        crf.set_transition_weights(transition_weights)
            .expect("unwrap");

        let input_sequence = vec![0, 1, 0];

        let graph = crf.to_factor_graph(&input_sequence).expect("unwrap");

        // Should have 3 variables (one per position)
        assert_eq!(graph.num_variables(), 3);

        // Should have 3 emission factors + 2 transition factors = 5 total
        assert_eq!(graph.num_factors(), 5);
    }
}