Skip to main content

clm_rust_core/layer1/
matrix.rs

1//! Layer 1: CPN Incidence Matrix & P-Invariant Nullspace Analysis
2//! Canonical Path: kernel/clm_rust_core/src/layer1/matrix.rs
3
4use super::types::PetriNet;
5pub use crate::cpn::solver::{math_gcd, math_lcm, solve_nullspace};
6
7/// Incidence Matrix representation D = D^+ - D^-
8#[derive(Debug, Clone, PartialEq)]
9pub struct IncidenceMatrix {
10    pub place_names: Vec<String>,
11    pub transition_names: Vec<String>,
12    /// Matrix rows correspond to places, columns correspond to transitions: D[place][transition]
13    pub d: Vec<Vec<i64>>,
14}
15
16impl IncidenceMatrix {
17    /// Builds incidence matrix from a PetriNet topology.
18    pub fn from_net(net: &PetriNet) -> Self {
19        let place_names: Vec<String> = net.places.iter().map(|p| p.id.clone()).collect();
20        let transition_names: Vec<String> = net.transitions.iter().map(|t| t.id.clone()).collect();
21
22        let num_places = place_names.len();
23        let num_trans = transition_names.len();
24        let mut d = vec![vec![0i64; num_trans]; num_places];
25
26        for (t_idx, t) in net.transitions.iter().enumerate() {
27            // Inputs consume tokens: -1 per input occurrence
28            for inp in &t.inputs {
29                if let Some(p_idx) = place_names.iter().position(|p| p == inp) {
30                    d[p_idx][t_idx] -= 1;
31                }
32            }
33            // Outputs produce tokens: +1 per output occurrence
34            for out in &t.outputs {
35                if let Some(p_idx) = place_names.iter().position(|p| p == out) {
36                    d[p_idx][t_idx] += 1;
37                }
38            }
39        }
40
41        Self {
42            place_names,
43            transition_names,
44            d,
45        }
46    }
47
48    /// Computes P-invariants x such that x^T * D = 0^T.
49    pub fn p_invariants(&self) -> Vec<Vec<i64>> {
50        solve_nullspace(&self.d, self.place_names.len(), self.transition_names.len(), true)
51    }
52
53    /// Verifies if a given weight vector x satisfies x^T * D = 0^T.
54    pub fn verify_invariant(&self, weights: &[i64]) -> bool {
55        if weights.len() != self.place_names.len() {
56            return false;
57        }
58        for t in 0..self.transition_names.len() {
59            let mut sum = 0i64;
60            for p in 0..self.place_names.len() {
61                sum += weights[p] * self.d[p][t];
62            }
63            if sum != 0 {
64                return false;
65            }
66        }
67        true
68    }
69}