-
Notifications
You must be signed in to change notification settings - Fork 0
/
coresyf_vector_creator_lnec_wings.py
executable file
·288 lines (227 loc) · 10.7 KB
/
coresyf_vector_creator_lnec_wings.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
#!/usr/bin/env python
#==============================================================================
# <coresyf_vector_creator.py>
#==============================================================================
# Project : Co-ReSyF
# Company : Deimos Engenharia
# Component : Co-ReSyF Tools (vector editing and creation tool)
# Language : Python (v.2.6)
#------------------------------------------------------------------------------
# Scope : Command line vector creation and edition tool for GDAL supported
# shapefiles.
# Usage : (see the following docstring)
#==============================================================================
# $LastChangedRevision: $:
# $LastChangedBy: $:
# $LastChangedDate: $:
#==============================================================================
'''
@summary:
This module runs the following Co-ReSyF tool:
- Vector creation and edition
It uses the GDAL ogr module to create and edit shapefiles.
It can be used to create new shapefiles or to add attribute fields and respective
values to existing shapefiles. Only the point geometry is supported.
Refs: https://pcjericks.github.io/py-gdalogr-cookbook/geometry.html#create-a-point
https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
@example:
Example 1 - Create a shapefile using text file with data field values separated by tab character:
./coresyf_vector_creator.py -o ../examples/VectorCreator/newshapefile.shp --data_file ../examples/VectorCreator/data_to_create.txt
Example 2 - Updating the previous shapefile with new data field values contained in 'data2.txt':
./coresyf_vector_creator.py -r ../examples/VectorCreator/newshapefile.shp --data_file ../examples/VectorCreator/data_to_edit.txt
@version: v.1.0
@author: RCCC
@change:
1.0
- First release of the tool.
'''
VERSION = '1.0'
USAGE = ( '\n'
'coresyf_vector_creator.py.py [-r <InputVectorfile>] [-o <OutputVectorfile>] [--o_format <VectorFormat>] [--data_file <DataFile>]'
"\n")
''' SYSTEM MODULES '''
from optparse import OptionParser
import sys
import csv, os
from osgeo import ogr, osr
import shutil
import time
def createPoint( point_coord = [] ):
my_point = ogr.Geometry( ogr.wkbPoint )
my_point.AddPoint(*point_coord)
print my_point.ExportToWkt()
return my_point
def createLine( line_coord = [] ):
my_line = ogr.Geometry( ogr.wkbLineString )
for point_coord in line_coord:
my_line.AddPoint(*point_coord)
print my_line.ExportToWkt()
return my_line
def createLinearRing( line_coord = [] ):
my_ring = ogr.Geometry( ogr.wkbLinearRing )
for point_coord in line_coord:
my_ring.AddPoint(*point_coord)
print my_ring.ExportToWkt()
return my_ring
def createMultiPoint( points_coord = [] ):
my_multipoint = ogr.Geometry( ogr.wkbMultiPoint )
for point_coord in points_coord:
my_multipoint.AddGeometry( createPoint(point_coord) )
print my_multipoint.ExportToWkt()
return my_multipoint
def createMultiLine( lines_coord = [] ):
my_multiline = ogr.Geometry( ogr.wkbMultiLineString )
for line_coord in lines_coord:
my_multiline.AddGeometry( createLine(line_coord) )
print my_multiline.ExportToWkt()
return my_multiline
def createPolygon( points_coord = [] ):
my_polygon = ogr.Geometry( ogr.wkbPolygon )
my_polygon.AddGeometry( createLinearRing(points_coord) )
print my_polygon.ExportToWkt()
return my_polygon
def createMultiPolygon( polygons_coord = [] ):
my_multipolygon = ogr.Geometry( ogr.wkbMultiPolygon )
for polygon_coord in polygons_coord:
my_multipolygon.AddGeometry( createPolygon(polygon_coord) )
print my_multipolygon.ExportToWkt()
return my_multipolygon
#createPoint([10, 20]) # POINT (10 20 0)
#createLine([[10, 20], [30, 40]]) # LINESTRING (10 20 0,30 40 0)
#createPolygon([[10, 20], [30, 40], [60, 70]]) # POLYGON ((10 20 0,30 40 0,60 70 0))
#createMultiPoint([[10, 20], [30, 40], [60, 70]]) # MULTIPOINT (10 20 0,30 40 0,60 70 0)
#createMultiLine([ [[10, 20], [30, 40], [60, 70]], [[10, 20], [30, 40], [60, 70]] ]) # MULTILINESTRING ((10 20 0,30 40 0,60 70 0),(10 20 0,30 40 0,60 70 0))
#createMultiPolygon([ [[10, 20], [30, 40], [60, 70]], [[10, 20], [30, 40], [60, 70]] ]) # MULTIPOLYGON (((10 20 0,30 40 0,60 70 0)),((10 20 0,30 40 0,60 70 0)))
def createGeoFromWKT (wkt_code):
geo = ogr.CreateGeometryFromWkt(wkt_code)
if geo:
return geo
else:
print ('WKT Expression Error. Check syntax')
#createGeoFromWKT('POINT (10 0)')
def createVector(file_path, data_file, format_name='ESRI Shapefile' ):
# this is a wings workaround since wings does not name files with extensions
#file_path = file_path + ".shp"
# set up the shapefile driver
output_file_path = file_path
file_path = "/tmp/Bathymetry"
driver = ogr.GetDriverByName( format_name )
# Remove output shapefile if it already exists
if os.path.exists(file_path):
driver.DeleteDataSource(file_path)
# create the data source
dst_datasource = driver.CreateDataSource( file_path + ".shp" )
# Create layer with the spatial reference, WGS84
proj = osr.SpatialReference()
proj.SetWellKnownGeogCS( 'EPSG:4326' )
layer_name = "Bathymetry"
dst_layer = dst_datasource.CreateLayer(layer_name, srs=proj, geom_type = ogr.wkbPoint)
# Read data from data file
data = csv.DictReader(open(data_file,"rb"), delimiter=',', quoting=csv.QUOTE_NONE)
# Add a new fields
for field in data.fieldnames:
new_field = ogr.FieldDefn(field, ogr.OFTReal)
dst_layer.CreateField(new_field)
new_field = None
# Add features and attributes to the shapefile
for row in data:
feature = ogr.Feature ( dst_layer.GetLayerDefn() )
for field in data.fieldnames:
feature.SetField(field, row[field])
# create the geometry from WKT
wkt = "POINT(%f %f)" % (float(row['Longitude']) , float(row['Latitude']))
point = ogr.CreateGeometryFromWkt(wkt)
feature.SetGeometry( point )
dst_layer.CreateFeature(feature)
feature = None
# end of the workaround. Now a file with shapefile contents is saved in the filepath that wings provided
#os.rename(file_path, file_path_temp)
dst_datasource = None
shutil.move(file_path + ".shp", output_file_path)
shutil.move(file_path + ".dbf", output_file_path + ".dbf")
shutil.move(file_path + ".prj", output_file_path + ".prj")
shutil.move(file_path + ".shx", output_file_path + ".shx")
#createVector('/home/rccc/_CORESYF/coresyf_toolkit/examples/VectorCreator/myshape.shp', '/home/rccc/_CORESYF/coresyf_toolkit/examples/VectorCreator/data_to_create.txt')
def editVector(file_path, data_file, format_name='ESRI Shapefile' ):
print "PASSEI AQUI"
# set up the shapefile driver
driver = ogr.GetDriverByName( format_name )
# Open the data source
inDataSource = driver.Open(file_path, 1) # 0 means read-only. 1 means writable.
# Get layer
inLayer = inDataSource.GetLayer()
# Read data from data file
data = csv.DictReader(open(data_file,"rb"), delimiter='\t', quoting=csv.QUOTE_NONE)
# Add a new fields
for field in data.fieldnames:
new_field = ogr.FieldDefn(field, ogr.OFTReal)
inLayer.CreateField(new_field)
new_field = None
# Add features and attributes to the shapefile
inFeature = inLayer.GetNextFeature()
for row in data:
for field in data.fieldnames:
inFeature.SetField(field, row[field])
inLayer.SetFeature(inFeature)
inFeature = inLayer.GetNextFeature()
if not inFeature: break
#editVector('/home/rccc/_CORESYF/coresyf_toolkit/examples/VectorCreator/myshape.shp', '/home/rccc/_CORESYF/coresyf_toolkit/examples/VectorCreator/data_to_edit.txt')
def main():
parser = OptionParser(usage = USAGE,
version = VERSION)
#==============================#
# Define command line options #
#==============================#
parser.add_option('-r',
dest="input_file", metavar=' ',
help="input file for editing (GDAL supported vector file)"
"use this option to update an existing vector file" , )
parser.add_option('-o',
dest="output_file", metavar=' ',
help=("output vector file to be created (default: 'output_vector.shp')"
"use this option to create a new vector file"),
default="output_vector.shp")
parser.add_option('--o_format',
dest="output_format", metavar=' ',
help= ("GDAL vector format for output file, some possible formats are"
" 'ESRI Shapefile', 'netCDF' (default: 'ESRI Shapefile')"),
default="ESRI Shapefile" )
parser.add_option('--data_file',
dest="data_file", metavar=' ',
help= ("Delimited text file with data fields separated by tab character"),
)
#==============================#
# Check mandatory options #
#==============================#
(opts, args) = parser.parse_args()
if len(sys.argv) == 1:
print(USAGE)
return
if not opts.input_file and not opts.output_file:
print("No vector file provided for editing or output file to be created. Nothing to do!")
print(USAGE)
return
if not opts.data_file:
print("No data file provided containing the field values. Nothing to do!")
print(USAGE)
return
if opts.input_file and not os.path.exists(opts.input_file):
print("The vector file %s was not found. No vector file available for editing!" % opts.input_file)
return
#==========#
# Run #
#==========#
try:
if opts.input_file:
print ("\nUpdating vector file using data from %s ..." % opts.data_file)
editVector(opts.input_file, opts.data_file)
else:
print ("\nCreating a new vector file using data from %s ..." % opts.data_file)
createVector(opts.output_file, opts.data_file, opts.output_format)
print ('...Done!')
except Exception as message:
print( str(message) )
print('Error: Unable to create or edit vector file.')
sys.exit(-1)
if __name__ == '__main__':
main()