Skip to content

Commit

Permalink
reduced compiler warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
holgerbrandl committed Nov 5, 2023
1 parent fab5b86 commit 498ff42
Show file tree
Hide file tree
Showing 32 changed files with 143 additions and 139 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ plugins {

group = "com.github.holgerbrandl"
//version = "0.8.101"
version = "0.12-SNAPSHOT"
version = "2023.1-SNAPSHOT"
//version = "0.12-SNAPSHOT"


Expand Down
4 changes: 2 additions & 2 deletions docs/userguide/docs/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Minor improvements
* Expose `Environment.getOrNull<T>()` from [koin](https://github.com/InsertKoinIO/koin/issues/182) to check for presence of registered dependencies in simulation environment
* [#46](https://github.com/holgerbrandl/kalasim/issues/46) clarify use of collect with filter
* [#52](https://github.com/holgerbrandl/kalasim/issues/54) Improved visualization of metric timelines to support zoom range
* [#67](https://github.com/holgerbrandl/kalasim/issues/67) & [#65](https://github.com/holgerbrandl/kalasim/issues/65) Added more safety guard mechanisms to prevent context violations when branching component processes.
* [#67](https://github.com/holgerbrandl/kalasim/issues/67) & [#64](https://github.com/holgerbrandl/kalasim/issues/64) Added more safety guard mechanisms to prevent context violations when branching component processes.

Starting with this release we have switched to calendar versioning for better clarity regarding our release density, timing and schedule.

Expand Down Expand Up @@ -216,7 +216,7 @@ createSimulation {
tickTransform = OffsetTransform(Instant.now(), DurationUnit.MINUTES)

run(Duration.ofMinutes(90).asTicks())
println(toWallTime(now))
println(asSimTime(now))
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fun main() {
program {
// load resources such as images
val image = loadImage("src/main/resources/1024px-Phlegra_Montes_on_Mars_ESA211127.jpg")
val truck = loadSVG("src/main/resources/tractor-svgrepo-com.svg")
// val truck = loadSVG("src/main/resources/tractor-svgrepo-com.svg")
val font = loadFont("file:IBM_Plex_Mono/IBMPlexMono-Bold.ttf", 24.0)

// optionally enable video recording
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.kalasim.animation

import org.kalasim.Component
import org.kalasim.asDuration
import org.kalasim.misc.AmbiguousDuration

fun <K, V> Map<K, V>.cmeAvoidingCopy(): Map<K, V> {
while(true) {
Expand Down Expand Up @@ -68,6 +69,7 @@ class AsyncAnimationStop(val rate: Double = 1.0) : Component() {
stop = true
}

@OptIn(AmbiguousDuration::class)
override fun repeatedProcess() = sequence {
if(stop) {
stopSimulation()
Expand Down
3 changes: 3 additions & 0 deletions modules/benchmarks/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
out
build
.gradle
7 changes: 6 additions & 1 deletion modules/benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ For gradle plugin options see https://github.com/melix/jmh-gradle-plugin

* This will execute all (methods annotated with `@Benchmark`) benchmarks with their predefined parameters:

`./gradlew --console=plain clean jmh`
```bash
# cd cd /d/projects/scheduling/kalasim/modules/benchmarks
./gradlew --console=plain clean jmh`
```

* Output is saved as CSV in `benchmarks/build/results/jmh/results.csv`

Expand Down Expand Up @@ -40,6 +43,8 @@ java -jar build/libs/benchmarks-jmh.jar org.kalasim.benchmarks.FabBench
## References
https://github.com/Kotlin/kotlinx-benchmark
https://howtodoinjava.com/java/library/jmh-java-microbenchmark-harness/
## How to automate benchmarking as part of the release process?
Expand Down
2 changes: 1 addition & 1 deletion modules/benchmarks/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ dependencies {
jmh("org.apache.commons:commons-lang3:3.12.0")
jmh("org.slf4j:slf4j-simple:2.0.9")

jmh("com.github.holgerbrandl:kalasim:0.9.2-SNAPSHOT")
jmh("com.github.holgerbrandl:kalasim:2023.1-SNAPSHOT")

// jmh ("com.systema.risuite:fsm-simulator:2.4.1")
// jmh(project(":"))
Expand Down
Binary file not shown.
6 changes: 6 additions & 0 deletions modules/benchmarks/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
45 changes: 23 additions & 22 deletions src/main/kotlin/org/kalasim/Component.kt
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,7 @@ open class Component(
scheduledTime = when {
failAt != null -> failAt
failDelay != null -> env.now + failDelay
else -> SimTime(Double.MAX_VALUE)
else -> SimTime.DISTANT_FUTURE
}

failed = false
Expand Down Expand Up @@ -1576,7 +1576,7 @@ open class Component(
scheduledTime = when {
failAt != null -> failAt
failDelay != null -> env.now + failDelay
else -> SimTime(Double.MAX_VALUE)
else -> SimTime.DISTANT_FUTURE
}

stateRequests
Expand Down Expand Up @@ -1862,27 +1862,28 @@ data class StateRequest<T>(val state: State<T>, val priority: Priority? = null,

infix fun <T> State<T>.turns(value: T) = StateRequest(this) { it == value }

internal fun formatWithInf(time: SimTime) =
if(time.isDistantFuture) "<inf>" else TRACE_DF.format(time.epochSeconds)
internal fun formatWithInf(env: Environment?, time: SimTime?) : String =
if(time==null || time.isDistantFuture) "<inf>" else formatWithInf(env?.asTickTime(time))

internal fun formatWithInf(time: TickTime) =
if(time.value == Double.MAX_VALUE || time.value.isInfinite()) "<inf>" else TRACE_DF.format(time.value)
internal fun formatWithInf(time: TickTime?) : String =
if(time==null || time.value == Double.MAX_VALUE || time.value.isInfinite()) "<inf>" else TRACE_DF.format(time.value)


data class ComponentLifecycleRecord(
val component: String,
val createdAt: SimTime,
val inDataSince: SimTime?,
val inData: SimTime,
val inCurrent: SimTime,
val inStandby: SimTime,
val inPassive: SimTime,
val inInterrupted: SimTime,
val inScheduled: SimTime,
val inRequesting: SimTime,
val inWaiting: SimTime
val inData: Duration,
val inCurrent: Duration,
val inStandby: Duration,
val inPassive: Duration,
val inInterrupted: Duration,
val inScheduled: Duration,
val inRequesting: Duration,
val inWaiting: Duration
)

@OptIn(AmbiguousDuration::class)
fun Component.toLifeCycleRecord(): ComponentLifecycleRecord {
val c = this

Expand All @@ -1892,14 +1893,14 @@ fun Component.toLifeCycleRecord(): ComponentLifecycleRecord {
c.name,
c.creationTime,
inDataSince = if(c.isData) c.stateTimeline.statsData().timepoints.last() else null,
(histogram[DATA] ?: 0.0).toTickTime(),
(histogram[CURRENT] ?: 0.0).toTickTime(),
(histogram[STANDBY] ?: 0.0).toTickTime(),
(histogram[PASSIVE] ?: 0.0).toTickTime(),
(histogram[INTERRUPTED] ?: 0.0).toTickTime(),
(histogram[SCHEDULED] ?: 0.0).toTickTime(),
(histogram[REQUESTING] ?: 0.0).toTickTime(),
(histogram[WAITING] ?: 0.0).toTickTime(),
env.asDuration(histogram[DATA] ?: 0.0),
env.asDuration(histogram[CURRENT] ?: 0.0),
env.asDuration(histogram[STANDBY] ?: 0.0),
env.asDuration(histogram[PASSIVE] ?: 0.0),
env.asDuration(histogram[INTERRUPTED] ?: 0.0),
env.asDuration(histogram[SCHEDULED] ?: 0.0),
env.asDuration(histogram[REQUESTING] ?: 0.0),
env.asDuration(histogram[WAITING] ?: 0.0),
)
}

Expand Down
8 changes: 4 additions & 4 deletions src/main/kotlin/org/kalasim/ComponentGenerator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ComponentGenerator<T>(
val iat: DurationDistribution,
startAt: SimTime? = null,
val forceStart: Boolean = false,
var until: SimTime = SimTime(Double.MAX_VALUE),
val until: SimTime? = null ,
val total: Int = Int.MAX_VALUE,
name: String? = null,
priority: Priority = Priority.NORMAL,
Expand All @@ -37,7 +37,7 @@ class ComponentGenerator<T>(
iat: RealDistribution,
startAt: SimTime? = null,
forceStart: Boolean = false,
until: SimTime = SimTime(Double.MAX_VALUE),
until: SimTime? = null,
total: Int = Int.MAX_VALUE,
name: String? = null,
priority: Priority = Priority.NORMAL,
Expand Down Expand Up @@ -66,7 +66,7 @@ class ComponentGenerator<T>(
iat: Duration,
startAt: SimTime? = null,
forceStart: Boolean = false,
until: SimTime = SimTime(Double.MAX_VALUE),
until: SimTime? = null,
total: Int = Int.MAX_VALUE,
name: String? = null,
priority: Priority = Priority.NORMAL,
Expand Down Expand Up @@ -108,7 +108,7 @@ class ComponentGenerator<T>(
while(true) {
val interArrivalTime = iatSeq.next()

if((env.now + interArrivalTime) > until || isData) {
if(until!=null && (env.now + interArrivalTime) > until || isData) {
// yield(activate(at = until, process = ComponentGenerator<T>::doFinalize))
break
}
Expand Down
12 changes: 0 additions & 12 deletions src/main/kotlin/org/kalasim/Distributions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,6 @@ fun SimContext.triangular(lowerLimit: Number, mode: Number, upperLimit: Number):
fun SimContext.triangular(lowerLimit: Duration, mode: Duration, upperLimit: Duration): DurationDistribution =
TriangularDistribution(env.rg, lowerLimit.inSeconds, mode.inSeconds, upperLimit.inSeconds).seconds

/** Clip the values of the distribution to the provided interval. */
// we could also adopt kotlin stdlib conventions and use coerceIn, coerceAtLeast and coerceAtMost
@Deprecated("Use rectify argument when creating normal distribution with normal(mean,sd, rectify=true)")
fun RealDistribution.clip(lower: Number = 0, upper: Number = Double.MAX_VALUE) =
Clipper(this, lower.toDouble(), upper.toDouble())


@Deprecated("substituted with rectify argument in normal()")
class Clipper internal constructor(val dist: RealDistribution, val lower: Double, val upper: Double) {
operator fun invoke(): Double = min(max(dist(), lower), upper)
}


/**
* Uniform distribution with built-in support for controlled-randomization.
Expand Down
2 changes: 2 additions & 0 deletions src/main/kotlin/org/kalasim/Environment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,8 @@ open class Environment(
@AmbiguousDuration
fun Number.asSimTime() = env.asSimTime(this)

fun TickTime.asSimTime() = env.asSimTime(this)

// deprecated because nothing should be logged outside a process
// fun log(msg: String) = main.log(msg)
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/org/kalasim/Resource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -469,8 +469,8 @@ val Resource.timeline: List<ResourceTimelineSegment>

// optionally add walltimes
// if (env.tickTransform != null) {
// statsDF = statsDF.add("start_wt") { it["start"].map<TickTime> { env.toWallTime(it) } }
// statsDF = statsDF.add("end_wt") { it["end"].map<TickTime> { env.toWallTime(it) } }
// statsDF = statsDF.add("start_wt") { it["start"].map<TickTime> { env.asSimTime(it) } }
// statsDF = statsDF.add("end_wt") { it["end"].map<TickTime> { env.asSimTime(it) } }
// }

return statsDF.toListOf<ResourceTimelineSegment>()
Expand Down
20 changes: 6 additions & 14 deletions src/main/kotlin/org/kalasim/SimContext.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,15 @@ interface SimContext : KoinComponent {
val Duration.ticks: Double
get() = asTicks()

// Scoped extensions
fun Instant.toTickTime(): TickTime {
require(env.startDate != null) { MISSING_TICK_TRAFO_ERROR }
/**
* Converts an [SimTime] to a [TickTime] using the current environment's wall-to-tick time conversion.
*
* @return The converted [TickTime].
*/// Scoped extensions
fun SimTime.toTickTime(): TickTime {
return env.wall2TickTime(this)
}

// operator fun TickTime.plus(duration: Duration): TickTime = TickTime(value + duration.asTicks())
// operator fun TickTime.minus(duration: Duration): TickTime = TickTime(value - duration.asTicks())

/** 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 {
require(env.startDate != null) { MISSING_TICK_TRAFO_ERROR }
return env.tick2wallTime(this)
}


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


Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/org/kalasim/SimulationEntity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ abstract class SimulationEntity(name: String? = null, val simKoin: Koin = Depend

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


val random
Expand Down
19 changes: 11 additions & 8 deletions src/main/kotlin/org/kalasim/TickTransform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ import kotlin.time.DurationUnit

typealias SimTime = Instant

@Deprecated("use is disencouraged because it has an implicit reference to tick-duration of environment")
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use is Disencouraged because it has an implicit reference to tick-duration of environment")
fun SimTime(offset: Number) = SimTime.fromEpochMilliseconds(offset.toLong())


Expand All @@ -52,13 +53,15 @@ value class Ticks(val value: Double) {
constructor(instant: Number) : this(instant.toDouble())
}

@Suppress("DEPRECATION")
@AmbiguousDuration
val Number.simTime: SimTime
get() = SimTime(this)

val Number.tt: TickTime
get() = TickTime(this.toDouble())

fun Number.toTickTime() = SimTime(this)
fun Number.asTickTime() = TickTime(this.toDouble())


// https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime
Expand Down Expand Up @@ -101,16 +104,16 @@ fun Environment.asTicks(duration: Duration): Double = duration.asTicks()
@AmbiguousDuration
fun Environment.asSimTime(someWhen: Number): SimTime = startDate + asDuration(someWhen)


@OptIn(AmbiguousDuration::class)
fun Environment.asSimTime(time: TickTime) = startDate + asDuration(time.value)


@AmbiguousDuration
fun Environment.asDuration(duration: Number): Duration = duration.let {
tickTransform.ticks2Duration(duration.toDouble())
}

/** Transforms an wall `Instant` to simulation time.*/
fun Environment.toTickTime(instant: SimTime) = instant.toTickTime()

/** Transforms a simulation time (typically `now`) to the corresponding wall time. */
fun Environment.toWallTime(time: TickTime) = time.toWallTime()
//fun Environment.toWallTimeOrNull(time: TickTime) = time.toWallTime()
fun Environment.asTickTime(instant: SimTime) = instant.toTickTime()

//operator fun Instant.plus(duration: Duration): Instant = this.plus(duration.toJavaDuration())
34 changes: 16 additions & 18 deletions src/main/kotlin/org/kalasim/analysis/DataFrameUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,29 @@ package org.kalasim.analysis

import org.jetbrains.kotlinx.dataframe.DataFrame
import org.jetbrains.kotlinx.dataframe.api.add
import org.jetbrains.kotlinx.dataframe.api.rename
import org.kalasim.*

@Deprecated("no longer needed, as `now` is of type Instant starting in kalasim v0.12")
fun DataFrame<*>.addWallTimes(sim: Environment, suffix: String = "_wt"): DataFrame<*> {
// figure which columns are of type ticktime
// val tickTimeColumns = columns().filter { it.type().toString().contains("TickTime") }.map { it.name() }

// return tickTimeColumns.fold(this) { df, ttColumnName ->
// df.add(ttColumnName + suffix) {
// val tickTime = ttColumnName<TickTime?>()
// tickTime?.let { sim.toWallTime(it) }
// }
// }

return this
}

fun DataFrame<*>.addTickTimes(sim: Environment, suffix: String = "_wt"): DataFrame<*> {
fun DataFrame<*>.addTickTimes(sim: Environment, suffix: String = "_tt"): DataFrame<*> {
// figure which columns are of type ticktime
val tickTimeColumns = columns().filter { it.type().toString().contains("Instant") }.map { it.name() }

return tickTimeColumns.fold(this) { df, ttColumnName ->
df.add(ttColumnName + suffix) {
val simTime = ttColumnName<SimTime?>()
simTime?.let { sim.toTickTime(it) }
simTime?.let { sim.asTickTime(it) }
}
}
}
}

/** rename *_wt columns to * and, <TickTime>_tt to <TickTime> to mimic old kalasim naming */
@Deprecated("do do this if possible but rather rework the downstream analysis scripts")
fun DataFrame<*>.toggleWtNames(suffix: String = "_tt", wt_suffix :String="_wt"): DataFrame<*> {
val simTimeColumns = columns().filter { it.type().toString().contains("Instant") }.map { it.name() }

val renamed = simTimeColumns.fold(this) { df, name -> df.rename(name to name + wt_suffix) }
val tickTimeColumns = columns().filter { it.type().toString().contains("TickTime") }.map { it.name() }

return tickTimeColumns.filter { it.endsWith(suffix) }
.fold(renamed) { df, name -> df.rename(name to name + "") }
}
Loading

0 comments on commit 498ff42

Please sign in to comment.