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
pub mod linalg;
pub mod mvcalc;
#[cfg(test)]
mod tests;
#[cfg(feature = "python_ffi")]
pub mod pyffi;
use linalg::*;
use mvcalc::*;
use meval::{ Context, eval_str_with_context };
use std::collections::HashMap;
pub enum SolverResult<T> {
Ok(T),
Warn(T),
Err
}
impl <'a>SolverResult<HashMap<&'a str, Variable>> {
pub fn unwrap(self) -> HashMap<&'a str, Variable> {
match self {
SolverResult::Ok(t) => t,
SolverResult::Warn(t) => t,
SolverResult::Err => panic!()
}
}
}
#[allow(dead_code)]
fn index_map<'a, V>(hm: &HashMap<&'a str, V>) -> HashMap<&'a str, usize> {
let mut i: usize = 0;
let mut res = HashMap::new();
for k in hm.keys() {
res.insert(*k, i);
i += 1;
}
res
}
fn split_hm<K, V>(hm: HashMap<K, V>) -> (Vec<K>, Vec<V>) {
let mut keys = Vec::new();
let mut vals = Vec::new();
for i in hm {
keys.push(i.0);
vals.push(i.1);
}
(keys, vals)
}
fn stitch_hm<K: std::hash::Hash + std::cmp::Eq, V>(mut keys: Vec<K>, mut vals: Vec<V>) -> HashMap<K, V> {
let mut res = HashMap::new();
for _ in 0..keys.len() {
res.insert(
keys.pop().unwrap(),
vals.pop().unwrap()
);
}
res
}
fn functionify<'a>(text: &'a str) -> impl Fn(&HashMap<&str, Variable>) -> f64 + 'a {
let func = move |v:&HashMap<&str, Variable>| -> f64 {
let mut ctx = Context::new();
for k in v {
ctx.var(*k.0, k.1.as_f64());
}
eval_str_with_context(text, ctx)
.expect(&format!("ERR: Failed to evaluate expression: {}", text))
};
func
}
fn newton_iteration<'a>(system: &Vec<&str>, mut guess: HashMap<&'a str, Variable>) -> Result<HashMap<&'a str, Variable>, ()> {
let mut j = jacobian(system, &guess);
let inv_result = j.invert();
if let Err(()) = inv_result {
return Err(()) }
let fx = Vec::from_iter(
system.iter().map(
|i| functionify(i)(&guess)
)
);
let x_n = stitch_hm(
j.vars.clone().unwrap(),
mat_vec_mul(j, fx)
);
for v in &mut guess {
v.1.step(-x_n[&v.0.to_string()])
}
Ok(guess)
}
pub fn mv_newton_raphson<'a>(
system: Vec<&str>,
mut guess: HashMap<&'a str, Variable>,
tolerance: f64,
max_iterations: i32
) -> SolverResult<HashMap<&'a str, Variable>> {
let error = |guess: &HashMap<&str, Variable>| -> f64 {
system.iter().map(
|i| {
let mut ctx = Context::new();
for j in guess {
ctx.var(*j.0, j.1.as_f64());
}
let exp = i.replace("=", "-");
let error_msg = format!("Correctness function failed to evaluate the system string: {}", &exp);
eval_str_with_context(&exp, ctx)
.expect(&error_msg)
.abs()
}
).sum()
};
let mut count = 0;
loop {
let res = newton_iteration(&system, guess);
if let Err(()) = res {
return SolverResult::Err;
}
guess = res.unwrap();
let e = error(&guess);
if e < tolerance { return SolverResult::Ok(guess)
} else if count > max_iterations { guess.insert("__error__", Variable::new(e, None));
return SolverResult::Warn(guess)
}
count += 1;
}
}