clm-kernel 0.0.19

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Open Monoidal Petri Net Composition Algebra (EPIC-CLC, CLC-01 / CLC-02).
//!
//! Implements symmetric monoidal categories (OpenPetri, \otimes, I) where nets
//! have input and output boundary interfaces, composed via safe cospan pushout gluing.
//!
//! Invariant: INV-CLC-03 (Open Monoidal Net Compositionality).

use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::open_petri_pullback::{compose_marked_open_petri_nets, BoundaryGlueSpec, BoundaryMarkingPullbackError};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BoundaryInterface {
    pub input_places: Vec<String>,
    pub output_places: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenPlace {
    pub id: String,
    pub initial_tokens: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenTransition {
    pub id: String,
    pub inputs: Vec<String>,
    pub outputs: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_arcs: Option<Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenPetriNet {
    pub name: String,
    pub places: Vec<OpenPlace>,
    pub transitions: Vec<OpenTransition>,
    pub inputs: Vec<String>,
    pub outputs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CospanCompositionResult {
    pub composite: OpenPetriNet,
    pub glued_place_map: BTreeMap<String, String>,
}

pub fn compose_open_petri_nets(
    net1: &OpenPetriNet,
    net2: &OpenPetriNet,
    boundary_map: Option<&BoundaryGlueSpec>,
) -> Result<CospanCompositionResult, BoundaryMarkingPullbackError> {
    compose_marked_open_petri_nets(net1, net2, boundary_map, false)
}

pub fn verify_composite_p_invariant(net: &OpenPetriNet, weights: &[f64]) -> bool {
    if weights.len() != net.places.len() {
        return false;
    }

    let place_index: HashMap<&str, usize> = net
        .places
        .iter()
        .enumerate()
        .map(|(idx, p)| (p.id.as_str(), idx))
        .collect();

    for tr in &net.transitions {
        let mut delta = 0.0;
        for inp in &tr.inputs {
            let idx = match place_index.get(inp.as_str()) {
                Some(&i) => i,
                None => return false,
            };
            delta -= weights[idx];
        }
        for out in &tr.outputs {
            let idx = match place_index.get(out.as_str()) {
                Some(&i) => i,
                None => return false,
            };
            delta += weights[idx];
        }
        if delta.abs() > 1e-9 {
            return false;
        }
    }

    true
}

pub fn to_petri_net_topology(open_net: &OpenPetriNet) -> Value {
    serde_json::json!({
        "name": open_net.name,
        "places": open_net.places.iter().map(|p| {
            serde_json::json!({
                "id": p.id,
                "initialTokens": p.initial_tokens
            })
        }).collect::<Vec<_>>(),
        "transitions": open_net.transitions.iter().map(|t| {
            serde_json::json!({
                "id": t.id,
                "inputs": t.inputs,
                "outputs": t.outputs
            })
        }).collect::<Vec<_>>()
    })
}