using System; using System.Collections.Generic; using System.Linq; using System.Text; using MathNet.Numerics.LinearAlgebra; namespace MathNet.Numerics.Optimization { public interface IEvaluation { Vector Point { get; } double Value { get; } Vector Gradient { get; } Matrix Hessian { get; } } public interface IObjectiveFunction { bool GradientSupported { get; } bool HessianSupported { get; } IEvaluation Evaluate(Vector point); } public abstract class BaseEvaluation : IEvaluation { protected double? _value; protected Vector _gradient; protected Matrix _hessian; protected Vector _point; public Vector Point { get { return _point; } } public double Value { get { if (!_value.HasValue) setValue(); return _value.Value; } } public Vector Gradient { get { if (_gradient == null) setGradient(); return _gradient; } } public Matrix Hessian { get { if (_hessian == null) setHessian(); return _hessian; } } protected abstract void setValue(); protected abstract void setGradient(); protected abstract void setHessian(); } public class CachedEvaluation : IEvaluation { private double? _value; private Vector _gradient; private Matrix _hessian; private SimpleObjectiveFunction _objective_object; private Vector _point; public CachedEvaluation(SimpleObjectiveFunction f, Vector point) { _objective_object = f; _point = point; } private double setValue() { _value = _objective_object.Objective(_point); return _value.Value; } private Vector setGradient() { _gradient = _objective_object.Gradient(_point); return _gradient; } private Matrix setHessian() { _hessian = _objective_object.Hessian(_point); return _hessian; } public Vector Point { get { return _point; } } public double Value { get { return _value ?? setValue(); } } public Vector Gradient { get { return _gradient ?? setGradient(); } } public Matrix Hessian { get { return _hessian ?? setHessian(); } } } public class SimpleObjectiveFunction : IObjectiveFunction { public Func,double> Objective { get; private set; } public Func,Vector> Gradient { get; private set; } public Func, Matrix> Hessian { get; private set; } public SimpleObjectiveFunction(Func,double> objective) { this.Objective = objective; this.Gradient = null; this.Hessian = null; } public SimpleObjectiveFunction(Func,double> objective, Func,Vector> gradient) { this.Objective = objective; this.Gradient = gradient; this.Hessian = null; } public SimpleObjectiveFunction(Func,double> objective, Func,Vector> gradient, Func, Matrix> hessian) { this.Objective = objective; this.Gradient = gradient; this.Hessian = hessian; } public bool GradientSupported { get { return this.Gradient != null; } } public bool HessianSupported { get { return this.Hessian != null; } } public IEvaluation Evaluate(Vector point) { return new CachedEvaluation(this, point); } } }