argmin/core/state/populationstate.rs
1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::core::{ArgminFloat, Problem, State, TerminationReason, TerminationStatus};
9#[cfg(feature = "serde1")]
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use web_time::Duration;
13
14/// Maintains the state from iteration to iteration of a population-based solver
15///
16/// This struct is passed from one iteration of an algorithm to the next.
17///
18/// Keeps track of
19///
20/// * individual of current and previous iteration
21/// * best individual of current and previous iteration
22/// * current and previous best cost function value
23/// * target cost function value
24/// * population (for population based algorithms)
25/// * current iteration number
26/// * iteration number where the last best individual was found
27/// * maximum number of iterations that will be executed
28/// * problem function evaluation counts
29/// * elapsed time
30/// * termination status
31#[derive(Clone, Default, Debug, Eq, PartialEq)]
32#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
33pub struct PopulationState<P, F> {
34 /// Current individual vector
35 pub individual: Option<P>,
36 /// Previous individual vector
37 pub prev_individual: Option<P>,
38 /// Current best individual vector
39 pub best_individual: Option<P>,
40 /// Previous best individual vector
41 pub prev_best_individual: Option<P>,
42 /// Current cost function value
43 pub cost: F,
44 /// Previous cost function value
45 pub prev_cost: F,
46 /// Current best cost function value
47 pub best_cost: F,
48 /// Previous best cost function value
49 pub prev_best_cost: F,
50 /// Target cost function value
51 pub target_cost: F,
52 /// All members of the population
53 pub population: Option<Vec<P>>,
54 /// Current iteration
55 pub iter: u64,
56 /// Iteration number of last best cost
57 pub last_best_iter: u64,
58 /// Maximum number of iterations
59 pub max_iters: u64,
60 /// Evaluation counts
61 pub counts: HashMap<String, u64>,
62 /// Update evaluation counts?
63 pub counting_enabled: bool,
64 /// Time required so far
65 pub time: Option<Duration>,
66 /// Status of optimization execution
67 pub termination_status: TerminationStatus,
68}
69
70impl<P, F> PopulationState<P, F>
71where
72 Self: State<Float = F>,
73 F: ArgminFloat,
74{
75 /// Set best individual of current iteration. This shifts the stored individual to the
76 /// previous individual.
77 ///
78 /// # Example
79 ///
80 /// ```
81 /// # use argmin::core::{PopulationState, State};
82 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
83 /// # let individual_old = vec![1.0f64, 2.0f64];
84 /// # let state = state.individual(individual_old);
85 /// # assert!(state.prev_individual.is_none());
86 /// # assert_eq!(state.individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
87 /// # assert_eq!(state.individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
88 /// # let individual = vec![0.0f64, 3.0f64];
89 /// let state = state.individual(individual);
90 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
91 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
92 /// # assert_eq!(state.individual.as_ref().unwrap()[0].to_ne_bytes(), 0.0f64.to_ne_bytes());
93 /// # assert_eq!(state.individual.as_ref().unwrap()[1].to_ne_bytes(), 3.0f64.to_ne_bytes());
94 /// ```
95 #[must_use]
96 pub fn individual(mut self, individual: P) -> Self {
97 std::mem::swap(&mut self.prev_individual, &mut self.individual);
98 self.individual = Some(individual);
99 self
100 }
101 /// Set the current cost function value. This shifts the stored cost function value to the
102 /// previous cost function value.
103 ///
104 /// # Example
105 ///
106 /// ```
107 /// # use argmin::core::{PopulationState, State};
108 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
109 /// # let cost_old = 1.0f64;
110 /// # let state = state.cost(cost_old);
111 /// # assert_eq!(state.prev_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
112 /// # assert_eq!(state.cost.to_ne_bytes(), 1.0f64.to_ne_bytes());
113 /// # let cost = 0.0f64;
114 /// let state = state.cost(cost);
115 /// # assert_eq!(state.prev_cost.to_ne_bytes(), 1.0f64.to_ne_bytes());
116 /// # assert_eq!(state.cost.to_ne_bytes(), 0.0f64.to_ne_bytes());
117 /// ```
118 #[must_use]
119 pub fn cost(mut self, cost: F) -> Self {
120 std::mem::swap(&mut self.prev_cost, &mut self.cost);
121 self.cost = cost;
122 self
123 }
124
125 /// Set target cost.
126 ///
127 /// When this cost is reached, the algorithm will stop. The default is
128 /// `Self::Float::NEG_INFINITY`.
129 ///
130 /// # Example
131 ///
132 /// ```
133 /// # use argmin::core::{PopulationState, State, ArgminFloat};
134 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
135 /// # assert_eq!(state.target_cost.to_ne_bytes(), f64::NEG_INFINITY.to_ne_bytes());
136 /// let state = state.target_cost(0.0);
137 /// # assert_eq!(state.target_cost.to_ne_bytes(), 0.0f64.to_ne_bytes());
138 /// ```
139 #[must_use]
140 pub fn target_cost(mut self, target_cost: F) -> Self {
141 self.target_cost = target_cost;
142 self
143 }
144
145 /// Set population.
146 ///
147 /// A population is a `Vec` of individuals.
148 ///
149 /// # Example
150 ///
151 /// ```
152 /// # use argmin::core::{PopulationState, State};
153 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
154 /// # assert!(state.population.is_none());
155 /// # let individual1 = vec![0.0f64, 1.0f64];
156 /// # let individual2 = vec![2.0f64, 3.0f64];
157 /// let state = state.population(vec![individual1, individual2]);
158 /// # assert_eq!(state.population.as_ref().unwrap()[0][0].to_ne_bytes(), 0.0f64.to_ne_bytes());
159 /// # assert_eq!(state.population.as_ref().unwrap()[0][1].to_ne_bytes(), 1.0f64.to_ne_bytes());
160 /// # assert_eq!(state.population.as_ref().unwrap()[1][0].to_ne_bytes(), 2.0f64.to_ne_bytes());
161 /// # assert_eq!(state.population.as_ref().unwrap()[1][1].to_ne_bytes(), 3.0f64.to_ne_bytes());
162 /// ```
163 #[must_use]
164 pub fn population(mut self, population: Vec<P>) -> Self {
165 self.population = Some(population);
166 self
167 }
168
169 /// Set maximum number of iterations
170 ///
171 /// # Example
172 ///
173 /// ```
174 /// # use argmin::core::{PopulationState, State, ArgminFloat};
175 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
176 /// # assert_eq!(state.max_iters, u64::MAX);
177 /// let state = state.max_iters(1000);
178 /// # assert_eq!(state.max_iters, 1000);
179 /// ```
180 #[must_use]
181 pub fn max_iters(mut self, iters: u64) -> Self {
182 self.max_iters = iters;
183 self
184 }
185
186 /// Returns the current cost function value
187 ///
188 /// # Example
189 ///
190 /// ```
191 /// # use argmin::core::{PopulationState, State, ArgminFloat};
192 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
193 /// # let state = state.cost(2.0);
194 /// let cost = state.get_cost();
195 /// # assert_eq!(cost.to_ne_bytes(), 2.0f64.to_ne_bytes());
196 /// ```
197 pub fn get_cost(&self) -> F {
198 self.cost
199 }
200
201 /// Returns the previous cost function value
202 ///
203 /// # Example
204 ///
205 /// ```
206 /// # use argmin::core::{PopulationState, State, ArgminFloat};
207 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
208 /// # state.prev_cost = 2.0;
209 /// let prev_cost = state.get_prev_cost();
210 /// # assert_eq!(prev_cost.to_ne_bytes(), 2.0f64.to_ne_bytes());
211 /// ```
212 pub fn get_prev_cost(&self) -> F {
213 self.prev_cost
214 }
215
216 /// Returns the current best cost function value
217 ///
218 /// # Example
219 ///
220 /// ```
221 /// # use argmin::core::{PopulationState, State, ArgminFloat};
222 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
223 /// # state.best_cost = 2.0;
224 /// let best_cost = state.get_best_cost();
225 /// # assert_eq!(best_cost.to_ne_bytes(), 2.0f64.to_ne_bytes());
226 /// ```
227 pub fn get_best_cost(&self) -> F {
228 self.best_cost
229 }
230
231 /// Returns the previous best cost function value
232 ///
233 /// # Example
234 ///
235 /// ```
236 /// # use argmin::core::{PopulationState, State, ArgminFloat};
237 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
238 /// # state.prev_best_cost = 2.0;
239 /// let prev_best_cost = state.get_prev_best_cost();
240 /// # assert_eq!(prev_best_cost.to_ne_bytes(), 2.0f64.to_ne_bytes());
241 /// ```
242 pub fn get_prev_best_cost(&self) -> F {
243 self.prev_best_cost
244 }
245
246 /// Returns the target cost function value
247 ///
248 /// # Example
249 ///
250 /// ```
251 /// # use argmin::core::{PopulationState, State, ArgminFloat};
252 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
253 /// # assert_eq!(state.target_cost.to_ne_bytes(), f64::NEG_INFINITY.to_ne_bytes());
254 /// # state.target_cost = 0.0;
255 /// let target_cost = state.get_target_cost();
256 /// # assert_eq!(target_cost.to_ne_bytes(), 0.0f64.to_ne_bytes());
257 /// ```
258 pub fn get_target_cost(&self) -> F {
259 self.target_cost
260 }
261
262 /// Moves the current individual out and replaces it internally with `None`
263 ///
264 /// # Example
265 ///
266 /// ```
267 /// # use argmin::core::{PopulationState, State, ArgminFloat};
268 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
269 /// # assert!(state.take_individual().is_none());
270 /// # let mut state = state.individual(vec![1.0, 2.0]);
271 /// # assert_eq!(state.individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
272 /// # assert_eq!(state.individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
273 /// let individual = state.take_individual(); // Option<P>
274 /// # assert!(state.take_individual().is_none());
275 /// # assert!(state.individual.is_none());
276 /// # assert_eq!(individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
277 /// # assert_eq!(individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
278 /// ```
279 pub fn take_individual(&mut self) -> Option<P> {
280 self.individual.take()
281 }
282
283 /// Returns a reference to previous individual
284 ///
285 /// # Example
286 ///
287 /// ```
288 /// # use argmin::core::{PopulationState, State, ArgminFloat};
289 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
290 /// # assert!(state.prev_individual.is_none());
291 /// # state.prev_individual = Some(vec![1.0, 2.0]);
292 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
293 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
294 /// let prev_individual = state.get_prev_individual(); // Option<&P>
295 /// # assert_eq!(prev_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
296 /// # assert_eq!(prev_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
297 /// ```
298 pub fn get_prev_individual(&self) -> Option<&P> {
299 self.prev_individual.as_ref()
300 }
301
302 /// Moves the previous individual out and replaces it internally with `None`
303 ///
304 /// # Example
305 ///
306 /// ```
307 /// # use argmin::core::{PopulationState, State, ArgminFloat};
308 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
309 /// # assert!(state.take_prev_individual().is_none());
310 /// # state.prev_individual = Some(vec![1.0, 2.0]);
311 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
312 /// # assert_eq!(state.prev_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
313 /// let prev_individual = state.take_prev_individual(); // Option<P>
314 /// # assert!(state.take_prev_individual().is_none());
315 /// # assert!(state.prev_individual.is_none());
316 /// # assert_eq!(prev_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
317 /// # assert_eq!(prev_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
318 /// ```
319 pub fn take_prev_individual(&mut self) -> Option<P> {
320 self.prev_individual.take()
321 }
322
323 /// Returns a reference to previous best individual
324 ///
325 /// # Example
326 ///
327 /// ```
328 /// # use argmin::core::{PopulationState, State, ArgminFloat};
329 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
330 /// # assert!(state.prev_best_individual.is_none());
331 /// # state.prev_best_individual = Some(vec![1.0, 2.0]);
332 /// # assert_eq!(state.prev_best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
333 /// # assert_eq!(state.prev_best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
334 /// let prev_best_individual = state.get_prev_best_individual(); // Option<&P>
335 /// # assert_eq!(prev_best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
336 /// # assert_eq!(prev_best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
337 /// ```
338 pub fn get_prev_best_individual(&self) -> Option<&P> {
339 self.prev_best_individual.as_ref()
340 }
341
342 /// Moves the best individual out and replaces it internally with `None`
343 ///
344 /// # Example
345 ///
346 /// ```
347 /// # use argmin::core::{PopulationState, State, ArgminFloat};
348 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
349 /// # assert!(state.take_best_individual().is_none());
350 /// # state.best_individual = Some(vec![1.0, 2.0]);
351 /// # assert_eq!(state.best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
352 /// # assert_eq!(state.best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
353 /// let best_individual = state.take_best_individual(); // Option<P>
354 /// # assert!(state.take_best_individual().is_none());
355 /// # assert!(state.best_individual.is_none());
356 /// # assert_eq!(best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
357 /// # assert_eq!(best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
358 /// ```
359 pub fn take_best_individual(&mut self) -> Option<P> {
360 self.best_individual.take()
361 }
362
363 /// Moves the previous best individual out and replaces it internally with `None`
364 ///
365 /// # Example
366 ///
367 /// ```
368 /// # use argmin::core::{PopulationState, State, ArgminFloat};
369 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
370 /// # assert!(state.take_prev_best_individual().is_none());
371 /// # state.prev_best_individual = Some(vec![1.0, 2.0]);
372 /// # assert_eq!(state.prev_best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
373 /// # assert_eq!(state.prev_best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
374 /// let prev_best_individual = state.take_prev_best_individual(); // Option<P>
375 /// # assert!(state.take_prev_best_individual().is_none());
376 /// # assert!(state.prev_best_individual.is_none());
377 /// # assert_eq!(prev_best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
378 /// # assert_eq!(prev_best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
379 /// ```
380 pub fn take_prev_best_individual(&mut self) -> Option<P> {
381 self.prev_best_individual.take()
382 }
383
384 /// Returns a reference to the population
385 ///
386 /// # Example
387 ///
388 /// ```
389 /// # use argmin::core::{PopulationState, State, ArgminFloat};
390 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
391 /// # assert!(state.population.is_none());
392 /// # assert!(state.get_population().is_none());
393 /// # let individual1 = vec![0.0f64, 1.0f64];
394 /// # let individual2 = vec![2.0f64, 3.0f64];
395 /// # let state = state.population(vec![individual1, individual2]);
396 /// # assert_eq!(state.population.as_ref().unwrap()[0][0].to_ne_bytes(), 0.0f64.to_ne_bytes());
397 /// # assert_eq!(state.population.as_ref().unwrap()[0][1].to_ne_bytes(), 1.0f64.to_ne_bytes());
398 /// # assert_eq!(state.population.as_ref().unwrap()[1][0].to_ne_bytes(), 2.0f64.to_ne_bytes());
399 /// # assert_eq!(state.population.as_ref().unwrap()[1][1].to_ne_bytes(), 3.0f64.to_ne_bytes());
400 /// let population = state.get_population();
401 /// # assert_eq!(population.unwrap()[0][0].to_ne_bytes(), 0.0f64.to_ne_bytes());
402 /// # assert_eq!(population.unwrap()[0][1].to_ne_bytes(), 1.0f64.to_ne_bytes());
403 /// # assert_eq!(population.unwrap()[1][0].to_ne_bytes(), 2.0f64.to_ne_bytes());
404 /// # assert_eq!(population.unwrap()[1][1].to_ne_bytes(), 3.0f64.to_ne_bytes());
405 /// ```
406 pub fn get_population(&self) -> Option<&Vec<P>> {
407 self.population.as_ref()
408 }
409
410 /// Takes population and replaces it internally with `None`.
411 ///
412 /// # Example
413 ///
414 /// ```
415 /// # use argmin::core::{PopulationState, State, ArgminFloat};
416 /// # let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
417 /// # assert!(state.population.is_none());
418 /// # assert!(state.get_population().is_none());
419 /// # let individual1 = vec![0.0f64, 1.0f64];
420 /// # let individual2 = vec![2.0f64, 3.0f64];
421 /// # let state = state.population(vec![individual1, individual2]);
422 /// # assert_eq!(state.population.as_ref().unwrap()[0][0].to_ne_bytes(), 0.0f64.to_ne_bytes());
423 /// # assert_eq!(state.population.as_ref().unwrap()[0][1].to_ne_bytes(), 1.0f64.to_ne_bytes());
424 /// # assert_eq!(state.population.as_ref().unwrap()[1][0].to_ne_bytes(), 2.0f64.to_ne_bytes());
425 /// # assert_eq!(state.population.as_ref().unwrap()[1][1].to_ne_bytes(), 3.0f64.to_ne_bytes());
426 /// let population = state.get_population();
427 /// # assert_eq!(population.unwrap()[0][0].to_ne_bytes(), 0.0f64.to_ne_bytes());
428 /// # assert_eq!(population.unwrap()[0][1].to_ne_bytes(), 1.0f64.to_ne_bytes());
429 /// # assert_eq!(population.unwrap()[1][0].to_ne_bytes(), 2.0f64.to_ne_bytes());
430 /// # assert_eq!(population.unwrap()[1][1].to_ne_bytes(), 3.0f64.to_ne_bytes());
431 /// ```
432 pub fn take_population(&mut self) -> Option<Vec<P>> {
433 self.population.take()
434 }
435
436 /// Overrides state of counting function executions (default: false)
437 /// ```
438 /// # use argmin::core::{State, PopulationState};
439 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
440 /// # assert!(!state.counting_enabled);
441 /// let state = state.counting(true);
442 /// # assert!(state.counting_enabled);
443 /// ```
444 #[must_use]
445 pub fn counting(mut self, mode: bool) -> Self {
446 self.counting_enabled = mode;
447 self
448 }
449}
450
451impl<P, F> State for PopulationState<P, F>
452where
453 P: Clone,
454 F: ArgminFloat,
455{
456 /// Type of an individual
457 type Param = P;
458 /// Floating point precision
459 type Float = F;
460
461 /// Create a new PopulationState instance
462 ///
463 /// # Example
464 ///
465 /// ```
466 /// # extern crate web_time;
467 /// # use web_time::Duration;
468 /// # use argmin::core::{PopulationState, State, ArgminFloat, TerminationStatus};
469 /// let state: PopulationState<Vec<f64>, f64> = PopulationState::new();
470 /// # assert!(state.individual.is_none());
471 /// # assert!(state.prev_individual.is_none());
472 /// # assert!(state.best_individual.is_none());
473 /// # assert!(state.prev_best_individual.is_none());
474 /// # assert_eq!(state.cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
475 /// # assert_eq!(state.prev_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
476 /// # assert_eq!(state.best_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
477 /// # assert_eq!(state.prev_best_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
478 /// # assert_eq!(state.target_cost.to_ne_bytes(), f64::NEG_INFINITY.to_ne_bytes());
479 /// # assert!(state.population.is_none());
480 /// # assert_eq!(state.iter, 0);
481 /// # assert_eq!(state.last_best_iter, 0);
482 /// # assert_eq!(state.max_iters, u64::MAX);
483 /// # assert_eq!(state.counts.len(), 0);
484 /// # assert_eq!(state.time.unwrap(), Duration::ZERO);
485 /// # assert_eq!(state.termination_status, TerminationStatus::NotTerminated);
486 /// ```
487 fn new() -> Self {
488 PopulationState {
489 individual: None,
490 prev_individual: None,
491 best_individual: None,
492 prev_best_individual: None,
493 cost: F::infinity(),
494 prev_cost: F::infinity(),
495 best_cost: F::infinity(),
496 prev_best_cost: F::infinity(),
497 target_cost: F::neg_infinity(),
498 population: None,
499 iter: 0,
500 last_best_iter: 0,
501 max_iters: u64::MAX,
502 counts: HashMap::new(),
503 counting_enabled: false,
504 time: Some(Duration::ZERO),
505 termination_status: TerminationStatus::NotTerminated,
506 }
507 }
508
509 /// Checks if the current individual is better than the previous best individual. If
510 /// a new best individual was found, the state is updated accordingly.
511 ///
512 /// # Example
513 ///
514 /// ```
515 /// # use argmin::core::{PopulationState, State, ArgminFloat};
516 /// let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
517 ///
518 /// // Simulating a new, better individual
519 /// state.best_individual = Some(vec![1.0f64]);
520 /// state.best_cost = 10.0;
521 /// state.individual = Some(vec![2.0f64]);
522 /// state.cost = 5.0;
523 ///
524 /// // Calling update
525 /// state.update();
526 ///
527 /// // Check if update was successful
528 /// assert_eq!(state.best_individual.as_ref().unwrap()[0], 2.0f64);
529 /// assert_eq!(state.best_cost.to_ne_bytes(), state.best_cost.to_ne_bytes());
530 /// assert!(state.is_best());
531 /// ```
532 ///
533 /// For algorithms which do not compute the cost function, every new individual will be
534 /// the new best:
535 ///
536 /// ```
537 /// # use argmin::core::{PopulationState, State, ArgminFloat};
538 /// let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
539 ///
540 /// // Simulating a new, better individual
541 /// state.best_individual = Some(vec![1.0f64]);
542 /// state.individual = Some(vec![2.0f64]);
543 ///
544 /// // Calling update
545 /// state.update();
546 ///
547 /// // Check if update was successful
548 /// assert_eq!(state.best_individual.as_ref().unwrap()[0], 2.0f64);
549 /// assert_eq!(state.best_cost.to_ne_bytes(), state.best_cost.to_ne_bytes());
550 /// assert!(state.is_best());
551 /// ```
552 fn update(&mut self) {
553 // check if individual is the best so far
554 // Comparison is done using `<` to avoid new solutions with the same cost function value as
555 // the current best to be accepted. However, some solvers to not compute the cost function
556 // value. Those will always have `Inf` cost. Therefore if both the new value and the
557 // previous best value are `Inf`, the solution is also accepted. Care is taken that both
558 // `Inf` also have the same sign.
559 if self.cost < self.best_cost
560 || (self.cost.is_infinite()
561 && self.best_cost.is_infinite()
562 && self.cost.is_sign_positive() == self.best_cost.is_sign_positive())
563 {
564 // If there is no individual, then also don't set the best individual.
565 if let Some(individual) = self.individual.as_ref().cloned() {
566 std::mem::swap(&mut self.prev_best_individual, &mut self.best_individual);
567 self.best_individual = Some(individual);
568 }
569 std::mem::swap(&mut self.prev_best_cost, &mut self.best_cost);
570 self.best_cost = self.cost;
571 self.last_best_iter = self.iter;
572 }
573 }
574
575 /// Returns a reference to the current individual
576 ///
577 /// # Example
578 ///
579 /// ```
580 /// # use argmin::core::{PopulationState, State, ArgminFloat};
581 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
582 /// # assert!(state.individual.is_none());
583 /// # state.individual = Some(vec![1.0, 2.0]);
584 /// # assert_eq!(state.individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
585 /// # assert_eq!(state.individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
586 /// let individual = state.get_param(); // Option<&P>
587 /// # assert_eq!(individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
588 /// # assert_eq!(individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
589 /// ```
590 fn get_param(&self) -> Option<&P> {
591 self.individual.as_ref()
592 }
593
594 /// Returns a reference to the current best individual
595 ///
596 /// # Example
597 ///
598 /// ```
599 /// # use argmin::core::{PopulationState, State, ArgminFloat};
600 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
601 /// # assert!(state.best_individual.is_none());
602 /// # state.best_individual = Some(vec![1.0, 2.0]);
603 /// # assert_eq!(state.best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
604 /// # assert_eq!(state.best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
605 /// let best_individual = state.get_best_param(); // Option<&P>
606 /// # assert_eq!(best_individual.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
607 /// # assert_eq!(best_individual.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
608 /// ```
609 fn get_best_param(&self) -> Option<&P> {
610 self.best_individual.as_ref()
611 }
612
613 /// Sets the termination status to [`Terminated`](`TerminationStatus::Terminated`) with the given reason
614 ///
615 /// # Example
616 ///
617 /// ```
618 /// # use argmin::core::{PopulationState, State, ArgminFloat, TerminationReason, TerminationStatus};
619 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
620 /// # assert_eq!(state.termination_status, TerminationStatus::NotTerminated);
621 /// let state = state.terminate_with(TerminationReason::MaxItersReached);
622 /// # assert_eq!(state.termination_status, TerminationStatus::Terminated(TerminationReason::MaxItersReached));
623 /// ```
624 fn terminate_with(mut self, reason: TerminationReason) -> Self {
625 self.termination_status = TerminationStatus::Terminated(reason);
626 self
627 }
628
629 /// Sets the time required so far.
630 ///
631 /// # Example
632 ///
633 /// ```
634 /// # extern crate web_time;
635 /// # use web_time::Duration;
636 /// # use argmin::core::{PopulationState, State, ArgminFloat, TerminationReason};
637 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
638 /// let state = state.time(Some(Duration::from_nanos(12)));
639 /// # assert_eq!(state.time.unwrap(), Duration::from_nanos(12));
640 /// ```
641 fn time(&mut self, time: Option<Duration>) -> &mut Self {
642 self.time = time;
643 self
644 }
645
646 /// Returns current cost function value.
647 ///
648 /// # Example
649 ///
650 /// ```
651 /// # use argmin::core::{PopulationState, State, ArgminFloat};
652 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
653 /// # state.cost = 12.0;
654 /// let cost = state.get_cost();
655 /// # assert_eq!(cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
656 /// ```
657 fn get_cost(&self) -> Self::Float {
658 self.cost
659 }
660
661 /// Returns current best cost function value.
662 ///
663 /// # Example
664 ///
665 /// ```
666 /// # use argmin::core::{PopulationState, State, ArgminFloat};
667 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
668 /// # state.best_cost = 12.0;
669 /// let best_cost = state.get_best_cost();
670 /// # assert_eq!(best_cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
671 /// ```
672 fn get_best_cost(&self) -> Self::Float {
673 self.best_cost
674 }
675
676 /// Returns target cost function value.
677 ///
678 /// # Example
679 ///
680 /// ```
681 /// # use argmin::core::{PopulationState, State, ArgminFloat};
682 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
683 /// # state.target_cost = 12.0;
684 /// let target_cost = state.get_target_cost();
685 /// # assert_eq!(target_cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
686 /// ```
687 fn get_target_cost(&self) -> Self::Float {
688 self.target_cost
689 }
690
691 /// Returns current number of iterations.
692 ///
693 /// # Example
694 ///
695 /// ```
696 /// # use argmin::core::{PopulationState, State, ArgminFloat};
697 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
698 /// # state.iter = 12;
699 /// let iter = state.get_iter();
700 /// # assert_eq!(iter, 12);
701 /// ```
702 fn get_iter(&self) -> u64 {
703 self.iter
704 }
705
706 /// Returns iteration number of last best individual
707 ///
708 /// # Example
709 ///
710 /// ```
711 /// # use argmin::core::{PopulationState, State, ArgminFloat};
712 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
713 /// # state.last_best_iter = 12;
714 /// let last_best_iter = state.get_last_best_iter();
715 /// # assert_eq!(last_best_iter, 12);
716 /// ```
717 fn get_last_best_iter(&self) -> u64 {
718 self.last_best_iter
719 }
720
721 /// Returns the maximum number of iterations.
722 ///
723 /// # Example
724 ///
725 /// ```
726 /// # use argmin::core::{PopulationState, State, ArgminFloat};
727 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
728 /// # state.max_iters = 12;
729 /// let max_iters = state.get_max_iters();
730 /// # assert_eq!(max_iters, 12);
731 /// ```
732 fn get_max_iters(&self) -> u64 {
733 self.max_iters
734 }
735
736 /// Returns the termination reason.
737 ///
738 /// # Example
739 ///
740 /// ```
741 /// # use argmin::core::{PopulationState, State, ArgminFloat, TerminationStatus};
742 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
743 /// let termination_status = state.get_termination_status();
744 /// # assert_eq!(*termination_status, TerminationStatus::NotTerminated);
745 /// ```
746 fn get_termination_status(&self) -> &TerminationStatus {
747 &self.termination_status
748 }
749
750 /// Returns the termination reason if terminated, otherwise None.
751 ///
752 /// # Example
753 ///
754 /// ```
755 /// # use argmin::core::{PopulationState, State, ArgminFloat, TerminationReason};
756 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
757 /// let termination_reason = state.get_termination_reason();
758 /// # assert_eq!(termination_reason, None);
759 /// ```
760 fn get_termination_reason(&self) -> Option<&TerminationReason> {
761 match &self.termination_status {
762 TerminationStatus::Terminated(reason) => Some(reason),
763 TerminationStatus::NotTerminated => None,
764 }
765 }
766
767 /// Returns the time elapsed since the start of the optimization.
768 ///
769 /// # Example
770 ///
771 /// ```
772 /// # extern crate web_time;
773 /// # use web_time::Duration;
774 /// # use argmin::core::{PopulationState, State, ArgminFloat};
775 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
776 /// let time = state.get_time();
777 /// # assert_eq!(time.unwrap(), Duration::ZERO);
778 /// ```
779 fn get_time(&self) -> Option<Duration> {
780 self.time
781 }
782
783 /// Increments the number of iterations by one
784 ///
785 /// # Example
786 ///
787 /// ```
788 /// # use argmin::core::{PopulationState, State, ArgminFloat};
789 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
790 /// # assert_eq!(state.iter, 0);
791 /// state.increment_iter();
792 /// # assert_eq!(state.iter, 1);
793 /// ```
794 fn increment_iter(&mut self) {
795 self.iter += 1;
796 }
797
798 /// Set all function evaluation counts to the evaluation counts of another `Problem`.
799 ///
800 /// ```
801 /// # use std::collections::HashMap;
802 /// # use argmin::core::{Problem, PopulationState, State, ArgminFloat};
803 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new().counting(true);
804 /// # assert_eq!(state.counts, HashMap::new());
805 /// # state.counts.insert("test2".to_string(), 10u64);
806 /// #
807 /// # #[derive(Eq, PartialEq, Debug)]
808 /// # struct UserDefinedProblem {};
809 /// #
810 /// # let mut problem = Problem::new(UserDefinedProblem {});
811 /// # problem.counts.insert("test1", 10u64);
812 /// # problem.counts.insert("test2", 2);
813 /// state.func_counts(&problem);
814 /// # let mut hm = HashMap::new();
815 /// # hm.insert("test1".to_string(), 10u64);
816 /// # hm.insert("test2".to_string(), 2u64);
817 /// # assert_eq!(state.counts, hm);
818 /// ```
819 fn func_counts<O>(&mut self, problem: &Problem<O>) {
820 if self.counting_enabled {
821 for (k, &v) in problem.counts.iter() {
822 let count = self.counts.entry(k.to_string()).or_insert(0);
823 *count = v
824 }
825 }
826 }
827
828 /// Returns function evaluation counts
829 ///
830 /// # Example
831 ///
832 /// ```
833 /// # use std::collections::HashMap;
834 /// # use argmin::core::{PopulationState, State, ArgminFloat};
835 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
836 /// # assert_eq!(state.counts, HashMap::new());
837 /// # state.counts.insert("test2".to_string(), 10u64);
838 /// let counts = state.get_func_counts();
839 /// # let mut hm = HashMap::new();
840 /// # hm.insert("test2".to_string(), 10u64);
841 /// # assert_eq!(*counts, hm);
842 /// ```
843 fn get_func_counts(&self) -> &HashMap<String, u64> {
844 &self.counts
845 }
846
847 /// Returns whether the current individual is also the best individual found so
848 /// far.
849 ///
850 /// # Example
851 ///
852 /// ```
853 /// # use argmin::core::{PopulationState, State, ArgminFloat};
854 /// # let mut state: PopulationState<Vec<f64>, f64> = PopulationState::new();
855 /// # state.last_best_iter = 12;
856 /// # state.iter = 12;
857 /// let is_best = state.is_best();
858 /// # assert!(is_best);
859 /// # state.last_best_iter = 12;
860 /// # state.iter = 21;
861 /// # let is_best = state.is_best();
862 /// # assert!(!is_best);
863 /// ```
864 fn is_best(&self) -> bool {
865 self.last_best_iter == self.iter
866 }
867}
868
869// TODO: Tests? Actually doc tests should already cover everything.