-
Notifications
You must be signed in to change notification settings - Fork 0
/
rural_profile_sorter.py
374 lines (307 loc) · 12.9 KB
/
rural_profile_sorter.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
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.txt
# -*- coding: utf-8 -*-
import logging
import sys
import os
import traceback
import tempfile
from turtlebase.logutils import LoggingConfig
from turtlebase import mainutils
import nens.gp
import nens.geom
import turtlebase.arcgis
log = logging.getLogger(__name__)
def get_line_parts(gp, line_fc, line_ident):
"""reads all the lines in the line_fc and return a dict with all line parts
"""
lineparts = {}
line_desc = gp.describe(line_fc)
row = gp.SearchCursor(line_fc)
for item in nens.gp.gp_iterator(row):
feat = item.GetValue(line_desc.ShapeFieldName)
item_id = item.GetValue(line_ident)
part = feat.getpart(0)
pnt_list = [(round(pnt.x, 5), round(pnt.y, 5)) for pnt in
nens.gp.gp_iterator(part)]
lineparts[item_id] = pnt_list
return lineparts
def get_pointcloud(gp, point_fc, point_ident, zcoord):
"""
reads all the points in the pointcloud and return a
dict with all points that match point_id
"""
pointcloud = {}
point_desc = gp.describe(point_fc)
row = gp.SearchCursor(point_fc)
for item in nens.gp.gp_iterator(row):
feat = item.GetValue(point_desc.ShapeFieldName)
item_id = item.GetValue(point_ident)
point_x, point_y = calculate_xy(gp, feat)
pnt_xyz = (point_x,
point_y,
float(item.GetValue(zcoord)))
if item_id not in pointcloud:
pointcloud[item_id] = [pnt_xyz]
else:
pointcloud[item_id].append(pnt_xyz)
return pointcloud
def calculate_xy(gp, point):
"""calculates coordinates from a point
in ArcGIS 9.3 and 10.0 the coordinates are stored as a string ("x y"
in ArcGIS 10.1
"""
installinfo = gp.GetInstallInfo("desktop")
if str(installinfo["Version"]) == "10.1":
x_coord = point.Centroid.X
y_coord = point.Centroid.Y
else:
x_coord = float(point.Centroid.split(" ")[0])
y_coord = float(point.Centroid.split(" ")[1])
return x_coord, y_coord
def create_centroids(gp, multipoints, output_fc, mp_ident):
"""creates a centerpoint fc out of a multipoint fc
"""
gp.AddXY_management(multipoints)
mpoint_desc = gp.describe(multipoints)
center_points = {}
row = gp.SearchCursor(multipoints)
for item in nens.gp.gp_iterator(row):
feat = item.GetValue(mpoint_desc.ShapeFieldName)
item_id = item.GetValue(mp_ident)
xcoord, ycoord = calculate_xy(gp, feat)
center_points[item_id] = {"xcoord": xcoord, "ycoord": ycoord}
workspace = os.path.dirname(output_fc)
fc_name = os.path.basename(output_fc)
gp.CreateFeatureClass_management(workspace, fc_name, "Point",
"#", "DISABLED", "DISABLED", "#")
gp.addfield(output_fc, 'proident', "TEXT")
gp.addfield(output_fc, 'xcoord', "DOUBLE")
gp.addfield(output_fc, 'ycoord', "DOUBLE")
rows = gp.InsertCursor(output_fc)
point = gp.CreateObject("Point")
for point_id, attributes in center_points.items():
row = rows.NewRow()
point.x = attributes['xcoord']
point.y = attributes['ycoord']
row.shape = point
row.SetValue('proident', point_id)
row.SetValue('xcoord', point.x)
row.SetValue('ycoord', point.y)
rows.InsertRow(row)
del rows
del row
def sort_pointcloud(gp, centerpoints_d, lineparts, pointcloud):
profiles_xyz = {}
profiles_yz = []
for centerpoint_id, attributes in centerpoints_d.items():
log.info(" - cross section: %s" % centerpoint_id)
if 'ovkident' in attributes:
ls = lineparts[attributes['ovkident']]
if 'target_lvl' in attributes:
targetlevel = attributes['target_lvl']
else:
targetlevel = -999
if 'water_lvl' in attributes:
waterlevel = attributes['water_lvl']
else:
waterlevel = -999
log.debug("ls: %s" % ls)
pc = pointcloud[centerpoint_id]
try:
sorted_points = nens.geom.sort_perpendicular_to_segment(ls, pc)
except:
log.warning("No intersection found, profile %s skipped",
centerpoint_id)
continue
profiles_xyz[centerpoint_id] = sorted_points
sum_x = 0
sum_y = 0
cnt_x = 0
cnt_y = 0
for coords in sorted_points:
sum_x += float(coords[0])
cnt_x += 1
sum_y += float(coords[1])
cnt_y += 1
avg_x = sum_x / cnt_x
avg_y = sum_y / cnt_y
abscissas = zip(nens.geom.abscissa_from_midsegment(sorted_points), sorted_points)
log.debug("abscissas %s" % abscissas)
for index, x in enumerate(abscissas):
profiles_yz.append({"proident": centerpoint_id,
"dist_mid": x[0], "bed_lvl": x[1][2],
"p_order": index + 1,
"target_lvl": targetlevel,
"water_lvl": waterlevel,
"xcoord": avg_x,
"ycoord": avg_y,
})
else:
continue
return profiles_xyz, profiles_yz
def write_profiles_xyz(gp, profiles_xyz, output_xyz):
"""
"""
workspace = os.path.dirname(output_xyz)
fc_name = os.path.basename(output_xyz)
gp.CreateFeatureClass_management(workspace, fc_name, "Point",
"#", "DISABLED", "DISABLED", "#")
gp.addfield(output_xyz, 'proident', "TEXT")
gp.addfield(output_xyz, 'xcoord', "DOUBLE")
gp.addfield(output_xyz, 'ycoord', "DOUBLE")
gp.addfield(output_xyz, 'zcoord', "DOUBLE")
gp.addfield(output_xyz, 'p_order', "SHORT")
rows = gp.InsertCursor(output_xyz)
point = gp.CreateObject("Point")
for point_id, attributes in profiles_xyz.items():
for index, point_xy in enumerate(attributes):
row = rows.NewRow()
point.x = point_xy[0]
point.y = point_xy[1]
row.shape = point
row.SetValue('proident', point_id)
row.SetValue('xcoord', point.x)
row.SetValue('ycoord', point.y)
row.SetValue('zcoord', point_xy[2])
row.SetValue('p_order', index + 1)
rows.InsertRow(row)
del rows
del row
def write_profiles_yz(gp, profiles_yz, output_yz):
"""
"""
workspace = os.path.dirname(output_yz)
table_name = os.path.basename(output_yz)
gp.CreateTable_management(workspace, table_name)
gp.addfield(output_yz, 'proident', "TEXT")
gp.addfield(output_yz, 'dist_mid', "DOUBLE")
gp.addfield(output_yz, 'bed_lvl', "DOUBLE")
gp.addfield(output_yz, 'p_order', "SHORT")
gp.addfield(output_yz, 'target_lvl', "DOUBLE")
gp.addfield(output_yz, 'water_lvl', "DOUBLE")
gp.addfield(output_yz, 'xcoord', "DOUBLE")
gp.addfield(output_yz, 'ycoord', "DOUBLE")
rows = gp.InsertCursor(output_yz)
for attributes in profiles_yz:
row = rows.NewRow()
row.SetValue('proident', attributes['proident'])
row.SetValue('dist_mid', float(attributes['dist_mid']))
row.SetValue('bed_lvl', float(attributes['bed_lvl']))
row.SetValue('p_order', int(attributes['p_order']))
row.SetValue('target_lvl', float(attributes['target_lvl']))
row.SetValue('water_lvl', float(attributes['water_lvl']))
row.SetValue('xcoord', float(attributes['xcoord']))
row.SetValue('ycoord', float(attributes['ycoord']))
rows.InsertRow(row)
del rows
del row
def main():
try:
gp = mainutils.create_geoprocessor()
config = mainutils.read_config(__file__, 'turtle-settings.ini')
logfile = mainutils.log_filename(config)
logging_config = LoggingConfig(gp, logfile=logfile)
mainutils.log_header(__name__)
#---------------------------------------------------------------------
# Create workspace
workspace = config.get('GENERAL', 'location_temp')
if workspace == "-":
workspace = tempfile.gettempdir()
turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)
if not os.path.isdir(workspace):
os.makedirs(workspace)
workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
gp, workspace)
if errorcode == 1:
log.error("failed to create a file geodatabase in %s" % workspace)
#---------------------------------------------------------------------
# Input parameters
"""
nodig voor deze tool:
"""
if len(sys.argv) == 6:
log.info("Reading input parameters")
mpoint = sys.argv[1]
hydroline = sys.argv[2]
output_xyz = sys.argv[3]
output_yz = sys.argv[4]
output_locations = sys.argv[5]
else:
log.warning("usage: <hydroline> <mpoint> <output_xyz> <output_yz>")
sys.exit(1)
#---------------------------------------------------------------------
# Check geometry input parameters
log.info("Check geometry of input parameters")
geometry_check_list = []
#log.debug(" - check <input >: %s" % argument1)
#"<check geometry from input data, append to list if incorrect>"
if len(geometry_check_list) > 0:
log.error("check input: %s" % geometry_check_list)
sys.exit(2)
#---------------------------------------------------------------------
ovkident = 'ovkident'
proident = 'proident'
zcoord = 'ZH'
# Check required fields in input data
log.info("Check required fields in input data")
missing_fields = []
#<check required fields from input data,
# append them to list if missing>
check_fields = {hydroline: [ovkident],
mpoint: [proident, zcoord]}
#check_fields = {input_1: [fieldname1, fieldname2],
# input_2: [fieldname1, fieldname2]}
for input_fc, fieldnames in check_fields.items():
for fieldname in fieldnames:
if not turtlebase.arcgis.is_fieldname(
gp, input_fc, fieldname):
errormsg = "fieldname %s not available in %s" % (
fieldname, input_fc)
log.error(errormsg)
missing_fields.append(errormsg)
if len(missing_fields) > 0:
log.error("missing fields in input data: %s" % missing_fields)
sys.exit(2)
#---------------------------------------------------------------------
multipoints = turtlebase.arcgis.get_random_file_name(workspace, ".shp")
log.info("Dissolving pointcloud to multipoint")
gp.Dissolve_management(mpoint, multipoints, proident)
if output_locations == '#':
output_locations = (
turtlebase.arcgis.get_random_file_name(workspace_gdb))
log.info("Calculating coordinates of centerpoints")
create_centroids(gp, multipoints, output_locations, proident)
centerpoints_sj = turtlebase.arcgis.get_random_file_name(workspace, ".shp")
log.info("Calculation adjacent hydrolines")
gp.SpatialJoin_analysis(output_locations, hydroline, centerpoints_sj,
'JOIN_ONE_TO_ONE', "#", "#", "CLOSEST", 100)
log.info("Reading center points")
centerpoints_d = nens.gp.get_table(gp, centerpoints_sj,
primary_key=proident)
log.info("Reading hydrolines")
lineparts = get_line_parts(gp, hydroline, ovkident)
log.info("Reading pointcloud")
pointcloud = get_pointcloud(gp, mpoint, proident, zcoord)
log.info("Sorting profiles")
profiles_xyz, profiles_yz = sort_pointcloud(gp, centerpoints_d,
lineparts, pointcloud)
log.info("Write xyz points to output")
write_profiles_xyz(gp, profiles_xyz, output_xyz)
log.info("Write yz information to output table")
write_profiles_yz(gp, profiles_yz, output_yz)
#---------------------------------------------------------------------
# Delete temporary workspace geodatabase & ascii files
try:
log.debug("delete temporary workspace: %s" % workspace_gdb)
gp.delete(multipoints)
gp.delete(centerpoints_sj)
log.info("workspace deleted")
except:
log.warning("failed to delete %s" % workspace_gdb)
mainutils.log_footer()
except:
log.error(traceback.format_exc())
sys.exit(1)
finally:
logging_config.cleanup()
del gp