1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::thread;
use crate::traits::{Environment, Agent, DefaultEnvironment};
pub fn generate_default_env<A: 'static + Agent>(pop_size: u64) -> Result<Box<dyn Environment>, &'static str> {
let mut pop: Vec<Box<dyn Agent>> = vec!();
for _ in 0..pop_size {
let agent: Box<dyn Agent> = A::generate()?;
pop.push(agent);
}
let env: Box<DefaultEnvironment> = DefaultEnvironment::generate(pop)?;
Ok(env)
}
pub fn tick(mut environment: Box<dyn Environment>) -> Result<Box<dyn Environment>, &'static str> {
(*environment).tick()?;
Ok(environment)
}
pub fn tick_collect(mut environment: Box<dyn Environment>) -> Result<Box<dyn Environment>, &'static str> {
(*environment).tick()?;
(*environment).collect()?;
Ok(environment)
}
pub fn collect(environment: Box<dyn Environment>) -> Result<Box<dyn Environment>, &'static str> {
(*environment).collect()?;
Ok(environment)
}
pub fn generate_default_tick_collect<A: 'static + Agent>(pop_size: u64, ticks: u64, runs: u64) -> Result<(), &'static str> {
let cpu_count: u64 = num_cpus::get() as u64;
for _ in 0..(runs / cpu_count + 1) {
let mut v = vec!();
for _ in 0..cpu_count {
v.push(thread::spawn(move || -> Result<(), &'static str> {
let mut env = generate_default_env::<A>(pop_size)?;
for _ in 0..ticks {
env = tick(env)?;
}
collect(env)?;
Ok(())
}));
}
for handle in v {
handle.join().unwrap().unwrap();
}
}
Ok(())
}
pub fn generate_env<E:'static + Environment, A: 'static + Agent>(pop_size: u64) -> Result<Box<dyn Environment>, &'static str> {
let mut pop: Vec<Box<dyn Agent>> = vec!();
for _ in 0..pop_size {
let agent: Box<dyn Agent> = A::generate()?;
pop.push(agent);
}
let env: Box<E> = E::generate(pop)?;
Ok(env)
}
pub fn generate_tick_collect<E: 'static + Environment, A: 'static + Agent>(pop_size: u64, ticks: u64, runs: u64) -> Result<(), &'static str> {
let cpu_count: u64 = num_cpus::get() as u64;
for _ in 0..(runs / cpu_count + 1) {
let mut v = vec!();
for _ in 0..cpu_count {
v.push(thread::spawn(move || -> Result<(), &'static str> {
let mut env = generate_env::<E, A>(pop_size)?;
for _ in 0..ticks {
env = tick(env)?;
}
collect(env)?;
Ok(())
}));
}
for handle in v {
handle.join().unwrap().unwrap();
}
}
Ok(())
}