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 )
0 commit comments