odem-rs-core 0.3.0

Core components of the odem-rs simulation framework
Documentation
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
//! This module is about preparing the simulation library for the execution of
//! a simulation model, defining traits and a default configuration for
//! specifying various data types and constants.
//!
//! Our library abstracts from concrete types and initial values for model time,
//! priority, and shared data, which requires the user to specify these
//! properties before any simulation model may be executed. To make this as
//! painless as possible, we employ the builder-pattern to construct a
//! configuration that is automatically passed down to the various constructors
//! for the model elements.
//!
//! ## `Config` Trait
//!
//! The [`Config`] trait is used to configure the simulation model and includes
//! the following associated types:
//!
//! - `Time`: Type for the model time. It is required to be copyable, partially
//!   ordered, and have a debug representation. It cannot be self-referential.
//! - `Rank`: Type used to prioritize pucks scheduled at the same model time,
//!   required to be copyable, totally ordered, and have a debug representation.
//!   It can also not be self-referential.
//! - `Data`: User-defined globally shared data type, intended for statistical
//!   aggregators, shared random number generators, or any data accessible from
//!   anywhere in the simulation model.
//! - `Plan`: Type of the continuation calendar, implementing the `Scheduler`
//!   trait for this configuration.
//!
//! Additionally, the `Config` trait includes methods to retrieve default values
//! for simulation start time, default rank for agents, and a reference to
//! globally shared data.
//!
//! ## `Time` Trait
//!
//! The [`Time`] trait encapsulates traits needed for the model-time type in a
//! configuration, including being `Unpin`, `PartialOrd`, `Copy`, and `Debug`.
//! It provides a default implementation for displaying time in a human-readable
//! format.
//!
//! ## `Rank` Trait
//!
//! The [`Rank`] trait encapsulates traits needed for the rank-type in a
//! configuration, including being `Unpin`, `Ord`, `Copy`, and `Debug`.
//! A blanket implementation is provided for all types meeting those criteria.
//!
//! ## Default Configuration
//!
//! The empty tuple `()` implements the simulation configuration used by
//! default. It uses `f64` for the model time with an initial value of `0.0`, an
//! empty tuple for rank, and no additional data.

use crate::calendar::{DefaultPlan, Scheduler};
use core::{any::Any, fmt, marker::PhantomData};

#[doc(inline)]
pub use odem_rs_meta::Config;

/* ************************* Configuration Traits *************************** */

/// Trait used to configure the various data types and constants used in a
/// simulation model.
pub trait Config: 'static {
	/// The type used for the model time.
	type Time: Time;
	/// The type used to prioritize pucks that are scheduled at the same
	/// model time.
	type Rank: Rank;
	/// User-defined, globally shared data type.
	///
	/// It is intended to be used for injecting statistical aggregators and
	/// shared random number generators but can be used whenever you would
	/// like to access some data from anywhere in the simulation model.
	/// Only one copy of this data exists during a simulation-run.
	type Data: Any;
	/// The type of the continuation calendar which has to implement the
	/// `Scheduler` trait for this configuration.
	///
	/// # Note
	///
	/// The `Scheduler`-trait is not yet part of the public API due to
	/// instability. The only valid choice at this point is [`DefaultPlan`].
	type Plan: Scheduler<Config = Self>;

	/// Returns the start or default time of the simulation.
	fn default_time(&self) -> Self::Time;

	/// Returns the default rank for agents in the simulation.
	fn default_rank(&self) -> Self::Rank;

	/// Returns a reference to the globally shared data during a simulation run.
	fn global_data(&self) -> &Self::Data;
}

/// Helper trait that encapsulates all the traits needed for the model-time
/// type of [configuration](Config).
pub trait Time: Unpin + PartialOrd + Copy + fmt::Debug + 'static {
	/// Formats the time in human-readable format.
	///
	/// Uses the debug implementation by default but can be overridden with
	/// a more suitable representation.
	fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(&self, f)
	}

	/// Displays the time in human-readable format using the [`format`]-method.
	///
	/// [`format`]: Self::format
	fn display(self) -> DisplayTime<Self> {
		DisplayTime(self)
	}
}

/// Helper trait that encapsulates all the traits needed for the rank-type
/// of a [configuration](Config).
pub trait Rank: Unpin + Ord + Copy + fmt::Debug + 'static {}

// blanket-implementation for all the right types
impl<R> Rank for R where R: Unpin + Ord + Copy + fmt::Debug + 'static {}

/* **************************************************** Default Configuration */

impl Config for () {
	type Time = f64;
	type Rank = ();
	type Data = ();
	type Plan = DefaultPlan<()>;

	fn default_time(&self) -> Self::Time {
		0.0
	}

	fn default_rank(&self) -> Self::Rank {}

	fn global_data(&self) -> &Self::Data {
		self
	}
}

/* ****************************************************** Built-In Time Types */

/// Implements [`Display`] by referring to [`Time::format`].
///
/// [`Display`]: fmt::Display
pub struct DisplayTime<T>(pub T);

impl<T: Time> fmt::Debug for DisplayTime<T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.format(f)
	}
}

impl<T: Time> fmt::Display for DisplayTime<T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.format(f)
	}
}

macro_rules! impl_signed_integral_time {
	($($T:ty),* $(,)?) => {$(
		impl Time for $T {
			fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				use fmt::Display;
				if f.alternate() {
					Display::fmt(&ClockTime::seconds(*self as isize), f)
				} else {
					Display::fmt(self, f)
				}
			}
		}
	)*};
}

impl_signed_integral_time!(i8, i16, i32, i64, i128, isize);

macro_rules! impl_unsigned_integral_time {
	($($T:ty),* $(,)?) => {$(
		impl Time for $T {
			fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				use fmt::Display;
				if f.alternate() {
					Display::fmt(&Seconds(*self as usize), f)
				} else {
					Display::fmt(self, f)
				}
			}
		}
	)*};
}

impl_unsigned_integral_time!(u8, u16, u32, u64, u128, usize);

macro_rules! impl_floating_time {
	($($T:ty),* $(,)?) => {$(
		impl Time for $T {
			fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				use fmt::Display;
				if f.alternate() {
					match f.precision() {
						None | Some(0) => Display::fmt(&ClockTime::seconds(*self as isize), f),
						Some(1) => Display::fmt(&ClockTime::milliseconds((*self * 1e+3) as isize), f),
						Some(2) => Display::fmt(&ClockTime::microseconds((*self * 1e+6) as isize), f),
						_ => Display::fmt(&ClockTime::nanoseconds((*self * 1e+9) as isize), f),
					}
				} else {
					Display::fmt(self, f)
				}
			}
		}
	)*};
}

impl_floating_time!(f32, f64);

impl Time for () {}

/* **************************************************** Normalized Model Time */

/// Helper for displaying normalized model-time in digital-clock-format.
#[derive(Copy, Clone)]
pub struct ClockTime<U> {
	/// The value-part of the time.
	value: isize,
	/// Indicator of the unit of time.
	_unit: PhantomData<U>,
}

impl ClockTime<()> {
	/// Constructs a [displayable](fmt::Display) clock time in nanoseconds.
	pub const fn nanoseconds(value: isize) -> impl fmt::Display {
		ClockTime::<Nanoseconds> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in microseconds.
	pub const fn microseconds(value: isize) -> impl fmt::Display {
		ClockTime::<Microseconds> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in milliseconds.
	pub const fn milliseconds(value: isize) -> impl fmt::Display {
		ClockTime::<Milliseconds> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in seconds.
	pub const fn seconds(value: isize) -> impl fmt::Display {
		ClockTime::<Seconds> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in minutes.
	pub const fn minutes(value: isize) -> impl fmt::Display {
		ClockTime::<Minutes> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in hours.
	pub const fn hours(value: isize) -> impl fmt::Display {
		ClockTime::<Hours> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in days.
	pub const fn days(value: isize) -> impl fmt::Display {
		ClockTime::<Days> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in years.
	pub const fn years(value: isize) -> impl fmt::Display {
		ClockTime::<Years> {
			value,
			_unit: PhantomData,
		}
	}
}

impl<U> ClockTime<U> {
	/// Private method that prints the time's sign.
	fn write_sign(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if self.value < 0 {
			write!(f, "-")
		} else if f.sign_plus() {
			write!(f, "+")
		} else {
			Ok(())
		}
	}
}

impl fmt::Display for ClockTime<Years> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Years(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Days> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Days(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Hours> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Hours(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Minutes> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Minutes(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Seconds> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Seconds(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Milliseconds> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Milliseconds(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Microseconds> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Microseconds(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Nanoseconds> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Nanoseconds(self.value.unsigned_abs()).fmt(f)
	}
}

/// Marks the inner quantity as 'in nanoseconds', i.e., 10^(-9) seconds.
struct Nanoseconds(usize);
/// Marks the inner quantity as 'in microseconds', i.e., 10^(-6) seconds.
struct Microseconds(usize);
/// Marks the inner quantity as 'in milliseconds', i.e., 10^(-3) seconds.
struct Milliseconds(usize);
/// Marks the inner quantity as 'in seconds'.
struct Seconds(usize);
/// Marks the inner quantity as 'in minutes'.
struct Minutes(usize);
/// Marks the inner quantity as 'in hours'.
struct Hours(usize);
/// Marks the inner quantity as 'in days'.
struct Days(usize);
/// Marks the inner quantity as 'in years'.
struct Years(usize);

impl fmt::Display for Years {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if self.0 != 0 || f.sign_aware_zero_pad() {
			write!(f, "{}a", self.0)
		} else {
			f.write_str("  ")
		}
	}
}

impl fmt::Display for Days {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;
		let mut p;

		if {
			p = quantity >= 365;
			p
		} || f.width().map(|w| w > 5).unwrap_or(false)
		{
			Years(quantity / 365).fmt(f)?;
			f.write_str(" ")?;
		}

		if quantity >= 7 || f.width().map(|w| w > 4).unwrap_or(false) {
			quantity %= 365;

			p |= quantity >= 7;
			if p || f.sign_aware_zero_pad() {
				write!(f, "{:2}w ", quantity / 7)?;
			} else {
				f.write_str("    ")?;
			}

			quantity %= 7;
		}

		if p || quantity != 0 || f.sign_aware_zero_pad() {
			write!(f, "{quantity}d")
		} else {
			f.write_str("  ")
		}
	}
}

impl fmt::Display for Hours {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;
		let p;

		if {
			p = quantity >= 24;
			p
		} || f.width().map(|w| w > 3).unwrap_or(false)
		{
			Days(quantity / 24).fmt(f)?;
			quantity %= 24;
			f.write_str(" ")?;
		}

		if p || quantity != 0 || f.sign_aware_zero_pad() {
			write!(f, "{quantity:02}h")
		} else {
			f.write_str("   ")
		}
	}
}

impl fmt::Display for Minutes {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;
		let p;

		if {
			p = quantity >= 60;
			p
		} || f.width().map(|w| w > 2).unwrap_or(false)
		{
			Hours(quantity / 60).fmt(f)?;
			quantity %= 60;
			f.write_str(" ")?;
		}

		if p || quantity != 0 || f.sign_aware_zero_pad() {
			write!(f, "{quantity:02}m")
		} else {
			f.write_str("   ")
		}
	}
}

impl fmt::Display for Seconds {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;
		let p;

		if {
			p = quantity >= 60;
			p
		} || f.width().map(|w| w > 1).unwrap_or(false)
		{
			Minutes(quantity / 60).fmt(f)?;
			quantity %= 60;
			f.write_str(" ")?;
		}

		if p || quantity != 0 || f.sign_aware_zero_pad() {
			write!(f, "{quantity:02}s")
		} else {
			f.write_str(" 0s")
		}
	}
}

impl fmt::Display for Milliseconds {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		Seconds(quantity / 1000).fmt(f)?;
		quantity %= 1000;
		write!(f, " {quantity:03}ms")
	}
}

impl fmt::Display for Microseconds {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		Milliseconds(quantity / 1000).fmt(f)?;
		quantity %= 1000;
		write!(f, " {quantity:03}µs")
	}
}

impl fmt::Display for Nanoseconds {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		Microseconds(quantity / 1000).fmt(f)?;
		quantity %= 1000;
		write!(f, " {quantity:03}ns")
	}
}

/* ****************************************************** Optional Time Types */

// support si time quantities as model time
#[cfg(feature = "uom")]
#[cfg_attr(docsrs, doc(cfg(feature = "uom")))]
mod uom {
	use super::{ClockTime, Time};
	use core::fmt;
	use uom::{
		Conversion,
		fmt::DisplayStyle,
		num_traits::{AsPrimitive, Num},
		si::{Units, time},
	};

	impl<U, V> Time for time::Time<U, V>
	where
		U: Units<V> + ?Sized + 'static,
		V: Conversion<V>
			+ Num
			+ PartialOrd
			+ PartialEq
			+ AsPrimitive<isize>
			+ fmt::Debug
			+ fmt::Display
			+ Unpin
			+ 'static,
		time::second: Conversion<V, T = V::T>,
		time::millisecond: Conversion<V, T = V::T>,
		time::microsecond: Conversion<V, T = V::T>,
		time::nanosecond: Conversion<V, T = V::T>,
	{
		fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
			use fmt::Display;

			if f.alternate() {
				// switch to a wall-clock-format for the alternative format
				match f.precision() {
					None | Some(0) => ClockTime::seconds(self.get::<time::second>().as_()).fmt(f),
					Some(1) => {
						ClockTime::milliseconds(self.get::<time::millisecond>().as_()).fmt(f)
					}
					Some(2) => {
						ClockTime::microseconds(self.get::<time::microsecond>().as_()).fmt(f)
					}
					_ => ClockTime::nanoseconds(self.get::<time::nanosecond>().as_()).fmt(f),
				}
			} else {
				// use the abbreviated format by default
				self.into_format_args(time::second, DisplayStyle::Abbreviation)
					.fmt(f)
			}
		}
	}
}