samyama_optimization/
common.rs

1use ndarray::Array1;
2use serde::{Deserialize, Serialize};
3
4/// Represents a candidate solution in the optimization space.
5#[derive(Clone, Debug, Serialize, Deserialize)]
6pub struct Individual {
7    pub variables: Array1<f64>,
8    pub fitness: f64,
9}
10
11impl Individual {
12    pub fn new(variables: Array1<f64>, fitness: f64) -> Self {
13        Self { variables, fitness }
14    }
15}
16
17/// Defines the optimization problem.
18pub trait Problem: Send + Sync {
19    /// The objective function to minimize.
20    fn objective(&self, variables: &Array1<f64>) -> f64;
21    
22    /// Optional constraints. Returns a penalty score (0 if all satisfied).
23    fn penalty(&self, _variables: &Array1<f64>) -> f64 {
24        0.0
25    }
26
27    /// Combined fitness (objective + penalty).
28    fn fitness(&self, variables: &Array1<f64>) -> f64 {
29        self.objective(variables) + self.penalty(variables)
30    }
31
32    /// Number of variables.
33    fn dim(&self) -> usize;
34
35    /// Lower and upper bounds for each variable.
36    fn bounds(&self) -> (Array1<f64>, Array1<f64>);
37}
38
39/// Configuration for the solver.
40#[derive(Clone, Debug, Serialize, Deserialize)]
41pub struct SolverConfig {
42    pub population_size: usize,
43    pub max_iterations: usize,
44}
45
46impl Default for SolverConfig {
47    fn default() -> Self {
48        Self {
49            population_size: 50,
50            max_iterations: 100,
51        }
52    }
53}
54
55/// The result of an optimization run.
56#[derive(Debug, Serialize, Deserialize)]
57pub struct OptimizationResult {
58    pub best_variables: Array1<f64>,
59    pub best_fitness: f64,
60    pub history: Vec<f64>,
61}
62
63/// A simple problem defined by a closure.
64pub struct SimpleProblem<F> 
65where F: Fn(&Array1<f64>) -> f64 + Send + Sync
66{
67    pub objective_func: F,
68    pub dim: usize,
69    pub lower: Array1<f64>,
70    pub upper: Array1<f64>,
71}
72
73impl<F> Problem for SimpleProblem<F> 
74where F: Fn(&Array1<f64>) -> f64 + Send + Sync
75{
76    fn objective(&self, variables: &Array1<f64>) -> f64 {
77        (self.objective_func)(variables)
78    }
79
80    fn dim(&self) -> usize { self.dim }
81
82    fn bounds(&self) -> (Array1<f64>, Array1<f64>) {
83        (self.lower.clone(), self.upper.clone())
84    }
85}