forked from rai-opensource/spatialmath-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumeric.py
More file actions
310 lines (247 loc) · 8.13 KB
/
numeric.py
File metadata and controls
310 lines (247 loc) · 8.13 KB
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
import numpy as np
from spatialmath import base
from functools import reduce
# this is a collection of useful algorithms, not otherwise categorized
def numjac(f, x, dx=1e-8, SO=0, SE=0):
r"""
Numerically compute Jacobian of function
:param f: the function, returns an m-vector
:type f: callable
:param x: function argument
:type x: ndarray(n)
:param dx: the numerical perturbation, defaults to 1e-8
:type dx: float, optional
:param SO: function returns SO(N) matrix, defaults to 0
:type SO: int, optional
:param SE: function returns SE(N) matrix, defaults to 0
:type SE: int, optional
:return: Jacobian matrix
:rtype: ndarray(m,n)
Computes a numerical approximation to the Jacobian for ``f(x)`` where
:math:`f: \mathbb{R}^n \mapsto \mathbb{R}^m`.
Uses first-order difference :math:`J[:,i] = (f(x + dx) - f(x)) / dx`.
If ``SO`` is 2 or 3, then it is assumed that the function returns
an SO(N) matrix and the derivative is converted to a column vector
.. math:
\vex \dmat{R} \mat{R}^T
If ``SE`` is 2 or 3, then it is assumed that the function returns
an SE(N) matrix and the derivative is converted to a colun vector.
"""
x = np.array(x)
Jcol = []
J0 = f(x)
I = np.eye(len(x))
f0 = np.array(f(x))
for i in range(len(x)):
fi = np.array(f(x + I[:, i] * dx))
Ji = (fi - f0) / dx
if SE > 0:
t = Ji[:SE, SE]
r = base.vex(Ji[:SE, :SE] @ J0[:SE, :SE].T)
Jcol.append(np.r_[t, r])
elif SO > 0:
R = Ji[:SO, :SO]
r = base.vex(R @ J0[:SO, :SO].T)
Jcol.append(r)
else:
Jcol.append(Ji)
# print(Ji)
return np.c_[Jcol].T
def numhess(J, x, dx=1e-8):
r"""
Numerically compute Hessian given Jacobian function
:param J: the Jacobian function, returns an ndarray(m,n)
:type J: callable
:param x: function argument
:type x: ndarray(n)
:param dx: the numerical perturbation, defaults to 1e-8
:type dx: float, optional
:return: Hessian matrix
:rtype: ndarray(m,n,n)
Computes a numerical approximation to the Hessian for ``J(x)`` where
:math:`f: \mathbb{R}^n \mapsto \mathbb{R}^{m \times n}`.
The result is a 3D array where
.. math::
H_{i,j,k} = \frac{\partial J_{j,k}}{\partial x_i}
Uses first-order difference :math:`H[:,:,i] = (J(x + dx) - J(x)) / dx`.
"""
I = np.eye(len(x))
Hcol = []
J0 = J(x)
for i in range(len(x)):
Ji = J(x + I[:,i] * dx)
Hi = (Ji - J0) / dx
Hcol.append(Hi)
return np.stack(Hcol, axis=0)
def array2str(X, valuesep=", ", rowsep=" | ", fmt="{:.3g}",
brackets=("[ ", " ]"), suppress_small=True):
"""
Convert array to single line string
:param X: 1D or 2D array to convert
:type X: ndarray(N,M), array_like(N)
:param valuesep: separator between numbers, defaults to ", "
:type valuesep: str, optional
:param rowsep: separator between rows, defaults to " | "
:type rowsep: str, optional
:param format: format string, defaults to "{:.3g}"
:type precision: str, optional
:param brackets: strings to be added to start and end of the string,
defaults to ("[ ", " ]"). Set to None to suppress brackets.
:type brackets: list, tuple of str
:param suppress_small: small values (:math:`|x| < 10^{-12}` are converted
to zero, defaults to True
:type suppress_small: bool, optional
:return: compact string representation of array
:rtype: str
Converts a small array to a compact single line representation.
"""
# convert to ndarray if not already
if isinstance(X, (list, tuple)):
X = base.getvector(X)
def format_row(x):
s = ""
for j, e in enumerate(x):
if abs(e) < 1e-12:
e = 0
if j > 0:
s += valuesep
s += fmt.format(e)
return s
if X.ndim == 1:
# 1D case
s = format_row(X)
else:
# 2D case
s = ""
for i, row in enumerate(X):
if i > 0:
s += rowsep
s += format_row(row)
if brackets is not None and len(brackets) == 2:
s = brackets[0] + s + brackets[1]
return s
def bresenham(p0, p1, array=None):
"""
Line drawing in a grid
:param p0: initial point
:type p0: array_like(2) of int
:param p1: end point
:type p1: array_like(2) of int
:return: arrays of x and y coordinates for points along the line
:rtype: ndarray(N), ndarray(N) of int
Return x and y coordinate vectors for points in a grid that lie on
a line from ``p0`` to ``p1`` inclusive.
The end points, and all points along the line are integers.
.. note:: The API is similar to the Bresenham algorithm but this
implementation uses NumPy vectorised arithmetic which makes it
faster than the Bresenham algorithm in Python.
"""
x0, y0 = p0
x1, y1 = p1
if array is not None:
_ = array[y0, x0] + array[y1, x1]
line = []
dx = x1 - x0
dy = y1 - y0
if abs(dx) >= abs(dy):
# shallow line -45° <= θ <= 45°
# y = mx + c
if dx == 0:
# case p0 == p1
x = np.r_[x0]
y = np.r_[y0]
else:
m = dy / dx
c = y0 - m * x0
if dx > 0:
# line to the right
x = np.arange(x0, x1 + 1)
elif dx < 0:
# line to the left
x = np.arange(x0, x1 - 1, -1)
y = np.round(x * m + c)
else:
# steep line θ < -45°, θ > 45°
# x = my + c
m = dx / dy
c = x0 - m * y0
if dy > 0:
# line to the right
y = np.arange(y0, y1 + 1)
elif dy < 0:
# line to the left
y = np.arange(y0, y1 - 1, -1)
x = np.round(y * m + c)
return x.astype(int), y.astype(int)
def mpq_point(data, p, q):
r"""
Moments of polygon
:param p: moment order x
:type p: int
:param q: moment order y
:type q: int
Returns the pq'th moment of the polygon
.. math::
M(p, q) = \sum_{i=0}^{n-1} x_i^p y_i^q
Example:
.. runblock:: pycon
>>> from spatialmath import Polygon2
>>> p = Polygon2([[1, 3, 2], [2, 2, 4]])
>>> p.moment(0, 0) # area
>>> p.moment(3, 0)
Note is negative for clockwise perimeter.
"""
x = data[0, :]
y = data[1, :]
return np.sum(x**p * y**q)
def gauss1d(mu, var, x):
"""
Gaussian function in 1D
:param mu: mean
:type mu: float
:param var: variance
:type var: float
:param x: x-coordinate values
:type x: array_like(n)
:return: Gaussian :math:`G(x)`
:rtype: ndarray(n)
:seealso: :func:`gauss2d`
"""
sigma = np.sqrt(var)
x = base.getvector(x)
return 1.0 / np.sqrt(sigma**2 * 2 * np.pi) * np.exp(-(x-mu)**2/2/sigma**2)
def gauss2d(mu, P, X, Y):
"""
Gaussian function in 2D
:param mu: mean
:type mu: array_like(2)
:param P: covariance matrix
:type P: ndarray(2,2)
:param X: array of x-coordinates
:type X: ndarray(n,m)
:param Y: array of y-coordinates
:type Y: ndarray(n,m)
:return: Gaussian :math:`g(x,y)`
:rtype: ndarray(n,m)
Computed :math:`g_{i,j} = G(x_{i,j}, y_{i,j})`
:seealso: :func:`gauss1d`
"""
x = X.ravel() - mu[0]
y = Y.ravel() - mu[1]
Pi = np.linalg.inv(P);
g = 1/(2*np.pi*np.sqrt(np.linalg.det(P))) * np.exp(
-0.5*(x**2 * Pi[0, 0] + y**2 * Pi[1, 1] + 2 * x * y * Pi[0, 1]));
return g.reshape(X.shape)
if __name__ == "__main__":
r = np.linspace(-4, 4, 6)
x, y = np.meshgrid(r, r)
print(gauss2d([0, 0], np.diag([1,2]), x, y))
# print(bresenham([2,2], [2,4]))
# print(bresenham([2,2], [2,-4]))
# print(bresenham([2,2], [4,2]))
# print(bresenham([2,2], [-4,2]))
# print(bresenham([2,2], [2,2]))
# print(bresenham([2,2], [3,6])) # steep
# print(bresenham([2,2], [6,3])) # shallow
# print(bresenham([2,2], [3,6])) # steep
# print(bresenham([2,2], [6,3])) # shallow