more-transformations 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. more_transformations/__init__.py +94 -0
  2. more_transformations/_shapes.py +184 -0
  3. more_transformations/_triads.py +35 -0
  4. more_transformations/_units.py +29 -0
  5. more_transformations/_version.py +24 -0
  6. more_transformations/angles.py +764 -0
  7. more_transformations/attitude_determination.py +504 -0
  8. more_transformations/casadi/__init__.py +65 -0
  9. more_transformations/casadi/angles.py +552 -0
  10. more_transformations/casadi/attitude_determination.py +229 -0
  11. more_transformations/casadi/ecef.py +778 -0
  12. more_transformations/casadi/euler.py +768 -0
  13. more_transformations/casadi/flat_earth.py +239 -0
  14. more_transformations/casadi/frames.py +806 -0
  15. more_transformations/casadi/geodesic.py +287 -0
  16. more_transformations/casadi/linalg.py +143 -0
  17. more_transformations/casadi/parameters.py +624 -0
  18. more_transformations/casadi/pose.py +401 -0
  19. more_transformations/casadi/quaternion.py +1198 -0
  20. more_transformations/casadi/rigid_body.py +174 -0
  21. more_transformations/casadi/rotations.py +459 -0
  22. more_transformations/casadi/utils.py +353 -0
  23. more_transformations/casadi/utm.py +269 -0
  24. more_transformations/constants.py +70 -0
  25. more_transformations/data/README +65 -0
  26. more_transformations/data/WMM2010.COF +93 -0
  27. more_transformations/data/WMM2015v2.COF +93 -0
  28. more_transformations/data/WMM2020.COF +93 -0
  29. more_transformations/data/WMM2025.COF +93 -0
  30. more_transformations/data/WMMHR2025.COF +9047 -0
  31. more_transformations/data/egm96_15.npz +0 -0
  32. more_transformations/ecef.py +883 -0
  33. more_transformations/euler.py +903 -0
  34. more_transformations/flat_earth.py +243 -0
  35. more_transformations/frames.py +1015 -0
  36. more_transformations/geodesic.py +963 -0
  37. more_transformations/geoid.py +166 -0
  38. more_transformations/kernels/__init__.py +102 -0
  39. more_transformations/kernels/_compile_ready.py +36 -0
  40. more_transformations/kernels/_numba.py +23 -0
  41. more_transformations/kernels/angles.py +139 -0
  42. more_transformations/kernels/ecef.py +70 -0
  43. more_transformations/kernels/euler.py +320 -0
  44. more_transformations/kernels/rotations.py +131 -0
  45. more_transformations/linalg.py +359 -0
  46. more_transformations/magnetic.py +451 -0
  47. more_transformations/pose.py +521 -0
  48. more_transformations/py.typed +0 -0
  49. more_transformations/quaternion.py +1443 -0
  50. more_transformations/rigid_body.py +207 -0
  51. more_transformations/rotations.py +517 -0
  52. more_transformations/utm.py +350 -0
  53. more_transformations-1.0.0.dist-info/METADATA +370 -0
  54. more_transformations-1.0.0.dist-info/RECORD +58 -0
  55. more_transformations-1.0.0.dist-info/WHEEL +5 -0
  56. more_transformations-1.0.0.dist-info/entry_points.txt +2 -0
  57. more_transformations-1.0.0.dist-info/licenses/LICENSE +201 -0
  58. more_transformations-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,764 @@
1
+ """Angle wrapping, unwrapping, circular mean, course and bearing.
2
+
3
+ Angles are in radians unless ``unit="deg"`` is given. Course and bearing are
4
+ measured clockwise from north.
5
+
6
+ Equations:
7
+
8
+ * ``ssa``: the smallest signed angle in ``(-pi, pi]`` (``(-180, 180]``); pi is
9
+ included and -pi is not, so an angle of exactly half a turn is +pi in both
10
+ directions. It is evaluated as ``fmod(x, T)`` plus one period of correction, ``T = 2 pi``,
11
+ so an angle already in range is returned unchanged.
12
+ * ``wrap_0_2pi``: ``fmod(x, T)`` plus ``T`` for a negative remainder, never
13
+ ``T`` itself.
14
+ * ``unwrap``: ``previous + ssa(x - previous)``, the sample-by-sample
15
+ continuous angle.
16
+ * ``circular_mean``: ``atan2(sum w sin a, sum w cos a)``, the direction of
17
+ the resultant of the unit vectors ``(cos a, sin a)``.
18
+ * ``course_of`` and ``bearing_and_range``: the angle from the north axis of a
19
+ planar vector, ``atan2(e, n)`` (Fossen 2011, Definition 2.4, p. 39); with
20
+ ``wrap="positive"`` the angle in ``[0, 2 pi)`` (``[0, 360)``) instead.
21
+ * ``flow_angles``, ``from_flow_angles``: angle of attack ``alpha = atan2(w, u)`` and
22
+ sideslip ``beta = asin(v / U)`` of a body velocity.
23
+ * ``azimuth_elevation``, ``from_azimuth_elevation``: azimuth clockwise from
24
+ north, elevation above the horizontal plane and range of a vector.
25
+ * ``path_error``: the error ``Ry(upsilon)^T Rz(gamma)^T (p - p0)`` in the frame
26
+ of the straight path from ``p0`` to ``p1`` (Breivik and Fossen 2005).
27
+ * ``destination``: ``p0`` plus ``distance (cos(bearing), sin(bearing))`` in the
28
+ north-east plane.
29
+
30
+ References
31
+ ----------
32
+ .. [1] Fossen, T. I. (2011). *Handbook of Marine Craft Hydrodynamics and Motion
33
+ Control*. Wiley, Chichester. Definition 2.4, p. 39.
34
+ .. [2] Fossen, T. I. (2021). *Handbook of Marine Craft Hydrodynamics and Motion
35
+ Control*, 2nd ed. Wiley, Hoboken. The angle of attack and the sideslip angle, and
36
+ the guidance chapter on the path-fixed frame (cited without equation numbers).
37
+ .. [3] Breivik, M. and Fossen, T. I. (2005). Principles of guidance-based path
38
+ following in 2D and 3D. *Proc. 44th IEEE Conference on Decision and Control*,
39
+ pp. 627-634: the path-fixed frame and its along-track, cross-track and
40
+ vertical-track errors (cited without equation numbers).
41
+ .. [4] Groves, P. D. (2013). *Principles of GNSS, Inertial, and Multisensor
42
+ Integrated Navigation Systems*, 2nd ed. Artech House, Boston. The azimuth and
43
+ elevation of a line of sight (cited without equation numbers).
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ from typing import Optional, overload
49
+
50
+ from collections.abc import Sequence
51
+
52
+ import numpy as np
53
+ from numpy.typing import ArrayLike, NDArray
54
+
55
+ from more_transformations import frames as _frames
56
+ from more_transformations._shapes import as_float as _as_float, check_wrap as _check_wrap, planar_batch as _planar_batch, vector_batch as _vector_batch
57
+ from more_transformations.kernels.angles import (
58
+ bearing_range as _bearing_range,
59
+ course_of as _course_of,
60
+ ssa as _ssa,
61
+ ssa_deg as _ssa_deg,
62
+ wrap_0_2pi as _wrap_0_2pi,
63
+ wrap_0_360 as _wrap_0_360,
64
+ )
65
+
66
+ __all__ = [
67
+ "ssa",
68
+ "wrap_0_2pi",
69
+ "unwrap",
70
+ "circular_mean",
71
+ "course_of",
72
+ "bearing_and_range",
73
+ "flow_angles",
74
+ "from_flow_angles",
75
+ "azimuth_elevation",
76
+ "from_azimuth_elevation",
77
+ "path_error",
78
+ "destination",
79
+ ]
80
+
81
+
82
+ def _check_angle_unit(unit: str) -> None:
83
+ if unit not in ("rad", "deg"):
84
+ raise ValueError("Unit must be 'rad' or 'deg'.")
85
+
86
+
87
+ def _angle(x: ArrayLike) -> float | NDArray[np.float64]:
88
+ """``x`` unchanged if it is a Python number or a numeric array, else a float array (``TypeError`` for a non-number)."""
89
+ if isinstance(x, (int, float)) or (isinstance(x, np.ndarray) and x.dtype.kind in "fiub"):
90
+ return x
91
+ return _as_float(x)
92
+
93
+
94
+ @overload
95
+ def ssa(x: float, *, unit: str = "rad") -> float: ...
96
+
97
+
98
+ @overload
99
+ def ssa(x: Sequence[float], *, unit: str = "rad") -> NDArray[np.float64]: ...
100
+
101
+
102
+ @overload
103
+ def ssa(x: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]: ...
104
+
105
+
106
+ def ssa(x: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]:
107
+ """Smallest signed angle, in (-pi, pi] or (-180, 180].
108
+
109
+ Parameters
110
+ ----------
111
+ x : float or array_like, shape (N,)
112
+ Angle.
113
+ unit : {"rad", "deg"}, optional
114
+ Unit of ``x`` and of the result.
115
+
116
+ Returns
117
+ -------
118
+ float or numpy.ndarray
119
+ The angle congruent to ``x`` in (-pi, pi] (``(-180, 180]`` for
120
+ degrees); ``ssa(pi) = pi`` and ``ssa(-pi) = pi``. An angle already in
121
+ range is returned unchanged, ``nan`` and ``inf`` give ``nan``.
122
+
123
+ Raises
124
+ ------
125
+ ValueError
126
+ If ``unit`` is neither ``"rad"`` nor ``"deg"``.
127
+
128
+ Notes
129
+ -----
130
+ The reduction is ``r = fmod(x, T)``, then ``r += T`` if ``r <= -T/2`` and
131
+ ``r -= T`` if ``r > T/2``. ``fmod`` is exact, so ``x`` is not rounded
132
+ before the reduction. In radians ``T`` is the double nearest ``2 pi``, so
133
+ for ``|x|`` beyond about 1e8 the result differs from a reduction by the
134
+ true ``2 pi``; the degree form uses the exact periods 180 and 360.
135
+
136
+ References
137
+ ----------
138
+ .. [1] Fossen, T. I. (2021). *Handbook of Marine Craft Hydrodynamics and Motion
139
+ Control*, 2nd ed. Wiley, Hoboken. Ch. 2 (the smallest signed angle).
140
+
141
+ Examples
142
+ --------
143
+ >>> import numpy as np
144
+ >>> from more_transformations import angles
145
+ >>> float(angles.ssa(3 * np.pi / 2)) == -np.pi / 2
146
+ True
147
+ >>> float(angles.ssa(190.0, unit="deg"))
148
+ -170.0
149
+ """
150
+ _check_angle_unit(unit)
151
+ x = _angle(x)
152
+ return _ssa(x) if unit == "rad" else _ssa_deg(x)
153
+
154
+
155
+ @overload
156
+ def wrap_0_2pi(x: float, *, unit: str = "rad") -> float: ...
157
+
158
+
159
+ @overload
160
+ def wrap_0_2pi(x: Sequence[float], *, unit: str = "rad") -> NDArray[np.float64]: ...
161
+
162
+
163
+ @overload
164
+ def wrap_0_2pi(x: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]: ...
165
+
166
+
167
+ def wrap_0_2pi(x: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]:
168
+ """Angle in [0, 2 pi) or [0, 360).
169
+
170
+ Parameters
171
+ ----------
172
+ x : float or array_like, shape (N,)
173
+ Angle.
174
+ unit : {"rad", "deg"}, optional
175
+ Unit of ``x`` and of the result.
176
+
177
+ Returns
178
+ -------
179
+ float or numpy.ndarray
180
+ The angle congruent to ``x`` in ``[0, T)``. The result is never ``T``:
181
+ for a tiny negative angle, where ``x + T`` rounds to ``T``, 0 is
182
+ returned. ``nan`` and ``inf`` give ``nan``.
183
+
184
+ Raises
185
+ ------
186
+ ValueError
187
+ If ``unit`` is neither ``"rad"`` nor ``"deg"``.
188
+
189
+ Examples
190
+ --------
191
+ >>> from more_transformations import angles
192
+ >>> float(angles.wrap_0_2pi(-90.0, unit="deg"))
193
+ 270.0
194
+ >>> float(angles.wrap_0_2pi(-1e-20))
195
+ 0.0
196
+ """
197
+ _check_angle_unit(unit)
198
+ x = _angle(x)
199
+ return _wrap_0_2pi(x) if unit == "rad" else _wrap_0_360(x)
200
+
201
+
202
+ @overload
203
+ def unwrap(x: float, previous: float, *, unit: str = "rad") -> float: ...
204
+
205
+
206
+ @overload
207
+ def unwrap(x: Sequence[float], previous: ArrayLike, *, unit: str = "rad") -> NDArray[np.float64]: ...
208
+
209
+
210
+ @overload
211
+ def unwrap(x: ArrayLike, previous: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]: ...
212
+
213
+
214
+ def unwrap(x: ArrayLike, previous: ArrayLike, *, unit: str = "rad") -> float | NDArray[np.float64]:
215
+ """Continuous angle: the value congruent to ``x`` that lies within a half turn of ``previous``.
216
+
217
+ ``previous + ssa(x - previous)``, so a sequence of wrapped angles becomes
218
+ one without jumps of a full turn, one sample at a time (the
219
+ sample-by-sample form of `numpy.unwrap`).
220
+
221
+ Parameters
222
+ ----------
223
+ x : float or array_like, shape (N,)
224
+ New angle.
225
+ previous : float or array_like, shape (N,)
226
+ Previous continuous angle; broadcast with ``x``.
227
+ unit : {"rad", "deg"}, optional
228
+ Unit of both angles and of the result.
229
+
230
+ Returns
231
+ -------
232
+ float or numpy.ndarray
233
+ The continuous angle.
234
+
235
+ Raises
236
+ ------
237
+ ValueError
238
+ If ``unit`` is neither ``"rad"`` nor ``"deg"``.
239
+
240
+ Examples
241
+ --------
242
+ >>> from more_transformations import angles
243
+ >>> float(angles.unwrap(-179.0, 179.0, unit="deg"))
244
+ 181.0
245
+ """
246
+ x = _as_float(x)
247
+ previous = _as_float(previous)
248
+ return previous + ssa(x - previous, unit=unit)
249
+
250
+
251
+ def circular_mean(
252
+ x: ArrayLike,
253
+ weights: Optional[ArrayLike] = None,
254
+ *,
255
+ axis: Optional[int] = None,
256
+ ) -> float | NDArray[np.float64]:
257
+ """Circular (weighted) mean of angles, in radians.
258
+
259
+ ``atan2(sum w sin a, sum w cos a)`` wrapped to (-pi, pi]. The weights are
260
+ first divided by their largest value (over ``axis``), which leaves the mean
261
+ unchanged and keeps the sums finite for any finite weights. One mean per call:
262
+ the angles along ``axis`` are the samples of that problem (``axis=-1`` of an array gives one mean
263
+ per row).
264
+
265
+ Parameters
266
+ ----------
267
+ x : array_like
268
+ Angles [rad].
269
+ weights : array_like, optional
270
+ Non-negative weights, broadcast to ``x``; equal by default. They need
271
+ not sum to 1.
272
+ axis : int, optional
273
+ Axis to reduce, as in NumPy; ``None`` reduces all elements.
274
+
275
+ Returns
276
+ -------
277
+ float or numpy.ndarray
278
+ The mean direction [rad]; a float when all elements are reduced.
279
+ When the resultant length of the scaled weights is at most
280
+ ``1e-12 * sum(w)`` (for example ``[0, pi]``), or all weights are zero,
281
+ the direction is undefined and 0.0 is returned.
282
+
283
+ Raises
284
+ ------
285
+ ValueError
286
+ If a weight is negative.
287
+
288
+ Notes
289
+ -----
290
+ The mean direction is the direction of the weighted resultant of the unit vectors
291
+ ``(cos a, sin a)``, ``(sum w cos a, sum w sin a)``; its angle is the
292
+ ``atan2`` of the two sums.
293
+
294
+ References
295
+ ----------
296
+ .. [1] Mardia, K. V., Jupp, P. E. (2000). *Directional Statistics*. Wiley. Chapter 2.
297
+
298
+ Examples
299
+ --------
300
+ >>> import numpy as np
301
+ >>> from more_transformations import angles
302
+ >>> round(angles.circular_mean([np.pi - 0.1, -np.pi + 0.1]), 12) == round(np.pi, 12)
303
+ True
304
+ >>> angles.circular_mean([0.0, np.pi])
305
+ 0.0
306
+ """
307
+ a = _as_float(x)
308
+ w = np.ones_like(a) if weights is None else np.broadcast_to(_as_float(weights), a.shape)
309
+ if np.any(w < 0.0):
310
+ raise ValueError("weights must be non-negative")
311
+ w_max = np.max(w, axis=axis, keepdims=True)
312
+ w = np.divide(w, w_max, out=np.zeros(a.shape), where=w_max > 0.0) # scale-free mean
313
+ S = np.sum(w * np.sin(a), axis=axis)
314
+ C = np.sum(w * np.cos(a), axis=axis)
315
+ W = np.sum(w, axis=axis)
316
+ defined = np.hypot(S, C) > 1e-12 * W
317
+ m = np.where(defined, _ssa(np.arctan2(S, C)), 0.0) # (-pi, pi]
318
+ return float(m) if m.ndim == 0 else m
319
+
320
+
321
+ def course_of(v: ArrayLike, *, frame: str = "NED", wrap: str = "signed") -> float | NDArray[np.float64]:
322
+ """Course of a planar vector, clockwise from north, in (-pi, pi] [rad].
323
+
324
+ Only the first two components are used. A zero vector, of either sign of
325
+ zero, has no direction and gives 0.
326
+
327
+ Parameters
328
+ ----------
329
+ v : array_like, shape (k,) or (N, k)
330
+ Vector ``(n, e, ...)`` for ``frame="NED"`` and ``(e, n, ...)`` for
331
+ ``"ENU"``; one vector per row for a 2-D array.
332
+ frame : {"NED", "ENU"}, optional
333
+ Frame of ``v``, in any case.
334
+ wrap : {"signed", "positive"}, optional
335
+ ``"signed"`` gives the course in (-pi, pi], ``"positive"`` the same
336
+ direction in [0, 2 pi).
337
+
338
+ Returns
339
+ -------
340
+ float or numpy.ndarray
341
+ Course [rad]; a float for a 1-D input, shape (N,) for an (N, k) input.
342
+
343
+ Raises
344
+ ------
345
+ ValueError
346
+ If ``frame`` is neither ``"NED"`` nor ``"ENU"``, or ``wrap`` is neither ``"signed"`` nor ``"positive"``.
347
+
348
+ Notes
349
+ -----
350
+ Applied to the horizontal body velocity ``(u, v)`` (forward, starboard) with ``frame="NED"``, the first two
351
+ components play the roles of north and east, so the result is ``atan2(v, u)``, the angle of the velocity from
352
+ the body x axis, positive to starboard: the crab angle for the velocity over ground, the sideslip angle in the
353
+ horizontal plane for the velocity through the water (Fossen 2021, the definitions of the crab angle and of the
354
+ sideslip angle, no equation number).
355
+
356
+ References
357
+ ----------
358
+ .. [1] Fossen (2011), Definition 2.4, p. 39.
359
+ .. [2] Fossen (2021), the crab angle and the sideslip angle (no equation number).
360
+
361
+ Examples
362
+ --------
363
+ >>> from more_transformations import angles
364
+ >>> round(float(angles.course_of([0.0, 1.0])), 6)
365
+ 1.570796
366
+ >>> round(float(angles.course_of([1.0, 0.0], frame="ENU")), 6)
367
+ 1.570796
368
+ >>> round(float(angles.course_of([0.0, -1.0], wrap="positive")), 6)
369
+ 4.712389
370
+ """
371
+ _check_wrap(wrap)
372
+ v = _planar_batch(v, "v")
373
+ i_n, i_e = (0, 1) if _frames.frame_name(frame) == "NED" else (1, 0)
374
+ course = _course_of(v[..., i_n], v[..., i_e])
375
+ return course if wrap == "signed" else _wrap_0_2pi(course)
376
+
377
+
378
+ def bearing_and_range(
379
+ p: ArrayLike, p0: ArrayLike, *, frame: str = "NED", wrap: str = "signed"
380
+ ) -> tuple[float | NDArray[np.float64], float | NDArray[np.float64]]:
381
+ """Planar bearing and horizontal range of a point seen from a reference.
382
+
383
+ The vertical component is ignored.
384
+
385
+ Parameters
386
+ ----------
387
+ p : array_like, shape (k,) or (N, k)
388
+ The point in the local frame ``frame``: ``(n, e, ...)`` for ``"NED"``,
389
+ ``(e, n, ...)`` for ``"ENU"`` [m].
390
+ p0 : array_like, shape (k,) or (N, k)
391
+ The reference, in the same frame; broadcast against ``p``.
392
+ frame : {"NED", "ENU"}, optional
393
+ Frame of the points, in any case.
394
+ wrap : {"signed", "positive"}, optional
395
+ ``"signed"`` gives the bearing in (-pi, pi], ``"positive"`` in [0, 2 pi).
396
+
397
+ Returns
398
+ -------
399
+ bearing, range : float or numpy.ndarray, shape (N,)
400
+ Bearing [rad], clockwise from north, in (-pi, pi] (``wrap="signed"``) or [0, 2 pi);
401
+ horizontal range [m], computed by ``hypot`` without overflow of the squares.
402
+
403
+ Raises
404
+ ------
405
+ ValueError
406
+ If ``frame`` is neither ``"NED"`` nor ``"ENU"``, or ``wrap`` is neither ``"signed"`` nor ``"positive"``.
407
+
408
+ References
409
+ ----------
410
+ .. [1] Fossen (2011), Definition 2.4, p. 39.
411
+
412
+ Examples
413
+ --------
414
+ >>> from more_transformations import angles
415
+ >>> bearing, rng = angles.bearing_and_range([3.0, 4.0], [0.0, 0.0])
416
+ >>> round(float(bearing), 6), float(rng)
417
+ (0.927295, 5.0)
418
+ """
419
+ _check_wrap(wrap)
420
+ d = _planar_batch(p, "p") - _planar_batch(p0, "p0")
421
+ i_n, i_e = (0, 1) if _frames.frame_name(frame) == "NED" else (1, 0)
422
+ bearing, rng = _bearing_range(d[..., i_n], d[..., i_e])
423
+ return (bearing if wrap == "signed" else _wrap_0_2pi(bearing)), rng
424
+
425
+
426
+
427
+ def _ned_components(v: NDArray[np.float64], frame: str) -> list[NDArray[np.float64]]:
428
+ """Components ``[n, e, d]`` (or ``[n, e]`` for two components) of ``v``, given in ``frame``."""
429
+ comp = [v[..., i] for i in range(v.shape[-1])]
430
+ if _frames.frame_name(frame) == "NED":
431
+ return comp
432
+ return [comp[1], comp[0]] + ([-comp[2]] if len(comp) == 3 else [])
433
+
434
+
435
+ def flow_angles(
436
+ v: ArrayLike,
437
+ ) -> tuple[float | NDArray[np.float64], float | NDArray[np.float64], float | NDArray[np.float64]]:
438
+ """Speed, angle of attack and sideslip angle of a body velocity.
439
+
440
+ Parameters
441
+ ----------
442
+ v : array_like, shape (3,) or (N, 3)
443
+ Body velocity ``(u, v, w)`` [m/s].
444
+
445
+ Returns
446
+ -------
447
+ speed, alpha, beta : float or numpy.ndarray, shape (N,)
448
+ ``U = |v|`` [m/s], the angle of attack ``alpha = atan2(w, u)`` in (-pi, pi] and the
449
+ sideslip angle ``beta = asin(v / U)`` in [-pi/2, pi/2] [rad]. For a zero velocity
450
+ ``alpha = beta = 0``.
451
+
452
+ Raises
453
+ ------
454
+ ValueError
455
+ If ``v`` does not have 3 components on its last axis.
456
+ TypeError
457
+ If ``v`` is not a number or a sequence of numbers.
458
+
459
+ Notes
460
+ -----
461
+ The velocity of the body relative to the fluid is ``(u, v, w) = U (cos alpha cos beta, sin beta,
462
+ sin alpha cos beta)``; inverting it gives the three results, and `from_flow_angles` is the
463
+ forward map. Since ``cos beta >= 0`` the pair ``(alpha, beta)`` is unique for ``U > 0``
464
+ (Fossen 2021, the angle of attack and the sideslip angle, no equation number).
465
+
466
+ References
467
+ ----------
468
+ .. [1] Fossen (2021), the angle of attack and the sideslip angle (no equation number).
469
+
470
+ Examples
471
+ --------
472
+ >>> from more_transformations import angles
473
+ >>> speed, alpha, beta = angles.flow_angles([1.0, 0.0, 1.0])
474
+ >>> round(float(speed), 6), round(float(alpha), 6), float(beta)
475
+ (1.414214, 0.785398, 0.0)
476
+ """
477
+ v = _vector_batch(v, 3, "v")
478
+ speed = np.sqrt((v * v).sum(axis=-1))
479
+ alpha = np.where(speed > 0.0, _ssa(np.arctan2(v[..., 2], v[..., 0])), 0.0)[()] # 0 for a zero velocity of either sign of zero
480
+ ratio = np.divide(v[..., 1], speed, out=np.zeros(speed.shape), where=speed > 0.0)
481
+ return speed, alpha, np.arcsin(np.clip(ratio, -1.0, 1.0))
482
+
483
+
484
+ def from_flow_angles(speed: ArrayLike, alpha: ArrayLike, beta: ArrayLike) -> NDArray[np.float64]:
485
+ """Body velocity of a speed, an angle of attack and a sideslip angle.
486
+
487
+ The inverse of `flow_angles`. With the speed of a current and its angles this builds a current
488
+ vector in the body frame.
489
+
490
+ Parameters
491
+ ----------
492
+ speed : float or array_like, shape (N,)
493
+ Speed [m/s].
494
+ alpha, beta : float or array_like, shape (N,)
495
+ Angle of attack and sideslip angle [rad]; broadcast with ``speed``.
496
+
497
+ Returns
498
+ -------
499
+ numpy.ndarray, shape (3,) or (N, 3)
500
+ ``(u, v, w) = U (cos alpha cos beta, sin beta, sin alpha cos beta)`` [m/s].
501
+
502
+ Raises
503
+ ------
504
+ ValueError
505
+ If the arguments cannot be broadcast together.
506
+ TypeError
507
+ If an argument is not a number.
508
+
509
+ References
510
+ ----------
511
+ .. [1] Fossen (2021), the angle of attack and the sideslip angle (no equation number).
512
+
513
+ Examples
514
+ --------
515
+ >>> from more_transformations import angles
516
+ >>> angles.from_flow_angles(2.0, 0.0, 0.0)
517
+ array([2., 0., 0.])
518
+ """
519
+ U, a, b = np.broadcast_arrays(*(_as_float(x) for x in (speed, alpha, beta)))
520
+ return np.stack([U * np.cos(a) * np.cos(b), U * np.sin(b), U * np.sin(a) * np.cos(b)], axis=-1)
521
+
522
+
523
+ def azimuth_elevation(
524
+ v: ArrayLike, *, frame: str = "NED"
525
+ ) -> tuple[float | NDArray[np.float64], float | NDArray[np.float64], float | NDArray[np.float64]]:
526
+ """Azimuth, elevation and range of a vector.
527
+
528
+ Parameters
529
+ ----------
530
+ v : array_like, shape (3,) or (N, 3)
531
+ Vector ``(n, e, d)`` for ``frame="NED"``, ``(e, n, u)`` for ``"ENU"`` [m].
532
+ frame : {"NED", "ENU"}, optional
533
+ Frame of ``v``, in any case.
534
+
535
+ Returns
536
+ -------
537
+ azimuth, elevation, range : float or numpy.ndarray, shape (N,)
538
+ Azimuth [rad], clockwise from north, in (-pi, pi] (0 for a vertical or zero vector);
539
+ elevation [rad], positive up, in [-pi/2, pi/2]; range ``|v|`` [m].
540
+
541
+ Raises
542
+ ------
543
+ ValueError
544
+ If ``frame`` is neither ``"NED"`` nor ``"ENU"``, or ``v`` does not have 3 components.
545
+ TypeError
546
+ If ``v`` is not a number or a sequence of numbers.
547
+
548
+ Notes
549
+ -----
550
+ With the horizontal components ``n``, ``e`` and the upward component ``u`` (``u = -d`` in NED),
551
+ ``azimuth = atan2(e, n)``, ``elevation = atan2(u, sqrt(n^2 + e^2))`` and ``range = |v|``
552
+ (Groves 2013, the azimuth and elevation of a line of sight, no equation number).
553
+
554
+ References
555
+ ----------
556
+ .. [1] Groves (2013), the azimuth and elevation of a line of sight (no equation number).
557
+
558
+ Examples
559
+ --------
560
+ >>> from more_transformations import angles
561
+ >>> az, el, rng = angles.azimuth_elevation([0.0, 3.0, -4.0])
562
+ >>> round(float(az), 6), round(float(el), 6), float(rng)
563
+ (1.570796, 0.927295, 5.0)
564
+ """
565
+ v = _vector_batch(v, 3, "v")
566
+ n, e, d = _ned_components(v, frame)
567
+ return _course_of(n, e), np.arctan2(-d, np.hypot(n, e)), np.sqrt((v * v).sum(axis=-1))
568
+
569
+
570
+ def from_azimuth_elevation(
571
+ azimuth: ArrayLike, elevation: ArrayLike, range: ArrayLike, *, frame: str = "NED"
572
+ ) -> NDArray[np.float64]:
573
+ """Vector of an azimuth, an elevation and a range, the inverse of `azimuth_elevation`.
574
+
575
+ Parameters
576
+ ----------
577
+ azimuth : float or array_like, shape (N,)
578
+ Azimuth, clockwise from north [rad].
579
+ elevation : float or array_like, shape (N,)
580
+ Elevation, positive up [rad].
581
+ range : float or array_like, shape (N,)
582
+ Length of the vector [m].
583
+ frame : {"NED", "ENU"}, optional
584
+ Frame of the result, in any case.
585
+
586
+ Returns
587
+ -------
588
+ numpy.ndarray, shape (3,) or (N, 3)
589
+ ``(n, e, d)`` for ``"NED"``, ``(e, n, u)`` for ``"ENU"`` [m], with
590
+ ``n = r cos(el) cos(az)``, ``e = r cos(el) sin(az)``, ``u = r sin(el)`` and ``d = -u``.
591
+
592
+ Raises
593
+ ------
594
+ ValueError
595
+ If ``frame`` is neither ``"NED"`` nor ``"ENU"``, or the arguments cannot be broadcast together.
596
+ TypeError
597
+ If an argument is not a number.
598
+
599
+ References
600
+ ----------
601
+ .. [1] Groves (2013), the azimuth and elevation of a line of sight (no equation number).
602
+
603
+ Examples
604
+ --------
605
+ >>> import numpy as np
606
+ >>> from more_transformations import angles
607
+ >>> angles.from_azimuth_elevation(np.pi / 2, 0.0, 2.0).round(6) + 0.0
608
+ array([0., 2., 0.])
609
+ """
610
+ ned = _frames.frame_name(frame) == "NED"
611
+ az, el, r = np.broadcast_arrays(*(_as_float(x) for x in (azimuth, elevation, range)))
612
+ n, e, u = r * np.cos(el) * np.cos(az), r * np.cos(el) * np.sin(az), r * np.sin(el)
613
+ return np.stack([n, e, -u] if ned else [e, n, u], axis=-1)
614
+
615
+
616
+ def path_error(
617
+ p: ArrayLike, p0: ArrayLike, p1: ArrayLike, *, frame: str = "NED"
618
+ ) -> tuple[float | NDArray[np.float64], ...]:
619
+ """Along-track, cross-track and vertical-track error of a point relative to a straight path.
620
+
621
+ Parameters
622
+ ----------
623
+ p : array_like, shape (k,) or (N, k), with k = 2 or 3
624
+ The point in the frame ``frame``: ``(n, e[, d])`` for ``"NED"``, ``(e, n[, u])`` for ``"ENU"`` [m].
625
+ p0, p1 : array_like, shape (k,) or (N, k)
626
+ The start and the end of the path, in the same frame and with the same k; broadcast against ``p``.
627
+ frame : {"NED", "ENU"}, optional
628
+ Frame of the points, in any case.
629
+
630
+ Returns
631
+ -------
632
+ tuple of float or numpy.ndarray, shape (N,)
633
+ ``(along, cross)`` for two components, ``(along, cross, vertical)`` for three [m]. ``along``
634
+ is the distance of the point from the start along the path (negative before the start),
635
+ ``cross`` the distance to the right of the direction of travel, and ``vertical`` the
636
+ distance below the path, normal to it. The results do not depend on the ``frame``, which
637
+ only fixes the order of the input components.
638
+
639
+ Raises
640
+ ------
641
+ ValueError
642
+ If ``p0`` equals ``p1`` (the path has no direction), ``frame`` is neither ``"NED"`` nor
643
+ ``"ENU"``, or the points do not have the same 2 or 3 components.
644
+ TypeError
645
+ If an argument is not a number or a sequence of numbers.
646
+
647
+ Notes
648
+ -----
649
+ The path-fixed frame has its x axis along the path, with the azimuth ``gamma = atan2(e1 - e0, n1 - n0)``
650
+ and the elevation angle ``upsilon = atan2(-(d1 - d0), hypot(n1 - n0, e1 - e0))``; the error of
651
+ the point in that frame is ``Ry(upsilon)^T Rz(gamma)^T (p - p0)`` (Breivik and Fossen 2005,
652
+ the path-fixed frame and its tracking errors, no equation number). For two components the
653
+ elevation is 0 and the error is ``(cos(gamma) dn + sin(gamma) de, -sin(gamma) dn + cos(gamma) de)``.
654
+ The cosines and sines are formed from the ratios of the path components, so no angle is computed;
655
+ a path that is vertical has the azimuth 0.
656
+
657
+ References
658
+ ----------
659
+ .. [1] Breivik and Fossen (2005), the path-fixed frame (no equation number).
660
+ .. [2] Fossen (2021), the guidance chapter on path following (no equation number).
661
+
662
+ Examples
663
+ --------
664
+ >>> from more_transformations import angles
665
+ >>> along, cross = angles.path_error([1.0, 2.0], [0.0, 0.0], [10.0, 0.0])
666
+ >>> float(along), float(cross)
667
+ (1.0, 2.0)
668
+ """
669
+ p = _vector_batch(p, (2, 3), "p")
670
+ p0 = _vector_batch(p0, (2, 3), "p0")
671
+ p1 = _vector_batch(p1, (2, 3), "p1")
672
+ if not p.shape[-1] == p0.shape[-1] == p1.shape[-1]:
673
+ raise ValueError("p, p0 and p1 must have the same number of components")
674
+ three = p.shape[-1] == 3
675
+ pn, p0n, p1n = (_ned_components(x, frame) for x in (p, p0, p1))
676
+ t = [b - a for a, b in zip(p0n, p1n)]
677
+ d = [x - a for x, a in zip(pn, p0n)]
678
+ horizontal = np.hypot(t[0], t[1])
679
+ length = np.sqrt(sum(c * c for c in t))
680
+ if np.any(length == 0.0):
681
+ raise ValueError("p0 and p1 coincide: the path has no direction")
682
+ flat = horizontal == 0.0
683
+ safe = np.where(flat, 1.0, horizontal)
684
+ cg = np.where(flat, 1.0, t[0] / safe) # cos(gamma) and sin(gamma) of the path azimuth
685
+ sg = np.where(flat, 0.0, t[1] / safe)
686
+ x1 = cg * d[0] + sg * d[1] # Rz(gamma)^T (p - p0)
687
+ y1 = -sg * d[0] + cg * d[1]
688
+ if not three:
689
+ return x1, y1
690
+ cu, su = horizontal / length, -t[2] / length # cos(upsilon) and sin(upsilon) of the path elevation
691
+ return cu * x1 - su * d[2], y1, su * x1 + cu * d[2] # Ry(upsilon)^T [x1, y1, d_down]
692
+
693
+
694
+ def destination(
695
+ p0: ArrayLike, bearing: ArrayLike, distance: ArrayLike, *, frame: str = "NED"
696
+ ) -> NDArray[np.float64]:
697
+ """Point reached from ``p0`` along a bearing for a distance, in the local plane.
698
+
699
+ The planar twin of `more_transformations.geodesic.destination`.
700
+
701
+ Parameters
702
+ ----------
703
+ p0 : array_like, shape (k,) or (N, k), with k = 2 or 3
704
+ Start point in the frame ``frame``: ``(n, e[, d])`` for ``"NED"``, ``(e, n[, u])`` for ``"ENU"`` [m].
705
+ bearing : float or array_like, shape (N,)
706
+ Bearing, clockwise from north [rad].
707
+ distance : float or array_like, shape (N,)
708
+ Horizontal distance [m]; negative runs backwards.
709
+ frame : {"NED", "ENU"}, optional
710
+ Frame of ``p0`` and of the result, in any case.
711
+
712
+ Returns
713
+ -------
714
+ numpy.ndarray, shape (k,) or (N, k)
715
+ The point, with the vertical component of ``p0`` unchanged.
716
+
717
+ Raises
718
+ ------
719
+ ValueError
720
+ If ``frame`` is neither ``"NED"`` nor ``"ENU"``, or the arguments cannot be broadcast together.
721
+ TypeError
722
+ If an argument is not a number or a sequence of numbers.
723
+
724
+ Notes
725
+ -----
726
+ ``n = n0 + distance cos(bearing)`` and ``e = e0 + distance sin(bearing)``: the inverse of the
727
+ bearing of Fossen (2011), Definition 2.4, p. 39 (`bearing_and_range`).
728
+
729
+ References
730
+ ----------
731
+ .. [1] Fossen (2011), Definition 2.4, p. 39.
732
+
733
+ Examples
734
+ --------
735
+ >>> import numpy as np
736
+ >>> from more_transformations import angles
737
+ >>> angles.destination([1.0, 1.0], np.pi / 2, 10.0).round(6)
738
+ array([ 1., 11.])
739
+ """
740
+ p0 = _vector_batch(p0, (2, 3), "p0")
741
+ i_n, i_e = (0, 1) if _frames.frame_name(frame) == "NED" else (1, 0)
742
+ brg, dist = np.broadcast_arrays(_as_float(bearing), _as_float(distance))
743
+ shape = np.broadcast_shapes(p0.shape[:-1], brg.shape)
744
+ out = np.array(np.broadcast_to(p0, shape + (p0.shape[-1],)))
745
+ out[..., i_n] += dist * np.cos(brg)
746
+ out[..., i_e] += dist * np.sin(brg)
747
+ return out
748
+
749
+
750
+ class Angles:
751
+ """Namespace of the functions of `more_transformations.angles`."""
752
+
753
+ ssa = staticmethod(ssa)
754
+ wrap_0_2pi = staticmethod(wrap_0_2pi)
755
+ unwrap = staticmethod(unwrap)
756
+ circular_mean = staticmethod(circular_mean)
757
+ course_of = staticmethod(course_of)
758
+ bearing_and_range = staticmethod(bearing_and_range)
759
+ flow_angles = staticmethod(flow_angles)
760
+ from_flow_angles = staticmethod(from_flow_angles)
761
+ azimuth_elevation = staticmethod(azimuth_elevation)
762
+ from_azimuth_elevation = staticmethod(from_azimuth_elevation)
763
+ path_error = staticmethod(path_error)
764
+ destination = staticmethod(destination)