use crate::Objective;
use ndarray::{Array1, ArrayView1};
use num_traits::Float;
pub trait Gradient<T: Float>: Send + Sync {
fn grad(&self, x: ArrayView1<T>) -> Array1<T>;
fn dim(&self) -> usize;
}
pub trait DifferentiableObjective<T: Float>: Objective<T> + Gradient<T> {
fn value_and_gradient(&self, x: ArrayView1<T>) -> (T, Array1<T>) {
(self.eval(x), self.grad(x))
}
}
pub struct AnalyticGradient<F>
where
F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
{
pub grad_fn: F,
pub dim: usize,
}
impl<F> AnalyticGradient<F>
where
F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
{
pub fn new(dim: usize, grad_fn: F) -> Self {
Self { grad_fn, dim }
}
}
impl<F> Gradient<f64> for AnalyticGradient<F>
where
F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
{
fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
(self.grad_fn)(x)
}
fn dim(&self) -> usize {
self.dim
}
}
pub struct FiniteDiffGradient<O: Objective<f64>> {
pub obj: O,
pub h: f64,
}
impl<O: Objective<f64>> FiniteDiffGradient<O> {
pub fn new(obj: O) -> Self {
Self { obj, h: 1e-5 }
}
pub fn with_step(obj: O, h: f64) -> Self {
assert!(h > 0.0, "h must be positive");
Self { obj, h }
}
}
impl<O: Objective<f64> + Send + Sync> Gradient<f64> for FiniteDiffGradient<O> {
fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
let n = x.len();
let mut g = Array1::zeros(n);
let mut xp = x.to_owned();
let mut xm = x.to_owned();
for i in 0..n {
xp[i] = x[i] + self.h;
xm[i] = x[i] - self.h;
g[i] = (self.obj.eval(xp.view()) - self.obj.eval(xm.view())) / (2.0 * self.h);
xp[i] = x[i];
xm[i] = x[i];
}
g
}
fn dim(&self) -> usize {
self.obj.dim()
}
}
#[cfg(test)]
mod fused_override_tests {
use super::*;
use crate::{Bounds, Objective};
use ndarray::{Array1, ArrayView1};
struct Counted;
impl Objective<f64> for Counted {
fn dim(&self) -> usize {
1
}
fn bounds(&self) -> &Bounds<f64> {
static CELL: std::sync::OnceLock<Bounds<f64>> = std::sync::OnceLock::new();
CELL.get_or_init(|| Bounds::new(Array1::from_elem(1, -1.0), Array1::from_elem(1, 1.0), 0.0))
}
fn eval(&self, _x: ArrayView1<f64>) -> f64 {
panic!("split eval must not run when value_and_gradient is fused")
}
}
impl Gradient<f64> for Counted {
fn dim(&self) -> usize {
1
}
fn grad(&self, _x: ArrayView1<f64>) -> Array1<f64> {
panic!("split grad must not run when value_and_gradient is fused")
}
}
impl DifferentiableObjective<f64> for Counted {
fn value_and_gradient(&self, x: ArrayView1<f64>) -> (f64, Array1<f64>) {
(x[0] * x[0], Array1::from_elem(1, 2.0 * x[0]))
}
}
#[test]
fn override_is_fused() {
let obj = Counted;
let x = Array1::from_elem(1, 3.0);
let (v, g) = obj.value_and_gradient(x.view());
assert_eq!(v, 9.0);
assert_eq!(g[0], 6.0);
}
}