5 Commits

Author SHA1 Message Date
herel 5dc9a4574b configurable width & height 2022-05-05 21:20:52 +02:00
herel b8ea034a84 add parser and timings 2022-05-05 20:54:49 +02:00
Maxluli bc13c48302 Ready to compare with C# 2022-05-03 14:47:57 +02:00
Maxluli ced3a93412 Release V1.0 2022-05-03 14:46:23 +02:00
Maxluli 3fe4ddc2ee Fixed bug appeared in the last merge 2022-05-03 14:36:18 +02:00
8 changed files with 280 additions and 939 deletions
Generated
+4 -26
View File
@@ -104,9 +104,9 @@ dependencies = [
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.9.1" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]] [[package]]
name = "heck" name = "heck"
@@ -125,9 +125,9 @@ dependencies = [
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.6.2" version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"hashbrown", "hashbrown",
@@ -157,27 +157,6 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
[[package]]
name = "parameterized"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33543d17fe882d6d8835b193d2c7f0fdc3317645ca7510aaaf6103848498381c"
dependencies = [
"parameterized-macro",
]
[[package]]
name = "parameterized-macro"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24792407b50d07456abc531c1bc629a642a005d3b292c97dc23bf5bff1ad9cea"
dependencies = [
"indexmap",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.16" version = "0.2.16"
@@ -277,7 +256,6 @@ version = "0.1.0"
dependencies = [ dependencies = [
"clap", "clap",
"console", "console",
"parameterized",
"rand", "rand",
] ]
+1 -2
View File
@@ -6,5 +6,4 @@ edition = "2021"
[dependencies] [dependencies]
console = "0.15.0" console = "0.15.0"
rand = "0.8.5" rand = "0.8.5"
parameterized = "1.0.0" clap = { version = "3.1.15", features = ["derive"] }
clap = { version = "3.0", features = ["derive"] }
+9
View File
@@ -0,0 +1,9 @@
# Rusty Propagation
Run :
```
cargo run -q
```
Speed run :
```
cargo run -q --release
```
+15 -14
View File
@@ -1,24 +1,25 @@
// use crate::prelude::*; // use crate::prelude::*;
// pub const MUTATION_TRAIT_INCREASE_PROBABILITY:i32 = 50; // pub const MUTATION_TRAIT_INCREASE_PROBABILITY:i32 = 50;
// pub const MUTATION_TRAIT_CHANGE_AMOUNT:i32 = 20; // pub const MUTATION_TRAIT_CHANGE_AMOUNT:i32 = 20;
// #[derive(Debug)] #[derive(Debug)]
pub struct Disease { pub struct Disease {
pub infection_rate: i32, pub infection_rate:u32,
pub curing_rate: i32, pub curing_rate:u32,
pub death_rate: i32, pub death_rate:u32,
pub traits: Vec<i32>, pub traits: Vec<u32>,
pub name: String, pub name: String,
} }
impl Disease { impl Disease{
pub fn new(infection_r: i32, curing_r: i32, death_r: i32, the_name: String) -> Self { pub fn new(infection_r:u32,curing_r:u32,death_r:u32,the_name:String) -> Self{
Self { Self{
infection_rate: infection_r, infection_rate : infection_r,
curing_rate: curing_r, curing_rate : curing_r,
death_rate: death_r, death_rate : death_r,
name: the_name, name : the_name,
traits: vec![infection_r, curing_r, death_r], traits : vec![infection_r,curing_r,death_r],
} }
} }
// pub fn mutate(&mut self){ // pub fn mutate(&mut self){
@@ -38,4 +39,4 @@ impl Disease {
// self.traits[i] = new_ratio as u32; // self.traits[i] = new_ratio as u32;
// } // }
// } // }
} }
+22 -22
View File
@@ -1,33 +1,33 @@
// use crate::prelude::*; // use crate::prelude::*;
// #[derive(Copy, Clone, PartialEq)] // #[derive(Copy, Clone, PartialEq)]
#[derive(PartialEq, Debug, Clone)] #[derive(PartialEq)]
pub enum State { pub enum State {
Normal, Normal,
Infected, Infected,
Dead, Dead,
Immune, Immune,
} }
#[derive(Clone)] // #[derive(Clone)]
pub struct Human { pub struct Human {
pub present_state: State, pub present_state : State,
pub x: i32, pub x : i32,
pub y: i32, pub y : i32,
} }
// impl Human { impl Human{
// // humans with state "Normal" // humans with state "Normal"
// pub fn new(pos_x: i32, pos_y: i32) -> Self { pub fn new(pos_x :i32, pos_y :i32) -> Self{
// Self { Self{
// present_state: State::Normal, present_state : State::Normal,
// x: pos_x, x : pos_x,
// y: pos_y, y : pos_y
// } }
// } }
// // pub fn new_empty() -> Self{ // pub fn new_empty() -> Self{
// // Self{ // Self{
// // present_state:State::Normal, // present_state:State::Normal,
// // x : 0, // x : 0,
// // y : 0, // y : 0,
// // } // }
// // } // }
// } }
+42 -31
View File
@@ -1,53 +1,64 @@
use clap::Parser;
mod disease;
mod human; mod human;
mod disease;
mod population; mod population;
mod prelude { mod prelude {
pub use crate::disease::*;
pub use crate::human::*; pub use crate::human::*;
pub use crate::disease::*;
pub use crate::population::*; pub use crate::population::*;
pub use console::style;
pub use console::Term;
pub use rand::Rng; pub use rand::Rng;
pub const CORRECTED_PERCENTAGE: i32 = 101; pub use console::Term;
pub use console::style;
pub const CORRECTED_PERCENTAGE:i32 = 101;
} }
use prelude::*; use prelude::*;
use clap::Parser;
use std::time::Instant;
#[derive(Parser)] #[derive(Parser, Debug)]
struct Cli { struct Args {
/// Number of threads to use /// Display stats after each propagation
threads: usize, #[clap(short, long)]
display: bool,
/// Width of humans grid in population
#[clap(short, long, default_value_t = 1000)]
width: i32,
/// Height of humans grid in population
#[clap(short, long, default_value_t = 1000)]
height: i32,
} }
fn main() { fn main() {
let args = Cli::parse(); let args = Args::parse();
let term = Term::stdout();
term.write_line("********** Rusty Propagation (Console) 2022 **********")
.expect("Oops Looks like we have a problem here...");
let disease = Disease::new(20, 10, 5, String::from("Covid 44")); let term = Term::stdout();
let mut population = Population::new(20, 10, 5, 1000, 1000, disease); term.write_line("********** Rusty Propagation (Console) 2022 **********").expect("Oops Looks like we have a problem here...");
term.write_line("Press any key to start the propagation").expect("Oops Looks like we have a problem here...");
let disease = Disease::new(20,10,5,String::from("Covid 44"));
let mut population = Population::new(20,10,5,args.width,args.height,disease);
//population.change_disease(disease); //population.change_disease(disease);
println!("Before Filling");
//population.display();
population.generate();
println!("After Filling"); println!("After Filling");
//population.display(); //population.display();
//population.display(); println!("After Propagation");
let mut stats: [i32; 4]; let mut stats: [i32;4];
// = [0,0,0,0]; // = [0,0,0,0];
let mut counter: u32 = 0; let mut counter:u32 = 0;
loop { let now = Instant::now();
loop{
counter += 1; counter += 1;
stats = population.propagate(args.threads); stats=population.propagate();
//population.display(); //population.display();
println!( if args.display {
"Normal: {} Infecteds: {} Immunes: {} Deads: {}", println!("Infecteds: {} Immunes: {} Deads: {}",stats[1],stats[2],stats[3]);
stats[0], stats[1], stats[2], stats[3]
);
if stats[1] == 0 {
break;
} }
} if stats[1] == 0 {break;}
println!("Propagation finished in {} steps", counter); }
println!("Propagation finished in {} steps, {:?}", counter, now.elapsed());
//population.display(); //population.display();
} }
+187 -396
View File
@@ -1,444 +1,235 @@
use std::sync::{Arc, RwLock};
use crate::prelude::*; use crate::prelude::*;
use std::thread;
use std::time::{Instant};
#[derive(Debug)] #[derive(Debug)]
pub struct Point { pub struct Point{
x: i32, x:i32,
y: i32, y:i32,
} }
pub struct Population { pub struct Population{
pub start_infected_ratio: i32, pub start_infected_ratio:u32,
pub start_immune_ratio: i32, pub start_immune_ratio:u32,
pub start_dead_ratio: i32, pub start_dead_ratio:u32,
pub humans: Arc<RwLock<Vec<Human>>>, pub humans:Vec<Human>,
pub width: i32, pub width:i32,
pub height: i32, pub height:i32,
pub age: i32, pub age:i32,
pub plague: Disease, pub plague:Disease,
pub size: usize,
} }
pub fn human_idx(x: i32, y: i32, width: i32) -> usize { pub fn human_idx(x: i32, y: i32, width: i32) -> usize {
((y * width) + x) as usize ((y * width) + x)as usize
} }
impl Population { impl Population{
pub fn new( pub fn new(start_infected_ratio:u32,start_immune_ratio:u32,start_dead_ratio:u32,width:i32,height:i32,plague:Disease)->Self{
start_infected_ratio: i32, let mut the_humans: Vec<Human> = Vec::with_capacity((width*height) as usize);
start_immune_ratio: i32, for x in 0..width{
start_dead_ratio: i32, for y in 0..height{
width: i32, the_humans.push(Human::new(x, y));
height: i32,
plague: Disease,
) -> Self {
let mut rng = rand::thread_rng();
let size: usize = (width * height) as usize;
let mut the_humans = vec![
Human {
x: 0,
y: 0,
present_state: State::Normal
};
size
];
for x in 0..width {
for y in 0..height {
let idx = human_idx(x, y, width);
let mut present_state = State::Normal;
if (start_infected_ratio > 0)
&& (rng.gen_range(0..CORRECTED_PERCENTAGE) <= start_infected_ratio)
{
present_state = State::Infected;
} else if (start_immune_ratio > 0)
&& (rng.gen_range(0..CORRECTED_PERCENTAGE) <= start_immune_ratio)
{
present_state = State::Immune;
} else if (start_dead_ratio > 0)
&& (rng.gen_range(0..CORRECTED_PERCENTAGE) <= start_dead_ratio)
{
present_state = State::Dead;
}
the_humans[idx] = Human{x: x, y: y, present_state: present_state};
} }
} }
Self{
Self { start_infected_ratio:start_infected_ratio,
start_infected_ratio: start_infected_ratio, start_immune_ratio:start_immune_ratio,
start_immune_ratio: start_immune_ratio, start_dead_ratio:start_dead_ratio,
start_dead_ratio: start_dead_ratio, width:width,
width: width, height:height,
height: height, plague:plague,
plague: plague, age:0,
age: 0, humans:the_humans,
humans: Arc::new(RwLock::new(the_humans)),
size: size,
} }
} }
// pub fn change_disease(&mut self, plague:Disease){ // pub fn change_disease(&mut self, plague:Disease){
// self.plague = plague; // self.plague = plague;
// } // }
pub fn generate(&mut self){
// fn is_inside(&self, pos: &Point) -> bool { //The ratios will not be exact, for example someone who wants 100% infected 100% immune and 100% dead, he will have 100% dead because they are overwriting each others
// if pos.x >= 0 && pos.x < self.width && pos.y >= 0 && pos.y < self.height { //Maybe consider limiting the total to not exceed 100 in the view
// true //Other thing, there will always be more of the last one because someone who is already infected for example could be then put to immune or dead
// } else { //One solution to this issue would be to have if else else statements but in this case for example 20% would be lower with the last because its 20% on the remaining population and not of the all
// false //In other words I did it that way but it can be changed just its not the right method to have perfect ratios
// } let mut rng = rand::thread_rng();
// } let mut i: i32 = 0;
for x in self.humans.iter_mut() {
// fn is_inside_and_infected(&self, point: Point) -> bool { if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_infected_ratio as i32
// let humans = Arc::clone(&self.humans); {
// if self.is_inside(&point) { x.present_state = State::Infected;
// let idx = human_idx(point.x, point.y, self.width); }
// let humans = humans.read().unwrap(); if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_immune_ratio as i32
// if humans[idx].present_state == State::Infected { {
// roll(self.plague.infection_rate) x.present_state = State::Immune;
// } else { }
// false if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_dead_ratio as i32
// } {
// } else { x.present_state = State::Dead;
// false }
// } i += 1;
// } }
println!("generate for {} humans", i);
pub fn propagate(&mut self, num_threads: usize) -> [i32; 4] { }
let timer = Instant::now(); pub fn propagate(&mut self)->[i32;4]{
let mut people_to_check: Vec<Point> = let mut people_to_check:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
Vec::with_capacity(self.size); let mut people_to_infect:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
let mut possible_infected: Vec<Point> = let mut people_to_cure:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
Vec::with_capacity(self.size); let mut people_to_kill:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
let mut people_to_infect: Vec<Point> = let mut stats: [i32;4] = [0,0,0,0];
Vec::with_capacity(self.size);
let mut people_to_cure: Vec<Point> =
Vec::with_capacity(self.size);
let mut people_to_kill: Vec<Point> =
Vec::with_capacity(self.size);
let mut stats: [i32; 4] = [0, 0, 0, 0];
// stats[0] Normal stats[1] Infected stats[2] Immune stats[3] Dead // stats[0] Normal stats[1] Infected stats[2] Immune stats[3] Dead
let mut threads = vec![]; /*
for h in self.humans.iter() {
let len: usize = (self.width * self.height) as usize; match h.present_state{
let mut lines = (len / num_threads) as usize; State::Normal => {stats[0] += 1;}
if len % num_threads != 0 { State::Infected => {people_to_check.push(Point{x:h.x,y:h.y});stats[1]+=1;}
lines += 1; State::Immune => {stats[2] += 1;}
State::Dead => {stats[3] += 1;}
}
} }
for x in 0..num_threads { */
let lower_bound = x * lines;
let mut upper_bound = (x + 1) * lines;
if upper_bound > len {
upper_bound = len;
};
let humans = Arc::clone(&self.humans); for x in 0..self.width{
threads.push(thread::spawn(move || { for y in 0..self.height{
let mut possible_infected: Vec<Point> =Vec::with_capacity(lines); let idx = human_idx(x as i32, y as i32, self.width as i32);
let mut people_to_check: Vec<Point> =Vec::with_capacity(lines); match self.humans[idx].present_state{
let mut stats: [i32; 4] = [0, 0, 0, 0]; State::Normal => {stats[0] += 1;}
let humans = humans.read().unwrap(); State::Infected => {people_to_check.push(Point{x:x,y:y});stats[1]+=1;}
State::Immune => {stats[2] += 1;}
for idx in lower_bound..upper_bound { State::Dead => {stats[3] += 1;}
let h = &humans[idx];
match h.present_state {
State::Normal => {
possible_infected.push(Point{ x: h.x, y: h.y});
stats[0] += 1;
}
State::Infected => {
people_to_check.push(Point { x: h.x, y: h.y });
stats[1] += 1;
}
State::Immune => {
stats[2] += 1;
}
State::Dead => {
stats[3] += 1;
}
}
} }
(possible_infected, people_to_check, stats)
}));
}
for t in threads {
let mut res = t.join().unwrap();
possible_infected.append(&mut res.0);
people_to_check.append(&mut res.1);
for x in 0..4 {
stats[x] += res.2[x];
} }
} }
#[cfg(debug_assertions)] //for pos in &people_to_check {
println!("after first pass {:?}", timer.elapsed()); for pos in people_to_check.iter() {
//people_to_check.iter().map(|pos|{
//get all the other people next to me and check if i die cure or infect
//now we can start to check if people would be infected or not
//let idx = human_idx(pos.x as i32, pos.y as i32, self.width as i32);
if pos.x > 0 && pos.x < self.width - 1 && pos.y > 0 && pos.y < self.height -1 {
if self.roll(self.plague.curing_rate){
//checks if the man dies
people_to_cure.push(Point{x:pos.x,y:pos.y});
}else{
if self.roll(self.plague.death_rate){
//cheks if the man dies
people_to_kill.push(Point{x:pos.x,y:pos.y});
}else{
let mut possible_infections:Vec<Point> = Vec::with_capacity(8);
// Vec::new();
//possible_infections.push(Point{x:pos.x,y:pos.y});
debug_assert_eq!( possible_infections.push(Point{x:pos.x -1,y:pos.y -1}); //Top Left
stats[0] + stats[1] + stats[2] + stats[3], possible_infections.push(Point{x:pos.x,y:pos.y-1}); //Top
self.size as i32 possible_infections.push(Point{x:pos.x +1,y:pos.y -1}); //Top Right
);
possible_infections.push(Point{x:pos.x -1,y:pos.y}); //Left
possible_infections.push(Point{x:pos.x +1,y:pos.y}); //Right
let mut threads = vec![]; possible_infections.push(Point{x:pos.x -1,y:pos.y + 1}); //Bottom Left
possible_infections.push(Point{x:pos.x,y:pos.y + 1}); //Bottom
possible_infections.push(Point{x:pos.x + 1,y:pos.y + 1}); //Bottom Right
let len: usize = people_to_check.len(); for poss_infected_pos in possible_infections.iter() {
let mut lines = (len / num_threads) as usize; //possible_infections.iter().map(|poss_infected_pos|{
if len % num_threads != 0 { let inf_idx = human_idx(poss_infected_pos.x, poss_infected_pos.y, self.width);
lines += 1; if self.humans[inf_idx].present_state == State::Normal{
} if self.roll(self.plague.infection_rate){
let people_to_check_arc = Arc::new(people_to_check); people_to_infect.push(Point{x:poss_infected_pos.x,y:poss_infected_pos.y});
for x in 0..num_threads { }
let lower_bound = x * lines; }
let mut upper_bound = (x + 1) * lines; };
if upper_bound > len {
upper_bound = len;
};
let curing_rate = self.plague.curing_rate;
let death_rate = self.plague.death_rate;
let people_to_check = Arc::clone(&people_to_check_arc);
threads.push(thread::spawn(move || {
let mut people_to_cure: Vec<Point> =Vec::with_capacity(lines);
let mut people_to_kill: Vec<Point> =Vec::with_capacity(lines);
for idx in lower_bound..upper_bound {
let pos = &people_to_check[idx];
if roll(curing_rate) {
//checks if the man recovers
people_to_cure.push(Point { x: pos.x, y: pos.y });
} else {
if roll(death_rate) {
//cheks if the man dies
people_to_kill.push(Point { x: pos.x, y: pos.y });
}
} }
} }
(people_to_cure, people_to_kill) }else{
})); //TODO
} //Check every special cases (corners sides etc..)
for t in threads {
let mut res = t.join().unwrap();
people_to_cure.append(&mut res.0);
people_to_kill.append(&mut res.1);
}
#[cfg(debug_assertions)] //REMOVE WHEN IMPLEMENTED
println!("after people_to_check {:?}", timer.elapsed()); //It is here to prevent an infected in the borders to keep the programm running as he thinks there are still people to simulate
people_to_kill.push(Point{x:pos.x,y:pos.y});
// check normal people to see if someone near is infected // @##
// ###
// ###
let mut threads = vec![]; // #@#
// ###
// ###
let len: usize = possible_infected.len(); // ##@
let mut lines = (len / num_threads) as usize; // ###
if len % num_threads != 0 { // ###
lines += 1;
}
let possible_infected_arc = Arc::new(possible_infected);
{ // ###
let (width, height) = (self.width, self.height); // @##
let infection_rate = self.plague.infection_rate; // ###
for x in 0..num_threads { // ###
let humans = Arc::clone(&self.humans); // ##@
// ###
// ###
// ###
// @##
let lower_bound = x * lines; // ###
let mut upper_bound = (x + 1) * lines; // ###
if upper_bound > len { // #@#
upper_bound = len;
};
let possible_infected = Arc::clone(&possible_infected_arc);
threads.push(thread::spawn(move || {
let humans = &humans.read().unwrap().to_vec();
let mut people_to_infect: Vec<Point> =Vec::with_capacity(lines);
for idx in lower_bound..upper_bound {
let pos = &possible_infected[idx];
let infected: bool = fn_is_inside_and_infected( // ###
Point { // ###
x: pos.x - 1, // ##@
y: pos.y - 1,
}, width, height, humans, infection_rate
) || //Top Left
fn_is_inside_and_infected(
Point {
x: pos.x,
y: pos.y - 1,
}, width, height, humans, infection_rate
) || //Top
fn_is_inside_and_infected(
Point {
x: pos.x + 1,
y: pos.y - 1,
}, width, height, humans, infection_rate
) || //Top Right
fn_is_inside_and_infected(
Point {
x: pos.x - 1,
y: pos.y,
}, width, height, humans, infection_rate
) || //Left
fn_is_inside_and_infected(
Point {
x: pos.x + 1,
y: pos.y,
}, width, height, humans, infection_rate
) || //Right
fn_is_inside_and_infected(
Point {
x: pos.x - 1,
y: pos.y + 1,
}, width, height, humans, infection_rate
) || //Bottom Left
fn_is_inside_and_infected(
Point {
x: pos.x,
y: pos.y + 1,
}, width, height, humans, infection_rate
) || //Bottom
fn_is_inside_and_infected(
Point {
x: pos.x + 1,
y: pos.y + 1,
}, width, height, humans, infection_rate
); //Bottom Right
if infected {
people_to_infect.push(Point { x: pos.x, y: pos.y });
}
}
people_to_infect
}));
} }
for t in threads { };
let mut res = t.join().unwrap(); for infected_position in &people_to_infect {
people_to_infect.append(&mut res); // println!("To infect: {:?}", infected_position);
} //people_to_infect.iter().map(|infected_position|{
} let infected_index = human_idx(infected_position.x, infected_position.y, self.width);
// let _ = infected_position.x;
//DEBUG
//println!("x: {} y: {} index: {}",infected_position.x,infected_position.y,infected_index);
self.humans[infected_index].present_state = State::Infected;
//DEBUG
//println!("Infected someone");
};
#[cfg(debug_assertions)] for cured_position in &people_to_cure {
println!("after possible_infected {:?}", timer.elapsed()); //people_to_cure.iter().map(|cured_position|{
let cured_index = human_idx(cured_position.x, cured_position.y, self.width);
self.humans[cured_index].present_state = State::Immune;
//DEBUG
//println!("Cured someone");
};
let mut threads = vec![]; for dead_position in &people_to_kill {
//people_to_kill.iter().map(|dead_position|{
{ let dead_index = human_idx(dead_position.x, dead_position.y, self.width);
let humans = Arc::clone(&self.humans); self.humans[dead_index].present_state = State::Dead;
let width = self.width; //DEBUG
threads.push(thread::spawn(move || { //println!("Killed someone");
for infected_position in people_to_infect.iter() { };
let infected_index = human_idx(infected_position.x, infected_position.y, width);
{
// eprint!("i");
let mut humans = humans.write().unwrap();
humans[infected_index].present_state = State::Infected;
}
}
}));
}
{
let humans = Arc::clone(&self.humans);
let width = self.width;
threads.push(thread::spawn(move || {
for cured_position in people_to_cure.iter() {
//people_to_cure.iter().map(|cured_position|{
let cured_index = human_idx(cured_position.x, cured_position.y, width);
{
let humans = humans.read().unwrap();
debug_assert_eq!(humans[cured_index].present_state, State::Infected, "This human should be infected: {:?}", humans[cured_index].present_state);
}
{
// eprint!("c");
let mut humans = humans.write().unwrap();
humans[cured_index].present_state = State::Immune;
}
//DEBUG
//println!("Cured someone");
}
}));
}
{
let humans = Arc::clone(&self.humans);
let width = self.width;
threads.push(thread::spawn(move || {
for dead_position in people_to_kill.iter() {
//people_to_kill.iter().map(|dead_position|{
let dead_index = human_idx(dead_position.x, dead_position.y, width);
{
let humans = humans.read().unwrap();
debug_assert!(humans[dead_index].present_state != State::Dead);
}
{
// eprint!("k");
let mut humans = humans.write().unwrap();
humans[dead_index].present_state = State::Dead;
}
}
}));
}
for t in threads {
t.join().unwrap();
}
#[cfg(debug_assertions)]
println!("after kills and co {:?}", timer.elapsed());
stats stats
} }
pub fn roll(&self,probability:u32)->bool{
// pub fn display(&mut self){
// let sprite = "#";
// print!("\n");
// for x in 0..self.width{
// for y in 0..self.height{
// let index = human_idx(x as i32,y as i32,self.width as i32);
// match self.humans[index].present_state {
// State::Normal => print!("{}",style(sprite).green()),
// State::Dead => print!("{}",style(sprite).black()),
// State::Infected => print!("{}",style(sprite).red()),
// State::Immune => print!("{}",style(sprite).blue()),
// _ => print!("{}",style(sprite).white()),
// }
// }
// print!("\n");
// }
// }
}
pub fn roll(probability: i32) -> bool {
if probability > 0 {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
rng.gen_range(0..CORRECTED_PERCENTAGE) <= probability rng.gen_range(0..CORRECTED_PERCENTAGE) <= probability as i32
} else { }
false pub fn display(&mut self){
let sprite = "#";
print!("\n");
for x in 0..self.width{
for y in 0..self.height{
let index = human_idx(x as i32,y as i32,self.width as i32);
match self.humans[index].present_state {
State::Normal => print!("{}",style(sprite).green()),
State::Dead => print!("{}",style(sprite).black()),
State::Infected => print!("{}",style(sprite).red()),
State::Immune => print!("{}",style(sprite).blue()),
_ => print!("{}",style(sprite).white()),
}
}
print!("\n");
}
} }
} }
fn fn_is_inside(pos: &Point, width: i32, height: i32) -> bool {
if (pos.x >= 0) && (pos.x < width) && (pos.y >= 0) && (pos.y < height) {
true
} else {
false
}
}
fn fn_is_inside_and_infected(point: Point, width: i32, height: i32, humans: &Vec<Human>, infection_rate: i32) -> bool {
if fn_is_inside(&point, width, height) {
let idx = human_idx(point.x, point.y, width);
if humans[idx].present_state == State::Infected {
roll(infection_rate)
} else {
false
}
} else {
false
}
}
-448
View File
@@ -1,448 +0,0 @@
#[cfg(test)]
mod tests {
use super::*;
use parameterized::parameterized;
#[derive(Debug)]
struct Stats {
normal: i32,
infected: i32,
immune: i32,
dead: i32,
}
impl Stats {
fn new() -> Stats {
Stats {
normal: 0,
infected: 0,
immune: 0,
dead: 0,
}
}
}
fn humans_stats(humans: &Vec<Human>) -> Stats {
let mut stats: Stats = Stats::new();
for human in humans.iter() {
match human.present_state {
State::Normal => {
stats.normal += 1;
}
State::Infected => {
stats.infected += 1;
}
State::Immune => {
stats.immune += 1;
}
State::Dead => {
stats.dead += 1;
}
}
}
stats
}
#[parameterized(x = {
2, 3, 5
}, y = {
1, 4, 0
}, width = {
3, 5, 7
}, res = {
5, 23, 5
})]
fn test_human_idx(x: i32, y: i32, width: i32, res: usize) {
assert_eq!(human_idx(x, y, width), res);
}
#[test]
fn test_human_stats() {
let mut humans: Vec<Human> = Vec::with_capacity(10);
let mut stats: Stats;
for _ in 0..10 {
humans.push(Human {
present_state: State::Normal,
x: 0,
y: 0,
});
}
stats = humans_stats(&humans);
assert_eq!(stats.normal, 10);
for x in 0..2 {
humans[x].present_state = State::Infected;
}
for x in 2..5 {
humans[x].present_state = State::Immune;
}
for x in 5..9 {
humans[x].present_state = State::Dead;
}
stats = humans_stats(&humans);
assert_eq!(stats.normal, 1);
assert_eq!(stats.infected, 2);
assert_eq!(stats.immune, 3);
assert_eq!(stats.dead, 4);
}
#[test]
fn population_new() {
let disease = Disease::new(20, 10, 5, String::from("Covid 44"));
let (width, height) = (5, 7);
let population = Population::new(20, 10, 5, 5, 7, disease);
let humans = Arc::clone(&population.humans);
assert_eq!(humans.lock().unwrap().len(), 5 * 7);
for h in humans.lock().unwrap().iter() {
let idx = human_idx(h.x, h.y, width);
assert_eq!(humans.lock().unwrap()[idx].x, h.x, "coordinates should match");
assert_eq!(humans.lock().unwrap()[idx].y, h.y, "coordinates should match");
}
assert_eq!(humans.lock().unwrap().len(), (width * height) as usize);
}
#[test]
fn population_gen() {
let disease = Disease::new(20, 10, 5, String::from("Covid 44"));
let (width, height) = (5, 7);
let population = Population::new(20, 10, 5, 5, 7, disease);
let stats: Stats = humans_stats(&population.humans);
println!("Stats: {:?}", stats);
assert_eq!(
stats.normal + stats.infected + stats.immune + stats.dead,
width * height
);
}
#[test]
fn plague_init_stats() {
let mut disease: Disease;
let mut population: Population;
let mut stats: Stats;
let (width, height) = (5, 7);
disease = Disease::new(0, 0, 0, String::from("Test"));
population = Population::new(0, 0, 0, width, height, disease);
stats = humans_stats(&population.humans);
println!("should be normal: {:?}", stats);
assert_eq!(stats.normal, width * height);
disease = Disease::new(0, 0, 0, String::from("Test"));
population = Population::new(100, 0, 0, width, height, disease);
stats = humans_stats(&population.humans);
println!("should be infected: {:?}", stats);
assert_eq!(stats.infected, width * height);
disease = Disease::new(0, 0, 0, String::from("Test"));
population = Population::new(0, 100, 0, width, height, disease);
stats = humans_stats(&population.humans);
println!("should be immune: {:?}", stats);
assert_eq!(stats.immune, width * height);
disease = Disease::new(0, 0, 0, String::from("Test"));
population = Population::new(0, 0, 100, width, height, disease);
stats = humans_stats(&population.humans);
println!("should be dead: {:?}", stats);
assert_eq!(stats.dead, width * height);
}
#[parameterized(rate = {0, 100}, expected = {false, true})]
fn roll_test(rate: i32, expected: bool) {
let tries = 100000;
let mut result = 0;
println!("Testing roll, rate {}, expected {}", rate, expected);
for _x in 0..tries {
if roll(rate) == expected {
result += 1;
}
}
assert_eq!(result, tries);
}
#[test]
fn propagate_simple() {
let disease: Disease = Disease::new(0, 0, 100, String::from("Deadly"));
let mut population: Population = Population::new(100, 0, 0, 10, 10, disease);
let mut stats: Stats;
let mut propagate_stats: [i32; 4];
// infect every one
stats = humans_stats(&population.humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.infected, 100, "everybody should be infected");
// kill every one
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
assert_eq!(propagate_stats, [0, 100, 0, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 0);
assert_eq!(stats.immune, 0);
assert_eq!(stats.dead, 100);
for _x in 0..100 {
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
assert_eq!(propagate_stats, [0, 0, 0, 100]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 0);
assert_eq!(stats.immune, 0);
assert_eq!(stats.dead, 100);
}
}
#[test]
fn propagate_infect_all() {
let disease: Disease = Disease::new(100, 0, 0, String::from("Deadly"));
let mut population: Population = Population::new(0, 0, 0, 3, 3, disease);
let mut stats: Stats;
let mut propagate_stats: [i32; 4];
// start with normal population
population.humans = vec![
Human {
present_state: State::Normal,
x: 0,
y: 0,
},
Human {
present_state: State::Normal,
x: 1,
y: 0,
},
Human {
present_state: State::Normal,
x: 2,
y: 0,
},
Human {
present_state: State::Normal,
x: 0,
y: 1,
},
Human {
present_state: State::Infected,
x: 1,
y: 1,
},
Human {
present_state: State::Normal,
x: 2,
y: 1,
},
Human {
present_state: State::Normal,
x: 0,
y: 2,
},
Human {
present_state: State::Normal,
x: 1,
y: 2,
},
Human {
present_state: State::Normal,
x: 2,
y: 2,
},
];
stats = humans_stats(&population.humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.normal, 8);
// kill every one
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
assert_eq!(propagate_stats, [8, 1, 0, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 9);
assert_eq!(stats.immune, 0);
assert_eq!(stats.dead, 0);
for _x in 0..100 {
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
assert_eq!(propagate_stats, [0, 9, 0, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 9);
assert_eq!(stats.immune, 0);
assert_eq!(stats.dead, 0);
}
}
#[test]
fn propagate_infect_cure_all() {
let disease: Disease = Disease::new(100, 100, 0, String::from("Deadly"));
let mut population: Population = Population::new(0, 0, 0, 3, 3, disease);
let mut stats: Stats;
let mut propagate_stats: [i32; 4];
// start with normal population
population.humans = vec![
Human {
present_state: State::Normal,
x: 0,
y: 0,
},
Human {
present_state: State::Normal,
x: 1,
y: 0,
},
Human {
present_state: State::Normal,
x: 2,
y: 0,
},
Human {
present_state: State::Normal,
x: 0,
y: 1,
},
Human {
present_state: State::Infected,
x: 1,
y: 1,
},
Human {
present_state: State::Normal,
x: 2,
y: 1,
},
Human {
present_state: State::Normal,
x: 0,
y: 2,
},
Human {
present_state: State::Normal,
x: 1,
y: 2,
},
Human {
present_state: State::Normal,
x: 2,
y: 2,
},
];
stats = humans_stats(&population.humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.normal, 8);
// infect every one
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
println!("population: {:?}", stats);
assert_eq!(propagate_stats, [8, 1, 0, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 8);
assert_eq!(stats.immune, 1);
assert_eq!(stats.dead, 0);
// cure every one
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
println!("population: {:?}", stats);
assert_eq!(propagate_stats, [0, 8, 1, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 0);
assert_eq!(stats.immune, 9);
assert_eq!(stats.dead, 0);
// then
for _x in 0..100 {
propagate_stats = population.propagate();
stats = humans_stats(&population.humans);
println!("propate_stats: {:?}", propagate_stats);
println!("population: {:?}", stats);
assert_eq!(propagate_stats, [0, 0, 9, 0]);
assert_eq!(stats.normal, 0);
assert_eq!(stats.infected, 0);
assert_eq!(stats.immune, 9);
assert_eq!(stats.dead, 0);
}
}
#[parameterized(infection_start = {0, 50, 100})]
fn propagate_harmless(infection_start: i32) {
let disease: Disease = Disease::new(0, 0, 0, String::from("Harmless"));
let (width, height) = (100, 100);
let mut population: Population = Population::new(infection_start, 0, 0, width, height, disease);
let stats_before: Stats;
let stats_after: Stats;
stats_before = humans_stats(&population.humans);
let should_be_infected = population.size as i32 * infection_start / 100;
let tolerance = (should_be_infected as f32 * 0.20) as i32;
println!("{:?}", stats_before);
assert!(stats_before.infected <= should_be_infected + tolerance, "{} infected, should be less than {}", stats_before.infected, should_be_infected + tolerance);
assert!(stats_before.infected >= should_be_infected - tolerance, "{} infected, should be more than {}", stats_before.infected, should_be_infected - tolerance);
population.propagate();
stats_after = humans_stats(&population.humans);
assert_eq!(stats_before.infected, stats_after.infected, "no one should have been infected");
}
#[parameterized(infection_rate = {0, 100, 0}, death_rate = {0, 0, 100}, infected_expected = {0, 1, 0})]
fn propagate_test(infection_rate: i32, death_rate: i32, infected_expected: i32) {
let disease: Disease;
let mut population: Population;
let mut stats: Stats;
let (width, height) = (100, 100);
let start_infected = 50;
println!(
"infection rate: {}, death_rate: {}",
infection_rate, death_rate
);
disease = Disease::new(infection_rate, 0, death_rate, String::from("Test"));
population = Population::new(start_infected, 0, 0, width, height, disease);
stats = humans_stats(&population.humans);
println!("Population after init: {:?}", stats);
// total * proba - 20% < infected < total * proba + 20%
let infected_at_start_proba = width * height * start_infected / 100;
let infected_tolerance = ((width * height) as f32 * 0.2) as i32;
assert!(stats.infected <= infected_at_start_proba + infected_tolerance);
assert!(stats.infected >= infected_at_start_proba - infected_tolerance);
assert_eq!(stats.dead, 0);
let infected_at_start = stats.infected;
let dead_at_start = stats.dead;
let propa_stats: [i32; 4] = population.propagate();
assert!(propa_stats[3] >= dead_at_start);
if death_rate == 0 {
assert_eq!(propa_stats[3], 0, "no human should have died");
}
stats = humans_stats(&population.humans);
println!("Population after propagate: {:?}", stats);
assert!(stats.infected <= infected_at_start + width * height * infected_expected);
let should_be_dead = infected_at_start * death_rate / 100;
let dead_tolerance = (should_be_dead as f32 * 0.20) as i32;
assert!(
stats.dead <= should_be_dead + dead_tolerance,
"death count should be less or equal than {}",
should_be_dead + dead_tolerance
);
assert!(stats.dead >= should_be_dead - dead_tolerance);
}
}