-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMASS_GT_GUI.py
More file actions
1180 lines (1016 loc) · 50.5 KB
/
Copy pathMASS_GT_GUI.py
File metadata and controls
1180 lines (1016 loc) · 50.5 KB
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
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 10:47:15 2020
@author: STH
"""
# Importeer de modules van het model
import __module_SHIP__
import __module_TOUR__
# Libraries nodig voor de user interface
import tkinter as tk
from tkinter import filedialog
from tkinter.ttk import Progressbar
import os.path
from sys import argv
import zlib
import base64
import tempfile
from threading import Thread
import multiprocessing as mp
import sys
import traceback
import datetime
import ast
class HiddenPrints: #
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
varDict = {}
'''FOR ALL MODULES'''
cwd = os.getcwd().replace(os.sep, '/')
datapath = cwd.replace('Code', '')
def generate_args(method):
varDict = {}
'''FOR ALL MODULES'''
cwd = os.getcwd().replace(os.sep, '/')
datapath = cwd.replace('Code', '')
if method == 'from_file':
if sys.argv[0] == '' :
params_file = open(f'{datapath}/Input/Params_ParcelGen.txt')
varDict['LABEL' ] = 'ConsoleRun'
varDict['DATAPATH'] = f'{datapath}'
varDict['INPUTFOLDER'] = f'{datapath}'+'/' +'Input' +'/'
varDict['OUTPUTFOLDER'] = f'{datapath}'+'/' + 'Output' +'/'
varDict['SKIMTIME'] = varDict['INPUTFOLDER'] + 'skimTijd_new_REF.mtx' #'skimTijd_new_REF.mtx'
varDict['SKIMDISTANCE'] = varDict['INPUTFOLDER'] + 'skimAfstand_new_REF.mtx' #'skimAfstand_new_REF.mtx'
varDict['ZONES'] = varDict['INPUTFOLDER'] +'Zones_v4.shp'#'Zones_v4.shp'
varDict['SEGS'] = varDict['INPUTFOLDER'] + 'SEGS2020.csv' #'SEGS2020.csv'
varDict['PARCELNODES'] = varDict['INPUTFOLDER'] + 'parcelNodes_v2.shp' #'parcelNodes_v2.shp'
varDict['CEP_SHARES'] = varDict['INPUTFOLDER'] + 'CEPshares.csv' #'CEPshares.csv'
varDict['ExternalZones'] = varDict['INPUTFOLDER'] + 'SupCoordinatesID.csv' #'CEPshares.csv'
else: # This is the part for line cod execution
locationparam = f'{datapath}' +'/'+ sys.argv[2] +'/' + sys.argv[4]
params_file = open(locationparam)
varDict['LABEL' ] = sys.argv[1]
varDict['DATAPATH'] = datapath
varDict['INPUTFOLDER'] = f'{datapath}'+'/' + sys.argv[2] +'/'
varDict['OUTPUTFOLDER'] = f'{datapath}'+'/' + sys.argv[3] +'/'
varDict['SKIMTIME'] = varDict['INPUTFOLDER'] + sys.argv[5] #'skimTijd_new_REF.mtx'
varDict['SKIMDISTANCE'] = varDict['INPUTFOLDER'] + sys.argv[6] #'skimAfstand_new_REF.mtx'
varDict['ZONES'] = varDict['INPUTFOLDER'] + sys.argv[7] #'Zones_v4.shp'
varDict['SEGS'] = varDict['INPUTFOLDER'] + sys.argv[8] #'SEGS2020.csv'
varDict['PARCELNODES'] = varDict['INPUTFOLDER'] + sys.argv[9] #'parcelNodes_v2.shp'
varDict['CEP_SHARES'] = varDict['INPUTFOLDER'] + sys.argv[10] #'CEPshares.csv'
varDict['ExternalZones'] = varDict['INPUTFOLDER'] + sys.argv[11] #'CEPshares.csv'
for line in params_file:
if len(line.split('=')) > 1:
key, value = line.split('=')
if len(value.split(';')) > 1:
value, dtype = value.split(';')
if len(dtype.split('#')) > 1: dtype, comment = dtype.split('#')
# Allow for spacebars around keys, values and dtypes
while key[0] == ' ' or key[0] == '\t': key = key[1:]
while key[-1] == ' ' or key[-1] == '\t': key = key[0:-1]
while value[0] == ' ' or value[0] == '\t': value = value[1:]
while value[-1] == ' ' or value[-1] == '\t': value = value[0:-1]
while dtype[0] == ' ' or dtype[0] == '\t': dtype = dtype[1:]
while dtype[-1] == ' ' or dtype[-1] == '\t': dtype = dtype[0:-1]
dtype = dtype.replace('\n',"")
# print(key, value, dtype)
if dtype == 'string': varDict[key] = str(value)
elif dtype == 'list': varDict[key] = ast.literal_eval(value)
elif dtype == 'int': varDict[key] = int(value)
elif dtype == 'float': varDict[key] = float(value)
elif dtype == 'bool': varDict[key] = eval(value)
elif dtype == 'variable': varDict[key] = globals()[value]
elif dtype == 'eval': varDict[key] = eval(value)
elif method == 'from_code':
print('Generating args from code')
varDict['INPUTFOLDER'] = 'C:/My Projects/Shipment_synthesizer/Input/'
varDict['OUTPUTFOLDER'] = 'C:/My Projects/Shipment_synthesizer/Output/'
varDict['PARAMFOLDER'] = 'C:/My Projects/Shipment_synthesizer/Input/'
varDict['DIMFOLDER'] = 'C:/My Projects/Shipment_synthesizer/Input/'
varDict['SKIMTIME'] = 'C:/My Projects/Shipment_synthesizer/Input/skimTijd_REF.mtx'
varDict['SKIMDISTANCE'] = 'C:/My Projects/Shipment_synthesizer/Input/skimAfstand_REF.mtx'
varDict['NODES'] = varDict['INPUTFOLDER'] + 'nodes_v5.shp'
varDict['ZONES'] = varDict['INPUTFOLDER'] + 'Zones_v6.shp'
varDict['SEGS'] = varDict['INPUTFOLDER'] + 'SEGS2020.csv'
varDict['PARCELNODES'] = varDict['INPUTFOLDER'] + 'parcelNodes_v2.shp'
varDict['DISTRIBUTIECENTRA'] = varDict['INPUTFOLDER'] + 'distributieCentra.csv'
varDict['NSTR_TO_LS'] = varDict['INPUTFOLDER'] + 'nstrToLogisticSegment.csv'
varDict['MAKE_DISTRIBUTION'] = varDict['INPUTFOLDER'] + 'MakeDistribution.csv'
varDict['USE_DISTRIBUTION'] = varDict['INPUTFOLDER'] + 'UseDistribution.csv'
varDict['SUP_COORDINATES_ID'] = varDict['INPUTFOLDER'] + 'SupCoordinatesID.csv'
varDict['CORRECTIONS_TONNES'] = varDict['INPUTFOLDER'] + 'CorrectionsTonnes2016.csv'
varDict['CEP_SHARES'] = varDict['INPUTFOLDER'] + 'CEPshares.csv'
varDict['COST_VEHTYPE'] = varDict['PARAMFOLDER'] + 'Cost_VehType_2016.csv'
varDict['COST_SOURCING'] = varDict['PARAMFOLDER'] + 'Cost_Sourcing_2016.csv'
varDict['NUTS3_TO_MRDH'] = varDict['PARAMFOLDER'] + 'NUTS32013toMRDH.csv'
varDict['VEHICLE_CAPACITY'] = varDict['PARAMFOLDER'] + 'CarryingCapacity.csv'
varDict['LOGISTIC_FLOWTYPES'] = varDict['PARAMFOLDER'] + 'LogFlowtype_Shares.csv'
varDict['PARAMS_TOD'] = varDict['PARAMFOLDER'] + 'Params_TOD.csv'
varDict['PARAMS_SSVT'] = varDict['PARAMFOLDER'] + 'Params_ShipSize_VehType.csv'
varDict['PARAMS_ET_FIRST'] = varDict['PARAMFOLDER'] + 'Params_EndTourFirst.csv'
varDict['PARAMS_ET_LATER'] = varDict['PARAMFOLDER'] + 'Params_EndTourLater.csv'
varDict['ZEZ_CONSOLIDATION'] = varDict['INPUTFOLDER'] + 'ConsolidationPotential.csv'
varDict['ZEZ_SCENARIO'] = varDict['INPUTFOLDER'] + 'ZEZscenario.csv'
varDict['YEARFACTOR'] = 209
varDict['NUTSLEVEL_INPUT'] = 3
varDict['PARCELS_GROWTHFREIGHT'] = 1.0
varDict['SHIPMENTS_REF'] = ""
varDict['FIRMS_REF'] = varDict['INPUTFOLDER'] + 'Firms.csv'
varDict['FAC_LS0'] = ""
varDict['FAC_LS1'] = ""
varDict['FAC_LS2'] = ""
varDict['FAC_LS3'] = ""
varDict['FAC_LS4'] = ""
varDict['FAC_LS5'] = ""
varDict['FAC_LS6'] = ""
varDict['FAC_LS7'] = ""
varDict['NEAREST_DC'] = ""
varDict['N_CPU'] = ""
varDict['SHIFT_FREIGHT_TO_COMB1'] = ""
varDict['SHIFT_FREIGHT_TO_COMB2'] = ""
varDict['LABEL'] = 'REF'
varDict['MODULES']='SHIP,TOUR'
args = ['', varDict]
return args, varDict
method = 'from_code' #either from_file or from_code
args, varDict = generate_args(method)
# TESTRUN = False # True to fasten further code TEST (runs with less parcels)
# TestRunLen = 100
# Class and functions: Graphical User Interface
class Root:
def __init__(self):
'''
Initialize a GUI object
'''
# Get directory of the script
self.datapath = os.path.dirname(os.path.realpath(argv[0]))
self.datapath = self.datapath.replace(os.sep, '/') + '/'
# self.moduleNames = [
# 'FS', 'SIF',
# 'SHIP', 'TOUR',
# 'PARCEL_DMND', 'PARCEL_SCHD',
# 'SERVICE',
# 'TRAF',
# 'OUTP']
# # Set graphics parameters
# self.width = 950
# self.height = 120
# self.bg = 'black'
# self.fg = 'white'
# self.font = 'Verdana'
# # Create a GUI window
# self.root = tk.Tk()
# self.root.title("Tactical Freight Simulator HARMONY")
# self.root.geometry(f'{self.width}x{self.height}+0+0')
# self.root.resizable(False, False)
# self.canvas = tk.Canvas(
# self.root,
# width=self.width,
# height=self.height,
# bg=self.bg)
# self.canvas.place(x=0, y=0)
# self.statusBar = tk.Label(
# self.root,
# text="",
# anchor='w',
# borderwidth=0,
# fg='black')
# self.statusBar.place(
# x=2,
# y=self.height - 22,
# width=self.width,
# height=22)
# # Remove the default tkinter icon from the window
# icon = zlib.decompress(base64.b64decode(
# 'eJxjYGAEQgEBBiDJwZDBy' +
# 'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
# _, self.iconPath = tempfile.mkstemp()
# with open(self.iconPath, 'wb') as iconFile:
# iconFile.write(icon)
# self.root.iconbitmap(bitmap=self.iconPath)
# # Create control file label and entry
# self.labelControlFile = tk.Label(
# self.root,
# text='Control file:',
# width=20,
# height=1,
# anchor='w',
# bg=self.bg,
# fg=self.fg,
# font=(self.font, 8))
# self.labelControlFile.place(x=5, y=9)
# self.controlFile = tk.StringVar(self.root, self.datapath)
# self.entryControlFile = tk.Entry(
# self.root,
# textvariable=self.controlFile,
# width=120,
# font=(self.font, 8))
# self.entryControlFile.place(x=80, y=10)
# # Create button to search for control file
# self.searchButton = tk.Button(
# self.root,
# text="...",
# command=self.file_dialog,
# width=2,
# font=(self.font, 5))
# self.searchButton.place(x=905, y=12)
# # Create button to run the main function
# self.runButton = tk.Button(
# self.root,
# text="Run",
# width=15,
# height=3,
# command=self.run_main,
# font=(self.font, 8))
# self.runButton.place(x=425, y=35)
# self.progressBar = Progressbar(
# self.root,
# length=int(self.width / 2))
# self.progressBar.place(x=int(self.width / 2), y=self.height - 22)
# # If the control file is passed as an argument
# # in a batch job or in the command line prompt
# if len(argv) > 1:
# self.controlFile.set(argv[1])
# self.run_main()
# # Keep GUI active until closed
# self.root.mainloop()
# def update_statusbar(self, text):
# self.statusBar.configure(text=text)
# def reset_statusbar(self, event=None):
# self.statusBar.configure(text="")
# def file_dialog(self):
# '''
# Open up a file dialog
# '''
# self.filename = filedialog.askopenfilename(
# initialdir="/",
# title="Select the .ini control file",
# filetype=(("Control files (.ini)", "*.ini"), ("All files", "*.*")))
# self.controlFile.set(self.filename)
def run_main(self, event=None):
Thread(target=self.actually_run_main, daemon=True).start()
def actually_run_main(self):
# '''
# Run the actual emission calculation
# '''
# # All the allowed keys in the control file
# self.varStrings = [
# "INPUTFOLDER", "OUTPUTFOLDER", "PARAMFOLDER", "DIMFOLDER",
# "SKIMTIME", "SKIMDISTANCE",
# "LINKS", "NODES",
# "EMISSIONFACS_BUITENWEG_LEEG", "EMISSIONFACS_BUITENWEG_VOL",
# "EMISSIONFACS_SNELWEG_LEEG", "EMISSIONFACS_SNELWEG_VOL",
# "EMISSIONFACS_STAD_LEEG", "EMISSIONFACS_STAD_VOL",
# "ZONES", "SEGS", "SUP_COORDINATES_ID",
# "DISTRIBUTIECENTRA", "DC_OPP_NUTS3",
# "NSTR_TO_LS",
# "MAKE_DISTRIBUTION", "USE_DISTRIBUTION",
# "DEPTIME_FREIGHT", "DEPTIME_PARCELS",
# "FIRMSIZE", "SBI_TO_SEGS",
# "COST_VEHTYPE", "COST_SOURCING",
# "COMMODITYMATRIX",
# "PARCELNODES", "CEP_SHARES",
# "MRDH_TO_NUTS3", "NUTS3_TO_MRDH", "MRDH_TO_COROP",
# "VEHICLE_CAPACITY",
# "LOGISTIC_FLOWTYPES",
# "PARAMS_SIF_PROD", "PARAMS_SIF_ATTR",
# "PARAMS_TOD", "PARAMS_SSVT",
# "PARAMS_ET_FIRST", "PARAMS_ET_LATER",
# "PARAMS_ECOMMERCE",
# "SERVICE_DISTANCEDECAY", "SERVICE_PA",
# "PARCELS_PER_HH", "PARCELS_PER_EMPL",
# "PARCELS_MAXLOAD", "PARCELS_DROPTIME",
# "PARCELS_SUCCESS_B2C", "PARCELS_SUCCESS_B2B",
# "PARCELS_GROWTHFREIGHT",
# "CROWDSHIPPING",
# "CRW_PARCELSHARE", "CRW_MODEPARAMS",
# "CRW_PDEMAND_CAR", "CRW_PDEMAND_BIKE",
# "ZEZ_CONSOLIDATION", "ZEZ_SCENARIO",
# "NEAREST_DC",
# "NUTSLEVEL_INPUT",
# "YEARFACTOR",
# "IMPEDANCE_SPEED_FREIGHT", "IMPEDANCE_SPEED_VAN",
# "N_CPU", "N_MULTIROUTE",
# "SHIPMENTS_REF", "FIRMS_REF",
# "SELECTED_LINKS",
# "CORRECTIONS_TONNES",
# "MICROHUBS", "VEHICLETYPES",
# "FAC_LS0", "FAC_LS1", "FAC_LS2", "FAC_LS3",
# "FAC_LS4", "FAC_LS5", "FAC_LS6", "FAC_LS7",
# "SHIFT_FREIGHT_TO_COMB1", "SHIFT_VAN_TO_COMB1",
# "SHIFT_FREIGHT_TO_COMB2",
# "LABEL",
# "MODULES"]
# nVars = len(self.varStrings)
# # At which index car the output, input and parameter folder be found
# whereOutputFolder, whereInputFolder, whereParamFolder, whereDimFolder = (
# None, None, None, None)
# for i in range(nVars):
# if self.varStrings[i] == "OUTPUTFOLDER":
# whereOutputFolder = i
# elif self.varStrings[i] == "INPUTFOLDER":
# whereInputFolder = i
# elif self.varStrings[i] == "PARAMFOLDER":
# whereParamFolder = i
# elif self.varStrings[i] == "DIMFOLDER":
# whereDimFolder = i
# # A list for the values belonging to each key in the control file
# varValues = ["" for i in range(nVars)]
# # Which variables are of numeric nature
# numericVars = [
# "PARCELS_PER_HH", "PARCELS_PER_EMPL",
# "PARCELS_MAXLOAD", "PARCELS_DROPTIME",
# "PARCELS_SUCCESS_B2C", "PARCELS_SUCCESS_B2B",
# "PARCELS_GROWTHFREIGHT",
# "YEARFACTOR",
# "NUTSLEVEL_INPUT",
# "CRW_PARCELSHARE",
# "N_MULTIROUTE",
# "FAC_LS0", "FAC_LS1", "FAC_LS2", "FAC_LS3",
# "FAC_LS4", "FAC_LS5", "FAC_LS6", "FAC_LS7",
# "SHIFT_FREIGHT_TO_COMB1", "SHIFT_VAN_TO_COMB1",
# "SHIFT_FREIGHT_TO_COMB2"]
# # Which variables refer to a directory path
# dirVars = [
# "INPUTFOLDER",
# "OUTPUTFOLDER",
# "PARAMFOLDER",
# "DIMFOLDER"]
# # Which variables refer to the modules that need to be run
# moduleVars = [
# "MODULES"]
# # Which variables refer to a file path
# fileVars = [
# "SKIMTIME", "SKIMDISTANCE",
# "LINKS", "NODES",
# "EMISSIONFACS_BUITENWEG_LEEG", "EMISSIONFACS_BUITENWEG_VOL",
# "EMISSIONFACS_SNELWEG_LEEG", "EMISSIONFACS_SNELWEG_VOL",
# "EMISSIONFACS_STAD_LEEG", "EMISSIONFACS_STAD_VOL",
# "ZONES", "SEGS", "SUP_COORDINATES_ID",
# "DISTRIBUTIECENTRA", "DC_OPP_NUTS3",
# "NSTR_TO_LS",
# "MAKE_DISTRIBUTION", "USE_DISTRIBUTION",
# "DEPTIME_FREIGHT", "DEPTIME_PARCELS",
# "FIRMSIZE", "SBI_TO_SEGS",
# "COST_VEHTYPE", "COST_SOURCING",
# "COMMODITYMATRIX",
# "PARCELNODES", "CEP_SHARES",
# "MRDH_TO_NUTS3", "NUTS3_TO_MRDH", "MRDH_TO_COROP",
# "VEHICLE_CAPACITY",
# "LOGISTIC_FLOWTYPES",
# "PARAMS_SIF_PROD", "PARAMS_SIF_ATTR",
# "PARAMS_TOD", "PARAMS_SSVT",
# "PARAMS_ET_FIRST", "PARAMS_ET_LATER",
# "PARAMS_ECOMMERCE",
# "SERVICE_DISTANCEDECAY", "SERVICE_PA",
# "ZEZ_CONSOLIDATION", "ZEZ_SCENARIO",
# "SHIPMENTS_REF", "FIRMS_REF",
# "CORRECTIONS_TONNES",
# "CRW_MODEPARAMS", "CRW_PDEMAND_CAR", "CRW_PDEMAND_BIKE",
# "MICROHUBS", "VEHICLETYPES"]
# # Variables that became obsolete due to changes in the modules
# # keep these in here to prevent errors on older ini files with these
# # arguments still in there
# obsoleteVars = [
# "DEPTIME_FREIGHT",
# "PARCELS_PER_HH"]
# # Variables for which a value in the control file is not obligatory
# optionalVars = [
# "SHIPMENTS_REF", "FIRMS_REF",
# "CORRECTIONS_TONNES",
# "SELECTED_LINKS",
# "N_CPU",
# "N_MULTIROUTE",
# "CROWDSHIPPING",
# "NEAREST_DC",
# "CRW_PARCELSHARE", "CRW_MODEPARAMS",
# "CRW_PDEMAND_CAR", "CRW_PDEMAND_BIKE",
# "MICROHUBS", "VEHICLETYPES",
# "FAC_LS0", "FAC_LS1", "FAC_LS2", "FAC_LS3",
# "FAC_LS4", "FAC_LS5", "FAC_LS6", "FAC_LS7",
# "SHIFT_FREIGHT_TO_COMB1", "SHIFT_VAN_TO_COMB1",
# "SHIFT_FREIGHT_TO_COMB2"]
# optionalVars = optionalVars + obsoleteVars
# Run the modules or not, is set to False if, for example,
# an input file could not be found
run = True
# Write a log file or not, is set to False if the specified
# outputfolder does not exist
writeLog = True
# In this string we collect the error messages
# errorMessage = ""
# try:
# with open(self.controlFile.get(), 'r') as f:
# lines = f.readlines()
# for line in lines:
# if len(line.split('=')) > 1:
# if line[0] != '#':
# key = line.split('=')[0]
# value = line.split('=')[1]
# # Allow spaces and tabs before/after the key
# # and the value
# while key[0] == ' ' or key[0] == '\t':
# key = key[1:]
# while key[-1] == ' ' or key[-1] == '\t':
# key = key[0:-1]
# while value[0] == ' ' or value[0] == '\t':
# value = value[1:]
# while value[-1] == ' ' or value[-1] == '\t':
# value = value[0:-1]
# print(key + ' = ' + value.replace('\n', ""))
# # Read the arguments in the control file
# for i in range(nVars):
# if key.upper() == self.varStrings[i]:
# # For numeric arguments, check if they
# # can be converted from string to float
# if self.varStrings[i] in numericVars:
# value = value.replace("'", "")
# value = value.replace('"', "")
# value = value.replace('\n', "")
# try:
# varValues[i] = float(value)
# except ValueError:
# if not (value == '' and value in optionalVars):
# varValues[i] = value
# errorMessage = (
# errorMessage +
# 'Fill in a numeric value for ' +
# self.varStrings[i] +
# ', could not convert following value to a number: ' +
# value +
# "\n")
# run = False
# # The argument which states which
# # modules should be run
# elif self.varStrings[i] in moduleVars:
# value = value.replace("'", "")
# value = value.replace('"', "")
# value = value.replace('\n', "")
# value = value.replace(' ', '')
# varValues[i] = value
# varValues[i] = varValues[i].split(',')
# for j in range(len(varValues[i])):
# varValues[i][j] = varValues[i][j].upper()
# if varValues[i][j] not in self.moduleNames:
# errorMessage = (
# errorMessage +
# 'Module ' +
# varValues[i][j] +
# ' does not exist.' +
# '\n')
# run = False
# # For string arguments, also replace
# # possible '\' by '/'
# else:
# value = value.replace(os.sep, '/')
# value = value.replace("'", "")
# value = value.replace('"', "")
# value = value.replace('\n', "")
# varValues[i] = value
# if self.varStrings[i] in dirVars:
# if varValues[i][-1] != '/':
# varValues[i] = varValues[i] + '/'
# if self.varStrings[i] in dirVars or self.varStrings[i] in fileVars:
# if self.varStrings[i] not in dirVars:
# tmp = varValues[i].split("<<")
# if len(tmp) > 1:
# tmp = tmp[1].split(">>")
# if tmp[0] == 'OUTPUTFOLDER':
# varValues[i] = varValues[whereOutputFolder] + tmp[1]
# if tmp[0] == 'INPUTFOLDER':
# varValues[i] = varValues[whereInputFolder] + tmp[1]
# if tmp[0] == 'PARAMFOLDER':
# varValues[i] = varValues[whereParamFolder] + tmp[1]
# if tmp[0] == 'DIMFOLDER':
# varValues[i] = varValues[whereDimFolder] + tmp[1]
# # Warning for unknown argument in control file
# if key.upper() not in self.varStrings:
# errorMessage = (
# errorMessage +
# 'Unknown parameter in control file: ' +
# key +
# "\n")
# run = False
# for i in range(nVars):
# # Warnings for non-existing directories
# if self.varStrings[i] in dirVars:
# if not os.path.isdir(varValues[i]) and varValues[i] != "":
# errorMessage = (
# errorMessage +
# 'The folder for parameter ' +
# self.varStrings[i] +
# ' does not exist: ' +
# "'" + varValues[i] + "'" +
# "\n")
# run = False
# # Can't write a logfile if the outputfolder
# # does not exist
# if self.varStrings[i] == "OUTPUTFOLDER":
# writeLog = False
# # Warnings for non-existing files
# if self.varStrings[i] in fileVars:
# if not os.path.isfile(varValues[i]) and varValues[i] != "":
# errorMessage = (
# errorMessage +
# 'The file for parameter ' +
# self.varStrings[i] +
# ' does not exist: ' +
# "'" + varValues[i] + "'" +
# "\n")
# run = False
# # Warnings for omitted arguments in control file
# for i in range(nVars):
# if varValues[i] == "" and self.varStrings[i] not in optionalVars:
# errorMessage = (
# errorMessage +
# 'Warning, no value given for parameter ' +
# self.varStrings[i] +
# ' in the controle file.' +
# "\n")
# run = False
# except Exception:
# errorMessage = (
# 'Could not find or read the following control file: ' +
# "'" + self.controlFile.get() + "'" +
# '\n\n' + str(sys.exc_info()[0]) +
# '\n\n' + str(traceback.format_exc()))
# run = False
# writeLog = False
# # Make a dictionary of the input arguments
# varDict = {}
# for i in range(nVars):
# varDict[self.varStrings[i]] = varValues[i]
# Check for outputfolder files when not all modules are run
# if os.path.isdir(varDict['OUTPUTFOLDER']):
# outFileChecks = [
# ["SHIP",
# "SIF",
# "CommodityMatrixNUTS3.csv"],
# ["TOUR",
# "SHIP",
# "Shipments_" + varDict['LABEL'] + ".csv"],
# ["PARCEL_SCHD",
# "PARCEL_DMND",
# "ParcelDemand_" + varDict['LABEL'] + ".csv"],
# ["TRAF",
# "TOUR",
# "Tours_" + varDict['LABEL'] + ".csv"],
# ["TRAF",
# "TOUR",
# "tripmatrix_" + varDict['LABEL'] + ".txt"],
# ["TRAF",
# "TOUR",
# "tripmatrix_" + varDict['LABEL'] + "_TOD0" + ".txt"],
# ["TRAF",
# "PARCEL_SCHD",
# "ParcelSchedule_" + varDict['LABEL'] + ".csv"],
# ["TRAF",
# "PARCEL_SCHD",
# "tripmatrix_parcels_" + varDict['LABEL'] + ".txt"],
# ["TRAF",
# "PARCEL_SCHD",
# "tripmatrix_parcels_" + varDict['LABEL'] + "_TOD0" + ".txt"],
# ["TRAF",
# "SERVICE",
# "TripsVanService.mtx"],
# ["TRAF",
# "SERVICE",
# "TripsVanConstruction.mtx"]]
# if varDict['FIRMS_REF'] == '':
# outFileChecks.append([
# "SHIP",
# "FS",
# "Firms.csv"])
# for x in outFileChecks:
# moduleWhichIsRun = x[0]
# moduleWhichIsNotRun = x[1]
# outfileToCheck = x[2]
# if moduleWhichIsRun in varDict['MODULES']:
# if moduleWhichIsNotRun not in varDict['MODULES']:
# if not os.path.isfile(varDict['OUTPUTFOLDER'] + outfileToCheck):
# run = False
# errorMessage = errorMessage + (
# 'Module ' +
# moduleWhichIsRun +
# ' is run but preceding module ' +
# moduleWhichIsNotRun +
# ' is not run. ' +
# 'In that case the following file is expected' +
# ' in the OUTPUTFOLDER, but it is not found: "' +
# outfileToCheck + '".\n')
# # Check on text files with dimensions / categories
# if os.path.isdir(varDict['DIMFOLDER']):
# dimFilenames = [
# 'combustion_type.txt',
# 'emission_type.txt',
# 'employment_sector.txt',
# 'flow_type.txt',
# 'logistic_segment.txt',
# 'municipality.txt',
# 'nstr.txt',
# 'shipment_size.txt',
# 'vehicle_type.txt']
# for filename in dimFilenames:
# if not os.path.isfile(varDict['DIMFOLDER'] + filename):
# run = False
# errorMessage = errorMessage + (
# 'Expected a text file called ' +
# '"' + filename + '"' +
# ' in DIMFOLDER, but could not find it.')
# Open the logfile and write the header, specified arguments and
# possible error messages
# if writeLog:
# self.logFileName = (
# varDict['OUTPUTFOLDER'] +
# "Logfile_20" +
# datetime.datetime.now().strftime("%y%m%d_%H%M%S") +
# ".log")
# with open(self.logFileName, "w") as f:
# f.write('##################################################\n')
# f.write('### Tactical Freight Simulator HARMONY ###\n')
# f.write('### Prototype version, January 2022 ###\n')
# f.write('##################################################\n')
# f.write('\n')
# f.write('##################################################\n')
# f.write('### Settings ###\n')
# f.write('##################################################\n')
# # f.write('Control file: ' + self.controlFile.get() + '\n')
# # for i in range(len(varValues)):
# # f.write(self.varStrings[i] + ' = ' + str(varValues[i]) + '\n')
# # if self.varStrings[i] in obsoleteVars and self.varStrings[i] != '':
# # f.write(
# # '\t(Note that variable ' +
# # self.varStrings[i] +
# # ' has become obsolete.' +
# # ' It is not used in any of the modules anymore.)\n')
# # f.write('\n')
# if not run:
# f.write('###################################################\n')
# f.write('### Errors while reading control file ###\n')
# f.write('###################################################\n')
# f.write(errorMessage)
# if run:
# self.statusBar.configure(text="Start calculations...")
# result = self.main(varDict)
# self.statusBar.configure(text="")
# if result[0] == 1:
# self.statusBar.configure(text=(
# "Error in calculation! " +
# "(Tool will be closed automatically after 20 seconds.)"))
# self.root.after(20000, lambda: self.root.destroy())
# else:
# self.statusBar.configure(text="Calculations finished.")
# self.progressBar['value'] = 100
# self.root.after(5000, lambda: self.root.destroy())
# else:
# self.statusBar.configure(text=(
# "Run was not started. See error message. "))
# errorMessage = (
# "Could not start the run for the following reasons: \n\n" +
# errorMessage)
# self.error_screen(text=errorMessage, size=[950, 150])
# def error_screen(self, text='', event=None,
# size=[950, 350], title='Error message'):
# '''
# Pop up a window with an error message
# '''
# windowError = tk.Toplevel(self.root)
# windowError.title(title)
# windowError.geometry(f'{size[0]}x{size[1]}+0+{self.height+50}')
# windowError.minsize(width=size[0], height=size[1])
# windowError.iconbitmap(bitmap=self.iconPath)
# labelError = tk.Label(
# windowError,
# text=text,
# anchor='w',
# justify='left')
# labelError.place(x=10, y=10)
def main(self, varDict):
run = True
result = [0, 0]
# with open(self.logFileName, "a") as f:
# f.write('###################################################\n')
# f.write('### Progress ###\n')
# f.write('###################################################\n')
args = [self, varDict]
# if run and 'FS' in varDict['MODULES']:
# print('\n')
# print('---------------------------------------------------')
# print('--------------- Firm Synthesis --------------------')
# print('---------------------------------------------------')
# f.write("Firm Synthesis" + '\n')
# f.write(
# "\tStarted at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n")
# self.statusBar.configure(
# text='Running Firm Synthesis...')
# result = __module_FS__.actually_run_module(args)
# if result[0] == 1:
# errorMessage = []
# errorMessage.append(
# '\nError in Firm Synthesis module!\n\n')
# errorMessage.append(
# 'See the log-file: ' +
# str(self.logFileName).split('/')[-1] + '\n\n')
# errorMessage.append(
# str(result[1][0]) + '\n' +
# str(result[1][1]) + '\n\n')
# self.error_screen(text=(
# errorMessage[0] +
# errorMessage[1] +
# errorMessage[2]))
# run = False
# f.write(errorMessage[0] + errorMessage[2])
# else:
# f.write(
# "\tFinished at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n\n")
# if run and 'SIF' in varDict['MODULES']:
# print('\n')
# print('---------------------------------------------------')
# print('--------- Spatial Interaction Freight -------------')
# print('---------------------------------------------------')
# f.write("Spatial Interaction Freight" + '\n')
# f.write(
# "\tStarted at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n")
# self.statusBar.configure(
# text='Running Spatial Interaction Freight...')
# result = __module_SIF__.actually_run_module(args)
# if result[0] == 1:
# errorMessage = []
# errorMessage.append(
# '\nError in Spatial Interaction Freight module!\n\n')
# errorMessage.append(
# 'See the log-file: ' +
# str(self.logFileName).split('/')[-1] + '\n\n')
# errorMessage.append(
# str(result[1][0]) + '\n' +
# str(result[1][1]) + '\n\n')
# self.error_screen(text=(
# errorMessage[0] +
# errorMessage[1] +
# errorMessage[2]))
# run = False
# f.write(errorMessage[0] + errorMessage[2])
# else:
# f.write(
# "\tFinished at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n\n")
if run and 'SHIP' in varDict['MODULES']:
print('\n')
print('---------------------------------------------------')
print('------------- Shipment Synthesizer ----------------')
print('---------------------------------------------------')
# f.write("Shipment Synthesizer" + '\n')
# f.write(
# "\tStarted at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n")
# self.statusBar.configure(
# text='Running Shipment Synthesizer...')
result = __module_SHIP__.actually_run_module(args)
# if result[0] == 1:
# errorMessage = []
# errorMessage.append(
# '\nError in Shipment Synthesizer module!\n\n')
# errorMessage.append(
# 'See the log-file: ' +
# str(self.logFileName).split('/')[-1] + '\n\n')
# errorMessage.append(
# str(result[1][0]) + '\n' +
# str(result[1][1]) + '\n\n')
# self.error_screen(text=(
# errorMessage[0] +
# errorMessage[1] +
# errorMessage[2]))
# run = False
# f.write(errorMessage[0] + errorMessage[2])
# else:
# f.write(
# "\tFinished at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n\n")
if run and 'TOUR' in varDict['MODULES']:
print('\n')
print('---------------------------------------------------')
print('---------------- Tour Formation -------------------')
print('---------------------------------------------------')
# f.write("Tour Formation" + '\n')
# f.write(
# "\tStarted at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n")
# self.statusBar.configure(
# text='Running Tour Formation...')
result = __module_TOUR__.actually_run_module(args)
# if result[0] == 1:
# errorMessage = []
# errorMessage.append(
# '\nError in Tour Formation module!\n\n')
# errorMessage.append(
# 'See the log-file: ' +
# str(self.logFileName).split('/')[-1] + '\n\n')
# errorMessage.append(
# str(result[1][0]) + '\n' +
# str(result[1][1]) + '\n\n')
# self.error_screen(text=(
# errorMessage[0] +
# errorMessage[1] +
# errorMessage[2]))
# run = False
# f.write(errorMessage[0] + errorMessage[2])
# else:
# f.write(
# "\tFinished at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n\n")
# if run and 'PARCEL_DMND' in varDict['MODULES']:
# print('\n')
# print('---------------------------------------------------')
# print('---------------- Parcel Demand --------------------')
# print('---------------------------------------------------')
# f.write("Parcel Demand" + '\n')
# f.write(
# "\tStarted at: " +
# datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") +
# "\n")
# self.statusBar.configure(
# text='Running Parcel Demand...')
# result = __module_PARCEL_DMND__.actually_run_module(args)
# if result[0] == 1:
# errorMessage = []
# errorMessage.append(
# '\nError in Parcel Demand module!\n\n')
# errorMessage.append(
# 'See the log-file: ' +