1use crate::core::FixedPointProblem;
2use instant;
3use num::traits::float::Float;
4use paste::item;
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct State<O: FixedPointProblem> {
10 pub param: O::Param,
12 pub prev_param: O::Param,
14 pub best_param: O::Param,
16 pub prev_best_param: O::Param,
18 pub cost: O::Float,
20 pub prev_cost: O::Float,
22 pub best_cost: O::Float,
24 pub prev_best_cost: O::Float,
26 pub iter: u64,
28 pub last_best_iter: u64,
30 pub max_iters: u64,
32 pub time: Option<instant::Duration>,
34 pub termination_reason: TerminationReason,
36}
37
38macro_rules! getter {
49 ($name:ident, $type:ty, $doc:tt) => {
50 item! {
51 #[doc=$doc]
52 pub fn [<get_ $name>](&self) -> $type {
53 self.$name.clone()
54 }
55 }
56 };
57}
58
59macro_rules! ogetter {
60 ($name:ident, $type:ty, $doc:tt) => {
61 item! {
62 #[doc=$doc]
63 pub fn [<get_ $name>](&self) -> Option<$type> {
64 self.$name.clone()
65 }
66 }
67 };
68}
69
70impl<O: FixedPointProblem> State<O> {
71 pub fn new(param: O::Param) -> Self {
73 State {
74 param: param.clone(),
75 prev_param: param.clone(),
76 best_param: param.clone(),
77 prev_best_param: param,
78 cost: O::Float::infinity(),
79 prev_cost: O::Float::infinity(),
80 best_cost: O::Float::infinity(),
81 prev_best_cost: O::Float::infinity(),
82 iter: 0,
83 last_best_iter: 0,
84 max_iters: std::u64::MAX,
85 time: Some(instant::Duration::new(0, 0)),
86 termination_reason: TerminationReason::NotTerminated,
87 }
88 }
89
90 pub fn terminated(&self) -> bool {
92 match self.termination_reason {
93 TerminationReason::NotTerminated => false,
94 TerminationReason::ToleranceBeaten => true,
95 TerminationReason::HitMaxIterations => true,
96 }
97 }
98
99 pub fn termination_reason(&mut self, reason: TerminationReason) {
101 self.termination_reason = reason;
102 }
103
104 getter!(param, O::Param, "Returns current parameter vector");
105}
106
107#[derive(Clone, Debug, Serialize, Deserialize)]
108pub enum TerminationReason {
110 NotTerminated,
112 ToleranceBeaten,
114 HitMaxIterations,
116}
117
118#[derive(Clone, Debug, Default)]
119pub struct IterData<P: FixedPointProblem> {
121 param: Option<P::Param>,
123 cost: Option<P::Float>,
125}
126
127impl<P: FixedPointProblem> IterData<P> {
128 pub fn new() -> Self {
130 IterData {
131 param: None,
132 cost: None,
133 }
134 }
135
136 pub fn param(mut self, param: P::Param) -> Self {
138 self.param = Some(param);
139 self
140 }
141
142 pub fn cost(mut self, cost: P::Float) -> Self {
144 self.cost = Some(cost);
145 self
146 }
147
148 ogetter!(param, P::Param, "Returns current parameter vector");
149 ogetter!(cost, P::Float, "Returns current cost");
150}