-
Notifications
You must be signed in to change notification settings - Fork 0
/
stFunctions.py
473 lines (434 loc) · 18.9 KB
/
stFunctions.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
"""
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import re
from geographiclib.geodesic import Geodesic
from qgis.core import QgsUnitTypes, QgsPointXY, QgsPoint, QgsGeometry, QgsExpression, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsWkbTypes
from qgis.utils import qgsfunction
from .settings import epsg4326, geod, settings
from .compass import Compass
# import traceback
group_name = 'Shape Tools'
def transform_coords(y, x, crs):
coord_crs = QgsCoordinateReferenceSystem(crs)
transform = QgsCoordinateTransform(coord_crs, epsg4326, QgsProject.instance())
pt = transform.transform(x, y)
return(pt.y(), pt.x())
def transform_geom(geom, crs):
coord_crs = QgsCoordinateReferenceSystem(crs)
transform = QgsCoordinateTransform(coord_crs, epsg4326, QgsProject.instance())
geom = transform.transform(geom)
return(geom)
def InitShapeToolsFunctions():
QgsExpression.registerFunction(st_from_meters)
QgsExpression.registerFunction(st_to_meters)
QgsExpression.registerFunction(st_geodesic_distance)
QgsExpression.registerFunction(st_geodesic_bearing)
QgsExpression.registerFunction(st_geodesic_transform)
QgsExpression.registerFunction(st_compass)
def UnloadShapeToolsFunctions():
QgsExpression.unregisterFunction('st_from_meters')
QgsExpression.unregisterFunction('st_to_meters')
QgsExpression.unregisterFunction('st_geodesic_distance')
QgsExpression.unregisterFunction('st_geodesic_bearing')
QgsExpression.unregisterFunction('st_geodesic_transform')
QgsExpression.unregisterFunction('st_compass')
comp = Compass()
def compass(azimuth, res, mode):
if mode == 'trad':
if res == 32: # 32 points
s = comp.traditional(degree=azimuth)
elif res == 16: # 16 points
s = comp.traditional16(degree=azimuth)
elif res == 8: # 8 points
s = comp.traditional08(degree=azimuth)
else: # 4 points
s = comp.traditional04(degree=azimuth)
elif mode == 'full':
if res == 32: # 32 points
s = comp.point(degree=azimuth)
elif res == 16: # 16 points
s = comp.point16(degree=azimuth)
elif res == 8: # 8 points
s = comp.point08(degree=azimuth)
else: # 4 points
s = comp.point04(degree=azimuth)
else:
if res == 32: # 32 points
s = comp.abbr(azimuth)
elif res == 16: # 16 points
s = comp.abbr16(azimuth)
elif res == 8: # 8 points
s = comp.abbr08(azimuth)
else: # 4 points
s = comp.abbr04(azimuth)
return(s)
@qgsfunction(args=2, group=group_name)
def st_from_meters(values, feature, parent):
"""
Convert a length in meters to another unit.
<h4>Syntax</h4>
<p><b>st_from_meters</b>( <i>length</i>, <i>units</i> )</p>
<h4>Arguments</h4>
<ul>
<li><i>length</i> → the length in meters to be converted.</li>
<li><i>units</i> → conversion unit</li>
<ul>
<li><i>'cm'</i> → centimeters</li>
<li><i>'m'</i> → meters</li>
<li><i>'km'</i> → kilometers</li>
<li><i>'in'</i> → inches</li>
<li><i>'ft'</i> → feet</li>
<li><i>'yard'</i> → yards</li>
<li><i>'mi'</i> → miles</li>
<li><i>'nm'</i> → nautical miles</li>
</ul></ul>
<h4>Example usage</h4>
<ul>
<li><b>st_from_meters</b>(1000, 'km') → returns 1</li>
</ul>
"""
try:
len = float(values[0])
unit = values[1]
if unit == 'cm':
return (len * 100)
elif unit == 'm':
return (len)
elif unit == 'km':
return(len * 0.001)
elif unit == 'in':
return (len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceFeet) * 12.0)
elif unit == 'ft':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceFeet))
elif unit == 'yard':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceYards))
elif unit == 'mi':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceMiles))
elif unit == 'nm':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceNauticalMiles))
else:
parent.setEvalErrorString("Error: invalid unit")
return
except Exception:
parent.setEvalErrorString("Error: invalid inputs")
return
@qgsfunction(args=2, group=group_name)
def st_to_meters(values, feature, parent):
"""
Convert a length to meters.
<h4>Syntax</h4>
<p><b>st_to_meters</b>( <i>length</i>, <i>units</i> )</p>
<h4>Arguments</h4>
<ul>
<li><i>length</i> → the length to be converted.</li>
<li><i>units</i> → units of the length</li>
<ul>
<li><i>'cm'</i> → centimeters</li>
<li><i>'m'</i> → meters</li>
<li><i>'km'</i> → kilometers</li>
<li><i>'in'</i> → inches</li>
<li><i>'ft'</i> → feet</li>
<li><i>'yard'</i> → yards</li>
<li><i>'mi'</i> → miles</li>
<li><i>'nm'</i> → nautical miles</li>
</ul></ul>
<h4>Example usage</h4>
<ul>
<li><b>st_to_meters</b>(1, 'km') → returns 1000</li>
</ul>
"""
try:
len = float(values[0])
unit = values[1]
if unit == 'cm':
return (len * 0.01)
elif unit == 'm':
return (len)
elif unit == 'km':
return(len * 1000)
elif unit == 'in':
return (len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceFeet, QgsUnitTypes.DistanceMeters) / 12.0)
elif unit == 'ft':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceFeet, QgsUnitTypes.DistanceMeters))
elif unit == 'yard':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceYards, QgsUnitTypes.DistanceMeters))
elif unit == 'mi':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMiles, QgsUnitTypes.DistanceMeters))
elif unit == 'nm':
return(len * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceNauticalMiles, QgsUnitTypes.DistanceMeters))
else:
parent.setEvalErrorString("Error: invalid unit")
return
except Exception:
parent.setEvalErrorString("Error: invalid inputs")
return
@qgsfunction(-1, group=group_name)
def st_geodesic_distance(values, feature, parent):
"""
Returns the geodesic distance in meters between two y, x (latitude, longitude) coordinates or two geometry points.
<h4>Syntax</h4>
<p><b>st_geodesic_distance</b>( <i>y1, x1, y2, x2[, crs='EPSG:4326']</i> )</p>
<p><b>st_geodesic_distance</b>( <i>geom1, geom2[, crs='EPSG:4326']</i> )</p>
<h4>Arguments</h4>
<p><i>y1</i> → the y or latitude coordinate for the first point.<br />
<i>x1</i> → the x or longitude coordinate for the first point.<br />
<i>y2</i> → the y or latitude coordinate for the second point.<br />
<i>x2</i> → the x or longitude coordinate for the second point.</p>
<p><i>geom1</i> → the first point geometry.<br />
<i>geom2</i> → the second point geometry.</p>
<p><i>crs</i> → optional coordinate reference system of the y, x coordinates. Default value is 'EPSG:4326' if not specified.</p>
<h4>Example usage</h4>
<ul>
<li><b>st_geodesic_distance</b>(40.0124, -105.2713, 39.7407, -104.9880) → 38696.715933</li>
<li><b>st_geodesic_distance</b>(4867744, -11718747, 4828332, -11687210, 'EPSG:3857') → 38697.029390</li>
<li><b>st_geodesic_distance</b>(<b>make_point</b>(-105.2713, 40.0124), <b>make_point</b>(-104.9880, 39.7407)) → 38696.715933</li>
<li><b>st_geodesic_distance</b>(<b>make_point</b>(-11718747, 4867744), <b>make_point</b>(-11687210, 4828332), 'EPSG:3857') → 38697.029390</li>
</ul>
"""
num_args = len(values)
if num_args < 2 or num_args > 5:
parent.setEvalErrorString("Error: invalid number of arguments")
return
try:
if num_args >= 4:
y1 = float(values[0])
x1 = float(values[1])
y2 = float(values[2])
x2 = float(values[3])
if num_args == 5:
crs = values[4]
if crs and crs != 'EPSG:4326':
y1, x1 = transform_coords(y1, x1, crs)
y2, x2 = transform_coords(y2, x2, crs)
else:
geom1 = values[0]
geom2 = values[1]
if geom1.type() != QgsWkbTypes.PointGeometry or geom2.type() != QgsWkbTypes.PointGeometry:
parent.setEvalErrorString("Error: invalid point geometry")
pt1 = geom1.asPoint()
pt2 = geom2.asPoint()
if num_args == 3:
crs = values[2]
pt1 = transform_geom(pt1, crs)
pt2 = transform_geom(pt2, crs)
y1 = pt1.y()
x1 = pt1.x()
y2 = pt2.y()
x2 = pt2.x()
l = geod.Inverse(y1, x1, y2, x2)
return(l['s12'])
except Exception:
parent.setEvalErrorString("Error: invalid parameters")
'''s = traceback.format_exc()
parent.setEvalErrorString(s)'''
return
@qgsfunction(-1, group=group_name)
def st_geodesic_bearing(values, feature, parent):
"""
Returns the geodesic azimuth starting from the first y, x (latitude, longitude) coordinate in the direction of the second coordinate.
<h4>Syntax</h4>
<p><b>st_geodesic_bearing</b>( <i>y1, x1, y2, x2[, crs='EPSG:4326']</i> )</p>
<p><b>st_geodesic_bearing</b>( <i>geom1, geom2[, crs='EPSG:4326']</i> )</p>
<h4>Arguments</h4>
<p><i>y1</i> → the y or latitude coordinate for the first point.<br />
<i>x1</i> → the x or longitude coordinate for the first point.<br />
<i>y2</i> → the y or latitude coordinate for the second point.<br />
<i>x2</i> → the x or longitude coordinate for the second point.</p>
<p><i>geom1</i> → the first point geometry.<br />
<i>geom2</i> → the second point geometry.</p>
<p><i>crs</i> → optional coordinate reference system of the y, x coordinates. Default value is 'EPSG:4326' if not specified.</p>
<h4>Example usage</h4>
<ul>
<li><b>st_geodesic_bearing</b>(40.0124, -105.2713, 39.7407, -104.9880) → 141.131805</li>
<li><b>st_geodesic_bearing</b>(4867744, -11718747, 4828332, -11687210, 'EPSG:3857') → 141.1319</li>
<li><b>st_geodesic_bearing</b>(<b>make_point</b>(-105.2713, 40.0124), <b>make_point</b>(-104.9880, 39.7407)) → 141.131805</li>
<li><b>st_geodesic_bearing</b>(<b>make_point</b>(-11718747, 4867744), <b>make_point</b>(-11687210, 4828332), 'EPSG:3857') → 141.1319</li>
</ul>
"""
num_args = len(values)
if num_args < 2 or num_args > 5:
parent.setEvalErrorString("Error: invalid number of arguments")
return
try:
if num_args >= 4:
y1 = float(values[0])
x1 = float(values[1])
y2 = float(values[2])
x2 = float(values[3])
if num_args == 5:
crs = values[4]
if crs and crs != 'EPSG:4326':
y1, x1 = transform_coords(y1, x1, crs)
y2, x2 = transform_coords(y2, x2, crs)
else:
geom1 = values[0]
geom2 = values[1]
if geom1.type() != QgsWkbTypes.PointGeometry or geom2.type() != QgsWkbTypes.PointGeometry:
parent.setEvalErrorString("Error: invalid point geometry")
pt1 = geom1.asPoint()
pt2 = geom2.asPoint()
if num_args == 3:
crs = values[2]
pt1 = transform_geom(pt1, crs)
pt2 = transform_geom(pt2, crs)
y1 = pt1.y()
x1 = pt1.x()
y2 = pt2.y()
x2 = pt2.x()
l = geod.Inverse(y1, x1, y2, x2)
return(l['azi1'])
except Exception:
parent.setEvalErrorString("Error: invalid parameters")
return
@qgsfunction(args=-1, group=group_name)
def st_geodesic_transform(values, feature, parent):
"""
Geodesically transfrom a shape (point, line, polygon) using rotation, translation, and scaling.
<h4>Syntax</h4>
<p><b>st_geodesic_transform</b>( <i>geom [, scale=1, rotate=0, distance=0, azimuth=0, unit='m', crs='EPSG:4326'</i>)</p>
<h4>Arguments</h4>
<ul>
<li><i>geom</i> → input geometry (point, line, polygon).</li>
<li><i>scale</i> → the scale factor. Default is 1.0.</li>
<li><i>rotate</i> → the rotation angle in degrees. Default is 0 degrees.</li>
<li><i>distance</i> → the translation distance. Default is 0.</li>
<li><i>azimuth</i> → the translation azimuth in degrees. Default is 0.</li>
<li><i>unit</i> → translation distance units</li>
<li><i>crs</i> → optional coordinate reference system of the input geometry. Default value is 'EPSG:4326' if not specified.</li>
<ul>
<li><i>'cm'</i> → centimeters</li>
<li><i>'m'</i> → meters</li>
<li><i>'km'</i> → kilometers</li>
<li><i>'in'</i> → inches</li>
<li><i>'ft'</i> → feet</li>
<li><i>'yard'</i> → yards</li>
<li><i>'mi'</i> → miles</li>
<li><i>'nm'</i> → nautical miles</li>
</ul></ul>
<h4>Example usage</h4>
<ul>
<li>geom_to_wkt(st_geodesic_transform(make_line(make_point(2,4),make_point(3,5)), 1.0, 45, 1000, 90, 'km')) → returns 'LineString (10.80438811 4.44561039, 12.21595371 4.44309579)'</li>
</ul>
"""
num_args = len(values)
if num_args < 1 or num_args > 7:
parent.setEvalErrorString("Error: invalid number of arguments")
return
scale = 1.0
rotate = 0.0
distance = 0.0
azimuth = 0.0
unit = 'm'
crs = 'EPSG:4326'
try:
geom = values[0]
if num_args > 1:
scale = float(values[1])
if num_args > 2:
rotate = float(values[2])
if num_args > 3:
distance = float(values[3])
if num_args > 4:
azimuth = float(values[4])
if num_args > 5:
unit = values[5]
if num_args > 6:
crs = values[6]
crs = QgsCoordinateReferenceSystem(crs)
geom_to_4326 = QgsCoordinateTransform(crs, epsg4326, QgsProject.instance())
to_crs = QgsCoordinateTransform(epsg4326, crs, QgsProject.instance())
if unit == 'cm':
factor = 0.01
elif unit == 'm':
factor = 1.0
elif unit == 'km':
factor = 1000.0
elif unit == 'in':
factor = QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceFeet, QgsUnitTypes.DistanceMeters) / 12.0
elif unit == 'ft':
factor = QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceFeet, QgsUnitTypes.DistanceMeters)
elif unit == 'yard':
factor = QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceYards, QgsUnitTypes.DistanceMeters)
elif unit == 'mi':
factor = QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMiles, QgsUnitTypes.DistanceMeters)
elif unit == 'nm':
factor = QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceNauticalMiles, QgsUnitTypes.DistanceMeters)
else:
parent.setEvalErrorString("Error: invalid unit")
centroid = geom.centroid().asPoint()
centroid = geom_to_4326.transform(centroid.x(), centroid.y())
cy = centroid.y()
cx = centroid.x()
if distance != 0:
distance *= factor
g = geod.Direct(cy, cx, azimuth, distance, Geodesic.LATITUDE | Geodesic.LONGITUDE)
new_centroid = QgsPoint(g['lon2'], g['lat2'])
else:
new_centroid = centroid
# Find the x & y coordinates of the new centroid
ncy = new_centroid.y()
ncx = new_centroid.x()
vertices = geom.vertices()
for vcnt, vertex in enumerate(vertices):
v = geom_to_4326.transform(vertex.x(), vertex.y())
gline = geod.Inverse(cy, cx, v.y(), v.x())
vdist = gline['s12']
vazi = gline['azi1']
if scale != 1:
vdist = vdist * scale
if rotate != 0:
vazi += rotate
g = geod.Direct(ncy, ncx, vazi, vdist, Geodesic.LATITUDE | Geodesic.LONGITUDE)
new_vertex = to_crs.transform(g['lon2'], g['lat2'])
geom.moveVertex(new_vertex.x(), new_vertex.y(), vcnt)
return(geom)
except Exception:
'''s = traceback.format_exc()
parent.setEvalErrorString(s)'''
parent.setEvalErrorString("Error: invalid input")
return
@qgsfunction(-1, group=group_name)
def st_compass(values, feature, parent):
"""
Returns the cardinal or compass direction given an azimuth as a string.
<h4>Syntax</h4>
<p><b>st_compass</b>( <i>azimuth[, npt=16, mode='abbr']</i> )</p>
<h4>Arguments</h4>
<p><i>azimuth</i> → specifies the azimuth and can be between -180 to 180 or 0 to 360 where 0 degrees is north.<br />
<i>npt</i> → the number compass directions. Valid values are 4, 8, 16, and 32.<br />
<i>mode</i> → 'abbr' returns the abbreviated compass direction, 'full' returns the full name and 'trad' returns the traditional name of the Mediterranean basin.<br />
<h4>Example usage</h4>
<ul>
<li><b>st_compass</b>(33) → 'NNE'</li>
<li><b>st_compass</b>(33, 8) → 'NE'</li>
<li><b>st_compass</b>(33, 32) → 'NEbN'</li>
<li><b>st_compass</b>(33, 16,'full') → 'north-northeast'</li>
<li><b>st_compass</b>(33, 32,'full') → 'northeast by north'</li>
<li><b>st_compass</b>(33, 32,'trad') → 'Quarto di Greco verso Tramontana'</li>
</ul>
"""
num_args = len(values)
if num_args < 1 or num_args > 3:
parent.setEvalErrorString("Error: invalid number of arguments")
return
try:
azimuth = float(values[0])
npt = 16
mode = 'abbr'
if num_args >= 2:
npt = float(values[1])
if num_args == 3:
mode = values[2].strip()
s = compass(azimuth, npt, mode)
return(s)
except Exception:
parent.setEvalErrorString("Error: invalid parameters")
return