32 Commits

Author SHA1 Message Date
f0583c35cf use mutex for stats instead of yield at the end 2022-05-05 21:57:02 +02:00
fbf3b376c6 unfold neighbor functions to gain some speed 2022-05-05 21:20:08 +02:00
13fc7e9bd5 configurable width & height 2022-05-05 20:56:32 +02:00
b6d07d4d3c max threads to 48 2022-05-05 20:41:20 +02:00
8a6b686490 display time take 2022-05-05 20:40:56 +02:00
113e91dcc8 working version
remove const

no need for RwLock as we don't use mut in thread \o/
2022-05-05 15:45:57 +02:00
66bded5763 remove dead code 2022-05-05 15:25:33 +02:00
94466c7f1b propagate each human consecutively 2022-05-05 14:33:52 +02:00
6684ad2675 remove generate and add some testing 2022-05-04 14:57:55 +02:00
3a41670fea check only normal people 2022-05-03 23:17:45 +02:00
fb6e9e82b3 remove unused code 2022-05-03 23:13:48 +02:00
bdb6e60e98 cargo fmt 2022-05-03 23:12:34 +02:00
a2bbd1d431 fix test propagate_infect_cure_all 2022-05-03 23:11:23 +02:00
b456a9fb63 human: remove new() trait 2022-05-03 23:10:54 +02:00
89020eeb21 check surroundings instead 2022-05-03 23:01:48 +02:00
5affe83fdc remove line 2022-05-03 22:29:51 +02:00
7193fb2b16 use 1000 x 1000 2022-05-03 20:57:12 +02:00
57db06ff9a move asserts to tests 2022-05-03 20:49:54 +02:00
6aaede2208 fix population humans initialization 2022-05-03 20:46:55 +02:00
1e26a78e3f main: display normals too 2022-05-03 20:45:40 +02:00
87f0219b3b human: implement clone 2022-05-03 20:45:32 +02:00
dda944efff check angles 2022-05-03 18:37:53 +02:00
e6e67da8c1 remove casts and correct 0 limit situation on roll() 2022-05-03 16:52:12 +02:00
e4076cba12 take roll out of Population 2022-05-03 16:37:36 +02:00
9940608781 fixing the roll function 2022-05-03 16:36:19 +02:00
6bd0f13526 Fix test 2022-05-03 16:14:56 +02:00
813c7668f6 verification 2022-05-03 16:12:39 +02:00
d0ae725d55 check infection rate first 2022-05-03 15:53:59 +02:00
1d49b31272 add tests 2022-05-03 15:45:37 +02:00
d8e2107cce add parametrized crate 2022-05-03 15:45:11 +02:00
4b88165c31 add tests 2022-05-03 13:50:10 +02:00
5eddad02ee check dead state 2022-05-03 13:48:32 +02:00
6 changed files with 960 additions and 255 deletions

223
Cargo.lock generated
View File

@@ -2,12 +2,74 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "3.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85a35a599b11c089a7f49105658d089b8f2cf0882993c17daf6de15285c2c35d"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"clap_lex",
"indexmap",
"lazy_static",
"strsim",
"termcolor",
"textwrap",
]
[[package]]
name = "clap_derive"
version = "3.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213"
dependencies = [
"os_str_bytes",
]
[[package]]
name = "console"
version = "0.15.0"
@@ -40,6 +102,43 @@ dependencies = [
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
[[package]]
name = "heck"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]]
name = "indexmap"
version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.124"
@@ -52,12 +151,81 @@ version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
[[package]]
name = "os_str_bytes"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "ppv-lite86"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
@@ -107,10 +275,38 @@ checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
name = "rusty_propagation"
version = "0.1.0"
dependencies = [
"clap",
"console",
"parameterized",
"rand",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "termcolor"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
dependencies = [
"winapi-util",
]
[[package]]
name = "terminal_size"
version = "0.1.17"
@@ -121,12 +317,30 @@ dependencies = [
"winapi",
]
[[package]]
name = "textwrap"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]]
name = "unicode-width"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]]
name = "unicode-xid"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wasi"
version = "0.10.2+wasi-snapshot-preview1"
@@ -149,6 +363,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"

View File

@@ -5,4 +5,6 @@ edition = "2021"
[dependencies]
console = "0.15.0"
rand = "0.8.5"
rand = "0.8.5"
parameterized = "1.0.0"
clap = { version = "3.1.15", features = ["derive"] }

View File

@@ -1,25 +1,24 @@
// use crate::prelude::*;
// pub const MUTATION_TRAIT_INCREASE_PROBABILITY:i32 = 50;
// pub const MUTATION_TRAIT_CHANGE_AMOUNT:i32 = 20;
#[derive(Debug)]
// #[derive(Debug)]
pub struct Disease {
pub infection_rate:u32,
pub curing_rate:u32,
pub death_rate:u32,
pub traits: Vec<u32>,
pub infection_rate: i32,
pub curing_rate: i32,
pub death_rate: i32,
pub traits: Vec<i32>,
pub name: String,
}
impl Disease{
pub fn new(infection_r:u32,curing_r:u32,death_r:u32,the_name:String) -> Self{
Self{
infection_rate : infection_r,
curing_rate : curing_r,
death_rate : death_r,
name : the_name,
traits : vec![infection_r,curing_r,death_r],
impl Disease {
pub fn new(infection_r: i32, curing_r: i32, death_r: i32, the_name: String) -> Self {
Self {
infection_rate: infection_r,
curing_rate: curing_r,
death_rate: death_r,
name: the_name,
traits: vec![infection_r, curing_r, death_r],
}
}
// pub fn mutate(&mut self){
@@ -39,4 +38,4 @@ impl Disease{
// self.traits[i] = new_ratio as u32;
// }
// }
}
}

View File

@@ -1,33 +1,33 @@
// use crate::prelude::*;
// #[derive(Copy, Clone, PartialEq)]
#[derive(PartialEq)]
#[derive(PartialEq, Debug, Clone)]
pub enum State {
Normal,
Infected,
Dead,
Immune,
}
// #[derive(Clone)]
#[derive(Clone)]
pub struct Human {
pub present_state : State,
pub x : i32,
pub y : i32,
pub present_state: State,
pub x: i32,
pub y: i32,
}
impl Human{
// humans with state "Normal"
pub fn new(pos_x :i32, pos_y :i32) -> Self{
Self{
present_state : State::Normal,
x : pos_x,
y : pos_y
}
}
// pub fn new_empty() -> Self{
// Self{
// present_state:State::Normal,
// x : 0,
// y : 0,
// }
// }
}
// impl Human {
// // humans with state "Normal"
// pub fn new(pos_x: i32, pos_y: i32) -> Self {
// Self {
// present_state: State::Normal,
// x: pos_x,
// y: pos_y,
// }
// }
// // pub fn new_empty() -> Self{
// // Self{
// // present_state:State::Normal,
// // x : 0,
// // y : 0,
// // }
// // }
// }

View File

@@ -1,44 +1,67 @@
mod human;
mod disease;
mod human;
mod population;
mod prelude {
pub use crate::human::*;
pub use crate::disease::*;
pub use crate::human::*;
pub use crate::population::*;
pub use rand::Rng;
pub use console::Term;
pub use console::style;
pub const CORRECTED_PERCENTAGE:i32 = 101;
pub use console::Term;
pub use rand::Rng;
pub const CORRECTED_PERCENTAGE: i32 = 101;
}
use prelude::*;
use clap::Parser;
use std::time::Instant;
#[derive(Parser, Debug)]
struct Args {
/// Number of threads
#[clap(short, long, default_value_t = 1)]
threads: usize,
/// 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,
}
fn main() {
let args = Args::parse();
let term = Term::stdout();
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...");
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,300,300,disease);
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);
println!("Before Filling");
//population.display();
population.generate();
println!("After Filling");
//population.display();
println!("After Propagation");
let mut stats: [i32;4];
// = [0,0,0,0];
let mut counter:u32 = 0;
loop{
counter += 1;
stats=population.propagate();
//population.display();
println!("Infecteds: {} Immunes: {} Deads: {}",stats[1],stats[2],stats[3]);
if stats[1] == 0 {break;}
}
println!("Propagation finished in {} steps",counter);
//population.display();
let mut stats: [i32; 4];
// = [0,0,0,0];
let mut counter: u32 = 0;
let now = Instant::now();
loop {
counter += 1;
stats = population.propagate_new(Some(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());
//population.display();
}

View File

@@ -1,220 +1,678 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use crate::prelude::*;
#[derive(Debug)]
pub struct Point{
x:i32,
y:i32,
}
pub struct Population{
pub start_infected_ratio:u32,
pub start_immune_ratio:u32,
pub start_dead_ratio:u32,
pub humans:Vec<Human>,
pub width:i32,
pub height:i32,
pub age:i32,
pub plague:Disease,
pub struct Population {
pub start_infected_ratio: i32,
pub start_immune_ratio: i32,
pub start_dead_ratio: i32,
pub humans: Arc<Vec<Human>>,
pub width: i32,
pub height: i32,
pub age: i32,
pub plague: Disease,
pub size: usize,
}
pub fn human_idx(x: i32, y: i32, width: i32) -> usize {
((y * width) + x)as usize
((y * width) + x) as usize
}
impl Population{
pub fn new(start_infected_ratio:u32,start_immune_ratio:u32,start_dead_ratio:u32,width:i32,height:i32,plague:Disease)->Self{
let mut the_humans: Vec<Human> = Vec::with_capacity((width*height) as usize);
for x in 0..width{
for y in 0..height{
the_humans.push(Human::new(x, y));
}
}
Self{
start_infected_ratio:start_infected_ratio,
start_immune_ratio:start_immune_ratio,
start_dead_ratio:start_dead_ratio,
width:width,
height:height,
plague:plague,
age:0,
humans:the_humans,
}
}
// pub fn change_disease(&mut self, plague:Disease){
// self.plague = plague;
// }
pub fn generate(&mut self){
//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
//Maybe consider limiting the total to not exceed 100 in the view
//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
//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
//In other words I did it that way but it can be changed just its not the right method to have perfect ratios
impl Population {
pub fn new(
start_infected_ratio: i32,
start_immune_ratio: i32,
start_dead_ratio: i32,
width: i32,
height: i32,
plague: Disease,
) -> Self {
let mut rng = rand::thread_rng();
let mut i: i32 = 0;
for x in self.humans.iter_mut() {
if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_infected_ratio as i32
{
x.present_state = State::Infected;
let size: usize = (width * height) as usize;
let mut the_humans: Vec<Human> = 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};
}
if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_immune_ratio as i32
{
x.present_state = State::Immune;
}
if rng.gen_range(0..CORRECTED_PERCENTAGE) < self.start_dead_ratio as i32
{
x.present_state = State::Dead;
}
i += 1;
}
println!("generate for {} humans", i);
Self {
start_infected_ratio: start_infected_ratio,
start_immune_ratio: start_immune_ratio,
start_dead_ratio: start_dead_ratio,
width: width,
height: height,
plague: plague,
age: 0,
humans: Arc::new(the_humans),
size: size,
}
}
pub fn propagate(&mut self)->[i32;4]{
let mut people_to_check:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
let mut people_to_infect:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
let mut people_to_cure:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
let mut people_to_kill:Vec<Point> = Vec::with_capacity((self.width * self.height) as usize);
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() {
match h.present_state{
State::Normal => {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;}
}
pub fn propagate_new(&mut self, num_threads: Option<usize>) -> [i32; 4] {
let humans = Arc::clone(&self.humans);
let len = humans.len();
let mut humans_n_plus_1: Vec<Human> = Vec::with_capacity(len);
let stats: [i32; 4] = [0, 0, 0, 0];
let num_threads = num_threads.unwrap_or(1);
if num_threads > 48 {
panic!("too many threads")
}
// 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 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});
possible_infections.push(Point{x:pos.x -1,y:pos.y -1}); //Top Left
possible_infections.push(Point{x:pos.x,y:pos.y-1}); //Top
possible_infections.push(Point{x:pos.x +1,y:pos.y -1}); //Top Right
// number of items per batch
let mut num_items = (len / num_threads) as usize;
if len % num_threads != 0 {
num_items += 1;
}
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 stats_arc = Arc::new(Mutex::new(stats));
for poss_infected_pos in possible_infections.iter() {
//possible_infections.iter().map(|poss_infected_pos|{
let inf_idx = human_idx(poss_infected_pos.x, poss_infected_pos.y, self.width);
if self.humans[inf_idx].present_state == State::Normal{
if self.roll(self.plague.infection_rate){
people_to_infect.push(Point{x:poss_infected_pos.x,y:poss_infected_pos.y});
for x in 0..num_threads {
// find items to process
let lower_bound = x * num_items;
let mut upper_bound = (x + 1) * num_items;
if upper_bound > len {
upper_bound = len;
};
// borrow copies of data for thread
let humans = Arc::clone(&self.humans);
let stats = Arc::clone(&stats_arc);
let (width, height, infection_rate, curing_rate, death_rate) =
(self.width, self.height, self.plague.infection_rate, self.plague.curing_rate, self.plague.death_rate);
threads.push(thread::spawn(move || {
// no write on data
// let humans = humans;
let mut humans_n_plus_1: Vec<Human> = Vec::with_capacity(num_items);
for idx in lower_bound..upper_bound {
let human = &humans[idx];
// let mut neighbors: Vec<&Human> = Vec::with_capacity(8);
let mut new_human = human.clone();
match human.present_state {
State::Normal => {
let possible = [
(human.x - 1, human.y - 1), (human.x, human.y - 1), (human.x + 1, human.y - 1),
(human.x - 1, human.y) , (human.x + 1, human.y),
(human.x - 1, human.y + 1), (human.x, human.y + 1), (human.x + 1, human.y + 1),
];
for neigh_coords in possible.iter() {
let neigh_idx = point_to_index(neigh_coords.0, neigh_coords.1, width, height);
match neigh_idx {
Some(x) => if humans[x].present_state == State::Infected {
if roll(infection_rate) {
new_human.present_state = State::Infected;
break;
}
}
None => {}
}
}
};
let mut stats = stats.lock().unwrap();
stats[0] += 1;
}
State::Infected => {
match die_or_cure(curing_rate, death_rate) {
Some(x) => new_human.present_state = x,
None => {}
}
let mut stats = stats.lock().unwrap();
stats[1] += 1;
}
State::Immune => {
let mut stats = stats.lock().unwrap();
stats[2] += 1;
}
State::Dead => {
let mut stats = stats.lock().unwrap();
stats[3] += 1;
}
}
humans_n_plus_1.push(new_human);
}
}else{
//TODO
//Check every special cases (corners sides etc..)
(humans_n_plus_1,)
}));
}
//REMOVE WHEN IMPLEMENTED
//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});
for t in threads {
let mut res = t.join().unwrap();
humans_n_plus_1.append(&mut res.0);
// for x in 0..4 {
// stats[x] += res.1[x];
// }
}
// @##
// ###
// ###
// #@#
// ###
// ###
// ##@
// ###
// ###
// ###
// @##
// ###
// ###
// ##@
// ###
// ###
// ###
// @##
// ###
// ###
// #@#
// ###
// ###
// ##@
}
};
for infected_position in &people_to_infect {
// 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");
};
for cured_position in &people_to_cure {
//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");
};
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);
self.humans[dead_index].present_state = State::Dead;
//DEBUG
//println!("Killed someone");
};
self.humans = Arc::new(humans_n_plus_1);
let stats = Arc::clone(&stats_arc);
let stats = *stats.lock().unwrap();
stats
}
pub fn roll(&self,probability:u32)->bool{
}
fn die_or_cure(curing_rate: i32, death_rate: i32) -> Option<State> {
if roll(curing_rate) {
Some(State::Immune)
} else if roll(death_rate) {
Some(State::Dead)
} else {
None
}
}
fn point_to_index(x: i32, y: i32, width: i32, height: i32) -> Option<usize> {
if (x >= 0) && (x < width) && (y >= 0) && (y < height) {
Some(human_idx(x, y, width))
} else {
None
}
}
fn roll(probability: i32) -> bool {
if probability > 0 {
let mut rng = rand::thread_rng();
rng.gen_range(0..CORRECTED_PERCENTAGE) <= probability as i32
}
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()),
rng.gen_range(0..CORRECTED_PERCENTAGE) <= probability
} else {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use parameterized::parameterized;
const THREADS: Option<usize> = Some(4);
#[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;
}
}
print!("\n");
}
}
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, width, height, disease);
let humans = Arc::clone(&population.humans);
assert_eq!(humans.len(), 5 * 7);
for h in humans.iter() {
let idx = human_idx(h.x, h.y, width);
assert_eq!(humans[idx].x, h.x, "coordinates should match");
assert_eq!(humans[idx].y, h.y, "coordinates should match");
}
}
#[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 humans = Arc::clone(&population.humans);
let stats: Stats = humans_stats(&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);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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
let humans = Arc::clone(&population.humans);
stats = humans_stats(&humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.infected, 100, "everybody should be infected");
// kill every one
propagate_stats = population.propagate_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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 = Arc::new(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,
},
]);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.normal, 8);
// kill every one
propagate_stats = population.propagate_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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 = Arc::new(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,
},
]);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&humans);
println!("stats after init: {:?}", stats);
assert_eq!(stats.normal, 8);
// infect every one
propagate_stats = population.propagate_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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_new(THREADS);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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;
let humans = Arc::clone(&population.humans);
stats_before = humans_stats(&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_new(THREADS);
let humans = Arc::clone(&population.humans);
stats_after = humans_stats(&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);
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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_new(THREADS);
assert!(propa_stats[3] >= dead_at_start);
if death_rate == 0 {
assert_eq!(propa_stats[3], 0, "no human should have died");
}
let humans = Arc::clone(&population.humans);
stats = humans_stats(&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);
}
}