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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Simulation configuration and execution.
use std::cell::RefCell;
use std::rc::Rc;
use log::Level::Trace;
use log::{debug, log_enabled, trace};
use rand::distributions::uniform::{SampleRange, SampleUniform};
use rand::prelude::Distribution;
use serde_json::json;
use serde_type_name::type_name;
use crate::component::Id;
use crate::context::SimulationContext;
use crate::handler::{EventCancellationPolicy, EventHandler};
use crate::log::log_undelivered_event;
use crate::state::SimulationState;
use crate::{async_mode_disabled, async_mode_enabled, Event};
async_mode_enabled!(
use futures::Future;
use crate::event::EventData;
use crate::async_mode::channel::channel;
use crate::async_mode::executor::Executor;
use crate::async_mode::{UnboundedQueue, EventKey};
use crate::handler::StaticEventHandler;
);
async_mode_disabled!(
type Handlers = Vec<Option<Rc<RefCell<dyn EventHandler>>>>;
struct Executor;
fn build_inner(seed: u64) -> (SimulationState, Executor) {
(SimulationState::new(seed), Executor {})
}
);
async_mode_enabled!(
enum EventHandlerImpl {
Mutable(Rc<RefCell<dyn EventHandler>>),
Static(Rc<dyn StaticEventHandler>),
}
type Handlers = Vec<Option<EventHandlerImpl>>;
fn build_inner(seed: u64) -> (SimulationState, Executor) {
let (task_sender, task_receiver) = channel();
let sim_state = SimulationState::new(seed, task_sender);
let executor = Executor::new(task_receiver);
(sim_state, executor)
}
);
/// Represents a simulation, provides methods for its configuration and execution.
pub struct Simulation {
sim_state: Rc<RefCell<SimulationState>>,
handlers: Handlers,
// Specific to async mode
#[allow(dead_code)]
executor: Executor,
}
impl Simulation {
/// Creates a new simulation with specified random seed.
pub fn new(seed: u64) -> Self {
let (sim_state, executor) = build_inner(seed);
Self {
sim_state: Rc::new(RefCell::new(sim_state)),
handlers: Vec::new(),
executor,
}
}
fn register(&mut self, name: &str) -> Id {
let id = self.sim_state.borrow_mut().register(name);
if id as usize == self.handlers.len() {
self.handlers.push(None);
}
id
}
/// Returns the identifier of component by its name.
///
/// Panics if component with such name does not exist.
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// let comp_id = sim.lookup_id(comp_ctx.name());
/// assert_eq!(comp_id, 0);
/// ```
///
/// ```should_panic
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// let comp1_id = sim.lookup_id("comp1");
/// ```
pub fn lookup_id(&self, name: &str) -> Id {
self.sim_state.borrow().lookup_id(name)
}
/// Returns the name of component by its identifier.
///
/// Panics if component with such Id does not exist.
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// let comp_name = sim.lookup_name(comp_ctx.id());
/// assert_eq!(comp_name, "comp");
/// ```
///
/// ```should_panic
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// let comp_name = sim.lookup_name(comp_ctx.id() + 1);
/// ```
pub fn lookup_name(&self, id: Id) -> String {
self.sim_state.borrow().lookup_name(id)
}
/// Creates a new simulation context with specified name.
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// assert_eq!(comp_ctx.id(), 0); // component ids are assigned sequentially starting from 0
/// assert_eq!(comp_ctx.name(), "comp");
/// ```
pub fn create_context<S>(&mut self, name: S) -> SimulationContext
where
S: AsRef<str>,
{
let ctx = SimulationContext::new(self.register(name.as_ref()), name.as_ref(), self.sim_state.clone());
debug!(
target: "simulation",
"[{:.3} {} simulation] Created context: {}",
self.time(),
crate::log::get_colored("DEBUG", colored::Color::Blue),
json!({"name": ctx.name(), "id": ctx.id()})
);
ctx
}
/// Registers the event handler implementation for component with specified name, returns the component Id.
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use simcore::{Event, EventHandler, Simulation, SimulationContext};
///
/// struct Component {
/// ctx: SimulationContext,
/// }
///
/// impl EventHandler for Component {
/// fn on(&mut self, event: Event) {
/// }
/// }
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// assert_eq!(comp_ctx.id(), 0);
/// let comp = Rc::new(RefCell::new(Component { ctx: comp_ctx }));
/// // When the handler is registered for component with existing context,
/// // the component Id assigned in create_context() is reused.
/// let comp_id = sim.add_handler("comp", comp);
/// assert_eq!(comp_id, 0);
/// ```
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use simcore::{Event, EventHandler, Simulation, SimulationContext};
///
/// struct Component {
/// }
///
/// impl EventHandler for Component {
/// fn on(&mut self, event: Event) {
/// }
/// }
///
/// let mut sim = Simulation::new(123);
/// let comp = Rc::new(RefCell::new(Component {}));
/// // It is possible to register event handler for component without context.
/// // In this case the component Id is assigned inside add_handler().
/// let comp_id = sim.add_handler("comp", comp);
/// assert_eq!(comp_id, 0);
/// ```
///
/// ```compile_fail
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use simcore::{Simulation, SimulationContext};
///
/// pub struct Component {
/// ctx: SimulationContext,
/// }
///
/// let mut sim = Simulation::new(123);
/// let comp_ctx = sim.create_context("comp");
/// let comp = Rc::new(RefCell::new(Component { ctx: comp_ctx }));
/// // should not compile because Component does not implement EventHandler trait
/// let comp_id = sim.add_handler("comp", comp);
/// ```
pub fn add_handler<S>(&mut self, name: S, handler: Rc<RefCell<dyn EventHandler>>) -> Id
where
S: AsRef<str>,
{
let id = self.register(name.as_ref());
assert!(
self.handlers[id as usize].is_none(),
"Handler for component {} with Id {} already exists",
name.as_ref(),
id
);
self.add_handler_inner(id, handler);
debug!(
target: "simulation",
"[{:.3} {} simulation] Added handler: {}",
self.time(),
crate::log::get_colored("DEBUG", colored::Color::Blue),
json!({"name": name.as_ref(), "id": id})
);
id
}
async_mode_disabled!(
fn add_handler_inner(&mut self, id: Id, handler: Rc<RefCell<dyn EventHandler>>) {
self.handlers[id as usize] = Some(handler);
}
);
async_mode_enabled!(
/// Registers the static event handler for component with specified name, returns the component Id.
///
/// In contrast to [`EventHandler`], [`StaticEventHandler`] has `'static` lifetime while processing
/// incoming events, which allows spawning asynchronous tasks using component's context.
/// See [`SimulationContext::spawn`](crate::context::SimulationContext::spawn) examples.
pub fn add_static_handler<S>(&mut self, name: S, static_handler: Rc<dyn StaticEventHandler>) -> Id
where
S: AsRef<str>,
{
let id = self.register(name.as_ref());
assert!(
self.handlers[id as usize].is_none(),
"Handler for component {} with Id {} already exists",
name.as_ref(),
id
);
self.handlers[id as usize] = Some(EventHandlerImpl::Static(static_handler));
self.sim_state.borrow_mut().on_static_handler_added(id);
debug!(
target: "simulation",
"[{:.3} {} simulation] Added static handler: {}",
self.time(),
crate::log::get_colored("DEBUG", colored::Color::Blue),
json!({"name": name.as_ref(), "id": id})
);
id
}
fn add_handler_inner(&mut self, id: Id, handler: Rc<RefCell<dyn EventHandler>>) {
self.handlers[id as usize] = Some(EventHandlerImpl::Mutable(handler));
}
);
/// Removes the event handler for component with specified name.
///
/// All subsequent events destined for this component will not be delivered until the handler is added again.
///
/// Pending events to be cancelled upon the handler removal are specified via [`EventCancellationPolicy`].
///
/// If async mode is enabled, all pending asynchronous tasks and activities related to this component are cancelled.
/// To continue receiving events asynchronously after the handler is re-added, spawn new asynchronous tasks
/// using [`SimulationContext::spawn`]. Otherwise, the events will be delivered via [`EventHandler::on`].
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use simcore::{Event, EventCancellationPolicy, EventHandler, Simulation, SimulationContext};
///
/// struct Component {
/// }
///
/// impl EventHandler for Component {
/// fn on(&mut self, event: Event) {
/// }
/// }
///
/// let mut sim = Simulation::new(123);
/// let comp = Rc::new(RefCell::new(Component {}));
/// let comp_id1 = sim.add_handler("comp", comp.clone());
/// sim.remove_handler("comp", EventCancellationPolicy::None);
/// // Assigned component Id is not changed if we call `add_handler` again.
/// let comp_id2 = sim.add_handler("comp", comp);
/// assert_eq!(comp_id1, comp_id2);
/// ```
pub fn remove_handler<S>(&mut self, name: S, cancel_policy: EventCancellationPolicy)
where
S: AsRef<str>,
{
let id = self.lookup_id(name.as_ref());
self.handlers[id as usize] = None;
self.sim_state.borrow_mut().on_static_handler_removed(id);
self.remove_handler_inner(id);
// cancel pending events related to the removed component based on the cancellation policy
match cancel_policy {
EventCancellationPolicy::All => self.cancel_events(|e| e.src == id || e.dst == id),
EventCancellationPolicy::Incoming => self.cancel_events(|e| e.dst == id),
EventCancellationPolicy::Outgoing => self.cancel_events(|e| e.src == id),
_ => {}
}
debug!(
target: "simulation",
"[{:.3} {} simulation] Removed handler: {}",
self.time(),
crate::log::get_colored("DEBUG", colored::Color::Blue),
json!({"name": name.as_ref(), "id": id})
);
}
async_mode_disabled!(
fn remove_handler_inner(&mut self, _id: u32) {}
);
async_mode_enabled!(
fn remove_handler_inner(&mut self, id: u32) {
// cancel pending timers and event promises related to the removed component
self.sim_state.borrow_mut().cancel_component_timers(id);
self.sim_state.borrow_mut().cancel_component_promises(id);
}
);
/// Returns the current simulation time.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.2);
/// sim.step();
/// assert_eq!(sim.time(), 1.2);
/// ```
pub fn time(&self) -> f64 {
self.sim_state.borrow().time()
}
/// Performs a single step through the simulation.
///
/// Takes the next event from the queue, advances the simulation time to event time and tries to process it
/// by invoking the [`EventHandler::on`] method of the corresponding event handler.
/// If there is no handler registered for component with Id `event.dst`, logs the undelivered event and discards it.
///
/// Returns `true` if some pending event was found (no matter was it properly processed or not) and `false`
/// otherwise. The latter means that there are no pending events, so no progress can be made.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.2);
/// let mut status = sim.step();
/// assert!(status);
/// assert_eq!(sim.time(), 1.2);
/// status = sim.step();
/// assert!(!status);
/// ```
pub fn step(&self) -> bool {
self.step_inner()
}
async_mode_disabled!(
fn step_inner(&self) -> bool {
let event_opt = self.sim_state.borrow_mut().next_event();
match event_opt {
Some(event) => {
self.deliver_event_via_handler(event);
true
}
None => false,
}
}
fn deliver_event_via_handler(&self, event: Event) {
if let Some(handler_opt) = self.handlers.get(event.dst as usize) {
self.log_event(&event);
if let Some(handler) = handler_opt {
handler.borrow_mut().on(event);
} else {
log_undelivered_event(event);
}
} else {
log_undelivered_event(event);
}
}
);
async_mode_enabled!(
fn step_inner(&self) -> bool {
if self.process_task() {
return true;
}
let has_timer = self.sim_state.borrow_mut().peek_timer().is_some();
let has_event = self.sim_state.borrow_mut().peek_event().is_some();
if !has_timer && !has_event {
return false;
}
if !has_timer {
self.process_event();
return true;
}
if !has_event {
self.process_timer();
return true;
}
let next_timer_time = self.sim_state.borrow_mut().peek_timer().unwrap().time;
let next_event_time = self.sim_state.borrow_mut().peek_event().unwrap().time;
if next_event_time <= next_timer_time {
self.process_event();
} else {
self.process_timer();
}
true
}
fn process_event(&self) {
let event = self.sim_state.borrow_mut().next_event().unwrap();
let event_key = self
.sim_state
.borrow()
.get_key_getter(event.data.type_id())
.map(|getter| getter(event.data.as_ref()));
if self.sim_state.borrow().has_event_promise_for(&event, event_key) {
self.log_event(&event);
self.sim_state.borrow_mut().complete_event_promise(event, event_key);
self.process_task();
} else {
self.deliver_event_via_handler(event);
}
}
fn process_task(&self) -> bool {
self.executor.process_task()
}
fn process_timer(&self) {
let next_timer = self.sim_state.borrow_mut().next_timer().unwrap();
next_timer.complete();
// drop timer to release the pointer to the state
drop(next_timer);
self.process_task();
}
fn deliver_event_via_handler(&self, event: Event) {
if let Some(handler_opt) = self.handlers.get(event.dst as usize) {
self.log_event(&event);
if let Some(handler) = handler_opt {
match handler {
EventHandlerImpl::Mutable(handler) => handler.borrow_mut().on(event),
EventHandlerImpl::Static(handler) => handler.clone().on(event),
}
} else {
log_undelivered_event(event);
}
} else {
log_undelivered_event(event);
}
}
);
fn log_event(&self, event: &Event) {
if log_enabled!(Trace) {
let src_name = self.lookup_name(event.src);
let dst_name = self.lookup_name(event.dst);
trace!(
target: &dst_name,
"[{:.3} {} {}] {}",
event.time,
crate::log::get_colored("EVENT", colored::Color::BrightBlack),
dst_name,
json!({"type": type_name(&event.data).unwrap(), "data": event.data, "src": src_name})
);
}
}
async_mode_enabled!(
/// Spawns a new asynchronous task.
///
/// The task's type lifetime must be `'static`.
/// This means that the spawned task must not contain any references to data owned outside the task.
///
/// To spawn methods inside simulation components use [`SimulationContext::spawn`].
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
///
/// let ctx = sim.create_context("client");
///
/// sim.spawn(async move {
/// let initial_time = ctx.time();
/// ctx.sleep(5.).await;
/// assert_eq!(ctx.time(), 5.);
/// });
///
/// sim.step_until_no_events();
/// assert_eq!(sim.time(), 5.);
/// ```
pub fn spawn(&self, future: impl Future<Output = ()> + 'static) {
self.sim_state.borrow_mut().spawn(future);
}
/// Registers a function that extracts [`EventKey`] from events of a type `T`.
///
/// Calling this function is required before using [`SimulationContext::recv_event_by_key`] or
/// [`SimulationContext::recv_event_by_key_from`] with type `T`. See examples for these methods.
pub fn register_key_getter_for<T: EventData>(&self, key_getter: impl Fn(&T) -> EventKey + 'static) {
self.sim_state.borrow_mut().register_key_getter_for::<T>(key_getter);
}
/// Creates an [`UnboundedQueue`] for producer-consumer communication.
///
/// This queue is designed to support convenient communication between several asynchronous tasks
/// within a single simulation component. This enables implementing the component logic as a set of
/// communicating concurrent activities.
///
/// The use of this primitive for inter-component communication is discouraged in favor of passing events
/// directly or via intermediate components.
///
/// # Examples
///
/// ```rust
/// use std::rc::Rc;
/// use std::cell::RefCell;
/// use simcore::{Simulation, SimulationContext, Event, StaticEventHandler};
/// use simcore::async_mode::UnboundedQueue;
///
/// struct Message {
/// payload: u32,
/// }
///
/// struct Component {
/// ctx: SimulationContext,
/// queue: UnboundedQueue<Message>,
/// }
///
/// impl Component {
/// fn start(self: Rc<Self>) {
/// self.ctx.spawn(self.clone().producer());
/// self.ctx.spawn(self.clone().consumer());
/// }
///
/// async fn producer(self: Rc<Self>) {
/// for i in 0..10 {
/// self.ctx.sleep(5.).await;
/// self.queue.put(Message {payload: i});
/// }
/// }
///
/// async fn consumer(self: Rc<Self>) {
/// for i in 0..10 {
/// let msg = self.queue.take().await;
/// assert_eq!(msg.payload, i);
/// }
/// }
/// }
///
/// impl StaticEventHandler for Component {
/// fn on(self: Rc<Self>, event: Event) {
/// }
/// }
///
/// let mut sim = Simulation::new(123);
///
/// let comp = Rc::new(Component {
/// ctx: sim.create_context("comp"),
/// queue: sim.create_queue("comp_queue")
/// });
/// sim.add_static_handler("comp", comp.clone());
///
/// comp.start();
/// sim.step_until_no_events();
///
/// assert_eq!(sim.time(), 50.);
/// ```
pub fn create_queue<T, S>(&mut self, name: S) -> UnboundedQueue<T>
where
S: AsRef<str>,
{
UnboundedQueue::new(self.create_context(name))
}
);
/// Performs the specified number of steps through the simulation.
///
/// This is a convenient wrapper around [`step`](Self::step), which invokes this method until the specified number of
/// steps is made, or `false` is returned (no more pending events).
///
/// Returns `true` if there could be more pending events and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.2);
/// comp_ctx.emit_self(SomeEvent {}, 1.3);
/// comp_ctx.emit_self(SomeEvent {}, 1.4);
/// let mut status = sim.steps(2);
/// assert!(status);
/// assert_eq!(sim.time(), 1.3);
/// status = sim.steps(2);
/// assert!(!status);
/// assert_eq!(sim.time(), 1.4);
/// ```
pub fn steps(&mut self, step_count: u64) -> bool {
for _ in 0..step_count {
if !self.step() {
return false;
}
}
true
}
/// Steps through the simulation until there are no pending events left.
///
/// This is a convenient wrapper around [`step`](Self::step), which invokes this method until `false` is returned.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.2);
/// comp_ctx.emit_self(SomeEvent {}, 1.3);
/// comp_ctx.emit_self(SomeEvent {}, 1.4);
/// sim.step_until_no_events();
/// assert_eq!(sim.time(), 1.4);
/// ```
pub fn step_until_no_events(&mut self) {
while self.step() {}
}
/// Steps through the simulation with duration limit.
///
/// This is a convenient wrapper around [`step`](Self::step), which invokes this method until the next event
/// time is above the specified threshold (`initial_time + duration`) or there are no pending events left.
///
/// This method also advances the simulation time to `initial_time + duration`. Note that the resulted time may
/// slightly differ from the expected value due to the floating point errors. This issue can be avoided by using
/// the [`step_until_time`](Self::step_until_time) method.
///
/// Returns `true` if there could be more pending events and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.0);
/// comp_ctx.emit_self(SomeEvent {}, 2.0);
/// comp_ctx.emit_self(SomeEvent {}, 3.5);
/// let mut status = sim.step_for_duration(1.8);
/// assert_eq!(sim.time(), 1.8);
/// assert!(status); // there are more events
/// status = sim.step_for_duration(1.8);
/// assert_eq!(sim.time(), 3.6);
/// assert!(!status); // there are no more events
/// ```
pub fn step_for_duration(&mut self, duration: f64) -> bool {
let end_time = self.sim_state.borrow().time() + duration;
self.step_until_time(end_time)
}
/// Steps through the simulation until the specified time.
///
/// This is a convenient wrapper around [`step`](Self::step), which invokes this method until the next event
/// time is above the specified time or there are no pending events left.
///
/// This method also advances the simulation time to the specified time.
///
/// Returns `true` if there could be more pending events and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.0);
/// comp_ctx.emit_self(SomeEvent {}, 2.0);
/// comp_ctx.emit_self(SomeEvent {}, 3.5);
/// let mut status = sim.step_until_time(1.8);
/// assert_eq!(sim.time(), 1.8);
/// assert!(status); // there are more events
/// status = sim.step_until_time(3.6);
/// assert_eq!(sim.time(), 3.6);
/// assert!(!status); // there are no more events
/// ```
pub fn step_until_time(&mut self, time: f64) -> bool {
self.step_until_time_inner(time)
}
async_mode_disabled!(
fn step_until_time_inner(&mut self, time: f64) -> bool {
let mut result = true;
loop {
if let Some(event) = self.sim_state.borrow_mut().peek_event() {
if event.time > time {
break;
}
} else {
result = false;
break;
}
self.step();
}
self.sim_state.borrow_mut().set_time(time);
result
}
);
async_mode_enabled!(
fn step_until_time_inner(&mut self, time: f64) -> bool {
let mut result;
loop {
while self.process_task() {}
result = false;
let mut step = false;
if let Some(event) = self.sim_state.borrow_mut().peek_event() {
result = true;
if event.time <= time {
step = true;
}
}
if let Some(timer) = self.sim_state.borrow_mut().peek_timer() {
result = true;
if timer.time <= time {
step = true;
}
}
if step {
self.step();
} else {
break;
}
}
self.sim_state.borrow_mut().set_time(time);
result
}
);
/// Returns a random float in the range _[0, 1)_
/// using the simulation-wide random number generator.
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let f: f64 = sim.rand();
/// assert!(f >= 0.0 && f < 1.0);
/// ```
pub fn rand(&mut self) -> f64 {
self.sim_state.borrow_mut().rand()
}
/// Returns a random number in the specified range
/// using the simulation-wide random number generator.
///
/// # Examples
///
/// ```rust
/// use simcore::Simulation;
///
/// let mut sim = Simulation::new(123);
/// let n: u32 = sim.gen_range(1..=10);
/// assert!(n >= 1 && n <= 10);
/// let f: f64 = sim.gen_range(0.1..0.5);
/// assert!(f >= 0.1 && f < 0.5);
/// ```
pub fn gen_range<T, R>(&mut self, range: R) -> T
where
T: SampleUniform,
R: SampleRange<T>,
{
self.sim_state.borrow_mut().gen_range(range)
}
/// Returns a random value from the specified distribution
/// using the simulation-wide random number generator.
pub fn sample_from_distribution<T, Dist: Distribution<T>>(&mut self, dist: &Dist) -> T {
self.sim_state.borrow_mut().sample_from_distribution(dist)
}
/// Returns a random alphanumeric string of specified length
/// using the simulation-wide random number generator.
pub fn random_string(&mut self, len: usize) -> String {
self.sim_state.borrow_mut().random_string(len)
}
/// Returns the total number of created events.
///
/// Note that cancelled events are also counted here.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::Simulation;
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp_ctx = sim.create_context("comp");
/// assert_eq!(sim.time(), 0.0);
/// comp_ctx.emit_self(SomeEvent {}, 1.0);
/// comp_ctx.emit_self(SomeEvent {}, 2.0);
/// comp_ctx.emit_self(SomeEvent {}, 3.5);
/// assert_eq!(sim.event_count(), 3);
/// ```
pub fn event_count(&self) -> u64 {
self.sim_state.borrow().event_count()
}
/// Cancels events that satisfy the given predicate function.
///
/// Note that already processed events cannot be cancelled.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::{Event, Simulation, SimulationContext};
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp1_ctx = sim.create_context("comp1");
/// let mut comp2_ctx = sim.create_context("comp2");
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 1.0);
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 2.0);
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 3.0);
/// sim.cancel_events(|e| e.id < 2);
/// sim.step();
/// assert_eq!(sim.time(), 3.0);
/// ```
pub fn cancel_events<F>(&mut self, pred: F)
where
F: Fn(&Event) -> bool,
{
self.sim_state.borrow_mut().cancel_events(pred);
}
/// Cancels events that satisfy the given predicate function and returns them.
///
/// Note that already processed events cannot be cancelled.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::{Event, Simulation, SimulationContext};
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut comp1_ctx = sim.create_context("comp1");
/// let mut comp2_ctx = sim.create_context("comp2");
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 1.0);
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 2.0);
/// comp1_ctx.emit(SomeEvent {}, comp2_ctx.id(), 3.0);
/// let cancelled = sim.cancel_and_get_events(|e| e.id < 2);
/// assert_eq!(cancelled.len(), 2);
/// sim.step();
/// assert_eq!(sim.time(), 3.0);
/// ```
pub fn cancel_and_get_events<F>(&mut self, pred: F) -> Vec<Event>
where
F: Fn(&Event) -> bool,
{
self.sim_state.borrow_mut().cancel_and_get_events(pred)
}
/// Returns a copy of pending events sorted by time.
///
/// Currently used for model checking in dslab-mp.
///
/// # Examples
///
/// ```rust
/// use serde::Serialize;
/// use simcore::{Event, Simulation, SimulationContext};
///
/// #[derive(Clone, Serialize)]
/// struct SomeEvent {
/// }
///
/// let mut sim = Simulation::new(123);
/// let mut ctx1 = sim.create_context("comp1");
/// let mut ctx2 = sim.create_context("comp2");
/// let event1 = ctx1.emit(SomeEvent {}, ctx2.id(), 1.0);
/// let event2 = ctx2.emit(SomeEvent {}, ctx1.id(), 1.0);
/// let event3 = ctx1.emit(SomeEvent {}, ctx2.id(), 2.0);
/// let events = sim.dump_events();
/// assert_eq!(events.len(), 3);
/// assert_eq!((events[0].id, events[0].time), (event1, 1.0));
/// assert_eq!((events[1].id, events[1].time), (event2, 1.0));
/// assert_eq!((events[2].id, events[2].time), (event3, 2.0));
/// ```
pub fn dump_events(&self) -> Vec<Event> {
self.sim_state.borrow().dump_events()
}
}