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
use std;
use ndarray::{Array1, Array2};
use errors::*;
use prelude::*;
use operator::ArgminOperator;
use result::ArgminResult;
use termination::TerminationReason;
pub struct Landweber<'a> {
omega: f64,
max_iters: u64,
state: Option<LandweberState<'a>>,
}
struct LandweberState<'a> {
operator: &'a ArgminOperator<'a>,
param: Array1<f64>,
iter: u64,
norm: f64,
}
impl<'a> LandweberState<'a> {
pub fn new(operator: &'a ArgminOperator<'a>, param: Array1<f64>) -> Self {
LandweberState {
operator: operator,
param: param,
iter: 0_u64,
norm: std::f64::NAN,
}
}
}
impl<'a> Landweber<'a> {
pub fn new(omega: f64) -> Self {
Landweber {
omega: omega,
max_iters: std::u64::MAX,
state: None,
}
}
pub fn max_iters(&mut self, max_iters: u64) -> &mut Self {
self.max_iters = max_iters;
self
}
}
impl<'a> ArgminSolver<'a> for Landweber<'a> {
type Parameter = Array1<f64>;
type CostValue = f64;
type Hessian = Array2<f64>;
type StartingPoints = Self::Parameter;
type ProblemDefinition = ArgminOperator<'a>;
fn init(
&mut self,
operator: &'a Self::ProblemDefinition,
init_param: &Self::StartingPoints,
) -> Result<()> {
self.state = Some(LandweberState::new(operator, init_param.clone()));
Ok(())
}
fn next_iter(&mut self) -> Result<ArgminResult<Self::Parameter, Self::CostValue>> {
let mut state = self.state.take().unwrap();
let prev_param = state.param.clone();
let diff = state.operator.apply(&prev_param) - state.operator.y;
state.param = state.param - self.omega * state.operator.apply_transpose(&diff);
state.iter += 1;
state.norm = diff.iter().map(|a| a.powf(2.0)).sum::<f64>().sqrt();
let mut out = ArgminResult::new(state.param.clone(), state.norm, state.iter);
self.state = Some(state);
out.set_termination_reason(self.terminate());
Ok(out)
}
fn terminate(&self) -> TerminationReason {
if self.state.as_ref().unwrap().iter >= self.max_iters {
return TerminationReason::MaxItersReached;
}
if self.state.as_ref().unwrap().norm < self.state.as_ref().unwrap().operator.target_cost {
return TerminationReason::TargetCostReached;
}
TerminationReason::NotTerminated
}
make_run!(
Self::ProblemDefinition,
Self::StartingPoints,
Self::Parameter,
Self::CostValue
);
}
impl<'a> Default for Landweber<'a> {
fn default() -> Self {
Self::new(1.0)
}
}