-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector_tools.py
504 lines (394 loc) · 18.4 KB
/
vector_tools.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
"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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-------------------------------------------------------------------------------
"""
import os
import click
import fiona
import fiona.crs
from shapely.geometry import shape, box
from shapely.ops import unary_union, nearest_points
from rtree import index
from shapely.geometry import LineString, MultiLineString, mapping, Point, MultiPoint
import numpy as np
def ExtractBylocation(input_file, mask_file, output_file, method):
selected_features = []
# Create spatial index for input layer
input_index = index.Index()
with fiona.open(input_file, 'r') as input_layer:
for idx, input_feature in input_layer.items():
in_feat = shape(input_feature['geometry'])
input_index.insert(idx, in_feat.bounds)
# Create spatial index for mask layer
mask_index = index.Index()
with fiona.open(mask_file, 'r') as mask_layer:
for idx, mask_feature in mask_layer.items():
mask_feat = shape(mask_feature['geometry'])
mask_index.insert(idx, mask_feat.bounds)
with fiona.open(mask_file, 'r') as mask_layer, fiona.open(input_file, 'r') as input_layer:
options = dict(
driver=input_layer.driver,
schema=input_layer.schema.copy(),
crs=input_layer.crs)
for mask_feature in mask_layer:
# print(polygon_feature)
mask = shape(mask_feature['geometry'])
# Get potential linestrings within the bounding box of the polygon
potential_input = list(input_index.intersection(mask.bounds))
for input_id in potential_input:
input_feature = input_layer[input_id]
# print(linestring_feature)
input = shape(input_feature['geometry'])
if method == 'intersects':
if mask.intersects(input):
selected_features.append(input_feature)
if method == 'contains':
if mask.contains(input):
selected_features.append(input_feature)
# Create a new GeoPackage file and write the selected features to it
with fiona.open(output_file, 'w', **options) as output_layer:
for feature in selected_features:
output_layer.write(feature)
def StrahlerOrder(hydro_network, output_network, overwrite=True):
"""
Calculate Strahler stream order
Parameters:
- params (object): An object containing the parameters.
- hydro_network (str): The filename of the hydro network.
- hydrography_strahler (str): The filename for hydro network with Strahler order.
- overwrite (bool): Optional. Specifies whether to overwrite existing tiled buffer files. Default is True.
- source code from https://here.isnew.info/strahler-stream-order-in-python.html
Returns:
- None
"""
click.secho('Compute Strahler order', fg='yellow')
# file path definition
# hydro_network = params.hydro_network.filename(tileset=tileset)
# hydrography_strahler = params.hydrography_strahler.filename(tileset=tileset)
# check overwrite
if os.path.exists(output_network) and not overwrite:
click.secho('Output already exists: %s' % output_network, fg='yellow')
return
# function to find head line in network (top upstream)
def find_head_lines(lines):
head_idx = []
num_lines = len(lines)
for i in range(num_lines):
line = lines[i]
first_point = line[0]
has_upstream = False
for j in range(num_lines):
if j == i:
continue
line = lines[j]
last_point = line[len(line)-1]
if first_point == last_point:
has_upstream = True
if not has_upstream:
head_idx.append(i)
return head_idx
# function to find next line downstream
def find_next_line(curr_idx, lines):
num_lines = len(lines)
line = lines[curr_idx]
last_point = line[len(line)-1]
next_idx = None
for i in range(num_lines):
if i == curr_idx:
continue
line = lines[i]
first_point = line[0]
if last_point == first_point:
next_idx = i
break
return next_idx
# function to find sibling line (confluence line)
def find_sibling_line(curr_idx, lines):
num_lines = len(lines)
line = lines[curr_idx]
last_point = line[len(line)-1]
sibling_idx = None
for i in range(num_lines):
if i == curr_idx:
continue
line = lines[i]
last_point2 = line[len(line)-1]
if last_point == last_point2:
sibling_idx = i
break
return sibling_idx
# read reference network
with fiona.open(hydro_network, 'r') as source:
schema = source.schema.copy()
driver=source.driver
crs=source.crs
# define new fields
strahler_field_name = "strahler"
strahler_field_type = 'int'
# Add the new field to the schema
schema['properties'][strahler_field_name] = strahler_field_type
lines = []
source_copy = []
# copy feature with strahler field in source_copy and the the line coordinates in lines
for feature in source:
# Create a new feature with the new field
new_properties = feature['properties']
new_properties[strahler_field_name] = 0 # Set the strahler field value to 0
geom = shape(feature['geometry'])
# copy line coordinates to find head line
line = geom.coords
lines.append(line)
# copy features in new list to update the data before write all
source_copy.append(feature)
# save head lines index
head_idx = find_head_lines(lines)
with click.progressbar(head_idx) as processing:
for idx in processing:
curr_idx = idx
curr_ord = 1
# head lines order = 1
source_copy[curr_idx]['properties'][strahler_field_name] = curr_ord
# go downstream from each head lines
while True:
# find next line downstream
next_idx = find_next_line(curr_idx, lines)
# stop iteration if no next line
if next_idx is None:
break
# copy next line feature and order
next_feat = source_copy[next_idx]
next_ord = next_feat['properties'][strahler_field_name]
# find sibling line
sibl_idx = find_sibling_line(curr_idx, lines)
# if confluence
if sibl_idx is not None:
sibl_feat = source_copy[sibl_idx]
sibl_ord = sibl_feat['properties'][strahler_field_name]
# check if confluence, and if same strahler order add +1 to order
if sibl_ord > curr_ord:
break
elif sibl_ord < curr_ord:
if next_ord == curr_ord:
break
else:
curr_ord += 1
# update order in next feature
source_copy[next_idx]['properties'][strahler_field_name] = curr_ord
# go further downstream
curr_idx = next_idx
# write final features from updated features copy
with fiona.open(output_network, 'w', driver=driver, crs=crs, schema=schema) as modif:
for feature in source_copy:
if feature['properties'][strahler_field_name] > 0:
modified_feature = {
'type': 'Feature',
'properties': feature['properties'],
'geometry': feature['geometry'],
}
modif.write(modified_feature)
def CreateSources(hydro_network, output_sources, overwrite=True):
"""
Create stream sources from reference hydrologic network :
Parameters:
- params (object): An object containing the parameters for buffering.
- hydrography_strahler_fieldbuf (str): The filename for hydro network pepared.
- sources (str) : stream sources filename path output.
- overwrite (bool): Optional. Specifies whether to overwrite existing tiled buffer files. Default is True.
Returns:
- None
"""
click.secho('Create stream sources from hydrologic network', fg='yellow')
# paths to files
# hydrography_strahler_fieldbuf = params.hydrography_strahler_fieldbuf.filename(tileset=None)
# sources = params.sources.filename(tileset=None)
# check overwrite
if os.path.exists(output_sources) and not overwrite:
click.secho('Output already exists: %s' % output_sources, fg='yellow')
return
with fiona.open(hydro_network, 'r') as hydro:
# Create output schema
schema = hydro.schema.copy()
schema['geometry'] = 'Point'
options = dict(
driver=hydro.driver,
schema=schema,
crs=hydro.crs)
with fiona.open(output_sources, 'w', **options) as output:
with click.progressbar(hydro) as processing:
# extract network line with strahler = 1 and create point with first line point coordinates
for feature in processing:
if feature['properties']['STRAHLER'] == 1:
properties = feature['properties']
geom = shape(feature['geometry'])
head_point = Point(geom.coords[0][:2])
output.write({
'geometry': mapping(head_point),
'properties': properties,
})
def IdentifyNetworkNodes(network, network_nodes, network_identified, crs):
"""
Identifies network nodes by finding the endpoints of lines in a given network dataset and
quantizing their coordinates. The nodes are output as a separate dataset and their
attributes are added to the input network dataset.
Parameters
----------
params : Parameters
Input parameters.
tileset : str, optional
The tileset to use for the input and output datasets. Default is 'default'.
Returns
-------
None
Raises
------
None
"""
# Step 1
click.secho('Get lines endpoints', fg='yellow')
coordinates = list()
def extract_coordinates(polyline):
""" Extract endpoints coordinates
"""
a = polyline['coordinates'][0]
b = polyline['coordinates'][-1]
coordinates.append(tuple(a))
coordinates.append(tuple(b))
with fiona.open(network) as fs:
with click.progressbar(fs) as processing:
for feature in processing:
extract_coordinates(feature['geometry'])
# Step 2
click.secho('Quantize coordinates', fg='yellow')
coordinates = np.array(coordinates)
minx = np.min(coordinates[:, 0])
miny = np.min(coordinates[:, 1])
maxx = np.max(coordinates[:, 0])
maxy = np.max(coordinates[:, 1])
quantization = 1e8
kx = (minx == maxx) and 1 or (maxx - minx)
ky = (miny == maxy) and 1 or (maxy - miny)
sx = kx / quantization
sy = ky / quantization
coordinates = np.int32(np.round((coordinates - (minx, miny)) / (sx, sy)))
# Step 3
click.secho('Build endpoints index', fg='yellow')
driver = 'GPKG'
schema = {
'geometry': 'Point',
'properties': [
('GID', 'int')
]
}
crs = fiona.crs.CRS.from_epsg(crs)
options = dict(driver=driver, crs=crs, schema=schema)
with fiona.open(network_nodes, 'w', **options) as dst:
coordinates_map = dict()
gid = 0
point_index = dict()
with click.progressbar(enumerate(coordinates), length=len(coordinates)) as processing:
for i, coordinate in processing:
c = tuple(coordinate)
if c not in coordinates_map:
coordinates_map[c] = i
node_coords = (c[0]*sx + minx, c[1]*sy + miny)
point_index[gid] = Point(node_coords[0], node_coords[1])
dst.write({
'type': 'Feature',
'geometry': {'type': 'Point', 'coordinates': node_coords},
'properties': {'GID': gid}
})
gid = gid + 1
del coordinates
del coordinates_map
# Step 4
click.secho('Output lines with nodes attributes', fg='yellow')
nodes_list = MultiPoint(list(point_index.values()))
def nearest(point):
""" Return the nearest point in the point index
"""
nearest_node = nearest_points(point, nodes_list)[1]
for candidate in point_index:
if point_index[candidate].equals(nearest_node):
return candidate
return None
schema = fs.schema
schema['properties']['NODEA'] = 'int:10'
schema['properties']['NODEB'] = 'int:10'
options = dict(driver=driver, crs=crs, schema=schema)
with fiona.open(network_identified, 'w', **options) as dst:
with click.progressbar(fs) as processing:
for feature in processing:
output_feature = feature
a = Point(output_feature['geometry']['coordinates'][0])
b = Point(output_feature['geometry']['coordinates'][-1])
output_feature['properties']['NODEA'] = nearest(a)
output_feature['properties']['NODEB'] = nearest(b)
dst.write(output_feature)
def prepare_network_attribut(network_file, output_file, crs):
"""
Prepare network attributes and create a new output file with additional fields.
Parameters:
- network_file (str): Path to the input network file.
- output_file (str): Path to the output file where the modified network will be saved.
- crs (dict): Coordinate Reference System information to be used for the output file.
Returns:
None
Opens the specified network file, adds new fields (CDENTITEHY, AXIS, TOPONYME) to the schema,
and creates a new output file with the modified schema and additional fields.
The new fields are populated based on existing properties in the input network file.
Raises:
IOError: If there is an issue opening or processing the network file.
ValueError: If there is an issue with the provided Coordinate Reference System.
"""
fields_to_remove = ['date_creation', 'date_modification', 'date_d_apparition', 'date_de_confirmation']
# open network file
with fiona.open(network_file) as source:
schema = {
'geometry': source.schema['geometry'],
'properties': {k: v for k, v in source.schema['properties'].items() if k not in fields_to_remove}
}
driver=source.driver
crs=source.crs
# define the new fields
cdentitehy_field_name = "CDENTITEHY"
cdentitehy_field_type = 'str'
axis_field_name = "AXIS"
axis_field_type = 'int'
toponyme_field_name = "TOPONYME"
toponyme_field_type = 'str'
# Add the new fields to the schema
schema['properties'][cdentitehy_field_name] = cdentitehy_field_type
schema['properties'][axis_field_name] = axis_field_type
schema['properties'][toponyme_field_name] = toponyme_field_type
# open output file in write mode
with fiona.open(output_file, 'w', driver=driver, crs=crs, schema=schema) as output:
# create progressbar during processing
with click.progressbar(source) as processing:
for feature in processing:
properties = {k: v for k, v in feature['properties'].items() if k not in fields_to_remove}
# update features new fields
properties[cdentitehy_field_name] = properties['code_du_cours_d_eau_bdcarthage']
liens_vers_cours_d_eau = properties['liens_vers_cours_d_eau']
properties[axis_field_name] = int(liens_vers_cours_d_eau[8:])
properties[toponyme_field_name] = properties['cpx_toponyme_de_cours_d_eau']
# create the feature to copy in output file
new_feature = {
'type': 'Feature',
'properties': properties,
'geometry': feature['geometry'],
}
# write feature in output file
output.write(new_feature)
print(cdentitehy_field_name + ', ' + axis_field_name + ' and ' + toponyme_field_name + ' fields adds and populate to ' + output_file)