simplerobotics 1.0.5.2__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.
- SimpleRobotics/RobotRR.py +156 -0
- SimpleRobotics/__init__.py +37 -0
- SimpleRobotics/animation.py +427 -0
- SimpleRobotics/formatting.py +65 -0
- SimpleRobotics/plotting.py +1272 -0
- SimpleRobotics/transforms.py +865 -0
- simplerobotics-1.0.5.2.dist-info/METADATA +173 -0
- simplerobotics-1.0.5.2.dist-info/RECORD +10 -0
- simplerobotics-1.0.5.2.dist-info/WHEEL +5 -0
- simplerobotics-1.0.5.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
"""Rotaciones y traslaciones para robótica.
|
|
2
|
+
|
|
3
|
+
La API pública es única para valores numéricos y simbólicos:
|
|
4
|
+
- Si los argumentos son numéricos, las funciones devuelven ``numpy.ndarray``.
|
|
5
|
+
- Si algún argumento es una expresión de SymPy, devuelven matrices de SymPy.
|
|
6
|
+
- SymPy es opcional: solo se necesita para entradas simbólicas.
|
|
7
|
+
|
|
8
|
+
Convenciones:
|
|
9
|
+
- Los ángulos se expresan en radianes salvo en funciones con sufijo ``_grados``.
|
|
10
|
+
- Se utilizan vectores columna y matrices homogéneas 4x4.
|
|
11
|
+
- Las matrices siguen la convención de mano derecha.
|
|
12
|
+
- ``rotx3``, ``roty3`` y ``rotz3`` devuelven rotaciones 3x3.
|
|
13
|
+
- ``rotx``, ``roty`` y ``rotz`` devuelven rotaciones homogéneas 4x4.
|
|
14
|
+
- ``trans(x, y, z)`` devuelve una traslación homogénea 4x4.
|
|
15
|
+
- ``RPY(phi, theta, psi)`` sigue Rz(phi) @ Ry(theta) @ Rx(psi).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import math
|
|
21
|
+
from math import pi, atan2, sqrt, sin, cos
|
|
22
|
+
from typing import Any
|
|
23
|
+
import numpy as np
|
|
24
|
+
import sympy as sp
|
|
25
|
+
|
|
26
|
+
Array = np.ndarray
|
|
27
|
+
|
|
28
|
+
def deg2rad(valor_en_grados: float) -> float:
|
|
29
|
+
"""Convierte grados a radianes, conservando expresiones simbólicas."""
|
|
30
|
+
if _usa_sympy(valor_en_grados):
|
|
31
|
+
sp = _sympy()
|
|
32
|
+
return valor_en_grados * sp.pi / 180
|
|
33
|
+
return math.radians(valor_en_grados)
|
|
34
|
+
|
|
35
|
+
def rad2deg(valor_en_radianes: float) -> float:
|
|
36
|
+
"""Convierte radianes a grados, conservando expresiones simbólicas."""
|
|
37
|
+
if _usa_sympy(valor_en_radianes):
|
|
38
|
+
sp = _sympy()
|
|
39
|
+
return valor_en_radianes * 180 / sp.pi
|
|
40
|
+
return math.degrees(valor_en_radianes)
|
|
41
|
+
|
|
42
|
+
def _usa_sympy(*valores: Any) -> bool:
|
|
43
|
+
"""Detecta expresiones SymPy, también dentro de listas y arreglos de objetos."""
|
|
44
|
+
|
|
45
|
+
def contiene_simbolos(valor: Any) -> bool:
|
|
46
|
+
if type(valor).__module__.split(".", 1)[0] == "sympy":
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
if isinstance(valor, np.ndarray) and valor.dtype == object:
|
|
50
|
+
return any(contiene_simbolos(elemento) for elemento in valor.flat)
|
|
51
|
+
|
|
52
|
+
if isinstance(valor, (list, tuple)):
|
|
53
|
+
return any(contiene_simbolos(elemento) for elemento in valor)
|
|
54
|
+
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
return any(contiene_simbolos(valor) for valor in valores)
|
|
58
|
+
|
|
59
|
+
def _sympy():
|
|
60
|
+
"""Importa SymPy solo cuando una operación simbólica lo necesita."""
|
|
61
|
+
try:
|
|
62
|
+
import sympy
|
|
63
|
+
except ImportError as exc:
|
|
64
|
+
raise ImportError(
|
|
65
|
+
"Esta operación recibió valores simbólicos. Instala el extra con "
|
|
66
|
+
"'python -m pip install -e \".[symbolic]\"' para utilizar SymPy."
|
|
67
|
+
) from exc
|
|
68
|
+
return sympy
|
|
69
|
+
|
|
70
|
+
def _trig(theta: Any) -> tuple[Any, Any]:
|
|
71
|
+
"""Calcula coseno y seno con el backend apropiado para el argumento."""
|
|
72
|
+
if _usa_sympy(theta):
|
|
73
|
+
sp = _sympy()
|
|
74
|
+
return sp.cos(theta), sp.sin(theta)
|
|
75
|
+
return math.cos(theta), math.sin(theta)
|
|
76
|
+
|
|
77
|
+
def rotx3(theta: float) -> Array:
|
|
78
|
+
"""Devuelve una rotación 3x3 alrededor de X (radianes).
|
|
79
|
+
|
|
80
|
+
Acepta números o expresiones SymPy. El tipo de salida depende de la entrada.
|
|
81
|
+
"""
|
|
82
|
+
c, s = _trig(theta)
|
|
83
|
+
filas = [
|
|
84
|
+
[1, 0, 0],
|
|
85
|
+
[0, c, -s],
|
|
86
|
+
[0, s, c],
|
|
87
|
+
]
|
|
88
|
+
return _sympy().Matrix(filas) if _usa_sympy(theta) else np.array(filas, dtype=float)
|
|
89
|
+
|
|
90
|
+
def roty3(theta: float) -> Array:
|
|
91
|
+
"""Devuelve una rotación 3x3 alrededor de Y (radianes)."""
|
|
92
|
+
c, s = _trig(theta)
|
|
93
|
+
filas = [
|
|
94
|
+
[c, 0, s],
|
|
95
|
+
[0, 1, 0],
|
|
96
|
+
[-s, 0, c],
|
|
97
|
+
]
|
|
98
|
+
return _sympy().Matrix(filas) if _usa_sympy(theta) else np.array(filas, dtype=float)
|
|
99
|
+
|
|
100
|
+
def rotz3(theta: float) -> Array:
|
|
101
|
+
"""Devuelve una rotación 3x3 alrededor de Z (radianes)."""
|
|
102
|
+
c, s = _trig(theta)
|
|
103
|
+
filas = [
|
|
104
|
+
[c, -s, 0],
|
|
105
|
+
[s, c, 0],
|
|
106
|
+
[0, 0, 1],
|
|
107
|
+
]
|
|
108
|
+
return _sympy().Matrix(filas) if _usa_sympy(theta) else np.array(filas, dtype=float)
|
|
109
|
+
|
|
110
|
+
def _homogeneous_rotation(rotation: Any) -> Any:
|
|
111
|
+
"""Inserta una matriz de rotación 3x3 en una matriz homogénea 4x4.
|
|
112
|
+
|
|
113
|
+
Se revisan todos los elementos para detectar matrices simbólicas. En Rx,
|
|
114
|
+
por ejemplo, el elemento [0, 0] siempre es 1, incluso cuando el ángulo
|
|
115
|
+
es simbólico; revisar solo ese elemento seleccionaría incorrectamente NumPy.
|
|
116
|
+
"""
|
|
117
|
+
es_simbolica = any(
|
|
118
|
+
_usa_sympy(rotation[i, j])
|
|
119
|
+
for i in range(rotation.shape[0])
|
|
120
|
+
for j in range(rotation.shape[1])
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
if es_simbolica:
|
|
124
|
+
sp = _sympy()
|
|
125
|
+
result = sp.eye(4)
|
|
126
|
+
result[:3, :3] = rotation
|
|
127
|
+
return result
|
|
128
|
+
|
|
129
|
+
result = np.eye(4, dtype=float)
|
|
130
|
+
result[:3, :3] = rotation
|
|
131
|
+
return result
|
|
132
|
+
|
|
133
|
+
def rotx(theta: float) -> Array:
|
|
134
|
+
"""Devuelve una rotación homogénea 4x4 alrededor de X (radianes).
|
|
135
|
+
|
|
136
|
+
Con un ángulo numérico devuelve ``numpy.ndarray``; con uno simbólico,
|
|
137
|
+
devuelve una matriz SymPy. No se necesita una función ``rotx_sym`` aparte.
|
|
138
|
+
"""
|
|
139
|
+
return _homogeneous_rotation(rotx3(theta))
|
|
140
|
+
|
|
141
|
+
def roty(theta: float) -> Array:
|
|
142
|
+
"""Devuelve una rotación homogénea 4x4 alrededor de Y (radianes)."""
|
|
143
|
+
return _homogeneous_rotation(roty3(theta))
|
|
144
|
+
|
|
145
|
+
def rotz(theta: float) -> Array:
|
|
146
|
+
"""Devuelve una rotación homogénea 4x4 alrededor de Z (radianes).
|
|
147
|
+
|
|
148
|
+
Acepta valores numéricos y expresiones SymPy mediante la misma función.
|
|
149
|
+
"""
|
|
150
|
+
return _homogeneous_rotation(rotz3(theta))
|
|
151
|
+
|
|
152
|
+
def _normaliza_entero_float(valor: Any) -> Any:
|
|
153
|
+
"""Convierte floats que representan enteros exactos en enteros Python.
|
|
154
|
+
|
|
155
|
+
Por ejemplo, 2.0 pasa a 2. Esto evita que una traslación escrita con
|
|
156
|
+
literales como ``trans(1.0, 2.0, 3.0)`` introduzca ``Float`` en una
|
|
157
|
+
expresión de SymPy al multiplicarse después por una rotación simbólica.
|
|
158
|
+
Los valores fraccionarios y no finitos se conservan sin cambios.
|
|
159
|
+
"""
|
|
160
|
+
if isinstance(valor, (float, np.floating)):
|
|
161
|
+
numero = float(valor)
|
|
162
|
+
if math.isfinite(numero) and numero.is_integer():
|
|
163
|
+
return int(numero)
|
|
164
|
+
return valor
|
|
165
|
+
|
|
166
|
+
def trans(x: float, y: float, z: float) -> Array:
|
|
167
|
+
"""Devuelve una traslación homogénea 4x4 para (x, y, z).
|
|
168
|
+
|
|
169
|
+
Si alguna coordenada es simbólica, devuelve una matriz SymPy. Los
|
|
170
|
+
floats que representan enteros exactos se normalizan para evitar
|
|
171
|
+
decimales innecesarios en composiciones simbólicas.
|
|
172
|
+
"""
|
|
173
|
+
x, y, z = (_normaliza_entero_float(v) for v in (x, y, z))
|
|
174
|
+
filas = [
|
|
175
|
+
[1, 0, 0, x],
|
|
176
|
+
[0, 1, 0, y],
|
|
177
|
+
[0, 0, 1, z],
|
|
178
|
+
[0, 0, 0, 1],
|
|
179
|
+
]
|
|
180
|
+
if _usa_sympy(x, y, z):
|
|
181
|
+
return _sympy().Matrix(filas)
|
|
182
|
+
|
|
183
|
+
# Los enteros se conservan como enteros; una coordenada fraccionaria
|
|
184
|
+
# hace que NumPy seleccione el tipo numérico que corresponde.
|
|
185
|
+
dtype = np.asarray([x, y, z]).dtype
|
|
186
|
+
result = np.eye(4, dtype=dtype)
|
|
187
|
+
result[:3, 3] = [x, y, z]
|
|
188
|
+
return result
|
|
189
|
+
|
|
190
|
+
def Rot_RPY(phi: float, theta: float, psi: float) -> Array:
|
|
191
|
+
"""Compone la rotación RPY: Rz(phi) @ Ry(theta) @ Rx(psi).
|
|
192
|
+
|
|
193
|
+
Los ángulos se expresan en radianes. Si alguno es simbólico, la operación
|
|
194
|
+
completa se realiza con matrices SymPy; de lo contrario usa NumPy.
|
|
195
|
+
"""
|
|
196
|
+
if _usa_sympy(phi, theta, psi):
|
|
197
|
+
sp = _sympy()
|
|
198
|
+
phi, theta, psi = (sp.sympify(v) for v in (phi, theta, psi))
|
|
199
|
+
return rotz3(phi) @ roty3(theta) @ rotx3(psi)
|
|
200
|
+
|
|
201
|
+
def Rot_RPY_grados(phi: float, theta: float, psi: float) -> Array:
|
|
202
|
+
"""Compone una rotación RPY; recibe los tres ángulos en grados."""
|
|
203
|
+
if _usa_sympy(phi, theta, psi):
|
|
204
|
+
sp = _sympy()
|
|
205
|
+
factor = sp.pi / 180
|
|
206
|
+
return Rot_RPY(phi * factor, theta * factor, psi * factor)
|
|
207
|
+
return Rot_RPY(math.radians(phi), math.radians(theta), math.radians(psi))
|
|
208
|
+
|
|
209
|
+
def Rot_eje(k: Any, theta: Any) -> Array:
|
|
210
|
+
|
|
211
|
+
if len(k) != 3:
|
|
212
|
+
raise ValueError("El eje k debe tener exactamente 3 componentes.")
|
|
213
|
+
|
|
214
|
+
kx, ky, kz = k
|
|
215
|
+
|
|
216
|
+
es_simbolica = _usa_sympy(kx, ky, kz, theta)
|
|
217
|
+
|
|
218
|
+
if es_simbolica:
|
|
219
|
+
|
|
220
|
+
sp = _sympy()
|
|
221
|
+
kx, ky, kz, theta = (
|
|
222
|
+
sp.sympify(v) for v in (kx, ky, kz, theta)
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
c, s = _trig(theta)
|
|
226
|
+
Vt = 1 - c
|
|
227
|
+
|
|
228
|
+
filas = [
|
|
229
|
+
[kx*kx*Vt+c, kx*ky*Vt-kz*s, kx*kz*Vt+ky*s],
|
|
230
|
+
[kx*ky*Vt+kz*s, ky*ky*Vt+c, ky*kz*Vt-kx*s],
|
|
231
|
+
[kx*kz*Vt-ky*s, ky*kz*Vt+kx*s, kz*kz*Vt+c]
|
|
232
|
+
]
|
|
233
|
+
return _sympy().Matrix(filas) if es_simbolica else np.array(filas, dtype=float)
|
|
234
|
+
|
|
235
|
+
def Rot_eje_grados(k: Any, theta: Any,) -> Array:
|
|
236
|
+
|
|
237
|
+
if _usa_sympy(k[0], k[1], k[2], theta):
|
|
238
|
+
|
|
239
|
+
sp = _sympy()
|
|
240
|
+
theta_rad = sp.simplify(theta) * sp.pi / 180
|
|
241
|
+
|
|
242
|
+
else:
|
|
243
|
+
|
|
244
|
+
theta_rad = np.deg2rad(theta)
|
|
245
|
+
|
|
246
|
+
return Rot_eje(k, theta_rad)
|
|
247
|
+
|
|
248
|
+
def Eje_theta(H: Any) -> tuple[Any, Any]:
|
|
249
|
+
|
|
250
|
+
es_simbolica = _usa_sympy(H)
|
|
251
|
+
|
|
252
|
+
if es_simbolica:
|
|
253
|
+
|
|
254
|
+
sp = _sympy()
|
|
255
|
+
H_sym = sp.Matrix(H)
|
|
256
|
+
|
|
257
|
+
if H_sym.shape != (4, 4):
|
|
258
|
+
raise ValueError("H debe ser una matriz de transformación 4x4.")
|
|
259
|
+
|
|
260
|
+
R_sym = H_sym[:3, :3]
|
|
261
|
+
|
|
262
|
+
if R_sym.free_symbols:
|
|
263
|
+
|
|
264
|
+
trace = sum(R_sym[i, i] for i in range(3))
|
|
265
|
+
theta = sp.acos((trace - 1) / 2)
|
|
266
|
+
|
|
267
|
+
Lambda = sp.Matrix([
|
|
268
|
+
(R_sym[2, 1] - R_sym[1, 2]) / (2 * sp.sin(theta)),
|
|
269
|
+
(R_sym[0, 2] - R_sym[2, 0]) / (2 * sp.sin(theta)),
|
|
270
|
+
(R_sym[1, 0] - R_sym[0, 1]) / (2 * sp.sin(theta))
|
|
271
|
+
])
|
|
272
|
+
|
|
273
|
+
norma = sp.sqrt(sum(componente**2 for componente in Lambda))
|
|
274
|
+
Lambda = Lambda / norma
|
|
275
|
+
|
|
276
|
+
return Lambda, theta
|
|
277
|
+
|
|
278
|
+
else:
|
|
279
|
+
|
|
280
|
+
H = np.eye(4, dtype=float)
|
|
281
|
+
H[:3, :3] = np.asarray(R_sym.tolist(), dtype=float)
|
|
282
|
+
|
|
283
|
+
else:
|
|
284
|
+
|
|
285
|
+
H = np.asarray(H, dtype=float)
|
|
286
|
+
|
|
287
|
+
if H.shape != (4, 4):
|
|
288
|
+
|
|
289
|
+
raise ValueError("H debe ser una matriz de trasformacion homogenea")
|
|
290
|
+
|
|
291
|
+
R = H[:3, :3]
|
|
292
|
+
|
|
293
|
+
val_cos = (np.trace(R) - 1) / 2
|
|
294
|
+
val_cos = max(-1.0, min(1.0, float(val_cos)))
|
|
295
|
+
theta = math.acos(val_cos)
|
|
296
|
+
|
|
297
|
+
tol = 1e-6
|
|
298
|
+
|
|
299
|
+
if theta < tol:
|
|
300
|
+
|
|
301
|
+
theta = 0.0
|
|
302
|
+
Lambda = np.array([1.0, 0.0, 0.0])
|
|
303
|
+
|
|
304
|
+
elif abs(theta - pi) < tol:
|
|
305
|
+
|
|
306
|
+
theta = pi
|
|
307
|
+
|
|
308
|
+
abs_lx = sqrt(max(0.0, (R[0, 0] + 1) / 2))
|
|
309
|
+
abs_ly = sqrt(max(0.0, (R[1, 1] + 1) / 2))
|
|
310
|
+
abs_lz = sqrt(max(0.0, (R[2, 2] + 1) / 2))
|
|
311
|
+
|
|
312
|
+
if abs_lx >= abs_ly and abs_lx >= abs_lz:
|
|
313
|
+
|
|
314
|
+
lx = abs_lx
|
|
315
|
+
ly = R[0, 1] / (2 * lx)
|
|
316
|
+
lz = R[0, 2] / (2 * lx)
|
|
317
|
+
|
|
318
|
+
elif abs_ly >= abs_lx and abs_ly >= abs_lz:
|
|
319
|
+
|
|
320
|
+
ly = abs_ly
|
|
321
|
+
lx = R[0, 1] / (2 * ly)
|
|
322
|
+
lz = R[1, 2] / (2 * ly)
|
|
323
|
+
|
|
324
|
+
else:
|
|
325
|
+
lz = abs_lz
|
|
326
|
+
lx = R[0, 2] / (2 * lz)
|
|
327
|
+
ly = R[1, 2] / (2 * lz)
|
|
328
|
+
|
|
329
|
+
Lambda = np.array([lx, ly, lz], dtype=float)
|
|
330
|
+
|
|
331
|
+
else:
|
|
332
|
+
|
|
333
|
+
lx = (R[2, 1] - R[1, 2]) / (2 * math.sin(theta))
|
|
334
|
+
ly = (R[0, 2] - R[2, 0]) / (2 * math.sin(theta))
|
|
335
|
+
lz = (R[1, 0] - R[0, 1]) / (2 * math.sin(theta))
|
|
336
|
+
|
|
337
|
+
Lambda = np.array([lx, ly, lz], dtype=float)
|
|
338
|
+
|
|
339
|
+
norma = np.linalg.norm(Lambda)
|
|
340
|
+
|
|
341
|
+
if norma == 0 or not math.isfinite(norma):
|
|
342
|
+
raise ValueError("No se pudo calcular un eje de rotación válido. "
|
|
343
|
+
"Comprueba que H represente una transformación rígida.")
|
|
344
|
+
|
|
345
|
+
Lambda = Lambda / norma
|
|
346
|
+
|
|
347
|
+
return Lambda, theta
|
|
348
|
+
|
|
349
|
+
def Eje_theta_grados(H: Any) -> tuple[Any, Any]:
|
|
350
|
+
|
|
351
|
+
Lambda, theta = Eje_theta(H)
|
|
352
|
+
|
|
353
|
+
return Lambda, rad2deg(theta)
|
|
354
|
+
|
|
355
|
+
def RPY(H: Any) -> tuple[Any, Any, Any]:
|
|
356
|
+
|
|
357
|
+
es_simbolica = _usa_sympy(H)
|
|
358
|
+
R = H[:3, :3]
|
|
359
|
+
|
|
360
|
+
if es_simbolica:
|
|
361
|
+
sp = _sympy()
|
|
362
|
+
Yaw = sp.atan2(R[2,1],R[2,2])
|
|
363
|
+
Roll = sp.atan2(R[1,0], R[0,0])
|
|
364
|
+
Pitch = sp.atan2(-R[2,0],sp.sqrt(R[0,0]**2 + (R[1,0])**2))
|
|
365
|
+
else:
|
|
366
|
+
|
|
367
|
+
r31 = R[2, 0]
|
|
368
|
+
tol = 1e-6
|
|
369
|
+
|
|
370
|
+
if abs(r31 + 1) < tol:
|
|
371
|
+
|
|
372
|
+
Pitch = pi / 2
|
|
373
|
+
Yaw = 0
|
|
374
|
+
Roll = math.atan2(R[1, 2], R[1, 1])
|
|
375
|
+
|
|
376
|
+
elif abs(r31 - 1) < tol:
|
|
377
|
+
|
|
378
|
+
Pitch = -pi / 2
|
|
379
|
+
Yaw = 0
|
|
380
|
+
Roll = math.atan2(-R[1, 2], R[1, 1])
|
|
381
|
+
|
|
382
|
+
else:
|
|
383
|
+
Yaw = math.atan2(R[2,1],R[2,2])
|
|
384
|
+
Roll = math.atan2(R[1,0], R[0,0])
|
|
385
|
+
Pitch = math.atan2(-R[2,0],sqrt(R[0,0]**2 + (R[1,0])**2))
|
|
386
|
+
|
|
387
|
+
return Roll, Pitch, Yaw
|
|
388
|
+
|
|
389
|
+
def RPY_grados(H: Any) -> tuple[Any, Any, Any]:
|
|
390
|
+
|
|
391
|
+
Roll, Pitch, Yaw=RPY(H)
|
|
392
|
+
|
|
393
|
+
return rad2deg(Roll), rad2deg(Pitch), rad2deg(Yaw)
|
|
394
|
+
|
|
395
|
+
def DH(theta: Any, d: Any, a: Any, alpha: Any) -> Array:
|
|
396
|
+
|
|
397
|
+
M = rotz(theta)@trans(a,0,d)@rotx(alpha)
|
|
398
|
+
return M
|
|
399
|
+
|
|
400
|
+
def H_inv(H: Any) -> Array:
|
|
401
|
+
|
|
402
|
+
R = H[:3, :3]
|
|
403
|
+
d = H[:3, 3]
|
|
404
|
+
es_simbolica = _usa_sympy(R, d)
|
|
405
|
+
|
|
406
|
+
if es_simbolica:
|
|
407
|
+
sp = _sympy()
|
|
408
|
+
|
|
409
|
+
R = sp.Matrix(R)
|
|
410
|
+
d = sp.Matrix(d).reshape(3, 1)
|
|
411
|
+
|
|
412
|
+
Rt = R.T
|
|
413
|
+
superior = Rt.row_join(-(Rt @ d))
|
|
414
|
+
inferior = sp.Matrix([[0, 0, 0, 1]])
|
|
415
|
+
|
|
416
|
+
Hi = superior.col_join(inferior)
|
|
417
|
+
|
|
418
|
+
else:
|
|
419
|
+
R = np.asarray(R, dtype=float)
|
|
420
|
+
d = np.asarray(d, dtype=float).reshape(3, 1)
|
|
421
|
+
|
|
422
|
+
Rt = R.T
|
|
423
|
+
superior = np.hstack((Rt, -(Rt @ d)))
|
|
424
|
+
inferior = np.array([[0, 0, 0, 1]])
|
|
425
|
+
|
|
426
|
+
Hi = np.vstack((superior, inferior))
|
|
427
|
+
|
|
428
|
+
return Hi
|
|
429
|
+
|
|
430
|
+
def Rot_Q(e1: float, e2: float, e3: float, e4: float) -> Array:
|
|
431
|
+
"""Devuelve una rotación 3x3 alrededor a partir de los componentes de un cuaternion."""
|
|
432
|
+
filas = [
|
|
433
|
+
[e1**2+e2**2-e3**2-e4**2, 2*(e2*e3+e1*e4), 2*(e2*e4-e1*e3)],
|
|
434
|
+
[2*(e2*e3-e1*e4), e1**2-e2**2+e3**2-e4**2, 2*(e1*e2+e3*e4)],
|
|
435
|
+
[2*(e1*e3+e2*e4), 2*(e3*e4-e1*e2), e1**2-e2**2-e3**2+e4**2],
|
|
436
|
+
]
|
|
437
|
+
|
|
438
|
+
return _sympy().Matrix(filas) if _usa_sympy(e1, e2, e3, e4) else np.array(filas, dtype=float)
|
|
439
|
+
|
|
440
|
+
def Quaternions(H: Array) -> tuple[Any, Any, Any, Any]:
|
|
441
|
+
|
|
442
|
+
R = H[:3,:3]
|
|
443
|
+
trace = R[0, 0] + R[1, 1] + R[2, 2]
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
e1 = (
|
|
447
|
+
_sympy().sqrt((trace + 1) / 4)
|
|
448
|
+
if _usa_sympy(H)
|
|
449
|
+
else np.sqrt((trace + 1) / 4)
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
e2 = (R[1,2]-R[2,1])/(4*e1)
|
|
453
|
+
e3 = (R[2,0]-R[0,2])/(4*e1)
|
|
454
|
+
e4 = (R[0,1]-R[1,0])/(4*e1)
|
|
455
|
+
|
|
456
|
+
return e1, e2, e3, e4
|
|
457
|
+
|
|
458
|
+
def Axis2Quaternions(Lambda: Any, theta: float) -> tuple[Any, Any, Any, Any]:
|
|
459
|
+
|
|
460
|
+
# Función que convierte los parámetros de Rodrigues (theta, lambda) a cuaterniones
|
|
461
|
+
|
|
462
|
+
es_simbolica = _usa_sympy(*Lambda, theta)
|
|
463
|
+
|
|
464
|
+
if es_simbolica:
|
|
465
|
+
sp = _sympy()
|
|
466
|
+
|
|
467
|
+
if isinstance(Lambda, sp.MatrixBase):
|
|
468
|
+
|
|
469
|
+
componentes = list(Lambda)
|
|
470
|
+
|
|
471
|
+
else:
|
|
472
|
+
|
|
473
|
+
componentes = np.asarray(Lambda, dtype=object).reshape(-1).tolist()
|
|
474
|
+
|
|
475
|
+
if len(componentes) != 3:
|
|
476
|
+
|
|
477
|
+
raise ValueError("Lambda debe contener 3 elementos")
|
|
478
|
+
|
|
479
|
+
l1, l2, l3, theta = (sp.sympify(valor) for valor in (*componentes, theta))
|
|
480
|
+
|
|
481
|
+
c = sp.cos(theta / 2)
|
|
482
|
+
s = sp.sin(theta / 2)
|
|
483
|
+
|
|
484
|
+
else:
|
|
485
|
+
componentes = np.asarray(Lambda, dtype=float).reshape(-1)
|
|
486
|
+
|
|
487
|
+
if componentes.size != 3:
|
|
488
|
+
raise ValueError("Lambda debe contener 3 elementos")
|
|
489
|
+
|
|
490
|
+
l1, l2, l3 = (float(valor) for valor in componentes)
|
|
491
|
+
|
|
492
|
+
c, s = _trig(float(theta) / 2)
|
|
493
|
+
|
|
494
|
+
e1 = -c
|
|
495
|
+
e2 = l1 * s
|
|
496
|
+
e3 = l2 * s
|
|
497
|
+
e4 = l3 * s
|
|
498
|
+
|
|
499
|
+
return e1, e2, e3, e4
|
|
500
|
+
|
|
501
|
+
def derivada_numerica(q: float, t:float) -> Any:
|
|
502
|
+
|
|
503
|
+
q = np.asarray(q, dtype=float).reshape(-1)
|
|
504
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
505
|
+
|
|
506
|
+
if q.size != t.size:
|
|
507
|
+
raise ValueError("q y t deben tener la misma cantidad de muestras.")
|
|
508
|
+
|
|
509
|
+
if t.size < 2:
|
|
510
|
+
raise ValueError("Se necesitan al menos 2 muestras.")
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
qp = t * 0
|
|
514
|
+
|
|
515
|
+
for x in range(1, len(t) - 1):
|
|
516
|
+
|
|
517
|
+
qp[x] = (q[x] - q[x - 1]) / (t[x] - t[x - 1])
|
|
518
|
+
|
|
519
|
+
qp[-1] = qp[-2]
|
|
520
|
+
|
|
521
|
+
return qp
|
|
522
|
+
|
|
523
|
+
def derivada_numerica2(q: float, t:float) -> Any:
|
|
524
|
+
|
|
525
|
+
q = np.asarray(q, dtype=float).reshape(-1)
|
|
526
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
527
|
+
|
|
528
|
+
if q.size != t.size:
|
|
529
|
+
raise ValueError("q y t deben tener la misma cantidad de muestras.")
|
|
530
|
+
|
|
531
|
+
if t.size < 2:
|
|
532
|
+
raise ValueError("Se necesitan al menos 2 muestras.")
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
qp = t * 0
|
|
536
|
+
|
|
537
|
+
for x in range(1, len(t) - 1):
|
|
538
|
+
|
|
539
|
+
qp[x] = (q[x] - q[x-1]) / (t[x] - t[x-1])
|
|
540
|
+
|
|
541
|
+
qp[-1] = qp[-2]
|
|
542
|
+
qp[0] = qp[1]
|
|
543
|
+
|
|
544
|
+
return qp
|
|
545
|
+
|
|
546
|
+
def derivada_numerica_central(q: float, t:float) -> Any:
|
|
547
|
+
|
|
548
|
+
q = np.asarray(q, dtype=float).reshape(-1)
|
|
549
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
550
|
+
|
|
551
|
+
if q.size != t.size:
|
|
552
|
+
raise ValueError("q y t deben tener la misma cantidad de muestras.")
|
|
553
|
+
|
|
554
|
+
if t.size < 2:
|
|
555
|
+
raise ValueError("Se necesitan al menos 2 muestras.")
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
qp = t * 0
|
|
559
|
+
|
|
560
|
+
for x in range(1, len(t) - 1):
|
|
561
|
+
|
|
562
|
+
qp[x] = (q[x+1] - q[x - 1]) / (t[x+1] - t[x - 1])
|
|
563
|
+
|
|
564
|
+
qp[-1] = qp[-2]
|
|
565
|
+
qp[0] = qp[1]
|
|
566
|
+
|
|
567
|
+
return qp
|
|
568
|
+
|
|
569
|
+
def interpolacion_cubica(q_i: float, q_f: float, qp_i: float, qp_f: float, t_i: float, t_f: float, t: float) -> Any:
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
573
|
+
|
|
574
|
+
if t.size == 0:
|
|
575
|
+
|
|
576
|
+
raise ValueError("El vector t no puede estar vacio")
|
|
577
|
+
|
|
578
|
+
T = t_f - t_i
|
|
579
|
+
|
|
580
|
+
if T == 0:
|
|
581
|
+
raise ValueError("t_f y t_i no pueden ser iguales.")
|
|
582
|
+
|
|
583
|
+
a = q_i
|
|
584
|
+
b = qp_i
|
|
585
|
+
|
|
586
|
+
c = (3 / T**2) * (q_f - q_i) - (2 / T**2) * qp_i - (1 / T**2) * qp_f
|
|
587
|
+
d = (-2 /T**3) * (q_f - q_i) + (1/T**2) * (qp_i + qp_f)
|
|
588
|
+
|
|
589
|
+
Q = a + b * (t - t_i) + c * (t - t_i)**2 + d * (t - t_i)**3
|
|
590
|
+
|
|
591
|
+
return Q
|
|
592
|
+
|
|
593
|
+
def interpolacion_cubica_vector(q_i: float, q_f: float, qp_i: float, qp_f: float, t: float) -> tuple[np.ndarray, np.ndarray]:
|
|
594
|
+
|
|
595
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
596
|
+
|
|
597
|
+
if t.size == 0:
|
|
598
|
+
|
|
599
|
+
raise ValueError("El vector t no puede estar vacio")
|
|
600
|
+
|
|
601
|
+
t_i = t[0]
|
|
602
|
+
t_f = t[-1]
|
|
603
|
+
|
|
604
|
+
T = t_f - t_i
|
|
605
|
+
|
|
606
|
+
if T == 0:
|
|
607
|
+
raise ValueError("t_f y t_i no pueden ser iguales.")
|
|
608
|
+
|
|
609
|
+
a = q_i
|
|
610
|
+
b = qp_i
|
|
611
|
+
|
|
612
|
+
c = (3 / T**2) * (q_f - q_i) - (2 / T**2) * qp_i - (1 / T**2) * qp_f
|
|
613
|
+
d = (-2 /T**3) * (q_f - q_i) + (1/T**2) * (qp_i + qp_f)
|
|
614
|
+
|
|
615
|
+
Q = np.zeros_like(t)
|
|
616
|
+
|
|
617
|
+
for x in range(len(t)):
|
|
618
|
+
|
|
619
|
+
Q[x] = a + b * (t[x] - t_i) + c * (t[x] - t_i)**2 + d * (t[x] - t_i)**3
|
|
620
|
+
|
|
621
|
+
Qp = derivada_numerica(Q, t)
|
|
622
|
+
|
|
623
|
+
return Q, Qp
|
|
624
|
+
|
|
625
|
+
def interpolacion_lineal(q_i: float, q_f: float, t_i: float, t_f: float, t: float) -> Any:
|
|
626
|
+
|
|
627
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
628
|
+
|
|
629
|
+
if t.size == 0:
|
|
630
|
+
raise ValueError("El vector t no puede estar vacio")
|
|
631
|
+
|
|
632
|
+
T = t_f - t_i
|
|
633
|
+
|
|
634
|
+
if T == 0:
|
|
635
|
+
raise ValueError("t_f y t_i no pueden ser iguales.")
|
|
636
|
+
|
|
637
|
+
Q = (q_f - q_i) * (t - t_i ) / T + q_i
|
|
638
|
+
|
|
639
|
+
return Q
|
|
640
|
+
|
|
641
|
+
def interpolacion_lineal_vector(q_i: float, q_f: float, t: float) -> tuple[np.ndarray, np.ndarray]:
|
|
642
|
+
|
|
643
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
644
|
+
|
|
645
|
+
if t.size < 2:
|
|
646
|
+
raise ValueError("Se necesitan 2 muestras")
|
|
647
|
+
|
|
648
|
+
t_i = t[0]
|
|
649
|
+
t_f = t[-1]
|
|
650
|
+
|
|
651
|
+
T = t_f - t_i
|
|
652
|
+
|
|
653
|
+
if T == 0:
|
|
654
|
+
raise ValueError("t_f y t_i no pueden ser iguales.")
|
|
655
|
+
|
|
656
|
+
Q = np.zeros_like(t)
|
|
657
|
+
|
|
658
|
+
for x in range(len(t)):
|
|
659
|
+
|
|
660
|
+
Q[x] = (q_f-q_i)*(t[x]-t_i)/T+q_i
|
|
661
|
+
|
|
662
|
+
if t.size == 2:
|
|
663
|
+
Qp = np.zeros_like(Q)
|
|
664
|
+
|
|
665
|
+
else:
|
|
666
|
+
Qp = derivada_numerica(Q, t)
|
|
667
|
+
|
|
668
|
+
return Q, Qp
|
|
669
|
+
|
|
670
|
+
def interpolacion_tramos(q_i: float, q_f: float, Vmax: float, Amax: float, t:Any) -> Any:
|
|
671
|
+
|
|
672
|
+
if Vmax <= 0 or Amax <= 0:
|
|
673
|
+
raise ValueError("Vmax y Amax deben ser positivos")
|
|
674
|
+
|
|
675
|
+
t = float(t)
|
|
676
|
+
|
|
677
|
+
s = np.sign(q_f - q_i)
|
|
678
|
+
|
|
679
|
+
Tau = Vmax / Amax
|
|
680
|
+
|
|
681
|
+
T = s * (q_f - q_i)/ Vmax + Vmax / Amax
|
|
682
|
+
|
|
683
|
+
if t <= Tau:
|
|
684
|
+
|
|
685
|
+
Q = q_i + s * ((Amax / 2) * t**2)
|
|
686
|
+
|
|
687
|
+
elif (T - Tau) <= t:
|
|
688
|
+
|
|
689
|
+
Q = q_f + s * (-(Amax * T**2)/2 + Amax * T * t - (Amax/2) * t**2)
|
|
690
|
+
|
|
691
|
+
else:
|
|
692
|
+
|
|
693
|
+
Q = (q_i - s * (Vmax**2/(2*Amax)) + s * Vmax * t)
|
|
694
|
+
|
|
695
|
+
return Q
|
|
696
|
+
|
|
697
|
+
def interpolacion_tramos_vector(q_i: float, q_f: float, Vmax: float, Amax: float, t:Any) ->tuple[np.ndarray, np.ndarray]:
|
|
698
|
+
|
|
699
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
700
|
+
|
|
701
|
+
if t.size == 0:
|
|
702
|
+
raise ValueError("El vector t no puede estar vacio")
|
|
703
|
+
|
|
704
|
+
if Vmax <= 0 or Amax <= 0:
|
|
705
|
+
raise ValueError("Vmax y Amax deben ser positivos")
|
|
706
|
+
|
|
707
|
+
s = np.sign(q_f - q_i)
|
|
708
|
+
|
|
709
|
+
Tau = Vmax / Amax
|
|
710
|
+
|
|
711
|
+
T = s * (q_f - q_i)/ Vmax + Vmax / Amax
|
|
712
|
+
|
|
713
|
+
Q = np.zeros_like(t)
|
|
714
|
+
|
|
715
|
+
for x in range(len(t)):
|
|
716
|
+
|
|
717
|
+
if t[x] <= Tau:
|
|
718
|
+
|
|
719
|
+
Q[x] = q_i + s * ((Amax / 2) * t[x]**2)
|
|
720
|
+
|
|
721
|
+
elif (T - Tau) <= t[x]:
|
|
722
|
+
|
|
723
|
+
Q[x] = q_f + s * (-(Amax * T**2)/2 + Amax * T * t[x] - (Amax/2) * t[x]**2)
|
|
724
|
+
|
|
725
|
+
else:
|
|
726
|
+
|
|
727
|
+
Q[x] = (q_i - s * (Vmax**2/(2*Amax)) + s * Vmax * t[x])
|
|
728
|
+
|
|
729
|
+
Qp = derivada_numerica(Q, t)
|
|
730
|
+
|
|
731
|
+
return Q, Qp
|
|
732
|
+
|
|
733
|
+
def Energia_robot(qp: Any, tau: Any, t: Any) -> Any:
|
|
734
|
+
|
|
735
|
+
# Función para calcular la energia del robot
|
|
736
|
+
|
|
737
|
+
qp = np.asarray(qp, dtype=float)
|
|
738
|
+
tau = np.asarray(tau, dtype=float)
|
|
739
|
+
t = np.asarray(t, dtype=float).reshape(-1)
|
|
740
|
+
|
|
741
|
+
if qp.ndim != 2:
|
|
742
|
+
raise ValueError("qp debe ser una matriz bidimensional.")
|
|
743
|
+
|
|
744
|
+
if tau.shape != qp.shape:
|
|
745
|
+
raise ValueError("tau debe tener las mismas dimensiones que qp.")
|
|
746
|
+
|
|
747
|
+
nmuestras, nsenales = qp.shape
|
|
748
|
+
|
|
749
|
+
Energia = t * 0
|
|
750
|
+
|
|
751
|
+
pt = qp[:, 0] * tau[:, 0]
|
|
752
|
+
|
|
753
|
+
for nn in range(1, nsenales):
|
|
754
|
+
|
|
755
|
+
pt = pt + qp[:, nn] * tau[:, nn]
|
|
756
|
+
|
|
757
|
+
y1F = 0.0
|
|
758
|
+
y1Fk1 = 0.0
|
|
759
|
+
Tant = 0.0
|
|
760
|
+
|
|
761
|
+
for k in range(nmuestras):
|
|
762
|
+
|
|
763
|
+
Tf = t[k] - Tant
|
|
764
|
+
Tant = t[k]
|
|
765
|
+
|
|
766
|
+
y1F = Tf * pt[k] + y1Fk1
|
|
767
|
+
y1Fk1 = y1F
|
|
768
|
+
|
|
769
|
+
Energia[k] = y1F
|
|
770
|
+
|
|
771
|
+
return Energia
|
|
772
|
+
|
|
773
|
+
def ejes(MatA: Any, t: float, *, ax: Any = None) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
774
|
+
|
|
775
|
+
# Esta función se utiliza para calcular los extremos de los vectores
|
|
776
|
+
# necesarios para dibujar un sistema coordenado relacionado con la matriz
|
|
777
|
+
# de transformación homogénea MatA.
|
|
778
|
+
|
|
779
|
+
MatA = np.asarray(MatA, dtype=float)
|
|
780
|
+
|
|
781
|
+
if MatA.shape != (4, 4):
|
|
782
|
+
raise ValueError("M debe ser una matriz de transformacion 4x4")
|
|
783
|
+
|
|
784
|
+
po=MatA @ np.array([[0], [0], [0], [1]], dtype=float)
|
|
785
|
+
px=MatA @ np.array([[t], [0], [0], [1]], dtype=float)
|
|
786
|
+
py=MatA @ np.array([[0], [t], [0], [1]], dtype=float)
|
|
787
|
+
pz=MatA @ np.array([[0], [0], [t], [1]], dtype=float)
|
|
788
|
+
|
|
789
|
+
return po, px, py, pz
|
|
790
|
+
|
|
791
|
+
def christoffel(M: Any, q: Any, i: float, j: float, k: float) -> sp.Expr:
|
|
792
|
+
|
|
793
|
+
# Función que calcula el símbolo de christoffel
|
|
794
|
+
# Usa variables "sym"
|
|
795
|
+
|
|
796
|
+
if M.rows != M.cols:
|
|
797
|
+
raise ValueError("M debe ser una matriz cuadrada.")
|
|
798
|
+
|
|
799
|
+
if q.rows != 1 and q.cols != 1:
|
|
800
|
+
raise ValueError("q debe ser un vector de posiciones articulares.")
|
|
801
|
+
|
|
802
|
+
if len(q) != M.rows:
|
|
803
|
+
raise ValueError(
|
|
804
|
+
"La longitud de q debe coincidir con las dimensiones de M."
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
n = M.rows
|
|
808
|
+
|
|
809
|
+
if not all(1 <= indice <= n for indice in (i, j, k)):
|
|
810
|
+
raise ValueError(
|
|
811
|
+
f"Los índices i, j y k deben estar entre 1 y {n}."
|
|
812
|
+
)
|
|
813
|
+
|
|
814
|
+
# Conversión de índices MATLAB (base 1) a Python (base 0)
|
|
815
|
+
i -= 1
|
|
816
|
+
j -= 1
|
|
817
|
+
k -= 1
|
|
818
|
+
|
|
819
|
+
cijk = sp.Rational(1, 2) * (sp.diff(M[k, j], q[i]) + sp.diff(M[k, i], q[j]) - sp.diff(M[i, j], q[k]))
|
|
820
|
+
|
|
821
|
+
return cijk
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def DK_RR(theta1: Any, theta2: Any, L1: float, L2: float) -> Any:
|
|
825
|
+
|
|
826
|
+
H1 = rotz(theta1) @ trans(L1, 0, 0)
|
|
827
|
+
H2 = rotz(theta2) @ trans(L2, 0, 0)
|
|
828
|
+
|
|
829
|
+
TK = H1 @ H2
|
|
830
|
+
|
|
831
|
+
return TK
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def IK_RR(x: float, y: float, L1: float, L2: float, codo: float) -> tuple[Any, Any]:
|
|
835
|
+
|
|
836
|
+
D = (x**2 + y**2 - L1**2 - L2**2) / (2 * L1 * L2)
|
|
837
|
+
|
|
838
|
+
if codo:
|
|
839
|
+
|
|
840
|
+
theta2 = atan2(-sqrt(1-D**2), D)
|
|
841
|
+
|
|
842
|
+
else:
|
|
843
|
+
theta2 = atan2(sqrt(1-D**2), D)
|
|
844
|
+
|
|
845
|
+
theta1=atan2(y,x)-atan2(L2*sin(theta2),L1+L2*cos(theta2))
|
|
846
|
+
|
|
847
|
+
return theta1, theta2
|
|
848
|
+
|
|
849
|
+
__all__ = [
|
|
850
|
+
"rotx3", "roty3", "rotz3",
|
|
851
|
+
"rotx", "roty", "rotz", "trans",
|
|
852
|
+
"deg2rad", "rad2deg",
|
|
853
|
+
"Rot_RPY", "Rot_RPY_grados", "RPY", "RPY_grados",
|
|
854
|
+
"Rot_eje", "Rot_eje_grados", "Eje_theta", "Eje_theta_grados",
|
|
855
|
+
"DH", "H_inv",
|
|
856
|
+
"Rot_Q", "Quaternions", "Axis2Quaternions",
|
|
857
|
+
"derivada_numerica", "derivada_numerica2", "derivada_numerica_central",
|
|
858
|
+
"interpolacion_cubica", "interpolacion_cubica_vector",
|
|
859
|
+
"interpolacion_lineal", "interpolacion_lineal_vector",
|
|
860
|
+
"interpolacion_tramos", "interpolacion_tramos_vector",
|
|
861
|
+
"Energia_robot",
|
|
862
|
+
"ejes",
|
|
863
|
+
"christoffel",
|
|
864
|
+
"IK_RR", "DK_RR"
|
|
865
|
+
]
|