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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use super::Grid1D;
#[derive(Clone)]
pub enum Grid2D {
Cartesian(CartesianGrid2D)
}
impl Grid2D {
pub fn new_cartesian(grid_x: Grid1D, grid_y: Grid1D,) -> Self {
Grid2D::Cartesian(CartesianGrid2D { grid_x, grid_y })
}
pub fn grid<'a>(&'a self) -> Box<dyn Iterator<Item=(f64,f64)> + 'a> {
#[allow(unreachable_patterns)]
match self {
Grid2D::Cartesian(grid) => Box::new(grid.grid()),
_ => unimplemented!()
}
}
}
#[derive(Clone)]
pub struct CartesianGrid2D {
pub grid_x: Grid1D,
pub grid_y: Grid1D
}
impl CartesianGrid2D {
pub fn grid<'a>(&'a self) -> CartesianGrid2DIterator<'a> {
CartesianGrid2DIterator::new(&self.grid_x, &self.grid_y)
}
}
pub struct CartesianGrid2DIterator<'a> {
grid_x: &'a Grid1D,
y_iter: Box<dyn Iterator<Item=f64>>,
x_iter: Box<dyn Iterator<Item=f64>>,
curr_y: Option<f64>
}
impl<'a> CartesianGrid2DIterator<'a> {
fn new(grid_x: &'a Grid1D, grid_y: &Grid1D) -> Self {
let mut y_iter = grid_y.grid();
let curr_y = y_iter.next();
Self {
grid_x,
y_iter,
x_iter: grid_x.grid(),
curr_y
}
}
}
impl Iterator for CartesianGrid2DIterator<'_> {
type Item = (f64,f64);
fn next(&mut self) -> Option<Self::Item> {
match self.curr_y {
Some(curr_y) => {
let next_x = self.x_iter.next();
match next_x {
Some(x) => Some((x, curr_y)),
None => {
let next_y = self.y_iter.next();
match next_y {
Some(y) => {
self.curr_y = Some(y);
self.x_iter = self.grid_x.grid();
let next_x = self.x_iter.next();
match next_x {
Some(x) => Some((x,y)),
None => None
}
},
None => None
}
}
}
},
None => None
}
}
}
#[allow(non_snake_case)]
#[derive(Clone)]
pub struct SIRStateSpatial2D {
pub S: Vec<f64>,
pub I: Vec<f64>,
pub R: Vec<f64>,
pub grid: Grid2D
}
impl SIRStateSpatial2D {
#[allow(non_snake_case)]
pub fn new<F>(grid: Grid2D, initfunc: F) -> Self
where F: Fn(f64,f64) -> (f64,f64,f64)
{
let mut S = vec![];
let mut I = vec![];
let mut R = vec![];
for (x,y) in grid.grid() {
let result = initfunc(x,y);
S.push(result.0);
I.push(result.1);
R.push(result.2);
}
Self {
S,I,R,
grid
}
}
}
#[allow(non_snake_case)]
pub struct SIRStateSpatial2DBorrowed<'a> {
pub S: &'a[f64],
pub I: &'a[f64],
pub R: &'a[f64],
pub grid: &'a Grid2D
}
impl<'a> SIRStateSpatial2DBorrowed<'a> {
#[allow(non_snake_case)]
pub(crate) fn from_vec(v: &'a Vec<f64>, grid: &'a Grid2D) -> Self {
let n = v.len() / 3;
let (S,IR) = v.split_at(n);
let (I,R) = IR.split_at(n);
Self {
S,I,R,grid
}
}
}