MoonDES 层级1:提供仿真环境、事件队列、主仿真循环。
| 符号 | 说明 |
|---|---|
| SimulationEnv | 全局仿真环境 |
| EventQueue | 最小堆优先级事件队列 |
| Event | 仿真事件 |
| EnvSnapshot | 环境状态快照 |
| new_env(until=) | 创建仿真环境 |
| new_queue() | 创建空事件队列 |
| new_event(id=, time=, callback=) | 创建事件 |
| SimulationEnv::run() | 主仿真循环 |
| SimulationEnv::step() | 单步推进 |
| SimulationEnv::schedule(time=, callback=) | 调度事件 |
| SimulationEnv::event_count() | 已注册事件数 |
| SimulationEnv::snapshot() | 捕获状态快照 |
| SimulationEnv::restore(snap) | 从快照恢复 |
///|
test {
let env = new_env(until=10.0)
inspect(env.now(), content="0")
let log : Array[String] = []
ignore(env.schedule(time=3.0, callback=fn() { log.push("A") }))
ignore(env.schedule(time=1.0, callback=fn() { log.push("B") }))
env.run()
assert_eq(log[0], "B")
assert_eq(log[1], "A")
inspect(env.event_count(), content="2")
}///|
test {
let q = new_queue()
inspect(q.is_empty(), content="true")
let e = new_event(id=0, time=1.0, callback=fn() { () })
q.push(e)
inspect(q.length(), content="1")
}impl FromJson for EnvSnapshotpub(all) struct Event {
id : Int
time : Double
priority : Int
status : EventStatus
callbacks : Array[() -> Unit]
}pub(all) struct SimulationEnv {
now : Double
until : Double
queue : EventQueue
status : EnvStatus
next_event_id : Int
next_process_id : Int
events : Map[Int, Event]
on_step_hook : (SimulationEnv, Double) -> Unit?
on_event_hook : (SimulationEnv, Event) -> Unit?
on_finish_hook : (SimulationEnv) -> Unit?
}fn SimulationEnv::_set_on_event_hook(self : SimulationEnv, hook : (SimulationEnv, Event) -> Unit?) -> Unitfn SimulationEnv::_set_on_finish_hook(self : SimulationEnv, hook : (SimulationEnv) -> Unit?) -> Unitfn SimulationEnv::_set_on_step_hook(self : SimulationEnv, hook : (SimulationEnv, Double) -> Unit?) -> Unittest {
let env = @core.new_env(until=10.0)
let log : Array[String] = []
ignore(env.schedule(time=2.0, callback=fn() { log.push("A") }))
ignore(env.schedule(time=1.0, callback=fn() { log.push("B") }))
env.run()
assert_eq(log[0], "B")
assert_eq(log[1], "A")
}fn SimulationEnv::schedule(self : SimulationEnv, time~ : Double, priority? : Int, callback~ : () -> Unit) -> Eventtest {
let env = @core.new_env(until=10.0)
let ev = env.timeout(5.0)
inspect(ev.time, content="5")
inspect(ev.is_pending(), content="true")
}test {
let env = @core.new_env(until=100.0)
inspect(env.now(), content="0")
inspect(env.until, content="100")
}MoonDES - 通用离散事件仿真引擎,基于 MoonBit 构建