3 Commits

Author SHA1 Message Date
herel a6d56af613 add cli option to specify number of threads 2022-05-05 13:19:24 +02:00
herel 1abf452ce5 use RwLock 2022-05-04 21:29:47 +02:00
herel ea74e1029b using Arc<Mutex<Vec<Human>>> 2022-05-04 20:37:40 +02:00
5 changed files with 773 additions and 611 deletions
Generated
+2 -2
View File
@@ -141,9 +141,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.125"
version = "0.2.124"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
checksum = "21a41fed9d98f27ab1c6d161da622a4fa35e8a54a8adc24bbf3ddd0ef70b0e50"
[[package]]
name = "once_cell"
+1 -1
View File
@@ -7,4 +7,4 @@ edition = "2021"
console = "0.15.0"
rand = "0.8.5"
parameterized = "1.0.0"
clap = { version = "3.1.15", features = ["derive"] }
clap = { version = "3.0", features = ["derive"] }
+10 -21
View File
@@ -1,3 +1,5 @@
use clap::Parser;
mod disease;
mod human;
mod population;
@@ -12,31 +14,21 @@ mod prelude {
}
use prelude::*;
use clap::Parser;
use std::time::Instant;
#[derive(Parser, Debug)]
struct Args {
/// Display stats after each propagation
#[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,
#[derive(Parser)]
struct Cli {
/// Number of threads to use
threads: usize,
}
fn main() {
let args = Args::parse();
let args = Cli::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 mut population = Population::new(20,10,5,args.width,args.height,disease);
let mut population = Population::new(20, 10, 5, 1000, 1000, disease);
//population.change_disease(disease);
println!("After Filling");
//population.display();
@@ -44,21 +36,18 @@ fn main() {
let mut stats: [i32; 4];
// = [0,0,0,0];
let mut counter: u32 = 0;
let now = Instant::now();
loop {
counter += 1;
stats = population.propagate();
stats = population.propagate(args.threads);
//population.display();
if args.display {
println!(
"Normal: {} Infecteds: {} Immunes: {} Deads: {}",
stats[0], stats[1], stats[2], stats[3]
);
}
if stats[1] == 0 {
break;
}
}
println!("Propagation finished in {} steps, {:?}", counter, now.elapsed());
println!("Propagation finished in {} steps", counter);
//population.display();
}
+240 -515
View File
@@ -1,4 +1,8 @@
use std::sync::{Arc, RwLock};
use crate::prelude::*;
use std::thread;
use std::time::{Instant};
#[derive(Debug)]
pub struct Point {
@@ -10,7 +14,7 @@ pub struct Population {
pub start_infected_ratio: i32,
pub start_immune_ratio: i32,
pub start_dead_ratio: i32,
pub humans: Vec<Human>,
pub humans: Arc<RwLock<Vec<Human>>>,
pub width: i32,
pub height: i32,
pub age: i32,
@@ -35,7 +39,7 @@ impl Population {
let size: usize = (width * height) as usize;
let mut the_humans: Vec<Human> = vec![
let mut the_humans = vec![
Human {
x: 0,
y: 0,
@@ -43,6 +47,7 @@ impl Population {
};
size
];
for x in 0..width {
for y in 0..height {
let idx = human_idx(x, y, width);
@@ -63,6 +68,7 @@ impl Population {
the_humans[idx] = Human{x: x, y: y, present_state: present_state};
}
}
Self {
start_infected_ratio: start_infected_ratio,
start_immune_ratio: start_immune_ratio,
@@ -71,7 +77,7 @@ impl Population {
height: height,
plague: plague,
age: 0,
humans: the_humans,
humans: Arc::new(RwLock::new(the_humans)),
size: size,
}
}
@@ -79,28 +85,31 @@ impl Population {
// self.plague = plague;
// }
fn is_inside(&self, pos: &Point) -> bool {
if pos.x >= 0 && pos.x < self.width && pos.y >= 0 && pos.y < self.height {
true
} else {
false
}
}
// fn is_inside(&self, pos: &Point) -> bool {
// if pos.x >= 0 && pos.x < self.width && pos.y >= 0 && pos.y < self.height {
// true
// } else {
// false
// }
// }
fn is_inside_and_infected(&self, point: Point) -> bool {
if self.is_inside(&point) {
let idx = human_idx(point.x, point.y, self.width);
if self.humans[idx].present_state == State::Infected {
roll(self.plague.infection_rate)
} else {
false
}
} else {
false
}
}
// fn is_inside_and_infected(&self, point: Point) -> bool {
// let humans = Arc::clone(&self.humans);
// if self.is_inside(&point) {
// let idx = human_idx(point.x, point.y, self.width);
// let humans = humans.read().unwrap();
// if humans[idx].present_state == State::Infected {
// roll(self.plague.infection_rate)
// } else {
// false
// }
// } else {
// false
// }
// }
pub fn propagate(&mut self) -> [i32; 4] {
pub fn propagate(&mut self, num_threads: usize) -> [i32; 4] {
let timer = Instant::now();
let mut people_to_check: Vec<Point> =
Vec::with_capacity(self.size);
let mut possible_infected: Vec<Point> =
@@ -114,7 +123,29 @@ impl Population {
let mut stats: [i32; 4] = [0, 0, 0, 0];
// stats[0] Normal stats[1] Infected stats[2] Immune stats[3] Dead
for h in self.humans.iter() {
let mut threads = vec![];
let len: usize = (self.width * self.height) as usize;
let mut lines = (len / num_threads) as usize;
if len % num_threads != 0 {
lines += 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);
threads.push(thread::spawn(move || {
let mut possible_infected: Vec<Point> =Vec::with_capacity(lines);
let mut people_to_check: Vec<Point> =Vec::with_capacity(lines);
let mut stats: [i32; 4] = [0, 0, 0, 0];
let humans = humans.read().unwrap();
for idx in lower_bound..upper_bound {
let h = &humans[idx];
match h.present_state {
State::Normal => {
possible_infected.push(Point{ x: h.x, y: h.y});
@@ -132,113 +163,233 @@ impl Population {
}
}
}
// for pos in &people_to_check {
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 roll(self.plague.curing_rate) {
(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)]
println!("after first pass {:?}", timer.elapsed());
debug_assert_eq!(
stats[0] + stats[1] + stats[2] + stats[3],
self.size as i32
);
let mut threads = vec![];
let len: usize = people_to_check.len();
let mut lines = (len / num_threads) as usize;
if len % num_threads != 0 {
lines += 1;
}
let people_to_check_arc = Arc::new(people_to_check);
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(self.plague.death_rate) {
if roll(death_rate) {
//cheks if the man dies
people_to_kill.push(Point { x: pos.x, y: pos.y });
}
}
}
for pos in possible_infected.iter() {
let infected: bool = self.is_inside_and_infected(
(people_to_cure, people_to_kill)
}));
}
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)]
println!("after people_to_check {:?}", timer.elapsed());
// 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
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x,
y: pos.y - 1,
},
}, width, height, humans, infection_rate
) || //Top
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x + 1,
y: pos.y - 1,
},
}, width, height, humans, infection_rate
) || //Top Right
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x - 1,
y: pos.y,
},
}, width, height, humans, infection_rate
) || //Left
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x + 1,
y: pos.y,
},
}, width, height, humans, infection_rate
) || //Right
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x - 1,
y: pos.y + 1,
},
}, width, height, humans, infection_rate
) || //Bottom Left
self.is_inside_and_infected(
fn_is_inside_and_infected(
Point {
x: pos.x,
y: pos.y + 1,
},
}, width, height, humans, infection_rate
) || //Bottom
self.is_inside_and_infected(
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 });
}
}
for infected_position in people_to_infect.iter() {
// 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");
people_to_infect
}));
}
for t in threads {
let mut res = t.join().unwrap();
people_to_infect.append(&mut res);
}
}
#[cfg(debug_assertions)]
println!("after possible_infected {:?}", timer.elapsed());
let mut threads = vec![];
{
let humans = Arc::clone(&self.humans);
let width = self.width;
threads.push(thread::spawn(move || {
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, self.width);
if self.humans[cured_index].present_state != State::Infected {
println!("not infected");
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;
}
self.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, self.width);
if self.humans[dead_index].present_state == State::Dead {
// println!("Already dead");
} else {
self.humans[dead_index].present_state = State::Dead;
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);
}
//DEBUG
{
// eprint!("k");
let mut humans = humans.write().unwrap();
humans[dead_index].present_state = State::Dead;
}
assert_eq!(
stats[0] + stats[1] + stats[2] + stats[3],
self.size as i32
);
}
}));
}
for t in threads {
t.join().unwrap();
}
#[cfg(debug_assertions)]
println!("after kills and co {:?}", timer.elapsed());
stats
}
@@ -270,450 +421,24 @@ pub fn roll(probability: i32) -> bool {
}
}
#[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);
assert_eq!(population.humans.len(), 5 * 7);
for h in population.humans.iter() {
let idx = human_idx(h.x, h.y, width);
assert_eq!(population.humans[idx].x, h.x, "coordinates should match");
assert_eq!(population.humans[idx].y, h.y, "coordinates should match");
}
assert_eq!(population.humans.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);
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
}
}
#[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);
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
}
}
#[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);
}
}
+448
View File
@@ -0,0 +1,448 @@
#[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);
}
}