Wed, 04 Oct 2023 08:59:29 -0500
Add Mapping codomain slicing and RealVectorField
0 | 1 | /*! |
5 | 2 | Tools for separating the computational steps of an iterative algorithm from stopping rules |
3 | and reporting. | |
0 | 4 | |
5 | 5 | The computational step is to be implemented as a closure. That closure gets passed a `state` |
6 | parameter that implements an [`if_verbose`][AlgIteratorState::if_verbose] method that is to | |
7 | be called to determine whether function values or other potentially costly things need to be | |
8 | calculated on that iteration. The parameter of [`if_verbose`][AlgIteratorState::if_verbose] is | |
9 | another closure that does the necessary computation. | |
0 | 10 | |
11 | ## Simple example | |
12 | ||
13 | ```rust | |
5 | 14 | # use alg_tools::types::*; |
15 | # use alg_tools::iterate::*; | |
16 | let mut iter = AlgIteratorOptions{ | |
17 | max_iter : 100, | |
18 | verbose_iter : Verbose::Every(10), | |
19 | .. Default::default() | |
20 | }; | |
0 | 21 | let mut x = 1 as float; |
22 | iter.iterate(|state|{ | |
23 | // This is our computational step | |
24 | x = x + x.sqrt(); | |
25 | state.if_verbose(||{ | |
26 | // return current value when requested | |
27 | return x | |
28 | }) | |
29 | }) | |
30 | ``` | |
31 | There is no colon after `state.if_verbose`, because we need to return its value. If you do something after the step, you need to store the result in a variable and return it from the main computational step afterwards. | |
32 | ||
33 | This will print out | |
34 | ```output | |
35 | 10/100 J=31.051164 | |
36 | 20/100 J=108.493699 | |
37 | 30/100 J=234.690039 | |
38 | 40/100 J=410.056327 | |
39 | 50/100 J=634.799262 | |
40 | 60/100 J=909.042928 | |
41 | 70/100 J=1232.870172 | |
42 | 80/100 J=1606.340254 | |
43 | 90/100 J=2029.497673 | |
44 | 100/100 J=2502.377071 | |
45 | ``` | |
46 | */ | |
47 | ||
5 | 48 | use colored::{Colorize, ColoredString}; |
0 | 49 | use core::fmt::Debug; |
50 | use serde::{Serialize, Deserialize}; | |
51 | use cpu_time::ProcessTime; | |
52 | use std::marker::PhantomData; | |
53 | use std::time::Duration; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
54 | use std::error::Error; |
0 | 55 | use crate::types::*; |
56 | use crate::logger::*; | |
57 | ||
5 | 58 | /// Create the displayed presentation for log items. |
0 | 59 | pub trait LogRepr : Debug { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
60 | fn logrepr(&self) -> ColoredString { format!("« {self:?} »").as_str().into() } |
0 | 61 | } |
62 | ||
63 | impl LogRepr for str { | |
64 | fn logrepr(&self) -> ColoredString { self.into() } | |
65 | } | |
66 | ||
67 | impl LogRepr for String { | |
68 | fn logrepr(&self) -> ColoredString { self.as_str().into() } | |
69 | } | |
70 | ||
71 | impl<T> LogRepr for T where T : Num { | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
72 | fn logrepr(&self) -> ColoredString { format!("J={self}").as_str().into() } |
0 | 73 | } |
74 | ||
75 | impl<V> LogRepr for Option<V> where V : LogRepr { | |
76 | fn logrepr(&self) -> ColoredString { | |
77 | match self { | |
78 | None => { "===missing value===".red() } | |
79 | Some(v) => { v.logrepr() } | |
80 | } | |
81 | } | |
82 | } | |
83 | ||
5 | 84 | /// Helper struct for returning results annotated with an additional string to |
85 | /// [`if_verbose`][AlgIteratorState::if_verbose]. The [`LogRepr`] implementation will | |
86 | /// display that string when so decided by the specific [`AlgIterator`] in use. | |
0 | 87 | #[derive(Debug,Clone)] |
88 | pub struct Annotated<F>(pub F, pub String); | |
89 | ||
90 | impl<V> LogRepr for Annotated<V> where V : LogRepr { | |
91 | fn logrepr(&self) -> ColoredString { | |
92 | format!("{}\t| {}", self.0.logrepr(), self.1).as_str().into() | |
93 | } | |
94 | } | |
95 | ||
96 | ||
97 | /// Basic log item. | |
98 | #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] | |
99 | pub struct LogItem<V> { | |
100 | pub iter : usize, | |
101 | // This causes [`csv`] to crash. | |
102 | //#[serde(flatten)] | |
103 | pub data : V | |
104 | } | |
105 | ||
5 | 106 | impl<V> LogItem<V> { |
107 | /// Creates a new log item | |
108 | fn new(iter : usize, data : V) -> Self { | |
109 | LogItem{ iter, data } | |
110 | } | |
0 | 111 | } |
112 | ||
5 | 113 | /// State of an [`AlgIterator`]. |
114 | /// | |
115 | /// This is the parameter obtained by the closure passed to [`AlgIterator::iterate`] or | |
116 | /// [`AlgIteratorFactory::iterate`]. | |
0 | 117 | pub trait AlgIteratorState { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
118 | /// Call `call_objective` if this is a verbose iteration. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
119 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
120 | /// Verbosity depends on the [`AlgIterator`] that produced this state. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
121 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
122 | /// The closure `calc_objective` should return an arbitrary value of type `V`, to be inserted |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
123 | /// into the log, or whatever is deemed by the [`AlgIterator`]. For usage instructions see the |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
124 | /// [module documentation][self]. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
125 | fn if_verbose<V, E : Error>(&self, calc_objective : impl FnMut() -> V) -> Step<V, E>; |
0 | 126 | |
5 | 127 | /// Returns the current iteration count. |
0 | 128 | fn iteration(&self) -> usize; |
31
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
129 | |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
130 | /// Indicates whether the iterator is quiet |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
131 | fn is_quiet(&self) -> bool; |
0 | 132 | } |
133 | ||
134 | /// Result of a step of an [`AlgIterator`] | |
135 | #[derive(Debug, Serialize)] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
136 | pub enum Step<V, Fail : Error = std::convert::Infallible> { |
0 | 137 | /// Iteration should be terminated |
138 | Terminated, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
139 | /// Iteration should be terminated due to failure |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
140 | Failure(Fail), |
0 | 141 | /// No result this iteration (due to verbosity settings) |
142 | Quiet, | |
143 | /// Result of this iteration (due to verbosity settings) | |
144 | Result(V), | |
145 | } | |
146 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
147 | impl<V, E : Error> Step<V, E> { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
148 | /// Maps the value contained within the `Step`, if any, by the closure `f`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
149 | pub fn map<U>(self, mut f : impl FnMut(V) -> U) -> Step<U, E> { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
150 | match self { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
151 | Step::Result(v) => Step::Result(f(v)), |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
152 | Step::Failure(e) => Step::Failure(e), |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
153 | Step::Quiet => Step::Quiet, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
154 | Step::Terminated => Step::Terminated, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
155 | } |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
156 | } |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
157 | } |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
158 | |
5 | 159 | /// An iterator for algorithms, produced by [`AlgIteratorFactory::prepare`]. |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
160 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
161 | /// Typically not accessed directly, but transparently produced by an [`AlgIteratorFactory`]. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
162 | /// Every [`AlgIteratorFactory`] has to implement a corresponding `AlgIterator`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
163 | pub trait AlgIterator : Sized { |
5 | 164 | /// The state type |
0 | 165 | type State : AlgIteratorState; |
5 | 166 | /// The output type for [`Self::step`]. |
0 | 167 | type Output; |
5 | 168 | /// The error type for [`Self::step`] and [`Self::iterate`]. |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
169 | type Err : Error; |
0 | 170 | |
171 | /// Advance the iterator. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
172 | fn step(&mut self) -> Step<Self::Output, Self::Err>; |
0 | 173 | |
174 | /// Return current iteration count. | |
175 | fn iteration(&self) -> usize { | |
176 | self.state().iteration() | |
177 | } | |
178 | ||
5 | 179 | /// Return current state. |
0 | 180 | fn state(&self) -> Self::State; |
181 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
182 | /// Iterate the `AlgIterator` until termination. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
183 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
184 | /// Returns either `()` or an error if the step closure terminated in [`Step::Failure´]. |
0 | 185 | #[inline] |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
186 | fn iterate(&mut self) -> Result<(), Self::Err> { |
0 | 187 | loop { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
188 | match self.step() { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
189 | Step::Terminated => return Ok(()), |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
190 | Step::Failure(e) => return Err(e), |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
191 | _ => {}, |
0 | 192 | } |
193 | } | |
194 | } | |
195 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
196 | /// Converts the `AlgIterator` into a plain [`Iterator`]. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
197 | /// |
5 | 198 | /// [`Step::Quiet`] results are discarded, and [`Step::Failure`] results **panic**. |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
199 | fn downcast(self) -> AlgIteratorI<Self> { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
200 | AlgIteratorI(self) |
0 | 201 | } |
202 | } | |
203 | ||
204 | /// Conversion of an `AlgIterator` into a plain [`Iterator`]. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
205 | /// |
5 | 206 | /// The conversion discards [`Step::Quiet`] and **panics** on [`Step::Failure`]. |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
207 | pub struct AlgIteratorI<A>(A); |
0 | 208 | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
209 | impl<A> Iterator for AlgIteratorI<A> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
210 | where A : AlgIterator { |
0 | 211 | type Item = A::Output; |
212 | ||
213 | fn next(&mut self) -> Option<A::Output> { | |
214 | loop { | |
215 | match self.0.step() { | |
216 | Step::Result(v) => return Some(v), | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
217 | Step::Failure(e) => panic!("{e:?}"), |
0 | 218 | Step::Terminated => return None, |
219 | Step::Quiet => continue, | |
220 | } | |
221 | } | |
222 | } | |
223 | } | |
224 | ||
5 | 225 | /// A factory for producing an [`AlgIterator`]. |
0 | 226 | /// |
5 | 227 | /// For usage instructions see the [module documentation][self]. |
0 | 228 | pub trait AlgIteratorFactory<V> : Sized { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
229 | type Iter<F, E> : AlgIterator<State = Self::State, Output = Self::Output, Err = E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
230 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
231 | E : Error; |
5 | 232 | /// The state type of the corresponding [`AlgIterator`]. |
233 | /// A reference to this is passed to the closures passed to methods such as [`Self::iterate`]. | |
0 | 234 | type State : AlgIteratorState; |
5 | 235 | /// The output type of the corresponding [`AlgIterator`]. |
236 | /// This is the output of the closures passed to methods such as [`Self::iterate`] after | |
237 | /// mappings performed by each [`AlgIterator`] implementation. | |
0 | 238 | type Output; |
239 | ||
240 | /// Prepare an [`AlgIterator`], consuming the factory. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
241 | /// |
0 | 242 | /// The function `step_fn` should accept a `state` ([`AlgIteratorState`] parameter, and return |
243 | /// a [`Step`]. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
244 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
245 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
246 | E : Error; |
0 | 247 | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
248 | /// Iterate the the closure `step`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
249 | /// |
5 | 250 | /// The closure should accept a `state` parameter (satisfying the trait [`AlgIteratorState`]). |
251 | /// It should return the output of | |
252 | /// `state.`[`if_verbose`][AlgIteratorState::if_verbose], [`Step::Terminated`] to indicate | |
253 | /// completion for other reason, or [`Step::Failure`] for termination for failure. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
254 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
255 | /// This method is equivalent to [`Self::prepare`] followed by [`AlgIterator::iterate`]. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
256 | #[inline] |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
257 | fn iterate_fallible<F, E>(self, step : F) -> Result<(), E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
258 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
259 | E : Error { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
260 | self.prepare(step).iterate() |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
261 | } |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
262 | |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
263 | /// Iterate the the closure `step`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
264 | /// |
5 | 265 | /// The closure should accept a `state` parameter (satisfying the trait [`AlgIteratorState`]), |
266 | /// It should return the output of | |
267 | /// `state.`[`if_verbose`][AlgIteratorState::if_verbose]. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
268 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
269 | /// For usage instructions see the [module documentation][self]. |
0 | 270 | /// |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
271 | /// This method is equivalent to [`Self::prepare`] followed by [`AlgIterator::iterate`] |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
272 | /// with the error type `E=`[`std::convert::Infallible`]. |
0 | 273 | #[inline] |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
274 | fn iterate<F>(self, step : F) |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
275 | where F : FnMut(&Self::State) -> Step<V> { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
276 | self.iterate_fallible(step).unwrap_or_default() |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
277 | } |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
278 | |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
279 | /// Iterate the closure `step` with data produced by `datasource`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
280 | /// |
5 | 281 | /// The closure should accept a `state` parameter (satisfying the trait [`AlgIteratorState`]), |
282 | /// and a data parameter taken from `datasource`. It should return the output of | |
283 | /// `state.`[`if_verbose`][AlgIteratorState::if_verbose], [`Step::Terminated`] to indicate | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
284 | /// completion for other reason, or [`Step::Failure`] for termination for failure. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
285 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
286 | /// If the `datasource` runs out of data, the iterator is considered having terminated |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
287 | /// successsfully. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
288 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
289 | /// For usage instructions see the [module documentation][self]. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
290 | #[inline] |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
291 | fn iterate_data_fallible<F, D, I, E>(self, mut datasource : I, mut step : F) -> Result<(), E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
292 | where F : FnMut(&Self::State, D) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
293 | I : Iterator<Item = D>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
294 | E : Error { |
0 | 295 | self.prepare(move |state| { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
296 | datasource.next().map_or(Step::Terminated, |d| step(state, d)) |
0 | 297 | }).iterate() |
298 | } | |
299 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
300 | /// Iterate the closure `step` with data produced by `datasource`. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
301 | /// |
5 | 302 | /// The closure should accept a `state` parameter (satisfying the trait [`AlgIteratorState`]), |
303 | /// and a data parameter taken from `datasource`. It should return the output of | |
304 | /// `state.`[`if_verbose`][AlgIteratorState::if_verbose]. | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
305 | /// |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
306 | /// If the `datasource` runs out of data, the iterator is considered having terminated |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
307 | /// successsfully. |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
308 | /// |
0 | 309 | /// For usage instructions see the [module documentation][self]. |
310 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
311 | fn iterate_data<F, D, I>(self, datasource : I, step : F) |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
312 | where F : FnMut(&Self::State, D) -> Step<V>, |
0 | 313 | I : Iterator<Item = D> { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
314 | self.iterate_data_fallible(datasource, step).unwrap_or_default() |
0 | 315 | } |
316 | ||
317 | // fn make_iterate<'own>(self) | |
318 | // -> Box<dyn (FnMut(dyn FnMut(&Self::State) -> Option<V>) -> ()) + 'own> { | |
319 | // Box::new(move |step| self.iterate(step)) | |
320 | // } | |
321 | ||
322 | // fn make_iterate_data<'own, D, I>(self, datasource : I) | |
323 | // -> Box<dyn (FnMut(dyn FnMut(&Self::State, D) -> Option<V>) -> ()) + 'own> | |
324 | // where I : Iterator<Item = D> + 'own { | |
325 | // Box::new(move |step| self.iterate_data(step, datasource)) | |
326 | // } | |
327 | ||
328 | /// Add logging to the iterator produced by the factory. | |
5 | 329 | /// |
330 | /// Returns a new factory whose corresponding [`AlgIterator`] only inserts that data into the | |
331 | /// log without passing it onwards. | |
332 | /// | |
333 | /// Use as: | |
334 | /// ```rust | |
335 | /// # use alg_tools::iterate::*; | |
336 | /// # use alg_tools::logger::*; | |
337 | /// let iter = AlgIteratorOptions::default(); | |
338 | /// let mut log = Logger::new(); | |
339 | /// iter.into_log(&mut log).iterate(|state|{ | |
340 | /// // perform iterations | |
341 | /// state.if_verbose(||{ | |
342 | /// // calculate and return function value or other displayed data v | |
343 | /// return 0 | |
344 | /// }) | |
345 | /// }) | |
346 | /// ``` | |
0 | 347 | fn into_log<'log>(self, logger : &'log mut Logger<Self::Output>) |
348 | -> LoggingIteratorFactory<'log, Self::Output, Self> | |
349 | where Self : Sized { | |
350 | LoggingIteratorFactory { | |
351 | base_options : self, | |
352 | logger, | |
353 | } | |
354 | } | |
355 | ||
356 | /// Map the output of the iterator produced by the factory. | |
5 | 357 | /// |
358 | /// Returns a new factory. | |
0 | 359 | fn mapped<U, G>(self, map : G) |
360 | -> MappingIteratorFactory<G, Self> | |
361 | where Self : Sized, | |
362 | G : Fn(usize, Self::Output) -> U { | |
363 | MappingIteratorFactory { | |
364 | base_options : self, | |
365 | map | |
366 | } | |
367 | } | |
368 | ||
5 | 369 | /// Adds iteration number to the output. |
370 | /// | |
371 | /// Returns a new factory. | |
372 | /// Typically followed by [`Self::into_log`]. | |
0 | 373 | fn with_iteration_number(self) |
374 | -> MappingIteratorFactory<fn(usize, Self::Output) -> LogItem<Self::Output>, Self> | |
375 | where Self : Sized { | |
5 | 376 | self.mapped(LogItem::new) |
0 | 377 | } |
378 | ||
379 | /// Add timing to the iterator produced by the factory. | |
380 | fn timed(self) -> TimingIteratorFactory<Self> | |
381 | where Self : Sized { | |
382 | TimingIteratorFactory(self) | |
383 | } | |
384 | ||
385 | /// Add value stopping threshold to the iterator produce by the factory | |
386 | fn stop_target(self, target : Self::Output) -> ValueIteratorFactory<Self::Output, Self> | |
387 | where Self : Sized, | |
388 | Self::Output : Num { | |
389 | ValueIteratorFactory { base_options : self, target : target } | |
390 | } | |
391 | ||
392 | /// Add stall stopping to the iterator produce by the factory | |
393 | fn stop_stall(self, stall : Self::Output) -> StallIteratorFactory<Self::Output, Self> | |
394 | where Self : Sized, | |
395 | Self::Output : Num { | |
396 | StallIteratorFactory { base_options : self, stall : stall } | |
397 | } | |
398 | ||
399 | /// Is the iterator quiet, i.e., on-verbose? | |
400 | fn is_quiet(&self) -> bool { false } | |
401 | } | |
402 | ||
5 | 403 | /// Options for [`BasicAlgIteratorFactory`]. |
404 | /// | |
405 | /// Use as: | |
0 | 406 | /// ``` |
407 | /// # use alg_tools::iterate::*; | |
408 | /// let iter = AlgIteratorOptions{ max_iter : 10000, .. Default::default() }; | |
409 | /// ``` | |
410 | #[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] | |
411 | pub struct AlgIteratorOptions { | |
412 | /// Maximum number of iterations | |
413 | pub max_iter : usize, | |
414 | /// Number of iterations between verbose iterations that display state. | |
415 | pub verbose_iter : Verbose, | |
416 | /// Whether verbose iterations are displayed, or just passed onwards to a containing | |
417 | /// `AlgIterator`. | |
418 | pub quiet : bool, | |
419 | } | |
420 | ||
421 | #[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] | |
422 | pub enum Verbose { | |
423 | /// Be verbose every $n$ iterations. | |
424 | Every(usize), | |
425 | /// Be verbose every $n$ iterations and initial $m$ iterations. | |
426 | EveryAndInitial{ every : usize, initial : usize }, | |
427 | /// Be verbose if iteration number $n$ divides by $b^{\text{floor}(\log_b(n))}$, where | |
428 | /// $b$ is indicated logarithmic base. So, with $b=10$, | |
429 | /// * every iteration for first 10 iterations, | |
430 | /// * every 10 iterations from there on until 100 iterations, | |
431 | /// * every 100 iteartinos frmo there on until 1000 iterations, etc. | |
432 | Logarithmic(usize), | |
433 | } | |
434 | ||
435 | impl Verbose { | |
436 | /// Indicates whether given iteration number is verbose | |
437 | pub fn is_verbose(&self, iter : usize) -> bool { | |
438 | match self { | |
439 | &Verbose::Every(every) => { | |
440 | every != 0 && iter % every == 0 | |
441 | }, | |
442 | &Verbose::EveryAndInitial{ every, initial } => { | |
443 | iter <= initial || (every != 0 && iter % every == 0) | |
444 | }, | |
445 | &Verbose::Logarithmic(base) => { | |
446 | let every = 10usize.pow((iter as float).log(base as float).floor() as u32); | |
447 | iter % every == 0 | |
448 | } | |
449 | } | |
450 | } | |
451 | } | |
452 | ||
453 | impl Default for AlgIteratorOptions { | |
454 | fn default() -> AlgIteratorOptions { | |
455 | AlgIteratorOptions{ | |
456 | max_iter : 1000, | |
457 | verbose_iter : Verbose::EveryAndInitial { every : 100, initial : 10 }, | |
458 | quiet : false | |
459 | } | |
460 | } | |
461 | } | |
462 | ||
463 | /// State of a `BasicAlgIterator` | |
464 | #[derive(Clone,Copy,Debug,Serialize,Eq,PartialEq)] | |
465 | pub struct BasicState { | |
5 | 466 | /// Current iteration |
0 | 467 | iter : usize, |
5 | 468 | /// Whether the iteration is verbose, i.e., results should be displayed. |
469 | /// Requires `calc` to be `true`. | |
0 | 470 | verbose : bool, |
5 | 471 | /// Whether results should be calculated. |
0 | 472 | calc : bool, |
31
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
473 | /// Indicates whether the iteration is quiet |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
474 | quiet : bool, |
0 | 475 | } |
476 | ||
477 | /// [`AlgIteratorFactory`] for [`BasicAlgIterator`] | |
478 | #[derive(Clone,Debug)] | |
479 | pub struct BasicAlgIteratorFactory<V> { | |
480 | options : AlgIteratorOptions, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
481 | _phantoms : PhantomData<V>, |
0 | 482 | } |
483 | ||
5 | 484 | /// The simplest [`AlgIterator`], created by [`BasicAlgIteratorFactory`] |
0 | 485 | #[derive(Clone,Debug)] |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
486 | pub struct BasicAlgIterator<F, V, E : Error> { |
0 | 487 | options : AlgIteratorOptions, |
488 | iter : usize, | |
489 | step_fn : F, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
490 | _phantoms : PhantomData<(V, E)>, |
0 | 491 | } |
492 | ||
493 | impl AlgIteratorOptions { | |
494 | /// [`AlgIteratorOptions`] is directly a factory for [`BasicAlgIterator`], | |
495 | /// however, due to type inference issues, it may become convenient to instantiate | |
496 | /// it to a specific return type for the inner step function. This method does that. | |
497 | pub fn instantiate<V>(&self) -> BasicAlgIteratorFactory<V> { | |
498 | BasicAlgIteratorFactory { | |
499 | options : self.clone(), | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
500 | _phantoms : PhantomData |
0 | 501 | } |
502 | } | |
503 | } | |
504 | ||
505 | impl<V> AlgIteratorFactory<V> for AlgIteratorOptions | |
506 | where V : LogRepr { | |
507 | type State = BasicState; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
508 | type Iter<F, E> = BasicAlgIterator<F, V, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
509 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
510 | E : Error; |
0 | 511 | type Output = V; |
512 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
513 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
514 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
515 | E : Error { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
516 | BasicAlgIterator{ |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
517 | options : self, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
518 | iter : 0, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
519 | step_fn, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
520 | _phantoms : PhantomData, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
521 | } |
0 | 522 | } |
523 | ||
524 | #[inline] | |
525 | fn is_quiet(&self) -> bool { | |
526 | self.quiet | |
527 | } | |
528 | } | |
529 | ||
530 | impl<V> AlgIteratorFactory<V> for BasicAlgIteratorFactory<V> | |
531 | where V : LogRepr { | |
532 | type State = BasicState; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
533 | type Iter<F, E> = BasicAlgIterator<F, V, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
534 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
535 | E : Error; |
0 | 536 | type Output = V; |
537 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
538 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
539 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
540 | E : Error { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
541 | BasicAlgIterator { |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
542 | options : self.options, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
543 | iter : 0, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
544 | step_fn, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
545 | _phantoms : PhantomData |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
546 | } |
0 | 547 | } |
548 | ||
549 | #[inline] | |
550 | fn is_quiet(&self) -> bool { | |
551 | self.options.quiet | |
552 | } | |
553 | } | |
554 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
555 | impl<F, V, E> AlgIterator for BasicAlgIterator<F, V, E> |
0 | 556 | where V : LogRepr, |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
557 | E : Error, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
558 | F : FnMut(&BasicState) -> Step<V, E> { |
0 | 559 | type State = BasicState; |
560 | type Output = V; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
561 | type Err = E; |
0 | 562 | |
563 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
564 | fn step(&mut self) -> Step<V, E> { |
0 | 565 | if self.iter >= self.options.max_iter { |
566 | Step::Terminated | |
567 | } else { | |
568 | self.iter += 1; | |
569 | let state = self.state(); | |
570 | let res = (self.step_fn)(&state); | |
571 | if let Step::Result(ref val) = res { | |
572 | if state.verbose && !self.options.quiet { | |
573 | println!("{}{}/{} {}{}", "".dimmed(), | |
574 | state.iter, | |
575 | self.options.max_iter, | |
576 | val.logrepr(), | |
577 | "".clear()); | |
578 | } | |
579 | } | |
580 | res | |
581 | } | |
582 | } | |
583 | ||
584 | #[inline] | |
585 | fn iteration(&self) -> usize { | |
586 | self.iter | |
587 | } | |
588 | ||
589 | #[inline] | |
590 | fn state(&self) -> BasicState { | |
591 | let iter = self.iter; | |
592 | let verbose = self.options.verbose_iter.is_verbose(iter); | |
31
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
593 | BasicState { |
0 | 594 | iter : iter, |
595 | verbose : verbose, | |
596 | calc : verbose, | |
31
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
597 | quiet : self.options.quiet |
0 | 598 | } |
599 | } | |
600 | } | |
601 | ||
602 | impl AlgIteratorState for BasicState { | |
603 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
604 | fn if_verbose<V, E : Error>(&self, mut calc_objective : impl FnMut() -> V) -> Step<V, E> { |
0 | 605 | if self.calc { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
606 | Step::Result(calc_objective()) |
0 | 607 | } else { |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
608 | Step::Quiet |
0 | 609 | } |
610 | } | |
611 | ||
612 | #[inline] | |
613 | fn iteration(&self) -> usize { | |
31
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
614 | self.iter |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
615 | } |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
616 | |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
617 | #[inline] |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
618 | fn is_quiet(&self) -> bool { |
50a77e4efcbb
Add is_quiet to AlgIteratorState as well.
Tuomo Valkonen <tuomov@iki.fi>
parents:
5
diff
changeset
|
619 | self.quiet |
0 | 620 | } |
621 | } | |
622 | ||
623 | // | |
624 | // Stall detecting iteration function. | |
625 | // | |
626 | ||
5 | 627 | /// An [`AlgIteratorFactory`] for an [`AlgIterator`] that detects “stall”. |
628 | /// | |
629 | /// We define stall as $(v_{k+n}-v_k)/v_k ≤ θ$, where $n$ the distance between | |
630 | /// [`Step::Result`] iterations, and $θ$ is the provided `stall` parameter. | |
0 | 631 | #[derive(Clone,Copy,Debug,Serialize,Eq,PartialEq)] |
632 | pub struct StallIteratorFactory<U : Num, BaseFactory> { | |
5 | 633 | /// An [`AlgIteratorFactory`] on which to build on |
0 | 634 | pub base_options : BaseFactory, |
635 | /// Stalling threshold $θ$. | |
636 | pub stall : U, | |
637 | } | |
638 | ||
639 | /// Iterator produced by [`StallIteratorFactory`]. | |
640 | pub struct StallIterator<U : Num, BaseIterator> { | |
641 | base_iterator : BaseIterator, | |
642 | stall : U, | |
643 | previous_value : Option<U>, | |
644 | } | |
645 | ||
646 | impl<V, U, BaseFactory> AlgIteratorFactory<V> | |
647 | for StallIteratorFactory<U, BaseFactory> | |
648 | where BaseFactory : AlgIteratorFactory<V, Output=U>, | |
649 | U : SignedNum + PartialOrd { | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
650 | type Iter<F, E> = StallIterator<U, BaseFactory::Iter<F, E>> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
651 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
652 | E : Error; |
0 | 653 | type State = BaseFactory::State; |
654 | type Output = BaseFactory::Output; | |
655 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
656 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
657 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
658 | E : Error { |
0 | 659 | StallIterator { |
660 | base_iterator : self.base_options.prepare(step_fn), | |
661 | stall : self.stall, | |
662 | previous_value : None, | |
663 | } | |
664 | } | |
665 | ||
666 | fn is_quiet(&self) -> bool { | |
667 | self.base_options.is_quiet() | |
668 | } | |
669 | } | |
670 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
671 | impl<U, BaseIterator> AlgIterator |
0 | 672 | for StallIterator<U, BaseIterator> |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
673 | where BaseIterator : AlgIterator<Output=U>, |
0 | 674 | U : SignedNum + PartialOrd { |
675 | type State = BaseIterator::State; | |
676 | type Output = BaseIterator::Output; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
677 | type Err = BaseIterator::Err; |
0 | 678 | |
679 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
680 | fn step(&mut self) -> Step<U, Self::Err> { |
0 | 681 | match self.base_iterator.step() { |
682 | Step::Result(nv) => { | |
683 | let previous_v = self.previous_value; | |
684 | self.previous_value = Some(nv); | |
685 | match previous_v { | |
686 | Some(pv) if (nv - pv).abs() <= self.stall * pv.abs() => Step::Terminated, | |
687 | _ => Step::Result(nv), | |
688 | } | |
689 | }, | |
690 | val => val, | |
691 | } | |
692 | } | |
693 | ||
694 | #[inline] | |
695 | fn iteration(&self) -> usize { | |
696 | self.base_iterator.iteration() | |
697 | } | |
698 | ||
699 | #[inline] | |
700 | fn state(&self) -> Self::State { | |
701 | self.base_iterator.state() | |
702 | } | |
703 | } | |
704 | ||
705 | /// An [`AlgIteratorFactory`] for an [`AlgIterator`] that detect whether step function | |
706 | /// return value is less than `target`, and terminates if it is. | |
707 | #[derive(Clone,Copy,Debug,Serialize,Eq,PartialEq)] | |
708 | pub struct ValueIteratorFactory<U : Num, BaseFactory> { | |
5 | 709 | /// An [`AlgIteratorFactory`] on which to build on |
0 | 710 | pub base_options : BaseFactory, |
5 | 711 | /// Target value |
0 | 712 | pub target : U, |
713 | } | |
714 | ||
715 | /// Iterator produced by [`ValueIteratorFactory`]. | |
716 | pub struct ValueIterator<U : Num, BaseIterator> { | |
717 | base_iterator : BaseIterator, | |
718 | target : U, | |
719 | } | |
720 | ||
721 | impl<V, U, BaseFactory> AlgIteratorFactory<V> | |
722 | for ValueIteratorFactory<U, BaseFactory> | |
723 | where BaseFactory : AlgIteratorFactory<V, Output=U>, | |
724 | U : SignedNum + PartialOrd { | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
725 | type Iter<F, E> = ValueIterator<U, BaseFactory::Iter<F, E>> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
726 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
727 | E : Error; |
0 | 728 | type State = BaseFactory::State; |
729 | type Output = BaseFactory::Output; | |
730 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
731 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
732 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
733 | E : Error { |
0 | 734 | ValueIterator { |
735 | base_iterator : self.base_options.prepare(step_fn), | |
736 | target : self.target | |
737 | } | |
738 | } | |
739 | ||
740 | fn is_quiet(&self) -> bool { | |
741 | self.base_options.is_quiet() | |
742 | } | |
743 | } | |
744 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
745 | impl<U, BaseIterator> AlgIterator |
0 | 746 | for ValueIterator<U, BaseIterator> |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
747 | where BaseIterator : AlgIterator<Output=U>, |
0 | 748 | U : SignedNum + PartialOrd { |
749 | type State = BaseIterator::State; | |
750 | type Output = BaseIterator::Output; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
751 | type Err = BaseIterator::Err; |
0 | 752 | |
753 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
754 | fn step(&mut self) -> Step<U, Self::Err> { |
0 | 755 | match self.base_iterator.step() { |
756 | Step::Result(v) => { | |
757 | if v <= self.target { | |
758 | Step::Terminated | |
759 | } else { | |
760 | Step::Result(v) | |
761 | } | |
762 | }, | |
763 | val => val, | |
764 | } | |
765 | } | |
766 | ||
767 | #[inline] | |
768 | fn iteration(&self) -> usize { | |
769 | self.base_iterator.iteration() | |
770 | } | |
771 | ||
772 | #[inline] | |
773 | fn state(&self) -> Self::State { | |
774 | self.base_iterator.state() | |
775 | } | |
776 | } | |
777 | ||
778 | // | |
779 | // Logging iterator | |
780 | // | |
781 | ||
782 | /// [`AlgIteratorFactory`] for a logging [`AlgIterator`]. | |
5 | 783 | /// |
784 | /// Typically produced with [`AlgIteratorFactory::into_log`]. | |
0 | 785 | /// The `Output` of the corresponding [`LoggingIterator`] is `()`: |
786 | #[derive(Debug)] | |
787 | pub struct LoggingIteratorFactory<'log, U, BaseFactory> { | |
5 | 788 | /// Base [`AlgIteratorFactory`] on which to build |
789 | base_options : BaseFactory, | |
790 | /// The `Logger` to use. | |
791 | logger : &'log mut Logger<U>, | |
0 | 792 | } |
793 | ||
794 | /// Iterator produced by `LoggingIteratorFactory`. | |
795 | pub struct LoggingIterator<'log, U, BaseIterator> { | |
796 | base_iterator : BaseIterator, | |
797 | logger : &'log mut Logger<U>, | |
798 | } | |
799 | ||
800 | ||
801 | impl<'log, V, BaseFactory> AlgIteratorFactory<V> | |
802 | for LoggingIteratorFactory<'log, BaseFactory::Output, BaseFactory> | |
803 | where BaseFactory : AlgIteratorFactory<V>, | |
804 | BaseFactory::Output : 'log { | |
805 | type State = BaseFactory::State; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
806 | type Iter<F, E> = LoggingIterator<'log, BaseFactory::Output, BaseFactory::Iter<F, E>> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
807 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
808 | E : Error; |
0 | 809 | type Output = (); |
810 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
811 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
812 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
813 | E : Error { |
0 | 814 | LoggingIterator { |
815 | base_iterator : self.base_options.prepare(step_fn), | |
816 | logger : self.logger, | |
817 | } | |
818 | } | |
819 | ||
820 | #[inline] | |
821 | fn is_quiet(&self) -> bool { | |
822 | self.base_options.is_quiet() | |
823 | } | |
824 | } | |
825 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
826 | impl<'log, BaseIterator> AlgIterator |
0 | 827 | for LoggingIterator<'log, BaseIterator::Output, BaseIterator> |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
828 | where BaseIterator : AlgIterator, |
0 | 829 | BaseIterator::Output : 'log { |
830 | type State = BaseIterator::State; | |
831 | type Output = (); | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
832 | type Err = BaseIterator::Err; |
0 | 833 | |
834 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
835 | fn step(&mut self) -> Step<Self::Output, Self::Err> { |
0 | 836 | match self.base_iterator.step() { |
837 | Step::Result(v) => { | |
838 | self.logger.log(v); | |
839 | Step::Quiet | |
840 | }, | |
841 | Step::Quiet => Step::Quiet, | |
842 | Step::Terminated => Step::Terminated, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
843 | Step::Failure(e) => Step::Failure(e), |
0 | 844 | } |
845 | } | |
846 | ||
847 | #[inline] | |
848 | fn iteration(&self) -> usize { | |
849 | self.base_iterator.iteration() | |
850 | } | |
851 | ||
852 | #[inline] | |
853 | fn state(&self) -> Self::State { | |
854 | self.base_iterator.state() | |
855 | } | |
856 | } | |
857 | ||
858 | /// This [`AlgIteratorFactory`] allows output mapping. | |
5 | 859 | /// |
860 | /// Typically produced with [`AlgIteratorFactory::mapped`]. | |
0 | 861 | #[derive(Debug)] |
862 | pub struct MappingIteratorFactory<G, BaseFactory> { | |
5 | 863 | /// Base [`AlgIteratorFactory`] on which to build |
864 | base_options : BaseFactory, | |
865 | /// A closure `G : Fn(usize, BaseFactory::Output) -> U` that gets the current iteration | |
866 | /// and the output of the base factory as input, and produces a new output. | |
867 | map : G, | |
0 | 868 | } |
869 | ||
5 | 870 | /// [`AlgIterator`] produced by [`MappingIteratorFactory`]. |
0 | 871 | pub struct MappingIterator<G, BaseIterator> { |
872 | base_iterator : BaseIterator, | |
873 | map : G, | |
874 | } | |
875 | ||
876 | ||
877 | impl<V, U, G, BaseFactory> AlgIteratorFactory<V> | |
878 | for MappingIteratorFactory<G, BaseFactory> | |
879 | where BaseFactory : AlgIteratorFactory<V>, | |
880 | G : Fn(usize, BaseFactory::Output) -> U { | |
881 | type State = BaseFactory::State; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
882 | type Iter<F, E> = MappingIterator<G, BaseFactory::Iter<F, E>> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
883 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
884 | E : Error; |
0 | 885 | type Output = U; |
886 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
887 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
888 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
889 | E : Error { |
0 | 890 | MappingIterator { |
891 | base_iterator : self.base_options.prepare(step_fn), | |
892 | map : self.map | |
893 | } | |
894 | } | |
895 | ||
896 | #[inline] | |
897 | fn is_quiet(&self) -> bool { | |
898 | self.base_options.is_quiet() | |
899 | } | |
900 | } | |
901 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
902 | impl<U, G, BaseIterator> AlgIterator |
0 | 903 | for MappingIterator<G, BaseIterator> |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
904 | where BaseIterator : AlgIterator, |
0 | 905 | G : Fn(usize, BaseIterator::Output) -> U { |
906 | type State = BaseIterator::State; | |
907 | type Output = U; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
908 | type Err = BaseIterator::Err; |
0 | 909 | |
910 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
911 | fn step(&mut self) -> Step<Self::Output, Self::Err> { |
0 | 912 | match self.base_iterator.step() { |
913 | Step::Result(v) => Step::Result((self.map)(self.iteration(), v)), | |
914 | Step::Quiet => Step::Quiet, | |
915 | Step::Terminated => Step::Terminated, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
916 | Step::Failure(e) => Step::Failure(e), |
0 | 917 | } |
918 | } | |
919 | ||
920 | #[inline] | |
921 | fn iteration(&self) -> usize { | |
922 | self.base_iterator.iteration() | |
923 | } | |
924 | ||
925 | #[inline] | |
926 | fn state(&self) -> Self::State { | |
927 | self.base_iterator.state() | |
928 | } | |
929 | } | |
930 | ||
931 | // | |
932 | // Timing iterator | |
933 | // | |
934 | ||
5 | 935 | /// An [`AlgIteratorFactory`] for an [`AlgIterator`] that adds spent CPU time to verbose events. |
0 | 936 | #[derive(Debug)] |
937 | pub struct TimingIteratorFactory<BaseFactory>(pub BaseFactory); | |
938 | ||
939 | /// Iterator produced by [`TimingIteratorFactory`] | |
940 | #[derive(Debug)] | |
941 | pub struct TimingIterator<BaseIterator> { | |
942 | base_iterator : BaseIterator, | |
943 | start_time : ProcessTime, | |
944 | } | |
945 | ||
946 | /// Data `U` with production time attached | |
947 | #[derive(Copy, Clone, Debug, Serialize)] | |
948 | pub struct Timed<U> { | |
949 | pub cpu_time : Duration, | |
950 | //#[serde(flatten)] | |
951 | pub data : U | |
952 | } | |
953 | ||
954 | impl<T> LogRepr for Timed<T> where T : LogRepr { | |
955 | fn logrepr(&self) -> ColoredString { | |
956 | format!("[{:.3}s] {}", self.cpu_time.as_secs_f64(), self.data.logrepr()).as_str().into() | |
957 | } | |
958 | } | |
959 | ||
960 | ||
961 | impl<V, BaseFactory> AlgIteratorFactory<V> | |
962 | for TimingIteratorFactory<BaseFactory> | |
963 | where BaseFactory : AlgIteratorFactory<V> { | |
964 | type State = BaseFactory::State; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
965 | type Iter<F, E> = TimingIterator<BaseFactory::Iter<F, E>> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
966 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
967 | E : Error; |
0 | 968 | type Output = Timed<BaseFactory::Output>; |
969 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
970 | fn prepare<F, E>(self, step_fn : F) -> Self::Iter<F, E> |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
971 | where F : FnMut(&Self::State) -> Step<V, E>, |
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
972 | E : Error { |
0 | 973 | TimingIterator { |
974 | base_iterator : self.0.prepare(step_fn), | |
975 | start_time : ProcessTime::now() | |
976 | } | |
977 | } | |
978 | ||
979 | #[inline] | |
980 | fn is_quiet(&self) -> bool { | |
981 | self.0.is_quiet() | |
982 | } | |
983 | } | |
984 | ||
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
985 | impl<BaseIterator> AlgIterator |
0 | 986 | for TimingIterator<BaseIterator> |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
987 | where BaseIterator : AlgIterator { |
0 | 988 | type State = BaseIterator::State; |
989 | type Output = Timed<BaseIterator::Output>; | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
990 | type Err = BaseIterator::Err; |
0 | 991 | |
992 | #[inline] | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
993 | fn step(&mut self) -> Step<Self::Output, Self::Err> { |
0 | 994 | match self.base_iterator.step() { |
995 | Step::Result(data) => { | |
996 | Step::Result(Timed{ | |
997 | cpu_time : self.start_time.elapsed(), | |
998 | data | |
999 | }) | |
1000 | }, | |
1001 | Step::Quiet => Step::Quiet, | |
1002 | Step::Terminated => Step::Terminated, | |
3
20db884b7028
Allow step closure of AlgIterators to indicate succesfull termination or failure.
Tuomo Valkonen <tuomov@iki.fi>
parents:
1
diff
changeset
|
1003 | Step::Failure(e) => Step::Failure(e), |
0 | 1004 | } |
1005 | } | |
1006 | ||
1007 | #[inline] | |
1008 | fn iteration(&self) -> usize { | |
1009 | self.base_iterator.iteration() | |
1010 | } | |
1011 | ||
1012 | #[inline] | |
1013 | fn state(&self) -> Self::State { | |
1014 | self.base_iterator.state() | |
1015 | } | |
1016 | } | |
1017 | ||
1018 | // | |
1019 | // Tests | |
1020 | // | |
1021 | ||
1022 | #[cfg(test)] | |
1023 | mod tests { | |
1024 | use super::*; | |
1025 | use crate::logger::Logger; | |
1026 | #[test] | |
1027 | fn iteration() { | |
1028 | let options = AlgIteratorOptions{ | |
1029 | max_iter : 10, | |
1030 | verbose_iter : Verbose::Every(3), | |
1031 | .. Default::default() | |
1032 | }; | |
1033 | ||
1034 | { | |
1035 | let mut start = 1 as int; | |
1036 | options.iterate(|state| { | |
1037 | start = start * 2; | |
1038 | state.if_verbose(|| start) | |
1039 | }); | |
1040 | assert_eq!(start, (2 as int).pow(10)); | |
1041 | } | |
1042 | ||
1043 | { | |
1044 | let mut start = 1 as int; | |
1045 | let mut log = Logger::new(); | |
1046 | let factory = options.instantiate() | |
1047 | .with_iteration_number() | |
1048 | .into_log(&mut log); | |
1049 | factory.iterate(|state| { | |
1050 | start = start * 2; | |
1051 | state.if_verbose(|| start) | |
1052 | }); | |
1053 | assert_eq!(start, (2 as int).pow(10)); | |
1054 | assert_eq!(log.data() | |
1055 | .iter() | |
1056 | .map(|LogItem{ data : v, iter : _ }| v.clone()) | |
1057 | .collect::<Vec<int>>(), | |
1
df3901ec2f5d
Fix some unit tests after fundamental changes that made them invalid
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
1058 | (1..10).map(|i| (2 as int).pow(i)) |
df3901ec2f5d
Fix some unit tests after fundamental changes that made them invalid
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
1059 | .skip(2) |
df3901ec2f5d
Fix some unit tests after fundamental changes that made them invalid
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
1060 | .step_by(3) |
0 | 1061 | .collect::<Vec<int>>()) |
1062 | } | |
1063 | } | |
1064 | } |