finishing frequency

This commit is contained in:
elvis
2025-07-02 17:27:36 +02:00
parent f3ba949b82
commit fb3256c4a7
4 changed files with 120 additions and 26 deletions

View File

@ -1,6 +1,6 @@
#![allow(dead_code)] #![allow(dead_code)]
use crate::rsprocess::structure::RSsystem; use crate::rsprocess::structure::{RSset, RSsystem};
use crate::rsprocess::translator; use crate::rsprocess::translator;
use crate::rsprocess::translator::Translator; use crate::rsprocess::translator::Translator;
use crate::rsprocess::{frequency, perpetual, statistics, transitions}; use crate::rsprocess::{frequency, perpetual, statistics, transitions};
@ -14,7 +14,11 @@ use std::io::prelude::*;
// the code // the code
use super::grammar; use super::grammar;
fn read_system(translator: &mut Translator, path: std::path::PathBuf) -> std::io::Result<RSsystem> { fn read_file<T, F>(
translator: &mut Translator,
path: std::path::PathBuf,
parser: F
) -> std::io::Result<T> where F: Fn(&mut Translator, String) -> T {
// 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);
@ -22,13 +26,25 @@ fn read_system(translator: &mut Translator, path: std::path::PathBuf) -> std::io
buf_reader.read_to_string(&mut contents)?; buf_reader.read_to_string(&mut contents)?;
// parse // parse
let result = grammar::SystemParser::new() let result = parser(translator, contents);
.parse(translator, &contents)
.unwrap();
Ok(result) Ok(result)
} }
fn parser_system(translator: &mut Translator, contents: String) -> RSsystem {
grammar::SystemParser::new()
.parse(translator, &contents)
.unwrap()
}
fn parser_experiment(translator: &mut Translator, contents: String) -> (Vec<u32>, Vec<RSset>) {
grammar::ExperimentParser::new()
.parse(translator, &contents)
.unwrap()
}
// equivalent main_do(stat) or main_do(stat, MissingE) // equivalent main_do(stat) or main_do(stat, MissingE)
pub fn stats() -> std::io::Result<()> { pub fn stats() -> std::io::Result<()> {
let mut translator = Translator::new(); let mut translator = Translator::new();
@ -36,7 +52,7 @@ pub fn stats() -> std::io::Result<()> {
let mut path = env::current_dir()?; let mut path = env::current_dir()?;
// file to read is inside testing/ // file to read is inside testing/
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_file(&mut translator, path, parser_system)?;
// print statistics to screan // print statistics to screan
println!("{}", statistics::of_RSsystem(&translator, &system)); println!("{}", statistics::of_RSsystem(&translator, &system));
@ -56,7 +72,7 @@ pub fn target() -> std::io::Result<()> {
let mut path = env::current_dir()?; let mut path = env::current_dir()?;
// file to read is inside testing/ // file to read is inside testing/
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_file(&mut translator, path, parser_system)?;
// 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) {
@ -83,7 +99,7 @@ pub fn run() -> std::io::Result<()> {
let mut path = env::current_dir()?; let mut path = env::current_dir()?;
// file to read is inside testing/ // file to read is inside testing/
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_file(&mut translator, path, parser_system)?;
// 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) {
@ -110,10 +126,12 @@ pub fn hoop() -> std::io::Result<()> {
let mut path = env::current_dir()?; let mut path = env::current_dir()?;
// file to read is inside testing/ // file to read is inside testing/
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_file(&mut translator, path, parser_system)?;
// 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 => { None => {
println!("No loop found."); println!("No loop found.");
@ -130,13 +148,14 @@ pub fn hoop() -> std::io::Result<()> {
Ok(()) Ok(())
} }
// equivalent to main_do(freq, PairList)
pub fn freq() -> std::io::Result<()> { pub fn freq() -> std::io::Result<()> {
let mut translator = Translator::new(); let mut translator = Translator::new();
let mut path = env::current_dir()?; let mut path = env::current_dir()?;
// file to read is inside testing/ // file to read is inside testing/
path = path.join("testing/first.system"); path = path.join("testing/first.system");
let system = read_system(&mut translator, path)?; let system = read_file(&mut translator, path, parser_system)?;
let res = match frequency::naive_frequency(&system) { let res = match frequency::naive_frequency(&system) {
Ok(f) => f, Ok(f) => f,
@ -153,3 +172,60 @@ pub fn freq() -> std::io::Result<()> {
Ok(()) Ok(())
} }
// equivalent to main_do(limitfreq, PairList)
pub fn limit_freq() -> std::io::Result<()> {
let mut translator = Translator::new();
let mut path = env::current_dir()?;
// file to read is inside testing/
path = path.join("testing/first.system");
let system = read_file(&mut translator, path, parser_system)?;
path = env::current_dir()?;
path = path.join("testing/first.experiment");
let (_, sets) = read_file(&mut translator, path, parser_experiment)?;
let res = match frequency::limit_frequency(&sets,
system.get_reaction_rules(),
system.get_available_entities()) {
Some(e) => e,
None => {return Ok(());}
};
println!(
"Frequency of encountered symbols:\n{}",
translator::FrequencyDisplay::from(&translator, &res)
);
Ok(())
}
// equivalent to main_do(fastfreq, PairList)
pub fn fast_freq() -> std::io::Result<()> {
let mut translator = Translator::new();
let mut path = env::current_dir()?;
// file to read is inside testing/
path = path.join("testing/first.system");
let system = read_file(&mut translator, path, parser_system)?;
path = env::current_dir()?;
path = path.join("testing/first.experiment");
let (weights, sets) = read_file(&mut translator, path, parser_experiment)?;
let res = match frequency::fast_frequency(&sets,
system.get_reaction_rules(),
system.get_available_entities(),
&weights) {
Some(e) => e,
None => {return Ok(());}
};
println!(
"Frequency of encountered symbols:\n{}",
translator::FrequencyDisplay::from(&translator, &res)
);
Ok(())
}

View File

@ -13,13 +13,17 @@ fn main() -> std::io::Result<()> {
// examples::stats()?; // examples::stats()?;
examples::freq()?; // examples::freq()?;
examples::hoop()?; // examples::hoop()?;
examples::target()?; // examples::target()?;
examples::run()?; // examples::run()?;
examples::limit_freq()?;
examples::fast_freq()?;
Ok(()) Ok(())
} }

View File

@ -26,7 +26,11 @@ impl Frequency {
pub fn add(&mut self, e: &RSset, run: usize) { pub fn add(&mut self, e: &RSset, run: usize) {
for &el in e.iter() { for &el in e.iter() {
self.frequency_map.entry(el).or_insert(vec![0; run + 1])[run] += 1 let entry = self.frequency_map.entry(el).or_insert(vec![0; run + 1]);
if entry.len() < run +1 {
entry.resize(run + 1, 0);
}
entry[run] += 1
} }
// TODO resize clones all prev values, replace with in place method // TODO resize clones all prev values, replace with in place method
if self.totals.len() < run + 1 { if self.totals.len() < run + 1 {

View File

@ -27,7 +27,7 @@ Num: i64 = {
}; };
// macro for matching sequence of patterns with C as separator // macro for matching sequence of patterns with C as separator
Separeted<T, C>: Vec<T> = { Separated<T, C>: Vec<T> = {
<mut v:(<T> C)+> <e:T?> => match e { <mut v:(<T> C)+> <e:T?> => match e {
None => v, None => v,
Some(e) => { Some(e) => {
@ -47,7 +47,7 @@ pub Set: RSset = {
Set_of_entities: RSset = { Set_of_entities: RSset = {
"{" "}" => RSset::from(vec![]), "{" "}" => RSset::from(vec![]),
"{" <t: Literal> "}" => RSset::from(vec![translator.encode(t)]), "{" <t: Literal> "}" => RSset::from(vec![translator.encode(t)]),
"{" <t: Separeted<Literal, ",">> "}" => "{" <t: Separated<Literal, ",">> "}" =>
RSset::from(t.into_iter().map(|t| translator.encode(t)).collect::<Vec<_>>()) RSset::from(t.into_iter().map(|t| translator.encode(t)).collect::<Vec<_>>())
}; };
@ -59,7 +59,7 @@ Set_of_entities: RSset = {
pub Reactions: Vec<RSreaction> = { pub Reactions: Vec<RSreaction> = {
"(" ")" => vec![], "(" ")" => vec![],
"(" <r: Reaction> ")" => vec![r], "(" <r: Reaction> ")" => vec![r],
"(" <s: Separeted<Reaction, ";">> ")" => s "(" <s: Separated<Reaction, ";">> ")" => s
} }
Reaction: RSreaction = { Reaction: RSreaction = {
@ -75,7 +75,7 @@ pub Context: RSprocess = {
"[" "]" => RSprocess::NondeterministicChoice{ children: vec![] }, "[" "]" => RSprocess::NondeterministicChoice{ children: vec![] },
"[" <t: CTX_process> "]" => "[" <t: CTX_process> "]" =>
RSprocess::NondeterministicChoice{children: vec![Rc::new(t)]}, RSprocess::NondeterministicChoice{children: vec![Rc::new(t)]},
"[" <t: Separeted<Boxed_CTX_process, ",">> "]" => "[" <t: Separated<Boxed_CTX_process, ",">> "]" =>
RSprocess::NondeterministicChoice{ children: t } RSprocess::NondeterministicChoice{ children: t }
}; };
@ -87,7 +87,7 @@ CTX_process: RSprocess = {
<c: Set_of_entities> "." <k: CTX_process> => <c: Set_of_entities> "." <k: CTX_process> =>
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: Separated<CTX_process, "+">> ")" =>
RSprocess::Summation{ RSprocess::Summation{
children: k.into_iter().map(Rc::new).collect::<Vec<_>>() children: k.into_iter().map(Rc::new).collect::<Vec<_>>()
}, },
@ -108,7 +108,7 @@ CTX_process: RSprocess = {
pub Environment: Box<RSenvironment> = { pub Environment: Box<RSenvironment> = {
"[" "]" => Box::new(RSenvironment::new()), "[" "]" => Box::new(RSenvironment::new()),
"[" <t:Env_term> "]" => Box::new(RSenvironment::from(vec![t])), "[" <t:Env_term> "]" => Box::new(RSenvironment::from(vec![t])),
"[" <t: Separeted<Env_term, ",">> "]" => Box::new(RSenvironment::from(t)) "[" <t: Separated<Env_term, ",">> "]" => Box::new(RSenvironment::from(t))
}; };
Env_term: (IdType, RSprocess) = { Env_term: (IdType, RSprocess) = {
@ -127,8 +127,8 @@ Formula_Assert: RSassert = {
"-" <f: Formula_Assert> => RSassert::Not(Box::new(f)), "-" <f: Formula_Assert> => RSassert::Not(Box::new(f)),
"(" <f1: Formula_Assert> "^" <f2: Formula_Assert> ")" => "(" <f1: Formula_Assert> "^" <f2: Formula_Assert> ")" =>
RSassert::Xor(Box::new(f1), Box::new(f2)), RSassert::Xor(Box::new(f1), Box::new(f2)),
"(" <f: Separeted<Formula_Assert, "\\/">> ")" => RSassert::Or(f), "(" <f: Separated<Formula_Assert, "\\/">> ")" => RSassert::Or(f),
"(" <f: Separeted<Formula_Assert, "/\\">> ")" => RSassert::And(f), "(" <f: Separated<Formula_Assert, "/\\">> ")" => RSassert::And(f),
<c: Set_of_entities> "inW" => RSassert::Sub(c, RSassertOp::InW), <c: Set_of_entities> "inW" => RSassert::Sub(c, RSassertOp::InW),
<c: Set_of_entities> "inR" => RSassert::Sub(c, RSassertOp::InR), <c: Set_of_entities> "inR" => RSassert::Sub(c, RSassertOp::InR),
<c: Set_of_entities> "inI" => RSassert::Sub(c, RSassertOp::InI), <c: Set_of_entities> "inI" => RSassert::Sub(c, RSassertOp::InI),
@ -149,8 +149,8 @@ pub BHML: Box<RSBHML> = {
Formula_BHML: RSBHML = { Formula_BHML: RSBHML = {
"true" => RSBHML::True, "true" => RSBHML::True,
"false" => RSBHML::False, "false" => RSBHML::False,
"(" <g: Separeted<Formula_BHML, "\\/">> ")" => RSBHML::Or(g), "(" <g: Separated<Formula_BHML, "\\/">> ")" => RSBHML::Or(g),
"(" <g: Separeted<Formula_BHML, "/\\">> ")" => RSBHML::And(g), "(" <g: Separated<Formula_BHML, "/\\">> ")" => RSBHML::And(g),
"<" <f: Formula_Assert> ">" <g: Formula_BHML> => "<" <f: Formula_Assert> ">" <g: Formula_BHML> =>
RSBHML::Diamond(Box::new(f), Box::new(g)), RSBHML::Diamond(Box::new(f), Box::new(g)),
"[" <f: Formula_Assert> "]" <g: Formula_BHML> => "[" <f: Formula_Assert> "]" <g: Formula_BHML> =>
@ -175,3 +175,13 @@ pub System: RSsystem = {
context_process, context_process,
Rc::new(reaction_rules)) Rc::new(reaction_rules))
} }
// experiment
// an experiment is composed by a sequence of weights and a sequence of sets of
// entities of equal length.
pub Experiment: (Vec<u32>, Vec<RSset>) = {
"Weights:" <w: Separated<Num, ",">>
"Sets:" <s: Separated<Set_of_entities, ",">>
=> (w.into_iter().map(|x| x as u32).collect::<Vec<_>>(), s)
}