-
Notifications
You must be signed in to change notification settings - Fork 10
/
Environment.kt
499 lines (378 loc) · 14.9 KB
/
Environment.kt
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
package org.kalasim
import com.github.holgerbrandl.jsonbuilder.json
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import org.apache.commons.math3.random.JDKRandomGenerator
import org.apache.commons.math3.random.RandomGenerator
import org.json.JSONObject
import org.kalasim.ComponentState.*
import org.kalasim.Defaults.DEFAULT_SEED
import org.kalasim.Priority.Companion.NORMAL
import org.kalasim.analysis.ConsoleTraceLogger
import org.kalasim.analysis.InteractionEvent
import org.kalasim.misc.*
import org.kalasim.monitors.MetricTimeline
import org.koin.core.Koin
import org.koin.core.definition.Definition
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import java.util.*
internal const val MAIN = "main"
typealias KoinModule = org.koin.core.module.Module
//internal class EnvBuildContext : KoinModule() {
// var enableConsoleLogger: Boolean = true
//}
// --> not possible because Module is not open
// https://github.com/InsertKoinIO/koin/issues/801
fun configureEnvironment(
enableConsoleLogger: Boolean = false,
builder: KoinModule.() -> Unit
): Environment =
declareDependencies(builder).createSimulation(enableConsoleLogger) {}
fun declareDependencies(
builder: KoinModule.() -> Unit
): KoinModule = module(createdAtStart = true) { builder() }
fun KoinModule.createSimulation(
enableConsoleLogger: Boolean = false,
enableTickMetrics: Boolean = false,
useCustomKoin: Boolean = false,
randomSeed: Int = DEFAULT_SEED,
builder: Environment.() -> Unit
): Environment = createSimulation(
enableConsoleLogger = enableConsoleLogger,
enableTickMetrics = enableTickMetrics,
dependencies = this,
useCustomKoin = useCustomKoin,
randomSeed = randomSeed,
builder = builder
)
fun createSimulation(
enableConsoleLogger: Boolean = false,
enableTickMetrics: Boolean = false,
dependencies: KoinModule? = null,
useCustomKoin: Boolean = false,
randomSeed: Int = DEFAULT_SEED,
builder: Environment.() -> Unit
): Environment =
Environment(
enableConsoleLogger = enableConsoleLogger,
enableTickMetrics = enableTickMetrics,
dependencies = dependencies,
randomSeed = randomSeed,
koin = if(useCustomKoin) koinApplication { }.koin else null
).apply(builder)
//fun Environment.createSimulation(builder: Environment.() -> Unit) {
// this.apply(builder)
//}
object Defaults {
const val DEFAULT_SEED = 42
}
internal class MainComponent(koin: Koin) : Component(MAIN, koin = koin) {
override fun process() = sequence<Component> {}
}
open class Environment(
enableConsoleLogger: Boolean = false,
enableTickMetrics: Boolean = false,
dependencies: KoinModule? = null,
koin: Koin? = null,
randomSeed: Int = DEFAULT_SEED,
startTime: TickTime = TickTime(0.0)
) : SimContext {
private var running: Boolean = false
val rg: RandomGenerator = JDKRandomGenerator(randomSeed)
val random: kotlin.random.Random = kotlin.random.Random(randomSeed.toLong())
internal val nameCache = mutableMapOf<String, Int>()
// As discussed in https://github.com/holgerbrandl/kalasim/issues/8, we could alternatively use a fibonacci
// heap for better performance
private val eventQueue = PriorityQueue<QueueElement>()
// TODO Fix order or add introspection API https://stackoverflow.com/questions/8129122/how-to-iterate-over-a-priorityqueue
/** Unmodifiable view on `eventQueue`. */
val queue: List<Component>
get() = eventQueue.map { it.component }
private val eventListeners = listOf<EventListener>().toMutableList()
val trackingPolicyFactory = TrackingPolicyFactory()
// val traceFilters = mutableListOf<EventFilter>()
init {
// traceFilters.add(EventFilter {
// if(it !is InteractionEvent) return@EventFilter true
//
// val action = it.renderAction()
//
// !(action.contains("entering requesters")
// || action.contains("entering claimers")
// || action.contains("removed from requesters")
// || action.contains("removed from claimers"))
// })
}
var now = startTime
internal set // todo since this is just used for testing, we could also maybe simply use run(newTime)
@Deprecated(message = "Use property instead. To be removed in v0.9", replaceWith = ReplaceWith("now"))
fun now() = now
// val foo = 3.ticks
// val foo = 3.simtime
/** Allows to transform ticks to real world time moements (represented by `java.time.Instant`) */
override var tickTransform: TickTransform? = null
var curComponent: Component? = null
private set
val main: Component
@Suppress("PropertyName")
internal val _koin: Koin
final override fun getKoin(): Koin = _koin
//redeclare to simplify imports
/** Resolves a dependency in the simulation. Dependencies can be disambiguated by using a qualifier.*/
inline fun <reified T : Any> get(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T =
getKoin().get(qualifier, parameters)
init {
// start console logger
// addTraceListener { print(it) }
if(enableConsoleLogger) {
addEventListener(ConsoleTraceLogger())
}
_koin = koin ?: run {
// KalasimContext.stopKoin()
//https://medium.com/koin-developers/ready-for-koin-2-0-2722ab59cac3
// https://github.com/InsertKoinIO/koin/issues/972
// CustomContext.startKoin(koinContext = CustomContext()) { modules(module { single { this@Environment } }) }
DependencyContext.startKoin()
}
// require(koins.createAtStart) {
// "createAtStart must be enabled by convention to instantiate injected components before starting the simulation"
// }
getKoin().loadModules(listOf(module {
single {
this@Environment
}
}))
main = MainComponent(getKoin())
// declare dependencies
if(dependencies != null) {
// val deps = dependencies ?: (module(createdAtStart = true) { })
getKoin().loadModules(listOf(dependencies))
// KoinContextHandler.get()._scopeRegistry.rootScope.createEagerInstances()
// startKoin { modules(koins) }
}
// curComponent = main
}
private val _tm: TickMetrics? = if(enableTickMetrics) TickMetrics(koin = koin) else null
val tickMetrics: MetricTimeline
get() {
require(_tm != null) { "Use enableTickMetrics=true to enable tick metrics" }
return _tm.timeline
}
// private var endOnEmptyEventlist = false
private val standBy = mutableListOf<Component>()
private val pendingStandBy = mutableListOf<Component>()
// fun build(vararg compoennts: Component) = components.forEach { this + it }
// seesm unused. To be deleted in v0.9
// fun build(builder: (Environment.() -> Unit)): Environment {
// builder(this)
// return (this)
// }
/**
* Start execution of the simulation
*
* If neither `until` nor `ticks` are specified, the main component will be reactivated at
* the time there are no more events on the event-list, i.e. possibly not at Double.MAX_VALUE. If you want
* to keep a simulation running simply call `run(Double.MAX_VALUE)`.
*
* @param duration Time to run
* @param priority If a component has the same time on the event list, the main component is sorted according to
* the priority. An event with a higher priority will be scheduled first.
*/
fun run(
duration: Ticks? = null,
priority: Priority = NORMAL,
urgent: Boolean = false
) = run(duration?.value, null, priority, urgent)
/**
* Start execution of the simulation
*
* If neither `until` nor `ticks` are specified, the main component will be reactivated at
* the time there are no more events on the event-list, i.e. possibly not at Double.MAX_VALUE. If you want
* to keep a simulation running simply call `run(Double.MAX_VALUE)`.
*
* @param duration Time to run
* @param until Absolute tick-time until the which the simulation should run
* @param priority If a component has the same time on the event list, the main component is sorted according to
* the priority. An event with a higher priority will be scheduled first.
*/
fun run(
duration: Number? = null,
until: TickTime? = null,
priority: Priority = NORMAL,
urgent: Boolean = false
): Environment {
// also see https://simpy.readthedocs.io/en/latest/topical_guides/environments.html
if(duration == null && until == null) {
// endOnEmptyEventlist = true
} else {
val scheduledTime = calcScheduleTime(until, duration)
main.reschedule(scheduledTime, priority, urgent, null, "running", SCHEDULED)
}
// restore dependency context
DependencyContext.setKoin(_koin)
running = true
while(running) {
step()
}
return (this)
}
/** Executes the next step of the future event list. */
private fun step() {
pendingStandBy.removeIf { it.componentState != STANDBY }
pendingStandBy.removeFirstOrNull()?.let {
setCurrent(it) // , "standby" --> removed field in v0.8
it.callProcess()
return
}
// move previously standby to pending-standby
pendingStandBy += standBy
standBy.clear()
val (time, component) = if(eventQueue.isNotEmpty()) {
val (c, time, _, _) = eventQueue.poll()
time to c
} else {
publishEvent(InteractionEvent(now, curComponent, null, null, "run end; no events left"))
val t =
// if (endOnEmptyEventlist) {
// publishEvent(InteractionEvent(now, curComponent, null, null, "run end; no events left"))
now
// } else {
// TickTime(Double.MAX_VALUE)
// }
t to main
}
require(time >= now) { "clock must not run backwards" }
now = time
setCurrent(component)
if(component == main) {
running = false
return
}
component.checkFail()
component.callProcess()
}
private fun setCurrent(c: Component) {
c.componentState = CURRENT
c.scheduledTime = null
curComponent = c
// c.log(c, info)
}
//
// Events
//
inline fun <reified T : Event> addAsyncEventListener(
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
crossinline block: (T) -> Unit
) = AsyncEventListener(scope).also { listener ->
listener.start(block)
addEventListener(listener)
}
inline fun <reified T : Event> addEventListener(
crossinline block: (T) -> Unit
) = addEventListener listener@{
if(it !is T) return@listener
block(it)
}
fun addEventListener(listener: EventListener) = eventListeners.add(listener)
@Suppress("unused")
fun removeEventListener(tr: EventListener) = eventListeners.remove(tr)
internal fun publishEvent(event: Event) {
eventListeners.forEach {
it.consume(event)
}
}
//
// Misc
//
internal fun addStandBy(component: Component) {
standBy.add(component)
}
fun remove(c: Component) {
unschedule(c)
// TODO what is happening here, can we simplify that?
if(c.componentState == STANDBY) {
standBy.remove(c)
pendingStandBy.remove(c)
}
}
internal fun unschedule(c: Component) {
val queueElem = eventQueue.firstOrNull {
it.component == c
}
if(queueElem != null) {
eventQueue.remove(queueElem)
}
}
private var queueCounter: Int = 0
internal fun push(component: Component, scheduledTime: TickTime, priority: Priority, urgent: Boolean) {
queueCounter++
// https://bezkoder.com/kotlin-priority-queue/
// Remove an element from the Priority Queue => Dequeue the least element. The front of the Priority Queue
// contains the least element according to the ordering, and the rear contains the greatest element.
eventQueue.add(QueueElement(component, scheduledTime, Priority(-priority.value), queueCounter, urgent))
// consistency checks
if(ASSERT_MODE == AssertMode.FULL) {
require(queue.none(Component::isPassive)) { "passive component must not be in event queue" }
// ensure that no scheduled components have the same name
require(queue.map { it.name }.distinct().size == queue.size) { "components must not have the same name" }
}
}
fun toJson(): JSONObject = json {
"now" to now
"queue" to queue.toList().map { it.name }.toTypedArray()
}
override fun toString(): String {
return toJson().toString(JSON_INDENT)
}
fun log(msg: String) = main.log(msg)
}
data class QueueElement(
val component: Component,
val time: TickTime,
val priority: Priority,
val queueCounter: Int,
val urgent: Boolean
) :
Comparable<QueueElement> {
//TODO clarify if we need/want to also support urgent
override fun compareTo(other: QueueElement): Int =
compareValuesBy(this, other, { it.time.value }, { it.priority.value }, { it.queueCounter })
// val heapSeq = if (urgent) -queueCounter else queueCounter
override fun toString(): String {
// return "${component.javaClass.simpleName}(${component.name}, $time, $priority, $seq)"
return "${component.javaClass.simpleName}(${component.name}, $time, $priority, $queueCounter) : ${component.componentState}"
}
}
fun Environment.calcScheduleTime(until: TickTime?, duration: Number?): TickTime {
return (until?.value to duration?.toDouble()).let { (till, duration) ->
if(till == null) {
require(duration != null) { "neither duration nor till specified" }
now.value + duration
} else {
require(duration == null) { "both duration and till specified" }
till
}
}.let { TickTime(it) }
}
inline fun <reified T> KoinModule.add(
qualifier: Qualifier? = null,
noinline definition: Definition<T>
) {
single(qualifier = qualifier, createdAtStart = true, definition = definition)
}
inline fun <reified T> Environment.dependency(qualifier: Qualifier? = null, builder: Environment.() -> T): T {
val something = builder(this)
getKoin().loadModules(listOf(
module(createdAtStart = true) {
add(qualifier) { something }
}
))
return something
}