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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use ndarray::prelude::*;
use crate::nonlinear::traits::*;
use crate::traits::ModelSpec;
#[cfg(feature = "data_trace")]
use serde::Serialize;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "data_trace", derive(Serialize))]
pub struct Newton<M: ModelSpec> {
/// Newton update vector
delta: Array1<M::Scalar>,
/// Jacobian status, current = `true` / stale = `false`
jcur: bool,
/// current number of iterations in a solve attempt
curiter: usize,
/// maximum number of iterations in a solve attempt
maxiters: usize,
/// total number of nonlinear iterations across all solves
niters: usize,
/// total number of convergence failures across all solves
nconvfails: usize,
}
impl<M> NLSolver<M> for Newton<M>
where
M: ModelSpec,
M::Scalar: num_traits::Float
+ num_traits::NumRef
+ num_traits::NumAssignRef
+ std::fmt::Debug
+ std::fmt::LowerExp,
{
fn new(size: usize, maxiters: usize) -> Self {
Newton {
delta: Array::zeros(size),
jcur: false,
curiter: 0,
maxiters,
niters: 0,
nconvfails: 0,
}
}
fn solve<NLP, S1, S2, S3>(
&mut self,
problem: &mut NLP,
y0: ArrayBase<S1, Ix1>,
mut y: ArrayBase<S2, Ix1>,
w: ArrayBase<S3, Ix1>,
tol: M::Scalar,
call_lsetup: bool,
) -> Result<(), failure::Error>
where
NLP: NLProblem<M>,
S1: ndarray::Data<Elem = M::Scalar>,
S2: ndarray::DataMut<Elem = M::Scalar>,
S3: ndarray::Data<Elem = M::Scalar>,
{
use std::ops::Neg;
// assume the Jacobian is good
let mut jbad = false;
let mut call_lsetup = call_lsetup;
// delta first c = [3.4639284579585095e-08,-2.2532389959396826e-05,0.0000000000000000e+00,]
// looping point for attempts at solution of the nonlinear system: Evaluate the nonlinear
// residual function (store in delta) Setup the linear solver if necessary Preform Newton
// iteraion
let retval: Result<(), failure::Error> = 'outer: loop {
// compute the nonlinear residual, store in delta
let retval = problem
.sys(y0.view(), self.delta.view_mut())
.and_then(|_| {
// if indicated, setup the linear system
if call_lsetup {
// NLS->LSetup() aka idaNlsLSetup()
problem
.setup(y0.view(), self.delta.view(), jbad)
.map(|jcur| self.jcur = jcur)
} else {
Ok(())
}
})
.and_then(|_| {
// initialize counter curiter
self.curiter = 0;
// load prediction into y
y.assign(&y0);
// looping point for Newton iteration. Break out on any error.
'inner: loop {
// increment nonlinear solver iteration counter
self.niters += 1;
// compute the negative of the residual for the linear system rhs
self.delta.mapv_inplace(M::Scalar::neg);
// solve the linear system to get Newton update delta
let retval =
problem
.solve(y.view(), self.delta.view_mut())
.and_then(|_| {
// update the Newton iterate
y += &self.delta;
// test for convergence
problem
.ctest(self, y.view(), self.delta.view(), tol, w.view())
.and_then(|converged| {
if converged {
// if successful update Jacobian status and return
self.jcur = false;
Ok(true)
} else {
self.curiter += 1;
if self.curiter >= self.maxiters {
Err(failure::Error::from(
Error::ConvergenceRecover {},
))
} else {
// compute the nonlinear residual, store in delta
// Ok(false) will continue to iterate 'inner
problem
.sys(y.view(), self.delta.view_mut())
.and(Ok(false))
}
}
})
});
// check if the iteration should continue; otherwise exit Newton loop
if let Ok(false) = retval {
continue 'inner;
} else {
break retval.and(Ok(()));
}
} // end of Newton iteration loop
});
// all inner-loop results go here
match &retval {
Ok(_) => {
return retval;
}
Err(error) => {
// If there is a recoverable convergence failure and the Jacobian-related data
// appears not to be current, increment the convergence failure count and loop
// again with a call to lsetup in which jbad = true.
if let Some(Error::ConvergenceRecover {}) = error.downcast_ref::<Error>() {
if !self.jcur {
self.nconvfails += 1;
call_lsetup = true;
jbad = true;
continue 'outer;
}
}
}
}
// Otherwise break out and return.
break 'outer retval;
}; // end of setup loop
// increment number of convergence failures
self.nconvfails += 1;
// all error returns exit here
retval
}
fn get_num_iters(&self) -> usize {
self.niters
}
fn get_cur_iter(&self) -> usize {
self.curiter
}
fn get_num_conv_fails(&self) -> usize {
self.nconvfails
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::linear::*;
use crate::traits::ModelSpec;
use ndarray::array;
use nearly_eq::assert_nearly_eq;
#[derive(Clone, Debug)]
struct TestProblem {
a: Array<f64, Ix2>,
x: Array<f64, Ix1>,
lsolver: Dense<f64>,
}
impl ModelSpec for TestProblem {
type Scalar = f64;
type Dim = Ix1;
fn model_size(&self) -> usize {
3
}
}
impl TestProblem {
/// Jacobian of the nonlinear residual function
///
/// ```math
/// (2x 2y 2z)
/// J(x,y,z) = (4x 2y -4)
/// (6x -4 2z)
/// ```
fn jac<S1, S2, S3>(
_t: f64,
y: ArrayBase<S1, Ix1>,
_fy: ArrayBase<S2, Ix1>,
mut j: ArrayBase<S3, Ix2>,
) -> Result<(), failure::Error>
where
S1: ndarray::Data<Elem = f64>,
S2: ndarray::Data<Elem = f64>,
S3: ndarray::DataMut<Elem = f64>,
{
j.assign(&array![
[2.0 * y[0], 2.0 * y[1], 2.0 * y[2]],
[4.0 * y[0], 2.0 * y[1], -4.0],
[6.0 * y[0], -4.0, 2.0 * y[2]]
]);
Ok(())
}
}
impl NLProblem<TestProblem> for TestProblem {
/// Nonlinear residual function
///
/// ```math
/// f1(x,y,z) = x^2 + y^2 + z^2 - 1 = 0
/// f2(x,y,z) = 2x^2 + y^2 - 4z = 0
/// f3(x,y,z) = 3x^2 - 4y + z^2 = 0
/// ```
fn sys<S1, S2>(
&mut self,
ycor: ArrayBase<S1, Ix1>,
mut res: ArrayBase<S2, Ix1>,
) -> Result<(), failure::Error>
where
S1: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
S2: ndarray::DataMut<Elem = <Self as ModelSpec>::Scalar>,
{
res[0] = ycor[0].powi(2) + ycor[1].powi(2) + ycor[2].powi(2) - 1.0;
res[1] = 2.0 * ycor[0].powi(2) + ycor[1].powi(2) - 4.0 * ycor[2];
res[2] = 3.0 * ycor[0].powi(2) - 4.0 * ycor[1] + ycor[2].powi(2);
Ok(())
}
fn setup<S1, S2>(
&mut self,
y: ArrayBase<S1, Ix1>,
_f: ArrayBase<S2, Ix1>,
_jbad: bool,
) -> Result<bool, failure::Error>
where
S1: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
S2: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
{
// compute the Jacobian
Self::jac(
0.0,
y.view(),
Array::zeros(self.model_size()),
self.a.view_mut(),
)
.map(|_| true)
.and_then(|_| {
// setup the linear solver
self.lsolver.setup(self.a.view_mut()).map(|_| true)
})
}
fn solve<S1, S2>(
&mut self,
_y: ArrayBase<S1, Ix1>,
mut b: ArrayBase<S2, Ix1>,
) -> Result<(), failure::Error>
where
S1: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
S2: ndarray::DataMut<Elem = <Self as ModelSpec>::Scalar>,
{
// Solve self.A * b = b
//retval = SUNLinSolSolve(Imem->LS, Imem->A, Imem->x, b, ZERO);
//N_VScale(ONE, Imem->x, b);
self.lsolver
.solve(self.a.view(), self.x.view_mut(), b.view(), 0.0)
.map(|_| {
b.assign(&self.x);
})
}
fn ctest<S1, S2, S3, NLS>(
&mut self,
_solver: &NLS,
_y: ArrayBase<S1, Ix1>,
del: ArrayBase<S2, Ix1>,
tol: <Self as ModelSpec>::Scalar,
ewt: ArrayBase<S3, Ix1>,
) -> Result<bool, failure::Error>
where
S1: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
S2: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
S3: ndarray::Data<Elem = <Self as ModelSpec>::Scalar>,
NLS: NLSolver<Self>,
{
use crate::norm_rms::NormRms;
// compute the norm of the correction
let delnrm = del.norm_wrms(&ewt.view());
//if (delnrm <= tol) return(SUN_NLS_SUCCESS); /* success */
//else return(SUN_NLS_CONTINUE); /* not converged */
Ok(delnrm <= tol)
}
}
#[test]
fn test_newton() {
// approximate solution
let y_exp = array![
0.785196933062355226,
0.496611392944656396,
0.369922830745872357
];
let mut p = TestProblem {
a: Array::zeros((3, 3)),
x: Array::zeros(3),
lsolver: Dense::new(3),
};
// set initial guess
let y0 = array![0.5, 0.5, 0.5];
let mut y = Array::zeros(3);
// set weights
let w = array![1.0, 1.0, 1.0];
let mut newton = Newton::new(p.model_size(), 10);
newton
.solve(&mut p, y0, y.view_mut(), w, 1e-2, true)
.expect("Should have converged.");
let expected_err = array![-0.00578453, 1.0143e-08, 1.47767e-08];
// print the solution
println!("Solution: y = {:?}", y);
println!("Solution Error = {:?}", &y - &y_exp);
println!("Number of nonlinear iterations: {}", newton.niters);
assert_nearly_eq!(&y - &y_exp, expected_err, 1e-9);
}
}