clm_rust_core/layer1/
matrix.rs1use super::types::PetriNet;
5pub use crate::cpn::solver::{math_gcd, math_lcm, solve_nullspace};
6
7#[derive(Debug, Clone, PartialEq)]
9pub struct IncidenceMatrix {
10 pub place_names: Vec<String>,
11 pub transition_names: Vec<String>,
12 pub d: Vec<Vec<i64>>,
14}
15
16impl IncidenceMatrix {
17 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 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 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 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 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}