-
Notifications
You must be signed in to change notification settings - Fork 4
/
vic_auto.py
279 lines (238 loc) · 14.1 KB
/
vic_auto.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
"""
Created on Sat Apr 13 2019
@author: Lokendra Singh Rathore
@National Institute of Hydrology, Roorkee, India
@email: lokendra.nalu@gmail.com
This script is to generate vegetation parameter, soil parameter file and elevation band file
for Variable Infiltration Capacity (VIC) hydrologic model
It does not generate Forcing files (A seperate python script is there for forcing files)
The script is written in Python 2.7 and has been tested on ArcGIS version 10.5
If you have Python 3, then change put the parantheses after print command allover otherwise it will not run
"""
#############################################################################################################################
#Following python libraries should be installed
import arcpy
import os
import pandas as pd
import numpy as np
############################################################################################################################
### Edit the path of following files:
### Note: Coordinate system for all input files should be : GCS WGS 1984
###Use \\ or / for file path, dont use \
### Make sure, there is not any space in the file or folder name (use _ insted)
workspace="G:\\Rathore\\vic_auto5" ## Put location a folder, all files will be saved in there (TIP: Create a fresh folder)
shape_file="G:/Rathore/vic_auto7/shape_proj.shp" #Shapefile of the basin area. Make sure its cordinates are GCS WGS 1984
dem="G:/Rathore/vic_auto7/dem_extfill.tif" #DEM " " " " " " " " " " "
lulc="G:/Rathore/swat_inp/soil_lulc/lulc.tif" #LULC image of area (TO MAKE VEG PARAMETER FILE)
soil="G:/Rathore/vic_auto7/soil_sbeas.tif" #SOIL Image (To make soil parameter file)
rooting_depth_csv="C:\\Python27\\ArcGIS10.5\\vic_auto\\RootingDepths.csv" ##Root depth csv file, provided with the docs
soil_appendix="C:\\Python27\\ArcGIS10.5\\vic_auto\\soil_appendix_3layer.xlsx" ##Soil appendix, provied with docs
###Cell height and width in degree, Edit acc
cell_h=0.05 ### 5 km = 0.05 degree
cell_w=0.05
##########################################################################################################################
## DO NOT EDIT ANYTHING##
arcpy.env.overwriteOutput = True
arcpy.env.workspace=workspace
arcpy.env.outputCoordinateSystem = arcpy.SpatialReference("WGS 1984")
os.chdir(workspace)
root=pd.read_csv(rooting_depth_csv)
desc = arcpy.Describe(shape_file)
print(("Extent:\n XMin: {0}, XMax: {1}, YMin: {2}, YMax: {3}".format(desc.extent.XMin, desc.extent.XMax, desc.extent.YMin, desc.extent.YMax)))
top=desc.extent.YMax
bottom=desc.extent.YMin
left=desc.extent.XMin
right=desc.extent.XMax
origin=str(left)+" "+ str(bottom)
opposite=str(right)+" "+ str(top)
y_axis=str(left)+" "+str(bottom+0.010)
#direc=arcpy.env.workspace+"\\"
grid_name="fishnet_f.shp"
threshold_area=cell_h*cell_h*10000*1000000*0.1
sql_cmd="basin_pt=1 AND area1>= {0}".format(threshold_area)
print "Making fishnet... \n"
arcpy.CreateFishnet_management(grid_name,origin, y_axis, str(cell_h),str(cell_w), "0", "0", opposite, "LABELS",geometry_type="POLYGON")
arcpy.AddField_management(shape_file, "basin_pt", "SHORT", 0, "", "", "refcode", "NULLABLE", "REQUIRED")
arcpy.CalculateField_management(shape_file,field="basin_pt",expression="1")
arcpy.Union_analysis(["fishnet_f.shp",shape_file], 'union.shp', 'ALL', '#', 'GAPS')
arcpy.AddField_management("union.shp","area1","DOUBLE")
arcpy.AddField_management("fishnet_f.shp", "run_grid", "SHORT", 0, "", "", "refcode", "NULLABLE", "REQUIRED")
print "Calculating area of each grid cell after union... \n"
arcpy.CalculateField_management("union.shp","area1",'!shape.area!',"PYTHON")
temp_layer=arcpy.MakeFeatureLayer_management("union.shp","temp_lyr")
arcpy.SelectLayerByAttribute_management(temp_layer,"NEW_SELECTION",sql_cmd) ##area1 threshold can be changed accordingly
print "Making run grid... \n"
arcpy.CopyFeatures_management(temp_layer,"new_run_grid")
arcpy.AddField_management("new_run_grid.shp", "run_grid1", "SHORT", 0, "", "", "refcode", "NULLABLE", "REQUIRED")
arcpy.CalculateField_management("new_run_grid.shp","run_grid1",'1')
arcpy.DeleteField_management(shape_file,"basin_pt")
d= {k:v for k,v in arcpy.da.SearchCursor("new_run_grid.shp",["FID_Fishne","run_grid1"])}
with arcpy.da.UpdateCursor("fishnet_f.shp",["FID","run_grid"]) as cursor:
for row in cursor:
if row[0] in d:
row[1]=d[row[0]]
cursor.updateRow(row)
print "Created run grid named new_run_grid.shp"
arcpy.MakeFeatureLayer_management("fishnet_f.shp","fish_lyr")
print "Calculating elevation ...\n"
arcpy.AddField_management("fish_lyr","ELEVATION","FLOAT")
arcpy.gp.ZonalStatisticsAsTable_sa("fish_lyr","FID",dem,"ele_tab",'DATA','MEAN')
ddd={k:v for k,v in arcpy.da.SearchCursor("ele_tab",["FID","MEAN"])}
with arcpy.da.UpdateCursor("fish_lyr",["FID","ELEVATION"]) as cursor:
for row in cursor:
if row[0] in ddd:
row[1]=ddd[row[0]]
cursor.updateRow(row)
arcpy.SelectLayerByAttribute_management("fish_lyr","NEW_SELECTION",'"run_grid"=1')
arcpy.AddField_management("fish_lyr","SOIL","SHORT")
print "Indetifying soil texture... \n"
arcpy.gp.ZonalStatisticsAsTable_sa("new_run_grid.shp","FID_fishne",soil,"soil_tab",'DATA','MAJORITY')
dd={k:v for k,v in arcpy.da.SearchCursor("soil_tab",["FID_fishne","MAJORITY"])}
with arcpy.da.UpdateCursor("fish_lyr",["FID","SOIL"]) as cursor:
for row in cursor:
if row[0] in dd:
row[1]=dd[row[0]]
cursor.updateRow(row)
arcpy.AddField_management("fish_lyr","lat","FLOAT")
arcpy.AddField_management("fish_lyr","lon","FLOAT")
print "Identifying centroid locations of each grid cells ... \n"
arcpy.CalculateField_management("fish_lyr","lat","!SHAPE.CENTROID.Y!","PYTHON_9.3")
arcpy.CalculateField_management("fish_lyr","lon","!SHAPE.CENTROID.X!","PYTHON_9.3")
arcpy.AddField_management("fish_lyr","slope","FLOAT")
print "The x,y are in degeree and z (elevation) is in meter, so the z=0.000009 was used bcoz 1 meter ~ 0.000009 (CAN BE CHANGED ACCORDINGLY)... \n"
arcpy.gp.Slope_sa(dem, 'slope_temp', 'PERCENT_RISE',"0.000009") # The x,y are in degeree and z in meter, so 1 meter ~ 0.000009 (CAN BE CHANGED ACCORDINGLY)
(arcpy.Raster('slope_temp')/100).save("slope_per")
print("Calculating slope... \n")
arcpy.gp.ZonalStatisticsAsTable_sa("fish_lyr","FID","slope_per","slope_tab",'DATA','MEAN')
arcpy.AddJoin_management("fish_lyr","FID","slope_tab","FID")
arcpy.CalculateField_management("fish_lyr","fishnet_f.slope","!slope_tab:MEAN!","PYTHON")
arcpy.RemoveJoin_management("fish_lyr","slope_tab")
print "Creating final fishnet (fishnet_final.shp) which consists rungrid, lat, lon, elevation, soil and slope values for all run cell ... \n"
arcpy.CopyFeatures_management("fish_lyr","fishnet_final.shp")
arcpy.AddField_management("fishnet_final.shp","area","FLOAT")
arcpy.CalculateField_management("fishnet_final.shp","area","!shape.area!","PYTHON")
user_soil=input("Do you want to generate Soil Parameter File?\n (Type 1 for YES and 0 for NO:)")
if user_soil==1:
print "Preparing soil parameter file, dont open any files until it completes... \n"
arcpy.ExcelToTable_conversion(soil_appendix,"soil_app1")
arcpy.AddJoin_management("fish_lyr","SOIL","soil_app1","SOIL_CLASS")
cols=[a.name for a in arcpy.ListFields("fish_lyr")]
cols_to_take=[cols[0]]+cols[3:5]+cols[6:9]+cols[12:]
arcpy.ExportXYv_stats("fish_lyr",cols_to_take,"COMMA","temp_soil.csv","ADD_FIELD_NAMES")
temp=pd.read_csv(workspace+"\\"+"temp_soil.csv")
temp=temp.iloc[:,2:]
temp["dsmax"]=temp["FISHNET_F.SLOPE"]*temp["SOIL_APP1:KSAT_Z1"]
temp["grid_no"]=temp['FISHNET_F.FID']
temp=temp.drop(['FISHNET_F.FID','FISHNET_F.SLOPE'],axis=1)
c1=temp.columns.tolist()
colord=[c1[0]]+[c1[-1]]+c1[2:6]+[c1[-2]]+c1[6:20]+[c1[1]]+c1[20:-2]
new_temp=temp[colord]
os.chdir(workspace)
arcpy.AddJoin_management("fish_lyr","SOIL","soil_app1","SOIL_CLASS")
cols=[a.name for a in arcpy.ListFields("fish_lyr")]
cols_to_take=[cols[0]]+cols[3:5]+cols[6:9]+cols[12:]
arcpy.ExportXYv_stats("fish_lyr",cols_to_take,"COMMA","temp_soil.csv","ADD_FIELD_NAMES")
temp=pd.read_csv(workspace+"\\"+"temp_soil.csv")
temp=temp.iloc[:,2:]
temp["dsmax"]=temp["FISHNET_F.SLOPE"]*temp["SOIL_APP1:KSAT_Z1"]
temp["grid_no"]=temp['FISHNET_F.FID']
temp=temp.drop(['FISHNET_F.FID','FISHNET_F.SLOPE'],axis=1)
c1=temp.columns.tolist()
colord=[c1[0]]+[c1[-1]]+c1[2:6]+[c1[-2]]+c1[6:20]+[c1[1]]+c1[20:-2]
new_temp=temp[colord]
new_temp=new_temp.dropna(axis=0)
os.chdir(workspace)
new_temp.to_csv("soil_parameter_new.txt",index=None,sep="\t")
arcpy.RemoveJoin_management("fish_lyr","soil_app1")
print "soil parameter with name soil_parameter_new has been generated, it is located in worskpace \n"
print "Remove the header line from soil par file or put a # to make it comment for VIC \n"
#### VEG PARAM SCRIPT##########
user_veg=input("Do you want to generate Vegetation Parameter File? \n (Type 1 for YES an 0 for NO:)")
if user_veg==1:
print "\nGenerating vegetation par file... \n"
arcpy.gp.TabulateArea_sa("fish_lyr","FID",lulc,"Value","lulc_tab")
arcpy.TableToTable_conversion("lulc_tab",arcpy.env.workspace,"temp_lulc.csv")
temp_l=pd.read_csv(workspace+"\\"+"temp_lulc.csv")
temp_l=temp_l.drop(["OID"],axis=1)
temp_l["Run_grid"]=1
tc=temp_l.columns.tolist()
tc_new=[tc[0]]+[tc[-1]]+tc[1:-1]
temp_l=temp_l[tc_new]
grid_data=temp_l
df=pd.DataFrame()
for i in range(grid_data.shape[0]):
if grid_data["Run_grid"][i]!= 0:
NZ=np.count_nonzero(grid_data.iloc[i,2:]) #no. of non zero lulc areas
s=pd.DataFrame([grid_data["FID"][i],NZ,-9999,-9999,-9999,-9999,-9999,-9999,-9999]).T
for j in range(2,grid_data.shape[1]):
if grid_data.iloc[i,j]!=0:
lulc_class=int(list(grid_data)[j].split("_")[1])
fract=grid_data.iloc[i,j]/sum(grid_data.iloc[i,2:])
for k in range(root.shape[0]):
if root.iloc[k,0]==lulc_class:
rvalues=root.iloc[k,1:]
s1=pd.DataFrame(pd.concat([pd.Series([-9999,lulc_class,fract]),rvalues])).T
s1.columns=range(9)
s=s.append(s1)
df=df.append(s)
df.replace(-9999," ").to_excel("vegparam_python_test.xlsx",header=None,index=None)
print "Completed making vegetation par file (vegparam_python_test.xlsx), located in workspace\n"
print "Convert the excel file to tab delimited text file for VIC\n"
#print "Vegetation parameter file and soil parameter file have been generated successfully. Remove the header line from soil par file\n"
#print "************************************************** ॐ ******************************************************"
############## SCRIPT FOR SONW/ELEVATION BAND FILE GENERATION ###################
os.chdir(workspace)
user=input("Do you want to make snow/elevation band file?\n (type 0 for no, 1 for yes):\n ")
if user==1:
user_i=input("Type the number of elevation bands required: ")
dem_ext=arcpy.sa.ExtractByMask(dem,shape_file)
dem_desc=arcpy.sa.Raster(str(dem_ext))
d1=dem_desc.minimum
d2=dem_desc.maximum
band_dif=math.ceil((d2-d1)/user_i)
r1=d1
remap=[]
print "The elevation band file will have the following range of bands: \n"
for i in range(user_i):
r= [r1+(i*band_dif), r1+band_dif*(i+1),i+1]
print r
remap.append(r)
remap[-1][1]=d2
dem_re=arcpy.sa.Reclassify(str(dem_ext),"VALUE",arcpy.sa.RemapRange(remap))
#dem_re.save("reclass_dem_eleband.tif")
print "Elevation band file is being processed... \n"
arcpy.RasterToPolygon_conversion(in_raster=dem_re,raster_field='VALUE',out_polygon_features="ras2poly_redem",simplify="NO_SIMPLIFY")
arcpy.sa.TabulateArea("fishnet_final.shp","FID", dem_re, "VALUE","tab_area_eleband")
arcpy.Union_analysis(["ras2poly_redem.shp","fishnet_f.shp"],"union_elebnd")
arcpy.gp.ZonalStatisticsAsTable_sa('union_elebnd.shp', 'FID_ras2po', dem_ext, "ele_eachzonetab1", 'DATA', 'MEAN')
arcpy.AddField_management("union_elebnd.shp","MEAN_ELE","DOUBLE")
arcpy.MakeFeatureLayer_management("union_elebnd.shp","union_elebndlyr")
arcpy.AddJoin_management("union_elebndlyr","FID_ras2po","ele_eachzonetab1","FID_ras2po",join_type="KEEP_COMMON")
arcpy.CalculateField_management("union_elebndlyr",'union_elebnd.MEAN_ELE',"!ele_eachzonetab1:MEAN!","PYTHON")
arcpy.RemoveJoin_management("union_elebndlyr")
arcpy.TableToExcel_conversion("union_elebndlyr","temp_eb.xls")
os.chdir(workspace)
temp_eb=pd.read_excel("temp_eb.xls")
new_col_lower=[x.lower() for x in list(temp_eb.columns)]
temp_eb.columns=new_col_lower
temp1=temp_eb[(temp_eb["run_grid"]==1) & (temp_eb["fid_ras2po"]>=0)]
temp2=temp1[["fid","fid_ras2po","fid_fishne","run_grid","mean_ele",'gridcode']]
pivot=pd.pivot_table(temp2,index=["fid_fishne"],columns="gridcode",values="mean_ele",aggfunc=np.mean,fill_value=0)
arcpy.TableToExcel_conversion("tab_area_eleband","tabulate_area_temp.xls")
tab_area=pd.read_excel("tabulate_area_temp.xls")
tab_area["sum"]=tab_area.iloc[:,2:].sum(axis=1)
df_rand=pd.DataFrame()
for i in range(user_i):
df_rand[str(i)]=tab_area.iloc[:,i+2]/tab_area["sum"]
df_rand["new"]=list(pivot.index)
pivot["new"]=list(pivot.index)
dfm1=df_rand.merge(pivot)
dfm2=pd.concat([dfm1,df_rand],axis=1)
#dfm2=dfm2.iloc[:,:-1]
dfm2.index=dfm2.new
dfm2=dfm2.drop("new",axis=1)
dfm2.to_csv("elebandfile_"+str(user_i),sep="\t",header=None)
print "Elevation/snow band file with mentioned band numbers, has been prepared with the name of \n"
print "elebandfile_"+str(user_i)+ " in the workspace.\n"
print "Make sure the elevation band file has same grid numbers as soil paramtere file"
print "VIC input files have been generated in the defined worskpace"