pfc-geometry 0.1.1__py3-none-any.whl → 0.2.4__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.
geometry/quaternion.py CHANGED
@@ -9,21 +9,22 @@ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9
9
  You should have received a copy of the GNU General Public License along with
10
10
  this program. If not, see <http://www.gnu.org/licenses/>.
11
11
  """
12
+ from __future__ import annotations
12
13
  from .point import Point
13
14
  from .base import Base
14
15
  from geometry import PZ
15
- from typing import Union, Tuple
16
16
  import numpy as np
17
+ import numpy.typing as npt
18
+ import pandas as pd
17
19
  from warnings import warn
18
20
  from numbers import Number
19
21
 
20
22
 
21
-
22
23
  class Quaternion(Base):
23
24
  cols=["w", "x", "y", "z"]
24
25
 
25
26
  @staticmethod
26
- def zero(count=1):
27
+ def zero(count=1) -> Quaternion:
27
28
  return Quaternion(np.tile([1,0,0,0], (count,1)))
28
29
 
29
30
  @property
@@ -31,19 +32,19 @@ class Quaternion(Base):
31
32
  return np.array([self.x, self.y, self.z, self.w]).T
32
33
 
33
34
  @property
34
- def axis(self):
35
+ def axis(self) -> Point:
35
36
  return Point(self.data[:,1:])
36
37
 
37
- def norm(self):
38
+ def norm(self) -> Quaternion:
38
39
  return self / abs(self)
39
40
 
40
- def conjugate(self):
41
+ def conjugate(self) -> Quaternion:
41
42
  return Quaternion(self.w, -self.x, -self.y, -self.z)
42
43
 
43
44
  def inverse(self):
44
45
  return self.conjugate().norm()
45
46
 
46
- def __mul__(self, other):
47
+ def __mul__(self, other: Number | Quaternion | npt.NDArray) -> Quaternion:
47
48
  if isinstance(other, Quaternion):
48
49
  a, b = Quaternion.length_check(self, Quaternion.type_check(other))
49
50
  w = a.w * b.w - a.axis.dot(b.axis)
@@ -53,15 +54,15 @@ class Quaternion(Base):
53
54
  elif isinstance(other, Number):
54
55
  return Quaternion(self.data * other)
55
56
  elif isinstance(other, np.ndarray):
56
- return Quaternions(self.data * self._dprep(other))
57
+ return Quaternion(self.data * self._dprep(other))
57
58
 
58
59
  raise TypeError(f"cant multiply a quaternion by a {other.__class__.__name__}")
59
60
 
60
- def __rmul__(self, other):
61
+ def __rmul__(self, other) -> Quaternion:
61
62
  #either it should have been picked up by the left hand object or it should commute
62
63
  return self * other
63
64
 
64
- def transform_point(self, point: Point):
65
+ def transform_point(self, point: Point) -> Point:
65
66
  '''Transform a point by the rotation described by self'''
66
67
  a, b = Base.length_check(self, point)
67
68
 
@@ -70,9 +71,9 @@ class Quaternion(Base):
70
71
  return (a * Quaternion(qdata) * a.inverse()).axis
71
72
 
72
73
  @staticmethod
73
- def from_euler(eul: Point):
74
- eul = Point.type_check(eul)
75
- # xyz-fixed Euler angle convention: matches ArduPilot AP_Math/Quaternion::from_euler
74
+ def from_euler(eul: Point) -> Quaternion:
75
+ '''Create a quaternion from a Point of Euler angles order z, y, x'''
76
+ eul = Point.type_check(eul).unwrap()
76
77
  half = eul * 0.5
77
78
  c = half.cos
78
79
  s = half.sin
@@ -86,18 +87,16 @@ class Quaternion(Base):
86
87
  ]).T
87
88
  )
88
89
 
89
- def to_euler(self):
90
-
91
- # roll (x-axis rotation)
90
+ def to_euler(self) -> Point:
91
+ '''Create a Point of Euler angles order z,y,x'''
92
92
  sinr_cosp = 2 * (self.w * self.x + self.y * self.z)
93
93
  cosr_cosp = 1 - 2 * (self.x * self.x + self.y * self.y)
94
94
  roll = np.arctan2(sinr_cosp, cosr_cosp)
95
95
 
96
- # pitch (y-axis rotation)
97
96
  sinp = 2 * (self.w * self.y - self.z * self.x)
98
- pitch = np.arcsin(sinp)
97
+ with np.errstate(invalid='ignore'):
98
+ pitch = np.arcsin(sinp)
99
99
 
100
- # yaw (z-axis rotation)
101
100
  siny_cosp = 2 * (self.w * self.z + self.x * self.y)
102
101
  cosy_cosp = 1 - 2 * (self.y * self.y + self.z * self.z)
103
102
  yaw = np.arctan2(siny_cosp, cosy_cosp)
@@ -111,7 +110,7 @@ class Quaternion(Base):
111
110
  return Point(roll, pitch, yaw)
112
111
 
113
112
  @staticmethod
114
- def from_axis_angle(axangles: Point):
113
+ def from_axis_angle(axangles: Point) -> Quaternion:
115
114
  small = 1e-6
116
115
  angles = abs(axangles)
117
116
 
@@ -132,43 +131,71 @@ class Quaternion(Base):
132
131
  #qdat[abs(Quaternions(qdat)) < .001] = np.array([[1, 0, 0, 0]])
133
132
  return Quaternion(qdat)
134
133
 
135
- def to_axis_angle(self):
134
+ def to_axis_angle(self) -> Point:
135
+ a = self._to_axis_angle()
136
+ b = (-self)._to_axis_angle()
137
+
138
+ res = a.data
139
+ replocs = abs(a)>abs(b)
140
+ res[replocs, :] = b.data[replocs, :]
141
+
142
+ return Point(res)
143
+
144
+ def _to_axis_angle(self) -> Point:
136
145
  """to a point of axis angles. must be normalized first."""
137
146
  angle = 2 * np.arccos(self.w)
138
147
  s = np.sqrt(1 - self.w**2)
139
148
  np.array(s)[np.array(s) < 1e-6] = 1.0
140
- return self.axis * angle / s
141
-
149
+ with np.errstate(divide="ignore", invalid='ignore'):
150
+ sangle = angle / s
151
+ sangle[sangle==np.inf] = 0
152
+ sangle[np.isnan(sangle)] = 0
153
+ res = self.axis * sangle
154
+ return res
142
155
 
143
156
  @staticmethod
144
- def axis_rates(q, qdot) -> Point:
157
+ def axis_rates(q: Quaternion, qdot: Quaternion) -> Point:
145
158
  wdash = qdot * q.conjugate()
146
159
  return wdash.norm().to_axis_angle()
147
160
 
148
161
  @staticmethod
149
- def body_axis_rates(q, qdot) -> Point:
162
+ def _axis_rates(q: Quaternion, qdot: Quaternion) -> Point:
163
+ wdash = qdot * q.conjugate()
164
+ return wdash.norm()._to_axis_angle()
165
+
166
+ @staticmethod
167
+ def body_axis_rates(q: Quaternion, qdot: Quaternion) -> Point:
150
168
  wdash = q.conjugate() * qdot
151
169
  return wdash.norm().to_axis_angle()
152
170
 
153
- def rotate(self, rate: Point):
171
+ @staticmethod
172
+ def _body_axis_rates(q: Quaternion, qdot: Quaternion) -> Point:
173
+ wdash = q.conjugate() * qdot
174
+ return wdash.norm()._to_axis_angle()
175
+
176
+ def rotate(self, rate: Point) -> Quaternion:
154
177
  return (Quaternion.from_axis_angle(rate) * self).norm()
155
178
 
156
- def body_rotate(self, rate: Point):
179
+ def body_rotate(self, rate: Point) -> Quaternion:
157
180
  return (self * Quaternion.from_axis_angle(rate)).norm()
158
181
 
159
- def diff(self, dt: np.array) -> Point:
182
+ def diff(self, dt: Number | npt.NDArray) -> Point:
160
183
  """differentiate in the world frame"""
184
+ if not pd.api.types.is_list_like(dt):
185
+ dt = np.full(len(self), dt)
161
186
  assert len(dt) == len(self)
162
187
  dt = dt * len(dt) / (len(dt) - 1)
163
188
 
164
- ps = Quaternion.axis_rates(
189
+ ps = Quaternion._axis_rates(
165
190
  Quaternion(self.data[:-1, :]),
166
191
  Quaternion(self.data[1:, :])
167
192
  ) / dt[:-1]
168
- return Point(np.vstack([ps.data, ps.data[-1,:]]))#.remove_outliers(2) # Bodge to get rid of phase jump
193
+ return Point(np.vstack([ps.data, ps.data[-1,:]]))
169
194
 
170
- def body_diff(self, dt: np.array) -> Point:
195
+ def body_diff(self, dt: Number | npt.NDArray) -> Point:
171
196
  """differentiate in the body frame"""
197
+ if not pd.api.types.is_list_like(dt):
198
+ dt = np.full(len(self), dt)
172
199
  assert len(dt) == len(self)
173
200
  dt = dt * len(dt) / (len(dt) - 1)
174
201
 
@@ -179,7 +206,7 @@ class Quaternion(Base):
179
206
  return Point(np.vstack([ps.data, ps.data[-1,:]]))
180
207
 
181
208
 
182
- def to_rotation_matrix(self):
209
+ def to_rotation_matrix(self) -> npt.NDArray[np.float64]:
183
210
  """http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
184
211
  https://github.com/mortlind/pymath3d/blob/master/math3d/quaternion.py
185
212
  """
@@ -193,7 +220,7 @@ class Quaternion(Base):
193
220
  ]).T
194
221
 
195
222
  @staticmethod
196
- def from_rotation_matrix(matrix: np.ndarray):
223
+ def from_rotation_matrix(matrix: npt.NDArray[np.float64]) -> Quaternion:
197
224
  # This method assumes row-vector and postmultiplication of that vector
198
225
  m = matrix.conj().transpose()
199
226
  if m[2, 2] < 0:
@@ -217,15 +244,12 @@ class Quaternion(Base):
217
244
  q *= 0.5 / np.sqrt(t)
218
245
  return Quaternion(*q)
219
246
 
220
- def __str__(self):
221
- return "W:{w:.2f}\nX:{x:.2f}\nY:{y:.2f}\nZ:{z:.2f}".format(w=self.w, x=self.x, y=self.y, z=self.z)
222
-
223
- def closest_principal(self):
247
+ def closest_principal(self) -> Quaternion:
224
248
  eul = self.to_euler()
225
249
  rads = eul * (2 / np.pi)
226
250
  return Quaternion.from_euler(rads.round(0) * np.pi/2)
227
251
 
228
- def is_inverted(self):
252
+ def is_inverted(self) -> bool:
229
253
  # does the rotation reverse the Z axis?
230
254
  return np.sign(self.transform_point(PZ()).z) > 0
231
255
 
geometry/time.py ADDED
@@ -0,0 +1,40 @@
1
+ from geometry import Base
2
+ from numbers import Number
3
+ from typing import Self
4
+ import numpy as np
5
+ from time import time
6
+
7
+
8
+ class Time(Base):
9
+ cols=["t", "dt"]
10
+
11
+ @staticmethod
12
+ def from_t(t: np.ndarray) -> Self:
13
+ if isinstance(t, Number):
14
+ return Time(t, 1/30)
15
+ else:
16
+ if len(t) == 1:
17
+ dt = np.array([1/30])
18
+ else:
19
+ arr = np.diff(t)
20
+ dt = np.concatenate([arr, [arr[-1]]])
21
+ return Time(t, dt)
22
+
23
+ def scale(self, duration) -> Self:
24
+ old_duration = self.t[-1] - self.t[0]
25
+ sfac = duration / old_duration
26
+ return Time(
27
+ self.t[0] + (self.t - self.t[0]) * sfac,
28
+ self.dt * sfac
29
+ )
30
+
31
+ def reset_zero(self):
32
+ return Time(self.t - self.t[0], self.dt)
33
+
34
+ @staticmethod
35
+ def now():
36
+ return Time.from_t(time())
37
+
38
+ def extend(self):
39
+ return Time.concatenate([self, Time(self.t[-1] + self.dt[-1], self.dt[-1])])
40
+
@@ -9,10 +9,11 @@ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9
9
  You should have received a copy of the GNU General Public License along with
10
10
  this program. If not, see <http://www.gnu.org/licenses/>.
11
11
  """
12
- from geometry import Base, Point, Quaternion, Point, P0, Q0, Coord
12
+ from geometry import Base, Point, Quaternion, P0, Q0, Coord
13
13
 
14
14
  import numpy as np
15
15
  from typing import Union
16
+ from typing import Self
16
17
 
17
18
 
18
19
  class Transformation(Base):
@@ -21,8 +22,16 @@ class Transformation(Base):
21
22
  def __init__(self, *args, **kwargs):
22
23
  if len(args) == len(kwargs) == 0:
23
24
  args = np.concatenate([P0().data,Q0().data],axis=1)
25
+ elif len(args) == 1:
26
+ if isinstance(args[0], Point):
27
+ args = np.concatenate([args[0].data,Q0().data],axis=1)
28
+ elif isinstance(args[0], Quaternion):
29
+ args = np.concatenate([P0().data,args[0].data],axis=1)
24
30
  if len(args) == 2:
25
- args = np.concatenate([args[0].data, args[1].data], axis=1)
31
+ _q = args[0] if isinstance(args[0], Quaternion) else args[1]
32
+ _p = args[0] if isinstance(args[0], Point) else args[1]
33
+ assert isinstance(_q, Quaternion) and isinstance(_p, Point), f'expected a Point and a Quaternion, got a {_p.__class__.__name__} and a {_q.__class__.__name__}'
34
+ args = np.concatenate([_p.data, _q.data], axis=1)
26
35
  super().__init__(*args, **kwargs)
27
36
  self.p = Point(self.data[:,:3])
28
37
  self.q = Quaternion(self.data[:,3:])
@@ -82,19 +91,24 @@ class Transformation(Base):
82
91
  )
83
92
 
84
93
 
85
- def apply(self, oin: Union[Point, Quaternion]):
94
+ def apply(self, oin: Union[Point, Quaternion, Self, Coord]):
86
95
  if isinstance(oin, Point):
87
96
  return self.point(oin)
88
97
  elif isinstance(oin, Quaternion):
89
98
  return self.rotate(oin)
99
+ elif isinstance(oin, Coord):
100
+ return self.coord(oin)
90
101
  elif isinstance(oin, self.__class__):
91
102
  return Transformation(self.apply(oin.p), self.apply(oin.q))
103
+
92
104
 
93
105
  def rotate(self, oin: Union[Point, Quaternion]):
94
106
  if isinstance(oin, Point):
95
107
  return self.q.transform_point(oin)
96
108
  elif isinstance(oin, Quaternion):
97
109
  return self.q * oin
110
+ else:
111
+ raise TypeError(f"expected a Point or a Quaternion, got a {oin.__class__.__name__}")
98
112
 
99
113
  def translate(self, point: Point):
100
114
  return point + self.p
@@ -102,8 +116,10 @@ class Transformation(Base):
102
116
  def point(self, point: Point):
103
117
  return self.translate(self.rotate(point))
104
118
 
105
- def coord(self, coord):
106
- return coord.translate(self.p).rotate(self.q.to_rotation_matrix())
119
+ def coord(self, coord=None):
120
+ if coord is None:
121
+ coord = Coord.zero()
122
+ return coord.translate(self.p).rotate(self.q)
107
123
 
108
124
 
109
125
  def to_matrix(self):
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.1
2
+ Name: pfc_geometry
3
+ Version: 0.2.4
4
+ Summary: A package for handling 3D geometry with a nice interface
5
+ Home-page: https://github.com/PyFlightCoach/geometry
6
+ Author: Thomas David
7
+ Author-email: thomasdavid0@gmail.com
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: setuptools
11
+ Requires-Dist: numpy
12
+ Requires-Dist: pandas
13
+
14
+ # geometry #
15
+
16
+ Tools for handling 3D geometry, mostly just adds a nice interface to various geometric enterties. Each geometric entity can also be a vector of geometric entities. Each entity wraps a numpy array with the relevant number of columns labelled according to the cols class property and rows equal to the number of elements in the vector. Attribute access to each column is available and returns a numpy array.
17
+
18
+ Where operations are supported between geometric types the size of the output is inferred based on the length of the inputs. Where the two vectors of entities are of the same length, elementwise operations are performed. Where one vector is length one and the other is greater than one then the operation will be performed on every element of the longer vector.
19
+
20
+ Magic methods are used extensively and the function of operators are logical for each type. If unsure what the logical option is then check the code where it should be pretty clear.
21
+
22
+ Many convenience methods and constructors are available. Documentation is limited but if you need something it has probably already been written so check the code first.
23
+
24
+
25
+ Some examples are available here: https://pfcdocumentation.readthedocs.io/pyflightcoach/geometry.html
26
+
27
+ now available on pypi:
28
+ ```bash
29
+ pip install pfc-geometry
30
+ ```
@@ -0,0 +1,15 @@
1
+ geometry/__init__.py,sha256=HNhMyemIJzDq1nDjrr09eX5PS7q9ULscSbYsXss3JRM,1253
2
+ geometry/base.py,sha256=ZgjOPv2QU6nBSEFurBXCIos0YVjEZhjjT-NTz06DCvo,11277
3
+ geometry/coordinate_frame.py,sha256=qO3jqUWF4PW4BOkw5rBMTXfOzBjlA1HYwGYmPtu2M8M,3039
4
+ geometry/gps.py,sha256=Fs3hakSQ754HUqRsA7NWg_MSEdYxNqyiu4gu6EDrFqI,3381
5
+ geometry/mass.py,sha256=BUWBSITwpdRfpJR5-oJTd16BI7FLZt8rhxdzr0cx1HY,1675
6
+ geometry/point.py,sha256=gwP9Jn80eSKmWE9Q2efS5oFYEGoO6XpBmPCFSOQ2j3Q,5025
7
+ geometry/quaternion.py,sha256=rw_9Fx9uKMMuGAWJjH1vU-iZzA15Vbn3HyzS4qV3oxY,9367
8
+ geometry/testing.py,sha256=o8yMBAdU5Vy0EspBYaof4fPGgRSFZhRDhzBjRPsLd0M,375
9
+ geometry/time.py,sha256=NdzVWdL7F3HpJb4MXYJ0uPHvgHqipVMTDTR-UVNx_wc,995
10
+ geometry/transformation.py,sha256=iCQRTC1sbH_TCRpm9d_PmGS8qxAne5LpGcCSeRpmcpM,4701
11
+ pfc_geometry-0.2.4.dist-info/LICENSE,sha256=z72U6pv-bQgJ_Svr4uCXnMjemsp38aSerhHEdEAOMJ4,7632
12
+ pfc_geometry-0.2.4.dist-info/METADATA,sha256=uyHMoGMgnSpAmPEcwQHjh_6AxVVqCZMQP0SebSx3HUE,1675
13
+ pfc_geometry-0.2.4.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
14
+ pfc_geometry-0.2.4.dist-info/top_level.txt,sha256=RWbWhWYclEM-OFtXLCB4eLv-jxNnlJB-NPC2YM587Fo,9
15
+ pfc_geometry-0.2.4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.38.4)
2
+ Generator: bdist_wheel (0.43.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
geometry/circle.py DELETED
@@ -1,28 +0,0 @@
1
- """
2
- This program is free software: you can redistribute it and/or modify it under
3
- the terms of the GNU General Public License as published by the Free Software
4
- Foundation, either version 3 of the License, or (at your option) any later
5
- version.
6
- This program is distributed in the hope that it will be useful, but WITHOUT
7
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8
- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9
- You should have received a copy of the GNU General Public License along with
10
- this program. If not, see <http://www.gnu.org/licenses/>.
11
- """
12
- from geometry import Point, Quaternion, Transformation
13
-
14
-
15
-
16
- class Circle():
17
- def __init__(self, radius: float, transform: Transformation):
18
- """The circle is about the Z axis, centre on the origin. The transformation
19
- defines the location of the axis.
20
-
21
- Args:
22
- radius (float): The radius of the circle
23
- transform (Transformation): The transformation to the circles axis (0,0,1)
24
- """
25
- self.radius = radius
26
- self.transform = transform
27
-
28
- #change