use super::types::PetriNet;
pub use crate::cpn::solver::{math_gcd, math_lcm, solve_nullspace};
#[derive(Debug, Clone, PartialEq)]
pub struct IncidenceMatrix {
pub place_names: Vec<String>,
pub transition_names: Vec<String>,
pub d: Vec<Vec<i64>>,
}
impl IncidenceMatrix {
pub fn from_net(net: &PetriNet) -> Self {
let place_names: Vec<String> = net.places.iter().map(|p| p.id.clone()).collect();
let transition_names: Vec<String> = net.transitions.iter().map(|t| t.id.clone()).collect();
let num_places = place_names.len();
let num_trans = transition_names.len();
let mut d = vec![vec![0i64; num_trans]; num_places];
for (t_idx, t) in net.transitions.iter().enumerate() {
for inp in &t.inputs {
if let Some(p_idx) = place_names.iter().position(|p| p == inp) {
d[p_idx][t_idx] -= 1;
}
}
for out in &t.outputs {
if let Some(p_idx) = place_names.iter().position(|p| p == out) {
d[p_idx][t_idx] += 1;
}
}
}
Self {
place_names,
transition_names,
d,
}
}
pub fn p_invariants(&self) -> Vec<Vec<i64>> {
solve_nullspace(&self.d, self.place_names.len(), self.transition_names.len(), true)
}
pub fn verify_invariant(&self, weights: &[i64]) -> bool {
if weights.len() != self.place_names.len() {
return false;
}
for t in 0..self.transition_names.len() {
let mut sum = 0i64;
for p in 0..self.place_names.len() {
sum += weights[p] * self.d[p][t];
}
if sum != 0 {
return false;
}
}
true
}
}