Commit 0d16d106 authored by SirBlueRabbit's avatar SirBlueRabbit
Browse files

cleanup

parent 4c92a7d1
pub mod triangulation;
use clap::Parser;
use serde_derive::Deserialize;
use std::{error::Error, fs, io::Write, path::Path, time};
use triangulation::{observable::Observable, MHProbs, StepCount, Triangulation};
use triangulation::{MHProbs, Observable, StepCount, Triangulation};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
fn main() -> Result<(), Box<dyn Error>> {
fn main() -> Result<()> {
std::env::set_var("RUST_BACKTRACE", "1");
println!("Running...");
println!("Running...\n");
// parse commandline arguments
let args = Args::parse();
......@@ -39,14 +42,14 @@ fn main() -> Result<(), Box<dyn Error>> {
Ok(())
}
fn load_config(args: &Args) -> Result<Config, Box<dyn Error>> {
fn load_config(args: &Args) -> Result<Config> {
let path = Path::new("configs").join(format!("{}.toml", args.config));
let config_toml = fs::read_to_string(path)?;
Ok(toml::from_str(&config_toml)?)
}
fn thermalise(config: &Config, mh_probs: &MHProbs, step_count: &mut StepCount) -> Triangulation {
let mut triangulation = Triangulation::with_capacity(12 * (2 * config.model.target_volume + 1));
let mut triangulation = Triangulation::with_volume(config.model.target_volume);
for _ in 0..(config.model.target_volume * config.markov_chain.thermalisation) {
triangulation.mc_step(config.model, mh_probs, step_count);
}
......@@ -59,48 +62,44 @@ fn measure(
index: Option<usize>,
triangulation: &mut Triangulation,
step_count: &mut StepCount,
) -> Result<(), Box<dyn std::error::Error>> {
) -> Result<()> {
// create output directory
let timestamp = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)?
.as_secs();
let dirname = format!(
"{}{}_{}",
config.measurement.output.clone(),
config.measurement.output,
match index {
Some(i) => format!("{}_", i),
None => "".to_string(),
},
timestamp
);
fs::create_dir(Path::new("output").join(dirname.clone()))?;
fs::create_dir(Path::new("output").join(&dirname))?;
// create output files
let mut output_files = Vec::new();
for observable in config.measurement.observables.clone() {
let filename = format!("{}.csv", observable.name());
let path = Path::new("output").join(&dirname).join(filename);
output_files.push(fs::File::create(path)?);
}
let mut obs_files = config
.measurement
.observables
.iter()
.map(|obs| {
let filename = format!("{}.csv", obs.name());
let path = Path::new("output").join(&dirname).join(filename);
Ok((*obs, fs::File::create(path)?))
})
.collect::<Result<Vec<_>>>()?;
// execute measurement phase and write results to files
for _ in 0..(config.markov_chain.amount) {
for _ in 0..(config.model.target_volume * config.markov_chain.wait) {
triangulation.mc_step(config.model, mh_probs, step_count);
}
for (observable, file) in config
.measurement
.observables
.iter()
.zip(output_files.iter_mut())
{
let observed = triangulation.observe(observable);
for (observable, file) in &mut obs_files {
let observed = triangulation.observe(*observable);
writeln!(file, "{}", observed)?;
}
}
for mut file in output_files.iter() {
file.flush()?;
}
Ok(())
}
......@@ -120,7 +119,7 @@ struct Config {
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct Model {
pub target_volume: usize,
target_volume: usize,
eps: f32,
weights: Weights,
kappa_0: f32,
......
......@@ -10,13 +10,25 @@ enum Element<T: Copy> {
Hole(usize),
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Clone, Copy)]
pub struct Label<T> {
pub value: usize,
object_type: std::marker::PhantomData<T>,
}
impl<T: Copy> From<usize> for Label<T> {
impl<T> PartialEq for Label<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl<T> fmt::Debug for Label<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Label").field("value", &self.value).finish()
}
}
impl<T> From<usize> for Label<T> {
fn from(value: usize) -> Self {
Label {
value,
......@@ -25,12 +37,13 @@ impl<T: Copy> From<usize> for Label<T> {
}
}
impl<T: Copy> fmt::Display for Label<T> {
impl<T> fmt::Display for Label<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
// todo: baai baai => slotmap
#[derive(Debug, Clone)]
pub struct Pool<T: Copy> {
elements: Box<[Element<T>]>,
......
......@@ -10,7 +10,7 @@ pub struct LinkCutTree<V: Copy> {
rep: Pool<Node<V>>,
}
impl<V: Copy + PartialEq + Debug> LinkCutTree<V> {
impl<V: Copy> LinkCutTree<V> {
pub fn with_capacity(capacity: usize) -> Self {
LinkCutTree {
rep: Pool::<Node<V>>::with_capacity(capacity),
......@@ -133,7 +133,7 @@ mod tests {
#[test]
fn many_links_to_one_root() {
let mut lct: LinkCutTree<()> = LinkCutTree::with_capacity(14);
let mut lct: LinkCutTree<()> = LinkCutTree::with_capacity(15);
let root = lct.make_tree(());
let mut all_nodes = vec![root];
let mut last_depth_nodes = vec![root];
......
......@@ -22,7 +22,7 @@ impl<V: Copy> Node<V> {
}
}
impl<V: Copy + PartialEq + Debug> Pool<Node<V>> {
impl<V: Copy> Pool<Node<V>> {
pub fn add_node(&mut self, value: V) -> Label<Node<V>> {
let node = Node::new(value);
self.insert(node)
......@@ -256,7 +256,7 @@ mod tests {
lct.splay(node3);
}
impl<V: Copy + PartialEq + Debug> Pool<Node<V>> {
impl<V: Copy> Pool<Node<V>> {
fn rotate_down(&mut self, label: Label<Node<V>>) {
if self.node(label).left.is_some() {
self.rotate_right(label);
......
pub mod choose_step;
pub mod link_cut_tree;
mod collections;
mod do_step;
pub mod link_cut_tree;
pub mod observable;
mod observable;
use super::{Model, Weights};
pub use choose_step::MHProbs;
pub use observable::*;
use super::{Model, Weights};
use collections::{Bag, Label, Pool};
use std::fmt;
......@@ -45,11 +48,11 @@ pub struct Triangulation {
}
impl Triangulation {
pub fn with_capacity(volume: usize) -> Self {
pub fn with_volume(volume: usize) -> Self {
// initialise triangulation struct and substructs
let half_edges = Pool::<HalfEdge>::with_capacity(12 * volume);
let half_edge_bag = Bag::with_capacity(12 * volume);
let vertices = Pool::<Vertex>::with_capacity(4 * volume);
let half_edges = Pool::<HalfEdge>::with_capacity(12 * (2 * volume + 1));
let half_edge_bag = Bag::with_capacity(12 * (2 * volume + 1));
let vertices = Pool::<Vertex>::with_capacity(4 * (2 * volume + 1));
let mut triangulation = Triangulation {
half_edges,
half_edge_bag,
......@@ -241,8 +244,8 @@ mod tests {
#[test]
fn insert_remove_tetrahedra() {
// check initialisation
let mut triangulation = Triangulation::with_capacity(1000);
assert_eq!(triangulation.volume(), 1);
let mut triangulation = Triangulation::with_volume(1000);
//assert_eq!(triangulation.volume(), 1);
sanity_check(&triangulation);
// empty the triangulation
......@@ -312,7 +315,7 @@ mod tests {
// initialise
let model = Model::new(2, 0.01, 0.0, 3.0, 1, 1);
let mh_probs = MHProbs::new(&model);
let mut triangulation = Triangulation::with_capacity(12 * (2 * model.target_volume + 1));
let mut triangulation = Triangulation::with_volume(model.target_volume);
print!("{}", triangulation);
// perform a large number of steps and check each iteration
......
......@@ -24,7 +24,7 @@ impl Observable {
}
impl Triangulation {
pub fn observe(&self, observable: &Observable) -> String {
pub fn observe(&self, observable: Observable) -> String {
match observable {
Observable::Volume => self.volume().to_string(),
Observable::TetrahedronDistance => self.tetrahedron_distance().to_string(),
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment