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
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::*;
pub mod rendering;
pub mod view;
#[derive(Clone)]
pub struct Experiment {
pub specs: Specs,
pub transform: Arc<dyn Fn() -> ResultTransform + Sync + Send>,
pub locale: ResultLocale,
pub run_count: usize,
pub title: String,
pub description: Option<String>,
pub verbose: bool,
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 {
#[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)
}
#[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)
}
#[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)
}
}
}
#[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)
}
}
}
#[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);
}
}
}
#[cfg(feature="dist_mode")]
pub type ExperimentCont = Box<dyn FnOnce(&LogicalProcessContext, SimulationBox<ResultSet>) -> simulation::Result<()>>;
pub trait ExperimentRendering {
type ExperimentContext: Send;
type ExperimentEnvironment: Send;
fn prepare(&self, experiment: &Experiment) -> simulation::Result<Self::ExperimentEnvironment>;
fn render(&self, experiment: &Experiment, reporters: &Vec<Box<dyn ExperimentReporter<Self> + Sync + Send>>, env: &Self::ExperimentEnvironment) -> simulation::Result<()>
where Self: Sized;
fn on_completed(&self, experiment: &Experiment, env: &Self::ExperimentEnvironment) -> simulation::Result<()>;
fn on_failed(&self, experiment: &Experiment, env: &Self::ExperimentEnvironment, err: &simulation::error::Error) -> simulation::Result<()>;
}
pub trait ExperimentView<R: ExperimentRendering> {
fn view(self) -> Box<dyn ExperimentGenerator<R>>;
}
pub trait ExperimentGenerator<R: ExperimentRendering> {
fn report(&self, rendering: &R, experiment: &Experiment, env: &R::ExperimentEnvironment) -> Box<dyn ExperimentReporter<R> + Sync + Send>;
}
#[derive(Clone)]
pub struct ExperimentData {
pub results: ResultSet,
pub predefined_observables: ResultPredefinedObservableSet
}
pub trait ExperimentReporter<R: ExperimentRendering> {
fn initialise(&self) -> simulation::Result<()>;
fn finalise(&self) -> simulation::Result<()>;
fn simulate(&self, xs: &ExperimentData) -> CompositeBox<()>;
fn context(&self) -> R::ExperimentContext;
}
pub trait ExperimentExecutor {
#[cfg(any(feature="branch_mode", feature="branch_wasm_mode"))]
fn execute(self, models: Vec<Box<dyn Fn() -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()>;
#[cfg(feature="dist_mode")]
fn execute(self, models: Vec<Box<dyn Fn(&LogicalProcessContext) -> simulation::Result<()> + Sync + Send>>) -> simulation::Result<()>;
}
#[cfg(feature="branch_mode")]
pub enum BasicExperimentExecutor {
Seq,
Par
}
#[cfg(feature="branch_wasm_mode")]
pub enum BasicExperimentExecutor {
Seq
}
#[cfg(feature="branch_wasm_mode")]
pub enum BasicExperimentExecutor {
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(())
}
}
}
}
#[cfg(feature="dist_mode")]
pub struct LogicalProcessExecutor {
pub network: Box<dyn Fn(usize) -> NetworkSupport>,
pub time_server_id: LogicalProcessId,
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(())
}
}