-
Notifications
You must be signed in to change notification settings - Fork 1
/
mp.py
executable file
·2667 lines (2587 loc) · 95.3 KB
/
mp.py
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
#!/usr/bin/python
#Copyright 2018 freevariable (https://github.com/freevariable)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import redis,random,math,sys,uuid
import time,datetime,getopt,flask,json
from concurrent.futures import ThreadPoolExecutor
import cPickle as pickle
redisDB=0
live=[]
schedOrders=[]
saveOrder={}
version="148"
minVersion="146"
hasTime=False
hasServices=False
startTime=datetime.datetime.strptime("001d06h30m00s","%jd%Hh%Mm%Ss")
SAVEFREQ=7200 # Save sim to saves/ dir every SAVEFREQ seconds
CLOCKHEADWAY=35 # in secs
ADHESIVEFACTOR=0.25
G=9.81 # N/kg
MULTICORE=False
CORES=1
WHEELFACTOR=G*0.025
DUMPDATA=True
TPROGRESS=False
STAPROGRESS=True
ACCSIGMA=0.0027
ACC=1.35 # m/s2 au demarrage
ALAW='EMU1' # law governing acc
# EMU1 is for MP05 EMUs
# STM1 is for steam engines
WEIGHT=143000.0 #in kg
PAXWEIGHT=75.0 #in kg
MAXPAX=698
UNITS='metric'
MPH=1.60934 #mph to kmh
POWER=2000000.0 #in W
VMX=80.0 #km/h max speed
VMX2=(VMX*VMX)/12.96 # VMX squared, in m/s
AIRFACTOR=0.368888/VMX2
TLENGTH=90.0 #length in m
DCC=-1.10 #m/s2
EMR=-1.50 #m/s2 emergency dcc
DLAW='EMU1' # law governing dcc between t=0 and t=tpoint
# EMU1 is for MP05 EMUs
SYNCPERIOD=0.5 # how often (in s) do we sync multicores
CYCLEPP=100 # how many ticks we calculate between two multicore syncs
CYCLE=CYCLEPP/SYNCPERIOD # how many ticks we calculate per second
# increasing cycle beyond 200 does not improve precision by more that 1 sec for the end-to-end journey
T0=0.0
VTHRESH=0.999
CONTROL="SIG" # two mutually exclusive values: SIG or TVM
REALTIME=False
SIGPOLL=1.0 # check for sig clearance (in sec)
tivs={}
stas={}
srvs={}
sigs={}
trss={}
conf={}
trs=[]
remlist=[]
segs={}
ncyc=0
t=0.0
maxLine=160.0 # max speed allowed on a line, km/h
exitCondition=False
projectDir='/'
schedulesDir='schedules/'
segmentsDir='segments/'
def initConfig():
f=open(projectDir+"routeConfig.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip().split(" ")
ss.append(s)
cnt=cnt+1
return ss
def initSRVs():
f=open(projectDir+"services.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip().split(" ")
ss.append(s)
cnt=cnt+1
return ss
def initSEGs():
f=open(projectDir+"segments.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip()
ss.append(s)
cnt=cnt+1
return ss
def initTIVs():
global segs
global conf
gts={}
for se in segs:
f=open(projectDir+segmentsDir+se+"/TIVs.txt","r")
tsf=f.readlines()
ts=[]
f.close()
cnt=0
for t in tsf:
if (t[0]!='#'):
t=t.rstrip().split(" ")
if conf['units']=='imperial':
t[0]=str(float(t[0])*MPH) #mileposts=>pK
t[1]=str(float(t[1])*MPH) #mph=>kmh
ts.append(t)
cnt=cnt+1
gts[se]=ts
return gts
def initStock():
f=open(projectDir+stockName,"r")
tsf=f.readlines()
ts=[]
f.close()
cnt=0
for t in tsf:
if (t[0]!='#'):
t=t.rstrip().split(" ")
ts.append(t)
cnt=cnt+1
return ts
def initSchedule():
global hasTime
global startTime
f=open(projectDir+schedulesDir+scheduleName,"r")
tsf=f.readlines()
ts=[]
f.close()
for t in tsf:
if (t[0]!='#'):
t=t.rstrip().split(" ")
if t[0]=='Time':
hasTime=True
auxT="001d"+t[1]
startTime=datetime.datetime.strptime(auxT,"%jd%Hh%Mm%Ss")
else:
ts.append(t)
return ts
def initCRVs():
global segs
global conf
gts={}
for se in segs:
f=open(projectDir+segmentsDir+se+"/CRVs.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip().split(" ")
if conf['units']=='imperial':
s[0]=str(float(s[0])*MPH) #miles=>pK
ss.append(s)
cnt=cnt+1
gts[se]=ss
return gts
def initGRDs():
global segs
global conf
gts={}
for se in segs:
f=open(projectDir+segmentsDir+se+"/GRDs.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip().split(" ")
if conf['units']=='imperial':
s[0]=str(float(s[0])*MPH) #miles=>pK
ss.append(s)
cnt=cnt+1
gts[se]=ss
return gts
def initSTAs():
global segs
global conf
gts={}
for se in segs:
f=open(projectDir+segmentsDir+se+"/STAs.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf:
if (s[0]!='#'):
s=s.rstrip().split(" ")
if conf['units']=='imperial':
s[0]=str(float(s[0])*MPH) #milepost=>pK
ss.append(s)
cnt=cnt+1
gts[se]=ss
return gts
def initSIGs():
global segs
global conf
gts={}
for se in segs:
f=open(projectDir+segmentsDir+se+"/SIGs.txt","r")
ssf=f.readlines()
ss=[]
f.close()
cnt=0
for s in ssf: # FIRST pass
redisSIG=""
if (s[0]!='#'):
s=s.rstrip().split(" ")
if conf['units']=='imperial':
s[0]=str(float(s[0])*MPH) #mile=>pK
if (len(s)<=2):
s.append('1') # this is a type 1 sig by default
redisSIG="green"
else:
if ((s[2]=='1')or (s[2]=='6')): # type 1 or 6
redisSIG="green"
elif (s[2]=='4C'): #type 4C
redisSIG="green"
if (len(s)!=6):
print "FATAL: type 4C sig requires 6 x verb:noun"
print s
print len(s)
sys.exit()
verbnoun=s[3].split(":")
if verbnoun[0]=="Main":
if not __debug__:
print "switch:"+s[1]+" main branch and default set to: "+verbnoun[1]
r.set("switch:"+s[1]+":mainPosition",verbnoun[1])
r.set("switch:"+s[1]+":position",verbnoun[1])
if se==verbnoun[1]:
redisSIG="green"
verbnoun=s[4].split(":")
if verbnoun[0]=="Branch":
if not __debug__:
print "switch:"+s[1]+" branch set to: "+verbnoun[1]
r.set("switch:"+s[1]+":branchPosition",verbnoun[1])
if se==verbnoun[1]:
redisSIG="red"
verbnoun=s[5].split(":")
if verbnoun[0]=="BranchOrientation":
if not __debug__:
print "switch:"+s[1]+" branch orientation set to: "+verbnoun[1]
r.set("switch:"+s[1]+":branchOrientation",verbnoun[1])
elif (s[2]=='4D'): #type 4D
redisSIG="green"
if (len(s)!=6):
print "FATAL: type 4D sig requires 6 x verb:noun"
print s
print len(s)
sys.exit()
verbnoun=s[3].split(":")
if verbnoun[0]=="Main":
if not __debug__:
print "switch:"+s[1]+" main branch and default set to: "+verbnoun[1]
r.set("switch:"+s[1]+":mainPosition",verbnoun[1])
r.set("switch:"+s[1]+":position",verbnoun[1])
verbnoun=s[4].split(":")
if verbnoun[0]=="Branch":
if not __debug__:
print "switch:"+s[1]+" branch set to: "+verbnoun[1]
r.set("switch:"+s[1]+":branchPosition",verbnoun[1])
verbnoun=s[5].split(":")
if verbnoun[0]=="BranchOrientation":
if not __debug__:
print "switch:"+s[1]+" branch orientation set to: "+verbnoun[1]
r.set("switch:"+s[1]+":branchOrientation",verbnoun[1])
elif (s[2]=='2'): #type 2
redisSIG="red"
if (len(s)!=6):
print "FATAL: type 2 sig requires 3 x verb:noun"
print s
print len(s)
sys.exit()
verbnoun=s[3].split(":")
if verbnoun[0]=="Reverse":
if not __debug__:
print "switch:"+s[1]+" reverse set to: "+verbnoun[1]
r.set("switch:"+s[1]+":reversePosition",verbnoun[1])
else:
print "FATAL: unkwnown Verb "+ verbnoun[0]+". Reverse was expected."
sys.exit()
verbnoun=s[4].split(":")
if verbnoun[0]=="Forward":
if not __debug__:
print "switch:"+s[1]+" forward set to: "+verbnoun[1]
r.set("switch:"+s[1]+":forwardPosition",verbnoun[1])
else:
print "FATAL: unkwnown Verb "+ verbnoun[0]
sys.exit()
verbnoun=s[5].split(":")
if verbnoun[0]=="Default":
if not __debug__:
print "switch:"+s[1]+" current set to: "+verbnoun[1]
r.set("switch:"+s[1]+":position",verbnoun[1])
else:
print "FATAL: unkwnown Verb "+ verbnoun[0]
sys.exit()
if (len(redisSIG)>2):
r.set("sig:"+se+":"+s[1],redisSIG)
ss.append(s)
cnt=cnt+1
prevs=None
if not __debug__:
print "______"+se+"_______"
cnt=0
for s in ss: # SECOND PASS
aligned=False
if ((s[2]=='4D') or (s[2]=='4C')): # type 4 SIG
k=r.get("switch:"+s[1]+":position")
kMain=r.get("switch:"+s[1]+":mainPosition")
if not __debug__:
print "switch of sig "+s[1]+" is in position "+k
if (k==se):
if not __debug__:
print " switch of sig "+s[1]+" is aligned to segment"
aligned=True
if (cnt<len(ss)-1):
if not __debug__:
print " switch of sig "+s[1]+" has a next sig in current seg: "+ss[cnt+1][1]+" of type: "+ss[cnt+1][2]
if prevs is not None:
if not __debug__:
print " switch of sig "+s[1]+" has a prev sig: "+prevs[1]+" of type: "+prevs[2]
if (s[2]=='4D'):
r.set("switch:"+s[1]+":mainPrevSig",cnt-1)
if (s[2]=='4C'):
if se==kMain:
r.set("switch:"+s[1]+":mainPrevSig",cnt-1)
else:
r.set("switch:"+s[1]+":branchPrevSig",cnt-1)
if ((s[2]=='4D') and (prevs[2]!='1')):
print "FATAL: a sig type 4D must be preceded by a type 1 or no sig!"
sys.exit()
if ((s[2]=='4C') and (prevs[2]!='6')):
print "FATAL: a sig type 4C must be preceded by a type 6!"
sys.exit()
k1=r.get("sig:"+se+":"+prevs[1])
if k1 is None:
if (aligned==True):
r.set("sig:"+se+":"+prevs[1],"green")
else:
r.set("sig:"+se+":"+prevs[1],"yellow")
else:
if k1=='green':
if (aligned==False):
r.set("sig:"+se+":"+prevs[1],"yellow")
k1=r.get("sig:"+se+":"+prevs[1])
if not __debug__:
print " prev color set to: "+k1
else:
if not __debug__:
print " (switch has no prev)"
if (s[2]=='2'): # type 2 SIG
k=r.get("switch:"+s[1]+":position")
if not __debug__:
print "switch of sig "+s[1]+" is in position "+k
if (k==se):
if not __debug__:
print " switch of sig "+s[1]+" is aligned to segment"
aligned=True
if (cnt<len(ss)-1):
if not __debug__:
print " switch of sig "+s[1]+" has a next sig: "+ss[cnt+1][1]+" of type: "+ss[cnt+1][2]
if (ss[cnt+1][2]!='5'):
print "FATAL: a sig type 2 must be followed by a type 5!"
sys.exit()
k1=r.get("sig:"+se+":"+ss[cnt+1][1])
if k1 is None:
if (aligned==True):
r.set("sig:"+se+":"+ss[cnt+1][1],"green")
else:
r.set("sig:"+se+":"+ss[cnt+1][1],"red")
else:
if ((k1=="green") or k1==("yellow")):
if (aligned==False):
r.set("sig:"+se+":"+ss[cnt+1][1],"red")
k1=r.get("sig:"+se+":"+ss[cnt+1][1])
else:
if not __debug__:
print " (switch has no succ)"
if prevs is not None:
if not __debug__:
print " switch of sig "+s[1]+" has a prev sig: "+prevs[1]+" of type: "+prevs[2]
print " so we set forwardPrevSig to "+str(cnt-1)+" for "+s[1]
r.set("switch:"+s[1]+":forwardPrevSig",cnt-1)
if (prevs[2]!='3'):
print "FATAL: a sig type 2 must be preceded by a type 3 or no sig!"
sys.exit()
else:
k1=r.get("sig:"+se+":"+prevs[1])
if k1 is None:
if (aligned==True):
r.set("sig:"+se+":"+prevs[1],"yellow")
else:
r.set("sig:"+se+":"+prevs[1],"yellow")
k1=r.get("sig:"+se+":"+prevs[1])
if not __debug__:
print " prev color set to: "+k1
else:
if not __debug__:
print " (switch has no prev)"
else: #not a type 2
if ((s[2]!='4C') and (cnt==len(ss)-1)):
if not __debug__:
print "INFO: SIG "+str(s)+" has not succ and is neither a type 2 nor a type 4C"
r.set("sig:"+se+":"+s[1],"red")
prevs=s
cnt=cnt+1
gts[se]=ss
return gts
def initAll():
global tivs
global stas
global sigs
global trss
global grds
global crvs
global trs
global segs
global jumpseat
global r
global stock
global conf
global hasServices
global srvs
random.seed()
stock={}
r.set('realtime:',REALTIME)
confraw=initConfig()
conf['units']='metric'
for aa in confraw:
if (aa[0]!="#"):
if (aa[0]=='units'):
conf['units']=aa[1]
if (aa[0]=='speedLine'):
maxLine=float(aa[1])
if not __debug__:
print "routeConfig details:"
print confraw
print conf
segs=initSEGs()
tivs=initTIVs()
stas=initSTAs()
sigs=initSIGs()
trss=initSchedule()
grds=initGRDs()
crvs=initCRVs()
stockraw=initStock()
cnt=0
stock['acceleration']=ACC
stock['waitTime']=10.0 # at stations, in secs
stock['k']=0.25
# stock['timbre']=18.0
stock['cylinders']=2
stock['accelerationLaw']=ALAW
stock['weight']=WEIGHT # whole train for EMUs, carriages only for pushed/pulled trains.
stock['tenderAxleLoad']=0.0 # always 0 for EMUs, in kg, including full water and coal
stock['driveAxleLoad']=0.0 # always 0 for EMUs, in kg
stock['deadFrontAxleLoad']=0.0 # always 0 for EMUs, in kg
stock['deadRearAxleLoad']=0.0 # always 0 for EMUs, in kg
stock['carriagesWeight']=0.0 # always 0 for EMUs
stock['waterCapacity']=0.0 # max kg of water in tender
stock['coalCapacity']=0.0 # max kg of coal in tender
stock['power']=POWER # only makes sense for EMUs
stock['maxSpeed']=VMX
stock['criticalSpeed']=0.0 # for STM only, in km/h
stock['airFactor']=AIRFACTOR # only makes sense for EMUs
stock['railFactor']=WHEELFACTOR # only makes sense for EMUs
stock['length']=TLENGTH
stock['deceleration']=DCC
stock['decelerationLaw']=DLAW
stock['emergency']=EMR
stock['maxPax']=MAXPAX
stock['paxWeight']=PAXWEIGHT
stock['criticalSpeed']=0.0
for aa in stockraw:
if (aa[0]!="#"):
if (aa[0]=='acceleration'):
stock['acceleration']=float(aa[1])
if (aa[0]=='expansion'):
stock['expansion']=aa[1]
if (aa[0]=='units'):
stock['units']=aa[1]
if (aa[0]=='driveAxles'):
stock['driveAxles']=int(aa[1])
if (aa[0]=='deadFrontAxles'):
stock['deadFrontAxles']=int(aa[1])
if (aa[0]=='deadFrontAxleLoad'):
stock['deadFrontAxleLoad']=float(aa[1])
if (aa[0]=='deadRearAxleLoad'):
stock['deadRearAxleLoad']=float(aa[1])
if (aa[0]=='driveAxleLoad'):
stock['driveAxleLoad']=float(aa[1])
if (aa[0]=='deadRearAxles'):
stock['deadRearAxles']=int(aa[1])
if (aa[0]=='tenderAxles'):
stock['tenderAxles']=int(aa[1])
if (aa[0]=='cylinders'):
stock['cylinders']=int(aa[1])
if (aa[0]=='wheelsDiameter'):
stock['wheelsDiameter']=float(aa[1])
if (aa[0]=='frontSurface'):
stock['frontSurface']=float(aa[1])
if (aa[0]=='pistonsLength'):
stock['pistonsLength']=float(aa[1])
if (aa[0]=='waitTime'):
stock['waitTime']=float(aa[1])
if (aa[0]=='indicatedGrade'):
stock['indicatedGrade']=float(aa[1])
if (aa[0]=='indicatedCurve'):
stock['indicatedCurve']=float(aa[1])
if (aa[0]=='k'):
stock['k']=float(aa[1])
if (aa[0]=='timbre'):
stock['timbre']=float(aa[1])
if (aa[0]=='accelerationLaw'):
stock['accelerationLaw']=aa[1]
if (aa[0]=='weight'):
stock['weight']=float(aa[1])
if (aa[0]=='waterCapacity'):
stock['waterCapacity']=float(aa[1])
if (aa[0]=='coalCapacity'):
stock['coalCapacity']=float(aa[1])
if (aa[0]=='tenderAxleLoad'):
stock['tenderAxleLoad']=float(aa[1])
if (aa[0]=='carriagesWeight'):
stock['carriagesWeight']=float(aa[1])
if (aa[0]=='power'):
stock['power']=float(aa[1])
if (aa[0]=='maxSpeed'):
stock['maxSpeed']=float(aa[1])
if conf['units']=='imperial':
stock['maxSpeed']=float(stock['maxSpeed'])*MPH
if (aa[0]=='criticalSpeed'):
stock['criticalSpeed']=float(aa[1])
if conf['units']=='imperial':
stock['criticalSpeed']=float(stock['criticalSpeed'])*MPH
if (aa[0]=='airFactor'):
stock['airFactor']=float(aa[1])
if (aa[0]=='length'):
stock['length']=float(aa[1])
if (aa[0]=='deceleration'):
stock['deceleration']=float(aa[1])
if (aa[0]=='maxPax'):
stock['maxPax']=int(aa[1])
if (aa[0]=='paxWeight'):
stock['paxWeight']=float(aa[1])
if (aa[0]=='decelerationLaw'):
stock['decelerationLaw']=aa[1]
if (aa[0]=='templateName'):
stock['templateName']=aa[1]
if (aa[0]=='emergency'):
stock['emergency']=float(aa[1])
if not __debug__:
print "rollingStock details:"
print stock
hasServices=False
# for aa in trss:
# if len(aa)>3:
# hasServices=True
# if hasServices==True:
# srvs=initSRVs()
# else:
# if not __debug__:
# print "INFO: no services found..."
for aa in trss:
if ((aa[0]!="#") and (cnt==0)):
found=False
for asi in sigs[aa[1]]:
if asi[1]==aa[2]:
aPos=1000.0*float(asi[0])
if len(aa)>3:
trs=Tr(aa[0],aa[1],aa[3],aPos)
else:
trs=Tr(aa[0],aa[1],None,aPos)
else:
if (aa[0]!="#"):
found=False
for asi in sigs[aa[1]]:
if asi[1]==aa[2]:
aPos=1000.0*float(asi[0])
if len(aa)>3:
aT=Tr(aa[0],aa[1],aa[3],aPos)
else:
aT=Tr(aa[0],aa[1],None,aPos)
if aT is not None:
trs.append(aT)
cnt=cnt+1
class Tr:
global stock
initSitchSeg=False
facingSig={}
trip=0
BDtiv=0.0 #breaking distance for next TIV
BDsta=0.0 #fornext station
DBrt=0.0 #for next realtime event (sig or tvm)
vapor=0.0 #consumption in kg per second
coal=0.0 #consumption in kg per second
consumptionCutOff=1.0
brakeWear=0.0
admissionWear=0.0
mechWear=0.0
waterQty=0.0
coalQty=0.0
indicatedPower=0.0 #in horsepower. n/a for EMUs
TIVcnt=0
STAcnt=0
SIGcnt=0
pathCnt=-1
pathBranch=''
service=None
name=''
nextSTA=''
nextSIG=''
nextTIV=''
nSTAx=0.0
nSIGx=0.0
nTIVx=0.0
nTIVvl=0.0
cTIVvl=0.0
nTIVtype=''
maxVk=0.0
initPos=0.0
PK=0.0
aGaussFactor=0.0
aFull=0.0
a=0.0
v=0.0
x=0.0
nv=0.0
cv=0.0
vK=0.0
critVk=0.0
startingPhase=True
tenderWeight=0.0
engineWeight=0.0
carriagesWeight=0.0
tgtVk=110.0
deltaBDtiv=0.0
deltaBDsta=0.0
advTIV=-1.0
staBrake=False
sigBrake=False
sigPoll=0.0
sigToPoll={}
inSta=False
atSig=False
react=False
waitSta=0.0
waitReact=0.0
BDzero=0.0
segment=''
grade=0.0 # percentage
gradient=0.0 # angle of inclination, in radian
oldGradient=0.0
power=0.0
m=0.0
def append(self,aTr):
self.trs.append(aTr)
def __iter__(self):
yield self
for t in self.trs:
for i in t:
yield i
def switch(self,name,newSegment,initPos):
if not __debug__:
print "SWITCHING..."+self.name+" "+name+" from pos "+str(self.x)+" in segment "+self.segment+" to pos "+str(initPos)+" in segment "+newSegment
self.x=initPos
self.segment=newSegment
self.GRDcnt=findMyGRDcnt(initPos,newSegment)
self.nextGRD=grds[newSegment][self.GRDcnt]
self.nGRDx=1000.0*float(self.nextGRD[0])
self.transitionGRDx=self.nGRDx+stock['length']
self.CRVcnt=findMyCRVcnt(initPos,newSegment)
self.nextCRV=crvs[newSegment][self.CRVcnt]
self.nCRVx=1000.0*float(self.nextCRV[0])
self.transitionCRVx=self.nCRVx+stock['length']
self.TIVcnt=findMyTIVcnt(initPos,newSegment)
self.STAcnt=findMySTAcnt(initPos,newSegment)
self.SIGcnt=findMySIGcnt(initPos,newSegment)
self.nextSTA=stas[newSegment][self.STAcnt]
self.nextSIG=sigs[newSegment][self.SIGcnt]
self.nSTAx=1000.0*float(self.nextSTA[0])
self.nSIGx=1000.0*float(self.nextSIG[0])
self.nextTIV=tivs[newSegment][self.TIVcnt]
if not __debug__:
print self.name+":t:"+str(t)+" My TIVcnt is: "+str(self.TIVcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My STAcnt is: "+str(self.STAcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My SIGcnt is: "+str(self.SIGcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" next TIV at PK"+self.nextTIV[0]+" with limit "+self.nextTIV[1]
print self.name+":t:"+str(t)+" next GRD at PK"+self.nextGRD[0]+" with grade "+self.nextGRD[1]
self.nTIVx=1000.0*float(self.nextTIV[0])
self.nTIVvl=float(self.nextTIV[1])
self.cTIVvl=0.0
self.nTIVtype='INC' # tiv increases speed
if (self.GRDcnt>0):
self.grade=float(grds[newSegment][self.GRDcnt-1][1])
else:
self.grade=float(grds[newSegment][self.GRDcnt][1])
self.gradient=self.grade/100.0 #good approx even for grad less than 3.0%
self.oldGradient=self.gradient
self.ratioGRD=1.0
if (self.TIVcnt>0):
self.maxVk=min(stock['maxSpeed'],float(tivs[newSegment][self.TIVcnt-1][1]))
else:
self.maxVk=min(stock['maxSpeed'],float(tivs[newSegment][self.TIVcnt][1]))
self.redisSIG="sig:"+self.segment+":"+sigs[self.segment][self.SIGcnt][1]
self.facingSig['seg']=self.segment
self.facingSig['cnt']=self.SIGcnt
self.facingSig['type']=sigs[self.segment][self.SIGcnt][2]
self.facingSig['name']=sigs[self.segment][self.SIGcnt][1]
previousSig=findPrevSig(self.facingSig)
if previousSig is None:
print "FATAL: no previousSig"
sys.exit()
if not __debug__:
print self.name+": facing Sig:"+str(self.facingSig)+" previous Sig:"+str(previousSig)
self.advSIGcol=r.get(self.redisSIG)
self.sigSpotted=False
updateSIGbyTrOccupationWrapper(previousSig,self.name,"red")
def reinit(self,initSegment,initPos):
global stock
global t
if not __debug__:
print "REinit..."+self.name+" at pos "+str(initPos)
gFactor=G*self.gradient
v2factor=0.0
self.pathCnt=-1
self.pathBranch=''
factors=gFactor+v2factor+stock['railFactor']
self.startingPhase=True
self.x=initPos
self.trip=self.trip+1
self.coasting=False
self.segment=initSegment
self.BDtiv=0.0 #breaking distance for next TIV
self.BDsta=0.0 #fornext station
self.DBrt=0.0 #for next realtime event (sig or tvm)
self.GRDcnt=findMyGRDcnt(initPos,initSegment)
self.nextGRD=grds[initSegment][self.GRDcnt]
self.nGRDx=1000.0*float(self.nextGRD[0])
self.transitionGRDx=self.nGRDx+stock['length']
self.CRVcnt=findMyCRVcnt(initPos,initSegment)
self.nextCRV=crvs[initSegment][self.CRVcnt]
self.nCRVx=1000.0*float(self.nextCRV[0])
self.transitionCRVx=self.nCRVx+stock['length']
self.TIVcnt=findMyTIVcnt(initPos,initSegment)
self.STAcnt=findMySTAcnt(initPos,initSegment)
self.SIGcnt=findMySIGcnt(initPos,initSegment)
self.nextSTA=stas[initSegment][self.STAcnt]
self.nextSIG=sigs[initSegment][self.SIGcnt]
self.nSTAx=1000.0*float(self.nextSTA[0])
self.nSIGx=1000.0*float(self.nextSIG[0])
self.nextTIV=tivs[initSegment][self.TIVcnt]
if not __debug__:
print self.name+":t:"+str(t)+" My TIVcnt is: "+str(self.TIVcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My STAcnt is: "+str(self.STAcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My SIGcnt is: "+str(self.SIGcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" next TIV at PK"+self.nextTIV[0]+" with limit "+self.nextTIV[1]
print self.name+":t:"+str(t)+" next GRD at PK"+self.nextGRD[0]+" with grade "+self.nextGRD[1]
self.nTIVx=1000.0*float(self.nextTIV[0])
self.nTIVvl=float(self.nextTIV[1])
self.cTIVvl=0.0
self.nTIVtype='INC' # tiv increases speed
if (self.GRDcnt>0):
self.grade=float(grds[initSegment][self.GRDcnt-1][1])
else:
self.grade=float(grds[initSegment][self.GRDcnt][1])
self.gradient=self.grade/100.0 #good approx even for grad less than 3.0%
self.oldGradient=self.gradient
self.ratioGRD=1.0
if (self.TIVcnt>0):
self.maxVk=min(stock['maxSpeed'],float(tivs[initSegment][self.TIVcnt-1][1]))
else:
self.maxVk=min(stock['maxSpeed'],float(tivs[initSegment][self.TIVcnt][1]))
self.PK=self.x
self.aGaussFactor=aGauss()
self.aFull=0.0
self.v=0.0
self.vK=0.0
self.nv=0.0
self.cv=0.0
if (stock['accelerationLaw']=='EMU1'):
self.a=getAccForEMU(stock['power'],stock['acceleration'],stock['railFactor'],stock['airFactor'],self.vK,self.m)+self.aGaussFactor
elif (stock['accelerationLaw']=='STM1'):
getLiveDataForSTM(self.vK,0.0,self.grade,self.nextCRV[1],self.critVk,self.tgtVk,self.timbre,self.engineWeight,self.tenderWeight,stock['carriagesWeight'],stock['wheelsDiameter'],stock['frontSurface'],stock['driveAxles'],stock['pistonsLength'],stock['cylinders'],stock['expansion'],stock['k'],self.cylinderDiameter,self.startingPhase)+self.aGaussFactor
self.a=live[0]
# self.vapor=live[1]
# self.coal=live[2]
self.deltaBDtiv=0.0
self.deltaBDsta=0.0
self.advTIV=-1.0
self.staBrake=False
self.sigBrake=False
self.inSta=False
self.atSig=False
self.react=False
self.waitSta=0.0
self.waitReact=0.0
self.BDzero=0.0
self.redisSIG="sig:"+self.segment+":"+sigs[self.segment][self.SIGcnt][1]
self.facingSig['seg']=self.segment
self.facingSig['cnt']=self.SIGcnt
self.facingSig['type']=sigs[self.segment][self.SIGcnt][2]
self.facingSig['name']=sigs[self.segment][self.SIGcnt][1]
previousSig=findPrevSig(self.facingSig)
if previousSig is None:
print "FATAL: no previousSig"
sys.exit()
if not __debug__:
print self.name+": facing Sig:"+str(self.facingSig)+" previous Sig:"+str(previousSig)
self.advSIGcol=r.get(self.redisSIG)
self.sigSpotted=False
updateSIGbyTrOccupationWrapper(previousSig,self.name,"red")
def dumpstate(self):
global r
r.hmset("state:"+self.name,{'t':t,'coasting':self.coasting,'x':self.x,'segment':self.segment,'gradient':self.gradient,'TIV':self.TIVcnt,'SIG':self.SIGcnt,'STA':self.STAcnt,'aFull':self.aFull,'v':self.v,'staBrake':self.staBrake,'sigBrake':self.sigBrake,'inSta':self.inSta,'atSig':self.atSig,'sigSpotted':self.sigSpotted,'maxVk':self.maxVk,'a':self.a,'nextSTA':self.nextSTA[2],'maxPax':stock['maxPax'],'pax':self.pax,'nextSIG':self.nextSIG[1],'nextTIV':self.nextTIV[1],'nTIVtype':self.nTIVtype,'advSIGcol':self.advSIGcol,'redisSIG':self.redisSIG,'units':conf['units'],'react':self.react,'mechWear':self.mechWear,'admissionWear':self.admissionWear,'brakeWear':self.brakeWear,'service':self.service})
def __init__(self,name,initSegment,service,initPos):
global r
global stock
global srvs
if not __debug__:
print "init..."+name+" at pos "+str(initPos)+"with service "+str(service)
self.maxSquareSpeed=stock['maxSpeed']*stock['maxSpeed']
self.initSwitchSeg=False
self.pax=stock['maxPax']
self.startingPhase=True
self.critVk=stock['criticalSpeed']
self.tgtVk=stock['maxSpeed']
self.m=stock['weight']+self.pax*PAXWEIGHT
if service is not None:
found=False
for ses in srvs:
if ses[0]==service:
self.service=ses
found=True
if found==False:
print str(self.name)+":FATAL: service "+str(service)+" not found in services.txt"
sys.exit()
if (stock['accelerationLaw']=='STM1'):
self.timbre=stock['timbre']
self.maxTimbre=stock['timbre']
self.waterQty=stock['waterCapacity']
self.coalQty=stock['coalCapacity']
self.engineWeight=stock['driveAxleLoad']*stock['driveAxles']+stock['deadRearAxleLoad']*stock['deadRearAxles']+stock['deadFrontAxleLoad']*stock['deadFrontAxles']
self.tenderWeight=stock['tenderAxles']*stock['tenderAxleLoad']+self.coalQty+self.waterQty-stock['waterCapacity']-stock['coalCapacity']
self.m=self.engineWeight+stock['carriagesWeight']+self.tenderWeight
self.carriagesWeight=stock['carriagesWeight']
rForIndicated=rollingResistance(self.engineWeight/1000.0,self.tenderWeight/1000.0,stock['carriagesWeight']/1000.0,stock['indicatedGrade'],stock['indicatedCurve'],self.tgtVk,0.0,stock['wheelsDiameter'],stock['frontSurface'],stock['driveAxles'],stock['k'],True)
self.cylinderPressure=cylinderPressureInKgCm2(stock['timbre'],stock['expansion'])
self.cylinderDiameter=cylinderDiameterInCm(stock['cylinders'],rForIndicated,stock['wheelsDiameter'],self.cylinderPressure,stock['pistonsLength'])
self.indicatedPower=indicatedPowerInHorsePower(rForIndicated,self.tgtVk)
self.vapor=hourlyVaporConsumptionInKg(self.indicatedPower,self.timbre,stock['expansion'])/3600.0
self.coal=hourlyCoalConsumptionInKg(self.vapor)
gFactor=G*self.gradient
v2factor=0.0
self.pathCnt=-1
self.pathBranch=''
factors=gFactor+v2factor+stock['railFactor']
self.trs=[]
self.trip=0
self.coasting=False
self.x=initPos
self.name=name
self.segment=initSegment
self.BDtiv=0.0 #breaking distance for next TIV
self.BDsta=0.0 #fornext station
self.DBrt=0.0 #for next realtime event (sig or tvm)
# self.gradient=math.atan(self.grade/100.0)
self.GRDcnt=findMyGRDcnt(initPos,initSegment)
self.CRVcnt=findMyCRVcnt(initPos,initSegment)
self.TIVcnt=findMyTIVcnt(initPos,initSegment)
self.STAcnt=findMySTAcnt(initPos,initSegment)
self.SIGcnt=findMySIGcnt(initPos,initSegment)
if stock['length']>initPos:
print "FATAL: "+str(self.name)+" must be located at least at x:"+str(stock['length'])+". Currently it is located at x:"+str(initPos)
sys.exit()
self.nextSTA=stas[initSegment][self.STAcnt]
self.nextSIG=sigs[initSegment][self.SIGcnt]
self.nextGRD=grds[initSegment][self.GRDcnt]
self.nextCRV=crvs[initSegment][self.CRVcnt]
self.nSTAx=1000.0*float(self.nextSTA[0])
self.nSIGx=1000.0*float(self.nextSIG[0])
self.nGRDx=1000.0*float(self.nextGRD[0])
self.nCRVx=1000.0*float(self.nextCRV[0])
self.transitionGRDx=self.nGRDx+stock['length']
self.transitionCRVx=self.nCRVx+stock['length']
self.nextTIV=tivs[initSegment][self.TIVcnt]
if not __debug__:
print self.name+":t:"+str(t)+" MyGRDcnt is:"+str(self.GRDcnt)
print self.name+":t:"+str(t)+" My TIVcnt is: "+str(self.TIVcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My STAcnt is: "+str(self.STAcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" My SIGcnt is: "+str(self.SIGcnt)+" based on pos:"+str(initPos)
print self.name+":t:"+str(t)+" next TIV at PK"+self.nextTIV[0]+" with limit "+self.nextTIV[1]
print self.name+":t:"+str(t)+" next GRD at PK"+self.nextGRD[0]+" with limit "+self.nextGRD[1]
self.nTIVx=1000.0*float(self.nextTIV[0])
self.nTIVvl=float(self.nextTIV[1])
self.cTIVvl=0.0
self.nTIVtype='INC' # tiv increases speed
if (self.TIVcnt>0):
self.maxVk=min(stock['maxSpeed'],float(tivs[initSegment][self.TIVcnt-1][1]))
else:
self.maxVk=min(stock['maxSpeed'],float(tivs[initSegment][self.TIVcnt][1]))
if (self.GRDcnt>0):
self.grade=float(grds[initSegment][self.GRDcnt-1][1])
else:
self.grade=float(grds[initSegment][self.GRDcnt][1])
#self.gradient=math.atan(self.grade/100.0)
self.gradient=self.grade/100.0
self.oldGradient=self.gradient
self.ratioGRD=1.0
self.PK=self.x
self.aGaussFactor=aGauss()
self.aFull=0.0
self.v=0.0
self.vK=0.0
self.nv=0.0
self.cv=0.0
if (stock['accelerationLaw']=='EMU1'):
self.a=getAccForEMU(stock['power'],stock['acceleration'],stock['railFactor'],stock['airFactor'],self.vK,self.m)+self.aGaussFactor
elif (stock['accelerationLaw']=='STM1'):
getLiveDataForSTM(self.vK,0.0,self.grade,self.nextCRV[1],self.critVk,self.tgtVk,self.timbre,self.engineWeight,self.tenderWeight,stock['carriagesWeight'],stock['wheelsDiameter'],stock['frontSurface'],stock['driveAxles'],stock['pistonsLength'],stock['cylinders'],stock['expansion'],stock['k'],self.cylinderDiameter,self.startingPhase)+self.aGaussFactor
self.a=live[0]
# self.vapor=live[1]
# self.coal=live[2]
self.deltaBDtiv=0.0
self.deltaBDsta=0.0
self.advTIV=-1.0
self.staBrake=False
self.sigBrake=False
self.inSta=False
self.atSig=False
self.waitSta=0.0
self.BDzero=0.0
self.redisSIG="sig:"+self.segment+":"+sigs[self.segment][self.SIGcnt][1]
self.facingSig['seg']=self.segment
self.facingSig['cnt']=self.SIGcnt
self.facingSig['type']=sigs[self.segment][self.SIGcnt][2]
self.facingSig['name']=sigs[self.segment][self.SIGcnt][1]
previousSig=findPrevSig(self.facingSig)
if previousSig is None:
print "FATAL: no previousSig"
sys.exit()
if not __debug__:
print self.name+": facing Sig:"+str(self.facingSig)+" previous Sig:"+str(previousSig)
self.advSIGcol="red" # safeguard before we run step()
self.sigSpotted=False
sigAlreadyOccupied=r.get("sig:"+previousSig['seg']+":"+previousSig['name']+":isOccupied")
if sigAlreadyOccupied is not None:
if sigAlreadyOccupied!=self.name:
print "IGNORED: "+str(self.name)+" and "+str(sigAlreadyOccupied)+" share the same signal block"
return None