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
use crate::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Clone, Serialize, Deserialize)]
pub struct ConjugateGradient<P> {
b: P,
r: P,
p: P,
p_prev: P,
rtr: f64,
alpha: f64,
beta: f64,
}
impl<P> ConjugateGradient<P>
where
P: Clone + Default,
{
pub fn new(b: P) -> Result<Self, Error> {
Ok(ConjugateGradient {
b,
r: P::default(),
p: P::default(),
p_prev: P::default(),
rtr: std::f64::NAN,
alpha: std::f64::NAN,
beta: std::f64::NAN,
})
}
pub fn p(&self) -> P {
self.p.clone()
}
pub fn p_prev(&self) -> P {
self.p_prev.clone()
}
pub fn residual(&self) -> P {
self.r.clone()
}
}
impl<P, O> Solver<O> for ConjugateGradient<P>
where
O: ArgminOp<Param = P, Output = P>,
P: Clone
+ Serialize
+ DeserializeOwned
+ ArgminSub<P, P>
+ ArgminDot<P, f64>
+ ArgminScaledAdd<P, f64, P>
+ ArgminAdd<P, P>
+ ArgminMul<f64, P>
+ ArgminDot<P, f64>,
{
const NAME: &'static str = "Conjugate Gradient";
fn init(
&mut self,
op: &mut OpWrapper<O>,
state: &IterState<O>,
) -> Result<Option<ArgminIterData<O>>, Error> {
let init_param = state.get_param();
let ap = op.apply(&init_param)?;
let r0 = self.b.sub(&ap).mul(&(-1.0));
self.r = r0.clone();
self.p = r0.mul(&(-1.0));
self.rtr = self.r.dot(&self.r);
Ok(None)
}
fn next_iter(
&mut self,
op: &mut OpWrapper<O>,
state: &IterState<O>,
) -> Result<ArgminIterData<O>, Error> {
self.p_prev = self.p.clone();
let apk = op.apply(&self.p)?;
self.alpha = self.rtr / self.p.dot(&apk);
let new_param = state.get_param().scaled_add(&self.alpha, &self.p);
self.r = self.r.scaled_add(&self.alpha, &apk);
let rtr_n = self.r.dot(&self.r);
self.beta = rtr_n / self.rtr;
self.rtr = rtr_n;
self.p = self.r.mul(&(-1.0)).scaled_add(&self.beta, &self.p);
let norm = self.r.dot(&self.r);
Ok(ArgminIterData::new()
.param(new_param)
.cost(norm.sqrt())
.kv(make_kv!("alpha" => self.alpha; "beta" => self.beta;)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::send_sync_test;
send_sync_test!(
conjugate_gradient,
ConjugateGradient<NoOperator<Vec<f64>, Vec<f64>, (), ()>>
);
}