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,156 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import trimesh
|
|
5
|
+
|
|
6
|
+
from SimpleRobotics.transforms import rotz, trans
|
|
7
|
+
from SimpleRobotics.animation import RobotScene
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# Dimensiones del robot, en metros.
|
|
11
|
+
L1 = 0.200
|
|
12
|
+
L2 = 0.150
|
|
13
|
+
D1 = 0.015
|
|
14
|
+
D2 = 0.010
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _cargar_stl(ruta: Path) -> trimesh.Trimesh:
|
|
18
|
+
"""Carga una geometría STL del robot."""
|
|
19
|
+
if not ruta.is_file():
|
|
20
|
+
raise FileNotFoundError(f"No se encuentra el archivo STL: {ruta}")
|
|
21
|
+
|
|
22
|
+
malla = trimesh.load(
|
|
23
|
+
str(ruta),
|
|
24
|
+
file_type="stl",
|
|
25
|
+
force="mesh",
|
|
26
|
+
process=True,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if not isinstance(malla, trimesh.Trimesh):
|
|
30
|
+
raise TypeError(
|
|
31
|
+
f"El archivo {ruta.name!r} no produjo una malla trimesh.Trimesh."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return malla
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _matrices_robot_rr(
|
|
38
|
+
theta1: float,
|
|
39
|
+
theta2: float,
|
|
40
|
+
) -> tuple[dict[str, np.ndarray], np.ndarray]:
|
|
41
|
+
"""Calcula las transformaciones de los elementos del robot RR."""
|
|
42
|
+
H01 = np.asarray(rotz(theta1) @ trans(L1, 0, 0), dtype=float)
|
|
43
|
+
H12 = np.asarray(rotz(theta2) @ trans(L2, 0, 0), dtype=float)
|
|
44
|
+
H02 = H01 @ H12
|
|
45
|
+
|
|
46
|
+
# Transformaciones usadas para ubicar los STL según el modelo MATLAB.
|
|
47
|
+
HB = np.eye(4, dtype=float)
|
|
48
|
+
HL1 = np.asarray(rotz(theta1) @ trans(0, 0, D1), dtype=float)
|
|
49
|
+
HL2 = HL1 @ np.asarray(trans(L1, 0, 0), dtype=float) @ np.asarray(
|
|
50
|
+
rotz(theta2), dtype=float
|
|
51
|
+
)
|
|
52
|
+
HL3 = HL2 @ np.asarray(trans(L2, 0, -D1 + D2), dtype=float)
|
|
53
|
+
|
|
54
|
+
# La jerarquía de RobotScene requiere transformaciones locales.
|
|
55
|
+
transformaciones_locales = {
|
|
56
|
+
"base": HB,
|
|
57
|
+
"link1": HL1,
|
|
58
|
+
"link2": np.linalg.solve(HL1, HL2),
|
|
59
|
+
"actuator": np.linalg.solve(HL2, HL3),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return transformaciones_locales, H02
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def actualizar_pose_robot_rr(
|
|
66
|
+
scene: RobotScene,
|
|
67
|
+
theta1: float,
|
|
68
|
+
theta2: float,
|
|
69
|
+
) -> np.ndarray:
|
|
70
|
+
"""Actualiza la pose del robot RR y devuelve H02."""
|
|
71
|
+
locales, H02 = _matrices_robot_rr(theta1, theta2)
|
|
72
|
+
|
|
73
|
+
scene.update_transforms(
|
|
74
|
+
{
|
|
75
|
+
"link1": locales["link1"],
|
|
76
|
+
"link2": locales["link2"],
|
|
77
|
+
"actuator": locales["actuator"],
|
|
78
|
+
},
|
|
79
|
+
space="local",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
return H02
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def Renderiza_Robot_RR(
|
|
86
|
+
theta1: float,
|
|
87
|
+
theta2: float,
|
|
88
|
+
carpeta_stl: str | Path,
|
|
89
|
+
*,
|
|
90
|
+
mostrar: bool = True,
|
|
91
|
+
mostrar_link2: bool = False,
|
|
92
|
+
window_size: tuple[int, int] = (1000, 750),
|
|
93
|
+
) -> tuple[RobotScene, np.ndarray]:
|
|
94
|
+
"""Construye la escena 3D del robot RR a partir de sus archivos STL."""
|
|
95
|
+
carpeta = Path(carpeta_stl).expanduser().resolve()
|
|
96
|
+
|
|
97
|
+
archivos = {
|
|
98
|
+
"Base": "Robot_2gdl_planar-Base.STL",
|
|
99
|
+
"Link1": "Robot_2gdl_planar-Eslabon1.STL",
|
|
100
|
+
"Link2": "Robot_2gdl_planar-Eslabon2.STL",
|
|
101
|
+
"Actuador": "Robot_2gdl_planar-Actuador.STL",
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
mallas = {
|
|
105
|
+
nombre: _cargar_stl(carpeta / archivo)
|
|
106
|
+
for nombre, archivo in archivos.items()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
locales, H02 = _matrices_robot_rr(theta1, theta2)
|
|
110
|
+
|
|
111
|
+
scene = RobotScene(
|
|
112
|
+
window_size=window_size,
|
|
113
|
+
background="white",
|
|
114
|
+
axes=True,
|
|
115
|
+
grid=True,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
scene.add_frame("base", transform=locales["base"])
|
|
119
|
+
scene.add_frame("link1", parent="base", transform=locales["link1"])
|
|
120
|
+
scene.add_frame("link2", parent="link1", transform=locales["link2"])
|
|
121
|
+
scene.add_frame(
|
|
122
|
+
"actuator",
|
|
123
|
+
parent="link2",
|
|
124
|
+
transform=locales["actuator"],
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
# Colores equivalentes a los RGB del ejemplo MATLAB.
|
|
128
|
+
scene.add_mesh(
|
|
129
|
+
"Base", mallas["Base"], frame="base", color=(1.0, 1.0, 0.0)
|
|
130
|
+
)
|
|
131
|
+
scene.add_mesh(
|
|
132
|
+
"Link1", mallas["Link1"], frame="link1", color=(1.0, 0.6, 0.0)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# MATLAB calcula HL2 y carga Link2, pero no dibuja ese STL.
|
|
136
|
+
if mostrar_link2:
|
|
137
|
+
scene.add_mesh(
|
|
138
|
+
"Link2", mallas["Link2"], frame="link2", color="lightgray"
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
scene.add_mesh(
|
|
142
|
+
"Actuador",
|
|
143
|
+
mallas["Actuador"],
|
|
144
|
+
frame="actuator",
|
|
145
|
+
color=(1.0, 0.8, 0.8),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
scene.plotter.show_bounds(
|
|
149
|
+
bounds=(-0.4, 0.4, -0.4, 0.4, -0.01, 0.15),
|
|
150
|
+
location="outer",
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if mostrar:
|
|
154
|
+
scene.show()
|
|
155
|
+
|
|
156
|
+
return scene, H02
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Librería educativa de robótica.
|
|
2
|
+
|
|
3
|
+
Etapa Final: Implementación de ejemplos de la toolbox original
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .transforms import (Rot_RPY,Rot_RPY_grados,rad2deg,deg2rad,rotx,rotx3,roty,roty3,
|
|
7
|
+
rotz,rotz3,trans, Rot_eje, Rot_eje_grados, Eje_theta, Eje_theta_grados,RPY,RPY_grados,DH, H_inv, Rot_Q, Quaternions,
|
|
8
|
+
derivada_numerica_central, derivada_numerica, derivada_numerica2, interpolacion_tramos_vector,
|
|
9
|
+
interpolacion_lineal, interpolacion_lineal_vector, interpolacion_tramos, Energia_robot, ejes, Axis2Quaternions, christoffel,
|
|
10
|
+
interpolacion_cubica, interpolacion_cubica_vector, IK_RR, DK_RR)
|
|
11
|
+
|
|
12
|
+
from .formatting import matriz_a_texto, mostrar_matriz
|
|
13
|
+
|
|
14
|
+
from .plotting import (eslabon, cilindro, cono, flecha, Sistema3D, tubo, tubo2, Sistema3Dbool, prisma_rectangular,
|
|
15
|
+
prisma_rectangularC, prisma_rectangularC2, piramide, linea_punteada, normaL2, Sistema, Load_STL, gripper,
|
|
16
|
+
giroZ, giro_z, eslabon_STL, esfera, ejes3D, distancia_z, DibujaPlano, desplazamiento_z, Dibujar_intermedio,)
|
|
17
|
+
|
|
18
|
+
from .RobotRR import (actualizar_pose_robot_rr, _matrices_robot_rr, Renderiza_Robot_RR, RobotScene,
|
|
19
|
+
_cargar_stl)
|
|
20
|
+
|
|
21
|
+
__version__ = "1.0.5.2"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"rotx3", "roty3", "rotz3",
|
|
25
|
+
"rotx", "roty", "rotz", "trans",
|
|
26
|
+
"Rot_RPY", "Rot_RPY_grados", "rad2deg", "deg2rad", "Rot_eje", "Rot_eje_grados"
|
|
27
|
+
"matriz_a_texto", "mostrar_matriz", "Eje_theta", "Eje_theta_grados",
|
|
28
|
+
"RPY", "RPY_grados", "DH", "H_inv", "eslabon", "cilindro", "cono", "flecha",
|
|
29
|
+
"Sistema3D", "tubo", "tubo2", "Sistema3Dbool", "Rot_Q", "Quaternions", "prisma_rectangular",
|
|
30
|
+
"prisma_rectangularC", "piramide", "prisma_rectangularC2", "linea_punteada", "normaL2", "Sistema",
|
|
31
|
+
"Load_STL", "interpolacion_tramos_vector", "derivada_numerica2", "derivada_numerica", "derivada_numerica_central",
|
|
32
|
+
"interpolacion_lineal", "interpolacion_lineal_vector", "interpolacion_tramos", "gripper", "giroZ", "giro_z",
|
|
33
|
+
"eslabon_STL", "Energia_robot", "esfera", "ejes", "ejes3D", "distancia_z", "DibujaPlano", "desplazamiento_z",
|
|
34
|
+
"Axis2Quaternions", "interpolacion_cubica_vector", "interpolacion_cubica", "christoffel", "Dibujar_intermedio",
|
|
35
|
+
"actualizar_pose_robot_rr", "matriz_a_texto", "Rot_eje_grados", "_matrices_robot_rr", "Renderiza_Robot_RR", "RobotScene",
|
|
36
|
+
"_cargar_stl", "IK_RR", "DK_RR",
|
|
37
|
+
]
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""Escenas 3D para animaciones de SimpleRobotics.
|
|
2
|
+
|
|
3
|
+
Este modulo contiene la primera pieza del sistema de animacion: RobotScene.
|
|
4
|
+
No implementa todavia el temporizador ni la reproduccion; eso correspondera
|
|
5
|
+
posteriormente a AnimationController.
|
|
6
|
+
|
|
7
|
+
Dependencias opcionales:
|
|
8
|
+
pip install trimesh pyvista
|
|
9
|
+
|
|
10
|
+
Uso previsto:
|
|
11
|
+
from SimpleRobotics.animation import RobotScene
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RobotScene:
|
|
23
|
+
"""Administra frames, geometria y actores de una escena robotica 3D.
|
|
24
|
+
|
|
25
|
+
Trimesh conserva el grafo de transformaciones. PyVista representa las
|
|
26
|
+
mallas mediante actores. Cada malla se almacena en coordenadas locales y
|
|
27
|
+
su actor recibe la transformacion global calculada por Trimesh.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
window_size:
|
|
32
|
+
Tamano inicial de la ventana (ancho, alto), en pixeles.
|
|
33
|
+
background:
|
|
34
|
+
Color de fondo aceptado por PyVista.
|
|
35
|
+
axes:
|
|
36
|
+
Si es True, muestra el widget de ejes de PyVista.
|
|
37
|
+
grid:
|
|
38
|
+
Si es True, muestra la cuadricula y los limites de referencia.
|
|
39
|
+
base_frame:
|
|
40
|
+
Nombre del sistema de referencia raiz. Por defecto, ``"world"``.
|
|
41
|
+
|
|
42
|
+
Notes
|
|
43
|
+
-----
|
|
44
|
+
Las transformaciones pasadas a add_frame, add_mesh y set_transform son
|
|
45
|
+
matrices homogeneas 4x4 que expresan la pose local respecto al padre.
|
|
46
|
+
update_transforms tambien admite matrices globales usando space="world".
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
_MESH_NODE_PREFIX = "__mesh__:"
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
window_size: tuple[int, int] = (1000, 750),
|
|
54
|
+
background: str = "white",
|
|
55
|
+
axes: bool = True,
|
|
56
|
+
grid: bool = True,
|
|
57
|
+
base_frame: str = "world",
|
|
58
|
+
) -> None:
|
|
59
|
+
# Importar dentro del constructor mantiene las dependencias de
|
|
60
|
+
# visualizacion fuera de las importaciones matematicas principales.
|
|
61
|
+
try:
|
|
62
|
+
import pyvista as pv
|
|
63
|
+
import trimesh
|
|
64
|
+
except ImportError as exc:
|
|
65
|
+
raise ImportError(
|
|
66
|
+
"RobotScene requiere las dependencias de visualizacion. "
|
|
67
|
+
"Instalalas con: pip install pyvista trimesh"
|
|
68
|
+
) from exc
|
|
69
|
+
|
|
70
|
+
if (
|
|
71
|
+
not isinstance(window_size, (tuple, list))
|
|
72
|
+
or len(window_size) != 2
|
|
73
|
+
or any(not isinstance(v, (int, np.integer)) or v <= 0 for v in window_size)
|
|
74
|
+
):
|
|
75
|
+
raise ValueError("window_size debe contener dos enteros positivos.")
|
|
76
|
+
|
|
77
|
+
self._pv = pv
|
|
78
|
+
self._trimesh = trimesh
|
|
79
|
+
self._base_frame = self._validar_nombre(base_frame, "base_frame")
|
|
80
|
+
|
|
81
|
+
self._scene = trimesh.Scene(base_frame=self._base_frame)
|
|
82
|
+
self._plotter = pv.Plotter(window_size=tuple(window_size))
|
|
83
|
+
self._plotter.set_background(background)
|
|
84
|
+
|
|
85
|
+
if axes:
|
|
86
|
+
self._plotter.add_axes()
|
|
87
|
+
if grid:
|
|
88
|
+
self._plotter.show_grid()
|
|
89
|
+
|
|
90
|
+
# Mapa de frames logicos y sus respectivos padres.
|
|
91
|
+
self._frames: dict[str, str | None] = {self._base_frame: None}
|
|
92
|
+
|
|
93
|
+
# Mapa entre nombres publicos de mallas y nodos internos de Trimesh.
|
|
94
|
+
self._mesh_nodes: dict[str, str] = {}
|
|
95
|
+
|
|
96
|
+
# Actores PyVista asociados a cada malla publica.
|
|
97
|
+
self._actors: dict[str, Any] = {}
|
|
98
|
+
|
|
99
|
+
self._closed = False
|
|
100
|
+
|
|
101
|
+
# ------------------------------------------------------------------
|
|
102
|
+
# Validacion y conversion interna
|
|
103
|
+
# ------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def _validar_nombre(name: str, parametro: str = "name") -> str:
|
|
107
|
+
if not isinstance(name, str) or not name.strip():
|
|
108
|
+
raise ValueError(f"{parametro} debe ser una cadena no vacia.")
|
|
109
|
+
return name
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def _validar_matriz(matrix: Any, parametro: str = "matrix") -> np.ndarray:
|
|
113
|
+
"""Valida una transformacion afin homogenea 4x4 numerica."""
|
|
114
|
+
try:
|
|
115
|
+
result = np.asarray(matrix, dtype=float)
|
|
116
|
+
except (TypeError, ValueError) as exc:
|
|
117
|
+
raise TypeError(f"{parametro} debe ser una matriz numerica 4x4.") from exc
|
|
118
|
+
|
|
119
|
+
if result.shape != (4, 4):
|
|
120
|
+
raise ValueError(f"{parametro} debe tener dimensiones 4x4.")
|
|
121
|
+
|
|
122
|
+
if not np.all(np.isfinite(result)):
|
|
123
|
+
raise ValueError(f"{parametro} no puede contener NaN o infinitos.")
|
|
124
|
+
|
|
125
|
+
if not np.allclose(result[3], [0.0, 0.0, 0.0, 1.0]):
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"La ultima fila de {parametro} debe ser [0, 0, 0, 1]."
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return result.copy()
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _a_polydata(mesh: Any, pv: Any) -> Any:
|
|
134
|
+
"""Convierte una malla triangular Trimesh a pyvista.PolyData."""
|
|
135
|
+
vertices = np.asarray(mesh.vertices, dtype=float)
|
|
136
|
+
faces = np.asarray(mesh.faces, dtype=np.int64)
|
|
137
|
+
|
|
138
|
+
if vertices.ndim != 2 or vertices.shape[1] != 3:
|
|
139
|
+
raise ValueError("La geometria debe tener vertices con forma (N, 3).")
|
|
140
|
+
|
|
141
|
+
if faces.ndim != 2 or faces.shape[1] != 3:
|
|
142
|
+
raise ValueError("La geometria debe contener caras triangulares (M, 3).")
|
|
143
|
+
|
|
144
|
+
if vertices.size == 0 or faces.size == 0:
|
|
145
|
+
raise ValueError("No se pueden agregar mallas vacias a RobotScene.")
|
|
146
|
+
|
|
147
|
+
# Formato VTK/PyVista: [3, i, j, k, 3, i, j, k, ...].
|
|
148
|
+
faces_pv = np.column_stack(
|
|
149
|
+
(np.full(len(faces), 3, dtype=np.int64), faces)
|
|
150
|
+
).ravel()
|
|
151
|
+
|
|
152
|
+
return pv.PolyData(vertices, faces_pv)
|
|
153
|
+
|
|
154
|
+
def _comprobar_abierta(self) -> None:
|
|
155
|
+
if self._closed:
|
|
156
|
+
raise RuntimeError("La escena ya fue cerrada y no puede modificarse.")
|
|
157
|
+
|
|
158
|
+
def _nodo_de(self, name: str) -> str:
|
|
159
|
+
"""Devuelve el nombre interno del nodo asociado a un frame o malla."""
|
|
160
|
+
if name in self._frames:
|
|
161
|
+
return name
|
|
162
|
+
if name in self._mesh_nodes:
|
|
163
|
+
return self._mesh_nodes[name]
|
|
164
|
+
raise KeyError(f"No existe un frame ni una malla llamada {name!r}.")
|
|
165
|
+
|
|
166
|
+
def _sincronizar_actores(self) -> None:
|
|
167
|
+
"""Copia a cada actor la pose global actual de su nodo Trimesh."""
|
|
168
|
+
for mesh_name, actor in self._actors.items():
|
|
169
|
+
node_name = self._mesh_nodes[mesh_name]
|
|
170
|
+
matrix_world, _ = self._scene.graph.get(
|
|
171
|
+
node_name, self._base_frame
|
|
172
|
+
)
|
|
173
|
+
actor.user_matrix = matrix_world
|
|
174
|
+
|
|
175
|
+
# ------------------------------------------------------------------
|
|
176
|
+
# API publica: frames
|
|
177
|
+
# ------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def add_frame(
|
|
180
|
+
self,
|
|
181
|
+
name: str,
|
|
182
|
+
parent: str | None = None,
|
|
183
|
+
transform: Any | None = None,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""Agrega un sistema de referencia hijo de ``parent``.
|
|
186
|
+
|
|
187
|
+
``transform`` es la matriz local del nuevo frame respecto a su padre.
|
|
188
|
+
Si se omite, se utiliza la identidad.
|
|
189
|
+
"""
|
|
190
|
+
self._comprobar_abierta()
|
|
191
|
+
name = self._validar_nombre(name)
|
|
192
|
+
parent = self._base_frame if parent is None else self._validar_nombre(parent, "parent")
|
|
193
|
+
|
|
194
|
+
if name == self._base_frame:
|
|
195
|
+
raise ValueError("No se puede volver a agregar el frame raiz.")
|
|
196
|
+
if name.startswith(self._MESH_NODE_PREFIX):
|
|
197
|
+
raise ValueError(
|
|
198
|
+
f"Los nombres de frames no pueden comenzar con "
|
|
199
|
+
f"{self._MESH_NODE_PREFIX!r}."
|
|
200
|
+
)
|
|
201
|
+
if name in self._frames or name in self._mesh_nodes:
|
|
202
|
+
raise ValueError(f"Ya existe un frame o malla llamado {name!r}.")
|
|
203
|
+
if parent not in self._frames:
|
|
204
|
+
raise KeyError(f"No existe el frame padre {parent!r}.")
|
|
205
|
+
|
|
206
|
+
matrix = self._validar_matriz(
|
|
207
|
+
np.eye(4) if transform is None else transform,
|
|
208
|
+
"transform",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
self._scene.graph.update(
|
|
212
|
+
frame_to=name,
|
|
213
|
+
frame_from=parent,
|
|
214
|
+
matrix=matrix,
|
|
215
|
+
)
|
|
216
|
+
self._frames[name] = parent
|
|
217
|
+
|
|
218
|
+
# ------------------------------------------------------------------
|
|
219
|
+
# API publica: geometria
|
|
220
|
+
# ------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def add_mesh(
|
|
223
|
+
self,
|
|
224
|
+
name: str,
|
|
225
|
+
mesh: Any,
|
|
226
|
+
frame: str,
|
|
227
|
+
transform: Any | None = None,
|
|
228
|
+
color: Any = "lightgray",
|
|
229
|
+
opacity: float = 1.0,
|
|
230
|
+
smooth_shading: bool = True,
|
|
231
|
+
) -> Any:
|
|
232
|
+
"""Asocia una malla Trimesh a un frame y crea su actor PyVista.
|
|
233
|
+
|
|
234
|
+
La geometria se mantiene en coordenadas locales. ``transform`` ubica
|
|
235
|
+
la malla respecto al frame indicado y puede omitirse para usar I4.
|
|
236
|
+
Devuelve el actor creado por PyVista.
|
|
237
|
+
"""
|
|
238
|
+
self._comprobar_abierta()
|
|
239
|
+
name = self._validar_nombre(name)
|
|
240
|
+
frame = self._validar_nombre(frame, "frame")
|
|
241
|
+
|
|
242
|
+
if name in self._mesh_nodes or name in self._frames:
|
|
243
|
+
raise ValueError(f"Ya existe un frame o malla llamado {name!r}.")
|
|
244
|
+
if frame not in self._frames:
|
|
245
|
+
raise KeyError(f"No existe el frame {frame!r}.")
|
|
246
|
+
if not isinstance(mesh, self._trimesh.Trimesh):
|
|
247
|
+
raise TypeError("mesh debe ser una instancia de trimesh.Trimesh.")
|
|
248
|
+
|
|
249
|
+
opacity = float(opacity)
|
|
250
|
+
if not 0.0 <= opacity <= 1.0:
|
|
251
|
+
raise ValueError("opacity debe estar entre 0 y 1.")
|
|
252
|
+
|
|
253
|
+
local_matrix = self._validar_matriz(
|
|
254
|
+
np.eye(4) if transform is None else transform,
|
|
255
|
+
"transform",
|
|
256
|
+
)
|
|
257
|
+
polydata = self._a_polydata(mesh, self._pv)
|
|
258
|
+
|
|
259
|
+
# El nodo interno de la geometria es hijo del frame del robot.
|
|
260
|
+
node_name = f"{self._MESH_NODE_PREFIX}{name}"
|
|
261
|
+
self._scene.add_geometry(
|
|
262
|
+
mesh,
|
|
263
|
+
node_name=node_name,
|
|
264
|
+
geom_name=name,
|
|
265
|
+
parent_node_name=frame,
|
|
266
|
+
transform=local_matrix,
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
matrix_world, _ = self._scene.graph.get(
|
|
270
|
+
node_name, self._base_frame
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
try:
|
|
274
|
+
actor = self._plotter.add_mesh(
|
|
275
|
+
polydata,
|
|
276
|
+
name=f"actor::{name}",
|
|
277
|
+
color=color,
|
|
278
|
+
opacity=opacity,
|
|
279
|
+
smooth_shading=smooth_shading,
|
|
280
|
+
user_matrix=matrix_world,
|
|
281
|
+
reset_camera=not self._actors,
|
|
282
|
+
render=False,
|
|
283
|
+
)
|
|
284
|
+
except Exception:
|
|
285
|
+
# Evita dejar una geometria sin actor si PyVista rechaza el mesh.
|
|
286
|
+
self._scene.delete_geometry(name)
|
|
287
|
+
raise
|
|
288
|
+
|
|
289
|
+
self._mesh_nodes[name] = node_name
|
|
290
|
+
self._actors[name] = actor
|
|
291
|
+
return actor
|
|
292
|
+
|
|
293
|
+
# ------------------------------------------------------------------
|
|
294
|
+
# API publica: transformaciones
|
|
295
|
+
# ------------------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
def set_transform(self, name: str, matrix: Any) -> None:
|
|
298
|
+
"""Actualiza la transformacion LOCAL de un frame respecto a su padre."""
|
|
299
|
+
self.update_transforms({name: matrix}, space="local")
|
|
300
|
+
|
|
301
|
+
def update_transforms(
|
|
302
|
+
self,
|
|
303
|
+
transforms: Mapping[str, Any],
|
|
304
|
+
space: str = "local",
|
|
305
|
+
) -> None:
|
|
306
|
+
"""Actualiza varios frames y sincroniza los actores una sola vez.
|
|
307
|
+
|
|
308
|
+
Parameters
|
|
309
|
+
----------
|
|
310
|
+
transforms:
|
|
311
|
+
Diccionario ``{nombre_frame: matriz_4x4}``.
|
|
312
|
+
space:
|
|
313
|
+
``"local"`` si las matrices son relativas al padre de cada frame;
|
|
314
|
+
``"world"`` si son relativas al frame raiz de la escena.
|
|
315
|
+
|
|
316
|
+
Si se actualizan simultaneamente un padre y un hijo en espacio global,
|
|
317
|
+
se usan las matrices globales nuevas de ambos para calcular las
|
|
318
|
+
transformaciones locales correspondientes.
|
|
319
|
+
"""
|
|
320
|
+
self._comprobar_abierta()
|
|
321
|
+
|
|
322
|
+
if not isinstance(transforms, Mapping):
|
|
323
|
+
raise TypeError("transforms debe ser un mapping nombre-matriz.")
|
|
324
|
+
if space not in {"local", "world"}:
|
|
325
|
+
raise ValueError("space debe ser 'local' o 'world'.")
|
|
326
|
+
if not transforms:
|
|
327
|
+
return
|
|
328
|
+
|
|
329
|
+
matrices = {}
|
|
330
|
+
for name, matrix in transforms.items():
|
|
331
|
+
if name not in self._frames:
|
|
332
|
+
raise KeyError(f"No existe el frame {name!r}.")
|
|
333
|
+
if name == self._base_frame:
|
|
334
|
+
raise ValueError("No se puede modificar la transformacion del frame raiz.")
|
|
335
|
+
matrices[name] = self._validar_matriz(matrix, f"transforms[{name!r}]")
|
|
336
|
+
|
|
337
|
+
if space == "local":
|
|
338
|
+
matrices_local = matrices
|
|
339
|
+
else:
|
|
340
|
+
matrices_local: dict[str, np.ndarray] = {}
|
|
341
|
+
for name, matrix_world in matrices.items():
|
|
342
|
+
parent = self._frames[name]
|
|
343
|
+
if parent is None:
|
|
344
|
+
raise RuntimeError(f"El frame {name!r} no tiene padre.")
|
|
345
|
+
|
|
346
|
+
if parent in matrices:
|
|
347
|
+
parent_world = matrices[parent]
|
|
348
|
+
else:
|
|
349
|
+
parent_world = self.get_world_transform(parent)
|
|
350
|
+
|
|
351
|
+
try:
|
|
352
|
+
matrices_local[name] = np.linalg.solve(
|
|
353
|
+
parent_world, matrix_world
|
|
354
|
+
)
|
|
355
|
+
except np.linalg.LinAlgError as exc:
|
|
356
|
+
raise ValueError(
|
|
357
|
+
f"La transformacion global del padre {parent!r} "
|
|
358
|
+
"no es invertible."
|
|
359
|
+
) from exc
|
|
360
|
+
|
|
361
|
+
# Todas las matrices se validan y calculan antes de modificar el grafo.
|
|
362
|
+
for name, matrix_local in matrices_local.items():
|
|
363
|
+
parent = self._frames[name]
|
|
364
|
+
self._scene.graph.update(
|
|
365
|
+
frame_to=name,
|
|
366
|
+
frame_from=parent,
|
|
367
|
+
matrix=matrix_local,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
self._sincronizar_actores()
|
|
371
|
+
|
|
372
|
+
def get_world_transform(self, name: str) -> np.ndarray:
|
|
373
|
+
"""Devuelve la matriz global de un frame o malla respecto a la raiz."""
|
|
374
|
+
self._comprobar_abierta()
|
|
375
|
+
node_name = self._nodo_de(name)
|
|
376
|
+
|
|
377
|
+
if node_name == self._base_frame:
|
|
378
|
+
return np.eye(4, dtype=float)
|
|
379
|
+
|
|
380
|
+
matrix, _ = self._scene.graph.get(
|
|
381
|
+
node_name, self._base_frame
|
|
382
|
+
)
|
|
383
|
+
return np.asarray(matrix, dtype=float).copy()
|
|
384
|
+
|
|
385
|
+
# ------------------------------------------------------------------
|
|
386
|
+
# API publica: ventana y renderizado
|
|
387
|
+
# ------------------------------------------------------------------
|
|
388
|
+
|
|
389
|
+
def render(self) -> None:
|
|
390
|
+
"""Solicita a PyVista renderizar la escena actual."""
|
|
391
|
+
self._comprobar_abierta()
|
|
392
|
+
self._plotter.render()
|
|
393
|
+
|
|
394
|
+
def show(self, **kwargs: Any) -> Any:
|
|
395
|
+
"""Muestra la ventana interactiva de PyVista."""
|
|
396
|
+
self._comprobar_abierta()
|
|
397
|
+
return self._plotter.show(**kwargs)
|
|
398
|
+
|
|
399
|
+
def close(self) -> None:
|
|
400
|
+
"""Cierra la ventana y libera los recursos de PyVista."""
|
|
401
|
+
if not self._closed:
|
|
402
|
+
self._plotter.close()
|
|
403
|
+
self._closed = True
|
|
404
|
+
|
|
405
|
+
# ------------------------------------------------------------------
|
|
406
|
+
# Propiedades de consulta
|
|
407
|
+
# ------------------------------------------------------------------
|
|
408
|
+
|
|
409
|
+
@property
|
|
410
|
+
def frames(self) -> tuple[str, ...]:
|
|
411
|
+
"""Nombres de los frames registrados, incluido el frame raiz."""
|
|
412
|
+
return tuple(self._frames.keys())
|
|
413
|
+
|
|
414
|
+
@property
|
|
415
|
+
def meshes(self) -> tuple[str, ...]:
|
|
416
|
+
"""Nombres publicos de las mallas agregadas a la escena."""
|
|
417
|
+
return tuple(self._mesh_nodes.keys())
|
|
418
|
+
|
|
419
|
+
@property
|
|
420
|
+
def trimesh_scene(self) -> Any:
|
|
421
|
+
"""Escena Trimesh subyacente, disponible para consultas avanzadas."""
|
|
422
|
+
return self._scene
|
|
423
|
+
|
|
424
|
+
@property
|
|
425
|
+
def plotter(self) -> Any:
|
|
426
|
+
"""Plotter PyVista subyacente, disponible para personalizacion avanzada."""
|
|
427
|
+
return self._plotter
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Funciones de presentación para matrices numéricas y simbólicas.
|
|
2
|
+
|
|
3
|
+
Estas funciones afectan únicamente a la visualización: la matriz original no se
|
|
4
|
+
modifica y conserva su tipo para poder seguir realizando operaciones.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def matriz_a_texto(matriz: Any, *, precision: int = 4) -> str:
|
|
15
|
+
"""Devuelve una representación legible de una matriz 2D.
|
|
16
|
+
|
|
17
|
+
Las matrices de SymPy se formatean como una matriz matemática alineada.
|
|
18
|
+
Las matrices numéricas se presentan con NumPy y precisión configurable.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
matriz: Matriz simbólica de SymPy o matriz numérica convertible a ndarray.
|
|
22
|
+
precision: Número de decimales para matrices numéricas.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Texto formateado. La matriz original no se modifica.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
ValueError: Si la entrada no es bidimensional o precision es negativa.
|
|
29
|
+
TypeError: Si la entrada no se puede interpretar como matriz.
|
|
30
|
+
"""
|
|
31
|
+
if precision < 0:
|
|
32
|
+
raise ValueError("precision debe ser mayor o igual que cero")
|
|
33
|
+
|
|
34
|
+
modulo = type(matriz).__module__.split(".", 1)[0]
|
|
35
|
+
if modulo == "sympy":
|
|
36
|
+
try:
|
|
37
|
+
import sympy as sp
|
|
38
|
+
except ImportError as exc: # pragma: no cover - objeto SymPy requiere el paquete
|
|
39
|
+
raise ImportError("Instala SymPy para mostrar matrices simbólicas.") from exc
|
|
40
|
+
|
|
41
|
+
if isinstance(matriz, sp.MatrixBase):
|
|
42
|
+
return sp.pretty(matriz, use_unicode=True)
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
arreglo = np.asarray(matriz)
|
|
46
|
+
except (TypeError, ValueError) as exc:
|
|
47
|
+
raise TypeError("matriz debe ser una matriz numérica o una matriz de SymPy") from exc
|
|
48
|
+
|
|
49
|
+
if arreglo.ndim != 2:
|
|
50
|
+
raise ValueError("matriz debe ser bidimensional")
|
|
51
|
+
|
|
52
|
+
return np.array2string(
|
|
53
|
+
arreglo,
|
|
54
|
+
precision=precision,
|
|
55
|
+
suppress_small=True,
|
|
56
|
+
separator=" ",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def mostrar_matriz(matriz: Any, *, precision: int = 4) -> None:
|
|
61
|
+
"""Imprime una matriz con formato legible, sin alterar la matriz original."""
|
|
62
|
+
print(matriz_a_texto(matriz, precision=precision))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
__all__ = ["matriz_a_texto", "mostrar_matriz"]
|