1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::{
    algorithm::Algorithm,
    random::{get_rng, random_seed, Prng, Seed},
    simulation::{SimResult, Simulation, SimulationBuilder, State},
    statistic::{ProcessingTime, TrackProcessingTime},
    termination::{StopFlag, Termination},
};
use chrono::{DateTime, Local};
use std::{
    error::Error,
    fmt::{self, Debug, Display},
    hash::Hash,
};

/// The `simulate` function creates a new `Simulator` for the given
/// `algorithm::Algorithm`.
pub fn simulate<A>(algorithm: A) -> SimulatorBuilderWithAlgorithm<A>
where
    A: Algorithm,
{
    SimulatorBuilderWithAlgorithm { algorithm }
}

#[derive(Clone, Debug, PartialEq)]
pub struct SimulatorBuilder<A, T>
where
    A: Algorithm,
    T: Termination<A>,
{
    algorithm: A,
    termination: T,
}

impl<A, T> SimulationBuilder<Simulator<A, T>, A> for SimulatorBuilder<A, T>
where
    A: Algorithm + TrackProcessingTime + Debug,
    <A as Algorithm>::Error: Eq + Hash + Display + Send + Sync,
    T: Termination<A>,
{
    fn build(self) -> Simulator<A, T> {
        self.build_with_seed(random_seed())
    }

    fn build_with_seed(self, seed: Seed) -> Simulator<A, T> {
        Simulator {
            algorithm: self.algorithm,
            termination: self.termination,
            run_mode: RunMode::NotRunning,
            rng: get_rng(seed),
            started_at: Local::now(),
            iteration: 0,
            processing_time: ProcessingTime::zero(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct SimulatorBuilderWithAlgorithm<A>
where
    A: Algorithm,
{
    algorithm: A,
}

impl<A> SimulatorBuilderWithAlgorithm<A>
where
    A: Algorithm,
{
    pub fn until<T>(self, termination: T) -> SimulatorBuilder<A, T>
    where
        T: Termination<A>,
    {
        SimulatorBuilder {
            algorithm: self.algorithm,
            termination,
        }
    }
}

/// The `RunMode` identifies whether the simulation is running and how it has
/// been started.
#[derive(Clone, Debug, PartialEq)]
enum RunMode {
    /// The simulation is running in loop mode. i.e. it was started by calling
    /// the `run` function.
    Loop,
    /// The simulation is running in step mode. i.e. it was started by calling
    /// the `step` function.
    Step,
    /// The simulation is not running.
    NotRunning,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SimError<A>
where
    A: Algorithm + Debug,
    <A as Algorithm>::Error: Eq + Hash + Debug,
{
    AlgorithmError(<A as Algorithm>::Error),
    SimulationAlreadyRunning(String),
}

impl<A> Display for SimError<A>
where
    A: Algorithm + Debug,
    <A as Algorithm>::Error: Eq + Hash + Debug + Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SimError::AlgorithmError(ref error) => write!(f, "algorithm error: {}", error),
            SimError::SimulationAlreadyRunning(ref message) => {
                write!(f, "simulation already running {}", message)
            }
        }
    }
}

impl<A> Error for SimError<A>
where
    A: Algorithm + Debug,
    <A as Algorithm>::Error: 'static + Eq + Hash + Debug + Display,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            SimError::AlgorithmError(ref error) => Some(error),
            SimError::SimulationAlreadyRunning(_) => None,
        }
    }
}

#[derive(Clone, Debug)]
pub struct Simulator<A, T>
where
    A: Algorithm,
    T: Termination<A>,
{
    algorithm: A,
    termination: T,
    run_mode: RunMode,
    rng: Prng,
    started_at: DateTime<Local>,
    iteration: u64,
    processing_time: ProcessingTime,
}

impl<A, T> Simulator<A, T>
where
    A: Algorithm + TrackProcessingTime + Debug,
    <A as Algorithm>::Error: Eq + Hash + Display + Send + Sync,
    T: Termination<A>,
{
    pub fn termination(&self) -> &T {
        &self.termination
    }

    /// Processes one iteration of the algorithm used in this simulation.
    fn process_one_iteration(&mut self) -> Result<State<A>, <Self as Simulation<A>>::Error> {
        let loop_started_at = Local::now();

        self.iteration += 1;
        let result = self.algorithm.next(self.iteration, &mut self.rng);
        self.processing_time += self.algorithm.processing_time();

        let loop_duration = Local::now().signed_duration_since(loop_started_at);
        match result {
            Ok(result) => Ok(State {
                started_at: self.started_at,
                iteration: self.iteration,
                duration: loop_duration,
                processing_time: self.algorithm.processing_time(),
                result,
            }),
            Err(error) => Err(SimError::AlgorithmError(error)),
        }
    }
}

impl<A, T> Simulation<A> for Simulator<A, T>
where
    A: Algorithm + TrackProcessingTime + Debug,
    <A as Algorithm>::Error: Eq + Hash + Display + Send + Sync,
    T: Termination<A>,
{
    type Error = SimError<A>;

    fn run(&mut self) -> Result<SimResult<A>, Self::Error> {
        match self.run_mode {
            RunMode::Loop => {
                return Err(SimError::SimulationAlreadyRunning(format!(
                    "in loop mode since {}",
                    &self.started_at
                )))
            }
            RunMode::Step => {
                return Err(SimError::SimulationAlreadyRunning(format!(
                    "in step mode since {}",
                    &self.started_at
                )))
            }
            RunMode::NotRunning => {
                self.run_mode = RunMode::Loop;
                self.started_at = Local::now();
            }
        }
        let result = loop {
            match self.process_one_iteration() {
                Ok(state) => {
                    // Stage 5: Be aware of the termination:
                    match self.termination.evaluate(&state) {
                        StopFlag::Continue => {}
                        StopFlag::StopNow(reason) => {
                            let processing_time = self.processing_time;
                            let duration = Local::now().signed_duration_since(self.started_at);
                            break Ok(SimResult::Final(state, processing_time, duration, reason));
                        }
                    }
                }
                Err(error) => {
                    break Err(error);
                }
            }
        };
        self.run_mode = RunMode::NotRunning;
        result
    }

    fn step(&mut self) -> Result<SimResult<A>, Self::Error> {
        match self.run_mode {
            RunMode::Loop => {
                return Err(SimError::SimulationAlreadyRunning(format!(
                    "in loop mode since {}",
                    &self.started_at
                )))
            }
            RunMode::Step => (),
            RunMode::NotRunning => {
                self.run_mode = RunMode::Step;
                self.started_at = Local::now();
            }
        }
        self.process_one_iteration().and_then(|state|
            // Stage 5: Be aware of the termination:
            Ok(match self.termination.evaluate(&state) {
                StopFlag::Continue => {
                    SimResult::Intermediate(state)
                },
                StopFlag::StopNow(reason) => {
                    let processing_time = self.processing_time;
                    let duration = Local::now().signed_duration_since(self.started_at);
                    self.run_mode = RunMode::NotRunning;
                    SimResult::Final(state, processing_time, duration, reason)
                },
            }))
    }

    fn stop(&mut self) -> Result<bool, Self::Error> {
        match self.run_mode {
            RunMode::Loop | RunMode::Step => {
                self.run_mode = RunMode::NotRunning;
                Ok(true)
            }
            RunMode::NotRunning => Ok(false),
        }
    }

    fn reset(&mut self) -> Result<bool, Self::Error> {
        match self.run_mode {
            RunMode::Loop => {
                return Err(SimError::SimulationAlreadyRunning(format!(
                    "Simulation still running in loop mode since {}. Wait for the \
                     simulation to finish or stop it before resetting it.",
                    &self.started_at
                )))
            }
            RunMode::Step => {
                return Err(SimError::SimulationAlreadyRunning(format!(
                    "Simulation still running in step mode since {}. Wait for the \
                     simulation to finish or stop it before resetting it.",
                    &self.started_at
                )))
            }
            RunMode::NotRunning => (),
        }
        self.run_mode = RunMode::NotRunning;
        self.processing_time = ProcessingTime::zero();
        self.iteration = 0;
        self.algorithm.reset().map_err(SimError::AlgorithmError)
    }
}