-
Notifications
You must be signed in to change notification settings - Fork 1
/
CARS_rev_06.py
2831 lines (2372 loc) · 151 KB
/
CARS_rev_06.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
# -*- coding: utf-8 -*-
"""
@author: Rizzieri Pedruzzi - [email protected] or [email protected]
"""
import os, sys, time, matplotlib, glob
import pandas as pd
import geopandas as gpd
import numpy as np
import datetime as dt
from shapely.geometry import Polygon
import pyproj, csv
import calendar
import matplotlib.pyplot as plt
from netCDF4 import Dataset
#matplotlib.use('Agg')
total_start_time = time.time()
'''
***** Case name and path to the folders - Please, set for all directories *****
'''
case_name = 'Country_Minwoo_v06' #'_Seoul_Old_AD'#
home_dir = r'C:/Users/pedruzzi/OneDrive - University of North Carolina at Chapel Hill/0000_EUA_IE/001_mobile_source_inventory/CARS_source_code/CARS_test_Country_Minwoo'
src_dir = home_dir+'/src'
input_dir = home_dir+'/input_country_from_KU'
inter_dir = home_dir+'/intermediate'#+case_name
output_dir = home_dir+'/output_'+case_name
met_dir = input_dir+'/metdata'
'''
***** Dates and Runlenght *****
'''
STDATE = '2017-01-02' # start date
ENDATE = '2017-01-02' # end date
STTIME = 00 # start time
RUNLEN = 24 # run length
'''
***** INPUT FILES, SHAPEFILES and attibutes *****
Set in this part the:
Activity data file;
List of Emissions factors tables (eg. in python, the list is set by brackets [])
Average Speed Distribution to calculate the 16 Speed bins emissions factors
Link and county Shape file with their attibute values
**** WARNING ****: the attibute information are from the attribute of the shapefile
make sure you are setting the correct name.
'''
temp_max = 17.8
temp_mean = 12.9
temp_min = 7.8
activity_file = 'cars_input_v3.2.2.csv' #'seoul_2017_OLD.csv' #
Emis_Factor_list = ['cng_v3.csv','diesel_v3.csv','gasoline_v3.csv','lpg_v3.csv',
'H-CNG_v3.csv','H-Diesel_v3.csv','H-Gasoline_v3.csv' ,'H-LPG_v3.csv'] #['gasoline.csv','diesel.csv','cng.csv','lpg.csv']
Cold_Start_list = ['cold_start_vehicles.csv']
avg_SPD_Dist_file = 'avgSpeedDistribution_rev_01.csv'
link_shape = '/shapes'+'/Road_by_County_SK_AADT_UTM52N.shp'
link_shape_att = ['LINK_ID' , 'EMD_CD' , 'EMD_ENG_NM', 'EMD_ENG_NM',
'ROAD_RANK', 'spd', 'SHAPE_STLe', 'VKT']
county_shape = '/shapes/TL_SCCO_EMD.shp'
county_shape_att = ['EMD_CD', 'EMD_ENG_NM', 'EMD_KOR_NM']
'''
'***** Temporal profiles names *****'
'''
temporal_profile_folder = input_dir+'/temporal_profile'
temporal_monthly_file = 'monthly_profile.csv'
temporal_week_file = 'week_profile.csv'
temporal_weekday_file = 'weekday_profile.csv'
temporal_weekend_file = 'weekend_profile.csv'
temporal_CrossRef = 'temporal_profile_CrossRef.csv'
'''
'***** Chemical speciation for PM2.5, VOC and NOx *****'
'''
chemical_profile_folder = input_dir+'/chemical_speciation'
chemical_profile = 'gspro_cmaq_cb6_2014fa_nata_cb6cmaq_14j_criteria.txt'
speciation_CrossRef = 'chem_profile_CrossRef.csv'
'''
Do you want to apply Deterioration factor into emissions factors?
If YES, set Deterioration_CALC = 'yes' and insert the deterioration
list file. Remember that vehciles names should match with emissions factor
and Activity data
'''
Deterioration_CALC = 'yes'
Deterioration_list = ['degradation_rate_Diesel.csv','degradation_rate_Gasoline.csv','degradation_rate_LPG.csv']
'''
Do you want to apply Control factors into emissions?
If YES, set Control_CALC = 'yes' and insert the control
list file. Remember that vehciles names should match with emissions factor
and Activity data
'''
Control_CALC = 'no' #'yes'
Control_list = ['control_factors_emergency_sma.csv']#['control_factors.csv']
''' IT IS NOT IMPLEMENTED
Do you want to estimate emissions for the future ?
If YES, set future_case = 'yes' and make sure there are activity data and
emissions factor for the vehicles you want to estimate.
Remember that vehciles names should match with emissions factor and Activity data
'''
future_case = 'no' #'yes' or 'no'
'''
***** PLOTTING *****
Do you want to generate the figures?
One option is the Adjustment of the plot scale. This was added to allow the user
change the scale of all plots, because sometimes, there are one point with high emissions
than the rest of the domain, so there is the need to renormalize the scale.
The adj_scale will multiply the maximum value of the plot area, so it will reduce
or increase the maximum value of the scale.
To use it, set the adj_scale to the value you want (e.g. 0.5) The default value is 0.4
*** WARNING ***: The plotting takes a bit longer to finish especially the 24 hours plot
'''
plot_figures = 'no' #'yes' or 'no'
plot_24 = 'no' #'yes' or 'no' #24 hours animated plot
adj_scale = 0.4
'''
'********** Gridding options **********'
If the user DO NOT want to generate the grid based on the GRIDDESC,
set the grid_size in meters (e.g 1000) and the grid2CMAQ = 'no'
'''
grid_size = 27000
'''
CARS has the option to create grid to air quality modeling.
To set it, change set grid2CMAQ to 'yes'
Set the gridfile_name pointing to GRIDDESC file.
Set the Radius_Earth (default=6370000.0)
Set the Datum
'''
grid2CMAQ = 'no' #'yes' or 'no'
gridfile_name = met_dir+'/GRIDDESC_NIER_09_01'
Radius_Earth = 6370000.0
Datum = 'WGS84'
'''
Do you want to CARS outpout the GRID shapefile?
If yes, set the outGridShape = 'yes'
This option was added because sometimes generate the shapefile
can take couple minutes.
'''
outGridShape = 'no'
'''
----------------------------------------------------------------------------------------
End of users input. Please, DO NOT CHANGE the code below this point.
Any bugs or issues report at
https://github.com/rpedruzzi/CARS
'''
if not os.path.exists(home_dir+'/intermediate'):
print('*** intermediate directory does not exist: Creating a new one')
os.makedirs(home_dir+'/intermediate/')
if not os.path.exists(output_dir):
print('*** Outdir directory does not exist: Creating a new one')
os.makedirs(output_dir)
if not os.path.exists(input_dir+'/emissions_factor/'):
print('emissions_factor directory does not exist: Creating a new one')
print('Remember to put the emissions factor files, average speed distribuition file,')
print('cold start vehicle files, degradation factor file and control factors file')
print('inside the emissions_factor directory')
os.makedirs(input_dir+'/emissions_factor/')
if not os.path.exists(output_dir+'/plots'):
print('*** intermediate directory does not exist: Creating a new one')
os.makedirs(output_dir+'/plots/')
if not os.path.exists(output_dir+'/LOGS'):
print('*** LOG directory does not exist: Creating a new one')
os.makedirs(output_dir+'/LOGS')
STDATE = STDATE+' {:>02.2s}'.format(str(STTIME))
RUNLEN = RUNLEN+1
df_times = pd.date_range(start=STDATE, freq='H', periods=RUNLEN )
run_period = pd.DataFrame({'DateTime' : df_times})
run_period['dayofweek'] = run_period.DateTime.dt.strftime('%a').str.lower() #%a or %A
run_period['month'] = run_period.DateTime.dt.strftime('%b').str.lower() #%a or %A
run_period[['Day','Hour']] = run_period['DateTime'].dt.strftime('%Y-%m-%d_%H:%M:%S').str.split('_',expand=True)
run_period['jul_day'] = run_period.DateTime.dt.strftime('%Y%j').astype(int)
run_period['jul_hour'] = run_period.DateTime.dt.strftime('%H0000').astype(int)
run_period['TFLAG'] = list(zip(run_period.jul_day, run_period.jul_hour))
class EmissionFactor_table:
def __init__(self, dataframe, name ):
self.dataframe = dataframe
self.name = name.split('.')[0]
class Activity_Data_table:
def __init__(self, dataframe, vhc_name, years, fuels, vehicle, vhc_count):
self.data = dataframe
self.fullname = vhc_name
self.years = years
self.fuels = fuels
self.vhc = vehicle
self.vhc_count = vhc_count
class Roads_Grid_table:
def __init__(self, grid_dataframe, surrogate, roads_df):
self.grid = grid_dataframe
self.surrogate = surrogate
self.roads_df = roads_df
class EF_Grid_table:
def __init__(self, EF_dataframe, EF_years, VHC_fullname_EF, Fuel_EF, Polls_EF):
self.data = EF_dataframe
self.EF_years = EF_years
self.EF_fullname = VHC_fullname_EF
self.EF_fuels = Fuel_EF
self.EF_polls = Polls_EF
class EF_Speed_Distribution:
def __init__(self, SPD_dataframe, Speeds, Speed_Bins):
self.data = SPD_dataframe
self.spd = Speeds
self.spd_bins = Speed_Bins
class Emissions_table:
def __init__(self, County_Emissions, County_Emissions_GeoRef,
County_Emissions_GeoRef_WGT,County, Years, vhc_name, road_by_county):
self.county_by_yr = County_Emissions
self.county_total = County_Emissions_GeoRef
self.county_total_WGT = County_Emissions_GeoRef_WGT
self.counties = County
self.years = Years
self.fullname = vhc_name
self.road_by_county = road_by_county
class Emissions_ChemSpec:
def __init__(self, ChemSpec_emissions, Grams_pollutants, Moles_pollutants):
self.chemspec_emissions = ChemSpec_emissions
self.grams_pol = Grams_pollutants
self.moles_pol = Moles_pollutants
class Temporal_table:
def __init__(self, temporal_monthly, temporal_week, temporal_weekday, temporal_weekend, temporal_CrossRef, Diurnal_profile):
self.monthly = temporal_monthly
self.week = temporal_week
self.weekday = temporal_weekday
self.weekend = temporal_weekend
self.crossref = temporal_CrossRef
self.diurnalPro = Diurnal_profile
class Chemical_Speciation_table:
def __init__(self, chemical_profile, speciation_CrossRef):
self.chempro = chemical_profile
self.crossref = speciation_CrossRef
class GRID_info_table:
def __init__(self, NTHIK, NCOLS, NROWS, NLAYS, GDTYP, P_ALP, P_BET, P_GAM,
XCENT, YCENT, XORIG, YORIG, XCELL, YCELL, GDNAM):
self.NTHIK = NTHIK
self.NCOLS = NCOLS
self.NROWS = NROWS
self.NLAYS = NLAYS
self.GDTYP = GDTYP
self.P_ALP = P_ALP
self.P_BET = P_BET
self.P_GAM = P_GAM
self.XCENT = XCENT
self.YCENT = YCENT
self.XORIG = XORIG
self.YORIG = YORIG
self.XCELL = XCELL
self.YCELL = YCELL
self.GDNAM = GDNAM
# =============================================================================
# Function to create the GrayJet colormap
# =============================================================================
def createGrayJet():
from matplotlib import cm
from matplotlib.colors import ListedColormap
import numpy as np
jet = cm.get_cmap('jet', 256)
newcolors = jet(np.linspace(0, 1, 256))
newcolors[0, :] = np.array([256/256, 256/256, 256/256, 1]) #white
newcolors[1:4, :] = np.array([200/256, 200/256, 200/256, 1]) #lightgray
GrayJet = ListedColormap(newcolors)
return GrayJet
# =============================================================================
GrayJet = createGrayJet()
# =============================================================================
# Function to read Temporal information
# =============================================================================
def read_griddesc(input_dir, gridfile_name, grid2CMAQ = 'no'):
if ((grid2CMAQ == 'yes') or (grid2CMAQ == 'y') or (grid2CMAQ == 'Y') or \
(grid2CMAQ == 'YES')) and (gridfile_name != ''):
start_time = time.time()
input_dir = input_dir
gridfile_name = gridfile_name
print('******************************************************************')
print('***** Processing GRIDDESC *****')
print('***** Please wait ... *****')
print('******************************************************************')
print('')
if os.path.exists(gridfile_name) == True:
print ('')
print ('Reading GridDesc file to generate gridded emissions ...')
print (gridfile_name)
griddesc = pd.read_csv(gridfile_name, header=None,engine='python')
GDTYP, P_ALP, P_BET, P_GAM, XCENT, YCENT = griddesc.loc[2,0].split()
P_ALP, P_BET, P_GAM, XCENT, YCENT = map(float, [P_ALP, P_BET, P_GAM, XCENT, YCENT])
GDTYP = int(GDTYP)
GDNAM = griddesc.loc[4,0].split()[0].replace("'",'')
COORD_NAME, XORIG, YORIG, XCELL, YCELL, NCOLS, NROWS, NTHIK = griddesc.loc[5,0].split()
XORIG, YORIG, XCELL, YCELL = map(float, [XORIG, YORIG, XCELL, YCELL])
NCOLS, NROWS, NTHIK = map(int, [NCOLS, NROWS, NTHIK])
NLAYS = 1 #for now NLAYS is equal 1 because CARS generates emissions only for the first level
else:
print ('')
print('*** ERROR ABORT ***: Griddesc file {0} does not exist!'.format(gridfile_name))
sys.exit('CARS can not read Griddesc file')
return GRID_info_table(NTHIK, NCOLS, NROWS, NLAYS, GDTYP, P_ALP, P_BET, P_GAM,
XCENT, YCENT, XORIG, YORIG, XCELL, YCELL, GDNAM)
else:
return
GRID_info = read_griddesc(input_dir, gridfile_name, grid2CMAQ = grid2CMAQ)
# =============================================================================
# Function to read Temporal information
# =============================================================================
def read_temporal_info(Temporal_Profile_Folder, Temporal_Monthly, Temporal_Week,
Temporal_WeekDay, Temporal_WeekEnd, Temporal_CrossRef, Run_Period):
start_time = time.time()
print('******************************************************************')
print('***** Processing temporal profile *****')
print('***** Please wait ... *****')
print('******************************************************************')
print('')
temp_dir = Temporal_Profile_Folder #temporal_profile_folder #
# sep = ';'
# Temporal_Monthly = 'monthly_profile.csv'
# Temporal_Week = 'week_profile.csv'
# Temporal_WeekDay = 'weekday_profile.csv'
# Temporal_WeekEnd = 'weekend_profile.csv'
# Temporal_CrossRef = 'temporal_profile_CrossRef_Seoul.csv' #'temporal_profile_CrossRef.csv'
month = '{0}{1}'.format(temp_dir+'/',Temporal_Monthly)
week = '{0}{1}'.format(temp_dir+'/',Temporal_Week)
weekday = '{0}{1}'.format(temp_dir+'/',Temporal_WeekDay)
weekend = '{0}{1}'.format(temp_dir+'/',Temporal_WeekEnd)
crossref = '{0}{1}'.format(temp_dir+'/',Temporal_CrossRef)
Times = Run_Period #run_period #
files = [month, week, weekday, weekend, crossref]
for ifl in files:
if os.path.exists(ifl) == False:
print ('')
print('*** ERROR ABORT ***: Temporal file ', ifl, ' "" does not exist!')
sys.exit('CARS preProcessor can not read Temporal profile')
else:
print ('')
print ('*** Reading Temporal information : ***')
print (ifl)
with open(month, 'r') as csvfile:
sep = csv.Sniffer().sniff(csvfile.read(40960)).delimiter
month_out = pd.read_csv(month, sep = sep).fillna(np.nan)
week_out = pd.read_csv(week, sep = sep).fillna(np.nan)
weekday_out = pd.read_csv(weekday, sep = sep).fillna(np.nan)
weekend_out = pd.read_csv(weekend, sep = sep).fillna(np.nan)
crossref_out = pd.read_csv(crossref, sep = sep).fillna(np.nan)
month_out.columns = map(str.lower, month_out.columns)
week_out.columns = map(str.lower, week_out.columns)
weekday_out.columns = map(str.lower, weekday_out.columns)
weekend_out.columns = map(str.lower, weekend_out.columns)
crossref_out.columns = map(str.lower, crossref_out.columns)
crossref_out['fullname'] = crossref_out.vehicle.str.cat(crossref_out[['types','fuel']], sep='_')
CR_month = crossref_out.loc[:,['fullname','road_type','month']]
CR_week = crossref_out.loc[:,['fullname','road_type','week']]
CR_wday = crossref_out.loc[:,['fullname','road_type','weekday']]
CR_wend = crossref_out.loc[:,['fullname','road_type','weekend']]
CR_month = pd.merge(CR_month, month_out , left_on='month' , right_on='profile', how='left')
CR_week = pd.merge(CR_week , week_out , left_on='week' , right_on='profile', how='left')
CR_wday = pd.merge(CR_wday , weekday_out, left_on='weekday' , right_on='profile', how='left')
CR_wend = pd.merge(CR_wend , weekend_out, left_on='weekend' , right_on='profile', how='left')
diurnal_temp = pd.DataFrame(columns=['Day']+list(CR_wday.columns)) #['DateTime']+list(CR_wday.fullname)) #
for i in Times.Day.unique():
x,y,z = i.split('-')
imonth = (dt.date(int(x), int(y), int(z))).strftime('%b').lower()
DofW = (dt.date(int(x), int(y), int(z))).strftime('%a').lower()
mon_week_F = pd.merge(CR_month.loc[:,['fullname','road_type',imonth]] ,
CR_week.loc[:,['fullname','road_type',DofW]] ,
left_on=['fullname','road_type'] ,
right_on=['fullname','road_type'], how='left')
ndays = pd.Period(i).days_in_month #getting the number of days in a month to apply into weekl profile
mon_week_F['factor'] = mon_week_F[imonth] * ( mon_week_F[DofW] * (7/ndays))
colsD = [str(y) for y in range(0,24)]
if (DofW == 'sun') or (DofW == 0) or (DofW == 'sat') or (DofW == 6):
aux_diurnal = CR_wend.copy()
aux_diurnal['Day'] = [i for x in aux_diurnal.index]
aux_diurnal.loc[:,colsD] = aux_diurnal.loc[:,colsD].apply(lambda x: np.asarray(x) * mon_week_F['factor'].values)
else:
aux_diurnal = CR_wday.copy()
aux_diurnal['Day'] = [i for x in aux_diurnal.index]
aux_diurnal.loc[:,colsD] = aux_diurnal.loc[:,colsD].apply(lambda x: np.asarray(x) * mon_week_F['factor'].values)
diurnal_temp = diurnal_temp.append(aux_diurnal,ignore_index=True, sort=False)
diurnal_temp = diurnal_temp.loc[:,['Day', 'fullname', 'road_type', 'profile']+list((np.arange(0,24)).astype(str))]
run_time = ((time.time() - start_time))
print('--- Elapsed time in seconds = {0} ---'.format(run_time))
print('--- Elapsed time in minutes = {0} ---'.format(run_time/60))
print('--- Elapsed time in hours = {0} ---'.format(run_time/3600))
print('')
print('******************************************************************')
print('***** Temporal calculation is done *****')
print('******************************************************************')
print('')
return Temporal_table(month_out, week_out, weekday_out, weekend_out, crossref_out, diurnal_temp)
TempPro = read_temporal_info(temporal_profile_folder, temporal_monthly_file, temporal_week_file,
temporal_weekday_file, temporal_weekend_file, temporal_CrossRef, run_period)
# =============================================================================
# Function to read Chemical speciation
# =============================================================================
def read_chemical_info(Chemical_Speciation_Folder, chemical_profile, Speciation_CrossRef):
start_time = time.time()
spec_dir = Chemical_Speciation_Folder #chemical_profile_folder#
chempro = '{0}{1}'.format(spec_dir+'/',chemical_profile)
crossref = '{0}{1}'.format(spec_dir+'/',Speciation_CrossRef) #speciation_CrossRef)#
files = [chempro, crossref]
for ifl in files:
if os.path.exists(ifl) == False:
print ('')
print('*** ERROR ABORT ***: Chemical Speciation file ', ifl, ' "" does not exist!')
sys.exit('CARS preProcessor can not read Chemical Speciation file')
else:
print ('')
print ('*** Reading Chemical Speciation information ... ***')
print (ifl)
with open(chempro, 'r') as csvfile:
sep = csv.Sniffer().sniff(csvfile.read(100000)).delimiter
chempro_out = pd.read_csv(chempro, sep = sep, comment='#',
header=None, usecols=[0,1,2,3,4],
names=['profile', 'pollutant', 'species', 'fraction', 'mw'],
engine ='python').fillna(0)
chempro_out['pollutant'] = chempro_out['pollutant'].str.replace('_','.')
chempro_out['pollutant'] = chempro_out['pollutant'].str.upper()
crossref_out = pd.read_csv(crossref, sep = sep, dtype=str).fillna(0)
run_time = ((time.time() - start_time))
print('--- Elapsed time in seconds = {0} ---'.format(run_time))
print('--- Elapsed time in minutes = {0} ---'.format(run_time/60))
print('--- Elapsed time in hours = {0} ---'.format(run_time/3600))
return Chemical_Speciation_table(chempro_out, crossref_out)
Chemical_Spec_Table = read_chemical_info(chemical_profile_folder, chemical_profile, speciation_CrossRef)
# =============================================================================
# Function to read the Speed average distribution
# =============================================================================
def read_avgSpeedDistribution(input_dir, avg_Speed_Distribution_file):
start_time = time.time()
input_dir = input_dir
spd_file = avg_SPD_Dist_file #avg_Speed_Distribution_file
name = '{0}{1}{2}'.format(input_dir,'/emissions_factor/',spd_file)
if os.path.exists(name) == True:
print ('')
print ('Reading Average Speed Distribution table ...')
print (name)
with open(name, 'r') as csvfile:
sep = csv.Sniffer().sniff(csvfile.read(4096)).delimiter
ASD = pd.read_csv(name, sep = sep).fillna(np.nan)
for ird in [101, 102, 103, 104, 105, 106, 107, 108]:
ASD.loc[:,str(ird)] = ASD.loc[:,str(ird)] / ASD.loc[:,str(ird)].sum()
else:
print ('')
print('*** ERROR ABORT ***: Average speed Distribution ', spd_file, ' "" does not exist!')
sys.exit('CARS preProcessor can not read Average speed Distribution')
out_spd_bins = pd.DataFrame({'spd_bins': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]})
out_spd = pd.DataFrame({'spd': list(ASD.Speed)})
run_time = ((time.time() - start_time))
print('--- Elapsed time in seconds = {0} ---'.format(run_time))
print('--- Elapsed time in minutes = {0} ---'.format(run_time/60))
print('--- Elapsed time in hours = {0} ---'.format(run_time/3600))
return EF_Speed_Distribution(ASD, out_spd, out_spd_bins)
avgSpeedDist = read_avgSpeedDistribution(input_dir, avg_SPD_Dist_file)
# =============================================================================
# Function to read the Activity Data
# =============================================================================
def read_activity_data_csv_SK(input_dir, ad_file, End_date, future_case = 'NO'):
start_time = time.time()
ad_file = ad_file #activity_file #
end_date = End_date #ENDATE #
future_case = future_case
# now = dt.datetime.now()
# ad_file = activity_file
# end_date = ENDATE
if len(end_date.split('-')) < 3:
print ('')
print ('***** ERROR *****: Please, Start date and End Data should be written as YYYY-MM-DD')
print ('')
sys.exit()
else:
current_yr = int(end_date.split('-')[0])
name = '{0}{1}{2}'.format(input_dir,'/activity_data/',ad_file)
with open(name, 'r') as csvfile:
sep = csv.Sniffer().sniff(csvfile.read(4096)).delimiter
outdf = pd.DataFrame(columns=['fuel','vehicle','types','daily_vkt','region_cd',
'manufacture_date'])
count_outdf = pd.DataFrame()
if os.path.exists(name) == True:
print ('')
print ('Reading Activity Data table ...')
print (name)
vhc_fuels = pd.DataFrame()
vhc_cars = pd.DataFrame()
for activity_data in pd.read_csv(name, chunksize=1500000, sep = sep, usecols = [0,1,2,3,4,5]):
print(activity_data.shape)
activity_data = activity_data.fillna(0)
# activity_data = pd.read_csv(name, chunksize=1500000, sep = sep, usecols = [0,1,2,3,4,5])
'''
header
0, 1, 2, 3, 4, 5,
Fuel,vehicle,Types,Daily_VKT,Region_code,Manufacture_date,
'''
activity_data.columns = ['fuel','vehicle','types','daily_vkt','region_cd',
'manufacture_date']
activity_data.loc[:,'vehicle'] = activity_data.loc[:,'vehicle'].str.lower()
activity_data.loc[:,'fuel'] = activity_data.loc[:,'fuel'].str.lower()
activity_data.loc[:,'types'] = activity_data.loc[:,'types'].str.lower()
activity_data.loc[:,'manufacture_date'] = (activity_data.loc[:,'manufacture_date'] / 10000).astype(int)
activity_data['fullname'] = activity_data.vehicle.str.cat(activity_data[['types','fuel']], sep='_')
activity_data['count'] = 1
vhc_fuels = vhc_fuels.append(pd.DataFrame({'fuels' : list(activity_data['fuel'].unique())}),ignore_index=True, sort=False)
vhc_cars = vhc_cars.append(pd.DataFrame({'vhc' : list(activity_data['vehicle'].unique())}),ignore_index=True, sort=False)
if (activity_data.loc[:,'manufacture_date'].max() > current_yr) and \
(future_case == 'NO') or (future_case == 'no') or (future_case == 'N') or (future_case == 'n'):
AD_max_yr = activity_data.loc[:,'manufacture_date'].max()
idx_drop = list(activity_data.loc[activity_data['manufacture_date'] > current_yr].index)
print('***** WARNING *****')
print('*** There are Activity data for future years . Check your input data ***')
print('Current year {0} : Activity data max year {1}'.format(current_yr,AD_max_yr))
print('*** Deleting these years ... ***')
activity_data = activity_data.drop(index=idx_drop).reset_index(drop=True)
if activity_data.loc[:,'daily_vkt'].min() < 0:
print('***** WARNING *****')
print('*** There are zero/null Activity data. Check your input data ***')
print('*** Deleting these data ... ***')
idxneg_drop = list(activity_data.loc[activity_data['daily_vkt'] < 0].index)
activity_data = activity_data.drop(index=idxneg_drop).reset_index(drop=True)
count_vhc = activity_data.groupby(['region_cd','fullname','manufacture_date']).sum().reset_index(drop=False)
count_vhc = count_vhc.drop(columns=['daily_vkt'])
count_vhc = count_vhc.sort_values(by=['region_cd','fullname','manufacture_date'])
count_vhc = count_vhc.pivot_table(values='count',
index=['region_cd','manufacture_date'],
columns='fullname',
aggfunc=np.sum, fill_value=0).reset_index(drop=False)
if count_outdf.shape[0] == 0:
count_outdf = count_vhc
else:
count_outdf = count_outdf.append(count_vhc, sort=True)
activity_data = activity_data.drop(columns=['count'])
grouped = activity_data.groupby(['manufacture_date','region_cd','fullname']).sum().reset_index(drop=False)
grouped = grouped.pivot_table(values='daily_vkt',
index=['manufacture_date','region_cd'],
columns='fullname',
aggfunc=np.sum).reset_index(drop=False).fillna(0.0)
grouped = grouped.sort_values(by=['region_cd','manufacture_date']).reset_index(drop=True)
outdf = outdf.append(grouped, ignore_index=True, sort=False)
# vhc_names = pd.DataFrame({'vhc_name' : list(activity_data.FullName.unique())})
# vhc_years = pd.DataFrame({'vhc_years' : list(grouped.manufacture_date.unique())})
# out_table = Activity_Data_table(grouped, vhc_names,vhc_years)
else:
print('*** ERROR ABORT ***: Emissions Factor file "" ', ad_file, ' "" does not exist!')
sys.exit('CARS preProcessor can not read Emissions Factor file')
count_outdf = count_outdf.groupby(['region_cd','manufacture_date']).sum().reset_index(drop=False)
count_outdf = count_outdf.sort_values(by=['region_cd','manufacture_date']).reset_index(drop=True)
outdf = outdf.groupby(['manufacture_date','region_cd']).sum().reset_index(drop=False)
outdf = outdf.sort_values(by=['region_cd','manufacture_date']).reset_index(drop=True)
nvhc = list(np.sort(outdf.columns))
nvhc.remove('manufacture_date')
nvhc.remove('region_cd')
vhc_names = pd.DataFrame({'vhc_name' : nvhc})
vhc_years = pd.DataFrame({'vhc_years' : list(outdf.manufacture_date.unique())})
vhc_fuels = pd.DataFrame({'fuels' : list(vhc_fuels.fuels.unique())})
vhc_cars = pd.DataFrame({'vhc' : list(vhc_cars.vhc.unique())})
# There are "generic" counties condes endind with 0000. So we aggregate it
# and split into the counties wich starts with the same four digits based on
# the vehicle with the greatest VKT
outdf.loc[:,'region_cd'] = outdf.loc[:,'region_cd'].astype(str)
gendf_list_drop = outdf.loc[(outdf.region_cd.str.endswith(('0000','000')))].index.to_list()
print('')
print('***** WARNING *****: There counties with generic entry, meaning it ends with "0000" ')
print('***** WARNING *****: These VKT values will be assigned into counties with similar region code')
print('')
gendf = outdf.loc[outdf.region_cd.str.endswith(('0000','000'))].reset_index(drop=True)
gendf['region_cd_4dig'] = gendf.loc[:,'region_cd'].str.slice(stop=4)
gendf_years = list(gendf.manufacture_date.unique())
outdf = outdf.drop(index=gendf_list_drop).reset_index(drop=True)
sumdict = outdf.loc[:,nvhc].sum().to_dict()
vhc_max_vkt = max(sumdict, key=sumdict.get) #getting the name og the vehivle with greatest VKT
# Creating the split factor based on the VKT of vehicle vhc_max_vkt
splitdf = outdf.loc[outdf.manufacture_date.isin(gendf_years),['manufacture_date','region_cd',vhc_max_vkt]].reset_index(drop=True)
splitdf = splitdf.rename(columns={vhc_max_vkt : 'split_factor'})
splitdf['region_cd_4dig'] = splitdf.loc[:,'region_cd'].str.slice(stop=4)
auxsplit = splitdf.groupby(['region_cd_4dig']).sum().reset_index(drop=False)
auxsplit = auxsplit.rename(columns={'split_factor' : 'total_by_cnt'})
auxsplit = auxsplit.drop(columns=['manufacture_date'])
splitdf = pd.merge(splitdf, auxsplit, right_on='region_cd_4dig', left_on='region_cd_4dig', how='left')
splitdf.loc[:,'split_factor'] = (splitdf.loc[:,'split_factor'] / splitdf.loc[:,'total_by_cnt']).fillna(0.0)
# Getting the total VKT by the "generic" county code
gendf = gendf.groupby(['region_cd_4dig']).sum().reset_index(drop=False)
gendf = gendf.drop(columns=['manufacture_date'])
gendf = pd.merge(gendf, splitdf.loc[:,['manufacture_date','region_cd','split_factor','region_cd_4dig']],
left_on ='region_cd_4dig', right_on ='region_cd_4dig', how='right').fillna(0.0)
# Applying the split factor after merge the df
gendf.loc[:,nvhc] = gendf.loc[:,nvhc].apply(lambda x: np.asarray(x) * gendf.split_factor.values).fillna(0.0)
gendf = gendf.drop(columns=['region_cd_4dig', 'split_factor'])
gendf = pd.merge(outdf.loc[:,['manufacture_date', 'region_cd']], gendf,
left_on = ['manufacture_date', 'region_cd'],
right_on = ['manufacture_date', 'region_cd'], how='left').fillna(0.0)
# Summing the splitted "Generic VKT" into the output dataframe
outdf.loc[:,nvhc] = outdf.loc[:,nvhc].add(gendf.loc[:,nvhc], axis=1)
outdf = outdf.groupby(['manufacture_date', 'region_cd']).sum().reset_index(drop=False)
# ------------------------------------------------------------------------#
# Doing the same split to the vehicle count
count_outdf.loc[:,'region_cd'] = count_outdf.loc[:,'region_cd'].astype(str)
count_list_drop = count_outdf.loc[count_outdf.region_cd.str.endswith('0000')].index.to_list()
print('')
print('***** WARNING *****: There counties with generic entry, meaning it ends with "0000" ')
print('***** WARNING *****: These VKT values will be assigned into counties with similar region code')
print('')
count_gendf = count_outdf.loc[count_outdf.region_cd.str.endswith('0000')].reset_index(drop=True)
count_gendf['region_cd_4dig'] = count_gendf.loc[:,'region_cd'].str.slice(stop=4)
count_outdf = count_outdf.drop(index=count_list_drop).reset_index(drop=True)
sumdict = count_outdf.loc[:,nvhc].sum().to_dict()
vhc_max_vkt = max(sumdict, key=sumdict.get) #getting the name og the vehivle with greatest VKT
# Creating the split factor based on the VKT of vehicle vhc_max_vkt
count_splitdf = count_outdf.loc[:,['manufacture_date','region_cd',vhc_max_vkt]]
count_splitdf = count_splitdf.rename(columns={vhc_max_vkt : 'split_factor'})
count_splitdf['region_cd_4dig'] = count_splitdf.loc[:,'region_cd'].str.slice(stop=4)
count_auxsplit = count_splitdf.groupby(['region_cd_4dig']).sum().reset_index(drop=False)
count_auxsplit = count_auxsplit.rename(columns={'split_factor' : 'total_by_cnt'})
count_auxsplit = count_auxsplit.drop(columns=['manufacture_date'])
count_splitdf = pd.merge(count_splitdf, count_auxsplit, right_on='region_cd_4dig', left_on='region_cd_4dig', how='left')
count_splitdf.loc[:,'split_factor'] = (count_splitdf.loc[:,'split_factor'] / count_splitdf.loc[:,'total_by_cnt']).fillna(0.0)
# Getting the total VKT by the "generic" county code
count_gendf = count_gendf.groupby(['region_cd_4dig']).sum().reset_index(drop=False)
count_gendf = count_gendf.drop(columns=['manufacture_date'])
count_gendf = pd.merge(count_gendf, count_splitdf.loc[:,['manufacture_date','region_cd','split_factor','region_cd_4dig']],
left_on ='region_cd_4dig', right_on ='region_cd_4dig', how='right').fillna(0.0)
# Applying the split factor after merge the df
count_gendf.loc[:,nvhc] = count_gendf.loc[:,nvhc].apply(lambda x: np.asarray(x) * count_gendf.split_factor.values).fillna(0.0)
count_gendf = count_gendf.drop(columns=['region_cd_4dig', 'split_factor'])
# Summing the splitted "Generic VKT" into the output dataframe
count_outdf.loc[:,nvhc] = count_outdf.loc[:,nvhc].add(count_gendf.loc[:,nvhc], axis=1)
count_outdf = count_outdf.groupby(['manufacture_date', 'region_cd']).sum().reset_index(drop=False)
run_time = ((time.time() - start_time))
print('--- Elapsed time in seconds = {0} ---'.format(run_time))
print('--- Elapsed time in minutes = {0} ---'.format(run_time/60))
print('--- Elapsed time in hours = {0} ---'.format(run_time/3600))
return Activity_Data_table(outdf, vhc_names, vhc_years, vhc_fuels, vhc_cars, count_outdf)
## =============================================================================
AD_SK = read_activity_data_csv_SK(input_dir, activity_file, ENDATE)
# =============================================================================
# Function to read link level shapefile
# =============================================================================
def roads_grid_surrogate_inf(input_dir, File_Name, Link_Shape_att, GridDesc_file='', Radius_Earth='', outGridShape = 'yes', Unit_meters = True):
start_time = time.time()
Link_Shape_att = link_shape_att
Link_ID_attr = Link_Shape_att[0] #= Link_ID_attr
Region_CD = Link_Shape_att[1] #= Region_Code
Region_NM = Link_Shape_att[2] #= Region_Name
RD_name_attr = Link_Shape_att[3] #= RD_name_attr
RD_type_attr = Link_Shape_att[4] #= RD_type_attr
Speed_attr = Link_Shape_att[5] #= Speed_attr
Link_length = Link_Shape_att[6] #= Link_length
VKT_attr = Link_Shape_att[7] #= VKT_attr
file_name = File_Name #link_shape #
gridfile_name = GridDesc_file #gridfile_name #
outGridShape = outGridShape
if Radius_Earth != '':
radius = Radius_Earth
else:
radius = 6370000.0
if ((grid2CMAQ == 'yes') or (grid2CMAQ == 'y') or (grid2CMAQ == 'Y') or \
(grid2CMAQ == 'YES')) and (gridfile_name == ''):
print('')
print('*** ERROR ***: Error on processing grid to CMAQ')
print('*** ERROR ***: Please set the gridfile_name and grid2CMAQ the correctly')
print('')
sys.exit()
shp_file = '{0}{1}'.format(input_dir,file_name)
if os.path.exists(shp_file) == True:
print ('')
print ('Reading Link Shapefile ...')
print (shp_file)
prj_file = shp_file.replace('.shp', '.prj')
prj = [l.strip() for l in open(prj_file,'r')][0]
lnk_shp = gpd.read_file(shp_file)
out_roads = lnk_shp.loc[:,['geometry',Link_ID_attr, Region_CD, Region_NM,
RD_name_attr, RD_type_attr, Speed_attr, Link_length, VKT_attr]]
number_links = np.arange(0,len(out_roads))
# changing the name of columns to keep a standard
out_roads = out_roads.rename(columns={Link_ID_attr : 'link_id'})
out_roads = out_roads.rename(columns={Region_CD : 'region_cd'})
out_roads = out_roads.rename(columns={Region_NM : 'region_nm'})
out_roads = out_roads.rename(columns={RD_name_attr : 'road_name'})
out_roads = out_roads.rename(columns={RD_type_attr : 'road_type'})
out_roads = out_roads.rename(columns={Speed_attr : 'max_speed'})
out_roads = out_roads.rename(columns={Link_length : 'link_length'})
out_roads = out_roads.rename(columns={VKT_attr : 'vkt_avg'})
out_roads['number_links'] = number_links
out_roads['activity_data'] = (out_roads['link_length'] * 0.0).astype(float)
out_roads['region_cd'] = out_roads['region_cd'].astype(int)
out_roads['road_type'] = out_roads['road_type'].astype(int)
out_roads['link_id'] = out_roads['link_id'].astype(np.int64)
out_roads['max_speed'] = out_roads['max_speed'].astype(float)
out_roads['link_length'] = out_roads['link_length'].astype(float)
out_roads['number_links'] = out_roads['number_links'].astype(int)
out_roads['geometry_BKP'] = out_roads.geometry
out_roads['geometry'] = out_roads.buffer(0.2) #changing link to area to do the overlay
out_roads['total_area'] = out_roads.area
out_roads['link_split_total'] = (out_roads['link_length'] * 0.0).astype(float)
out_roads['link_split_county'] = (out_roads['link_length'] * 0.0).astype(float)
out_roads['vkt_split_county'] = (out_roads['link_length'] * 0.0).astype(float)
reduc = 0.6 #60% reduction as BH asked
rt = {101 : 80 *reduc, 102 : 60 *reduc, 103 : 60 *reduc, 104 : 50 *reduc, #60% reduction as BH asked
105 : 30 *reduc, 106 : 30 *reduc, 107 : 30 *reduc, 108 : 30 *reduc}
for key, ispd in rt.items():
out_roads.loc[(out_roads.loc[:,'road_type'] == key),'max_speed'] = ispd
# Creating grid
if ((grid2CMAQ == 'yes') or (grid2CMAQ == 'y') or (grid2CMAQ == 'Y') or \
(grid2CMAQ == 'YES')) and (gridfile_name != ''):
if os.path.exists(gridfile_name) == True:
print ('')
print ('Reading GridDesc file to generate gridded emissions ...')
print ('')
print (gridfile_name)
griddesc = pd.read_csv(gridfile_name, header=None,engine='python')
COORDTYPE, P_ALP, P_BET, P_GAM, XCENT, YCENT = griddesc.loc[2,0].split()
P_ALP, P_BET, P_GAM, XCENT, YCENT = map(float, [P_ALP, P_BET, P_GAM, XCENT, YCENT])
GRID_NAME = griddesc.loc[4,0].split()[0].replace("'",'')
COORD_NAME, XORIG, YORIG, XCELL, YCELL, NCOLS, NROWS, NTHIK = griddesc.loc[5,0].split()
XORIG, YORIG, XCELL, YCELL, NCOLS, NROWS, NTHIK = \
map(float, [XORIG, YORIG, XCELL, YCELL, NCOLS, NROWS, NTHIK])
if (COORDTYPE == '1'): #lat-lon
proj_grid = pyproj.Proj(init='epsg:4326')
elif (COORDTYPE == '2'): #lambert
proj_grid = pyproj.Proj('+proj=lcc +ellps=sphere +lat_1={0} +lat_2={1} +lat_0={3} +lon_0={2} +a={4} +R={4} +no_defs'.format(P_ALP, P_BET, XCENT, YCENT,radius)) #lcc
elif (COORDTYPE == '5') and (P_ALP <0):
proj_grid = pyproj.Proj('+proj=utm +zone={0} +south +datum=WGS84 +to_meter=1 +no_defs'.format(P_ALP, radius))
elif (COORDTYPE == '5') and (P_ALP >= 0):
proj_grid = pyproj.Proj('+proj=utm +zone={0} +datum=WGS84 +to_meter=1 +no_defs'.format(P_ALP,radius))
elif (COORDTYPE == '6'): #polar
proj_grid = pyproj.Proj('+proj=stere +lat_0={0} +lat_ts={1} +lon_0={2} +lat_0={3} +R={4} +ellps=WGS84 +datum=WGS84 +to_meter=1 +no_defs'.format(P_ALP, P_BET, P_GAM, XCENT, YCENT, radius))
cols = int(NCOLS)
rows = int(NROWS)
print("")
print('***** The domain has {0} columns and {1} rows '.format(cols,rows))
print("")
proj_grid(XORIG, YORIG, inverse=True)
proj_grid(XCENT, YCENT, inverse=True)
xmin, ymin = [(float(XORIG)), (float(YORIG))]
xmax, ymax = [xmin + ((cols+1) * XCELL), ymin + ((rows+1) * YCELL)]
proj_grid(xmax,ymax, inverse=True)
lat_list = (np.arange(ymin,ymax,YCELL))
lon_list = (np.arange(xmin,xmax,XCELL))
polygons = []
grid_row = []
grid_col = []
print('')
print('Creating grid celss ...')
print('')
for j in range(0,rows):
yini = lat_list[j]
yfin = lat_list[j+1]
for i in range(0,cols):
grid_row.append(j+1)
grid_col.append(i+1)
xini = lon_list[i]
xfin = lon_list[i+1]
polygons.append(Polygon([(xini, yini), (xfin, yini),
(xfin, yfin), (xini, yfin), (xini, yini)]))
grid_ID = [x for x in range (1,len(polygons)+1)]
grid = gpd.GeoDataFrame({'geometry': polygons, 'grid_id': grid_ID,
'row' : grid_row, 'col' : grid_col})
grid.crs = proj_grid.srs
# exporting grid as shapefile
if (outGridShape == 'yes') or (outGridShape == 'YES') or \
(outGridShape == 'y') or (outGridShape == 'Y'):
grid.to_file(filename = output_dir+'/grid_{0}.shp'.format(case_name),
driver='ESRI Shapefile', crs_wkt=grid.crs)
out_roads = out_roads.to_crs(proj_grid.srs)
else:
print ('')
print ('There is no GridCro File in {0}'.format(gridfile_name))
sys.exit()
else:
roads_bounds = out_roads.bounds
xmin = roads_bounds.minx.min() - grid_size
xmax = roads_bounds.maxx.max() + grid_size
ymin = roads_bounds.miny.min() - grid_size
ymax = roads_bounds.maxy.max() + grid_size
cols = int(abs(xmax - xmin) / grid_size)
rows = int(abs(ymax - ymin) / grid_size)
print(cols,rows)
lat_list = (np.arange(ymin,ymax,grid_size))
lon_list = (np.arange(xmin,xmax,grid_size))
polygons = []
grid_row = []
grid_col = []
print('')
print('Creating grid celss ...')
print('')
for j in range(0,rows):
yini = lat_list[j]
yfin = lat_list[j+1]
for i in range(0,cols):
grid_row.append(j+1)
grid_col.append(i+1)
xini = lon_list[i]
xfin = lon_list[i+1]
polygons.append(Polygon([(xini, yini), (xfin, yini), (xfin, yfin), (xini, yfin), (xini, yini)]))
crs = out_roads.crs #{'init': 'epsg:4326'}
grid_ID = [x for x in range (1,len(polygons)+1)]
grid = gpd.GeoDataFrame({'geometry':polygons, 'grid_id':grid_ID,
'row':grid_row, 'col':grid_col}, crs=crs)
grid.crs = crs
# exporting grid as shapefile
if (outGridShape == 'yes') or (outGridShape == 'YES') or \
(outGridShape == 'y') or (outGridShape == 'Y'):
grid.to_file(filename = output_dir+'/grid_{0}.shp'.format(case_name), driver='ESRI Shapefile',crs_wkt=prj)
print('')
print('Calculating the surrograte based on the link shapefile ...')
print('')
#creating the surrogate
surrogate = gpd.overlay(out_roads, grid, how='intersection').reset_index(drop=True)
surrogate['split_area'] = surrogate.area
surrogate['vkt_norm'] = ((surrogate.loc[:,'vkt_avg'] * \
surrogate.loc[:,'split_area']) / \
surrogate.loc[:,'total_area']).astype(float)
surrogate['weight_factor'] = surrogate['vkt_norm'] * 0.0
for igeocd in out_roads.region_cd.unique():
srgt_split_vkt = surrogate.vkt_norm.loc[surrogate.region_cd == igeocd].values / \
(surrogate.vkt_norm.loc[surrogate.region_cd == igeocd]).sum()
surrogate.loc[surrogate.region_cd == igeocd, ['weight_factor']] = srgt_split_vkt
vkt_split_county = out_roads.vkt_avg.loc[out_roads.region_cd == igeocd].values / \
(out_roads.vkt_avg.loc[out_roads.region_cd == igeocd]).sum()
out_roads.loc[out_roads.region_cd == igeocd, ['vkt_split_county']] = vkt_split_county
lnk_split_county = out_roads.link_length.loc[out_roads.region_cd == igeocd].values / \
(out_roads.link_length.loc[out_roads.region_cd == igeocd]).sum()
out_roads.loc[out_roads.region_cd == igeocd, ['link_split_county']] = lnk_split_county
surrogate = surrogate.groupby(['region_cd','grid_id']).sum()
surrogate = surrogate.reset_index(drop=False)
surrogate = surrogate.loc[:,['region_cd', 'grid_id', 'link_length',
'vkt_avg', 'total_area', 'split_area',
'link_split_total','link_split_county',
'vkt_split_county', 'weight_factor']]
surrogate = pd.merge(grid, surrogate, how='left', on=['grid_id'])
surrogate.loc[:,~surrogate.columns.str.contains('geometry')] = \
surrogate.loc[:,~surrogate.columns.str.contains('geometry')].fillna(0)
out_roads = out_roads.drop(columns=['geometry'])
out_roads = out_roads.rename(columns={'geometry_BKP': 'geometry'}).set_geometry('geometry')
out_roads['region_cd'] = out_roads['region_cd'].astype(int)
surrogate['region_cd'] = surrogate['region_cd'].astype(int)
else:
print('*** ERROR ABORT ***: Shapefile "" ', shp_file, ' "" does not exist!')
sys.exit('CARS preProcessor can not read link Shapefile file')
run_time = ((time.time() - start_time))
print('--- Elapsed time in seconds = {0} ---'.format(run_time))
print('--- Elapsed time in minutes = {0} ---'.format(run_time/60))
print('--- Elapsed time in hours = {0} ---'.format(run_time/3600))
return Roads_Grid_table(grid, surrogate, out_roads)
# =============================================================================
roads_RGS = roads_grid_surrogate_inf(input_dir, link_shape, link_shape_att,
gridfile_name, Radius_Earth, Unit_meters = True )
# =============================================================================
# Function to read link level shapefile
# =============================================================================
def processing_County_shape(input_dir, file_name, County_Shape_att, GridDesc_file='', Radius_Earth=''):
start_time = time.time()
Region_Geocode = County_Shape_att[0] #Region_CD
Region_name_attr = County_Shape_att[1] #Region_name_attr
Region_name_attr_SK = County_Shape_att[2] #Region_name_attr_SK
# Link_ID_attr = 'LINK_ID'