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
#[derive(Clone)]
pub enum Grid1D {
Equidistant(EquidistantGrid1D)
}
impl Grid1D {
pub fn new_equidistant(xlim: (f64,f64), n: usize) -> Self {
Grid1D::Equidistant(EquidistantGrid1D{xlim,n})
}
pub fn grid(&self) -> Box<dyn Iterator<Item=f64>> {
#[allow(unreachable_patterns)]
match self {
Grid1D::Equidistant(grid) => Box::new(grid.grid()),
_ => unimplemented!()
}
}
}
#[derive(Clone)]
pub struct EquidistantGrid1D {
pub xlim: (f64,f64),
pub n: usize
}
impl EquidistantGrid1D {
pub fn grid(&self) -> EquidistantGrid1DIter {
EquidistantGrid1DIter {
i: 0,
n: self.n,
dx: self.delta(),
offset: self.xlim.0
}
}
pub fn delta(&self) -> f64 {
(self.xlim.1 - self.xlim.0) / (self.n - 1) as f64
}
}
pub struct EquidistantGrid1DIter {
i: usize,
n: usize,
dx: f64,
offset: f64
}
impl Iterator for EquidistantGrid1DIter {
type Item = f64;
fn next(&mut self) -> Option<Self::Item> {
if self.i >= self.n {
None
}
else {
let res = self.offset + self.dx * self.i as f64;
self.i += 1;
Some(res)
}
}
}
#[allow(non_snake_case)]
#[derive(Clone)]
pub struct SIRStateSpatial1D {
pub S: Vec<f64>,
pub I: Vec<f64>,
pub R: Vec<f64>,
pub grid: Grid1D
}
impl SIRStateSpatial1D {
#[allow(non_snake_case)]
pub fn new<F>(grid: Grid1D, initfunc: F) -> Self
where F: Fn(f64) -> (f64,f64,f64)
{
let mut S = vec![];
let mut I = vec![];
let mut R = vec![];
for x in grid.grid() {
let result = initfunc(x);
S.push(result.0);
I.push(result.1);
R.push(result.2);
}
Self {
S,I,R,
grid
}
}
}
#[allow(non_snake_case)]
pub struct SIRStateSpatial1DBorrowed<'a> {
pub S: &'a[f64],
pub I: &'a[f64],
pub R: &'a[f64],
pub grid: &'a Grid1D,
}
impl<'a> SIRStateSpatial1DBorrowed<'a> {
#[allow(non_snake_case)]
pub(crate) fn from_vec(v: &'a Vec<f64>, grid: &'a Grid1D) -> 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
}
}
}