-
Notifications
You must be signed in to change notification settings - Fork 0
/
sim.go
832 lines (674 loc) · 23.3 KB
/
sim.go
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package sim
import (
"fmt"
"log"
"slices"
"time"
"math"
"sort"
"bufio"
"os"
"gonum.org/v1/gonum/stat/distuv"
"golang.org/x/exp/rand"
)
const (
AC_Reset string = "\x1b[0m"
AC_CodeRed string = "\x1b[31m"
AC_CodeGreen string = "\x1b[32m"
AC_CodeYellow string = "\x1b[33m"
AC_CodeBlue string = "\x1b[34m"
AC_CodeMagenta string = "\x1b[35m"
AC_CodeCyan string = "\x1b[36m"
AC_CodeBold string = "\x1b[1m"
AC_ResetBold string = "\x1b[22m"
)
func AC_Red(str string) string {return AC_CodeRed + str + AC_Reset}
func AC_Green(str string) string {return AC_CodeGreen + str + AC_Reset}
func AC_Yellow(str string) string {return AC_CodeYellow + str + AC_Reset}
func AC_Blue(str string) string {return AC_CodeBlue + str + AC_Reset}
func AC_Magenta(str string) string {return AC_CodeMagenta + str + AC_Reset}
func AC_Cyan(str string) string {return AC_CodeCyan + str + AC_Reset}
func AC_Bold(str string) string {return AC_CodeBold + str + AC_ResetBold}
type MonthInfo struct {
NumDays int
BeginingSec float64
}
var Months [12]MonthInfo
const ProgressBarMaxSize = 40
// var NumDays [12]int = [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
func WaitForEnter() {
fmt.Printf(AC_Bold("[STEP THROUGH] Press ENTER to continue\n"))
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
type RNG interface {
Next() float64
}
type RNGExponential struct {
Rate float64
RNG rand.Rand
}
type RNGNormal struct {
Mean float64
StdDev float64
RNG rand.Rand
}
type RNGLogNormal struct {
Mean float64
StdDev float64
RNG distuv.LogNormal
}
type RNGTriangular struct {
A float64
B float64
C float64
RNG distuv.Triangle
}
type RNGDiscrete struct {
Weights []float64
RNG distuv.Categorical
}
func NewRNGExponential(rate float64) *RNGExponential {
return &RNGExponential{Rate: rate, RNG: *rand.New(rand.NewSource(uint64(time.Now().UnixMilli())))}
}
func NewRNGNormal(mean float64, stddev float64) *RNGNormal {
return &RNGNormal{Mean: mean, StdDev: stddev, RNG: *rand.New(rand.NewSource(uint64(time.Now().UnixMilli())))}
}
func NewRNGLogNormal(mean float64, stddev float64) *RNGLogNormal {
mu := math.Log(math.Pow(mean, 2) / math.Sqrt(math.Pow(mean, 2) + math.Pow(stddev, 2)))
sigma := math.Sqrt(math.Log(1 + math.Pow(stddev, 2)/math.Pow(mean, 2)))
return &RNGLogNormal{Mean: mean, StdDev: stddev, RNG: distuv.LogNormal{Mu: mu, Sigma: sigma, Src: rand.NewSource(uint64(time.Now().UnixMilli()))}}
}
func NewRNGTriangular(a float64, b float64, c float64) *RNGTriangular {
return &RNGTriangular{A: a, B: b, C: c, RNG: distuv.NewTriangle(a, b, c, rand.NewSource(uint64(time.Now().UnixMilli())))}
}
func NewRNGDiscrete(w []float64) *RNGDiscrete {
return &RNGDiscrete{Weights: w, RNG: distuv.NewCategorical(w, rand.NewSource(uint64(time.Now().UnixMilli())))}
}
func (rng *RNGExponential) Next() float64 {
return rng.RNG.ExpFloat64() / rng.Rate
}
func (rng *RNGNormal) Next() float64 {
return rng.RNG.NormFloat64() * rng.StdDev + rng.Mean
}
func (rng *RNGLogNormal) Next() float64 {
return rng.RNG.Rand()
}
func (rng *RNGTriangular) Next() float64 {
return rng.RNG.Rand()
}
func (rng *RNGDiscrete) Next() float64 {
return rng.RNG.Rand()
}
func Minutes(n float64) float64 {return 60*n}
func Hours(n float64) float64 {return Minutes(60)*n}
func Days(n float64) float64 {return Hours(24)*n}
func Years(n float64) float64 {return Days(365)*n}
type QueueType int
const (
QueueType_Resource QueueType = iota
QueueType_Process
)
type QueueStatistics struct {
TotalEntitiesIn int
TotalEntitiesOut int
TotalTimeInQueue float64
AvgTimeInQueue float64
}
type QueueStats struct {
Type QueueType
Id string
DateIn float64
DateOut float64
}
type ProcessStats struct {
Id string
DateQueued float64
DateStart float64
DateEnd float64
}
type EntityBase struct {
Id int
Type string
QueueStats []*QueueStats
ProcessStats []*ProcessStats
Resources map[string]float64
Environment *Environment
}
type Entity interface {
GetEnvironment() *Environment
GetEntityBase() *EntityBase
Initialize(id int, tp string)
SetId(id int)
GetId() int
SetType(tp string)
GetType() string
GetName() string
EnterQueue(queueType QueueType, id string, date float64)
LeaveQueue(queueType QueueType, id string, date float64)
StartProcess(date float64)
EndProcess(date float64)
GetTimeInQueue() float64
GetProcessDuration() float64
GetResourceAmount(rid string) float64
SeizeResource(rid string, amount float64, date float64)
ReleaseResources()
}
func (entityBase *EntityBase) GetEnvironment() *Environment {
return entityBase.Environment
}
func (entityBase *EntityBase) GetEntityBase() *EntityBase {
return entityBase
}
func (entityBase *EntityBase) GetResourceAmount(rid string) float64 {
amount, ok := entityBase.Resources[rid]
if ok {
return amount
}
return 0
}
func (entityBase *EntityBase) GetTimeInQueue() float64 {
st := entityBase.ProcessStats[len(entityBase.ProcessStats)-1]
return st.DateStart - st.DateQueued
}
func (entityBase *EntityBase) StartProcess(date float64) {
entityBase.ProcessStats[len(entityBase.ProcessStats)-1].DateStart = date
}
func (entityBase *EntityBase) EndProcess(date float64) {
entityBase.ProcessStats[len(entityBase.ProcessStats)-1].DateEnd = date
}
func (entityBase *EntityBase) GetProcessDuration() float64 {
return entityBase.ProcessStats[len(entityBase.ProcessStats)-1].DateEnd - entityBase.ProcessStats[len(entityBase.ProcessStats)-1].DateStart
}
func (entityBase *EntityBase) Initialize(id int, tp string) {
entityBase.Id = id
entityBase.Type = tp
entityBase.QueueStats = make([]*QueueStats, 0)
entityBase.ProcessStats = make([]*ProcessStats, 0)
entityBase.Resources = make(map[string]float64)
}
func (entityBase *EntityBase) SetId(id int) {
entityBase.Id = id
}
func (entityBase *EntityBase) GetId() int {
return entityBase.Id
}
func (entityBase *EntityBase) SetType(tp string) {
entityBase.Type = tp
}
func (entityBase *EntityBase) GetType() string {
return entityBase.Type
}
func (entityBase *EntityBase) GetName() string {
return fmt.Sprintf("%s %d", entityBase.Type, entityBase.Id)
}
func (entityBase *EntityBase) EnterQueue(tp QueueType, id string, date float64) {
entityBase.QueueStats = append(entityBase.QueueStats, &QueueStats{Type: tp, Id: id, DateIn: date})
if tp == QueueType_Process {
entityBase.ProcessStats = append(entityBase.ProcessStats, &ProcessStats{Id: id, DateQueued: date})
}
}
func (entityBase *EntityBase) LeaveQueue(tp QueueType, id string, date float64) {
for i := len(entityBase.QueueStats)-1; i >= 0; i-- {
st := entityBase.QueueStats[i]
if st.Type == tp && st.Id == id {
st.DateOut = date
return
}
}
}
func (entityBase *EntityBase) SeizeResource(rid string, amount float64, date float64) {
entityBase.Resources[rid] = amount
entityBase.LeaveQueue(QueueType_Resource, rid, date)
}
func (entityBase *EntityBase) ReleaseResources() {
entityBase.Resources = make(map[string]float64)
}
type ResourceBase struct {
Id string
Amount float64
Queue []Entity
// Statistics
TotalEntitiesIn int
TotalEntitiesOut int
TotalTimeInQueue float64
AvgTimeInQueue float64
}
type Resource interface {
Enqueue(entity Entity)
Dequeue()
GetAmount() float64
SetAmount(amount float64)
}
func (res *ResourceBase) Enqueue(entity Entity) {
res.Queue = append(res.Queue, entity)
res.TotalEntitiesIn++
}
func (res *ResourceBase) Dequeue() {
res.Queue = res.Queue[1:]
res.TotalEntitiesOut++
}
func (res *ResourceBase) GetAmount() float64 {
return res.Amount
}
func (res *ResourceBase) SetAmount(amount float64) {
res.Amount = amount
}
type ProcessBase struct {
Id string
Groups []string
Needs map[string]float64
Queue []Entity
RNG RNG
DelayFunc func (process *ProcessBase, entity Entity) float64
Forward func (entity Entity)
NextProcess string
QueueStats QueueStatistics
AvgDuration float64
AccumDuration float64
TotalEntitiesOut int
}
type Process interface {
GetProcessBase() *ProcessBase
Initialize(base ProcessBase)
GetId() string
GetDuration(entity Entity) float64
GetNeeds() map[string]float64
Enqueue(entity Entity)
Dequeue()
GetQueueSize() int
GetNextInQueue() Entity
GetStatistics() QueueStatistics
}
func (process *ProcessBase) GetProcessBase() *ProcessBase {
return process
}
func (process *ProcessBase) Initialize(base ProcessBase) {
*process = base
}
func (process *ProcessBase) GetStatistics() QueueStatistics {
return process.QueueStats
}
func (process *ProcessBase) GetId() string {
return process.Id
}
func (process *ProcessBase) GetNeeds() map[string]float64 {
return process.Needs
}
func (process *ProcessBase) GetDuration(entity Entity) float64 {
if process.DelayFunc != nil {
return process.DelayFunc(process, entity)
} else {
return process.RNG.Next()
}
}
func (process *ProcessBase) Enqueue(entity Entity) {
process.Queue = append(process.Queue, entity)
process.QueueStats.TotalEntitiesIn++
}
func (process *ProcessBase) Dequeue() {
entity := process.Queue[0]
process.QueueStats.TotalTimeInQueue += entity.GetTimeInQueue()
process.Queue = process.Queue[1:]
process.QueueStats.TotalEntitiesOut++
process.QueueStats.AvgTimeInQueue = process.QueueStats.TotalTimeInQueue / float64(process.QueueStats.TotalEntitiesIn)
}
func (process *ProcessBase) GetQueueSize() int {
return len(process.Queue)
}
func (process *ProcessBase) GetNextInQueue() Entity {
return process.Queue[0]
}
type OngoingProcess struct {
Process Process
Entity Entity
DateStart float64
DateEnd float64
}
type ByDateEnd []OngoingProcess
func (a ByDateEnd) Len() int { return len(a) }
func (a ByDateEnd) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByDateEnd) Less(i, j int) bool { return a[i].DateEnd < a[j].DateEnd }
type EntitySourceBase struct {
Id string
RNG RNG
MaxGenerations int
BatchSize int
Env *Environment
// Simulation
NextGen float64
Generations int
}
type EntitySource interface {
GetEntitySourceBase() *EntitySourceBase
GetEnvironment() *Environment
Initialize(base EntitySourceBase)
GetId() string
Generate() Entity
Update()
GetNextGen() float64
GetBatchSize() int
GetMaxGenerations() int
GetGenerations() int
}
type ByNextGen []EntitySource
func (a ByNextGen) Len() int { return len(a) }
func (a ByNextGen) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByNextGen) Less(i, j int) bool { return a[i].GetNextGen() < a[j].GetNextGen() }
func (source *EntitySourceBase) GetEntitySourceBase() *EntitySourceBase {
return source
}
func (source *EntitySourceBase) GetEnvironment() *Environment {
return source.Env
}
func (source *EntitySourceBase) GetId() string {
return source.Id
}
func (source *EntitySourceBase) Initialize(base EntitySourceBase) {
*source = base
}
func (source *EntitySourceBase) GetNextGen() float64 {
return source.NextGen
}
func (source *EntitySourceBase) GetBatchSize() int {
return source.BatchSize
}
func (source *EntitySourceBase) GetMaxGenerations() int {
return source.MaxGenerations
}
func (source *EntitySourceBase) GetGenerations() int {
return source.Generations
}
func (source *EntitySourceBase) Update() {
source.NextGen += source.RNG.Next()
source.Generations++
}
type PrintfFunc func (format string, a ...any) (n int, err error)
func DisabledPrintf(format string, a ...any) (n int, err error) {return 0, nil}
type Environment struct {
EntitySources []EntitySource // array because needs sorting
Resources map[string]Resource // map of strings because persistent
Entities map[int]Entity // map of int because constantly deleting
Processes []Process // array because needs sorting
WatchedProcesses map[string]Process // array because needs sorting
OngoingProcesses []OngoingProcess // array because needs sorting
NextEntityId int
Now float64 // seconds
EndDate float64 // seconds
Replications int // seconds
RunStart time.Time
LastBarRefresh time.Time
ProgressBarSize int
ProgressPercent int
StepThrough bool
LogLevel int
Printf [3]PrintfFunc
}
func (env* Environment) GetCurrentMonth() int {
for m := 0; m < 12; m++ {
if env.Now >= Months[m].BeginingSec {
return m
}
}
return 0
}
func (env *Environment) SetLogLevel(level int) {
for i := 0; i < len(env.Printf); i++ {
env.Printf[i] = DisabledPrintf
}
for i := 1; i <= level; i++ {
env.Printf[i] = fmt.Printf
}
env.LogLevel = level
}
func GetHumanTime(s float64) string {
days := s / 60 / 60 / 24
hours := (days - math.Floor(days)) * 24
minutes := (hours - math.Floor(hours)) * 60
seconds := (minutes - math.Floor(minutes)) * 60
return fmt.Sprintf("%.0fd %02.0f:%02.0f:%05.2f", math.Floor(days), math.Floor(hours), math.Floor(minutes), seconds)
}
func (env *Environment) Enqueue(entity Entity, process Process) {
for rid, _ := range process.GetNeeds() {
env.Resources[rid].Enqueue(entity)
entity.EnterQueue(QueueType_Resource, rid, env.Now)
}
process.Enqueue(entity)
entity.EnterQueue(QueueType_Process, process.GetId(), env.Now)
env.WatchedProcesses[process.GetId()] = process
}
func (env *Environment) GetProcess(pid string) Process {
for _, process := range env.Processes {
if process.GetId() == pid {
return process
}
}
return nil
}
func (env *Environment) GetProcessBase(pid string) *ProcessBase {
process := env.GetProcess(pid)
return process.GetProcessBase()
}
func (env *Environment) ForwardTo(entity Entity, pid string) {
process := env.GetProcess(pid)
if process == nil {
log.Fatalf("Process not found: %s", pid)
}
env.Enqueue(entity, env.GetProcess(pid))
}
func (env *Environment) AddResource(resource *ResourceBase) {
env.Resources[resource.Id] = resource
}
func (env *Environment) AddProcess(base ProcessBase) {
if len(base.Groups) == 0 {
base.Groups = []string{"Unnamed"}
}
env.Processes = append(env.Processes, &base)
}
func (env *Environment) AddEntitySource(entitySource EntitySource) {
entitySource.GetEntitySourceBase().BatchSize = max(1, entitySource.GetEntitySourceBase().BatchSize)
entitySource.GetEntitySourceBase().MaxGenerations = 9999999999
entitySource.GetEntitySourceBase().Env = env
env.EntitySources = append(env.EntitySources, entitySource)
}
func (env *Environment) AddEntity(entityType string, entity Entity) {
entity.Initialize(env.NextEntityId, entityType)
entity.GetEntityBase().Environment = env
env.Entities[entity.GetId()] = entity
env.NextEntityId++
}
func (env *Environment) MaybeStartProcess(process Process) {
for process.GetQueueSize() > 0 {
entity := process.GetNextInQueue()
readyToStart := true
for rid, amount := range process.GetNeeds() {
seized := entity.GetResourceAmount(rid)
if seized < amount {
if env.Resources[rid].GetAmount() >= amount {
env.Resources[rid].SetAmount(env.Resources[rid].GetAmount() - amount)
entity.SeizeResource(rid, amount, env.Now)
} else {
readyToStart = false
}
}
}
if readyToStart {
env.Printf[2]("[PROCESS STARTED] %s | %s\n", process.GetId(), entity.GetName())
entity.LeaveQueue(QueueType_Process, process.GetId(), env.Now)
duration := process.GetDuration(entity)
env.StartProcess(process, entity, env.Now + duration)
if process.GetQueueSize() == 0 {
env.WatchedProcesses[process.GetId()] = nil
}
} else {
break
}
}
}
func (env *Environment) StartProcess(process Process, entity Entity, endDate float64) {
entity.StartProcess(env.Now)
process.Dequeue()
ongoing := OngoingProcess{Process: process, Entity: entity, DateStart: env.Now, DateEnd: endDate}
env.OngoingProcesses = append(env.OngoingProcesses, ongoing)
}
func Cast[T Entity](entity Entity) T {
if t, ok := entity.(T); ok {
return t
}
panic("Cast failed!")
}
func GetProgressBarSize(progress float64) int {
return int(math.Ceil(progress * float64(ProgressBarMaxSize)))
}
func RefreshProgressBar(progress float64) {
fmt.Printf("\033[%dD[", ProgressBarMaxSize+2+5)
progressBarSize := GetProgressBarSize(progress)
for c := 0; c < progressBarSize; c++ {
fmt.Printf("\u25A0")
}
fmt.Printf("%.*s] %3.0f%%", ProgressBarMaxSize - progressBarSize, " ", progress * 100)
}
func (env *Environment) Begin() {
var NumDays [12]int = [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
Months := make([]MonthInfo, 12)
for m := 0; m < 12; m++ {
Months[m].NumDays = NumDays[m]
}
for m := 1; m < 12; m++ {
Months[m].BeginingSec = float64(NumDays[m-1]) * 24 * 60 * 60
}
if env.StepThrough {
env.LogLevel = 2
}
env.SetLogLevel(env.LogLevel)
sort.Sort(ByNextGen(env.EntitySources))
env.Now = env.EntitySources[0].GetNextGen()
env.RunStart = time.Now()
env.LastBarRefresh = time.Now()
env.Printf[1]("[STARTING SIMULATION]\n")
env.Printf[1]("[REPLICATIONS] %d\n", env.Replications)
env.Printf[1]("[SIMULATED TIME] %s\n", GetHumanTime(env.EndDate))
env.ProgressBarSize = GetProgressBarSize(0)
env.ProgressPercent = 0;
}
func (env *Environment) Advance() bool {
if env.Now >= env.EndDate {
return false
}
env.Printf[2](AC_Green(AC_Bold("[SIMULATION CLOCK] %s (%.2fs)\n")), GetHumanTime(env.Now), env.Now)
for s := 0; s < len(env.EntitySources); {
source := env.EntitySources[s]
if source.GetNextGen() > env.Now {
break
}
for e := 0; e < source.GetBatchSize(); e++ {
entity := source.Generate()
env.Printf[2]("[NEW ENTITY] %s | %s\n", source.GetId(), entity.GetName())
_ = entity
}
source.Update()
if source.GetGenerations() == source.GetMaxGenerations() {
env.EntitySources = slices.Delete(env.EntitySources, s, s+1)
} else {
s++
}
}
nextTime := env.Now
for nextTime == env.Now {
for len(env.OngoingProcesses) > 0 {
ongoing := env.OngoingProcesses[0]
if ongoing.DateEnd > env.Now {
break
}
entity := ongoing.Entity
process := ongoing.Process
entity.EndProcess(env.Now)
env.Printf[2]("[PROCESS ENDED] %s | %s\n", process.GetId(), entity.GetName())
for rid, amount := range process.GetNeeds() {
env.Resources[rid].SetAmount(env.Resources[rid].GetAmount() + amount)
}
entity.ReleaseResources()
env.OngoingProcesses = env.OngoingProcesses[1:]
process.GetProcessBase().TotalEntitiesOut++
process.GetProcessBase().AccumDuration += entity.GetProcessDuration()
process.GetProcessBase().AvgDuration = process.GetProcessBase().AccumDuration / float64(process.GetProcessBase().TotalEntitiesOut)
if ongoing.Process.GetProcessBase().Forward != nil {
ongoing.Process.GetProcessBase().Forward(entity)
} else if ongoing.Process.GetProcessBase().NextProcess != "" {
env.ForwardTo(entity, ongoing.Process.GetProcessBase().NextProcess)
} else {
// dispose
}
}
// start processes that can be started
for _, process := range env.WatchedProcesses {
env.MaybeStartProcess(process)
}
for key, process := range env.WatchedProcesses {
if process == nil {
delete(env.WatchedProcesses, key)
}
}
sort.Sort(ByDateEnd(env.OngoingProcesses))
sort.Sort(ByNextGen(env.EntitySources))
// Update simulation clock
nextTime = env.EndDate
if len(env.EntitySources) > 0 {
nextTime = min(nextTime, env.EntitySources[0].GetNextGen())
}
if len(env.OngoingProcesses) > 0 {
nextTime = min(nextTime, env.OngoingProcesses[0].DateEnd)
}
}
env.Now = nextTime
if env.StepThrough {
WaitForEnter()
} else if (env.LogLevel == 1) {
progress := env.Now / env.EndDate
newProgressPercent := int(math.Ceil(progress * 100))
if time.Since(env.LastBarRefresh).Seconds() >= 1.0/15.0 && (GetProgressBarSize(progress) > env.ProgressBarSize || env.ProgressPercent != newProgressPercent) {
env.LastBarRefresh = time.Now()
RefreshProgressBar(progress)
env.ProgressBarSize = GetProgressBarSize(progress)
env.ProgressPercent = newProgressPercent
}
} else {
env.Printf[2]("\n")
}
if env.Now >= env.EndDate {
if env.StepThrough {
RefreshProgressBar(1)
}
env.Printf[1]("\n")
env.Printf[1]("[SIMULATION ENDED]\n")
env.Printf[1]("[AVG REPLICATION TIME] %.2fs\n", time.Since(env.RunStart).Seconds())
env.Printf[1]("\n")
return false
} else {
return true
}
}
func (env *Environment) Run() {
env.Begin()
for env.Advance() {}
}
func (env *Environment) PrintProcessesStatistics(groupId string) {
fmt.Printf("[PROCESS STATISTICS] Group: %s\n", groupId)
fmt.Printf("%24s%16s%16s%16s%18s\n", "Process", "Entities In", "Entities Out", "Avg Q Time (s)", "Avg Duration (s)")
for _, process := range env.Processes {
if slices.Contains(process.GetProcessBase().Groups, groupId) {
st := process.GetStatistics()
fmt.Printf("%24.24s%16d%16d%16.2f%18.2f\n", process.GetId(), st.TotalEntitiesIn, process.GetProcessBase().TotalEntitiesOut, st.AvgTimeInQueue, process.GetProcessBase().AvgDuration)
}
}
}
func NewEnvironment() *Environment {
env := &Environment{}
env.Entities = make(map[int]Entity, 0)
env.EntitySources = make([]EntitySource, 0)
env.Resources = make(map[string]Resource, 0)
env.Processes = make([]Process, 0)
env.OngoingProcesses = make([]OngoingProcess, 0)
env.WatchedProcesses = make(map[string]Process)
env.Replications = 1
return env
}