Skip to content

Commit 118d0c5

Browse files
committed
Added functionality to update graip database with stability index from a raster.
1 parent 259750b commit 118d0c5

File tree

2 files changed

+174
-0
lines changed

2 files changed

+174
-0
lines changed

AddStabilityIndexToDatabase.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
__author__ = 'Pabitra'
2+
3+
import os
4+
import sys
5+
6+
from osgeo import ogr, gdal
7+
from gdalconst import *
8+
import pyodbc
9+
import click
10+
11+
import utils
12+
13+
@click.command()
14+
### Use the followings for debugging within PyCharm
15+
# @click.option('--mdb', default=r"E:\Graip\GRAIPPythonTools\demo\demo_CSI\test.mdb", type=click.Path(exists=True))
16+
# @click.option('--dp', default=r"E:\Graip\GRAIPPythonTools\demo\demo_CSI\drainpoints.shp", type=click.Path(exists=True))
17+
# @click.option('--si', default=r"E:\Graip\GRAIPPythonTools\demo\demo_CSI\Data\demsi_from_taudem_2.tif", type=click.Path(exists=True))
18+
19+
@click.option('--mdb', default="test.mdb", type=click.Path(exists=True))
20+
@click.option('--dp', default="DrainPoints.shp", type=click.Path(exists=True))
21+
@click.option('--si', default="demsi.tif", type=click.Path(exists=True))
22+
def main(mdb, dp, si):
23+
_validate_args(mdb, dp, si)
24+
_sindex_drain_points(mdb, dp, si)
25+
26+
def _validate_args(mdb, dp, si):
27+
driver = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())
28+
29+
dataSource = driver.Open(dp, GA_ReadOnly)
30+
if not dataSource:
31+
raise utils.ValidationException("Not a valid shape file (%s) provided for parameter --dp." % dp)
32+
else:
33+
dataSource.Destroy()
34+
35+
try:
36+
if not os.path.dirname(mdb):
37+
mdb = os.path.join(os.getcwd(), mdb)
38+
39+
conn = pyodbc.connect(utils.MS_ACCESS_CONNECTION % mdb)
40+
conn.close()
41+
except pyodbc.Error as ex:
42+
raise utils.ValidationException(ex.message)
43+
44+
dataSource = gdal.Open(si, GA_ReadOnly)
45+
if not dataSource:
46+
raise utils.ValidationException("File open error. Not a valid file (%s) provided for the '--si' parameter."
47+
% si)
48+
49+
else:
50+
dataSource = None
51+
52+
53+
def _sindex_drain_points(mdb, dp, si):
54+
# for each drain point in the drain points shape file find the cell value in the combined stability index grid file
55+
# and use that value to populate the corresponding row in the drainpoints table
56+
driver = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())
57+
dataSource = driver.Open(dp, GA_Update)
58+
layer = dataSource.GetLayer()
59+
layerDefn = layer.GetLayerDefn()
60+
fld_index_graipdid = layerDefn.GetFieldIndex('GRAIPDID')
61+
62+
si_grid = gdal.Open(si)
63+
si_band = si_grid.GetRasterBand(1)
64+
65+
field_to_create = 'SI'
66+
try:
67+
#delete field if it exists in drainpoints shapefile
68+
fld_index_dp = layerDefn.GetFieldIndex(field_to_create)
69+
if fld_index_dp > 0:
70+
layer.DeleteField(fld_index_dp)
71+
72+
# add a new field (column) to the attribute table of drainpoints shapefile
73+
layer.CreateField(ogr.FieldDefn(field_to_create, ogr.OFTReal))
74+
75+
fld_index_dp = layerDefn.GetFieldIndex(field_to_create)
76+
except:
77+
pass
78+
79+
try:
80+
conn = pyodbc.connect(utils. MS_ACCESS_CONNECTION % mdb)
81+
cursor = conn.cursor()
82+
83+
for feature in layer:
84+
geom = feature.GetGeometryRef()
85+
total_points = geom.GetPointCount()
86+
if total_points > 0:
87+
# calculate range from the elevation of 2 end points of the road segment
88+
row, col = utils.get_coordinate_to_grid_row_col(geom.GetX(0), geom.GetY(0), si_grid)
89+
si_cell_data = si_band.ReadAsArray(xoff=col, yoff=row, win_xsize=1, win_ysize=1)
90+
graipdid = feature.GetFieldAsInteger(fld_index_graipdid)
91+
dp_row = cursor.execute("SELECT * FROM DrainPoints WHERE GRAIPDID=%d" % graipdid).fetchone()
92+
93+
if dp_row:
94+
if si_cell_data[0][0] == si_band.GetNoDataValue():
95+
dp_row.SI = -9999
96+
else:
97+
dp_row.SI = float(si_cell_data[0][0])
98+
99+
update_sql = "UPDATE DrainPoints SET SI=? WHERE GRAIPDID=?"
100+
data = (dp_row.SI, dp_row.GRAIPDID)
101+
102+
cursor.execute(update_sql, data)
103+
104+
# write si data to drainpoints shapefile
105+
feature.SetField(fld_index_dp, data[0])
106+
# rewrite the feature to the layer - this will in fact save the data to the file
107+
layer.SetFeature(feature)
108+
109+
geom = None
110+
conn.commit()
111+
except:
112+
raise
113+
finally:
114+
# cleanup
115+
if conn:
116+
conn.close()
117+
118+
if dataSource:
119+
dataSource.Destroy()
120+
121+
if __name__ == '__main__':
122+
try:
123+
main()
124+
print("Adding of stability index to database was successful.\n")
125+
sys.exit(0)
126+
except Exception as e:
127+
print("Adding of stability index to database failed.\n")
128+
print(e.message)
129+
sys.exit(1)

ArcGISAddStabilityIndexToDatabase.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
__author__ = 'Pabitra'
2+
import os
3+
import subprocess
4+
5+
import arcpy
6+
7+
# get the input parameters
8+
graip_database_file = arcpy.GetParameterAsText(0)
9+
desc = arcpy.Describe(graip_database_file)
10+
graip_database_file = str(desc.catalogPath)
11+
12+
dp_shapefile = arcpy.GetParameterAsText(1)
13+
desc = arcpy.Describe(dp_shapefile)
14+
dp_shapefile = str(desc.catalogPath)
15+
16+
si_grid_file = arcpy.GetParameterAsText(2)
17+
desc = arcpy.Describe(si_grid_file)
18+
si_grid_file = str(desc.catalogPath)
19+
20+
# construct command to execute
21+
current_script_dir = os.path.dirname(os.path.realpath(__file__))
22+
23+
# put quotes around file paths in case they have spaces
24+
graip_database_file = '"' + graip_database_file + '"'
25+
dp_shapefile = '"' + dp_shapefile + '"'
26+
si_grid_file = '"' + si_grid_file + '"'
27+
py_script_to_execute = os.path.join(current_script_dir, 'AddStabilityIndexToDatabase.py')
28+
py_script_to_execute = '"' + py_script_to_execute + '"'
29+
cmd = py_script_to_execute + \
30+
' --mdb ' + graip_database_file + \
31+
' --dp ' + dp_shapefile + \
32+
' --si ' + si_grid_file
33+
34+
# show executing command
35+
arcpy.AddMessage('\nEXECUTING COMMAND:\n' + cmd)
36+
37+
# Capture the contents of shell command and print it to the arcgis dialog box
38+
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
39+
arcpy.AddMessage('\nProcess started:\n')
40+
start_message = "Please wait. It may take few seconds. Computation is in progress ..."
41+
arcpy.AddMessage(start_message)
42+
for line in process.stdout.readlines():
43+
if start_message not in line:
44+
arcpy.AddMessage(line)
45+

0 commit comments

Comments
 (0)