Skip to content

Commit

Permalink
reformatted sources
Browse files Browse the repository at this point in the history
  • Loading branch information
holgerbrandl committed Oct 29, 2023
1 parent 2c10014 commit 2b7b67c
Show file tree
Hide file tree
Showing 94 changed files with 374 additions and 359 deletions.
1 change: 1 addition & 0 deletions docs/userguide/docs/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Breaking API Changes

* Most importantly we have migrated the API to use `org.kalasim.SimTime` to track simulation. `SimTime` is a simple typealias for `kotlinx.datetime.Instant`, effectively giving users the full flexibility of using a well designed and established date-time concept. `org.kalasim.TickTime` is still available for backward compatibility reasons, but is opt-in or required to subclass `TickedComponent`.
* Simplified the configurability for [tracking](advanced.md#continuous-simulation) of entity timelines and statistics. It's now more direct via constructor parameters in addition to environment defaults
* [#65](https://github.com/holgerbrandl/kalasim/issues/65) Improved arithmetics of [metric timelines](monitors.md#value-monitors)

Minor improvements
Expand Down
16 changes: 10 additions & 6 deletions src/main/kotlin/org/kalasim/ClockSync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ class ClockSync(
val syncsPerTick: Number = 1,
val maxDelay: Duration? = null,
koin: Koin = DependencyContext.get()
) : Component(trackingConfig = ComponentTrackingConfig(logCreation = false, logStateChangeEvents = false), koin = koin) {
) : Component(
trackingConfig = ComponentTrackingConfig(logCreation = false, logStateChangeEvents = false),
koin = koin
) {

var tickDuration: Duration = tickDuration
set(value) {
Expand All @@ -32,14 +35,14 @@ class ClockSync(
}


val holdTime = (1.0 / syncsPerTick.toDouble()).toDuration()
val holdTime = (1.0 / syncsPerTick.toDouble()).toDuration()

private var syncStartWall: Instant? = null
private var syncStartSim: SimTime? = null

override fun process() = sequence {

while (true) {
while(true) {
//wait until we have caught up with wall clock
val tickDurationMs = tickDuration.inWholeMilliseconds.toDouble()

Expand All @@ -50,7 +53,8 @@ class ClockSync(


// val simTimeSinceSyncStart = ((env.now - syncStartTicks!!) * tickDurationMs).roundToLong().milliseconds
val simTimeSinceSyncStart = ((env.now - syncStartSim!!).asTicks() * tickDurationMs).roundToLong().milliseconds
val simTimeSinceSyncStart =
((env.now - syncStartSim!!).asTicks() * tickDurationMs).roundToLong().milliseconds
val wallTimeSinceSyncStart = now - syncStartWall!!

val sleepDuration = simTimeSinceSyncStart - wallTimeSinceSyncStart
Expand All @@ -59,7 +63,7 @@ class ClockSync(
// println("sim $simTimeSinceSyncStart wall $wallTimeSinceSyncStart; Resync by sleep for ${sleepDuration}ms")
// }

if (maxDelay != null && sleepDuration > maxDelay) {
if(maxDelay != null && sleepDuration > maxDelay) {
throw ClockOverloadException(
env.now,
"Maximum delay between wall clock and simulation clock exceeded at time ${env.now}. " +
Expand All @@ -68,7 +72,7 @@ class ClockSync(
}

// simulation is too fast if value is larger
if (sleepDuration > Duration.ZERO) {
if(sleepDuration > Duration.ZERO) {
// wait accordingly to let wall clock catch up
Thread.sleep(sleepDuration.inWholeMilliseconds)
}
Expand Down
10 changes: 4 additions & 6 deletions src/main/kotlin/org/kalasim/Component.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ open class TickedComponent(
process: ProcessPointer? = null,
trackingConfig: ComponentTrackingConfig = ComponentTrackingConfig(),
koin: Koin = DependencyContext.get(),
) : Component(name,at, delay, priority, process, koin, trackingConfig){
) : Component(name, at, delay, priority, process, koin, trackingConfig) {


/**
Expand Down Expand Up @@ -189,7 +189,7 @@ open class Component(

private val waits = mutableListOf<StateRequest<*>>()

init{
init {
}

/** Will be `true` if a component's request was not honored in time, or a wait predicate was not met before it timed outs. */
Expand Down Expand Up @@ -273,7 +273,7 @@ open class Component(
}
}

val tickDelay = delay?: Duration.ZERO
val tickDelay = delay ?: Duration.ZERO

// if (at != null || (process != null && (process.name != "process" || overriddenProcess))) {
@Suppress("LeakingThis")
Expand Down Expand Up @@ -1337,8 +1337,6 @@ open class Component(
// @Deprecated("Use Duration instead of Ticks")




/**
* Hold the component.
*
Expand Down Expand Up @@ -1746,7 +1744,7 @@ open class Component(
}


suspend fun SequenceScope<Component>.join(components: List<Component>) = sequence<Component> {
suspend fun SequenceScope<Component>.join(components: List<Component>) = sequence<Component> {
wait(*components.map { it.componentState() turns PASSIVE }.toTypedArray())
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/org/kalasim/ComponentGenerator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package org.kalasim

import org.apache.commons.math3.distribution.RealDistribution
import org.kalasim.analysis.snapshot.ComponentGeneratorSnapshot
import org.kalasim.misc.DependencyContext
import org.kalasim.misc.AmbiguousDuration
import org.kalasim.misc.DependencyContext
import org.koin.core.Koin
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/org/kalasim/Distributions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import org.kalasim.misc.asCMPairList
import java.lang.Double.min
import java.util.*
import kotlin.math.max
import kotlin.time.*
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit

/**
* Distribution support API with controlled randomization via `env.rg`
Expand Down Expand Up @@ -205,7 +206,6 @@ fun SimContext.discreteUniform(range: IntRange) = discreteUniform(range.first, r
fun SimContext.discreteUniform(lower: Int, upper: Int) = UniformIntegerDistribution(env.rg, lower, upper)



//
// Enumerations
//
Expand Down
7 changes: 3 additions & 4 deletions src/main/kotlin/org/kalasim/DurationExensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ public inline val Long.day get() = toDuration(DurationUnit.DAYS)

/** The value of this duration expressed as a Double number of days. */
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Duration.inDays: Double
val Duration.inDays: Double
get() = toDouble(DurationUnit.DAYS)

/** The value of this duration expressed as a Double number of hours. */
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Duration.inHours: Double
val Duration.inHours: Double
get() = toDouble(DurationUnit.HOURS)

/** The value of this duration expressed as a Double number of minutes. */
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Duration.inMinutes: Double
val Duration.inMinutes: Double
get() = toDouble(DurationUnit.MINUTES)

/** The value of this duration expressed as a Double number of seconds. */
Expand All @@ -39,5 +39,4 @@ internal val Duration.inSeconds
get() = toDouble(DurationUnit.SECONDS)



public inline val Int.weeks get() = times(7).toDuration(DurationUnit.DAYS)
5 changes: 1 addition & 4 deletions src/main/kotlin/org/kalasim/Environment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,6 @@ open class Environment(
get() = now.toTickTime()




@Suppress("LeakingThis")
// That's a pointless self-recursion, but it allows to simplify support API (tick-transform, distributions, etc.)
/** Self-pointer. Pointless from a user-perspective, but helpful to build the kalasim APIs more efficiently.*/
Expand Down Expand Up @@ -204,7 +202,7 @@ open class Environment(
qualifier: String, noinline parameters: ParametersDefinition? = null,
): T = getKoin().get(named(qualifier), parameters)

val entityTrackingDefaults = SimEntityTrackingDefaults()
val entityTrackingDefaults = SimEntityTrackingDefaults()

init {

Expand All @@ -231,7 +229,6 @@ open class Environment(
// }



// self register the environment
getKoin().loadModules(listOf(module {
single {
Expand Down
3 changes: 2 additions & 1 deletion src/main/kotlin/org/kalasim/Resource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package org.kalasim

import com.github.holgerbrandl.jsonbuilder.json
import org.jetbrains.kotlinx.dataframe.api.*
import org.kalasim.analysis.*
import org.kalasim.analysis.EntityCreatedEvent
import org.kalasim.analysis.ResourceActivityEvent
import org.kalasim.analysis.snapshot.ResourceSnapshot
import org.kalasim.misc.*
import org.kalasim.monitors.*
Expand Down
7 changes: 3 additions & 4 deletions src/main/kotlin/org/kalasim/SimContext.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.kalasim

import org.koin.core.component.KoinComponent
import kotlinx.datetime.Instant
import org.koin.core.component.KoinComponent
import kotlin.time.Duration

/**
Expand Down Expand Up @@ -32,14 +32,13 @@ interface SimContext : KoinComponent {

/** Transforms a simulation time (typically `now`) to the corresponding wall time. */
@Deprecated("no longer needed as sim-time is also expressed as kotlinx.datetimex.Instant starting in v0.12")
fun TickTime.toWallTime(): Instant
{
fun TickTime.toWallTime(): Instant {
require(env.startDate != null) { MISSING_TICK_TRAFO_ERROR }
return env.tick2wallTime(this)
}


fun Number.toDuration() : Duration = env.tickTransform.ticks2Duration(this.toDouble())
fun Number.toDuration(): Duration = env.tickTransform.ticks2Duration(this.toDouble())


// would be nice but makes it harder to use TickTime outside of env
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/org/kalasim/SimulationEntity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ abstract class SimulationEntity(name: String? = null, val simKoin: Koin = Depend
// private set

@Deprecated("no longer needed as sim-time is also expressed as kotlinx.datetimex.Instant starting in v0.12")
val nowWT : Instant = now
val nowWT: Instant = now
// get() = now.toWallTime()


Expand Down Expand Up @@ -106,7 +106,7 @@ internal fun Class<*>.defaultName(nameCache: MutableMap<String, Int>) =
simpleName.ifEmpty { "Component" } + "." + getComponentCounter(simpleName, nameCache)

private fun String.defaultName(nameCache: MutableMap<String, Int>) =
this + getComponentCounter(this.removeRange(length-1 until length), nameCache)
this + getComponentCounter(this.removeRange(length - 1 until length), nameCache)

private fun getComponentCounter(className: String, nameCache: MutableMap<String, Int>) =
nameCache.merge(className, 1, Int::plus)
Expand Down
9 changes: 4 additions & 5 deletions src/main/kotlin/org/kalasim/State.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ package org.kalasim
import org.kalasim.analysis.EntityCreatedEvent
import org.kalasim.analysis.StateChangedEvent
import org.kalasim.analysis.snapshot.StateSnapshot
import org.kalasim.misc.*
import org.kalasim.monitors.CategoryTimeline
import org.kalasim.monitors.MetricTimeline
import org.kalasim.monitors.NumericStatisticMonitor
import org.kalasim.misc.DependencyContext
import org.kalasim.misc.StateTrackingConfig
import org.kalasim.monitors.*
import org.koin.core.Koin

/**
Expand All @@ -21,7 +20,7 @@ open class State<T>(
name: String? = null,
koin: Koin = DependencyContext.get(),
val trackingConfig: StateTrackingConfig = koin.getEnvDefaults().DefaultStateConfig,
) : SimulationEntity(name, koin) {
) : SimulationEntity(name, koin) {

private var maxTriggerCxt: Int? = null
private val isTriggerCxt
Expand Down
3 changes: 2 additions & 1 deletion src/main/kotlin/org/kalasim/TickTransform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package org.kalasim
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import org.kalasim.misc.AmbiguousDuration
import kotlin.time.*
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit

// note: remove @JvmInline because it did not seem ready on the java-interop-side
// value class ? --> Blocked by https://github.com/holgerbrandl/kalasim/issues/45
Expand Down
13 changes: 8 additions & 5 deletions src/main/kotlin/org/kalasim/analysis/ConsoleTraceLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import org.kalasim.misc.titlecaseFirstChar
import java.util.logging.Level



class ConsoleTraceLogger(var logLevel: Level = Level.INFO) : EventListener {

enum class EventsTableColumn { Time, Current, Receiver, Action, Info }
Expand Down Expand Up @@ -55,23 +54,26 @@ class ConsoleTraceLogger(var logLevel: Level = Level.INFO) : EventListener {
val receiverChanged = component != lastReceiver

listOf(
TRACE_DF.format(time.epochSeconds/60.0),
TRACE_DF.format(time.epochSeconds / 60.0),
if(ccChanged) current?.name else null,
if(receiverChanged) component?.name else null,
// ((source?.name ?: "") + " " + (renderAction() ?: "")).trim(),
(action ?: "").titlecaseFirstChar(),
if(event is ComponentStateChangeEvent){ "New state: ${event.state.toString().lowercase()}"} else ""
if(event is ComponentStateChangeEvent) {
"New state: ${event.state.toString().lowercase()}"
} else ""
).apply {
// update last element
lastCurrent = this@with.current
lastReceiver = this@with.component
}
}

is EntityCreatedEvent -> {
val ccChanged = creator != lastCurrent

listOf(
TRACE_DF.format(time.epochSeconds/60.0),
TRACE_DF.format(time.epochSeconds / 60.0),
if(ccChanged) creator?.name else null,
entity.name,
"Created",
Expand All @@ -82,8 +84,9 @@ class ConsoleTraceLogger(var logLevel: Level = Level.INFO) : EventListener {
lastReceiver = this@with.entity
}
}

else -> {
listOf(TRACE_DF.format(time.epochSeconds/60.0), "", "", toString())
listOf(TRACE_DF.format(time.epochSeconds / 60.0), "", "", toString())
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/main/kotlin/org/kalasim/analysis/Events.kt
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,17 @@ open class InteractionEvent(


/** Fired when a simulation state is changing its value. https://www.kalasim.org/state/ */
open class StateChangedEvent<T>(
open class StateChangedEvent<T>(
time: SimTime,
val state: State<T>,
val newValue: T,
current: Component? = null,
val trigger: Int? = null
): InteractionEvent(time, current, null){
) : InteractionEvent(time, current, null) {

override val action: String?
get() {
return if(trigger!=null) {
return if(trigger != null) {
"State changes to '$newValue' with trigger allowing $trigger components"
} else {
"State changed to '$newValue'"
Expand All @@ -133,7 +133,7 @@ open class StateChangedEvent<T>(
"current" to current?.name
"state" to state.name
"newValue" to newValue
if(trigger!=null) {
if(trigger != null) {
"trigger" to trigger
}
}
Expand Down Expand Up @@ -162,7 +162,7 @@ open class ComponentStateChangeEvent(
component: Component,
val state: ComponentState,
details: String? = null
) : InteractionEvent(time, current, component, details){
) : InteractionEvent(time, current, component, details) {

override fun toJson(): JSONObject = json {
"time" to time
Expand Down
Loading

0 comments on commit 2b7b67c

Please sign in to comment.