forked from lmotta/scripts-for-gis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
union_neighbour.py
371 lines (318 loc) · 12.4 KB
/
union_neighbour.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Union neighbour
Description : Union neighbour polygon
Arguments : Shapefiles
-------------------
begin : 2015-12-14
copyright : (C) 2015 by Luiz Motta
email : motta dot luiz at gmail.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
#ogr2ogr -overwrite example01_neighbour.shp example01_neighbour.geojson
import os, sys
import argparse
import datetime
try:
from osgeo import ogr
from osgeo import osr
except ImportError:
import ogr
import osr
def run(name_file, year, quiet_status):
def printStatus(status, newLine=False):
if not newLine and quiet_status:
return
if newLine:
ch = "\n"
else:
ch = ""
sys.stdout.write( "\r%s" % ( status.ljust(100) + ch ) )
sys.stdout.flush()
def getLayer(name_file):
inDataSource = driver.Open( name_file, 0 )
#
if inDataSource is None:
printStatus( "File '%s' can't open" % name_file, True )
return None
#
inLayer = inDataSource.GetLayer()
#
return ( inDataSource, inLayer)
def getFeatures(layer):
feats = []
feat = layer.GetNextFeature()
while feat:
geomf = feat.GetGeometryRef()
feats.append( { 'attributes': feat.items(), 'geom': geomf.Clone(), 'fid': feat.GetFID() } )
feat.Destroy()
feat = layer.GetNextFeature()
layer.ResetReading()
return feats
def createOutLayer(spatialRef, suffix, fields, geomType):
( path_file, ext ) = os.path.splitext( name_file )
outFile = "%s_%s%s" % ( path_file, suffix, ext )
#
if os.path.exists( outFile ):
driver.DeleteDataSource( outFile )
#
outDataSource = driver.CreateDataSource( outFile )
#
if outDataSource is None:
printStatus( "File '%s' not be created" % outFile, True )
return None
#
outLayer = outDataSource.CreateLayer( outFile, srs=spatialRef, geom_type=geomType )
#
if outLayer is None:
printStatus( "File '%s' not be created" % outFile, True )
return None
#
for item in fields:
f = ogr.FieldDefn( item['name'], item['type'] )
if item.has_key( 'width' ):
f.SetWidth( item[ 'width' ] )
outLayer.CreateField( f )
#
return ( outFile, outDataSource, outLayer )
def addFeaturesOut(f, fid, defnOut):
feat = ogr.Feature( defnOut )
feat.SetGeometry( f['geom'] )
feat.SetFID( f['fid'] )
for item in f['attributes']:
feat.SetField( item[ 'name' ], item[ 'value' ])
outLayer.CreateFeature( feat )
feat.Destroy()
def getCoordTransform7390( layer ):
wkt7390 = 'PROJCS["Brazil / Albers Equal Area Conic (WGS84)",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["longitude_of_center",-50.0],PARAMETER["standard_parallel_1",10.0],PARAMETER["standard_parallel_2",-40.0],PARAMETER["latitude_of_center",-25.0],UNIT["Meter",1.0]]'
sr7390 = osr.SpatialReference()
sr7390.ImportFromWkt( wkt7390 )
return osr.CreateCoordinateTransformation( layer.GetSpatialRef(), sr7390 )
def processNeighbour(inFeats, layer, year, ct):
def getFeaturesTouchSpatialFilter(layer, geom, fid=None):
layer.SetSpatialFilter( geom )
feats = []
feat = layer.GetNextFeature()
while feat:
if fid is None or feat.GetFID() != fid:
geomf = feat.GetGeometryRef()
if geomf.Touches( geom ):
feats.append( { 'attributes': feat.items(), 'geom': geomf.Clone(), 'fid': feat.GetFID() } )
feat.Destroy()
feat = layer.GetNextFeature()
layer.ResetReading()
return feats
def removeFeaturesInNotTouch(inFeats):
total = len( inFeats )
removed = 0
for item in inFeats:
feats = getFeaturesTouchSpatialFilter( layer, item['geom'], item['fid'] )
if len( feats ) == 0:
item['geom'].Destroy()
item['geom'] = None
removed += 1
printStatus( "Removing features that hasn't neighbors (%d / %d)..." % ( removed, total ) )
return filter( lambda x: not x['geom'] is None, inFeats )
def createOutFeatures(inFeats, ct):
def getValueEvent(inFeat):
day = inFeat['attributes']['day_of_year']
geom = inFeat['geom'].Clone()
geom.Transform( ct )
area = geom.Area() / 10000.0
geom.Destroy()
return {'day_of_year': day, 'area_ha': area }
def getInitValues(inFeat, id_group):
outFeat = {}
outFeat['id_group'] = id_group
outFeat['geom'] = inFeat['geom'].Clone()
outFeat['events'] = [ getValueEvent( inFeat ) ]
return outFeat
def addValues(outFeat, inFeat):
geomUnion = outFeat['geom'].Union( inFeat['geom'])
outFeat['geom'].Destroy()
outFeat['geom'] = geomUnion
outFeat['events'].append( getValueEvent( inFeat ) )
def destroyGeommetries(fids, inFeats):
total = len( fids )
i = 0
for item in inFeats:
if item['fid'] in fids:
i += 0
item['geom'].Destroy()
item['geom'] = None
if i == total:
break
def getSumSameDays( events ):
new_events = []
days = map( lambda x: x['day_of_year'], events )
days = list( set( days ) )
for item1 in days:
f_days = filter( lambda x: x['day_of_year'] == item1, events )
if len( f_days ) == 1:
total_area_ha = f_days[0]['area_ha']
else:
total_area_ha = 0
for item2 in f_days:
total_area_ha += item2['area_ha']
event = { 'day_of_year': item1, 'area_ha': total_area_ha }
new_events.append( event )
return new_events
printStatus( "Creating polygon with neighbors..." )
total = len( inFeats )
outFeats = []
id_group = 0
loop = True
while loop:
loop = False
for item in inFeats:
feats = getFeaturesTouchSpatialFilter( layer, item['geom'], item['fid'] ) # Always has feats!
# Add from Query inFeats
id_group += 1
outFeat = getInitValues( item, id_group )
# FID's for remove inFeats
fids = [ item['fid'] ] + map( lambda x: x['fid'], feats )
for item2 in feats:
addValues( outFeat, item2 )
# Add from Query by outFeat
while True:
feats = getFeaturesTouchSpatialFilter( layer, outFeat['geom'] )
if len( feats ) == 0:
break
fids += map( lambda x: x['fid'], feats )
for item2 in feats:
addValues( outFeat, item2 )
#
outFeats.append( outFeat )
destroyGeommetries( fids, inFeats )
inFeats = filter( lambda x: not x['geom'] is None, inFeats )
current = len( inFeats )
if current > 0:
loop = True
data = ( id_group, total - current, total )
printStatus( "%d groups (%d of %d features)..." % data )
break # NEWs values of inFeats!
# Remove duplicate day_of_year in events, if has only one day remove item
hasDestroy = False
for item in outFeats:
events = getSumSameDays( item['events'])
del item['events']
if len( events ) == 1:
hasDestroy = True
item['geom'].Destroy()
item['geom'] = None
else:
item['events'] = events
if hasDestroy:
outFeats = filter( lambda x: not x['geom'] is None, outFeats )
return ( outFeats, inFeats )
inFeats = removeFeaturesInNotTouch( inFeats )
return createOutFeatures( inFeats, ct )
def getSumEvents(outFeat):
def getDate( day ):
s_jd = "%.04d%.03d" % ( year, day)
return datetime.datetime.strptime( s_jd, '%Y%j' ).strftime("%Y-%m-%d")
events = sorted( outFeat['events'], key=lambda x: x['day_of_year'] )
num_events = len( events )
day = events[0]['day_of_year']
date_ini = getDate( day )
date_end = getDate( events[num_events - 1]['day_of_year'] )
area_ini_ha = events[0]['area_ha']
#
days_events = "%03d" % day
area_end_ha = area_ini_ha
area_events_ha = "%f" % area_ini_ha
for item in events[1:]:
days_events = "%s;%03d" % ( days_events, item['day_of_year'] )
area_end_ha += item['area_ha']
area_events_ha = "%s;%f" % ( area_events_ha, item['area_ha'] )
#
return {
'num_events': num_events,
'date_ini': date_ini,
'date_end': date_end,
'area_ini_ha': area_ini_ha,
'area_end_ha': area_end_ha,
'days_events': days_events,
'area_events_ha': area_events_ha
}
ogr.RegisterAll()
driver = ogr.GetDriverByName( "GeoJSON" )
if not os.path.exists( name_file ):
printStatus( "File '%s' not exist" % name_file, True )
return 1
# Input
data = getLayer( name_file )
if data is None:
return 1
( inDataSource, inLayer ) = data
printStatus( "Reading features..." )
inFeats = getFeatures( inLayer )
# Output
fields = [
{ 'name': 'id_group', 'type': ogr.OFTInteger },
{ 'name': 'num_events', 'type': ogr.OFTInteger },
{ 'name': 'date_ini', 'type': ogr.OFTString, 'width': 10 },
{ 'name': 'date_end', 'type': ogr.OFTString, 'width': 10 },
{ 'name': 'area_ini_ha', 'type': ogr.OFTReal },
{ 'name': 'area_end_ha', 'type': ogr.OFTReal },
{ 'name': 'days_events', 'type': ogr.OFTString, 'width': 200 },
{ 'name': 'area_events_ha', 'type': ogr.OFTString, 'width': 200 }
]
data = createOutLayer( inLayer.GetSpatialRef(), 'neighbour', fields, ogr.wkbMultiPolygon )
if data is None:
return 1
( outName, outDataSource, outLayer ) = data
defnOut = outLayer.GetLayerDefn()
# Process
data = ( outName, inLayer.GetFeatureCount() )
printStatus( "Processing '%s' (%d features)" % data, True )
( outFeats, inFeats ) = processNeighbour( inFeats, inLayer, year, getCoordTransform7390( inLayer ) )
totalOutFeats = len( outFeats )
# Clean
for item in inFeats:
item['geom'].Destroy()
del inFeats[:]
# Save Features
fid = 0
for item in outFeats:
fid += 1
sumEvent = getSumEvents( item )
f = { 'fid': fid, 'geom': item['geom'],
'attributes': [
{ 'name': 'id_group', 'value': item['id_group'] },
{ 'name': 'num_events', 'value': sumEvent['num_events'] },
{ 'name': 'date_ini', 'value': sumEvent['date_ini'] },
{ 'name': 'date_end', 'value': sumEvent['date_end'] },
{ 'name': 'area_ini_ha', 'value': sumEvent['area_ini_ha'] },
{ 'name': 'area_end_ha', 'value': sumEvent['area_end_ha'] },
{ 'name': 'days_events', 'value': sumEvent['days_events'] },
{ 'name': 'area_events_ha', 'value': sumEvent['area_events_ha'] }
]
}
addFeaturesOut( f, fid, defnOut )
del f['attributes']
item['geom'].Destroy()
del outFeats[:]
inDataSource.Destroy()
outDataSource.Destroy()
printStatus( "Finish! '%s' (%d features)" % ( outName, totalOutFeats ), True )
return 0
def main():
parser = argparse.ArgumentParser(description='Create union neighbour polygon.' )
parser.add_argument( '-q', '--quiet', action="store_false", help='Hides the processing status' )
parser.add_argument( 'geojson', metavar='GeoJSON', type=str, help='Name of GeoJSON file' )
parser.add_argument( 'year', metavar='Year', type=int, help='Year for julian days' )
args = parser.parse_args()
return run( args.geojson, args.year, not args.quiet )
if __name__ == "__main__":
sys.exit( main() )