Skip to main content

oxilean_std/convex_optimization/
quadraticfunction_traits.rs

1//! # QuadraticFunction - Trait Implementations
2//!
3//! This module contains trait implementations for `QuadraticFunction`.
4//!
5//! ## Implemented Traits
6//!
7//! - `ConvexFunction`
8//!
9//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
10
11use super::functions::ConvexFunction;
12use super::types::QuadraticFunction;
13
14impl ConvexFunction for QuadraticFunction {
15    /// f(x) = 0.5 * x^T Q x + c^T x + d.
16    fn eval(&self, x: &[f64]) -> f64 {
17        let n = x.len();
18        let mut quad = 0.0_f64;
19        for i in 0..n {
20            for j in 0..n {
21                quad += x[i] * self.coeffs[i][j] * x[j];
22            }
23        }
24        let linear: f64 = self.linear.iter().zip(x).map(|(c, xi)| c * xi).sum();
25        0.5 * quad + linear + self.constant
26    }
27    /// ∇f(x) = Q x + c.
28    fn gradient(&self, x: &[f64]) -> Vec<f64> {
29        let n = x.len();
30        let mut grad = vec![0.0_f64; n];
31        for i in 0..n {
32            for j in 0..n {
33                grad[i] += self.coeffs[i][j] * x[j];
34            }
35            grad[i] += self.linear[i];
36        }
37        grad
38    }
39    /// A quadratic function is strongly convex iff Q is positive definite (approximated
40    /// here by checking that all diagonal entries are strictly positive).
41    fn is_strongly_convex(&self) -> bool {
42        self.coeffs.iter().enumerate().all(|(i, row)| row[i] > 0.0)
43    }
44}