-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgridtools.py
1447 lines (1314 loc) · 61.4 KB
/
gridtools.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
import arcpy
#from arcpy.sa import * #If anything is ever not defined see if it is part of arcpy.as
import glob
import os
import sys
import csv
import traceback
import numpy
##from scipy import stats
try:
import mysql.connector
from mysql.connector import errorcode
except ImportError:
print('No MySQL support. Use SQLite database or install MySQL')
import sqlite3
import datetime
import json
import shutil
import subprocess
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
##Checkout needed Extentions
class SpatialLicenseError(Exception):
pass
class GeostatsLicenseError(Exception):
pass
try:
if arcpy.CheckExtension('Spatial') == "Available":
arcpy.CheckOutExtension('Spatial')
else:
raise SpatialLicenseError
except SpatialLicenseError:
arcpy.AddError("Spatial License is unavailable")
sys.exit(1) ## Terminate script
try:
if arcpy.CheckExtension('Geostats') == "Available":
arcpy.CheckOutExtension('Geostats')
else:
raise GeostatsLicenseError
except GeostatsLicenseError:
arcpy.AddError("Geostats License is unavailable")
sys.exit(1) ## Terminate script
data = {'sql_ph': '%s'}
##Set up workspaces
scratchWS = arcpy.env.scratchFolder
arcpy.env.workspace = scratchWS
arcpy.env.scratchWorkspace = scratchWS
arcpy.AddMessage('Scratch Workspace: ' + scratchWS)
scratchGDB = arcpy.env.scratchGDB
arcpy.env.overwriteOutput = True
##Add workspace to data dict
data['scratch_ws'] = scratchWS
data['scratch_gdb'] = scratchGDB
date_now = datetime.datetime.now()
s_now = date_now.strftime('%Y%d%b_%H%M%S')
os.makedirs(scratchWS + '/Output_' + s_now)
outFolder = '{0}/Output_{1}'.format(scratchWS, s_now)
data['out_folder'] = outFolder
##arcpy.AddMessage('Output Folder: ' + outFolder)
##Define Functions
def roundTime(dt, roundTo=60):
seconds = (dt - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
def selectWatershed(watershed):
''' Initialize all Relevant Data from the Geodatabase based on chosen watershed '''
stations = '' # Feature class of station meta data/locations
elev_tiff = '' # Needed for wind speed. Cannot have NoData cells
dem = '' # Needed for almost all/elev_tiff can also be used for this
view_factor = '' # Needed for Thermal radiation
search_radius = ''
db = ''
if watershed == 'Johnston Draw':
arcpy.AddMessage('Johnston Draw Watershed')
base_path = r'C:\ReynoldsCreek\Input_Data'
stations = r'{0}\Input_Data.gdb\station_locations_jd'.format(base_path)
stations_soil = r'{0}\Input_Data.gdb\station_locations_jd'.format(base_path)
elev_tiff = r'{0}\jd_elevation_filled.tif'.format(base_path)
dem = elev_tiff
view_factor = r'{0}\jd_view_factor.tif'.format(base_path)
search_radius = '1000'
db = '{0}/jd_data.db'.format(base_path)
data['sql_ph'] = '?'
elif watershed == 'Reynolds Creek':
arcpy.AddMessage('Reynolds Creek Watershed')
base_path = r'C:\ReynoldsCreek\Input_Data'
stations = r'{0}\Input_Data.gdb\station_locations_rc'.format(base_path)
stations_soil = r'{0}\Input_Data.gdb\station_locations_rc_soil'.format(base_path)
elev_tiff = r'{0}\rc_elev_filled.tif'.format(base_path)
dem = elev_tiff
view_factor = r'{0}\rc_view_factor.tif'.format(base_path)
search_radius = '10000'
db = r'{0}\rc_data.db'.format(base_path)
data['sql_ph'] = '?'
elif watershed == 'Valles Caldera':
arcpy.AddMessage('Valles Caldera Watershed')
base_path = r'C:\ReynoldsCreek\Input_Data'
stations = r'{0}\Input_Data.gdb\station_locations_vc'.format(base_path)
stations_soil = r'{0}\Input_Data.gdb\station_locations_vc'.format(base_path)
elev_tiff = r'{0}\vc_elev_filled.tif'.format(base_path)
dem = elev_tiff
view_factor = ''
search_radius = '21500'
db = r'{0}\vc_data.db'.format(base_path)
data['sql_ph'] = '?'
##elif watershed == 'TESTING':
## arcpy.AddMessage('Testing watershed')
## file_path = os.path.dirname(os.path.abspath(__file__))
## base_path = r'{0}\demo_data'.format(file_path)
## stations = '{0}\demo_sites.shp'.format(base_path)
## elev_tiff = '{0}\demo_data.tif'.format(base_path)
## dem = '{0}\demo_data.tif'.format(base_path)
## view_factor = '{0}\demo_data_vf.tif'.format(base_path)
## db = '{0}\demo.db'.format(base_path)
## search_radius = '1000'
## data['sql_ph'] = '?'
return stations, stations_soil, elev_tiff, dem, view_factor, search_radius, db
def ConnectDB(db, username = 'root', passwd = ''):
'''connect to MySQL database'''
if len(db.split('.')) == 1:
try:
cnx = mysql.connector.connect(user=username, password=passwd,
host='localhost',
database=db,
buffered=True)
return cnx
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
arcpy.AddMessage('Something is wrong with your user name or password')
elif err.errno == errorcode.ER_BAD_DB_ERROR:
arcpy.AddMessage('Database does not exist')
else:
arcpy.AddMessage(err)
else:
arcpy.AddMessage('Connection successful')
## Connect to sqlite3 database
elif db.split('.')[-1] == 'db':
cnx = sqlite3.connect(db)
return cnx
def ParameterList(param_dict, rows, table_type):
'''Append all data to the end of the parameter list'''
if table_type == 'climate':
for row in rows:
if data['watershed'] == 'Johnston Draw' or data['watershed'] == 'TESTING':
param_dict['site_key'].append(row[0])
param_dict['date_time'].append(row[1])
param_dict['air_temperature'].append(row[8])
param_dict['vapor_pressure'].append(row[10])
param_dict['dew_point'].append(row[11])
param_dict['solar_radiation'].append(row[12])
param_dict['wind_speed'].append(row[13])
param_dict['wind_direction'].append(row[14])
elif data['watershed'] == 'Reynolds Creek' or data['watershed'] == 'Valles Caldera':
param_dict['site_key'].append(row[0])
param_dict['date_time'].append(row[1])
param_dict['air_temperature'].append(row[9])
param_dict['vapor_pressure'].append(row[11])
param_dict['dew_point'].append(row[12])
param_dict['solar_radiation'].append(row[13])
param_dict['wind_speed'].append(row[14])
param_dict['wind_direction'].append(row[15])
elif table_type == 'precip':
for row in rows:
if data['watershed'] == 'Johnston Draw' or data['watershed'] == 'TESTING':
param_dict['site_key'].append(row[0])
param_dict['ppts'].append(row[2])
param_dict['pptu'].append(row[3])
param_dict['ppta'].append(row[4])
elif data['watershed'] == 'Reynolds Creek' or data['watershed'] == 'Valles Caldera':
param_dict['site_key'].append(row[0])
param_dict['ppts'].append(row[2])
param_dict['pptu'].append(row[3])
param_dict['ppta'].append(row[4])
elif table_type == 'soil_temperature':
for row in rows:
if data['watershed'] == 'Johnston Draw':
param_dict['site_key'].append(row[0])
param_dict['stm005'].append(row[3]) # column 3 is soil temp at 5 cm depth
if data['watershed'] == 'Reynolds Creek':
param_dict['site_key'].append(row[0])
param_dict['stm005'].append(row[4]) # column 3 is soil temp at 5 cm depth
elif table_type == 'snow_depth':
for row in rows:
if data['watershed'] == 'Johnston Draw' or data['watershed'] == 'Reynolds Creek' or data['watershed'] == 'TESTING':
param_dict['site_key'].append(row[0])
param_dict['zs'].append(row[-1])
##arcpy.AddMessage(param_dict)
return param_dict
def BuildClimateTable(params, num):
arcpy.management.CreateTable(data['scratch_gdb'], 'climate_table')
table = data['scratch_gdb'] + '/climate_table'
keys = [] # Holds data types collected (wind speed, air temperature, etc) to add to table
for key in params:
if key == 'site_key':
ftype = 'TEXT'
elif key == 'date_time':
ftype = 'DATE'
else:
ftype = 'FLOAT'
arcpy.management.AddField(in_table = table,
field_name = key,
field_type = ftype)
keys.append(key)
in_cursor = arcpy.InsertCursor(table)
#print keys
#print params
#Add data from rows into climate table
for j in range(0, num):
row = in_cursor.newRow()
for k in range(0, len(keys)):
# keys[x] = site_key, air_temperature, etc.
# params[keys[k][j] = value (ie -2.5)
row.setValue(keys[k], params[ keys[k] ][j])
in_cursor.insertRow(row)
del in_cursor
## del row
return table
def DataTable(parameter, data_table, multi_fields = []):
''' Create paramater scratch table to be used for interpolation '''
scratch_data = []
temp_table1 = parameter + '_table'
temp_table2 = 'in_memory/' + parameter + '_table2'
##===============================================================
##
## These checks really need some work.
##
##===============================================================
if len(multi_fields) == 2: #Simplify these checks somehow
#Thermal radation stats_fields
# format - [['air_temperature', 'MEAN'], ['vapor_pressure', 'MEAN']]
stats_fields = []
clause = '{0} > -500 AND {1} > -500'.format(multi_fields[0], multi_fields[1])
for l in multi_fields:
stats_fields.append([l, 'MEAN'])
elif len(multi_fields) == 3:
# Wind speed
stats_fields = []
clause = '{0} > -500 AND {1} > -500 AND {2} > -500'.format(multi_fields[0], multi_fields[1], multi_fields[2])
for l in multi_fields:
stats_fields.append([l, 'MEAN'])
else: # regular parameters
stats_fields = parameter + ' MEAN'
clause = parameter + ' > -500'
# Make new temporary table
out = arcpy.management.MakeTableView(in_table = data_table,
out_view = temp_table1,
where_clause = clause)
scratch_data.append(temp_table1)
out_mem = arcpy.analysis.Statistics(in_table = temp_table1,
out_table = temp_table2,
statistics_fields = stats_fields,
case_field = 'site_key')
# Copy stats to tempStations feature class
if parameter == 'stm005':
###====================================
###
### Soil temperature feature class already has elevation data for all feature classes
###
###====================================
arcpy.env.extent = data['station_locations_soil']
temp_stations = arcpy.management.CopyFeatures(in_features = data['station_locations_soil'],
out_feature_class = data['scratch_gdb'] + '/tempStations')
else:
temp_stations = arcpy.management.CopyFeatures(in_features = data['fc_stations_elev'],
out_feature_class = data['scratch_gdb'] + '/tempStations')
# Join stats to temp stations feature class
if len(multi_fields) > 0: #Thermal radiation and wind speed
tr_fields = []
for l in multi_fields:
tr_fields.append('MEAN_' + l)
arcpy.management.JoinField(in_data = temp_stations,
in_field = 'Site_key',
join_table = temp_table2,
join_field = 'site_key',
fields = tr_fields)
else: # Regular paramters
arcpy.management.JoinField(in_data = temp_stations,
in_field = 'Site_Key',
join_table = temp_table2,
join_field = 'site_key',
fields = 'MEAN_' + parameter)
# Delete rows from feature class that have negative or null elevations
cursor = arcpy.UpdateCursor(temp_stations)
if parameter == 'stm005':
arcpy.AddMessage('Soil temperature')
arcpy.env.extent = data['station_locations_soil']
else:
for row in cursor:
if (row.getValue('RASTERVALU') < 0 or
row.getValue('RASTERVALU') == 'None' or
row.getValue('RASTERVALU') is None ):
cursor.deleteRow(row)
else:
row.setValue('RASTERVALU', round(row.getValue('RASTERVALU'), 2))
cursor.updateRow(row)
del cursor
del row
# Delete rows from feature class that have null values for paramter
cursor = arcpy.UpdateCursor(temp_stations)
if len(multi_fields) == 2: #thermal Radiation check
for row in cursor:
val0 = 'MEAN_' + multi_fields[0]
val1 = 'MEAN_' + multi_fields[1]
if row.isNull(val0) or row.isNull(val1):
cursor.deleteRow(row)
if len(multi_fields) == 3: # Wind speed
for row in cursor:
val0 = 'MEAN_' + multi_fields[0]
val1 = 'MEAN_' + multi_fields[1]
val2 = 'MEAN_' + multi_fields[2]
if row.isNull(val0) or row.isNull(val1) or row.isNull(val2):
cursor.deleteRow(row)
else:
for row in cursor:
if row.isNull('MEAN_' + parameter):
cursor.deleteRow(row)
else:
row.setValue('MEAN_' + parameter, round(row.getValue('MEAN_' + parameter), 2))
cursor.updateRow(row)
del cursor
del row
DeleteScratchData(scratch_data)
return temp_stations
def DetrendedMethod(parameter, data_table, date_stamp, out_ras):
arcpy.AddMessage('Detrended Kriging')
resid_raster = data['scratch_gdb'] + '/' + parameter
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_ras, date_stamp, data['file_format'])
# Add unique ID field to temporary data table for use in OLS function
arcpy.management.AddField(in_table = data_table,
field_name = 'Unique_ID',
field_type = 'SHORT',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
arcpy.management.CalculateField(in_table = data_table,
field = 'Unique_ID',
expression = '!OBJECTID!',
expression_type = 'PYTHON_9.3')
#Run ordinary least squares of temporary data table
coef_table = arcpy.management.CreateTable(data['scratch_gdb'], 'coef_table_' + parameter)
ols = arcpy.stats.OrdinaryLeastSquares(Input_Feature_Class = data_table,
Unique_ID_Field = 'Unique_ID',
Output_Feature_Class = 'in_memory/fcResid',
Dependent_Variable = 'MEAN_' + parameter,
Explanatory_Variables = 'RASTERVALU',
Coefficient_Output_Table = coef_table)
intercept = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[0]
slope = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[1]
#Calculate residuals and add them to temporary data table
arcpy.management.AddField(in_table = data_table,
field_name = 'residual',
field_type = 'DOUBLE',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
cursor = arcpy.UpdateCursor(data_table)
for row in cursor:
row_math = row.getValue('MEAN_' + parameter) - ((slope * row.getValue('RASTERVALU')) + intercept)
row.setValue('residual', row_math)
cursor.updateRow(row)
del cursor
del row
#Run ordinary kriging on residuals
#Dewpoint/Vapor pressure kriging model
k_model = KrigingModelOrdinary('SPHERICAL', 460, 3686, .1214, .2192)
#Air temp kriging model
#k_model = KrigingModelOrdinary('LINEAR', 37.061494)
radius = RadiusFixed(10000, 1)
outKrig = arcpy.sa.Kriging(in_point_features = data_table,
z_field = 'residual',
kriging_model = k_model,
cell_size = data['output_cell_size'],
search_radius = radius)
outKrig.save(resid_raster)
return_raster = arcpy.Raster(resid_raster) + (arcpy.Raster(data['dem']) * slope + intercept)
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(return_raster, out_raster_name)
else:
return_raster.save(out_raster_name)
#Delete scratch/residual data.
del outKrig
del k_model
del radius
arcpy.management.Delete(resid_raster)
return out_raster_name
def IDWMethod(parameter, data_table, date_stamp, out_ras):
arcpy.AddMessage('Inverse Distance Weighted')
scratch_raster = '{0}/{1}'.format(data['scratch_gdb'], parameter)
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_ras, date_stamp, data['file_format'])
idw_out = arcpy.sa.Idw(in_point_features = data_table,
z_field = 'MEAN_' + parameter,
cell_size = data['elev_tiff'],
power = 2)
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(idw_out, out_raster_name)
else:
idw_out.save(out_raster_name)
arcpy.AddMessage('Out Raster {0}'.format(out_raster_name))
return out_raster_name
def EBKMethod(parameter, data_table, date_stamp, out_ras):
arcpy.AddMessage('Empirical Bayesian Kriging')
scratch_raster = '{0}/{1}'.format(data['scratch_gdb'], parameter)
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_ras, date_stamp, data['file_format'])
#arcpy.AddMessage(data_table)
arcpy.ga.EmpiricalBayesianKriging(in_features = data_table,
z_field = 'MEAN_' + parameter,
out_raster = scratch_raster,
cell_size = data['output_cell_size'],
transformation_type = 'EMPIRICAL',
max_local_points = '100',
overlap_factor = '1',
number_semivariograms = '100',
search_neighborhood = 'NBRTYPE=SmoothCircular RADIUS={0} SMOOTH_FACTOR=0.2'.format(data['search_radius']),
output_type = 'PREDICTION',
quantile_value = '0.5',
threshold_type = 'EXCEED',
semivariogram_model_type='WHITTLE_DETRENDED')
#Mask output to size of original DEM
## For some reason this is no longer a problem.
## Extract By Mask does not run well on newer versions of arcmap so it is not used.
#outExtract = ExtractByMask(scratch_raster, data['dem'])
outExtract = arcpy.Raster(scratch_raster)
if(data['file_format'] =='ASC'):
arcpy.conversion.RasterToASCII(outExtract, out_raster_name)
else:
outExtract.save(out_raster_name)
arcpy.management.Delete(scratch_raster)
return out_raster_name
def CombinedMethod(parameter, data_table, date_stamp, out_ras):
arcpy.AddMessage('Combined Method')
scratch_raster = '{0}/{1}'.format(data['scratch_gdb'], parameter)
resid_raster = '{0}/{1}_{2}'.format(data['scratch_gdb'], parameter, 'residual')
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_ras, date_stamp, data['file_format'])
# Add unique ID field to temporary data table for use in OLS function
arcpy.management.AddField(in_table = data_table,
field_name = 'Unique_ID',
field_type = 'SHORT',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
arcpy.management.CalculateField(in_table = data_table,
field = 'Unique_ID',
expression = '!OBJECTID!',
expression_type = 'PYTHON_9.3')
#Run ordinary least squares of temporary data table
coef_table = arcpy.management.CreateTable(data['scratch_gdb'], 'coef_table_' + parameter)
ols = arcpy.stats.OrdinaryLeastSquares(Input_Feature_Class = data_table,
Unique_ID_Field = 'Unique_ID',
Output_Feature_Class = 'in_memory/fcResid',
Dependent_Variable = 'MEAN_' + parameter,
Explanatory_Variables = 'RASTERVALU',
Coefficient_Output_Table = coef_table)
intercept = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[0]
slope = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[1]
#Calculate residuals and add them to temporary data table
arcpy.management.AddField(in_table = data_table,
field_name = 'residual',
field_type = 'DOUBLE',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
cursor = arcpy.UpdateCursor(data_table)
for row in cursor:
row_math = row.getValue('MEAN_' + parameter) - ((slope * row.getValue('RASTERVALU')) + intercept)
row.setValue('residual', row_math)
cursor.updateRow(row)
del cursor
del row
arcpy.ga.EmpiricalBayesianKriging(in_features = data_table,
z_field = 'MEAN_' + parameter,
out_raster = resid_raster,
cell_size = data['output_cell_size'],
transformation_type = 'EMPIRICAL',
max_local_points = '100',
overlap_factor = '1',
number_semivariograms = '100',
search_neighborhood = 'NBRTYPE=SmoothCircular RADIUS=10000.9518700025 SMOOTH_FACTOR=0.2',
output_type = 'PREDICTION',
quantile_value = '0.5',
threshold_type = 'EXCEED',
semivariogram_model_type='WHITTLE_DETRENDED')
out_extract = arcpy.sa.ExtractByMask(resid_raster, data['dem'])
out_extract.save(scratch_raster)
#Add back elevation trends and save final raster
output_raster = arcpy.Raster(scratch_raster) + (arcpy.Raster(data['dem']) * slope + intercept)
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(output_raster, out_raster_name)
else:
output_raster.save(out_raster_name)
arcpy.management.Delete(scratch_raster)
arcpy.management.Delete(resid_raster)
return out_raster_name
def Interpolate(parameter, scratch_table, date_stamp, out_name):
'''Interpolate using the chosen method'''
raster = ''
if data['kriging_method'] == 'Detrended':
raster = DetrendedMethod(parameter, scratch_table, date_stamp, out_name)
#raster.save(data['out_folder'] + '/' + param + '.tif')
elif data['kriging_method'] == 'Combined':
raster = CombinedMethod(parameter, scratch_table, date_stamp, out_name)
elif data['kriging_method'] == 'IDW':
raster = IDWMethod(parameter, scratch_table, date_stamp, out_name)
else:
try:
raster = EBKMethod(parameter, scratch_table, date_stamp, out_name)
except arcpy.ExecuteError:
arcpy.AddMessage(arcpy.GetMessages(2))
return raster
def OLS(parameter, scratch_table, date_stamp, out_name):
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_name, date_stamp, data['file_format'])
#Run ordinary least squares on scratch_table
coef_table = arcpy.management.CreateTable(data['scratch_gdb'], 'coef_table')
if parameter == 'stm005':
exp_var = 'Elevation'
else:
exp_var = 'RASTERVALU'
arcpy.management.AddField(in_table = scratch_table,
field_name = 'Unique_ID',
field_type = 'SHORT',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
arcpy.management.CalculateField(in_table = scratch_table,
field = 'Unique_ID',
expression = '!OBJECTID!',
expression_type = 'PYTHON_9.3')
ols = arcpy.stats.OrdinaryLeastSquares(Input_Feature_Class = scratch_table,
Unique_ID_Field = 'Unique_ID',
Output_Feature_Class = 'in_memory/fcResid',
Dependent_Variable = 'MEAN_' + parameter,
Explanatory_Variables = exp_var,
Coefficient_Output_Table = coef_table)
intercept = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[0]
slope = list((row.getValue('Coef') for row in arcpy.SearchCursor(coef_table, fields='Coef')))[1]
arcpy.env.extent = data['ext_elev']
return_raster = arcpy.Raster(data['dem']) * slope + intercept
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(return_raster, out_raster_name)
else:
return_raster.save(out_raster_name)
return out_raster_name
def AirTemperature(clim_tab, date_stamp):
arcpy.AddMessage('Air Temperature')
param = 'air_temperature'
out_raster_title = 'T_a'
scratch_table = DataTable(param, clim_tab)
#arcpy.management.CopyRows(scratch_table, data['scratch_gdb'] + '/temp_ta')
#Kriging
raster = Interpolate(param, scratch_table, date_stamp, out_raster_title)
#Delete tempStations when done.
#arcpy.management.Delete(scratch_table)
return raster
def DewPoint(clim_tab, date_stamp):
arcpy.AddMessage('Dewpoint Temperature')
param = 'dew_point'
scratch_table = DataTable(param, clim_tab)
out_raster_title = 'T_pp'
#arcpy.management.CopyRows(scratch_table, data['scratch_gdb'] + '/temp_dp')
#Kriging
raster = Interpolate(param, scratch_table, date_stamp, out_raster_title)
#Delete tempStations when done
arcpy.management.Delete(scratch_table)
return raster
def PercentSnow(dew_point, date_stamp):
inRas = arcpy.Raster(dew_point)
outRas = '{0}/percent_snow_{1}.{2}'.format(data['out_folder'], date_stamp, data['file_format'])
out_snow_ras = arcpy.sa.Con(inRas < -5.0, 1.0,
arcpy.sa.Con((inRas >= -5.0) & (inRas < -3.0), 1.0,
arcpy.sa.Con((inRas >= -3.0) & (inRas < -1.5), 1.0,
arcpy.sa.Con((inRas >= -1.5) & (inRas < -0.5), 1.0,
arcpy.sa.Con((inRas >= -0.5) & (inRas < 0.0), 0.75,
arcpy.sa.Con((inRas >= 0.0) & (inRas < 0.5), 0.25,
arcpy.sa.Con(inRas >= 0.5,0.0)))))))
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(out_snow_ras, outRas)
else:
arcpy.management.CopyRaster(in_raster = out_snow_ras,
out_rasterdataset=outRas,
pixel_type = '32_BIT_FLOAT')
return outRas
def SnowDensity(dew_point, date_stamp):
inRas = arcpy.Raster(dew_point)
outRas = '{0}/rho_snow_{1}.{2}'.format(data['out_folder'], date_stamp, data['file_format'])
out_snow_density = arcpy.sa.Con(inRas < -5.0, 1.0,
arcpy.sa.Con((inRas >= -5.0) & (inRas < -3.0), 1.0,
arcpy.sa.Con((inRas >= -3.0) & (inRas < -1.5), 1.0,
arcpy.sa.Con((inRas >= -1.5) & (inRas < -0.5), 1.0,
arcpy.sa.Con((inRas >= -0.5) & (inRas < 0.0), 0.75,
arcpy.sa.Con((inRas >= 0.0) & (inRas < 0.5), 0.25,
arcpy.sa.Con(inRas >= 0.5,0.0)))))))
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(out_snow_density, outRas)
else:
arcpy.management.CopyRaster(in_raster = out_snow_density,
out_rasterdataset=outRas,
pixel_type = '32_BIT_FLOAT')
return outRas
def VaporPressure(clim_tab, date_stamp):
arcpy.AddMessage('Vapor Pressure')
param = 'vapor_pressure'
scratch_table = DataTable(param, clim_tab)
out_raster_title = 'e_a'
#arcpy.management.CopyRows(scratch_table, data['scratch_gdb'] + '/temp_ta')
#Kriging
raster = Interpolate(param, scratch_table, date_stamp, out_raster_title)
#Delete tempStations when done.
arcpy.management.Delete(scratch_table)
return raster
def SolarRadiation(clim_tab, date_stamp, date_time, time_step):
arcpy.AddMessage('Solar Radiation')
scratch_data = []
param = 'solar_radiation'
out_raster_title = 'S_n'
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_raster_title, date_stamp, data['file_format'])
#set up area solar radiation tool parameters and run the tool
#Set up time parameters
day_of_year = date_time.timetuple().tm_yday
i_sr_start = int(date_time.strftime('%H'))
i_sr_end = i_sr_start + data['time_step']
in_twd = TimeWithinDay(day_of_year, i_sr_start, i_sr_end)
sky_size = 200
try:
out_global_radiation = arcpy.sa.AreaSolarRadiation(data['dem'], '', sky_size, in_twd)
#out_global_radiation = out_global_radiation / data['time_step']
except arcpy.ExecuteError:
msgs = arcpy.GetMessages(2)
#arcpy.AddMessage(msgs)
if 'Failed to open raster dataset' in msgs or 'Error in creating sun map' in msgs:
arcpy.AddMessage("Skip night hours")
return
#Set up scratch data table
scratch_table = DataTable(param, clim_tab)
scratch_data.append(scratch_table)
glob_rad_raster = data['scratch_gdb'] + '/glob_rad_raster'
sim_points = data['scratch_gdb'] + '/simPoints'
scratch_data.append(glob_rad_raster)
scratch_data.append(sim_points)
#Correct global radiation raster for cloud conditions
#Extract simulated global radiation values to station location feature class
arcpy.management.AlterField(in_table = scratch_table,
field = 'RASTERVALU',
new_field_name = 'Elevation')
arcpy.sa.ExtractValuesToPoints(in_point_features = scratch_table,
in_raster = out_global_radiation,
out_point_features = sim_points,
interpolate_values = 'NONE',
add_attributes = 'VALUE_ONLY')
arcpy.management.AddField(in_table = sim_points,
field_name = 'ratio',
field_type = 'FLOAT',
field_is_nullable = 'NULLABLE',
field_is_required = 'NON_REQUIRED')
arcpy.management.CalculateField(in_table = sim_points,
field = 'ratio',
expression = '!MEAN_solar_radiation!/ !RASTERVALU!',
expression_type = 'PYTHON_9.3')
#convert 'ration' field to numpy array
na = arcpy.da.TableToNumPyArray(sim_points, 'ratio')
#calculate average ratio
d_mean_ratio = numpy.mean(na['ratio'])
d_mean_ratio2 = numpy.asscalar(d_mean_ratio)
#multiply simulated raster by average ratio
out_global_radiation_corrected = out_global_radiation * d_mean_ratio2
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(out_global_radiation, out_raster_name)
else:
out_global_radiation_corrected.save(out_raster_name)
arcpy.management.Delete(scratch_table)
return out_raster_name
def ThermalRadiation(clim_tab, date_stamp, in_air, in_vap, in_surface_temp):
arcpy.AddMessage('Thermal Radiation')
param = 'thermal_radiation'
out_raster_title = 'I_lw'
out_file = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_raster_title, date_stamp, data['file_format'])
z = data['dem']
vf = data['view_factor']
T_a = in_air
vp = in_vap
fields = ['air_temperature', 'vapor_pressure']
scratch_table = DataTable(param, clim_tab, multi_fields=fields)
P_m = 0.0 # Reference Air Pressure (Vapor pressure)
T_m = 0.0 # Reference Air Temp
z_m = 0.0 # Reference elevation
T_s = in_surface_temp
cursor = arcpy.UpdateCursor(scratch_table)
for row in cursor:
z_m = row.getValue('RASTERVALU')
P_m = row.getValue('MEAN_vapor_pressure')
T_m = row.getValue('MEAN_air_temperature')
cursor.deleteRow(row)
break
del cursor
del row
arcpy.AddMessage("P_m: " + str(P_m))
arcpy.AddMessage("T_m: " + str(T_m))
arcpy.AddMessage("z_m: " + str(z_m))
arcpy.AddMessage("T_s: " + str(T_s))
# Constants
g = 9.8 # Gravity
m = 0.0289 # Molecular Weight of dry air
R = 8.3143 # Gas constant
sigma = 5.6697 * 10 ** -8 # Stefan-Boltzmann constant
epsilon_s = 0.95 # Surface emissivity
gamma = -0.006 # temperature lapse rate (K m^-1)
# convert temperature parameters to Kelvin
T_m = T_m + 274.15
T_s = T_s + 274.15
T_a = arcpy.sa.Float(Raster(T_a) + 274.15)
# convert vapor pressure to mb
P_m = P_m * 0.01
vp = arcpy.sa.Float(Raster(vp) * 0.01)
#Correct air temperature and vapor pressure rasters (Marks and Dozier (1979), pg. 164)
#(4) corrected air temperature
T_prime = T_a + (0.0065 * arcpy.Raster(z))
#saturated vapor pressure from original air temperature (T_a)
e_sa = arcpy.sa.Float(6.11 * 10**((7.5*arcpy.sa.Float(T_a))/(237.3 + arcpy.sa.Float(T_a))))
#saturated vapor pressure from corrected air temperature (T_prime)
e_sprime = arcpy.sa.Float(6.11 * 10**((7.5*arcpy.sa.Float(T_a))/(237.3 + arcpy.sa.Float(T_a))))
rh = arcpy.sa.Float(vp / e_sa) #(5) relative humidity
e_prime = arcpy.sa.Float(rh * e_sprime) #(6) corrected vapor pressure
#Pressure at a given elevation (Marks and Dozier (1979), pg. 168-169)
term1 = ((-g*m)/(R*gamma))
delta_z = arcpy.Raster(z) - z_m
term2 = ((T_m + gamma * delta_z)) / T_m
lnTerm = arcpy.sa.Ln(term2)
expTerm = arcpy.sa.Exp(term1 * lnTerm)
P_a = P_m * expTerm #(10) air pressure
#effective emissivity (Marks and Dozier (1979), pg. 164)
epsilon_a = arcpy.sa.Float((1.24 * (e_prime / T_prime)**(1/7)) * (P_a / 1013.0)) #(7)
#Incoming longwave radiation (Marks and Dozier (1979), pg. 164)
term3 = arcpy.sa.Float((epsilon_a * sigma * (T_a ** 4)) * vf)
term4 = arcpy.sa.Float(epsilon_s * sigma * (T_s ** 4))
term5 = (1 - arcpy.Raster(vf))
output_thermal_radiation = arcpy.sa.Float(term3 + (term4 * term5)) #(9)
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(output_thermal_radiation, out_file)
else:
output_thermal_radiation.save(out_file)
return out_file
def PrecipitationMass(precip_tab, date_stamp):
arcpy.AddMessage('Precipitation mass')
param = 'ppta'
out_raster_title = 'm_pp'
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_raster_title, date_stamp, data['file_format'])
scratch_table = DataTable(param, precip_tab)
if data['watershed'] == 'Johnston Draw':
cursor = arcpy.SearchCursor(scratch_table)
x = []
y = []
for row in cursor:
x.append(row.getValue('RASTERVALU'))
y.append(row.getValue('MEAN_ppta'))
del cursor
del row
A = numpy.vstack([x,numpy.ones(len(x))]).T
slope, intercept = numpy.linalg.lstsq(A, y)[0]
arcpy.AddMessage('Slope {0}, Intercept {1}'.format(slope, intercept))
if slope != 0.0 and intercept != 0.0:
#Create final raster
arcpy.env.extent = data['ext_elev']
raster = (arcpy.Raster(data['dem']) * slope + intercept)
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(raster, out_raster_name)
else:
raster.save(out_raster_name)
return out_raster_name
else:
return
else:
raster = Interpolate(param, scratch_table, date_stamp, out_raster_title)
#Delete tempStations when done
arcpy.management.Delete(scratch_table)
return raster
def SoilTemperature(soil_tab, date_stamp):
arcpy.AddMessage('Soil Temperature')
param = 'stm005'
out_raster_title = 'T_g'
#Create Scratch Table --
# this is different from the rest in that it does not delete no elevation
scratch_table = DataTable(param, soil_tab)
raster = OLS(param, scratch_table, date_stamp, out_raster_title)
arcpy.management.Delete(scratch_table)
return raster
def SnowDepth(snow_tab, date_stamp):
arcpy.AddMessage('Snow depth')
param = 'zs'
out_raster_title = 'zs'
scratch_table = DataTable(param, snow_tab)
cursor = arcpy.SearchCursor(scratch_table)
values = []
for row in cursor:
values.append(row.getValue('MEAN_zs'))
del cursor
del row
average = numpy.mean(values)
count = int(arcpy.management.GetCount(scratch_table).getOutput(0))
if count >= 10 and average > 0:
raster = Interpolate(param, scratch_table, date_stamp, out_raster_title)
else:
if count < 10:
arcpy.AddMessage('Not enough data for snow depth. Try a different time step.')
if average == 0:
arcpy.AddMessage('No snow on the ground. Try a different time step if needed.')
arcpy.management.Delete(scratch_table)
return raster
def SnowCoverTemperature(date_stamp):
arcpy.AddMessage('Upper Layer')
ul_param = 'T_s_0'
avg_param = 'T_s'
ul_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], ul_param, date_stamp, data['file_format'])
avg_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], avg_param, date_stamp, data['file_format'])
if len(data['ul_interp_values']['features']) <= 1:
upper_layer_temperature = -0.0008 * arcpy.Raster(data['dem']) + 0.1053
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(upper_layer_temperature, ul_raster_name)
else:
upper_layer_temperature.save(ul_raster_name)
else:
ls_elevation = []
ls_temperature = []
for rec in data['ul_interp_values']['features']:
ls_elevation.append(rec['attributes']['Elevation'])
ls_density.append(rec['attributes']['Temperature'])
lr_results = stats.linregress(ls_elevation, ls_density)
slope_ul = lr_results[0]
intercept_ul = lr_results[1]
upper_layer_temperature = slope_ul * arcpy.Raster(data['dem']) + intercept_ul
if(data['file_format'] == 'ASC'):
arcpy.conversion.RasterToASCII(upper_layer_temperature, ul_raster_name)
else:
upper_layer_temperature.save(ul_raster_name)
if len(data['ll_interp_values']['features']) <=1:
lower_layer_temperature = -0.0008 * arcpy.Raster(data['dem']) + 1.3056
else:
ls_elevation = []
ls_temperature = []
for rec in data['ll_interp_values']['features']:
ls_elevation.append(rec['attributes']['Elevation'])
ls_temperature.append(rec['attributes']['Temperature'])
lr_results = stats.linregress(ls_elevation, ls_temperature)
slope_ll = lr_results[0]
intercept_ll = lr_results[1]
lower_layer_temperature = slope_ll * arcpy.Raster(data['dem']) + intercept_ll
#average snowcover temperature is the average of the upper and lower layer temperatures
avg_sc_temp = arcpy.sa.CellStatistics([upper_layer_temperature, lower_layer_temperature], 'MEAN', 'NODATA')
if data['file_format'] == 'ASC':
arcpy.conversion.RasterToASCII(avg_sc_temp, avg_raster_name)
else:
avg_sc_temp.save(avg_raster_name)
return ul_raster_name, avg_raster_name
def SnowDensityInterpolation(date_stamp):
arcpy.AddMessage('Snow Density Interpolation')
param = 'rho'
out_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'], param, date_stamp, data['file_format'])
if len(data['density_interp_values']['features']) <= 1:
snow_density_raster = -0.0395 * arcpy.Raster(data['dem']) + 405.26
if data['file_format'] == 'ASC':
arcpy.conversion.RasterToASCII(snow_density_raster, out_raster_name)
else:
snow_density_raster.save(out_raster_name)
else: # This will not work until we get scypy loaded
ls_elevation = []
ls_density = []
for rec in data['density_interp_values']['features']:
ls_elevation.append(rec['attributes']['Elevation'])
ls_density.append(rec['attributes']['Density'])
lr_results = stats.linregress(ls_elevation, ls_density)
slope = lr_results[0]
intercept = lr_results[1]
snow_density_raster = slope * arcpy.Raster(data['dem']) + intercept
snow_density_raster.save(out_raster_name)
return out_raster_name
def Constants(rl, h2o, date_stamp):
arcpy.AddMessage('Constants')
rl_param = 'z_0'
h2o_param = 'h2o_sat'
rl_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'],rl_param,date_stamp, data['file_format'])
h2o_raster_name = '{0}/{1}_{2}.{3}'.format(data['out_folder'],h2o_param,date_stamp, data['file_format'])
desc = arcpy.Describe(data['dem'])
coord_system = desc.spatialReference
rl_constant = CreateConstantRaster(rl, 'FLOAT', data['output_cell_size'])
arcpy.management.DefineProjection(rl_constant, coord_system)
if data['file_format'] == 'ASC':
arcpy.conversion.RasterToASCII(rl_constant, rl_raster_name)
else:
rl_constant.save(rl_raster_name)
h2o_constant = CreateConstantRaster(h2o, 'FLOAT', data['output_cell_size'])
arcpy.management.DefineProjection(h2o_constant, coord_system)
if data['file_format'] == 'ASC':
arcpy.conversion.RasterToASCII(h2o_constant, h2o_raster_name)
else:
h2o_constant.save(h2o_raster_name)
return rl_raster_name, h2o_raster_name
def WindSpeed(clim_tab, date_stamp, in_date_time):
arcpy.AddMessage('Wind Speed')
scratch_data = []
param = 'wind_speed'
out_raster_title = 'u'
out_file = '{0}/{1}_{2}.{3}'.format(data['out_folder'], out_raster_title, date_stamp, data['file_format'])
fields = ['wind_speed', 'wind_direction', 'air_temperature']
scratch_table = DataTable(param, clim_tab, multi_fields=fields)
ninja_path = 'Upload text'
#ninja_path = 'C:/WindNinja/WindNinja-3.1.1/bin/WindNinja_cli.exe' # comment to upload
wind_date = in_date_time.split(" ")[0]
wind_time = in_date_time.split(" ")[1]
ls_wind_date = wind_date.split("-")
ls_wind_time = wind_time.split(":")
wind_year = ls_wind_date[0]
wind_month = ls_wind_date[1]
wind_day = ls_wind_date[2]
wind_hour = ls_wind_time[0]
wind_minute = ls_wind_time[1]
#Build station csv file from SQL data
# Add coordinates to station feature class