forked from NCAR/wrf_hydro_arcgis_preprocessor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GEOGRID_STANDALONE.pyt
1668 lines (1403 loc) · 75.3 KB
/
GEOGRID_STANDALONE.pyt
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
# *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
# ** Copyright UCAR (c) 2016
# ** University Corporation for Atmospheric Research(UCAR)
# ** National Center for Atmospheric Research(NCAR)
# ** Research Applications Laboratory(RAL)
# ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA
# ** 2016/4/27 10:00:00
# *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
# --- Import Modules --- #
import sys
sys.dont_write_bytecode = True # Do not write .pyc files
import os
import shutil
import time
import numpy
import arcpy
import netCDF4 # Packaged with ArcGIS 10.3 and higher
import re # Added 10/11/2016 for string matching in netCDF global attributes
# Specify import path and append to PATH
configfile = '~/wrf_hydro_functions.py'
sys.path.insert(1,os.path.dirname(os.path.expanduser(configfile)))
import wrf_hydro_functions # Function script packaged with this toolbox
reload(wrf_hydro_functions) # Re-load the function script in case of script changes
# --- End Import Modules --- #
# --- Module Configurations --- #
arcpy.env.overwriteOutput = True # Allow overwriting of outputs
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
from arcpy.sa import *
# --- End Module Configurations --- #
# Find out if we are in 32-bit or 64-bit
if sys.maxsize > 2**32:
bit64 = True
else:
bit64 = False
# --- Globals --- #
inunits = 'm' # Set units for input Elevation raster dataset: 'm' or 'cm'
outNCType = 'NETCDF3_64BIT' # Set output netCDF format for spatial metdata files
#outNCType = 'NETCDF4_CLASSIC' # Define the output netCDF version for RouteLink.nc and LAKEPARM.nc
LK_nc = wrf_hydro_functions.LK_nc # Grab default lake parameter table name from function script
RT_nc = wrf_hydro_functions.RT_nc # Grab default Route Link parameter table name from function script
# Processing Notes to insert into netCDF global attributes
# Processing notes for Spatial Metdata files
processing_notes_SM = '''Created: %s''' %time.ctime()
# Processing notes for the FULLDOM (Routing Grid) file
processing_notesFD = '''Created: %s''' %time.ctime()
# Default groundwater bucket (GWBUCKPARM) parameters
Community = True # Switch to provide Community WRF-Hydro GWBUCKPARM outputs
coeff = 1.0000
expon = 3.000
zmax = 50.00
zinit = 10.0000
nodataVal = -9999
# --- End Globals --- #
# --- Toolbox Classes --- #
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "WRFHydro_GIS_Pre-Processor"
self.alias = ""
self.description = "This is a standalone ArcGIS geoprocessing toolbox for WRF-Hydro."
# List of tool classes associated with this toolbox
self.tools = [ProcessGeogridFile,
ExportGrid,
ExamineOutputs,
ExportPRJ,
GenerateLatLon,
SpatialMetadataFile,
DomainShapefile,
Reach_Based_Routing_Addition,
Lake_Parameter_Addition,
GWBUCKPARM]
class ProcessGeogridFile(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Process GEOGRID File"
self.description = "This tool takes an input WRF GEOGRID file in NetCDF format" + \
" and uses the HGT_M grid and an input high-resolution elevation grid" + \
"to produce a high-resolution hydrologically processed output."
self.canRunInBackground = True #self.canRunInBackground = False
self.category = "Processing"
def getParameterInfo(self):
"""Define parameter definitions"""
in_nc = arcpy.Parameter(
displayName="Input GEOGRID File",
name="in_nc",
datatype="File",
parameterType="Required",
direction="Input")
in_csv = arcpy.Parameter(
displayName="Forecast Points (CSV)",
name="in_csv",
datatype="File",
parameterType="Optional",
direction="Input")
# To define a file filter that includes .csv and .txt extensions, set the filter list to a list of file extension names
in_csv.filter.list = ['csv']
basin_mask = arcpy.Parameter(
displayName="Mask CHANNELGRID variable to forecast basins?",
name="basin_mask",
datatype="GPBoolean",
parameterType="Optional",
direction="Input")
basin_mask.value = False
RB_routing = arcpy.Parameter(
displayName="Create reach-based routing (RouteLink) files?",
name="RB_routing",
datatype="GPBoolean",
parameterType="Optional",
direction="Input")
RB_routing.value = False
Lake_routing = arcpy.Parameter(
displayName="Create lake parameter (LAKEPARM) file?",
name="Lake_routing",
datatype="GPBoolean",
parameterType="Optional",
direction="Input")
Lake_routing.value = False
in_reservoirs = arcpy.Parameter(
displayName="Reservoirs Shapefile or Feature Class",
name="in_reservoirs",
datatype="DEFeatureClass",
parameterType="Optional",
direction="Input")
# Removed 5/11/2017 to simplify creation of lake features (using 1...n ID scheme)
## in_LakeIDField = arcpy.Parameter(
## displayName="ID field (Integer) for identifying lakes",
## name="in_IDfield",
## datatype="GPString",
## parameterType="Optional",
## direction="Input")
## in_LakeIDField.filter.type = "ValueList"
in_raster = arcpy.Parameter(
displayName="Input Elevation Raster",
name="in_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Input")
cellsize = arcpy.Parameter(
displayName="Regridding (nest) Factor",
name="cellsize",
datatype="GPLong",
parameterType="Required",
direction="Input")
cellsize.value = 10
threshold = arcpy.Parameter(
displayName="Number of routing grid cells to define stream",
name="threshold",
datatype="GPLong",
parameterType="Required",
direction="Input")
threshold.value = 200
ovroughrtfac_val = arcpy.Parameter(
displayName="OVROUGHRTFAC Value",
name="ovroughrtfac_val",
datatype="Any Value",
parameterType="Required",
direction="Input")
ovroughrtfac_val.value = 1.0
ovroughrtfac_val.category = "Parameter Values"
retdeprtfac_val = arcpy.Parameter(
displayName="RETDEPRTFAC Value",
name="retdeprtfac_val",
datatype="Any Value",
parameterType="Required",
direction="Input")
retdeprtfac_val.value = 1.0
retdeprtfac_val.category = "Parameter Values"
out_zip = arcpy.Parameter(
displayName="Output ZIP File",
name="out_zip",
datatype="File",
parameterType="Required",
direction="Output")
out_zip.value = 'WRF_Hydro_routing_grids.zip'
parameters = [in_nc, in_csv, basin_mask, RB_routing, Lake_routing, in_reservoirs, in_raster, cellsize, threshold, ovroughrtfac_val, retdeprtfac_val, out_zip] #, in_LakeIDField
return parameters
def isLicensed(self):
"""Allow the tool to execute, only if the ArcGIS Spatial Analyst extension
is available."""
try:
if arcpy.CheckExtension("Spatial") != "Available":
raise Exception
except Exception:
return False # tool cannot be executed
return True # tool can be executed
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
# Only activate masking if a CSV file has been input
if not parameters[1].altered:
parameters[2].enabled = False
else:
parameters[2].enabled = True
# Only activate Lake input parameter and lake ID field parameter if requesting LAKEPARM file
if parameters[4].value == True:
parameters[5].enabled = True
#parameters[6].enabled = True
else:
parameters[5].enabled = False
#parameters[6].enabled = False
## # Populate lake ID field combo box with list of Integer type fields from reservoirs shapefile
## if parameters[5].altered:
## in_lakes_file = parameters[5].valueAsText
## FieldNames = [field.name for field in arcpy.ListFields(in_lakes_file, "", "Integer")]
## parameters[6].filter.list = FieldNames
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
# Ensure that if a LAKEPARM table is requested, a lakes feature class is provided
if parameters[4].value == True and parameters[5].value is None:
parameters[5].setErrorMessage("Must specify Reservoirs Shapefile or Feature Class.")
return
def execute(self, parameters, messages):
"""The source code of the tool."""
tic = time.time()
reload(wrf_hydro_functions) # Reload in case code changes have been made
isError = False # Starting Error condition (no errors)
# Gather all necessary parameters
in_nc = parameters[0].valueAsText
in_csv = parameters[1].valueAsText
basin_mask = parameters[2].valueAsText
routing = parameters[3].value
Lake_routing = parameters[4].value
in_reservoir = parameters[5].valueAsText
#lakeIDfield = parameters[6].valueAsText
in_raster = parameters[6].valueAsText
cellsize = parameters[7].value
threshold = parameters[8].value
ovroughrtfac_val = parameters[9].value
retdeprtfac_val = parameters[10].value
out_zip = parameters[11].valueAsText
# Prepare output log file
outtable = open(os.path.join(os.path.dirname(out_zip), os.path.basename(out_zip) + '.log'), "w")
loglines = ['Begining processing on %s' %time.ctime()]
loglines.append('64-bit: %s' %bit64)
loglines.append('Input parameters:')
for param in parameters:
loglines.append(' Parameter: %s: %s' %(param.displayName, param.valueAsText))
outtable.writelines("\n".join(loglines) + "\n")
## if lakeIDfield is None:
## loglines = [' No Lake ID Field provided']
## arcpy.AddMessage(loglines[-1])
# Interpret the input for reservoir routing
if Lake_routing is False:
in_lakes = None
else:
in_lakes = in_reservoir
# Create scratch directory for temporary outputs
projdir = os.path.join(os.path.dirname(out_zip), 'scratchdir')
if os.path.exists(projdir):
shutil.rmtree(projdir)
os.makedirs(projdir)
arcpy.env.overwriteOutput = True
arcpy.env.workspace = projdir
arcpy.env.scratchWorkspace = projdir
'''Pre-defining the variables and populating variable attributes is
a much faster strategry than creating and populating each variable
sequentially, especially for netCDF3 versions. Also, unsigned integer
types are only allowed in NETCDF4.'''
# List of variables to create [<varname>, <vardtype>, <long_name>]
varList2D = [['CHANNELGRID', 'i4', ''],
['FLOWDIRECTION', 'i2', ''],
['FLOWACC', 'i4', ''],
['TOPOGRAPHY', 'f4', ''],
['RETDEPRTFAC', 'f4', ''],
['OVROUGHRTFAC', 'f4', ''],
['STREAMORDER', 'i1', ''],
['frxst_pts', 'i4', ''],
['basn_msk', 'i4', ''],
['LAKEGRID', 'i4', ''],
['landuse', 'f4', ''],
['LKSATFAC', 'f4', '']]
# Add variables depending on the input options
if routing:
varList2D.append(['LINKID', 'i4', ''])
# Step 1 - Georeference geogrid file
LU_INDEX, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, 'LU_INDEX') # Process: Generate LU Index grid
outtable.writelines("\n".join(loglines) + "\n")
hgt_m_raster, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, 'HGT_M')
outtable.writelines("\n".join(loglines) + "\n")
##LANDMASK, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, 'LANDMASK') # Process: Generate LANDMASK grid (1=Land, 0=Water)
##outtable.writelines("\n".join(loglines) + "\n")
# Create spatial metadata file for GEOGRID/LDASOUT grids
descData = arcpy.Describe(hgt_m_raster)
DXDY_dict = {u'DX': float(descData.meanCellWidth), u'DY': float(descData.meanCellHeight)}
out_nc1 = os.path.join(projdir, wrf_hydro_functions.LDASFile)
rootgrp1 = netCDF4.Dataset(out_nc1, 'w', format=outNCType) # wrf_hydro_functions.outNCType)
rootgrp1, grid_mapping, loglines = wrf_hydro_functions.create_CF_NetCDF(arcpy, hgt_m_raster, rootgrp1, map_pro, projdir, DXDY_dict,
sr2, GeoTransform, addLatLon=False, notes=processing_notes_SM, loglines=loglines)
rootgrp1.close()
del descData
# Step 2 - Create high resolution topography layers
mosprj, cellsize1, cellsize2, loglines = wrf_hydro_functions.create_high_res_topogaphy(arcpy, in_raster, hgt_m_raster, cellsize, sr2, projdir)
outtable.writelines("\n".join(loglines) + "\n")
# Create FULLDOM file
descData2 = arcpy.Describe(mosprj)
DXDY_dict = {u'DX': float(descData2.meanCellWidth), u'DY': float(descData2.meanCellHeight)}
GT_bits = GeoTransform.split(" ") # Split up GeoTransform string for replacing DX and DY
GeoTransform = '%s %s %s %s %s %s ' %(GT_bits[0], DXDY_dict['DX'], GT_bits[2], GT_bits[3], GT_bits[4], -DXDY_dict['DY']) # Alter DX/DY
out_nc2 = os.path.join(projdir, wrf_hydro_functions.FullDom)
rootgrp2 = netCDF4.Dataset(out_nc2, 'w', format=outNCType) # wrf_hydro_functions.outNCType)
rootgrp2, grid_mapping, loglines = wrf_hydro_functions.create_CF_NetCDF(arcpy, mosprj, rootgrp2, map_pro, projdir, DXDY_dict,
sr2, GeoTransform, addLatLon=True, notes=processing_notesFD, loglines=loglines, addVars=varList2D)
del descData2
### Step X(a) - Test to match LANDMASK - Only used for areas surrounded by water (LANDMASK=0)
##mosprj2, loglines = wrf_hydro_functions.adjust_to_landmask(arcpy, mosprj, LANDMASK, sr2, projdir, inunits)
##outtable.writelines("\n".join(loglines) + "\n")
##del LANDMASK
try:
# Step 4 - Hyrdo processing functions
rootgrp2, loglines = wrf_hydro_functions.sa_functions(arcpy, rootgrp2, basin_mask, mosprj, ovroughrtfac_val, retdeprtfac_val, projdir, in_csv, threshold, inunits, LU_INDEX, cellsize1, cellsize2, routing, in_lakes) #, lakeIDfield) # , mosprj2,
outtable.writelines("\n".join(loglines) + "\n")
rootgrp2.close()
arcpy.Delete_management(LU_INDEX) # Added 4/19/2017 to allow zipws to complete
arcpy.Delete_management(hgt_m_raster) # Added 4/19/2017 to allow zipws to complete
except Exception as e:
loglines.append('Exception: %s' %e)
arcpy.AddMessage(loglines[-1])
rootgrp2.close()
isError = True
# zip the folder
nclist = ['GEOGRID_LDASOUT_Spatial_Metadata.nc',
wrf_hydro_functions.FullDom,
'gw_basns.nc',
'gw_basns_geogrid.txt',
'gw_basns_geogrid.prj',
RT_nc,
'Route_Link.csv',
'LAKEPARM.TBL',
LK_nc,
'streams.shp', 'streams.shx', 'streams.shp.xml', 'streams.sbx', 'streams.sbn', 'streams.prj', 'streams.dbf',
'lakes.shp', 'lakes.shx', 'lakes.shp.xml', 'lakes.sbx', 'lakes.sbn', 'lakes.prj', 'lakes.dbf']
zipper = wrf_hydro_functions.zipUpFolder(arcpy, projdir, out_zip, nclist)
# Clean up and give finishing message
del LU_INDEX, hgt_m_raster
if isError:
loglines = ['Error encountered after %s seconds.' %(time.time()-tic)]
arcpy.AddMessage(loglines[-1])
raise SystemExit
else:
loglines = ['Completed without error in %s seconds.' %(time.time()-tic)]
arcpy.AddMessage(loglines[-1])
shutil.rmtree(projdir)
outtable.write(loglines[-1])
outtable.close()
return
class ExportGrid(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Export grid from GEOGRID file"
self.description = "This tool takes an input WRF Geogrid file in NetCDF format" + \
" and uses the specified variable's grid to produce a raster."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_nc = arcpy.Parameter(
displayName="Input GEOGRID File",
name="in_nc",
datatype="File",
parameterType="Required",
direction="Input")
# Fourth parameter
var_name = arcpy.Parameter(
displayName="Variable Name",
name="var_name",
datatype="GPString",
parameterType="Required",
direction="Input")
var_name.filter.type = "ValueList"
# Third parameter
out_raster = arcpy.Parameter(
displayName="Output Raster",
name="out_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Output")
parameters = [in_nc, var_name, out_raster]
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if parameters[0].altered:
in_nc_file = parameters[0].valueAsText
# Establish an object for reading the input NetCDF file
ncFP = arcpy.NetCDFFileProperties(in_nc_file)
# Loop through global variables in NetCDF file to gather projection information
ncVarNames = ncFP.getVariablesByDimension('west_east')
ncMassgridNames = []
for x in ncVarNames:
mgridvar = ncFP.getAttributeValue(x, 'stagger') # Only use variables on Massgrid for now ('M')
if mgridvar == 'M':
ncMassgridNames.append(x)
parameters[1].filter.list = ncMassgridNames
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
reload(wrf_hydro_functions) # Reload in case code changes have been made
# Set environments
arcpy.env.overwriteOutput = True
# Gather all necessary parameters
in_nc = parameters[0].valueAsText
Variable = parameters[1].valueAsText
out_raster = parameters[2].valueAsText
# Use wrf_hydro_functions to perform process
nc_raster, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, Variable)
# Set environments and save
arcpy.env.outputCoordinateSystem = sr2
nc_raster.save(out_raster)
arcpy.DefineProjection_management(out_raster, sr2)
del nc_raster
arcpy.AddMessage(' Process completed without error.')
arcpy.AddMessage(' Output Raster: %s' %out_raster)
return
class ExamineOutputs(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Examine Outputs of GIS Preprocessor"
self.description = "This tool takes the output zip file from the ProcessGeogrid script" + \
"and creates a raster from each output NetCDF file." + \
"" + \
"The Input should be a .zip file that was created using the WRF Hydro pre-" + \
"processing tools. The Output Folder parameter should be set to a non-existent " +\
"folder location. The tool will create the folder which will contain the results."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_zip = arcpy.Parameter(
displayName="Input ZIP File",
name="in_zip",
datatype="File",
parameterType="Required",
direction="Input")
# Output parameter
out_folder = arcpy.Parameter(
displayName="Output Folder",
name="out_folder",
datatype="DEFolder",
parameterType="Required",
direction="Output")
out_folder.defaultEnvironmentName = "workspace"
parameters = [in_zip, out_folder]
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
reload(wrf_hydro_functions) # Reload in case code changes have been made
# Initiate input and output parameters
in_zip = parameters[0].valueAsText
out_folder = parameters[1].valueAsText
# Create output directory
os.mkdir(out_folder)
# Use wrf_hydro_functions to perform process
out_sfolder = wrf_hydro_functions.Examine_Outputs(arcpy, in_zip, out_folder)
return
class ExportPRJ(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Export ESRI projection file (PRJ) from GEOGRID file"
self.description = "This tool takes an input WRF Geogrid file in NetCDF format" + \
" and uses the specified variable's projection parameters" + \
" to produce a projection file."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_nc = arcpy.Parameter(
displayName="Input GEOGRID File",
name="in_nc",
datatype="File",
parameterType="Required",
direction="Input")
# Second parameter
out_prj = arcpy.Parameter(
displayName="Output Projection File (.prj)",
name="out_prj",
datatype="DEPrjFile",
parameterType="Required",
direction="Output")
parameters = [in_nc, out_prj]
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
reload(wrf_hydro_functions) # Reload in case code changes have been made
# Set environments
arcpy.env.overwriteOutput = True
# Gather all necessary parameters
in_nc = parameters[0].valueAsText
out_prj = parameters[1].valueAsText
Variable = 'HGT_M'
# Use wrf_hydro_functions to perform process
nc_raster, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, Variable)
del nc_raster, sr2
# Optional save .prj file
with open(out_prj, 'w') as prj_file:
prj_file.write(Projection_String)
arcpy.AddMessage(' Process completed without error.')
arcpy.AddMessage(' Output Projection File: %s' %out_prj)
return
class GenerateLatLon(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Generate Latitude and Longitude Rasters"
self.description = "This tool takes an input raster (most likely produced" + \
" using the ExportGrid tool) and uses that grid to produce" + \
" latitude and longitude ESRI GRID rasters."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_raster = arcpy.Parameter(
displayName="Input Raster",
name="in_raster",
datatype="Raster Dataset",
parameterType="Required",
direction="Input")
# datatype="DERasterDataset" keyword can be used at 10.1 SP1
# Output parameter
out_folder = arcpy.Parameter(
displayName="Output Folder",
name="out_folder",
datatype="DEFolder",
parameterType="Required",
direction="Input")
out_folder.defaultEnvironmentName = "workspace"
parameters = [in_raster, out_folder]
return parameters
def isLicensed(self):
"""Allow the tool to execute, only if the ArcGIS Spatial Analyst extension
is available."""
try:
if arcpy.CheckExtension("Spatial") != "Available":
raise Exception
except Exception:
return False # tool cannot be executed
return True # tool can be executed
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
# Set environments
arcpy.env.overwriteOutput = True
# Gather all necessary parameters
inraster = parameters[0].valueAsText
projdir = parameters[1].valueAsText
arcpy.AddMessage('Input Raster Dataset: %s' %inraster)
arcpy.AddMessage('Directory to be used for outputs: %s' %projdir)
# Create latitude and longitude rasters
in_raster = arcpy.Raster(inraster)
loglines, xout2, yout2, xmap, ymap = wrf_hydro_functions.create_lat_lon_rasters(arcpy, projdir, in_raster)
arcpy.Delete_management(xmap)
arcpy.Delete_management(ymap)
del xmap, ymap, loglines
# Write to disk
xout2.save(os.path.join(projdir, 'longitude'))
yout2.save(os.path.join(projdir, 'latitude'))
arcpy.AddMessage(' Process completed without error.')
return
class SpatialMetadataFile(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Build Spatial Metadata File"
self.description = "This tool takes an input GEOGRID and uses that grid " + \
" information to produce spatial metadata files against " + \
" the multiple resolutions of WRF Hydro output files."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_nc = arcpy.Parameter(
displayName="Input GEOGRID File",
name="in_nc",
datatype="File",
parameterType="Optional",
direction="Input")
in_nc.filter.list = ['nc']
format_out = arcpy.Parameter(
displayName="Output Grid Resolution",
name="format_out",
datatype="String",
parameterType="Required",
direction="Input")
# Set a value list for input raster catalog
format_out.filter.type = "ValueList"
format_out.filter.list = ["LDASOUT", "RTOUT"]
format_out.value = "LDASOUT"
# Input parameter
factor = arcpy.Parameter(
displayName="Regridding Factor",
name="factor",
datatype="GPLong",
parameterType="Optional",
direction="Input")
factor.value = 1
# Output parameter
out_nc = arcpy.Parameter(
displayName="Output netCDF File",
name="out_nc",
datatype="File",
parameterType="Required",
direction="Output")
# Output parameter
latlon_vars = arcpy.Parameter(
displayName="Include LATITUDE and LONGITUDE 2D variables?",
name="latlon_vars",
datatype="Boolean",
parameterType="Optional",
direction="Input")
latlon_vars.value = False
parameters = [in_nc, format_out, factor, out_nc, latlon_vars]
return parameters
def isLicensed(self):
"""Allow the tool to execute, only if the ArcGIS Spatial Analyst extension
is available."""
try:
if arcpy.CheckExtension("Spatial") != "Available":
raise Exception
except Exception:
return False # tool cannot be executed
return True # tool can be executed
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
# Only activate Regridding Factor parameter if requesting CHRTOUT resolution
if parameters[1].altered:
if parameters[1].value == "LDASOUT":
parameters[2].enabled = False
parameters[2].value = 1
elif parameters[1].value == "RTOUT":
parameters[2].enabled = True
else:
parameters[2].enabled = False
parameters[2].value = 1
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
reload(wrf_hydro_functions) # Reload in case code changes have been made
# Coordinate Attribute Conventions from: http:https://www.unidata.ucar.edu/software/thredds/current/netcdf-java/tutorial/CoordinateAttributes.html
# Esri's use of CF conventions discussed here: http:https://pro.arcgis.com/en/pro-app/help/data/multidimensional/spatial-reference-for-netcdf-data.htm
# Set environments
tic1 = time.time()
arcpy.env.overwriteOutput = True
# Gather all necessary parameters
in_nc = parameters[0].valueAsText
format_out = parameters[1].valueAsText
factor = float(parameters[2].valueAsText)
out_nc = parameters[3].valueAsText
latlon_vars = parameters[4].value
projdir = os.path.dirname(out_nc)
# Print informational messages
arcpy.AddMessage('Input Raster Dataset: %s' %in_nc)
arcpy.AddMessage('Output Grid Resolution: %s' %format_out)
arcpy.AddMessage('Output Regridding Factor: %s' %factor)
arcpy.AddMessage('Directory to be used for outputs: %s' %projdir)
arcpy.AddMessage('Output netCDF File: %s' %out_nc)
# Prepare output log file
outtable = open(os.path.join(projdir, os.path.basename(out_nc) + '.log'), "w")
loglines = ['Begining processing on %s' %time.ctime()]
loglines.append('64-bit: %s' %bit64)
loglines.append('Input parameters:')
for param in parameters:
loglines.append(' Parameter: %s: %s' %(param.displayName, param.valueAsText))
# Georeference geogrid file
in_raster, sr, Projection_String, map_pro, GeoTransformStr, loglines2 = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, 'HGT_M')
loglines += loglines2
descData = arcpy.Describe(in_raster)
DXDY_dict = {u'DX': descData.meanCellWidth/factor, u'DY': descData.meanCellHeight/factor}
loglines.append(' New Resolution: %s %s' %(DXDY_dict[u'DX'], DXDY_dict[u'DY']))
arcpy.AddMessage(loglines[-1])
# Record GEOGRID MAP_PROJ attribute
loglines.append(' Map Projection of GEOGRID: %s' %wrf_hydro_functions.projdict[map_pro])
arcpy.AddMessage(loglines[-1])
loglines.append(' Esri PE String: %s' %Projection_String)
arcpy.AddMessage(loglines[-1])
# Create high resolution raster for RTOUT output using Spatial Analyst CreateConstantRaster function
if format_out == "RTOUT":
arcpy.env.snapRaster = in_raster
arcpy.env.outputCoordinateSystem = sr
in_raster = CreateConstantRaster(1, "INTEGER", DXDY_dict[u'DX'], descData.Extent) # Requires Spatial Analyst
# Create the netCDF file with spatial metadata
rootgrp = netCDF4.Dataset(out_nc, 'w', format=outNCType)
rootgrp, grid_mapping, loglines = wrf_hydro_functions.create_CF_NetCDF(arcpy, in_raster, rootgrp, map_pro, projdir,
DXDY_dict, sr, GeoTransformStr, latlon_vars, notes=processing_notes_SM, loglines=loglines)
rootgrp.close()
del in_raster
loglines += ['Completed without error in %s seconds.' %(time.time()-tic1)]
# Clean up and give finishing message
arcpy.AddMessage(loglines[-1])
outtable.writelines("\n".join(loglines) + "\n")
outtable.close()
return
class DomainShapefile(object):
"""This function taks the WRF GEOGRID file and outputs a polygon shapefile using the bounding coordinate information."""
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create Domain Boundary Shapefile"
self.description = "This tool takes an WRF Geogrid file and creates a single" + \
" polygon shapefile that makes up the boundary of the domain" + \
" of the M-grid (HGT_M, for example)."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_nc = arcpy.Parameter(
displayName="Input GEOGRID File",
name="in_nc",
datatype="File",
parameterType="Required",
direction="Input")
# Output parameter
out_shp = arcpy.Parameter(
displayName="Output Shapefile",
name="out_shp",
datatype="DEShapefile",
parameterType="Required",
direction="Output")
parameters = [in_nc, out_shp]
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
try:
if arcpy.CheckExtension("Spatial") != "Available":
raise Exception
except Exception:
return False # tool cannot be executed
return True # tool can be executed
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
reload(wrf_hydro_functions) # Reload in case code changes have been made
# Gather all necessary parameters
in_nc = parameters[0].valueAsText
out_shp = parameters[1].valueAsText
# Create scratch directory for temporary outputs
projdir = os.path.dirname(in_nc)
arcpy.env.overwriteOutput = True
arcpy.env.workspace = projdir
arcpy.env.scratchWorkspace = projdir
# Get coarse grid raster
hgt_m_raster, sr2, Projection_String, map_pro, GeoTransform, loglines = wrf_hydro_functions.georeference_geogrid_file(arcpy, in_nc, 'HGT_M')
del Projection_String, loglines
# Use coarse grid raster to create shapefile
wrf_hydro_functions.domain_shapefile(arcpy, hgt_m_raster, out_shp, sr2)
# Delete intermediate files in scratch dir
del hgt_m_raster, sr2
return parameters
class Reach_Based_Routing_Addition(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Add reach-based routing"
self.description = "This tool takes an input Routing Stack .ZIP file," + \
" typically created by the ProcessGeogridFile tool," + \
" and adds in the reach-based routing table and grids."
self.canRunInBackground = True
self.category = "Utilities"
def getParameterInfo(self):
"""Define parameter definitions"""
# Input parameter
in_zip = arcpy.Parameter(
displayName="Routing Stack ZIP File",
name="in_zip",
datatype="File",
parameterType="Required",
direction="Input")
in_zip.filter.list = ['zip']
# Output parameter
out_zip = arcpy.Parameter(
displayName="Output ZIP File",
name="out_zip",
datatype="File",
parameterType="Required",
direction="Output")
parameters = [in_zip, out_zip]
return parameters
def isLicensed(self):
"""Allow the tool to execute, only if the ArcGIS Spatial Analyst extension
is available."""
try:
if not arcpy.CheckExtension("Spatial") == "Available":