formatting with rustfmt

This commit is contained in:
elvis
2025-07-01 19:22:50 +02:00
parent dcb4cbecb0
commit eba5d1266d
14 changed files with 796 additions and 639 deletions

View File

@ -1,23 +1,19 @@
use crate::rsprocess::{frequency, #![allow(dead_code)]
statistics,
transitions,
perpetual};
use crate::rsprocess::structure::RSsystem; use crate::rsprocess::structure::RSsystem;
use crate::rsprocess::translator::{Translator, WithTranslator}; use crate::rsprocess::translator::{Translator, WithTranslator};
use crate::rsprocess::{frequency, perpetual, statistics, transitions};
use std::env; use std::env;
use std::fs; use std::fs;
use std::io::prelude::*;
use std::io; use std::io;
use std::io::prelude::*;
// grammar is defined in main.rs, calling lalrpop_mod! twice, generates twice // grammar is defined in main.rs, calling lalrpop_mod! twice, generates twice
// the code // the code
use super::grammar; use super::grammar;
fn read_system( fn read_system(translator: &mut Translator, path: std::path::PathBuf) -> std::io::Result<RSsystem> {
translator: &mut Translator,
path: std::path::PathBuf
) -> std::io::Result<RSsystem> {
// we read the file with a buffer // we read the file with a buffer
let f = fs::File::open(path.clone())?; let f = fs::File::open(path.clone())?;
let mut buf_reader = io::BufReader::new(f); let mut buf_reader = io::BufReader::new(f);
@ -25,7 +21,9 @@ fn read_system(
buf_reader.read_to_string(&mut contents)?; buf_reader.read_to_string(&mut contents)?;
// parse // parse
let result = grammar::SystemParser::new().parse(translator, &contents).unwrap(); let result = grammar::SystemParser::new()
.parse(translator, &contents)
.unwrap();
Ok(result) Ok(result)
} }
@ -39,7 +37,6 @@ pub fn stats() -> std::io::Result<()> {
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_system(&mut translator, path)?;
// print statistics to screan // print statistics to screan
println!("{}", statistics::of_RSsystem(&translator, &system)); println!("{}", statistics::of_RSsystem(&translator, &system));
@ -63,12 +60,17 @@ pub fn target() -> std::io::Result<()> {
// the system needs to terminate to return // the system needs to terminate to return
let res = match transitions::target(&system) { let res = match transitions::target(&system) {
Ok(o) => o, Ok(o) => o,
Err(e) => {println!("Error computing target: {e}"); return Ok(());} Err(e) => {
println!("Error computing target: {e}");
return Ok(());
}
}; };
println!("After {} steps we arrive at state:\n{}", println!(
"After {} steps we arrive at state:\n{}",
res.0, res.0,
WithTranslator::from_RSset(&translator, &res.1)); WithTranslator::from_RSset(&translator, &res.1)
);
Ok(()) Ok(())
} }
@ -85,7 +87,10 @@ pub fn run() -> std::io::Result<()> {
// the system needs to terminate to return // the system needs to terminate to return
let res = match transitions::run_separated(&system) { let res = match transitions::run_separated(&system) {
Ok(o) => o, Ok(o) => o,
Err(e) => {println!("Error computing target: {e}"); return Ok(());} Err(e) => {
println!("Error computing target: {e}");
return Ok(());
}
}; };
println!("The trace is composed of the entities:"); println!("The trace is composed of the entities:");
@ -109,7 +114,10 @@ pub fn hoop() -> std::io::Result<()> {
// we retrieve the id for "x" and use it to find the corresponding loop // we retrieve the id for "x" and use it to find the corresponding loop
let res = match perpetual::lollipops_only_loop_named(system, translator.encode("x")) { let res = match perpetual::lollipops_only_loop_named(system, translator.encode("x")) {
Some(o) => o, Some(o) => o,
None => {println!("No loop found."); return Ok(());} None => {
println!("No loop found.");
return Ok(());
}
}; };
println!("The loop is composed by the sets:"); println!("The loop is composed by the sets:");
@ -131,10 +139,16 @@ pub fn freq() -> std::io::Result<()> {
let res = match frequency::naive_frequency(&system) { let res = match frequency::naive_frequency(&system) {
Ok(f) => f, Ok(f) => f,
Err(e) => {println!("Error computing target: {e}"); return Ok(());} Err(e) => {
println!("Error computing target: {e}");
return Ok(());
}
}; };
println!("Frequency of encountered symbols:\n{}", WithTranslator::from_Frequency(&translator, &res)); println!(
"Frequency of encountered symbols:\n{}",
WithTranslator::from_Frequency(&translator, &res)
);
Ok(()) Ok(())
} }

View File

@ -1,5 +1,5 @@
mod rsprocess;
mod examples; mod examples;
mod rsprocess;
lalrpop_util::lalrpop_mod!( lalrpop_util::lalrpop_mod!(
#[allow(clippy::uninlined_format_args)] pub grammar, // name of module #[allow(clippy::uninlined_format_args)] pub grammar, // name of module
@ -11,15 +11,15 @@ fn main() -> std::io::Result<()> {
// std::thread::sleep(std::time::Duration::new(2, 0)); // std::thread::sleep(std::time::Duration::new(2, 0));
// println!("{}", now.elapsed().as_micros()); // println!("{}", now.elapsed().as_micros());
examples::stats()?; // examples::stats()?;
examples::freq()?; examples::freq()?;
examples::hoop()?; // examples::hoop()?;
examples::target()?; // examples::target()?;
examples::run()?; // examples::run()?;
Ok(()) Ok(())
} }

View File

@ -6,7 +6,7 @@
//! inhibitors and products are held. //! inhibitors and products are held.
#![allow(dead_code)] #![allow(dead_code)]
use super::structure::{RSset, RSreaction}; use super::structure::{RSreaction, RSset};
/// Computes the result of a single reaction (if enabled returns the products) /// Computes the result of a single reaction (if enabled returns the products)
/// otherwise returns None. /// otherwise returns None.
@ -29,18 +29,16 @@ pub fn compute_all<'a>(
current_state: &'a RSset, current_state: &'a RSset,
reactions: Vec<&'a RSreaction> reactions: Vec<&'a RSreaction>
) -> RSset { ) -> RSset {
reactions.iter().fold( reactions.iter().fold(RSset::new(), |acc, r| {
RSset::new(), acc.union_option(compute_step(current_state, r))
|acc, r| acc.union_option(compute_step(current_state, r)) })
)
} }
pub fn compute_all_owned<'a>( pub fn compute_all_owned<'a>(
current_state: &'a RSset, current_state: &'a RSset,
reactions: &'a [RSreaction] reactions: &'a [RSreaction]
) -> RSset { ) -> RSset {
reactions.iter().fold( reactions.iter().fold(RSset::new(), |acc, r| {
RSset::new(), acc.union_option(compute_step(current_state, r))
|acc, r| acc.union_option(compute_step(current_state, r)) })
)
} }

View File

@ -1,23 +1,20 @@
#![allow(dead_code)] #![allow(dead_code)]
use super::perpetual::{ use super::perpetual::{
lollipops_decomposed_named, lollipops_decomposed_named, lollipops_prefix_len_loop_decomposed,
lollipops_prefix_len_loop_decomposed, lollipops_prefix_len_loop_decomposed_named,
lollipops_prefix_len_loop_decomposed_named
}; };
use super::structure::{RSenvironment, RSreaction, RSset}; use super::structure::{RSenvironment, RSreaction, RSset};
use super::translator::IdType; use super::translator::IdType;
use std::cmp; use std::cmp;
use std::collections::HashSet; use std::collections::HashSet;
// see confluent, confluents // see confluent, confluents
pub fn confluent( pub fn confluent(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
entities: &[RSset], entities: &[RSset],
) -> Option<(usize, usize, Vec<RSset>)> { ) -> Option<(usize, usize, Vec<RSset>)> {
let all_loops = lollipops_prefix_len_loop_decomposed(delta, let all_loops = lollipops_prefix_len_loop_decomposed(delta,
reaction_rules, reaction_rules,
entities.first()?); entities.first()?);
@ -26,7 +23,8 @@ pub fn confluent(
let mut max_distance = prefix_len; let mut max_distance = prefix_len;
for available_entities in entities.iter().skip(1) { for available_entities in entities.iter().skip(1) {
let all_loops = lollipops_prefix_len_loop_decomposed(delta, let all_loops =
lollipops_prefix_len_loop_decomposed(delta,
reaction_rules, reaction_rules,
available_entities); available_entities);
// FIXME we take just the first? do we compare all? // FIXME we take just the first? do we compare all?
@ -40,13 +38,12 @@ pub fn confluent(
Some((max_distance, dimension, hoop)) Some((max_distance, dimension, hoop))
} }
// see confluent, confluents // see confluent, confluents
pub fn confluent_named( pub fn confluent_named(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
entities: &[RSset], entities: &[RSset],
symb: IdType symb: IdType,
) -> Option<(usize, usize, Vec<RSset>)> { ) -> Option<(usize, usize, Vec<RSset>)> {
let (prefix_len, first_hoop) = let (prefix_len, first_hoop) =
lollipops_prefix_len_loop_decomposed_named(delta, lollipops_prefix_len_loop_decomposed_named(delta,
@ -58,11 +55,12 @@ pub fn confluent_named(
let hoop = first_hoop; let hoop = first_hoop;
for available_entities in entities.iter().skip(1) { for available_entities in entities.iter().skip(1) {
let (prefix_len, new_hoop) = let (prefix_len, new_hoop) = lollipops_prefix_len_loop_decomposed_named(
lollipops_prefix_len_loop_decomposed_named(delta, delta,
reaction_rules, reaction_rules,
available_entities, available_entities,
symb)?; symb,
)?;
if new_hoop.len() != dimension || !hoop.contains(new_hoop.first()?) { if new_hoop.len() != dimension || !hoop.contains(new_hoop.first()?) {
return None; return None;
@ -79,9 +77,10 @@ pub fn invariant_named(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
entities: &[RSset], entities: &[RSset],
symb: IdType symb: IdType,
) -> Option<(Vec<RSset>, Vec<RSset>)> { ) -> Option<(Vec<RSset>, Vec<RSset>)> {
let (prefix, hoop) = lollipops_decomposed_named(delta, let (prefix, hoop) =
lollipops_decomposed_named(delta,
reaction_rules, reaction_rules,
entities.first()?, entities.first()?,
symb)?; symb)?;
@ -97,13 +96,12 @@ pub fn invariant_named(
available_entities, available_entities,
symb)?; symb)?;
if new_hoop.len() != dimension || !hoop.contains(new_hoop.first()?) { if new_hoop.len() != dimension || !hoop.contains(new_hoop.first()?) {
return None return None;
} }
invariant.append(&mut new_prefix.clone()); invariant.append(&mut new_prefix.clone());
} }
// remove duplicates, maybe better with sorting? // remove duplicates, maybe better with sorting?
invariant = invariant = invariant
invariant
.iter() .iter()
.cloned() .cloned()
.collect::<HashSet<_>>() .collect::<HashSet<_>>()
@ -120,9 +118,10 @@ pub fn loop_confluent_named(
deltas: &[RSenvironment], deltas: &[RSenvironment],
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
entities: &[RSset], entities: &[RSset],
symb: IdType symb: IdType,
) -> Option<Vec<(usize, usize, Vec<RSset>)>> { ) -> Option<Vec<(usize, usize, Vec<RSset>)>> {
deltas.iter() deltas
.iter()
.map(|q| confluent_named(q, reaction_rules, entities, symb)) .map(|q| confluent_named(q, reaction_rules, entities, symb))
.collect::<Option<Vec<_>>>() .collect::<Option<Vec<_>>>()
} }
@ -133,16 +132,17 @@ pub fn strong_confluent_named(
deltas: &[RSenvironment], deltas: &[RSenvironment],
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
entities: &[RSset], entities: &[RSset],
symb: IdType symb: IdType,
) -> Option<Vec<(Vec<RSset>, usize, Vec<RSset>)>> { ) -> Option<Vec<(Vec<RSset>, usize, Vec<RSset>)>> {
deltas.iter() deltas
.iter()
.map(|q| { .map(|q| {
let (invariant, hoop) = invariant_named(q, let (invariant, hoop) = invariant_named(q,
reaction_rules, reaction_rules,
entities, entities,
symb)?; symb)?;
let length = invariant.len(); let length = invariant.len();
Some((invariant, length, hoop)) } Some((invariant, length, hoop))
) })
.collect::<Option<Vec<_>>>() .collect::<Option<Vec<_>>>()
} }

View File

@ -1,7 +1,7 @@
#![allow(dead_code)] #![allow(dead_code)]
use std::collections::HashMap;
use crate::rsprocess::perpetual::lollipops_only_loop_decomposed_q; use crate::rsprocess::perpetual::lollipops_only_loop_decomposed_q;
use std::collections::HashMap;
use super::perpetual::lollipops_only_loop_named; use super::perpetual::lollipops_only_loop_named;
use super::structure::{RSreaction, RSset, RSsystem}; use super::structure::{RSreaction, RSset, RSsystem};
@ -12,12 +12,16 @@ use super::translator::IdType;
pub struct Frequency { pub struct Frequency {
pub frequency_map: HashMap<IdType, Vec<u32>>, pub frequency_map: HashMap<IdType, Vec<u32>>,
pub totals: Vec<usize>, pub totals: Vec<usize>,
pub weights: Vec<u32> pub weights: Vec<u32>,
} }
impl Frequency { impl Frequency {
pub fn new() -> Self { pub fn new() -> Self {
Frequency { frequency_map: HashMap::new(), totals: vec![], weights: vec![] } Frequency {
frequency_map: HashMap::new(),
totals: vec![],
weights: vec![],
}
} }
pub fn add(&mut self, e: &RSset, run: usize) { pub fn add(&mut self, e: &RSset, run: usize) {
@ -42,7 +46,6 @@ impl Default for Frequency {
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// see naiveFreq, assume the system is finite, calculate the frequency of // see naiveFreq, assume the system is finite, calculate the frequency of
@ -76,7 +79,7 @@ pub fn loop_frequency(system: &RSsystem, symb: IdType) -> Frequency {
pub fn limit_frequency( pub fn limit_frequency(
q: &[RSset], q: &[RSset],
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset available_entities: &RSset,
) -> Option<Frequency> { ) -> Option<Frequency> {
let mut available_entities = available_entities.clone(); let mut available_entities = available_entities.clone();
@ -93,18 +96,18 @@ pub fn limit_frequency(
lollipops_only_loop_decomposed_q(q.last().unwrap(), lollipops_only_loop_decomposed_q(q.last().unwrap(),
reaction_rules, reaction_rules,
&available_entities) &available_entities)
.iter().for_each(|e| freq.add(e, 0)); .iter()
.for_each(|e| freq.add(e, 0));
Some(freq) Some(freq)
} }
// see fastFreq, q[i] is given enough times such that the stabilizes in a loop, // see fastFreq, q[i] is given enough times such that the stabilizes in a loop,
// calculate the frequency of the symbols in any state in any loop, weighted. // calculate the frequency of the symbols in any state in any loop, weighted.
pub fn fast_frequency( pub fn fast_frequency(
q: &[RSset], q: &[RSset],
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset, available_entities: &RSset,
weights: &[u32] weights: &[u32],
) -> Option<Frequency> { ) -> Option<Frequency> {
// FIXME: we return the empty frequency or do we not return anything? // FIXME: we return the empty frequency or do we not return anything?
let mut available_entities = available_entities.clone(); let mut available_entities = available_entities.clone();

View File

@ -64,7 +64,8 @@ pub Reactions: Vec<RSreaction> = {
Reaction: RSreaction = { Reaction: RSreaction = {
"[" <r: Set> "," <i: Set> "," <p: Set> "]" => RSreaction::from(r, i, p), "[" <r: Set> "," <i: Set> "," <p: Set> "]" => RSreaction::from(r, i, p),
"[" "r:" <r: Set> "," "i:" <i: Set> "," "p:" <p: Set> "]" => RSreaction::from(r, i, p), "[" "r:" <r: Set> "," "i:" <i: Set> "," "p:" <p: Set> "]" =>
RSreaction::from(r, i, p),
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -87,14 +88,18 @@ CTX_process: RSprocess = {
RSprocess::EntitySet{ entities: c, next_process: Rc::new(k) }, RSprocess::EntitySet{ entities: c, next_process: Rc::new(k) },
"(" <k: CTX_process> ")" => k, "(" <k: CTX_process> ")" => k,
"(" <k: Separeted<CTX_process, "+">> ")" => "(" <k: Separeted<CTX_process, "+">> ")" =>
RSprocess::Summation{ children: k.into_iter().map(Rc::new).collect::<Vec<_>>() }, RSprocess::Summation{
children: k.into_iter().map(Rc::new).collect::<Vec<_>>()
},
"<" <n: Num> <k1: CTX_process> ">" "." <k: CTX_process> => "<" <n: Num> <k1: CTX_process> ">" "." <k: CTX_process> =>
RSprocess::WaitEntity{ repeat: n, RSprocess::WaitEntity{ repeat: n,
repeated_process: Rc::new(k1), repeated_process: Rc::new(k1),
next_process: Rc::new(k) }, next_process: Rc::new(k) },
"nil" => RSprocess::Nill, "nil" => RSprocess::Nill,
<identifier: Literal> => <identifier: Literal> =>
RSprocess::RecursiveIdentifier{ identifier: translator.encode(identifier) } RSprocess::RecursiveIdentifier{
identifier: translator.encode(identifier)
}
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -165,5 +170,8 @@ pub System: RSsystem = {
"Initial Entities:" <available_entities: Set> "Initial Entities:" <available_entities: Set>
"Context:" <context_process: Context> "Context:" <context_process: Context>
"Reactions:" <reaction_rules: Reactions> "Reactions:" <reaction_rules: Reactions>
=> RSsystem::from(delta.into(), available_entities, context_process, Rc::new(reaction_rules)) => RSsystem::from(delta.into(),
available_entities,
context_process,
Rc::new(reaction_rules))
} }

View File

@ -1,9 +1,9 @@
pub mod translator;
pub mod structure;
pub mod support_structures;
pub mod classical; pub mod classical;
pub mod transitions;
pub mod perpetual;
pub mod confluence; pub mod confluence;
pub mod frequency; pub mod frequency;
pub mod perpetual;
pub mod statistics; pub mod statistics;
pub mod structure;
pub mod support_structures;
pub mod transitions;
pub mod translator;

View File

@ -1,9 +1,8 @@
#![allow(dead_code)] #![allow(dead_code)]
use super::classical::compute_all_owned; use super::classical::compute_all_owned;
use super::translator::IdType;
use super::structure::{RSenvironment, RSprocess, RSreaction, RSset, RSsystem}; use super::structure::{RSenvironment, RSprocess, RSreaction, RSset, RSsystem};
use super::translator::IdType;
// returns the prefix and the loop from a trace // returns the prefix and the loop from a trace
fn split<'a>( fn split<'a>(
@ -34,9 +33,12 @@ fn find_loop(
} }
} }
// finds the loops by simulating the system // finds the loops by simulating the system
fn find_only_loop(rs: &[RSreaction], entities: RSset, q: &RSset) -> Vec<RSset> { fn find_only_loop(
rs: &[RSreaction],
entities: RSset,
q: &RSset
) -> Vec<RSset> {
let mut entities = entities; let mut entities = entities;
let mut trace = vec![]; let mut trace = vec![];
loop { loop {
@ -51,7 +53,6 @@ fn find_only_loop(rs: &[RSreaction], entities: RSset, q: &RSset) -> Vec<RSset> {
} }
} }
// 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(
rs: &[RSreaction], rs: &[RSreaction],
@ -80,7 +81,11 @@ fn filter_delta<'a>(x: (&IdType, &'a RSprocess)) -> Option<&'a RSset> {
use super::structure::RSprocess::*; use super::structure::RSprocess::*;
let (id, rest) = x; let (id, rest) = x;
if let EntitySet{ entities, next_process} = rest { if let EntitySet {
entities,
next_process,
} = rest
{
if let RecursiveIdentifier { identifier } = &**next_process { if let RecursiveIdentifier { identifier } = &**next_process {
if identifier == id { if identifier == id {
return Some(entities); return Some(entities);
@ -90,12 +95,11 @@ fn filter_delta<'a>(x: (&IdType, &'a RSprocess)) -> Option<&'a RSset> {
None None
} }
// see lollipop // see lollipop
pub fn lollipops_decomposed( pub fn lollipops_decomposed(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset available_entities: &RSset,
) -> Vec<(Vec<RSset>, Vec<RSset>)> { ) -> Vec<(Vec<RSset>, Vec<RSset>)> {
// FIXME: i think we are only interested in "x", not all symbols that // FIXME: i think we are only interested in "x", not all symbols that
// satisfy X = pre(Q, rec(X)) // satisfy X = pre(Q, rec(X))
@ -110,9 +114,11 @@ pub fn lollipops_decomposed(
// see lollipop // see lollipop
pub fn lollipops(system: RSsystem) -> Vec<(Vec<RSset>, Vec<RSset>)> { pub fn lollipops(system: RSsystem) -> Vec<(Vec<RSset>, Vec<RSset>)> {
lollipops_decomposed(system.get_delta(), lollipops_decomposed(
system.get_delta(),
system.get_reaction_rules(), system.get_reaction_rules(),
system.get_available_entities()) system.get_available_entities(),
)
} }
// see loop // see loop
@ -121,18 +127,21 @@ pub fn lollipops_only_loop(system: RSsystem) -> Vec<Vec<RSset>> {
// satisfy X = pre(Q, rec(X)) // satisfy X = pre(Q, rec(X))
let filtered = system.get_delta().iter().filter_map(filter_delta); let filtered = system.get_delta().iter().filter_map(filter_delta);
let find_loop_fn = |q| find_only_loop(system.get_reaction_rules(), let find_loop_fn = |q| {
find_only_loop(
system.get_reaction_rules(),
system.get_available_entities().clone(), system.get_available_entities().clone(),
q); q,
)
};
filtered.map(find_loop_fn).collect::<Vec<_>>() filtered.map(find_loop_fn).collect::<Vec<_>>()
} }
pub fn lollipops_prefix_len_loop_decomposed( pub fn lollipops_prefix_len_loop_decomposed(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset available_entities: &RSset,
) -> Vec<(usize, Vec<RSset>)> { ) -> Vec<(usize, Vec<RSset>)> {
// FIXME: i think we are only interested in "x", not all symbols that // FIXME: i think we are only interested in "x", not all symbols that
// satisfy X = pre(Q, rec(X)) // satisfy X = pre(Q, rec(X))
@ -149,7 +158,7 @@ pub fn lollipops_prefix_len_loop_decomposed(
pub fn lollipops_only_loop_decomposed( pub fn lollipops_only_loop_decomposed(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset available_entities: &RSset,
) -> Vec<Vec<RSset>> { ) -> Vec<Vec<RSset>> {
// FIXME: i think we are only interested in "x", not all symbols that // FIXME: i think we are only interested in "x", not all symbols that
// satisfy X = pre(Q, rec(X)) // satisfy X = pre(Q, rec(X))
@ -178,7 +187,11 @@ fn filter_delta_named<'a>(
return None; return None;
} }
if let EntitySet{ entities, next_process} = rest { if let EntitySet {
entities,
next_process,
} = rest
{
if let RecursiveIdentifier { identifier } = &**next_process { if let RecursiveIdentifier { identifier } = &**next_process {
if identifier == id { if identifier == id {
return Some(entities); return Some(entities);
@ -193,9 +206,12 @@ pub fn lollipops_decomposed_named(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset, available_entities: &RSset,
symb: IdType symb: IdType,
) -> Option<(Vec<RSset>, Vec<RSset>)> { ) -> Option<(Vec<RSset>, Vec<RSset>)> {
let filtered = delta.iter().filter_map(|x| filter_delta_named(x, &symb)).next(); let filtered = delta
.iter()
.filter_map(|x| filter_delta_named(x, &symb))
.next();
let find_loop_fn = |q| find_loop(reaction_rules, let find_loop_fn = |q| find_loop(reaction_rules,
available_entities.clone(), available_entities.clone(),
@ -209,10 +225,12 @@ pub fn lollipops_named(
system: RSsystem, system: RSsystem,
symb: IdType symb: IdType
) -> Option<(Vec<RSset>, Vec<RSset>)> { ) -> Option<(Vec<RSset>, Vec<RSset>)> {
lollipops_decomposed_named(system.get_delta(), lollipops_decomposed_named(
system.get_delta(),
system.get_reaction_rules(), system.get_reaction_rules(),
system.get_available_entities(), system.get_available_entities(),
symb) symb,
)
} }
// see loop // see loop
@ -220,13 +238,19 @@ pub fn lollipops_only_loop_named(
system: RSsystem, system: RSsystem,
symb: IdType symb: IdType
) -> Option<Vec<RSset>> { ) -> Option<Vec<RSset>> {
let filtered = system.get_delta().iter() let filtered = system
.filter_map(|x| filter_delta_named(x, &symb)).next(); .get_delta()
.iter()
.filter_map(|x| filter_delta_named(x, &symb))
.next();
let find_loop_fn = let find_loop_fn = |q| {
|q| find_only_loop(system.get_reaction_rules(), find_only_loop(
system.get_reaction_rules(),
system.get_available_entities().clone(), system.get_available_entities().clone(),
q); q,
)
};
filtered.map(find_loop_fn) filtered.map(find_loop_fn)
} }
@ -235,10 +259,12 @@ pub fn lollipops_prefix_len_loop_decomposed_named(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset, available_entities: &RSset,
symb: IdType symb: IdType,
) -> Option<(usize, Vec<RSset>)> { ) -> Option<(usize, Vec<RSset>)> {
let filtered = delta.iter() let filtered = delta
.filter_map(|x| filter_delta_named(x, &symb)).next(); .iter()
.filter_map(|x| filter_delta_named(x, &symb))
.next();
let find_loop_fn = |q| find_prefix_len_loop(reaction_rules, let find_loop_fn = |q| find_prefix_len_loop(reaction_rules,
available_entities.clone(), available_entities.clone(),
@ -252,10 +278,12 @@ pub fn lollipops_only_loop_decomposed_named(
delta: &RSenvironment, delta: &RSenvironment,
reaction_rules: &[RSreaction], reaction_rules: &[RSreaction],
available_entities: &RSset, available_entities: &RSset,
symb: IdType symb: IdType,
) -> Option<Vec<RSset>> { ) -> Option<Vec<RSset>> {
let filtered = delta.iter() let filtered = delta
.filter_map(|x| filter_delta_named(x, &symb)).next(); .iter()
.filter_map(|x| filter_delta_named(x, &symb))
.next();
let find_loop_fn = |q| find_only_loop(reaction_rules, let find_loop_fn = |q| find_only_loop(reaction_rules,
available_entities.clone(), available_entities.clone(),

View File

@ -10,101 +10,98 @@ pub fn of_RSsystem<'a>(translator: &'a Translator, system: &'a RSsystem) -> Stri
result.push_str( result.push_str(
"=============================================================\n" "=============================================================\n"
); );
result.push_str( result.push_str(&format!(
&format!("the initial state has {} entities:\n", "the initial state has {} entities:\n",
system.get_available_entities().len()) system.get_available_entities().len()
); ));
result.push_str( result.push_str(&format!(
&format!("{}\n", "{}\n",
WithTranslator::from_RSset(translator, WithTranslator::from_RSset(translator, system.get_available_entities())
system.get_available_entities())) ));
);
let reactants = let reactants = system
system
.get_reaction_rules() .get_reaction_rules()
.iter() .iter()
.fold(RSset::new(), |acc, new| acc.union(new.reactants())); .fold(RSset::new(), |acc, new| acc.union(new.reactants()));
result.push_str( result.push_str(&format!(
&format!("The reactants are {}:\n{}\n", "The reactants are {}:\n{}\n",
reactants.len(), reactants.len(),
WithTranslator::from_RSset(translator, &reactants)) WithTranslator::from_RSset(translator, &reactants)
); ));
let inhibitors = let inhibitors = system
system
.get_reaction_rules() .get_reaction_rules()
.iter() .iter()
.fold(RSset::new(), |acc, new| acc.union(new.inihibitors())); .fold(RSset::new(), |acc, new| acc.union(new.inihibitors()));
result.push_str( result.push_str(&format!(
&format!("The inhibitors are {}:\n{}\n", "The inhibitors are {}:\n{}\n",
inhibitors.len(), inhibitors.len(),
WithTranslator::from_RSset(translator, &inhibitors)) WithTranslator::from_RSset(translator, &inhibitors)
); ));
let products = let products = system
system
.get_reaction_rules() .get_reaction_rules()
.iter() .iter()
.fold(RSset::new(), |acc, new| acc.union(new.products())); .fold(RSset::new(), |acc, new| acc.union(new.products()));
result.push_str( result.push_str(&format!(
&format!("The products are {}:\n{}\n", "The products are {}:\n{}\n",
products.len(), products.len(),
WithTranslator::from_RSset(translator, &products)) WithTranslator::from_RSset(translator, &products)
); ));
let total = reactants.union(&inhibitors.union(&products)); let total = reactants.union(&inhibitors.union(&products));
result.push_str( result.push_str(&format!(
&format!("The reactions involve {} entities:\n{}\n", "The reactions involve {} entities:\n{}\n",
total.len(), total.len(),
WithTranslator::from_RSset(translator, &total)) WithTranslator::from_RSset(translator, &total)
); ));
let entities_env = system.get_delta().all_elements(); let entities_env = system.get_delta().all_elements();
result.push_str( result.push_str(&format!(
&format!("The environment involves {} entities:\n{}\n", "The environment involves {} entities:\n{}\n",
entities_env.len(), entities_env.len(),
WithTranslator::from_RSset(translator, &entities_env)) WithTranslator::from_RSset(translator, &entities_env)
); ));
let entities_context = system.get_context_process().all_elements(); let entities_context = system.get_context_process().all_elements();
result.push_str( result.push_str(&format!(
&format!("The context involves {} entities:\n{}\n", "The context involves {} entities:\n{}\n",
entities_context.len(), entities_context.len(),
WithTranslator::from_RSset(translator, &entities_context)) WithTranslator::from_RSset(translator, &entities_context)
); ));
let entities_all = total.union(&entities_env) let entities_all = total
.union(&entities_env)
.union(&entities_context) .union(&entities_context)
.union(system.get_available_entities()); .union(system.get_available_entities());
result.push_str( result.push_str(&format!(
&format!("The whole RS involves {} entities:\n{}\n", "The whole RS involves {} entities:\n{}\n",
entities_all.len(), entities_all.len(),
WithTranslator::from_RSset(translator, &entities_all)) WithTranslator::from_RSset(translator, &entities_all)
); ));
let possible_e = products.union(system.get_available_entities()) let possible_e = products
.union(system.get_available_entities())
.union(&entities_context); .union(&entities_context);
let missing_e = reactants.subtraction(&possible_e); let missing_e = reactants.subtraction(&possible_e);
result.push_str( result.push_str(&format!(
&format!("There are {} reactants that will never be available:\n{}\n", "There are {} reactants that will never be available:\n{}\n",
missing_e.len(), missing_e.len(),
WithTranslator::from_RSset(translator, &missing_e)) WithTranslator::from_RSset(translator, &missing_e)
); ));
let entities_not_needed = entities_context.subtraction(&total); let entities_not_needed = entities_context.subtraction(&total);
result.push_str( result.push_str(&format!(
&format!("The context can provide {} entities that will never be used:\n{}\n", "The context can provide {} entities that will never be used:\n{}\n",
entities_not_needed.len(), entities_not_needed.len(),
WithTranslator::from_RSset(translator, &entities_not_needed)) WithTranslator::from_RSset(translator, &entities_not_needed)
); ));
result.push_str( result.push_str(&format!(
&format!("There are {} reactions in total.\n", "There are {} reactions in total.\n",
system.get_reaction_rules().len()) system.get_reaction_rules().len()
); ));
let mut admissible_reactions = vec![]; let mut admissible_reactions = vec![];
let mut nonadmissible_reactions = vec![]; let mut nonadmissible_reactions = vec![];
@ -117,15 +114,15 @@ pub fn of_RSsystem<'a>(translator: &'a Translator, system: &'a RSsystem) -> Stri
} }
} }
result.push_str( result.push_str(&format!(
&format!("- the applicable reactions are {}.\n", "- the applicable reactions are {}.\n",
admissible_reactions.len()) admissible_reactions.len()
); ));
result.push_str( result.push_str(&format!(
&format!("- there are {} reactions that will never be enabled.\n", "- there are {} reactions that will never be enabled.\n",
nonadmissible_reactions.len()) nonadmissible_reactions.len()
); ));
result.push_str( result.push_str(
"=============================================================" "============================================================="
); );

View File

@ -1,39 +1,47 @@
#![allow(dead_code)] #![allow(dead_code)]
use super::translator::IdType;
use std::collections::{BTreeSet, HashMap, VecDeque}; use std::collections::{BTreeSet, HashMap, VecDeque};
use std::hash::Hash; use std::hash::Hash;
use std::rc::Rc; use std::rc::Rc;
use super::translator::{IdType};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// RSset // RSset
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RSset { pub struct RSset {
identifiers: BTreeSet<IdType> identifiers: BTreeSet<IdType>,
} }
impl<const N: usize> From<[IdType; N]> for RSset { impl<const N: usize> From<[IdType; N]> for RSset {
fn from(arr: [IdType; N]) -> Self { fn from(arr: [IdType; N]) -> Self {
RSset{identifiers: BTreeSet::from(arr)} RSset {
identifiers: BTreeSet::from(arr),
}
} }
} }
impl From<&[IdType]> for RSset { impl From<&[IdType]> for RSset {
fn from(arr: &[IdType]) -> Self { fn from(arr: &[IdType]) -> Self {
RSset{identifiers: BTreeSet::from_iter(arr.to_vec())} RSset {
identifiers: BTreeSet::from_iter(arr.to_vec()),
}
} }
} }
impl From<Vec<IdType>> for RSset { impl From<Vec<IdType>> for RSset {
fn from(arr: Vec<IdType>) -> Self { fn from(arr: Vec<IdType>) -> Self {
RSset{identifiers: BTreeSet::from_iter(arr)} RSset {
identifiers: BTreeSet::from_iter(arr),
}
} }
} }
impl RSset { impl RSset {
pub fn new() -> Self { pub fn new() -> Self {
RSset{identifiers: BTreeSet::new()} RSset {
identifiers: BTreeSet::new(),
}
} }
pub fn is_subset(&self, b: &RSset) -> bool { pub fn is_subset(&self, b: &RSset) -> bool {
@ -61,7 +69,9 @@ impl RSset {
pub fn intersection(&self, b: &RSset) -> RSset { pub fn intersection(&self, b: &RSset) -> RSset {
// TODO maybe find more efficient way without copy/clone // TODO maybe find more efficient way without copy/clone
let res: BTreeSet<_> = b.identifiers.intersection(&self.identifiers) let res: BTreeSet<_> = b
.identifiers
.intersection(&self.identifiers)
.copied() .copied()
.collect(); .collect();
RSset { identifiers: res } RSset { identifiers: res }
@ -69,7 +79,9 @@ impl RSset {
pub fn subtraction(&self, b: &RSset) -> RSset { pub fn subtraction(&self, b: &RSset) -> RSset {
// TODO maybe find more efficient way without copy/clone // TODO maybe find more efficient way without copy/clone
let res: BTreeSet<_> = self.identifiers.difference(&b.identifiers) let res: BTreeSet<_> = self
.identifiers
.difference(&b.identifiers)
.copied() .copied()
.collect(); .collect();
RSset { identifiers: res } RSset { identifiers: res }
@ -111,7 +123,6 @@ impl IntoIterator for RSset {
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// RSreaction // RSreaction
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -119,20 +130,24 @@ impl IntoIterator for RSset {
pub struct RSreaction { pub struct RSreaction {
reactants: RSset, reactants: RSset,
inihibitors: RSset, inihibitors: RSset,
products: RSset products: RSset,
} }
impl RSreaction { impl RSreaction {
pub fn new() -> Self { pub fn new() -> Self {
RSreaction{ reactants: RSset::new(), RSreaction {
reactants: RSset::new(),
inihibitors: RSset::new(), inihibitors: RSset::new(),
products: RSset::new(), } products: RSset::new(),
}
} }
pub fn from(reactants: RSset, inihibitors: RSset, products: RSset) -> Self { pub fn from(reactants: RSset, inihibitors: RSset, products: RSset) -> Self {
RSreaction{ reactants, RSreaction {
reactants,
inihibitors, inihibitors,
products } products,
}
} }
// see enable // see enable
@ -164,47 +179,53 @@ impl Default for RSreaction {
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// RSprocess // RSprocess
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum RSprocess { pub enum RSprocess {
Nill, Nill,
RecursiveIdentifier{ identifier: IdType }, RecursiveIdentifier {
EntitySet{ entities: RSset, identifier: IdType,
next_process: Rc<RSprocess> }, },
WaitEntity{ repeat: i64, EntitySet {
entities: RSset,
next_process: Rc<RSprocess>,
},
WaitEntity {
repeat: i64,
repeated_process: Rc<RSprocess>, repeated_process: Rc<RSprocess>,
next_process: Rc<RSprocess> }, next_process: Rc<RSprocess>,
Summation{ children: Vec<Rc<RSprocess>> }, },
NondeterministicChoice{ children: Vec<Rc<RSprocess>> } Summation {
children: Vec<Rc<RSprocess>>,
},
NondeterministicChoice {
children: Vec<Rc<RSprocess>>,
},
} }
impl RSprocess { impl RSprocess {
// TODO: remove all the clone() // TODO: remove all the clone()
pub fn concat(&self, new: &RSprocess) -> RSprocess { pub fn concat(&self, new: &RSprocess) -> RSprocess {
match (self, new) { match (self, new) {
(RSprocess::NondeterministicChoice{children: c1}, (
RSprocess::NondeterministicChoice{children: c2}) => { RSprocess::NondeterministicChoice { children: c1 },
RSprocess::NondeterministicChoice { RSprocess::NondeterministicChoice { children: c2 },
children: [c1.clone(), ) => RSprocess::NondeterministicChoice {
c2.clone()].concat() children: [c1.clone(), c2.clone()].concat(),
}
}, },
(RSprocess::NondeterministicChoice{children}, new) | (RSprocess::NondeterministicChoice { children }, new)
(new, RSprocess::NondeterministicChoice{children}) => { | (new, RSprocess::NondeterministicChoice { children }) => {
let mut new_children = children.clone(); let mut new_children = children.clone();
new_children.push(Rc::new(new.clone())); new_children.push(Rc::new(new.clone()));
RSprocess::NondeterministicChoice{ children: new_children }
},
(_, _) => {
RSprocess::NondeterministicChoice { RSprocess::NondeterministicChoice {
children: vec![Rc::new(self.clone()), children: new_children,
Rc::new(new.clone())]
} }
} }
(_, _) => RSprocess::NondeterministicChoice {
children: vec![Rc::new(self.clone()), Rc::new(new.clone())],
},
} }
} }
@ -216,11 +237,18 @@ impl RSprocess {
match el { match el {
Self::Nill => {} Self::Nill => {}
Self::RecursiveIdentifier { identifier: _ } => {} Self::RecursiveIdentifier { identifier: _ } => {}
Self::EntitySet { entities, next_process } => { Self::EntitySet {
entities,
next_process,
} => {
elements.push(entities); elements.push(entities);
queue.push_back(next_process); queue.push_back(next_process);
} }
Self::WaitEntity { repeat: _, repeated_process, next_process } => { Self::WaitEntity {
repeat: _,
repeated_process,
next_process,
} => {
queue.push_back(repeated_process); queue.push_back(repeated_process);
queue.push_back(next_process); queue.push_back(next_process);
} }
@ -245,17 +273,21 @@ impl RSprocess {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RSchoices { pub struct RSchoices {
context_moves: Vec<(Rc<RSset>, Rc<RSprocess>)> context_moves: Vec<(Rc<RSset>, Rc<RSprocess>)>,
} }
impl RSchoices { impl RSchoices {
pub fn new() -> Self { pub fn new() -> Self {
RSchoices{ context_moves: vec![] } RSchoices {
context_moves: vec![],
}
} }
pub fn new_not_empty() -> Self { pub fn new_not_empty() -> Self {
RSchoices{ context_moves: vec![(Rc::new(RSset::new()), RSchoices {
Rc::new(RSprocess::Nill))] } context_moves: vec![(Rc::new(RSset::new()),
Rc::new(RSprocess::Nill))],
}
} }
pub fn append(&mut self, a: &mut RSchoices) { pub fn append(&mut self, a: &mut RSchoices) {
@ -263,25 +295,29 @@ impl RSchoices {
} }
pub fn replace(&mut self, a: Rc<RSprocess>) { pub fn replace(&mut self, a: Rc<RSprocess>) {
self.context_moves = self.context_moves = self
self.context_moves .context_moves
.iter_mut() .iter_mut()
.map(|(c1, _)| (Rc::clone(c1), Rc::clone(&a))).collect::<Vec<_>>(); .map(|(c1, _)| (Rc::clone(c1), Rc::clone(&a)))
.collect::<Vec<_>>();
} }
pub fn shuffle(&mut self, choices: RSchoices) { pub fn shuffle(&mut self, choices: RSchoices) {
match (self.context_moves.is_empty(), choices.context_moves.is_empty()){ match (
self.context_moves.is_empty(),
choices.context_moves.is_empty(),
) {
(true, true) => {} (true, true) => {}
(true, false) => { self.context_moves = choices.context_moves } (true, false) => self.context_moves = choices.context_moves,
(false, true) => {} (false, true) => {}
(false, false) => { (false, false) => {
let mut new_self = vec![]; let mut new_self = vec![];
for item_self in &self.context_moves { for item_self in &self.context_moves {
for item_choices in &choices.context_moves { for item_choices in &choices.context_moves {
new_self.push( new_self.push((
(Rc::new(item_self.0.union(&item_choices.0)), Rc::new(item_self.0.union(&item_choices.0)),
Rc::new(item_self.1.concat(&item_choices.1))) Rc::new(item_self.1.concat(&item_choices.1)),
); ));
} }
} }
self.context_moves = new_self; self.context_moves = new_self;
@ -303,16 +339,19 @@ impl IntoIterator for RSchoices {
} }
} }
impl<const N: usize> From<[(Rc<RSset>, Rc<RSprocess>); N]> for RSchoices { impl<const N: usize> From<[(Rc<RSset>, Rc<RSprocess>); N]> for RSchoices {
fn from(arr: [(Rc<RSset>, Rc<RSprocess>); N]) -> Self { fn from(arr: [(Rc<RSset>, Rc<RSprocess>); N]) -> Self {
RSchoices{context_moves: arr.to_vec()} RSchoices {
context_moves: arr.to_vec(),
}
} }
} }
impl From<&[(Rc<RSset>, Rc<RSprocess>)]> for RSchoices { impl From<&[(Rc<RSset>, Rc<RSprocess>)]> for RSchoices {
fn from(arr: &[(Rc<RSset>, Rc<RSprocess>)]) -> Self { fn from(arr: &[(Rc<RSset>, Rc<RSprocess>)]) -> Self {
RSchoices{context_moves: arr.to_vec()} RSchoices {
context_moves: arr.to_vec(),
}
} }
} }
@ -332,7 +371,9 @@ pub struct RSenvironment {
impl RSenvironment { impl RSenvironment {
pub fn new() -> RSenvironment { pub fn new() -> RSenvironment {
RSenvironment{definitions: HashMap::new()} RSenvironment {
definitions: HashMap::new(),
}
} }
pub fn get(&self, k: IdType) -> Option<&RSprocess> { pub fn get(&self, k: IdType) -> Option<&RSprocess> {
@ -360,19 +401,25 @@ impl Default for RSenvironment {
impl<const N: usize> From<[(IdType, RSprocess); N]> for RSenvironment { impl<const N: usize> From<[(IdType, RSprocess); N]> for RSenvironment {
fn from(arr: [(IdType, RSprocess); N]) -> Self { fn from(arr: [(IdType, RSprocess); N]) -> Self {
RSenvironment{definitions: HashMap::from(arr)} RSenvironment {
definitions: HashMap::from(arr),
}
} }
} }
impl From<&[(IdType, RSprocess)]> for RSenvironment { impl From<&[(IdType, RSprocess)]> for RSenvironment {
fn from(arr: &[(IdType, RSprocess)]) -> Self { fn from(arr: &[(IdType, RSprocess)]) -> Self {
RSenvironment{definitions: HashMap::from_iter(arr.to_vec())} RSenvironment {
definitions: HashMap::from_iter(arr.to_vec()),
}
} }
} }
impl From<Vec<(IdType, RSprocess)>> for RSenvironment { impl From<Vec<(IdType, RSprocess)>> for RSenvironment {
fn from(arr: Vec<(IdType, RSprocess)>) -> Self { fn from(arr: Vec<(IdType, RSprocess)>) -> Self {
RSenvironment{definitions: HashMap::from_iter(arr)} RSenvironment {
definitions: HashMap::from_iter(arr),
}
} }
} }
@ -397,14 +444,18 @@ impl RSsystem {
} }
} }
pub fn from(delta: Rc<RSenvironment>, pub fn from(
delta: Rc<RSenvironment>,
available_entities: RSset, available_entities: RSset,
context_process: RSprocess, context_process: RSprocess,
reaction_rules: Rc<Vec<RSreaction>>) -> RSsystem { reaction_rules: Rc<Vec<RSreaction>>,
RSsystem { delta: Rc::clone(&delta), ) -> RSsystem {
RSsystem {
delta: Rc::clone(&delta),
available_entities, available_entities,
context_process, context_process,
reaction_rules: Rc::clone(&reaction_rules) } reaction_rules: Rc::clone(&reaction_rules),
}
} }
pub fn get_delta(&self) -> &Rc<RSenvironment> { pub fn get_delta(&self) -> &Rc<RSenvironment> {
@ -437,7 +488,8 @@ impl Default for RSsystem {
pub struct RSlabel { pub struct RSlabel {
pub available_entities: RSset, pub available_entities: RSset,
pub context: RSset, pub context: RSset,
pub t: RSset, /// union of available_entities and context pub t: RSset,
/// union of available_entities and context
pub reactants: RSset, pub reactants: RSset,
pub reactantsi: RSset, // reactants absent pub reactantsi: RSset, // reactants absent
pub inihibitors: RSset, pub inihibitors: RSset,
@ -447,42 +499,51 @@ pub struct RSlabel {
impl RSlabel { impl RSlabel {
pub fn new() -> Self { pub fn new() -> Self {
RSlabel { available_entities: RSset::new(), RSlabel {
available_entities: RSset::new(),
context: RSset::new(), context: RSset::new(),
t: RSset::new(), t: RSset::new(),
reactants: RSset::new(), reactants: RSset::new(),
reactantsi: RSset::new(), reactantsi: RSset::new(),
inihibitors: RSset::new(), inihibitors: RSset::new(),
ireactants: RSset::new(), ireactants: RSset::new(),
products: RSset::new() } products: RSset::new(),
}
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn from(available_entities: RSset, pub fn from(
available_entities: RSset,
context: RSset, context: RSset,
t: RSset, t: RSset,
reactants: RSset, reactants: RSset,
reactantsi: RSset, reactantsi: RSset,
inihibitors: RSset, inihibitors: RSset,
ireactants: RSset, ireactants: RSset,
products: RSset,) -> Self { products: RSset,
RSlabel { available_entities, ) -> Self {
RSlabel {
available_entities,
context, context,
t, t,
reactants, reactants,
reactantsi, reactantsi,
inihibitors, inihibitors,
ireactants, ireactants,
products } products,
}
} }
pub fn get_context(&self) -> (RSset, RSset, RSset) { pub fn get_context(&self) -> (RSset, RSset, RSset) {
// TODO remove clone? // TODO remove clone?
(self.available_entities.clone(), self.context.clone(), self.t.clone()) (
self.available_entities.clone(),
self.context.clone(),
self.t.clone(),
)
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// RSassertOp // RSassertOp
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -491,7 +552,7 @@ pub enum RSassertOp {
InW, InW,
InR, InR,
InI, InI,
InP InP,
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -504,7 +565,7 @@ pub enum RSassert {
Or(Vec<RSassert>), Or(Vec<RSassert>),
And(Vec<RSassert>), And(Vec<RSassert>),
Sub(RSset, RSassertOp), Sub(RSset, RSassertOp),
NonEmpty(RSassertOp) NonEmpty(RSassertOp),
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -518,5 +579,5 @@ pub enum RSBHML {
Or(Vec<RSBHML>), Or(Vec<RSBHML>),
And(Vec<RSBHML>), And(Vec<RSBHML>),
Diamond(Box<RSassert>, Box<RSBHML>), Diamond(Box<RSassert>, Box<RSBHML>),
Box(Box<RSassert>, Box<RSBHML>) Box(Box<RSassert>, Box<RSBHML>),
} }

View File

@ -10,7 +10,9 @@ pub struct TransitionsIterator<'a> {
} }
impl<'a> TransitionsIterator<'a> { impl<'a> TransitionsIterator<'a> {
pub fn from(system: &'a RSsystem) -> Result<TransitionsIterator<'a>, String> { pub fn from(
system: &'a RSsystem
) -> Result<TransitionsIterator<'a>, String> {
match unfold(system.get_delta(), system.get_context_process()) { match unfold(system.get_delta(), system.get_context_process()) {
Ok(o) => Ok(TransitionsIterator { Ok(o) => Ok(TransitionsIterator {
choices_iterator: o.into_iter(), choices_iterator: o.into_iter(),

View File

@ -1,8 +1,11 @@
#![allow(dead_code)] #![allow(dead_code)]
use super::structure::{ use super::structure::{RSchoices,
RSchoices, RSenvironment, RSlabel, RSprocess, RSset, RSsystem RSenvironment,
}; RSlabel,
RSprocess,
RSset,
RSsystem};
use super::support_structures::TransitionsIterator; use super::support_structures::TransitionsIterator;
use std::rc::Rc; use std::rc::Rc;
@ -85,14 +88,14 @@ pub fn unfold(
} }
pub fn iterator_transitions<'a>( pub fn iterator_transitions<'a>(
system: &'a RSsystem, system: &'a RSsystem
) -> Result<TransitionsIterator<'a>, String> { ) -> Result<TransitionsIterator<'a>, String> {
TransitionsIterator::from(system) TransitionsIterator::from(system)
} }
// see oneTransition, transition, smartTransition, smartOneTransition // see oneTransition, transition, smartTransition, smartOneTransition
pub fn one_transition( pub fn one_transition(
system: &RSsystem, system: &RSsystem
) -> Result<Option<(RSlabel, RSsystem)>, String> { ) -> Result<Option<(RSlabel, RSsystem)>, String> {
let mut tr = TransitionsIterator::from(system)?; let mut tr = TransitionsIterator::from(system)?;
Ok(tr.next()) Ok(tr.next())
@ -100,14 +103,16 @@ pub fn one_transition(
// see allTransitions, smartAllTransitions // see allTransitions, smartAllTransitions
pub fn all_transitions( pub fn all_transitions(
system: &RSsystem, system: &RSsystem
) -> Result<Vec<(RSlabel, RSsystem)>, String> { ) -> Result<Vec<(RSlabel, RSsystem)>, String> {
let tr = TransitionsIterator::from(system)?; let tr = TransitionsIterator::from(system)?;
Ok(tr.collect::<Vec<_>>()) Ok(tr.collect::<Vec<_>>())
} }
// see oneTarget, smartOneTarget, target, smartTarget // see oneTarget, smartOneTarget, target, smartTarget
pub fn target(system: &RSsystem) -> Result<(i64, RSset), String> { pub fn target(
system: &RSsystem
) -> Result<(i64, RSset), String> {
let current = one_transition(system)?; let current = one_transition(system)?;
if current.is_none() { if current.is_none() {
return Ok((0, system.get_available_entities().clone())); return Ok((0, system.get_available_entities().clone()));

View File

@ -47,10 +47,13 @@ impl Translator {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
use super::{frequency::Frequency, structure::{ use super::{
RSassert, RSassertOp, RSchoices, RSenvironment, RSlabel, RSprocess, frequency::Frequency,
RSreaction, RSset, RSsystem, RSBHML, structure::{
}}; RSBHML, RSassert, RSassertOp, RSchoices, RSenvironment, RSlabel,
RSprocess, RSreaction, RSset, RSsystem,
},
};
use std::fmt; use std::fmt;
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
@ -100,7 +103,7 @@ pub enum WithTranslator<'a> {
Frequency { Frequency {
translator: &'a Translator, translator: &'a Translator,
frequency: &'a Frequency, frequency: &'a Frequency,
} },
} }
macro_rules! from_RS { macro_rules! from_RS {
@ -125,7 +128,12 @@ impl<'a> WithTranslator<'a> {
from_RS!(from_RSchoices, RSchoices, choices, RSchoices); from_RS!(from_RSchoices, RSchoices, choices, RSchoices);
from_RS!(from_RSenvironment, RSenvironment, environment, RSenvironment); from_RS!(
from_RSenvironment,
RSenvironment,
environment,
RSenvironment
);
from_RS!(from_RSsystem, RSsystem, system, RSsystem); from_RS!(from_RSsystem, RSsystem, system, RSsystem);
@ -216,8 +224,11 @@ fn print_process(
let mut it = children.iter().peekable(); let mut it = children.iter().peekable();
while let Some(child) = it.next() { while let Some(child) = it.next() {
if it.peek().is_none() { if it.peek().is_none() {
write!(f, "{}", write!(
WithTranslator::from_RSprocess(translator, child))?; f,
"{}",
WithTranslator::from_RSprocess(translator, child)
)?;
} else { } else {
write!( write!(
f, f,
@ -233,11 +244,17 @@ fn print_process(
let mut it = children.iter().peekable(); let mut it = children.iter().peekable();
while let Some(child) = it.next() { while let Some(child) = it.next() {
if it.peek().is_none() { if it.peek().is_none() {
write!(f, "{}", write!(
WithTranslator::from_RSprocess(translator, child))?; f,
"{}",
WithTranslator::from_RSprocess(translator, child)
)?;
} else { } else {
write!(f, "{}, ", write!(
WithTranslator::from_RSprocess(translator, child))?; f,
"{}, ",
WithTranslator::from_RSprocess(translator, child)
)?;
} }
} }
write!(f, "]") write!(f, "]")
@ -327,7 +344,9 @@ fn print_label(
translator: &Translator, translator: &Translator,
label: &RSlabel label: &RSlabel
) -> fmt::Result { ) -> fmt::Result {
write!(f, "{{available_entities: {}, context: {}, t: {}, reactants: {}, reactantsi: {}, inihibitors: {}, ireactants: {}, products: {}}}", write!(
f,
"{{available_entities: {}, context: {}, t: {}, reactants: {}, reactantsi: {}, inihibitors: {}, ireactants: {}, products: {}}}",
WithTranslator::from_RSset(translator, &label.available_entities), WithTranslator::from_RSset(translator, &label.available_entities),
WithTranslator::from_RSset(translator, &label.context), WithTranslator::from_RSset(translator, &label.context),
WithTranslator::from_RSset(translator, &label.t), WithTranslator::from_RSset(translator, &label.t),
@ -390,9 +409,9 @@ fn print_frequency(
while let Some((e, freq)) = freq_it.next() { while let Some((e, freq)) = freq_it.next() {
write!(f, "{} -> ", translator.decode(*e))?; write!(f, "{} -> ", translator.decode(*e))?;
let mut iter = freq.iter() let mut iter = freq
.zip(frequency.totals.iter() .iter()
.zip(frequency.weights.iter())) .zip(frequency.totals.iter().zip(frequency.weights.iter()))
.peekable(); .peekable();
let mut total_freq = 0.; let mut total_freq = 0.;
@ -422,28 +441,50 @@ fn print_frequency(
impl<'a> fmt::Display for WithTranslator<'a> { impl<'a> fmt::Display for WithTranslator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
WithTranslator::RSset { translator, set, } => WithTranslator::RSset {
print_set(f, translator, set), translator,
WithTranslator::RSreaction { translator, reaction, } => set
print_reaction(f, translator, reaction), } => print_set(f, translator, set),
WithTranslator::RSprocess { translator, process, } => WithTranslator::RSreaction {
print_process(f, translator, process), translator,
WithTranslator::RSchoices { translator, choices, } => reaction,
print_choices(f, translator, choices), } => print_reaction(f, translator, reaction),
WithTranslator::RSenvironment { translator, environment, } => WithTranslator::RSprocess {
print_environment(f, translator, environment), translator,
WithTranslator::RSsystem { translator, system, } => process,
print_system(f, translator, system), } => print_process(f, translator, process),
WithTranslator::RSlabel { translator, label, } => WithTranslator::RSchoices {
print_label(f, translator, label), translator,
WithTranslator::RSassertOp { translator, assert_op, } => choices,
print_assert_op(f, translator, assert_op), } => print_choices(f, translator, choices),
WithTranslator::RSassert { translator, assert, } => WithTranslator::RSenvironment {
print_assert(f, translator, assert), translator,
WithTranslator::RSBHML { translator, bhml, } => environment,
print_bhml(f, translator, bhml), } => print_environment(f, translator, environment),
WithTranslator::Frequency { translator, frequency } => WithTranslator::RSsystem {
print_frequency(f, translator, frequency), translator,
system
} => print_system(f, translator, system),
WithTranslator::RSlabel {
translator,
label
} => print_label(f, translator, label),
WithTranslator::RSassertOp {
translator,
assert_op,
} => print_assert_op(f, translator, assert_op),
WithTranslator::RSassert {
translator,
assert
} => print_assert(f, translator, assert),
WithTranslator::RSBHML {
translator,
bhml
} => print_bhml(f, translator, bhml),
WithTranslator::Frequency {
translator,
frequency,
} => print_frequency(f, translator, frequency),
} }
} }
} }

View File

@ -1,4 +1,4 @@
Environment: [x = {a}.y, y =({a}.x + {b}.y)] Environment: [x = {a}.y, y =({a}.nill + {b}.nill)]
Initial Entities: {a, b} Initial Entities: {a, b}
Context: [({a,b}.{a}.{a,c}.x + {a,b}.{a}.{a}.nil)] Context: [({a,b}.{a}.{a,c}.x + {a,b}.{a}.{a}.nil)]
Reactions: ([r: {a,b}, i: {c}, p: {b}]) Reactions: ([r: {a,b}, i: {c}, p: {b}])