argmin/core/state/linearprogramstate.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 solver
15///
16/// This struct is passed from one iteration of an algorithm to the next.
17///
18/// Keeps track of
19///
20/// * parameter vector of current and previous iteration
21/// * best parameter vector of current and previous iteration
22/// * cost function value of current and previous iteration
23/// * current and previous best cost function value
24/// * target cost function value
25/// * current iteration number
26/// * iteration number where the last best parameter vector was found
27/// * maximum number of iterations that will be executed
28/// * problem function evaluation counts (cost function, gradient, jacobian, hessian,
29/// * elapsed time
30/// * termination status
31#[derive(Clone, Debug)]
32#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
33pub struct LinearProgramState<P, F> {
34 /// Current parameter vector
35 pub param: Option<P>,
36 /// Previous parameter vector
37 pub prev_param: Option<P>,
38 /// Current best parameter vector
39 pub best_param: Option<P>,
40 /// Previous best parameter vector
41 pub prev_best_param: 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 /// Current iteration
53 pub iter: u64,
54 /// Iteration number of last best cost
55 pub last_best_iter: u64,
56 /// Maximum number of iterations
57 pub max_iters: u64,
58 /// Evaluation counts
59 pub counts: HashMap<String, u64>,
60 /// Update evaluation counts?
61 pub counting_enabled: bool,
62 /// Time required so far
63 pub time: Option<Duration>,
64 /// Status of optimization execution
65 pub termination_status: TerminationStatus,
66}
67
68impl<P, F> LinearProgramState<P, F> {
69 /// Set parameter vector. This shifts the stored parameter vector to the previous parameter
70 /// vector.
71 ///
72 /// # Example
73 ///
74 /// ```
75 /// # use argmin::core::{LinearProgramState, State};
76 /// # let state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
77 /// # let param_old = vec![1.0f64, 2.0f64];
78 /// # let state = state.param(param_old);
79 /// # assert!(state.prev_param.is_none());
80 /// # assert_eq!(state.param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
81 /// # assert_eq!(state.param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
82 /// # let param = vec![0.0f64, 3.0f64];
83 /// let state = state.param(param);
84 /// # assert_eq!(state.prev_param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
85 /// # assert_eq!(state.prev_param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
86 /// # assert_eq!(state.param.as_ref().unwrap()[0].to_ne_bytes(), 0.0f64.to_ne_bytes());
87 /// # assert_eq!(state.param.as_ref().unwrap()[1].to_ne_bytes(), 3.0f64.to_ne_bytes());
88 /// ```
89 #[must_use]
90 pub fn param(mut self, param: P) -> Self {
91 std::mem::swap(&mut self.prev_param, &mut self.param);
92 self.param = Some(param);
93 self
94 }
95
96 /// Set target cost.
97 ///
98 /// When this cost is reached, the algorithm will stop. The default is
99 /// `Self::Float::NEG_INFINITY`.
100 ///
101 /// # Example
102 ///
103 /// ```
104 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
105 /// # let state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
106 /// # assert_eq!(state.target_cost.to_ne_bytes(), f64::NEG_INFINITY.to_ne_bytes());
107 /// let state = state.target_cost(0.0);
108 /// # assert_eq!(state.target_cost.to_ne_bytes(), 0.0f64.to_ne_bytes());
109 /// ```
110 #[must_use]
111 pub fn target_cost(mut self, target_cost: F) -> Self {
112 self.target_cost = target_cost;
113 self
114 }
115
116 /// Set maximum number of iterations
117 ///
118 /// # Example
119 ///
120 /// ```
121 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
122 /// # let state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
123 /// # assert_eq!(state.max_iters, u64::MAX);
124 /// let state = state.max_iters(1000);
125 /// # assert_eq!(state.max_iters, 1000);
126 /// ```
127 #[must_use]
128 pub fn max_iters(mut self, iters: u64) -> Self {
129 self.max_iters = iters;
130 self
131 }
132
133 /// Set the current cost function value. This shifts the stored cost function value to the
134 /// previous cost function value.
135 ///
136 /// # Example
137 ///
138 /// ```
139 /// # use argmin::core::{LinearProgramState, State};
140 /// # let state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
141 /// # let cost_old = 1.0f64;
142 /// # let state = state.cost(cost_old);
143 /// # assert_eq!(state.prev_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
144 /// # assert_eq!(state.cost.to_ne_bytes(), 1.0f64.to_ne_bytes());
145 /// # let cost = 0.0f64;
146 /// let state = state.cost(cost);
147 /// # assert_eq!(state.prev_cost.to_ne_bytes(), 1.0f64.to_ne_bytes());
148 /// # assert_eq!(state.cost.to_ne_bytes(), 0.0f64.to_ne_bytes());
149 /// ```
150 #[must_use]
151 pub fn cost(mut self, cost: F) -> Self {
152 std::mem::swap(&mut self.prev_cost, &mut self.cost);
153 self.cost = cost;
154 self
155 }
156
157 /// Overrides state of counting function executions (default: false)
158 /// ```
159 /// # use argmin::core::{State, LinearProgramState};
160 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
161 /// # assert!(!state.counting_enabled);
162 /// let state = state.counting(true);
163 /// # assert!(state.counting_enabled);
164 /// ```
165 #[must_use]
166 pub fn counting(mut self, mode: bool) -> Self {
167 self.counting_enabled = mode;
168 self
169 }
170}
171
172impl<P, F> State for LinearProgramState<P, F>
173where
174 P: Clone,
175 F: ArgminFloat,
176{
177 /// Type of parameter vector
178 type Param = P;
179 /// Floating point precision
180 type Float = F;
181
182 /// Create new `LinearProgramState` instance
183 ///
184 /// # Example
185 ///
186 /// ```
187 /// # extern crate web_time;
188 /// # use web_time::Duration;
189 /// # use std::collections::HashMap;
190 /// # use argmin::core::TerminationStatus;
191 /// use argmin::core::{LinearProgramState, State};
192 /// let state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
193 ///
194 /// # assert!(state.param.is_none());
195 /// # assert!(state.prev_param.is_none());
196 /// # assert!(state.best_param.is_none());
197 /// # assert!(state.prev_best_param.is_none());
198 /// # assert_eq!(state.cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
199 /// # assert_eq!(state.prev_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
200 /// # assert_eq!(state.best_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
201 /// # assert_eq!(state.prev_best_cost.to_ne_bytes(), f64::INFINITY.to_ne_bytes());
202 /// # assert_eq!(state.target_cost.to_ne_bytes(), f64::NEG_INFINITY.to_ne_bytes());
203 /// # assert_eq!(state.iter, 0);
204 /// # assert_eq!(state.last_best_iter, 0);
205 /// # assert_eq!(state.max_iters, u64::MAX);
206 /// # assert_eq!(state.counts, HashMap::new());
207 /// # assert_eq!(state.time.unwrap(), Duration::ZERO);
208 /// # assert_eq!(state.termination_status, TerminationStatus::NotTerminated);
209 /// ```
210 fn new() -> Self {
211 LinearProgramState {
212 param: None,
213 prev_param: None,
214 best_param: None,
215 prev_best_param: None,
216 cost: Self::Float::infinity(),
217 prev_cost: Self::Float::infinity(),
218 best_cost: Self::Float::infinity(),
219 prev_best_cost: Self::Float::infinity(),
220 target_cost: Self::Float::neg_infinity(),
221 iter: 0,
222 last_best_iter: 0,
223 max_iters: u64::MAX,
224 counts: HashMap::new(),
225 counting_enabled: false,
226 time: Some(Duration::ZERO),
227 termination_status: TerminationStatus::NotTerminated,
228 }
229 }
230
231 /// Checks if the current parameter vector is better than the previous best parameter value. If
232 /// a new best parameter vector was found, the state is updated accordingly.
233 ///
234 /// # Example
235 ///
236 /// ```
237 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
238 /// let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
239 ///
240 /// // Simulating a new, better parameter vector
241 /// state.best_param = Some(vec![1.0f64]);
242 /// state.best_cost = 10.0;
243 /// state.param = Some(vec![2.0f64]);
244 /// state.cost = 5.0;
245 ///
246 /// // Calling update
247 /// state.update();
248 ///
249 /// // Check if update was successful
250 /// assert_eq!(state.best_param.as_ref().unwrap()[0], 2.0f64);
251 /// assert_eq!(state.best_cost.to_ne_bytes(), state.best_cost.to_ne_bytes());
252 /// assert!(state.is_best());
253 /// ```
254 ///
255 /// For algorithms which do not compute the cost function, every new parameter vector will be
256 /// the new best:
257 ///
258 /// ```
259 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
260 /// let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
261 ///
262 /// // Simulating a new, better parameter vector
263 /// state.best_param = Some(vec![1.0f64]);
264 /// state.param = Some(vec![2.0f64]);
265 ///
266 /// // Calling update
267 /// state.update();
268 ///
269 /// // Check if update was successful
270 /// assert_eq!(state.best_param.as_ref().unwrap()[0], 2.0f64);
271 /// assert_eq!(state.best_cost.to_ne_bytes(), state.best_cost.to_ne_bytes());
272 /// assert!(state.is_best());
273 /// ```
274 fn update(&mut self) {
275 // check if parameters are the best so far
276 // Comparison is done using `<` to avoid new solutions with the same cost function value as
277 // the current best to be accepted. However, some solvers to not compute the cost function
278 // value (such as the Newton method). Those will always have `Inf` cost. Therefore if both
279 // the new value and the previous best value are `Inf`, the solution is also accepted. Care
280 // is taken that both `Inf` also have the same sign.
281 if self.cost < self.best_cost
282 || (self.cost.is_infinite()
283 && self.best_cost.is_infinite()
284 && self.cost.is_sign_positive() == self.best_cost.is_sign_positive())
285 {
286 let param = (*self.param.as_ref().unwrap()).clone();
287 let cost = self.cost;
288 std::mem::swap(&mut self.prev_best_param, &mut self.best_param);
289 self.best_param = Some(param);
290 std::mem::swap(&mut self.prev_best_cost, &mut self.best_cost);
291 self.best_cost = cost;
292 self.last_best_iter = self.iter;
293 }
294 }
295
296 /// Returns a reference to the current parameter vector
297 ///
298 /// # Example
299 ///
300 /// ```
301 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
302 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
303 /// # assert!(state.param.is_none());
304 /// # state.param = Some(vec![1.0, 2.0]);
305 /// # assert_eq!(state.param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
306 /// # assert_eq!(state.param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
307 /// let param = state.get_param(); // Option<&P>
308 /// # assert_eq!(param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
309 /// # assert_eq!(param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
310 /// ```
311 fn get_param(&self) -> Option<&P> {
312 self.param.as_ref()
313 }
314
315 /// Returns a reference to the current best parameter vector
316 ///
317 /// # Example
318 ///
319 /// ```
320 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
321 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
322 /// # assert!(state.best_param.is_none());
323 /// # state.best_param = Some(vec![1.0, 2.0]);
324 /// # assert_eq!(state.best_param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
325 /// # assert_eq!(state.best_param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
326 /// let best_param = state.get_best_param(); // Option<&P>
327 /// # assert_eq!(best_param.as_ref().unwrap()[0].to_ne_bytes(), 1.0f64.to_ne_bytes());
328 /// # assert_eq!(best_param.as_ref().unwrap()[1].to_ne_bytes(), 2.0f64.to_ne_bytes());
329 /// ```
330 fn get_best_param(&self) -> Option<&P> {
331 self.best_param.as_ref()
332 }
333
334 /// Sets the termination status to [`Terminated`](`TerminationStatus::Terminated`) with the given reason
335 ///
336 /// # Example
337 ///
338 /// ```
339 /// # use argmin::core::{LinearProgramState, State, ArgminFloat, TerminationReason, TerminationStatus};
340 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
341 /// # assert_eq!(state.termination_status, TerminationStatus::NotTerminated);
342 /// let state = state.terminate_with(TerminationReason::MaxItersReached);
343 /// # assert_eq!(state.termination_status, TerminationStatus::Terminated(TerminationReason::MaxItersReached));
344 /// ```
345 fn terminate_with(mut self, reason: TerminationReason) -> Self {
346 self.termination_status = TerminationStatus::Terminated(reason);
347 self
348 }
349
350 /// Sets the time required so far.
351 ///
352 /// # Example
353 ///
354 /// ```
355 /// # extern crate web_time;
356 /// # use web_time::Duration;
357 /// # use argmin::core::{LinearProgramState, State, ArgminFloat, TerminationReason};
358 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
359 /// let state = state.time(Some(Duration::from_nanos(12)));
360 /// # assert_eq!(state.time.unwrap(), Duration::from_nanos(12));
361 /// ```
362 fn time(&mut self, time: Option<Duration>) -> &mut Self {
363 self.time = time;
364 self
365 }
366
367 /// Returns current cost function value.
368 ///
369 /// # Example
370 ///
371 /// ```
372 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
373 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
374 /// # state.cost = 12.0;
375 /// let cost = state.get_cost();
376 /// # assert_eq!(cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
377 /// ```
378 fn get_cost(&self) -> Self::Float {
379 self.cost
380 }
381
382 /// Returns current best cost function value.
383 ///
384 /// # Example
385 ///
386 /// ```
387 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
388 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
389 /// # state.best_cost = 12.0;
390 /// let best_cost = state.get_best_cost();
391 /// # assert_eq!(best_cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
392 /// ```
393 fn get_best_cost(&self) -> Self::Float {
394 self.best_cost
395 }
396
397 /// Returns target cost function value.
398 ///
399 /// # Example
400 ///
401 /// ```
402 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
403 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
404 /// # state.target_cost = 12.0;
405 /// let target_cost = state.get_target_cost();
406 /// # assert_eq!(target_cost.to_ne_bytes(), 12.0f64.to_ne_bytes());
407 /// ```
408 fn get_target_cost(&self) -> Self::Float {
409 self.target_cost
410 }
411
412 /// Returns current number of iterations.
413 ///
414 /// # Example
415 ///
416 /// ```
417 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
418 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
419 /// # state.iter = 12;
420 /// let iter = state.get_iter();
421 /// # assert_eq!(iter, 12);
422 /// ```
423 fn get_iter(&self) -> u64 {
424 self.iter
425 }
426
427 /// Returns iteration number of last best parameter vector.
428 ///
429 /// # Example
430 ///
431 /// ```
432 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
433 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
434 /// # state.last_best_iter = 12;
435 /// let last_best_iter = state.get_last_best_iter();
436 /// # assert_eq!(last_best_iter, 12);
437 /// ```
438 fn get_last_best_iter(&self) -> u64 {
439 self.last_best_iter
440 }
441
442 /// Returns the maximum number of iterations.
443 ///
444 /// # Example
445 ///
446 /// ```
447 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
448 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
449 /// # state.max_iters = 12;
450 /// let max_iters = state.get_max_iters();
451 /// # assert_eq!(max_iters, 12);
452 /// ```
453 fn get_max_iters(&self) -> u64 {
454 self.max_iters
455 }
456
457 /// Returns the termination status.
458 ///
459 /// # Example
460 ///
461 /// ```
462 /// # use argmin::core::{LinearProgramState, State, ArgminFloat, TerminationStatus};
463 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
464 /// let termination_status = state.get_termination_status();
465 /// # assert_eq!(*termination_status, TerminationStatus::NotTerminated);
466 /// ```
467 fn get_termination_status(&self) -> &TerminationStatus {
468 &self.termination_status
469 }
470
471 /// Returns the termination reason if terminated, otherwise None.
472 ///
473 /// # Example
474 ///
475 /// ```
476 /// # use argmin::core::{LinearProgramState, State, ArgminFloat, TerminationReason};
477 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
478 /// let termination_reason = state.get_termination_reason();
479 /// # assert_eq!(termination_reason, None);
480 /// ```
481 fn get_termination_reason(&self) -> Option<&TerminationReason> {
482 match &self.termination_status {
483 TerminationStatus::Terminated(reason) => Some(reason),
484 TerminationStatus::NotTerminated => None,
485 }
486 }
487
488 /// Returns the time elapsed since the start of the optimization.
489 ///
490 /// # Example
491 ///
492 /// ```
493 /// # extern crate web_time;
494 /// # use web_time::Duration;
495 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
496 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
497 /// let time = state.get_time();
498 /// # assert_eq!(time.unwrap(), Duration::ZERO);
499 /// ```
500 fn get_time(&self) -> Option<Duration> {
501 self.time
502 }
503
504 /// Increments the number of iterations by one
505 ///
506 /// # Example
507 ///
508 /// ```
509 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
510 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
511 /// # assert_eq!(state.iter, 0);
512 /// state.increment_iter();
513 /// # assert_eq!(state.iter, 1);
514 /// ```
515 fn increment_iter(&mut self) {
516 self.iter += 1;
517 }
518
519 /// Set all function evaluation counts to the evaluation counts of another `Problem`.
520 ///
521 /// ```
522 /// # use std::collections::HashMap;
523 /// # use argmin::core::{Problem, LinearProgramState, State, ArgminFloat};
524 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new().counting(true);
525 /// # assert_eq!(state.counts, HashMap::new());
526 /// # state.counts.insert("test2".to_string(), 10u64);
527 /// #
528 /// # #[derive(Eq, PartialEq, Debug)]
529 /// # struct UserDefinedProblem {};
530 /// #
531 /// # let mut problem = Problem::new(UserDefinedProblem {});
532 /// # problem.counts.insert("test1", 10u64);
533 /// # problem.counts.insert("test2", 2);
534 /// state.func_counts(&problem);
535 /// # let mut hm = HashMap::new();
536 /// # hm.insert("test1".to_string(), 10u64);
537 /// # hm.insert("test2".to_string(), 2u64);
538 /// # assert_eq!(state.counts, hm);
539 /// ```
540 fn func_counts<O>(&mut self, problem: &Problem<O>) {
541 if self.counting_enabled {
542 for (k, &v) in problem.counts.iter() {
543 let count = self.counts.entry(k.to_string()).or_insert(0);
544 *count = v
545 }
546 }
547 }
548
549 /// Returns function evaluation counts
550 ///
551 /// # Example
552 ///
553 /// ```
554 /// # use std::collections::HashMap;
555 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
556 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
557 /// # assert_eq!(state.counts, HashMap::new());
558 /// # state.counts.insert("test2".to_string(), 10u64);
559 /// let counts = state.get_func_counts();
560 /// # let mut hm = HashMap::new();
561 /// # hm.insert("test2".to_string(), 10u64);
562 /// # assert_eq!(*counts, hm);
563 /// ```
564 fn get_func_counts(&self) -> &HashMap<String, u64> {
565 &self.counts
566 }
567
568 /// Returns whether the current parameter vector is also the best parameter vector found so
569 /// far.
570 ///
571 /// # Example
572 ///
573 /// ```
574 /// # use argmin::core::{LinearProgramState, State, ArgminFloat};
575 /// # let mut state: LinearProgramState<Vec<f64>, f64> = LinearProgramState::new();
576 /// # state.last_best_iter = 12;
577 /// # state.iter = 12;
578 /// let is_best = state.is_best();
579 /// # assert!(is_best);
580 /// # state.last_best_iter = 12;
581 /// # state.iter = 21;
582 /// # let is_best = state.is_best();
583 /// # assert!(!is_best);
584 /// ```
585 fn is_best(&self) -> bool {
586 self.last_best_iter == self.iter
587 }
588}