clm-kernel 0.0.21

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1: CPN Incidence Matrix & P-Invariant Nullspace Analysis
//! Canonical Path: kernel/clm_rust_core/src/layer1/matrix.rs

use super::types::PetriNet;
pub use crate::cpn::solver::{math_gcd, math_lcm, solve_nullspace};

/// Incidence Matrix representation D = D^+ - D^-
#[derive(Debug, Clone, PartialEq)]
pub struct IncidenceMatrix {
    pub place_names: Vec<String>,
    pub transition_names: Vec<String>,
    /// Matrix rows correspond to places, columns correspond to transitions: D[place][transition]
    pub d: Vec<Vec<i64>>,
}

impl IncidenceMatrix {
    /// Builds incidence matrix from a PetriNet topology.
    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() {
            // Inputs consume tokens: -1 per input occurrence
            for inp in &t.inputs {
                if let Some(p_idx) = place_names.iter().position(|p| p == inp) {
                    d[p_idx][t_idx] -= 1;
                }
            }
            // Outputs produce tokens: +1 per output occurrence
            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,
        }
    }

    /// Computes P-invariants x such that x^T * D = 0^T.
    pub fn p_invariants(&self) -> Vec<Vec<i64>> {
        solve_nullspace(&self.d, self.place_names.len(), self.transition_names.len(), true)
    }

    /// Verifies if a given weight vector x satisfies x^T * D = 0^T.
    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
    }
}