graphmind_optimization/
common.rs1use ndarray::Array1;
2use serde::{Deserialize, Serialize};
3
4#[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
17pub trait Problem: Send + Sync {
19 fn objective(&self, variables: &Array1<f64>) -> f64;
21
22 fn penalty(&self, _variables: &Array1<f64>) -> f64 {
24 0.0
25 }
26
27 fn fitness(&self, variables: &Array1<f64>) -> f64 {
29 self.objective(variables) + self.penalty(variables)
30 }
31
32 fn dim(&self) -> usize;
34
35 fn bounds(&self) -> (Array1<f64>, Array1<f64>);
37}
38
39#[derive(Clone, Debug, Serialize, Deserialize)]
41pub struct MultiObjectiveIndividual {
42 pub variables: Array1<f64>,
43 pub fitness: Vec<f64>,
44 pub rank: usize,
45 pub crowding_distance: f64,
46}
47
48impl MultiObjectiveIndividual {
49 pub fn new(variables: Array1<f64>, fitness: Vec<f64>) -> Self {
50 Self {
51 variables,
52 fitness,
53 rank: 0,
54 crowding_distance: 0.0,
55 }
56 }
57}
58
59pub trait MultiObjectiveProblem: Send + Sync {
61 fn objectives(&self, variables: &Array1<f64>) -> Vec<f64>;
63
64 fn penalties(&self, _variables: &Array1<f64>) -> Vec<f64> {
66 vec![]
67 }
68
69 fn dim(&self) -> usize;
71
72 fn bounds(&self) -> (Array1<f64>, Array1<f64>);
74
75 fn num_objectives(&self) -> usize;
77}
78
79#[derive(Debug, Serialize, Deserialize)]
81pub struct MultiObjectiveResult {
82 pub pareto_front: Vec<MultiObjectiveIndividual>,
83 pub history: Vec<f64>, }
85
86#[derive(Clone, Debug, Serialize, Deserialize)]
88pub struct SolverConfig {
89 pub population_size: usize,
90 pub max_iterations: usize,
91}
92
93impl Default for SolverConfig {
94 fn default() -> Self {
95 Self {
96 population_size: 50,
97 max_iterations: 100,
98 }
99 }
100}
101
102#[derive(Debug, Serialize, Deserialize)]
104pub struct OptimizationResult {
105 pub best_variables: Array1<f64>,
106 pub best_fitness: f64,
107 pub history: Vec<f64>,
108}
109
110pub struct SimpleProblem<F>
112where
113 F: Fn(&Array1<f64>) -> f64 + Send + Sync,
114{
115 pub objective_func: F,
116 pub dim: usize,
117 pub lower: Array1<f64>,
118 pub upper: Array1<f64>,
119}
120
121impl<F> Problem for SimpleProblem<F>
122where
123 F: Fn(&Array1<f64>) -> f64 + Send + Sync,
124{
125 fn objective(&self, variables: &Array1<f64>) -> f64 {
126 (self.objective_func)(variables)
127 }
128
129 fn dim(&self) -> usize {
130 self.dim
131 }
132
133 fn bounds(&self) -> (Array1<f64>, Array1<f64>) {
134 (self.lower.clone(), self.upper.clone())
135 }
136}