argmin/solver/newton/
newton_method.rs

1// Copyright 2018-2020 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! # References:
9//!
10//! [0] Jorge Nocedal and Stephen J. Wright (2006). Numerical Optimization.
11//! Springer. ISBN 0-387-30303-0.
12
13use crate::prelude::*;
14use serde::{Deserialize, Serialize};
15use std::default::Default;
16
17/// Newton's method iteratively finds the stationary points of a function f by using a second order
18/// approximation of f at the current point.
19///
20/// [Example](https://github.com/argmin-rs/argmin/blob/master/examples/newton.rs)
21///
22/// # References:
23///
24/// [0] Jorge Nocedal and Stephen J. Wright (2006). Numerical Optimization.
25/// Springer. ISBN 0-387-30303-0.
26#[derive(Clone, Serialize, Deserialize)]
27pub struct Newton<F> {
28    /// gamma
29    gamma: F,
30}
31
32impl<F: ArgminFloat> Newton<F> {
33    /// Constructor
34    pub fn new() -> Self {
35        Newton {
36            gamma: F::from_f64(1.0).unwrap(),
37        }
38    }
39
40    /// set gamma
41    pub fn set_gamma(mut self, gamma: F) -> Result<Self, Error> {
42        if gamma <= F::from_f64(0.0).unwrap() || gamma > F::from_f64(1.0).unwrap() {
43            return Err(ArgminError::InvalidParameter {
44                text: "Newton: gamma must be in  (0, 1].".to_string(),
45            }
46            .into());
47        }
48        self.gamma = gamma;
49        Ok(self)
50    }
51}
52
53impl<F: ArgminFloat> Default for Newton<F> {
54    fn default() -> Newton<F> {
55        Newton::new()
56    }
57}
58
59impl<O, F> Solver<O> for Newton<F>
60where
61    O: ArgminOp<Float = F>,
62    O::Param: ArgminScaledSub<O::Param, O::Float, O::Param>,
63    O::Hessian: ArgminInv<O::Hessian> + ArgminDot<O::Param, O::Param>,
64    F: ArgminFloat,
65{
66    const NAME: &'static str = "Newton method";
67
68    fn next_iter(
69        &mut self,
70        op: &mut OpWrapper<O>,
71        state: &IterState<O>,
72    ) -> Result<ArgminIterData<O>, Error> {
73        let param = state.get_param();
74        let grad = op.gradient(&param)?;
75        let hessian = op.hessian(&param)?;
76        let new_param = param.scaled_sub(&self.gamma, &hessian.inv()?.dot(&grad));
77        Ok(ArgminIterData::new().param(new_param))
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use crate::test_trait_impl;
85
86    test_trait_impl!(newton_method, Newton<f64>);
87}