-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_lane_simulation.go
1254 lines (1087 loc) · 37.3 KB
/
multi_lane_simulation.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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"github.com/go-siris/siris/core/errors"
"gonum.org/v1/gonum/stat/distuv"
"gonum.org/v1/gonum/stat/sampleuv"
"log"
"math"
"math/rand"
"strings"
"sync"
"time"
)
type Direction int
const unlikelyIterations = 5
const (
Horizontal Direction = iota
Vertical
)
type AccidentResolution int
const (
Unresolved AccidentResolution = iota
Resolved
ToBeDeleted
)
type Accident struct {
loc *StatefulLocation
resolution AccidentResolution
prevLocationState LocationState
probRestart float64
removalRate float64
}
type Parking struct {
prevLoc *StatefulLocation
car *SmartCar
parkingTimeRate float64
parkingLoc *StatefulLocation
}
type SmartCarState int
const (
Working SmartCarState = iota
Deleted
)
type SmartCar struct {
ID string
Speed float64
X int
Y int
Direction Direction
probMovement float64
carState SmartCarState
slowingDown bool
WaitingTime float64
smartCarLock sync.Mutex
}
func (car *SmartCar) isSlowingDown() bool {
car.smartCarLock.Lock()
defer car.smartCarLock.Unlock()
return car.slowingDown
}
func (car *SmartCar) getSpeed() float64 {
car.smartCarLock.Lock()
defer car.smartCarLock.Unlock()
return car.Speed
}
func (car *SmartCar) setSlowingDown(item bool) {
car.smartCarLock.Lock()
defer car.smartCarLock.Unlock()
car.slowingDown = item
}
func (car *SmartCar) setSpeed(res float64) {
car.smartCarLock.Lock()
defer car.smartCarLock.Unlock()
car.Speed = res
}
type LocationState int
const (
Empty LocationState = 0
Intersection LocationState = 1
LaneLoc LocationState = 2
ParkingLoc LocationState = 3
AccidentLocationState LocationState = 4
CrossWalk LocationState = 5
)
// Location is one spot on a lane
type StatefulLocation struct {
Cars map[string]*SmartCar // Allows for easy removal of the car
LocationState LocationState
X int
Y int
locationLock sync.Mutex
}
func (loc *StatefulLocation) setLocationState(state LocationState) {
loc.locationLock.Lock()
defer loc.locationLock.Unlock()
loc.LocationState = state
}
func (loc *StatefulLocation) getLocationState() LocationState {
loc.locationLock.Lock()
defer loc.locationLock.Unlock()
return loc.LocationState
}
func getNewCarSpeed(speedType CarDistributionType, carSpeedEndRange float64, carSpeed float64, removeUnlikely bool, unlikelyCutoff float64) (float64, float64) {
var speed float64
var prob float64
if speedType == constantDistribution {
speed = 1.0
prob = 1.0
} else if speedType == normalDistribution {
var UnitNormal = distuv.Normal{Mu: carSpeed, Sigma: 1}
speed = UnitNormal.Rand()
prob = UnitNormal.Prob(speed)
} else if speedType == exponentialDistribution {
var exponential = distuv.Exponential{Rate: carSpeed}
speed = getExpRand(carSpeed, unlikelyCutoff, removeUnlikely)
prob = exponential.Prob(speed)
} else if speedType == poissonDistribution {
var poisson = distuv.Poisson{Lambda: carSpeed}
speed = getPoissonRand(carSpeed, unlikelyCutoff, removeUnlikely)
prob = poisson.Prob(speed)
} else if speedType == uniformDistribution {
if carSpeedEndRange == 0 {
carSpeedEndRange = 1
}
speed = UniformRandMinMax(0, carSpeedEndRange)
prob = 1 / carSpeedEndRange
}
return speed, prob
}
type SlowCar struct {
car *SmartCar
oldSpeed float64
slowDownRate float64
}
func (loc *StatefulLocation) canMoveToParking() bool {
state := loc.getLocationState()
return state == LaneLoc || state == CrossWalk || state == AccidentLocationState
}
func (loc *StatefulLocation) addNCars(numCars int,
direction Direction,
probMovement float64,
speedType CarDistributionType,
carSpeedEndRange float64,
carSpeed float64,
unlikely bool, unlikelyCutoff float64) {
for i := 0; i < numCars; i++ {
var id string
if direction == Horizontal {
id = fmt.Sprintf("hcar %d", i)
} else {
id = fmt.Sprintf("vcar %d", i)
}
speed, _ := getNewCarSpeed(speedType, carSpeedEndRange, carSpeed, unlikely, unlikelyCutoff)
loc.Cars[id] = &SmartCar{
ID: id,
Direction: direction,
X: -1, Y: -1,
Speed: speed,
probMovement: probMovement,
carState: Working,
smartCarLock: sync.Mutex{}}
}
}
func (loc *StatefulLocation) noCars() bool {
loc.locationLock.Lock()
defer loc.locationLock.Unlock()
return len(loc.Cars) == 0
}
func (loc *StatefulLocation) isEmpty() bool {
state := loc.getLocationState()
return loc.noCars() &&
(state == LaneLoc ||
state == Intersection ||
state == CrossWalk)
}
func (loc *StatefulLocation) removeCar(car *SmartCar) {
loc.locationLock.Lock()
defer loc.locationLock.Unlock()
delete(loc.Cars, car.ID)
}
func (loc *StatefulLocation) getCar(del bool) (*SmartCar) {
loc.locationLock.Lock()
defer loc.locationLock.Unlock()
var currCar *SmartCar
for k, v := range loc.Cars {
if del {
delete(loc.Cars, k)
}
currCar = v
break
}
return currCar
}
func (loc *StatefulLocation) addCar(car *SmartCar) {
loc.locationLock.Lock()
car.smartCarLock.Lock()
defer car.smartCarLock.Unlock()
defer loc.locationLock.Unlock()
car.X = loc.X
car.Y = loc.Y
loc.Cars[car.ID] = car
}
type CarDistributionType int
const (
exponentialDistribution CarDistributionType = iota
normalDistribution
poissonDistribution
constantDistribution
uniformDistribution
)
func convertToCarDistributionType(item int) CarDistributionType {
switch item {
case 0:
return exponentialDistribution
case 1:
return normalDistribution
case 2:
return poissonDistribution
case 3:
return constantDistribution
case 4:
return uniformDistribution
}
return uniformDistribution
}
type LaneChoice int
const (
trafficBasedChoice LaneChoice = iota
uniformLaneChoice
)
func convertIntLaneChoice(item int) LaneChoice {
switch item {
case 0:
return uniformLaneChoice
case 1:
return trafficBasedChoice
}
return uniformLaneChoice
}
type GeneralLaneSimulationConfig struct {
sizeOfLane int
numVerticalLanes int
numHorizontalLanes int
inAlpha float64
outBeta float64
carMovementP float64
// num cars to through in each bin
numHorizontalCars int
numVerticalCars int
// in lane movement type
inLaneChoice LaneChoice
outLaneChoice LaneChoice
// multiple lanes
probSwitchingLanes float64
laneSwitchChoice LaneChoice
// Handles accidents
accidentProb float64
carRemovalRate float64 // exponential time
carRestartProb float64 // car restart rate
// Handles different car rates
carClock float64 // for uniform, defaults to start of range
carSpeedUniformEndRange float64
CarDistributionType CarDistributionType
reSampleSpeedEveryClk bool
// handles cars going to fast
probPolicePullOverProb float64
speedBasedPullOver bool
// parking
parkingEnabled bool
distractionRate float64 // poisson to get into parking
parkingTimeRate float64 // how long should car stay in parking
crossWalkCutoff int /// numbers of cars in parking
// crosswalk
crossWalkEnabled bool
crossWalkSlowDownRate float64
pedestrianDeathAccidentProb float64 //
// intersection
probEnteringIntersection float64
intersectionAccidentProb float64 // if unspecified the same as regular accident probability
accidentScaling bool // retry for accident based on the number of cars there
slowDownSpeed float64
removeUnlikelyEvents bool
unlikelyCutoff float64
// scales poisson rate by certain amount
}
func DefaultGeneralLaneConfig() *GeneralLaneSimulationConfig {
config := GeneralLaneSimulationConfig{}
config.sizeOfLane = 10
config.numHorizontalLanes = 1
config.numVerticalLanes = 1
config.inAlpha = 1
config.outBeta = 1
config.inLaneChoice = uniformLaneChoice
config.outLaneChoice = uniformLaneChoice
config.numHorizontalCars = 10
config.numVerticalCars = 10
config.carMovementP = 0.5
config.probSwitchingLanes = 0
config.accidentProb = 0
config.carClock = 1
config.CarDistributionType = constantDistribution
config.reSampleSpeedEveryClk = false
config.parkingEnabled = false
config.probEnteringIntersection = 1
config.parkingTimeRate = 1
config.accidentScaling = false
config.crossWalkCutoff = 2
config.intersectionAccidentProb = 0
config.removeUnlikelyEvents = true
config.unlikelyCutoff = 0.05
return &config
}
// GeneralLaneSimulation handles a general simulation with n horizontal lanes and n vertical lanes and intersections
type GeneralLaneSimulation struct {
Simulation
Locations [][]*StatefulLocation
InHorizontalRoot *StatefulLocation
InVerticalRoot *StatefulLocation
OutHorizontalRoot *StatefulLocation
OutVerticalRoot *StatefulLocation
config *GeneralLaneSimulationConfig
moveCarsIn chan Direction
moveCarsOut chan Direction
carClock chan *SmartCar
crossWalkClock chan *SlowCar
accidentChan chan *Accident
parkingReturn chan *Parking
runningSimulationLock sync.Mutex
numAccidents int
}
func (sim *GeneralLaneSimulation) isRunningSimulation() bool {
sim.runningSimulationLock.Lock()
defer sim.runningSimulationLock.Unlock()
return sim.runningSimulation
}
func (sim *GeneralLaneSimulation) setRunningSimulation(res bool) {
sim.runningSimulationLock.Lock()
defer sim.runningSimulationLock.Unlock()
sim.runningSimulation = res
}
type JsonGeneralLocation struct {
Cars map[string]SmartCar `json:"cars"` // Allows for easy removal of the car
LocationState int `json:"state"`
}
type JsonGeneralLaneSimulation struct {
Locations [][]JsonGeneralLocation `json:"locations"`
}
func (sim *GeneralLaneSimulation) getJsonRepresentation() JsonGeneralLaneSimulation {
jsonGen := JsonGeneralLaneSimulation{Locations: make([][]JsonGeneralLocation, sim.config.sizeOfLane)}
for i := 0; i < sim.config.sizeOfLane; i++ {
jsonGen.Locations[i] = make([]JsonGeneralLocation, sim.config.sizeOfLane)
for j := 0; j < sim.config.sizeOfLane; j++ {
jsonGen.Locations[i][j] = JsonGeneralLocation{}
jsonGen.Locations[i][j].Cars = make(map[string]SmartCar, 0)
jsonGen.Locations[i][j].LocationState = int(sim.Locations[i][j].getLocationState())
loc := sim.Locations[i][j]
loc.locationLock.Lock()
cars := loc.Cars
for k, v := range cars {
v.smartCarLock.Lock()
waitingTime := math.Floor(v.WaitingTime * 100)/100
speed := math.Floor(v.Speed * 100)/100
v.smartCarLock.Unlock()
jsonGen.Locations[i][j].Cars[k] = SmartCar{ID: v.ID, WaitingTime: waitingTime, Speed: speed}
}
loc.locationLock.Unlock()
}
}
return jsonGen
}
func (sim *GeneralLaneSimulation) String() (string) {
var b strings.Builder
fmt.Fprintf(&b, RightPad2Len("", "-", 20)+" \n")
fmt.Fprintf(&b, " horizontalInBin ")
for car := range sim.InHorizontalRoot.Cars {
fmt.Fprintf(&b, car+" ")
}
fmt.Fprintf(&b, " horizontalOutBin ")
for car := range sim.OutHorizontalRoot.Cars {
fmt.Fprintf(&b, car+" ")
}
fmt.Fprintf(&b, "\n")
fmt.Fprintf(&b, " verticalInBin ")
for car := range sim.InVerticalRoot.Cars {
fmt.Fprintf(&b, car+" ")
}
fmt.Fprintf(&b, " verticalOutBin ")
for car := range sim.OutVerticalRoot.Cars {
fmt.Fprintf(&b, car+" ")
}
fmt.Fprintf(&b, "\n")
for i := 0; i < sim.config.sizeOfLane; i++ {
for j := 0; j < sim.config.sizeOfLane; j++ {
loc := sim.Locations[i][j]
loc.locationLock.Lock()
if len(loc.Cars) == 0 {
fmt.Fprintf(&b, RightPad2Len("", "_", 8)+" ")
} else {
car := loc.getCar(false)
fmt.Fprintf(&b, RightPad2Len(car.ID, " ", 8)+" ")
}
loc.locationLock.Unlock()
}
fmt.Fprintf(&b, "\n")
}
s := b.String() // no copying
return s
}
func medianBasedRange(laneSize int, numLanes int) (int, int) {
return int(laneSize/2 - (numLanes-1)/2), int(laneSize/2 + (numLanes-1)/2)
}
func (sim *GeneralLaneSimulation) horizontalIndexRange() (int, int) {
config := sim.config
if config.numHorizontalLanes%2 == 0 {
left, right := medianBasedRange(config.sizeOfLane-1, config.numHorizontalLanes)
return left - 1, right
}
return medianBasedRange(config.sizeOfLane, config.numHorizontalLanes)
}
func (sim *GeneralLaneSimulation) verticalIndexRange() (int, int) {
config := sim.config
if config.numVerticalLanes%2 == 0 {
left, right := medianBasedRange(config.sizeOfLane-1, config.numVerticalLanes)
return left - 1, right
}
return medianBasedRange(config.sizeOfLane, config.numVerticalLanes)
}
func (sim *GeneralLaneSimulation) allCarsMovedIn() (bool) {
sim.OutHorizontalRoot.locationLock.Lock()
sim.OutVerticalRoot.locationLock.Lock()
defer sim.OutHorizontalRoot.locationLock.Unlock()
defer sim.OutVerticalRoot.locationLock.Unlock()
if sim.config.numHorizontalLanes > 0 && len(sim.OutHorizontalRoot.Cars) != sim.config.sizeOfLane {
return false
}
if sim.config.numVerticalLanes > 0 && len(sim.OutVerticalRoot.Cars) != sim.config.sizeOfLane {
return false
}
return true
}
type CheckLocationType int
const (
Open CheckLocationType = iota
NotOpen
AllLocationTypes
)
func (loc *StatefulLocation) shouldCheckForMovingIn(checkLocationType CheckLocationType) bool {
return checkLocationType == Open && loc.isEmpty() || checkLocationType == NotOpen && !loc.isEmpty() || checkLocationType == AllLocationTypes
}
func (sim *GeneralLaneSimulation) getHorizontalLanesAtIndex(index int, checkLocationType CheckLocationType) []*StatefulLocation {
openLanes := make([]*StatefulLocation, 0)
low, high := sim.horizontalIndexRange()
for i := low; i <= high; i++ {
loc := sim.Locations[i][index]
if loc.shouldCheckForMovingIn(checkLocationType) {
openLanes = append(openLanes, loc)
}
}
return openLanes
}
func (sim *GeneralLaneSimulation) getVerticalLanesAtIndex(index int, checkLocationType CheckLocationType) []*StatefulLocation {
openLanes := make([]*StatefulLocation, 0)
low, high := sim.verticalIndexRange()
for i := low; i <= high; i++ {
loc := sim.Locations[index][i]
if loc.shouldCheckForMovingIn(checkLocationType) {
openLanes = append(openLanes, loc)
}
}
return openLanes
}
func initMultiLaneSimulation(config *GeneralLaneSimulationConfig) (*GeneralLaneSimulation, error) {
simulation := GeneralLaneSimulation{config: config}
sizeOfLane := simulation.config.sizeOfLane
numVerticalLanes := simulation.config.numVerticalLanes
numHorizontalLanes := simulation.config.numHorizontalLanes
if sizeOfLane-2 <= 0 {
return nil, errors.New("The lane must be 2 spots")
}
if !(sizeOfLane > numVerticalLanes && sizeOfLane > numHorizontalLanes) {
return nil, errors.New("The number of vertical/horizontal lanes cannot be more than size of lane")
}
locations := make([][] *StatefulLocation, sizeOfLane)
for i := range locations {
locations[i] = make([]*StatefulLocation, sizeOfLane)
for j := 0; j < sizeOfLane; j++ {
locations[i][j] = &StatefulLocation{LocationState: Empty, Cars: make(map[string]*SmartCar), locationLock: sync.Mutex{}}
locations[i][j].X = i
locations[i][j].Y = j
}
}
// Initialize horizontal locations
horizontalStartIndex, horizontalEndIndex := simulation.horizontalIndexRange()
for i := horizontalStartIndex; i <= horizontalEndIndex; i++ {
for j := 0; j < sizeOfLane; j++ {
locations[i][j].LocationState = LaneLoc
}
}
if numHorizontalLanes > 0 {
horizontalRoot := StatefulLocation{Cars: make(map[string]*SmartCar, 0)}
horizontalRoot.addNCars(simulation.config.numHorizontalCars,
Horizontal,
simulation.config.carMovementP,
simulation.config.CarDistributionType,
simulation.config.carSpeedUniformEndRange,
simulation.config.carClock,
simulation.config.removeUnlikelyEvents,
simulation.config.unlikelyCutoff)
simulation.InHorizontalRoot = &horizontalRoot
simulation.OutHorizontalRoot = &StatefulLocation{Cars: make(map[string]*SmartCar, 0), X: -1, Y: -1}
}
// Initialize vertical locations
verticalStartIndex, verticalEndIndex := simulation.verticalIndexRange()
for i := 0; i < sizeOfLane; i++ {
for j := verticalStartIndex; j <= verticalEndIndex; j++ {
if locations[i][j].LocationState == LaneLoc {
locations[i][j].LocationState = Intersection
// If it is already on the horizontal path then send in update
} else {
locations[i][j].LocationState = LaneLoc
}
}
}
simulation.Locations = locations
if numVerticalLanes > 0 {
verticalRoot := StatefulLocation{Cars: make(map[string]*SmartCar, 0)}
verticalRoot.addNCars(simulation.config.numVerticalCars,
Vertical,
simulation.config.carMovementP,
simulation.config.CarDistributionType,
simulation.config.carSpeedUniformEndRange, simulation.config.carClock, simulation.config.removeUnlikelyEvents,
simulation.config.unlikelyCutoff)
simulation.InVerticalRoot = &verticalRoot
simulation.OutVerticalRoot = &StatefulLocation{Cars: make(map[string]*SmartCar, 0), X: -1, Y: -1}
}
// Note: Decided to only use one position for parking
// Initialize ParkingLoc Locations
if simulation.config.parkingEnabled {
for i := 0; i < sizeOfLane; i++ {
//verticalParkingStart := verticalStartIndex - 1
verticalParkingEnd := verticalEndIndex + 1
//simulation.addParkingIfInBounds(verticalParkingStart, i)
simulation.addParkingIfInBounds(verticalParkingEnd, i)
//horizontalParkingStart := horizontalStartIndex - 1
horizontalParkingEnd := horizontalEndIndex + 1
//simulation.addParkingIfInBounds(i, horizontalParkingStart)
simulation.addParkingIfInBounds(i, horizontalParkingEnd)
}
}
simulation.moveCarsIn = make(chan Direction)
simulation.moveCarsOut = make(chan Direction)
simulation.carClock = make(chan *SmartCar)
simulation.accidentChan = make(chan *Accident)
simulation.parkingReturn = make(chan *Parking)
simulation.crossWalkClock = make(chan *SlowCar)
simulation.setRunningSimulation(false)
simulation.drawUpdateChan = make(chan bool)
simulation.runningSimulationLock = sync.Mutex{}
return &simulation, nil
}
func normalize(arr []float64, totalCount float64) []float64 {
weights := make([]float64, 0)
for _, item := range arr {
weights = append(weights, item/totalCount)
}
return weights
}
func (sim *GeneralLaneSimulation) addParkingIfInBounds(i int, j int) {
if !isInBounds(i, sim.config.sizeOfLane) || !isInBounds(j, sim.config.sizeOfLane) {
return
}
location := sim.Locations[i][j]
state := location.getLocationState()
if state == Intersection || state == LaneLoc {
return
}
location.setLocationState(ParkingLoc)
}
func isInBounds(index int, size int) bool {
return index >= 0 && index < size
}
func (sim *GeneralLaneSimulation) countNumCarsNearby(loc *StatefulLocation) int {
count := 1
if isInBounds(loc.X+1, sim.config.sizeOfLane) && !sim.Locations[loc.X+1][loc.Y].isEmpty() {
count++
}
if isInBounds(loc.X-1, sim.config.sizeOfLane) && !sim.Locations[loc.X-1][loc.Y].isEmpty() {
count++
}
if isInBounds(loc.Y+1, sim.config.sizeOfLane) && !sim.Locations[loc.X-1][loc.Y+1].isEmpty() {
count++
}
if isInBounds(loc.Y-1, sim.config.sizeOfLane) && !sim.Locations[loc.X-1][loc.Y-1].isEmpty() {
count++
}
return count
}
func (sim *GeneralLaneSimulation) selectBasedOnTraffic(locs []*StatefulLocation, direction Direction) *StatefulLocation {
weights := make([]float64, 0)
totalCount := 0.0
var i int
for _, item := range locs {
if direction == Horizontal {
i = item.X
} else {
i = item.Y
}
count := 0.0
for j := 0; j < sim.config.sizeOfLane; j++ {
if direction == Horizontal && !sim.Locations[i][j].isEmpty() ||
direction == Vertical && !sim.Locations[j][i].isEmpty() {
count++
}
}
weights = append(weights, count)
totalCount += count
}
weights = normalize(weights, totalCount)
w := sampleuv.NewWeighted(
weights,
nil,
)
i, _ = w.Take()
return locs[i%len(locs)]
}
func (sim *GeneralLaneSimulation) RandomlyPickLocation(lanes []*StatefulLocation, direction Direction, choice LaneChoice) *StatefulLocation {
if choice == uniformLaneChoice {
return lanes[rand.Intn(len(lanes))]
}
return sim.selectBasedOnTraffic(lanes, direction)
}
func (singleSim *GeneralLaneSimulation) close() {
singleSim.setRunningSimulation(false)
}
// RunSingleLaneSimulation runs the simulation such that all the cars from bin 0 move to the last bin
func RunGeneralSimulation(simulation *GeneralLaneSimulation) {
defer simulation.close()
simulation.setRunningSimulation(true)
moveCarsIn := simulation.moveCarsIn
moveCarsOut := simulation.moveCarsOut
carClock := simulation.carClock
accidentChan := simulation.accidentChan
parkingChan := simulation.parkingReturn
crossWalkClock := simulation.crossWalkClock
drawUpdateChan := simulation.drawUpdateChan
go moveCarsThroughBinsDirection(moveCarsIn, Horizontal, simulation, simulation.config.inAlpha,
simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
go moveCarsThroughBinsDirection(moveCarsOut, Horizontal, simulation, simulation.config.outBeta,
simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
go moveCarsThroughBinsDirection(moveCarsIn, Vertical, simulation, simulation.config.inAlpha,
simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
go moveCarsThroughBinsDirection(moveCarsOut, Vertical, simulation, simulation.config.outBeta,
simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
log.Println("starting simulation")
for {
if !simulation.isRunningSimulation() {
return
}
if simulation.isCompleted() {
return
}
select {
case carInDirection := <-moveCarsIn:
if !simulation.isRunningSimulation() {
return
}
openLanes := make([]*StatefulLocation, 0)
var root *StatefulLocation
if carInDirection == Horizontal {
openLanes = simulation.getHorizontalLanesAtIndex(0, Open)
root = simulation.InHorizontalRoot
} else if carInDirection == Vertical {
openLanes = simulation.getVerticalLanesAtIndex(0, Open)
root = simulation.InVerticalRoot
}
if len(openLanes) == 0 {
break
}
chosenLoc := simulation.RandomlyPickLocation(openLanes, carInDirection, simulation.config.inLaneChoice)
currCar := root.getCar(true) // allows for picking any car from the pool
if currCar == nil {
break
}
chosenLoc.addCar(currCar)
log.Println("placing car ", currCar.ID, "at", currCar.X, currCar.Y)
go MoveSmartCarInLane(currCar, carClock, chosenLoc, simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
drawUpdateChan <- true
break
case carOutDirection := <-moveCarsOut:
if !simulation.isRunningSimulation() {
return
}
openLanes := make([]*StatefulLocation, 0)
var root *StatefulLocation
lastIndex := simulation.config.sizeOfLane - 1
if carOutDirection == Horizontal {
openLanes = simulation.getHorizontalLanesAtIndex(lastIndex, NotOpen)
root = simulation.OutHorizontalRoot
} else if carOutDirection == Vertical {
openLanes = simulation.getVerticalLanesAtIndex(lastIndex, NotOpen)
root = simulation.OutVerticalRoot
}
if len(openLanes) == 0 {
break
}
chosenLoc := simulation.RandomlyPickLocation(openLanes, carOutDirection, simulation.config.outLaneChoice)
currCar := chosenLoc.getCar(true) // allows for removing any car from the pool
if currCar == nil {
break
}
root.addCar(currCar)
log.Println("took out car", currCar.ID, currCar.X, currCar.Y)
drawUpdateChan <- true
break
case car := <-carClock:
log.Println("recieved", car.ID)
if !simulation.isRunningSimulation() {
return
}
if car == nil {
break
}
car.smartCarLock.Lock()
x := car.X
y := car.Y
direction := car.Direction
car.smartCarLock.Unlock()
if x == -1 || y == -1 ||
!isInBounds(x, simulation.config.sizeOfLane) ||
!isInBounds(y, simulation.config.sizeOfLane) {
log.Println("invalid bounds", car.ID)
break
}
currLoc := simulation.Locations[x][y]
var nextLoc *StatefulLocation
switchLanes := UniformRand() < simulation.config.probSwitchingLanes
if direction == Horizontal {
if y+1 == simulation.config.sizeOfLane {
log.Println("at the end", car.ID)
break
}
if !switchLanes {
nextLoc = simulation.Locations[x][y+1]
} else {
log.Println("attempting lane switch", car.ID)
var openLanes []*StatefulLocation
openLanes = simulation.getHorizontalLanesAtIndex(y+1, AllLocationTypes)
nextLoc = simulation.RandomlyPickLocation(openLanes, direction, simulation.config.laneSwitchChoice) // TODO consider whether the car can pick its own position to switch to
}
} else if direction == Vertical {
if x+1 == simulation.config.sizeOfLane {
log.Println("at the end", car.ID)
break
}
if !switchLanes {
nextLoc = simulation.Locations[x+1][y]
} else {
log.Println("attempting lane switch", car.ID)
var openLanes []*StatefulLocation
openLanes = simulation.getVerticalLanesAtIndex(x+1, AllLocationTypes)
nextLoc = simulation.RandomlyPickLocation(openLanes, direction, simulation.config.laneSwitchChoice)
}
}
if currLoc.getLocationState() == AccidentLocationState {
log.Println("current location accident state", car.ID)
break
}
if nextLoc.getLocationState() == AccidentLocationState {
log.Println("next location accident state", car.ID)
go MoveSmartCarInLane(car, carClock, currLoc, simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff) // just try again later
break
}
if simulation.config.parkingEnabled && currLoc.canMoveToParking() { // parking can only happen on regular lane
distractionOccurs := getPoissonRand(1, simulation.config.unlikelyCutoff, simulation.config.removeUnlikelyEvents) < simulation.config.distractionRate
if distractionOccurs {
var parkingLoc *StatefulLocation
if direction == Horizontal {
_, bottomEnd := simulation.horizontalIndexRange()
if isInBounds(bottomEnd+1, simulation.config.sizeOfLane) {
parkingLoc = simulation.Locations[bottomEnd+1][y]
}
} else {
_, bottomEnd := simulation.verticalIndexRange()
if isInBounds(bottomEnd+1, simulation.config.sizeOfLane) {
parkingLoc = simulation.Locations[x][bottomEnd+1]
}
}
if parkingLoc != nil {
currLoc.removeCar(car)
parkingLoc.addCar(car)
go HandleParking(&Parking{prevLoc: currLoc, car: car, parkingTimeRate: simulation.config.parkingTimeRate, parkingLoc: parkingLoc}, parkingChan)
simulation.AddCrossWalkIfNeeded(parkingLoc, direction)
log.Println("handle parking", car.ID)
break
}
}
}
var accidentOccurs = false
if !nextLoc.noCars() {
randPoisson := getPoissonRand(1, simulation.config.unlikelyCutoff, simulation.config.removeUnlikelyEvents)
accidentOccurs = randPoisson < simulation.config.accidentProb
if nextLoc.getLocationState() == Intersection {
accidentOccurs = randPoisson < simulation.config.intersectionAccidentProb
}
//log.Println("next Car has more than 1", accidentOccurs, poisson.Prob(poisson.Rand()))
if simulation.config.accidentScaling {
numCarsNearby := simulation.countNumCarsNearby(nextLoc)
for i := 0; i < numCarsNearby; i++ {
if accidentOccurs {
break
}
accidentOccurs = randPoisson < simulation.config.accidentProb
randPoisson = getPoissonRand(1, simulation.config.unlikelyCutoff, simulation.config.removeUnlikelyEvents)
}
}
if !accidentOccurs {
log.Println("car is already there")
go MoveSmartCarInLane(car, carClock, currLoc, simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff) // just try again with another exponential clock
break
}
// If next position blocked, attempt to move again on a exponential clock
}
if !accidentOccurs && nextLoc.getLocationState() == CrossWalk {
accidentOccurs = getPoissonRand(1, simulation.config.unlikelyCutoff, simulation.config.removeUnlikelyEvents) < simulation.config.pedestrianDeathAccidentProb
}
if accidentOccurs {
simulation.runningSimulationLock.Lock()
simulation.numAccidents += 1
simulation.runningSimulationLock.Unlock()
prevLocState := nextLoc.getLocationState()
nextLoc.setLocationState(AccidentLocationState)
currLoc.removeCar(car)
nextLoc.addCar(car)
go HandleAccident(&Accident{prevLocationState: prevLocState, loc: nextLoc, resolution: Unresolved, removalRate: simulation.config.carRemovalRate, probRestart: simulation.config.carRestartProb}, accidentChan, simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff)
drawUpdateChan <- true
log.Println("accident occured", car.ID)
break
}
if !(UniformRand() < simulation.config.probEnteringIntersection) { // doesn't enter intersection try again
log.Println("unable to enter intersection", car.ID)
go MoveSmartCarInLane(car, carClock, currLoc, simulation.config.removeUnlikelyEvents, simulation.config.unlikelyCutoff) // just try again with another exponential clock
break
}
log.Println("removed car from currLoc", car.ID)
currLoc.removeCar(car)
pollicePullsOver := UniformRand() < simulation.config.probPolicePullOverProb
if simulation.config.speedBasedPullOver {
_, prob := getNewCarSpeed(simulation.config.CarDistributionType,
simulation.config.carSpeedUniformEndRange,
simulation.config.carClock,
simulation.config.removeUnlikelyEvents,
simulation.config.unlikelyCutoff)
if simulation.config.probPolicePullOverProb < prob {
pollicePullsOver = true
log.Println("police pulls over", car.ID)
}
}
// Re sample if config is available