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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// Copyright (c) 2020-2022  David Sorokin <david.sorokin@gmail.com>, based in Yoshkar-Ola, Russia
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::sync::Arc;
use std::default::Default;
use std::result;

#[cfg(feature="branch_mode")]
use std::io;

#[cfg(feature="branch_mode")]
use std::io::*;

use dvcompute_dist::simulation;
use dvcompute_dist::simulation::*;
use dvcompute_dist::simulation::generator::*;
use dvcompute_dist::simulation::composite::*;
use dvcompute_dist::simulation::simulation::*;
use dvcompute_dist::simulation::event::*;
use dvcompute_dist::simulation::observable::disposable::*;
use dvcompute_results_dist::simulation::results;
use dvcompute_results_dist::simulation::results::*;
use dvcompute_results_dist::simulation::results::locale::*;

#[cfg(feature="branch_mode")]
use rayon::prelude::*;

#[cfg(feature="dist_mode")]
use dvcompute_dist::simulation::comm::context::*;

#[cfg(feature="dist_mode")]
use dvcompute_dist::simulation::comm::pid::*;

#[cfg(feature="dist_mode")]
use dvcompute_dist::simulation::comm::lp::*;

#[cfg(feature="dist_mode")]
use dvcompute_dist::simulation::comm::time::*;

#[cfg(feature="dist_mode")]
use dvcompute_network::network::*;

/// Default renderers.
pub mod rendering;

/// Default view instances.
pub mod view;

/// It defines the simulation experiment.
#[derive(Clone)]
pub struct Experiment {

    /// The simulation specs for the experiment.
    pub specs: Specs,

    /// How the results must be transformed before rendering.
    pub transform: Arc<dyn Fn() -> ResultTransform + Sync + Send>,

    /// Specifies a locale.
    pub locale: ResultLocale,

    /// How many simulation runs should be launched.
    pub run_count: usize,

    /// The experiment title.
    pub title: String,

    /// The experiment description.
    pub description: Option<String>,

    /// Whether the process of generating the results is verbose.
    pub verbose: bool,

    /// The number of threads used when running the simulation experiment (can be ignored).
    pub num_threads: Option<usize>
}

impl Default for Experiment {

    fn default() -> Self {
        Self {
            specs: Specs {
                start_time: 0.0,
                stop_time: 10.0,
                dt: 0.01,
                generator_type: GeneratorType::Simple
            },
            transform: Arc::new(|| { ResultTransform::new(|x| { results::Result::Ok(x.clone()) }) }),
            locale: ResultLocale::En,
            run_count: 1,
            title: String::from("Simulation Experiment"),
            description: None,
            verbose: true,
            num_threads: None
        }
    }
}

impl Experiment {

    /// Run the simulation experiment with the specified executor.
    #[cfg(any(feature="branch_mode", feature="branch_wasm_mode"))]
    pub fn run<I, R, F, E, M>(&self,
        generators: I,
        rendering: R,
        simulation: F,
        executor: E) -> simulation::Result<()>
            where
                I: IntoIterator<Item = Box<dyn ExperimentGenerator<R>>>,
                R: ExperimentRendering + Send + 'static,
                F: FnOnce() -> M + Sync + Send + Clone + 'static,
                M: Simulation<Item = ResultSet> + Clone + 'static,
                E: ExperimentExecutor
    {
        let specs = self.specs.clone();
        let launcher = move |comp: SimulationBox<()>, run_index, run_count| {
            comp.run_by_index(specs, run_index, run_count)
        };

        self.run_with_executor_and_launcher(generators, rendering, simulation, executor, launcher)
    }

    /// Run the simulation experiment.
    #[cfg(feature="dist_mode")]
    pub fn run<'a, I, R, F, E>(&self,
        generators: I,
        rendering: R,
        simulation: F,
        executor: E) -> simulation::Result<()>
            where
                I: IntoIterator<Item = Box<dyn ExperimentGenerator<R>>>,
                R: ExperimentRendering + Send + 'static,
                F: FnOnce(&LogicalProcessContext, ExperimentCont) -> simulation::Result<()> + Sync + Send + Clone + 'static,
                E: ExperimentExecutor
    {
        let specs = self.specs.clone();
        let launcher = move |ctx: &LogicalProcessContext, comp: SimulationBox<()>, run_index, run_count| {
            comp.run_by_index(specs, ctx, run_index, run_count)
        };

        self.run_with_executor_and_launcher(generators, rendering, simulation, executor, launcher)
    }

    /// Run the simulation experiment with the specified executor and launcher.
    #[cfg(any(feature="branch_mode", feature="branch_wasm_mode"))]
    fn run_with_executor_and_launcher<I, R, F, E, L, M>(&self,
        generators: I,
        rendering: R,
        simulation: F,
        executor: E,
        launcher: L) -> simulation::Result<()>
            where
                I: IntoIterator<Item = Box<dyn ExperimentGenerator<R>>>,
                R: ExperimentRendering + Send + 'static,
                F: FnOnce() -> M + Sync + Send + Clone + 'static,
                M: Simulation<Item = ResultSet> + Clone + 'static,
                E: ExperimentExecutor,
                L: FnOnce(SimulationBox<()>, usize, usize) -> simulation::Result<()> + Sync + Send + Clone + 'static
    {
        let env = rendering.prepare(self)?;
        let reporters: Vec<_> = generators.into_iter()
            .map(|x| { x.report(&rendering, self, &env) })
            .collect();
        let reporters = Arc::new(reporters);
        for reporter in reporters.iter() {
            reporter.initialise()?;
        }
        let simulate: Vec<_> = (0 .. self.run_count)
            .map(|run_index| {
                let run_count  = self.run_count;
                let simulation = simulation.clone();
                let launcher   = launcher.clone();
                let reporters  = reporters.clone();
                let f: Box<dyn Fn() -> simulation::Result<()> + Sync + Send> = {
                    Box::new(move || {
                        let simulation = simulation.clone();
                        let launcher   = launcher.clone();
                        let reporters  = reporters.clone();
                        let comp = {
                            ResultPredefinedObservableSet::new()
                                .flat_map(move |predefined_observables| {
                                    simulation().flat_map(move |results| {
                                        let d = ExperimentData { results, predefined_observables };
                                        let comps: Vec<_> = reporters.iter()
                                            .map(|x| { x.simulate(&d) })
                                            .collect();
                                        composite_sequence_(comps)
                                            .run(empty_disposable())
                                            .run_in_start_time_by(false)
                                            .flat_map(move |((), fs)| {
                                                return_event(())
                                                    .run_in_stop_time()
                                                    .finally({
                                                        fs.into_event()
                                                            .run_in_stop_time()
                                                    })
                                            })
                                    })
                                })
                                .into_boxed()
                        };

                        launcher(comp, run_index, run_count)
                    })
                };

                f
            })
            .collect();
        let x = executor.execute(simulate);
        for reporter in reporters.iter() {
            reporter.finalise()?;
        }
        match x {
            result::Result::Ok(a) => {
                rendering.render(&self, &reporters, &env)?;
                rendering.on_completed(&self, &env)?;
                result::Result::Ok(a)
            },
            result::Result::Err(e) => {
                rendering.on_failed(&self, &env, &e)?;
                result::Result::Err(e)
            }
        }
    }

    /// Run the simulation experiment with the specified executor and launcher.
    #[cfg(feature="dist_mode")]
    fn run_with_executor_and_launcher<I, R, F, E, L>(&self,
        generators: I,
        rendering: R,
        simulation: F,
        executor: E,
        launcher: L) -> simulation::Result<()>
            where
                I: IntoIterator<Item = Box<dyn ExperimentGenerator<R>>>,
                R: ExperimentRendering + Send + 'static,
                F: FnOnce(&LogicalProcessContext, ExperimentCont) -> simulation::Result<()> + Sync + Send + Clone + 'static,
                E: ExperimentExecutor,
                L: FnOnce(&LogicalProcessContext, SimulationBox<()>, usize, usize) -> simulation::Result<()> + Sync + Send + Clone + 'static
    {
        let env = rendering.prepare(self)?;
        let reporters: Vec<_> = generators.into_iter()
            .map(|x| { x.report(&rendering, self, &env) })
            .collect();
        let reporters = Arc::new(reporters);
        for reporter in reporters.iter() {
            reporter.initialise()?;
        }
        let simulate: Vec<_> = (0 .. self.run_count)
            .map(|run_index| {
                let run_count  = self.run_count;
                let simulation = simulation.clone();
                let launcher   = launcher.clone();
                let reporters  = reporters.clone();
                let f: Box<dyn Fn(&LogicalProcessContext) -> simulation::Result<()> + Sync + Send> = {
                    Box::new(move |ctx| {
                        let simulation = simulation.clone();
                        let launcher   = launcher.clone();
                        let reporters  = reporters.clone();
                        simulation(ctx, Box::new(move |ctx, results| {
                            let comp = {
                                results
                                    .flat_map(move |results| {
                                        ResultPredefinedObservableSet::new()
                                            .flat_map(move |predefined_observables| {
                                                let d = ExperimentData { results, predefined_observables };
                                                let comps: Vec<_> = reporters.iter()
                                                    .map(|x| { x.simulate(&d) })
                                                    .collect();
                                                composite_sequence_(comps)
                                                    .run(empty_disposable())
                                                    .run_in_start_time_by(false)
                                                    .flat_map(move |((), fs)| {
                                                        return_event(())
                                                            .run_in_stop_time()
                                                            .finally({
                                                                fs.into_event()
                                                                    .run_in_stop_time()
                                                            })
                                                    })
                                            })
                                            .into_boxed()
                                    })
                                    .into_boxed()
                            };

                            launcher(ctx, comp, run_index, run_count)
                        }))
                    })
                };

                f
            })
            .collect();
        let x = executor.execute(simulate);
        for reporter in reporters.iter() {
            reporter.finalise()?;
        }
        match x {
            result::Result::Ok(a) => {
                rendering.render(&self, &reporters, &env)?;
                rendering.on_completed(&self, &env)?;
                result::Result::Ok(a)
            },
            result::Result::Err(e) => {
                rendering.on_failed(&self, &env, &e)?;
                result::Result::Err(e)
            }
        }
    }

    /// Run the time server for the specified number of run counts.
    #[cfg(feature="dist_mode")]
    pub fn run_time_server<F>(network: F, run_count: usize, ps: TimeServerParameters)
        where F: Fn(usize) -> NetworkSupport
    {
        for run_index in 0 .. run_count {
            let mut network = network(run_index);
            let init_quorum = (network.size() - 1) as usize;
            let ps = ps.clone();

            network.barrier();
            TimeServer::run(network, init_quorum, ps);
        }
    }
}

/// The continuation of simulation experiment.
#[cfg(feature="dist_mode")]
pub type ExperimentCont = Box<dyn FnOnce(&LogicalProcessContext, SimulationBox<ResultSet>) -> simulation::Result<()>>;

/// It allows rendering the simulation results in an arbitrary way.
pub trait ExperimentRendering {

    /// Defines a context used when rendering the experiment.
    type ExperimentContext: Send;

    /// Defines the experiment environment.
    type ExperimentEnvironment: Send;

    /// Prepare before rendering the experiment.
    fn prepare(&self, experiment: &Experiment) -> simulation::Result<Self::ExperimentEnvironment>;

    /// Render the experiment after the simulation is finished, example,
    /// create the `index.html` file in the specified directory.
    fn render(&self, experiment: &Experiment, reporters: &Vec<Box<dyn ExperimentReporter<Self> + Sync + Send>>, env: &Self::ExperimentEnvironment) -> simulation::Result<()>
        where Self: Sized;

    /// It is called when the experiment has been completed.
    fn on_completed(&self, experiment: &Experiment, env: &Self::ExperimentEnvironment) -> simulation::Result<()>;

    /// It is called when the experiment has been failed.
    fn on_failed(&self, experiment: &Experiment, env: &Self::ExperimentEnvironment, err: &simulation::error::Error) -> simulation::Result<()>;
}

/// Defines a view in which the simulation results should be saved.
/// You should extend this type class to define your own views such
/// as the PDF document.
pub trait ExperimentView<R: ExperimentRendering> {

    /// Get the view of the corresponding results.
    fn view(self) -> Box<dyn ExperimentGenerator<R>>;
}

/// This is a generator of the reporter with the specified rendering backend.
pub trait ExperimentGenerator<R: ExperimentRendering> {

    /// Create the result reporter.
    fn report(&self, rendering: &R, experiment: &Experiment, env: &R::ExperimentEnvironment) -> Box<dyn ExperimentReporter<R> + Sync + Send>;
}

/// It describes the source simulation data used in the experiment.
#[derive(Clone)]
pub struct ExperimentData {

    /// The simulation results used in the experiment.
    pub results: ResultSet,

    /// The predefined signals provided by every model.
    pub predefined_observables: ResultPredefinedObservableSet
}

/// Defines what creates the simulation reports by the specified renderer.
pub trait ExperimentReporter<R: ExperimentRendering> {

    /// Initialise the reporting before the simulation runs are started.
    fn initialise(&self) -> simulation::Result<()>;

    /// Finalise the reporting after all simulation runs are finished.
    fn finalise(&self) -> simulation::Result<()>;

    /// Start the simulation run in the start time.
    fn simulate(&self, xs: &ExperimentData) -> CompositeBox<()>;

    /// The context used by the renderer.
    fn context(&self) -> R::ExperimentContext;
}

/// It executes the simulation experiment.
pub trait ExperimentExecutor {

    /// Execute the simulation models.
    #[cfg(any(feature="branch_mode", feature="branch_wasm_mode"))]
    fn execute(self, models: Vec<Box<dyn Fn() -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()>;

    /// Execute the simulation models.
    #[cfg(feature="dist_mode")]
    fn execute(self, models: Vec<Box<dyn Fn(&LogicalProcessContext) -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()>;
}

/// The prebuit simulation experiment executors.
#[cfg(feature="branch_mode")]
pub enum BasicExperimentExecutor {

    /// Sequentially launch each experiment after experiment.
    Seq,

    /// Lauch experiments in parallel.
    Par
}

/// The prebuit simulation experiment executors.
#[cfg(feature="branch_wasm_mode")]
pub enum BasicExperimentExecutor {

    /// Sequentially launch each experiment after experiment.
    Seq
}

/// The prebuit simulation experiment executors.
#[cfg(feature="branch_wasm_mode")]
pub enum BasicExperimentExecutor {

    /// Sequentially launch each experiment after experiment.
    Seq
}

#[cfg(feature="branch_mode")]
impl Default for BasicExperimentExecutor {

    fn default() -> Self {
        BasicExperimentExecutor::Par
    }
}

#[cfg(feature="branch_wasm_mode")]
impl Default for BasicExperimentExecutor {

    fn default() -> Self {
        BasicExperimentExecutor::Seq
    }
}

#[cfg(feature="branch_wasm_mode")]
impl Default for BasicExperimentExecutor {

    fn default() -> Self {
        BasicExperimentExecutor::Seq
    }
}

#[cfg(feature="branch_mode")]
impl ExperimentExecutor for BasicExperimentExecutor {

    fn execute(self, models: Vec<Box<dyn Fn() -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()> {
        match self {
            BasicExperimentExecutor::Seq => {
                for x in models {
                    match x() {
                        result::Result::Ok(()) => continue,
                        result::Result::Err(e) => return result::Result::Err(e)
                    }
                }

                result::Result::Ok(())
            },
            BasicExperimentExecutor::Par => {
                models.par_iter()
                    .map(|x| {
                        match x() {
                            result::Result::Ok(()) => {},
                            result::Result::Err(e) => {
                                let _ = writeln!(io::stderr(), "Error: {:?}", e);
                            }
                        }
                        0
                    })
                    .sum::<usize>();

                result::Result::Ok(())
            }
        }
    }
}

#[cfg(feature="branch_wasm_mode")]
impl ExperimentExecutor for BasicExperimentExecutor {

    fn execute(self, models: Vec<Box<dyn Fn() -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()> {
        match self {
            BasicExperimentExecutor::Seq => {
                for x in models {
                    match x() {
                        result::Result::Ok(()) => continue,
                        result::Result::Err(e) => return result::Result::Err(e)
                    }
                }

                result::Result::Ok(())
            }
        }
    }
}

/// The logical process executor.
#[cfg(feature="dist_mode")]
pub struct LogicalProcessExecutor {

    /// Get the network support by the specified run index.
    pub network: Box<dyn Fn(usize) -> NetworkSupport>,

    /// The time server logical process identifier.
    pub time_server_id: LogicalProcessId,

    /// The logical process parameters.
    pub ps: LogicalProcessParameters
}

#[cfg(feature="dist_mode")]
impl ExperimentExecutor for LogicalProcessExecutor {

    fn execute(self, models: Vec<Box<dyn Fn(&LogicalProcessContext) -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()> {
        for (x, run_index) in models.into_iter().zip(0..) {
            let mut network = (self.network)(run_index);
            let x = move |ctx: &LogicalProcessContext| {
                match x(ctx) {
                    result::Result::Ok(()) => {},
                    result::Result::Err(e) => {
                        log::error!("{:?}", e);
                    }
                }
            };
            let time_server_id = self.time_server_id.clone();
            let ps = self.ps.clone();

            network.barrier();
            LogicalProcess::run(network, time_server_id, ps, x);
        }

        result::Result::Ok(())
    }
}