Prohibiting set

This commit is contained in:
elvis
2025-08-27 23:58:43 +02:00
parent 8b0fbcee00
commit a0f4297774
12 changed files with 291 additions and 77 deletions

View File

@ -1,6 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use super::super::{translator, graph, set, process, system, label}; use super::super::{translator, graph, set, process, system, label, element};
use super::super::set::BasicSet; use super::super::set::BasicSet;
/// If changing IntegerType in assert.rs, also change from Num to another /// If changing IntegerType in assert.rs, also change from Num to another
@ -54,7 +54,7 @@ pub enum Expression<S> {
Integer(IntegerType), Integer(IntegerType),
Label(Box<label::Label>), Label(Box<label::Label>),
Set(set::Set), Set(set::Set),
Element(translator::IdType), Element(element::IdType),
String(String), String(String),
Var(Variable<S>), Var(Variable<S>),
@ -176,7 +176,7 @@ pub enum AssertReturnValue {
String(String), String(String),
Label(label::Label), Label(label::Label),
Set(set::Set), Set(set::Set),
Element(translator::IdType), Element(element::IdType),
Node(petgraph::graph::NodeIndex), Node(petgraph::graph::NodeIndex),
Edge(petgraph::graph::EdgeIndex), Edge(petgraph::graph::EdgeIndex),
Neighbours(petgraph::graph::NodeIndex), Neighbours(petgraph::graph::NodeIndex),

View File

@ -7,7 +7,8 @@ use super::choices::Choices;
use super::process::Process; use super::process::Process;
use super::reaction::{Reaction, BasicReaction, ExtensionReaction}; use super::reaction::{Reaction, BasicReaction, ExtensionReaction};
use super::set::{BasicSet, Set}; use super::set::{BasicSet, Set};
use super::translator::{IdType, Translator, PrintableWithTranslator, Formatter}; use super::element::IdType;
use super::translator::{Translator, PrintableWithTranslator, Formatter};
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Environment { pub struct Environment {

View File

@ -223,7 +223,7 @@ pub mod node_formatter {
use petgraph::{Graph, Directed}; use petgraph::{Graph, Directed};
use petgraph::visit::IntoNodeReferences; use petgraph::visit::IntoNodeReferences;
use super::super::translator::IdType; use super::super::element::IdType;
use super::super::graph::{SystemGraph, OperationType}; use super::super::graph::{SystemGraph, OperationType};
use super::super::set::Set; use super::super::set::Set;
use super::super::process::Process; use super::super::process::Process;

View File

@ -5,7 +5,8 @@ use std::collections::HashMap;
use super::reaction::{Reaction, ExtensionReaction}; use super::reaction::{Reaction, ExtensionReaction};
use super::set::{Set, ExtensionsSet}; use super::set::{Set, ExtensionsSet};
use super::system::System; use super::system::System;
use super::translator::{IdType, Translator, PrintableWithTranslator, PRECISION}; use super::element::IdType;
use super::translator::{Translator, PrintableWithTranslator, PRECISION};
/// structure that holds the frequency of elements of a run or multiple runs, /// structure that holds the frequency of elements of a run or multiple runs,
/// weighted. To print use ```translator::FrequencyDisplay```. /// weighted. To print use ```translator::FrequencyDisplay```.

View File

@ -3,7 +3,8 @@ use std::str::FromStr;
use lalrpop_util::ParseError; use lalrpop_util::ParseError;
use crate::rsprocess::{set, reaction, process, environment, system, label}; use crate::rsprocess::{set, reaction, process, environment, system, label};
use crate::rsprocess::assert::types; use crate::rsprocess::assert::types;
use crate::rsprocess::translator::{ Translator, IdType }; use crate::rsprocess::element::IdType;
use crate::rsprocess::translator::Translator;
use crate::rsprocess::presets; use crate::rsprocess::presets;
use crate::rsprocess::graph; use crate::rsprocess::graph;

View File

@ -6,8 +6,9 @@ use std::rc::Rc;
use super::label::Label; use super::label::Label;
use super::set::{BasicSet, Set}; use super::set::{BasicSet, Set};
use super::element::IdType;
use super::system::System; use super::system::System;
use super::translator::{self, IdType}; use super::translator;
pub type SystemGraph = Graph<System, Label, Directed, u32>; pub type SystemGraph = Graph<System, Label, Directed, u32>;

View File

@ -3,6 +3,7 @@
pub mod translator; pub mod translator;
mod format_helpers; mod format_helpers;
pub mod element;
pub mod choices; pub mod choices;
pub mod environment; pub mod environment;
pub mod label; pub mod label;
@ -22,3 +23,6 @@ pub mod transitions;
#[cfg(test)] #[cfg(test)]
mod system_test; mod system_test;
#[cfg(test)]
mod set_test;

View File

@ -5,7 +5,8 @@ use std::rc::Rc;
use super::reaction::Reaction; use super::reaction::Reaction;
use super::set::{Set, BasicSet}; use super::set::{Set, BasicSet};
use super::translator::{IdType, Translator, PrintableWithTranslator, Formatter}; use super::element::IdType;
use super::translator::{Translator, PrintableWithTranslator, Formatter};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Process { pub enum Process {

View File

@ -6,53 +6,61 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::hash::Hash; use std::hash::Hash;
use super::set::{BasicSet, ExtensionsSet, Set}; use super::set::{BasicSet, ExtensionsSet, Set, PositiveSet};
use super::translator::{Translator, PrintableWithTranslator, Formatter}; use super::translator::{Translator, PrintableWithTranslator, Formatter};
pub trait BasicReaction<S: BasicSet>: pub trait BasicReaction:
Clone + Default + Eq + Hash + Serialize + PrintableWithTranslator Clone + Default + Eq + Hash + Serialize + PrintableWithTranslator
where for<'de> Self: Deserialize<'de>, where for<'de> Self: Deserialize<'de>,
{ {
fn enabled(&self, state: &S) -> bool; type Set: BasicSet;
fn compute_step(&self, state: &S) -> Option<&S>; fn enabled(&self, state: &Self::Set) -> bool;
fn compute_step(&self, state: &Self::Set) -> Option<&Self::Set>;
} }
pub trait ExtensionReaction<S: BasicSet> { pub trait ExtensionReaction: Sized {
fn compute_all(reactions: &[Self], state: &S) -> S type Set: BasicSet;
where Self: Sized;
fn find_loop(reactions: &[Self], entities: S, q: &S) -> (Vec<S>, Vec<S>) fn compute_all(reactions: &[Self], state: &Self::Set) -> Self::Set;
where Self: Sized;
fn find_only_loop(reactions: &[Self], entities: S, q: &S) -> Vec<S> fn find_loop(
where Self: Sized; reactions: &[Self],
entities: Self::Set,
q: &Self::Set
) -> (Vec<Self::Set>, Vec<Self::Set>);
fn find_only_loop(
reactions: &[Self],
entities: Self::Set,
q: &Self::Set
) -> Vec<Self::Set>;
fn find_prefix_len_loop( fn find_prefix_len_loop(
reactions: &[Self], reactions: &[Self],
entities: S, entities: Self::Set,
q: &S q: &Self::Set
) -> (usize, Vec<S>) ) -> (usize, Vec<Self::Set>);
where Self: Sized;
fn lollipops_only_loop_decomposed_q( fn lollipops_only_loop_decomposed_q(
reactions: &[Self], reactions: &[Self],
entities: &S, entities: &Self::Set,
q: &S q: &Self::Set
) -> Vec<S> ) -> Vec<Self::Set>;
where Self: Sized;
} }
/// Implementations for all reactions.
impl<T: BasicReaction<Set = Set>, Set: BasicSet> ExtensionReaction for T {
type Set = Set;
impl<T: BasicReaction<S>, S: BasicSet> ExtensionReaction<S> for T {
/// Computes the result of a series of reactions. Returns the union of all /// Computes the result of a series of reactions. Returns the union of all
/// products. /// products.
/// see result /// see result
fn compute_all( fn compute_all(
reactions: &[Self], reactions: &[Self],
state: &S state: &Set
) -> S ) -> Set
where Self: Sized { where Self: Sized {
reactions.iter().fold(S::default(), |mut acc: S, r| { reactions.iter().fold(Set::default(), |mut acc: Set, r| {
acc.extend(r.compute_step(state)); acc.extend(r.compute_step(state));
acc acc
}) })
@ -61,9 +69,9 @@ impl<T: BasicReaction<S>, S: BasicSet> ExtensionReaction<S> for T {
/// Finds the loops by simulating the system. /// Finds the loops by simulating the system.
fn find_loop( fn find_loop(
reactions: &[Self], reactions: &[Self],
entities: S, entities: Set,
q: &S q: &Set
) -> (Vec<S>, Vec<S>) { ) -> (Vec<Set>, Vec<Set>) {
let mut entities = entities; let mut entities = entities;
let mut trace = vec![]; let mut trace = vec![];
loop { loop {
@ -82,9 +90,9 @@ impl<T: BasicReaction<S>, S: BasicSet> ExtensionReaction<S> for T {
/// Finds the loops by simulating the system. /// Finds the loops by simulating the system.
fn find_only_loop( fn find_only_loop(
reactions: &[Self], reactions: &[Self],
entities: S, entities: Set,
q: &S q: &Set
) -> Vec<S> { ) -> Vec<Set> {
let mut entities = entities; let mut entities = entities;
let mut trace = vec![]; let mut trace = vec![];
loop { loop {
@ -103,9 +111,9 @@ impl<T: BasicReaction<S>, S: BasicSet> ExtensionReaction<S> for T {
/// Finds the loops and the length of the prefix by simulating the system. /// Finds the loops and the length of the prefix by simulating the system.
fn find_prefix_len_loop( fn find_prefix_len_loop(
reactions: &[Self], reactions: &[Self],
entities: S, entities: Set,
q: &S q: &Set
) -> (usize, Vec<S>) { ) -> (usize, Vec<Set>) {
let mut entities = entities; let mut entities = entities;
let mut trace = vec![]; let mut trace = vec![];
loop { loop {
@ -124,9 +132,9 @@ impl<T: BasicReaction<S>, S: BasicSet> ExtensionReaction<S> for T {
/// see loop/5 /// see loop/5
fn lollipops_only_loop_decomposed_q( fn lollipops_only_loop_decomposed_q(
reactions: &[Self], reactions: &[Self],
entities: &S, entities: &Set,
q: &S, q: &Set,
) -> Vec<S> { ) -> Vec<Set> {
let find_loop_fn = let find_loop_fn =
|q| Self::find_only_loop(reactions, |q| Self::find_only_loop(reactions,
entities.clone(), entities.clone(),
@ -148,7 +156,9 @@ pub struct Reaction {
pub products: Set, pub products: Set,
} }
impl BasicReaction<Set> for Reaction { impl BasicReaction for Reaction {
type Set = Set;
/// returns true if ```current_state``` enables the reaction /// returns true if ```current_state``` enables the reaction
/// see enable /// see enable
fn enabled(&self, current_state: &Set) -> bool { fn enabled(&self, current_state: &Set) -> bool {
@ -159,10 +169,7 @@ impl BasicReaction<Set> for Reaction {
/// Computes the result of a single reaction (if enabled returns the /// Computes the result of a single reaction (if enabled returns the
/// products) otherwise returns None. /// products) otherwise returns None.
/// see result /// see result
fn compute_step( fn compute_step(&self, state: &Set) -> Option<&Set> {
&self,
state: &Set,
) -> Option<&Set> {
if self.enabled(state) { if self.enabled(state) {
Some(&self.products) Some(&self.products)
} else { } else {
@ -186,10 +193,48 @@ impl PrintableWithTranslator for Reaction {
impl Reaction { impl Reaction {
pub fn from(reactants: Set, inhibitors: Set, products: Set) -> Self { pub fn from(reactants: Set, inhibitors: Set, products: Set) -> Self {
Reaction { Reaction { reactants, inhibitors, products }
reactants, }
inhibitors, }
products,
// -----------------------------------------------------------------------------
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct PositiveReaction {
pub reactants: PositiveSet,
pub products: PositiveSet
}
impl BasicReaction for PositiveReaction {
type Set = PositiveSet;
fn enabled(&self, state: &PositiveSet) -> bool {
self.reactants.is_subset(state)
}
fn compute_step(&self, state: &PositiveSet) -> Option<&PositiveSet> {
if self.enabled(state) {
Some(&self.products)
} else {
None
} }
} }
} }
impl PrintableWithTranslator for PositiveReaction {
fn print(&self, f: &mut std::fmt::Formatter, translator: &Translator)
-> std::fmt::Result {
write!(
f,
"(r: {}, p: {})",
Formatter::from(translator, &self.reactants),
Formatter::from(translator, &self.products),
)
}
}
impl PositiveReaction {
pub fn from(reactants: PositiveSet, products: PositiveSet) -> Self {
PositiveReaction { reactants, products }
}
}

View File

@ -3,8 +3,8 @@ use std::collections::{BTreeSet, BTreeMap};
use std::hash::Hash; use std::hash::Hash;
use std::fmt; use std::fmt;
use super::translator::{IdType, Translator, PrintableWithTranslator}; use super::translator::{Formatter, Translator, PrintableWithTranslator};
use super::element::{IdType, PositiveType, IdState};
/// Basic trait for all Set implementations. /// Basic trait for all Set implementations.
/// Implement IntoIterator for &Self to have .iter() (not required directly by /// Implement IntoIterator for &Self to have .iter() (not required directly by
@ -199,24 +199,118 @@ impl From<Vec<IdType>> for Set {
} }
} }
// ----------------------------------------------------------------------------- impl Set {
/// Converts set to positive set. All elements with the same state.
pub fn to_positive_set(&self, state: IdState) -> PositiveSet {
PositiveSet { identifiers: self.iter().map(|x| (*x, state)).collect() }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, /// Computes minimized prohibiting set from reactants and inhibitors.
Deserialize)] /// Computes the powerset of the smallest reactants inhibitors set and
pub enum IdState { /// checks for each element of that set if they are also in all other
Positive, /// unions.
Negative pub fn prohibiting_set(
} reactants: &[Set],
inhibitors: &[Set],
impl std::fmt::Display for IdState { ) -> Result<Vec<PositiveSet>, String> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if reactants.len() != inhibitors.len() {
match self { return Err(format!("Different length inputs supplied to create \
Self::Positive => write!(f, "+"), prohibiting set. reactants: {:?}, \
Self::Negative => write!(f, "-") inhibitors: {:?}",
reactants, inhibitors))
} }
if let Some((r, i)) =
reactants.iter()
.zip(inhibitors.iter())
.find(|(sr, si)| !sr.intersection(si).is_empty())
{
return Err(format!("Element in both reactants and inhibitors when \
creating prohibiting set. reactants: {:?}, \
inhibitors: {:?}",
r, i))
}
let union = reactants.iter()
.zip(inhibitors.iter())
.map(|(sr, si)| {
sr.to_positive_set(IdState::Negative)
.union(&si.to_positive_set(IdState::Positive))
})
.collect::<Vec<_>>();
let union_union = union.iter()
.fold(PositiveSet::default(), |acc, s| acc.union(s));
let mut t = union_union.powerset();
for set in union.iter() {
t.retain(|el| !el.intersection(set).is_empty());
}
// minimization
// remove sets that contain other sets
let mut tmp_t = t.clone().into_iter();
let mut e = tmp_t.next().unwrap_or_default();
loop {
let mut modified = false;
t.retain(|set| {
if *set == e {
true
} else if e.is_subset(set) {
modified = true;
false
} else {
true
}
});
if !modified {
e = {
match tmp_t.next() {
Some(a) => a,
None => break,
}
};
}
}
// replace pair of sets that have a common negative-positive element
// with set without
// cannot happen, caught by error "Element in both ..." above
// for e in t.clone() {
// let mut removed_e = false;
// let mut position = 0;
// let mut removed_elements = vec![];
// t.retain(|set| {
// if set == &e {
// position += 1;
// true
// } else if removed_e {
// true
// } else if let elements = set.opposite_intersection(&e)
// && !elements.is_empty()
// {
// removed_e = true;
// removed_elements.extend(elements);
// false
// } else {
// position += 1;
// true
// }
// });
// if removed_e {
// let mut set = t.get(position).unwrap().clone();
// set = set.subtraction(&Set::from(removed_elements.clone())
// .to_positive_set(IdState::Positive));
// set = set.subtraction(&Set::from(removed_elements)
// .to_positive_set(IdState::Negative));
// t.remove(position);
// t.push(set);
// }
// }
Ok(t)
} }
} }
// -----------------------------------------------------------------------------
#[derive(Clone, Debug, Default, PartialOrd, Eq, Ord, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialOrd, Eq, Ord, Serialize, Deserialize)]
pub struct PositiveSet { pub struct PositiveSet {
pub identifiers: BTreeMap<IdType, IdState>, pub identifiers: BTreeMap<IdType, IdState>,
@ -319,14 +413,16 @@ impl PrintableWithTranslator for PositiveSet {
while let Some((id, s)) = it.next() { while let Some((id, s)) = it.next() {
if it.peek().is_none() { if it.peek().is_none() {
write!(f, write!(f,
"{}{}", "{}",
s, Formatter::from(translator,
translator.decode(*id).unwrap_or("Missing".into()))?; &PositiveType { id: *id, state: *s })
)?;
} else { } else {
write!(f, write!(f,
"{}{}, ", "{}, ",
s, Formatter::from(translator,
translator.decode(*id).unwrap_or("Missing".into()))?; &PositiveType { id: *id, state: *s })
)?;
} }
} }
write!(f, "}}") write!(f, "}}")
@ -339,6 +435,12 @@ impl PartialEq for PositiveSet {
} }
} }
impl Hash for PositiveSet {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.identifiers.hash(state)
}
}
impl IntoIterator for PositiveSet { impl IntoIterator for PositiveSet {
type Item = (IdType, IdState); type Item = (IdType, IdState);
type IntoIter = std::collections::btree_map::IntoIter<IdType, IdState>; type IntoIter = std::collections::btree_map::IntoIter<IdType, IdState>;
@ -356,3 +458,60 @@ impl<'a> IntoIterator for &'a PositiveSet {
self.identifiers.iter() self.identifiers.iter()
} }
} }
impl<const N: usize> From<[(IdType, IdState); N]> for PositiveSet {
fn from(arr: [(IdType, IdState); N]) -> Self {
PositiveSet {
identifiers: BTreeMap::from(arr),
}
}
}
impl From<&[(IdType, IdState)]> for PositiveSet {
fn from(arr: &[(IdType, IdState)]) -> Self {
PositiveSet {
identifiers: BTreeMap::from_iter(arr.to_vec()),
}
}
}
impl From<Vec<(IdType, IdState)>> for PositiveSet {
fn from(arr: Vec<(IdType, IdState)>) -> Self {
PositiveSet {
identifiers: BTreeMap::from_iter(arr),
}
}
}
impl PositiveSet {
pub fn powerset(&self) -> Vec<Self> {
self.into_iter().fold({
let mut asd = Vec::with_capacity(2_usize.pow(self.len() as u32));
asd.push(vec![]);
asd
}, |mut p, x| {
let i = p.clone().into_iter()
.map(|mut s| {
s.push(x);
s
});
p.extend(i);
p
}).into_iter()
.map(|x| Self::from(x.into_iter()
.map(|(el, s)| (*el, *s))
.collect::<Vec<_>>()))
.collect::<Vec<_>>()
}
pub fn opposite_intersection(&self, other: &Self) -> Vec<IdType> {
let mut ret = vec![];
for (el, state) in self {
if let Some(state2) = other.identifiers.get(el) && *state == !*state2 {
ret.push(*el);
}
}
ret
}
}

View File

@ -9,8 +9,9 @@ use super::label::Label;
use super::process::Process; use super::process::Process;
use super::reaction::{Reaction, ExtensionReaction}; use super::reaction::{Reaction, ExtensionReaction};
use super::set::{BasicSet, Set}; use super::set::{BasicSet, Set};
use super::element::IdType;
use super::transitions::TransitionsIterator; use super::transitions::TransitionsIterator;
use super::translator::{IdType, Translator, PrintableWithTranslator, Formatter}; use super::translator::{Translator, PrintableWithTranslator, Formatter};
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]

View File

@ -4,11 +4,11 @@ use serde::{Serialize, Deserialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use super::element::IdType;
/// precision for printing frequencies /// precision for printing frequencies
pub static PRECISION: &usize = &2; pub static PRECISION: &usize = &2;
pub type IdType = u32;
/// Structure that keeps track of association string and id. Ids given /// Structure that keeps track of association string and id. Ids given
/// sequentially from 0. /// sequentially from 0.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]