diff --git a/src/roboticstoolbox/robot/DHRobot.py b/src/roboticstoolbox/robot/DHRobot.py index 43ee71d55..a375eddcc 100644 --- a/src/roboticstoolbox/robot/DHRobot.py +++ b/src/roboticstoolbox/robot/DHRobot.py @@ -636,16 +636,16 @@ def reach(self) -> Any: :rtype: float A conservative estimate of the reach of the robot. It is computed as - :math:`\sum_j |a_j| + |d_j|` where :math:`d_j` is taken as the maximum - joint coordinate (``qlim``) if the joint is primsmatic. + :math:`\sum_j |a_j| + |d_j|`. For a prismatic joint, :math:`|d_j|` is + the largest displacement over ``qlim``, including the joint offset + and flip. Base and tool transforms are not included. .. note:: - This is the *length sum* referred to in Craig's book - Probably an overestimate of the actual reach - - Used by numerical inverse kinematics to scale translational - error. - - For a prismatic joint, uses ``qlim`` if it is set + - Without prismatic joint limits, only the fixed offset + contributes; unbounded joint travel cannot be estimated. .. warning:: Computed on the first access. If kinematic parameters subsequently change this will not be reflected. @@ -653,9 +653,15 @@ def reach(self) -> Any: if self._reach is None: d = 0 for link in self: - d += abs(link.a) + (link.d) - if link.isprismatic and link.qlim is not None: - d += link.qlim[1] + d += abs(link.a) + if link.isprismatic: + if link.qlim is not None: + travel = -link.qlim if link.isflip else link.qlim + d += max(abs(travel + link.offset)) + else: + d += abs(link.offset) + else: + d += abs(link.d) self._reach = d return self._reach diff --git a/src/roboticstoolbox/robot/Robot.py b/src/roboticstoolbox/robot/Robot.py index e7b1a19c2..c268458a3 100644 --- a/src/roboticstoolbox/robot/Robot.py +++ b/src/roboticstoolbox/robot/Robot.py @@ -663,7 +663,8 @@ def reach(self) -> float: :rtype: float A conservative estimate of the reach of the robot. It is computed as - the sum of the translational ETs that define the link transform. + the sum of the translation lengths along the longest branch, including + compound transforms. Base and tool transforms are not included. Computed on the first access. If kinematic parameters subsequently change this will not be reflected. @@ -671,9 +672,9 @@ def reach(self) -> float: .. rubric:: Notes - Probably an overestimate of reach - - Used by numerical inverse kinematics to scale translational - error. - - For a prismatic joint, uses ``qlim`` if it is set + - For a prismatic joint, bounds the displacement over ``qlim``, + including its offset and flip. Without limits, only the fixed + offset contributes; unbounded joint travel cannot be estimated. """ @@ -693,12 +694,16 @@ def reach(self) -> float: # joint limits. They might be set in the ET # or in the Link depending on how the robot # was constructed - if link.qlim is not None: - d += max(link.qlim) - elif et.qlim is not None: # pragma nocover - d += max(et.qlim) + qlim = link.qlim if link.qlim is not None else et.qlim + if qlim is not None: + travel = -qlim if et.isflip else qlim + d += max(abs(travel + et.offset)) + else: + d += abs(cast(float, et.offset)) else: d += abs(cast(float, et.param)) + elif not et.iselementary: + d += float(np.linalg.norm(et.A()[:-1, -1])) link = link.parent # type: ignore[assignment] if link is None or isinstance(link, str): d_all.append(d) @@ -1413,6 +1418,9 @@ def closest_point( world frame which connect the line of length distance between the shapes. If the distance is negative then the shapes are collided. + Includes collision geometry on all grippers, using each gripper's + own current joint configuration. + """ if not skip: @@ -1424,7 +1432,8 @@ def closest_point( p1 = None p2 = None - for link in self.links: + links = [*self.links, *(link for g in self.grippers for link in g.links)] + for link in links: td, tp1, tp2 = link.closest_point(shape, inf_dist, skip=True) if td is not None and d is not None and td < d: @@ -1611,11 +1620,14 @@ def joint_velocity_damper( """ Compute the joint velocity damper for QP motion control + :param q: joint coordinates in joint-index order, defaults to the + robot's current configuration :param ps: The minimum angle (in radians) in which the joint is allowed to approach to its limit :param pi: The influence angle (in radians) in which the velocity damper becomes active - :param n: The number of joints to consider. Defaults to all joints + :param n: The number of leading joint coordinates to consider. + Defaults to all joints :param gain: The gain for the velocity damper :returns: tuple of (Ain, Bin) inequality constraint matrices for an optimiser @@ -1635,12 +1647,20 @@ def joint_velocity_damper( Ain = np.zeros((n, n)) Bin = np.zeros(n) + if n == 0: + return Ain, Bin + + # qlim follows link order, whereas q and the constraint columns follow + # joint indices. These orders can differ in an explicitly indexed robot. + jindices = [link.jindex for link in self.links if link.isjoint] + qlim = self.qlim[:, np.argsort(jindices)] + for i in range(n): - if q[i] - self.qlim[0, i] <= pi: - Bin[i] = -gain * (((self.qlim[0, i] - q[i]) + ps) / (pi - ps)) + if q[i] - qlim[0, i] <= pi: + Bin[i] = -gain * (((qlim[0, i] - q[i]) + ps) / (pi - ps)) Ain[i, i] = -1 - if self.qlim[1, i] - q[i] <= pi: - Bin[i] = gain * ((self.qlim[1, i] - q[i]) - ps) / (pi - ps) + if qlim[1, i] - q[i] <= pi: + Bin[i] = gain * ((qlim[1, i] - q[i]) - ps) / (pi - ps) Ain[i, i] = 1 return Ain, Bin @@ -1673,6 +1693,9 @@ def link_collision_damper( make it impossible for the robot to run into a collision. Requires See examples/neo.py for use case. + The contact-point Jacobian and the obstacle's translational velocity + are projected onto the separation normal in world coordinates. + """ end, start, _ = self._get_limit_links(start=start, end=end) @@ -1704,22 +1727,19 @@ def indiv_calculation(link: Link, link_col: CollisionShape, q: NDArray) -> Any: axis=0, ) - # tool = (self.fkine(q, end=link).inv() * SE3(wTlp)).A[:3, 3] - - # Je = self.jacob0(q, end=link, tool=tool) - # Je[:3, :] = self._T[:3, :3] @ Je[:3, :] - - # n_dim = Je.shape[1] - # dp = norm_h @ shape.v - # l_Ain = zeros((1, self.n)) - - Je = self.jacobe(q, start=start, end=link, tool=link_col.T) - n_dim = Je.shape[1] + # Transform the link-origin body Jacobian to the closest + # point in world axes, including the contact's lever arm. + # Ignore the robot's end-effector tool for this link pose. + wTl = self.fkine(q, end=link, tool=SE3()) + cTl = SE3(wTlp).inv() * wTl + Jlink = self.jacobe(q, start=start, end=link, tool=SE3()) + Jc = cTl.Ad() @ Jlink + n_dim = Jc.shape[1] dp = norm_h @ shape.v l_Ain = np.zeros((1, self.n)) start_jidx = get_link_joint_index(start) - l_Ain[0, start_jidx : start_jidx + n_dim] = 1 * norm_h @ Je + l_Ain[0, start_jidx : start_jidx + n_dim] = norm_h @ Jc l_bin = (xi * (d - ds) / (di - ds)) + dp else: # pragma nocover l_Ain = None @@ -2321,7 +2341,8 @@ def reach(self) -> float: :rtype: float A conservative estimate of the reach of the robot. It is computed as - the sum of the translational ETs that define the link transform. + the sum of the translation lengths along the longest branch, including + compound transforms. Base and tool transforms are not included. Computed on the first access. If kinematic parameters subsequently change this will not be reflected. @@ -2329,9 +2350,9 @@ def reach(self) -> float: .. rubric:: Notes - Probably an overestimate of reach - - Used by numerical inverse kinematics to scale translational - error. - - For a prismatic joint, uses ``qlim`` if it is set + - For a prismatic joint, bounds the displacement over ``qlim``, + including its offset and flip. Without limits, only the fixed + offset contributes; unbounded joint travel cannot be estimated. """ @@ -2351,12 +2372,16 @@ def reach(self) -> float: # joint limits. They might be set in the ET # or in the Link depending on how the robot # was constructed - if link.qlim is not None: - d += max(link.qlim) - elif et.qlim is not None: # pragma nocover - d += max(et.qlim) + qlim = link.qlim if link.qlim is not None else et.qlim + if qlim is not None: + travel = -qlim if et.isflip else qlim + d += max(abs(travel + et.offset)) + else: + d += abs(cast(float, et.offset)) else: d += abs(cast(float, et.param)) + elif not et.iselementary: + d += float(np.linalg.norm(et.A()[:-1, -1])) link = link.parent # type: ignore[assignment] if link is None or isinstance(link, str): d_all.append(d) diff --git a/tests/test_closest_grippers.py b/tests/test_closest_grippers.py new file mode 100644 index 000000000..19b5b0a0e --- /dev/null +++ b/tests/test_closest_grippers.py @@ -0,0 +1,94 @@ +"""Robot distance queries include independently configured gripper geometry.""" + +import numpy as np +import pytest +from spatialgeometry import Sphere +from spatialmath import SE3 + +from roboticstoolbox import ET, Link, Robot +from tests import skip_no_collision_checking + +pytestmark = skip_no_collision_checking + + +def gripper_robot(arm_geometry: bool = True) -> Robot: + arm = Link(ET.Rz(), name="arm", collision=[Sphere(0.1)] if arm_geometry else []) + finger = Link( + ET.tx(1) * ET.tx(), parent=arm, name="finger", collision=[Sphere(0.1)] + ) + robot = Robot([arm, finger], gripper_links=finger) + robot.grippers[0].q = [0.2] + return robot + + +@pytest.mark.parametrize("arm_geometry", [False, True]) +@pytest.mark.parametrize("obstacle_x, expected", [(1.6, 0.2), (1.3, -0.1)]) +def test_gripper_is_the_closest_collision_body( + arm_geometry: bool, obstacle_x: float, expected: float +) -> None: + robot = gripper_robot(arm_geometry) + obstacle = Sphere(0.1, pose=SE3.Tx(obstacle_x)) + + distance, robot_point, obstacle_point = robot.closest_point( + np.zeros(1), obstacle, inf_dist=0.5 + ) + + assert distance == pytest.approx(expected) + np.testing.assert_allclose(robot_point, [1.3, 0, 0], atol=1e-9) + np.testing.assert_allclose(obstacle_point, [obstacle_x - 0.1, 0, 0], atol=1e-9) + assert robot.iscollided(np.zeros(1), obstacle) == (expected < 0) + + +def test_arm_can_remain_closer_than_the_gripper() -> None: + robot = gripper_robot() + obstacle = Sphere(0.1, pose=SE3.Tx(-0.4)) + + distance, robot_point, obstacle_point = robot.closest_point( + np.zeros(1), obstacle, inf_dist=2 + ) + + assert distance == pytest.approx(0.2) + np.testing.assert_allclose(robot_point, [-0.1, 0, 0], atol=1e-9) + np.testing.assert_allclose(obstacle_point, [-0.3, 0, 0], atol=1e-9) + + +def test_distance_follows_each_grippers_independent_configuration() -> None: + arm = Link(ET.Rz(), name="arm") + first = Link(ET.tx(), parent=arm, name="first", collision=[Sphere(0.1)]) + second = Link(ET.tx(), parent=arm, name="second", collision=[Sphere(0.1)]) + robot = Robot([arm, first, second], gripper_links=[first, second]) + robot.base = SE3(0.4, -0.2, 0.3) * SE3.Rz(np.pi / 2) + robot.grippers[0].q = [-1.0] + robot.grippers[1].q = [1.2] + obstacle = Sphere(0.1, pose=robot.base * SE3.Tx(1.6)) + + distance, robot_point, obstacle_point = robot.closest_point(np.zeros(1), obstacle) + + assert distance == pytest.approx(0.2) + np.testing.assert_allclose(robot_point, (robot.base * SE3.Tx(1.3)).t, atol=1e-9) + np.testing.assert_allclose(obstacle_point, (robot.base * SE3.Tx(1.5)).t, atol=1e-9) + robot.grippers[1].q = [-1.0] + assert robot.closest_point(np.zeros(1), obstacle) == (None, None, None) + robot.grippers[0].q = [1.4] + assert robot.closest_point(np.zeros(1), obstacle)[0] == pytest.approx(0.0) + + +def test_skip_uses_the_grippers_existing_world_transforms() -> None: + robot = gripper_robot() + obstacle = Sphere(0.1, pose=SE3.Tx(1.6)) + robot.closest_point(np.zeros(1), obstacle) + robot.grippers[0].q = [0.3] + + assert robot.closest_point(np.array([np.pi]), obstacle, skip=True)[ + 0 + ] == pytest.approx(0.2) + assert robot.closest_point(np.zeros(1), obstacle)[0] == pytest.approx(0.1) + + +def test_empty_and_distant_gripper_geometry_give_no_result() -> None: + robot = gripper_robot(arm_geometry=False) + obstacle = Sphere(0.1, pose=SE3.Tx(10)) + assert robot.closest_point(np.zeros(1), obstacle) == (None, None, None) + robot.grippers[0].links[0].collision = [] + obstacle.T = SE3.Tx(1.3) + assert robot.closest_point(np.zeros(1), obstacle) == (None, None, None) diff --git a/tests/test_collision_damper_frames.py b/tests/test_collision_damper_frames.py new file mode 100644 index 000000000..39a66935a --- /dev/null +++ b/tests/test_collision_damper_frames.py @@ -0,0 +1,108 @@ +"""Collision constraints agree with world-frame contact distance changes.""" + +import numpy as np +import pytest +from spatialgeometry import Cuboid, Sphere +from spatialmath import SE3 + +from roboticstoolbox import ET, Link, Robot, models +from tests import skip_no_collision_checking + +pytestmark = skip_no_collision_checking + + +@pytest.mark.parametrize("base_angle", [0.0, np.pi / 2]) +@pytest.mark.parametrize("end_angle", [0.0, np.pi / 2]) +def test_prismatic_damper_is_invariant_to_frame_rotations( + base_angle: float, end_angle: float +) -> None: + root = Link(ET.tz(0), name="base") + slider = Link(ET.tx(), name="slider", parent=root) + end = Link(ET.Rz(end_angle), name="end", parent=slider, collision=[Sphere(0.05)]) + robot = Robot([root, slider, end], base=SE3.Rz(base_angle)) + q = np.array([0.1]) + normal = robot.base.R @ np.array([1.0, 0.0, 0.0]) + centre = robot.fkine(q, tool=SE3()).t + obstacle = Sphere(0.05, pose=SE3(centre + 0.2 * normal)) + obstacle.v = [0.03, -0.04, 0.01, 0, 0, 0] + distance, _, _ = robot.closest_point(q, obstacle) + assert distance == pytest.approx(0.1) + + a, b = robot.link_collision_damper(obstacle, q, di=0.3, ds=0.05) + + # Positive slider velocity closes the gap at the same speed in every frame. + np.testing.assert_allclose(a, [[1.0]], atol=1e-12) + np.testing.assert_allclose(b, [0.2 + normal @ obstacle.v[:3]], atol=1e-12) + + +@pytest.mark.parametrize("rotated_base", [False, True]) +@pytest.mark.parametrize("start_index", [None, 2]) +def test_panda_damper_matches_contact_distance_gradient( + rotated_base: bool, start_index: int | None +) -> None: + robot = models.ETS.Panda() + if rotated_base: + robot.base = SE3(0.3, -0.2, 0.4) * SE3.RPY([0.3, -0.4, 0.7]) + # A robot-level end-effector tool must not offset a collision on link 4. + robot.tool = SE3(0.2, 0.1, -0.15) * SE3.Rx(0.4) + collision_pose = SE3(0.04, -0.03, 0.08) * SE3.Ry(0.6) + robot.links[4].collision = [Sphere(0.05, pose=collision_pose)] + q = robot.qr.copy() + centre = robot.fkine(q, end=robot.links[4], tool=collision_pose).t + obstacle = Sphere(0.05, pose=SE3(centre + [0.2, -0.1, 0.15])) + expected = np.zeros(robot.n) + step = 1e-6 + for j in range(0 if start_index is None else start_index, 5): + dq = np.zeros(robot.n) + dq[j] = step + plus, _, _ = robot.closest_point(q + dq, obstacle) + minus, _, _ = robot.closest_point(q - dq, obstacle) + assert plus is not None and minus is not None + expected[j] = -(plus - minus) / (2 * step) + + distance, _, _ = robot.closest_point(q, obstacle) + assert distance is not None and 0.05 < distance < 0.5 + start = None if start_index is None else robot.links[start_index] + a, b = robot.link_collision_damper(obstacle, q, start=start, di=0.5, ds=0.05) + + assert a.shape == (1, robot.n) + np.testing.assert_allclose(a[0], expected, atol=1e-8) + np.testing.assert_allclose(b, [(distance - 0.05) / 0.45], atol=1e-12) + + +def test_distant_collision_has_no_constraint() -> None: + robot = models.ETS.Panda() + robot.links[4].collision = [Sphere(0.05)] + obstacle = Sphere(0.05, pose=SE3.Tx(10)) + robot.closest_point(robot.qr, obstacle) + + assert robot.link_collision_damper(obstacle, robot.qr) == (None, None) + + +def test_cuboid_damper_uses_contact_point_lever_arm() -> None: + root = Link(ET.tz(0), name="base") + collision_pose = SE3.Tx(0.8) * SE3.Rz(0.3) + hinge = Link( + ET.Rz(), + parent=root, + name="hinge", + collision=[Cuboid([0.3, 0.6, 0.2], pose=collision_pose)], + ) + robot = Robot([root, hinge]) + q = np.array([0.4]) + pose = robot.fkine(q, end=hinge, tool=collision_pose) + # The nearest point lies inside the x face, displaced in y from its centre. + obstacle = Sphere(0.05, pose=pose * SE3(0.5, 0.15, 0.02)) + step = 1e-6 + plus, _, _ = robot.closest_point(q + step, obstacle) + minus, _, _ = robot.closest_point(q - step, obstacle) + assert plus is not None and minus is not None + expected = -(plus - minus) / (2 * step) + # Using the cuboid centre instead would omit the -0.15 contact offset. + assert expected == pytest.approx(0.8 * np.sin(0.3) - 0.15, abs=1e-8) + distance, _, _ = robot.closest_point(q, obstacle) + assert distance == pytest.approx(0.3) + + a, _ = robot.link_collision_damper(obstacle, q, di=0.5, ds=0.05) + + np.testing.assert_allclose(a, [[expected]], atol=1e-8) diff --git a/tests/test_joint_damper_indices.py b/tests/test_joint_damper_indices.py new file mode 100644 index 000000000..73d5156ff --- /dev/null +++ b/tests/test_joint_damper_indices.py @@ -0,0 +1,141 @@ +"""Joint-limit constraints must address the same coordinates as robot.q.""" + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal +from scipy.optimize import LinearConstraint, minimize + +from roboticstoolbox import ET, Link, Robot, models + + +def indexed_robot(indices, mixed=False, first_limits=(-1, 1)): + base = Link(ET.tx(0.4), name="base") + first = Link(ET.Rz(jindex=indices[0], qlim=first_limits), parent=base, name="first") + fixed = Link(ET.tx(0.6), parent=first, name="fixed") + transform = ET.tx if mixed else ET.Ry + second = Link( + transform(jindex=indices[1], qlim=[-2, 2]), parent=fixed, name="second" + ) + third = Link(ET.Rz(jindex=indices[2], qlim=[-3, 3]), parent=second, name="third") + return Robot([base, first, fixed, second, third]) + + +def coordinates_and_constraints(indices, gain=1.0): + q = np.empty(3) + q[indices] = [0.94, -1.92, 0.0] + diagonal = np.empty(3) + diagonal[indices] = [1, -1, 0] + bound = np.empty(3) + # Distances 0.06 and 0.08 to the upper/lower limit with ps=.05, pi=.1. + bound[indices] = gain * np.array([0.2, 0.6, 0.0]) + return q, np.diag(diagonal), bound + + +@pytest.mark.parametrize("indices", [[0, 1, 2], [1, 0, 2], [2, 0, 1], [1, 2, 0]]) +@pytest.mark.parametrize("mixed", [False, True]) +@pytest.mark.parametrize("explicit_q", [False, True]) +@pytest.mark.parametrize("gain", [0.5, 1.5]) +def test_damper_uses_global_joint_coordinates(indices, mixed, explicit_q, gain): + robot = indexed_robot(indices, mixed=mixed) + q, expected_a, expected_b = coordinates_and_constraints(indices, gain) + if not explicit_q: + robot.q = q + original_state = robot.q.copy() + original_argument = q.copy() + + actual_a, actual_b = robot.joint_velocity_damper( + q=q if explicit_q else None, gain=gain + ) + + assert_allclose(actual_a, expected_a, atol=1e-14) + assert_allclose(actual_b, expected_b, atol=1e-14) + assert_array_equal(robot.q, original_state) + assert_array_equal(q, original_argument) + + +@pytest.mark.parametrize("indices", [[2, 0, 1], [1, 2, 0]]) +@pytest.mark.parametrize("n", [0, 1, 2, 3]) +def test_n_selects_a_prefix_of_the_configuration_vector(indices, n): + robot = indexed_robot(indices, mixed=True) + q, expected_a, expected_b = coordinates_and_constraints(indices) + + actual_a, actual_b = robot.joint_velocity_damper(q=q, n=n) + + assert actual_a.shape == (n, n) + assert actual_b.shape == (n,) + assert_allclose(actual_a, expected_a[:n, :n], atol=1e-14) + assert_allclose(actual_b, expected_b[:n], atol=1e-14) + + +def test_unspecified_revolute_limits_keep_the_existing_pi_default(): + robot = indexed_robot([2, 0, 1], first_limits=None) + q = np.array([0.0, 0.0, np.pi - 0.06]) + + a, b = robot.joint_velocity_damper(q=q) + + assert_allclose(a, np.diag([0, 0, 1]), atol=1e-14) + assert_allclose(b, [0, 0, 0.2], atol=1e-14) + + +def test_empty_prefix_does_not_require_limits_for_unused_joints(): + robot = Robot([Link(ET.tx())]) + a, b = robot.joint_velocity_damper(n=0) + assert a.shape == (0, 0) + assert b.shape == (0,) + + +@pytest.mark.parametrize("factory", [models.DH.Puma560, models.URDF.Panda]) +def test_existing_ordered_robot_models_keep_their_constraints(factory): + robot = factory() + q = np.mean(robot.qlim, axis=0) + q[0] = robot.qlim[1, 0] - 0.06 + q[-1] = robot.qlim[0, -1] + 0.08 + expected = np.zeros(robot.n) + expected[0], expected[-1] = 1, -1 + bound = np.zeros(robot.n) + bound[0], bound[-1] = 0.2, 0.6 + + a, b = robot.joint_velocity_damper(q=q) + + assert_allclose(a, np.diag(expected), atol=1e-14) + assert_allclose(b, bound, atol=1e-14) + + +def test_qp_motion_respects_the_physical_joint_limit(): + robot = Robot( + ET.Rz(jindex=1, qlim=[-1, 1]) + * ET.tx(1) + * ET.Rz(jindex=0, qlim=[-2, 2]) + * ET.tx(1) + ) + q = np.array([0.0, 0.94]) + desired = np.array([0.4, 2.0]) + a, b = robot.joint_velocity_damper(q=q) + active = np.any(a != 0, axis=1) + constraints = ( + [LinearConstraint(a[active], -np.inf, b[active])] if np.any(active) else [] + ) + result = minimize( + lambda velocity: 0.5 * np.sum((velocity - desired) ** 2), + np.zeros(2), + jac=lambda velocity: velocity - desired, + constraints=constraints, + method="SLSQP", + options={"ftol": 1e-12}, + ) + assert result.success + + following = q + 0.05 * result.x + # The first physical joint is q[1]. Its safety margin is 0.05 below 1. + # Without its constraint, the requested step reaches 1.04 and crosses + # even the hard joint limit; the constrained step ends at 0.95. + assert following[1] <= 0.95 + 1e-12 + assert_allclose(result.x, [0.4, 0.2], atol=1e-12) + assert_allclose( + robot.fkine(following).t[:2], + [ + np.cos(following[1]) + np.cos(following.sum()), + np.sin(following[1]) + np.sin(following.sum()), + ], + atol=1e-12, + ) diff --git a/tests/test_robot_reach_bounds.py b/tests/test_robot_reach_bounds.py new file mode 100644 index 000000000..b3c2328fe --- /dev/null +++ b/tests/test_robot_reach_bounds.py @@ -0,0 +1,168 @@ +"""Reach bounds include compound transforms and signed joint travel.""" + +import io + +import matplotlib +import numpy as np +import pytest +from spatialmath import SE2, SE3 + +import roboticstoolbox as rtb +from roboticstoolbox.models.URDF.URDFRobot import URDF_file + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +@pytest.mark.parametrize("planar", [False, True]) +@pytest.mark.parametrize("compiled", [False, True]) +def test_compound_translation_contributes_to_reach(planar, compiled): + if planar: + ets = rtb.ET2.SE2(SE2(3, 4, 0.7)) * rtb.ET2.R() + robot_type = rtb.Robot2 + else: + ets = rtb.ET.SE3(SE3(3, 4, 0) * SE3.RPY(0.2, -0.4, 0.7)) * rtb.ET.Rz() + robot_type = rtb.Robot + robot = robot_type(ets.compile() if compiled else ets) + + assert robot.reach == pytest.approx(5) + for angle in [-2, 0, 1.3]: + assert np.linalg.norm(robot.fkine([angle]).t) <= robot.reach + 1e-12 + + +@pytest.mark.parametrize("planar", [False, True]) +@pytest.mark.parametrize("limits", [(-2, -1), (-3, 1), (1, 2)]) +@pytest.mark.parametrize("offset", [-4, 0, 4]) +@pytest.mark.parametrize("flip", [False, True]) +def test_prismatic_reach_bounds_signed_travel(planar, limits, offset, flip): + et_type, ets_type, robot_type = ( + (rtb.ET2, rtb.ETS2, rtb.Robot2) if planar else (rtb.ET, rtb.ETS, rtb.Robot) + ) + joint = et_type.tx(qlim=limits, flip=flip) + joint.offset = offset + robot = robot_type(ets_type(joint)) + travel = [(offset - q if flip else offset + q) for q in limits] + + assert robot.reach == pytest.approx(max(abs(t) for t in travel)) + for q in np.linspace(*limits, 9): + assert np.linalg.norm(robot.fkine([q]).t) <= robot.reach + 1e-12 + + +@pytest.mark.parametrize("link_type", [rtb.PrismaticDH, rtb.PrismaticMDH]) +@pytest.mark.parametrize("limits", [(-2, -1), (-3, 1), (1, 2)]) +@pytest.mark.parametrize("offset", [-4, 0, 4]) +@pytest.mark.parametrize("flip", [False, True]) +def test_dh_prismatic_reach_bounds_signed_travel(link_type, limits, offset, flip): + link = link_type( + a=-0.5, alpha=0.6, theta=0.3, qlim=limits, offset=offset, flip=flip + ) + robot = rtb.DHRobot([link]) + travel = [(offset - q if flip else offset + q) for q in limits] + + assert robot.reach == pytest.approx(0.5 + max(abs(t) for t in travel)) + for q in np.linspace(*limits, 9): + assert np.linalg.norm(robot.fkine([q]).t) <= robot.reach + 1e-12 + + +@pytest.mark.parametrize("link_type", [rtb.RevoluteDH, rtb.RevoluteMDH]) +def test_dh_negative_constant_d_is_a_length(link_type): + robot = rtb.DHRobot([link_type(a=-1, d=-2, alpha=0.6)]) + + assert robot.reach == 3 + for q in [-2, 0, 1.3]: + assert np.linalg.norm(robot.fkine([q]).t) <= robot.reach + + +@pytest.mark.parametrize("planar", [False, True]) +def test_reach_uses_longest_branch(planar): + if planar: + root = rtb.Link2(rtb.ET2.SE2(SE2(3, 4))) + first = rtb.Link2(rtb.ET2.tx(qlim=[-3, -1]), parent=root) + second = rtb.Link2(rtb.ET2.SE2(SE2(4, 0)) * rtb.ET2.R(), parent=root) + robot = rtb.Robot2([root, first, second]) + else: + root = rtb.Link(rtb.ET.SE3(SE3(3, 4, 0))) + first = rtb.Link(rtb.ET.tx(qlim=[-3, -1]), parent=root) + second = rtb.Link(rtb.ET.SE3(SE3(4, 0, 0)) * rtb.ET.Rz(), parent=root) + robot = rtb.Robot([root, first, second]) + + assert robot.reach == 9 + frames = robot.fkine_all([-3, 0.7]) + for link in robot.ee_links: + assert np.linalg.norm(frames[link.number].t) <= robot.reach + + +def test_urdf_joint_origins_contribute_to_reach(): + # Use the real URDF loader without network models or mesh downloads. + links, name, _ = URDF_file( + io.StringIO( + """ + + + + + + + + + + + + """ + ) + ) + robot = rtb.Robot(links, name=name) + + assert robot.reach == pytest.approx(7) + for q in np.linspace(-2, 2, 9): + assert np.linalg.norm(robot.fkine([q]).t) <= robot.reach + 1e-12 + + +@pytest.mark.parametrize("compound", [False, True]) +def test_planar_plot_limits_include_robot(compound): + from roboticstoolbox.backends.PyPlot import PyPlot2 + + if compound: + robot = rtb.Robot2(rtb.ET2.SE2(SE2(3, 4)) * rtb.ET2.R()) + q = [0.5] + else: + robot = rtb.Robot2(rtb.ETS2(rtb.ET2.tx(qlim=[-2, -1]))) + q = [-2] + env = PyPlot2() + try: + env.launch() + env.add(robot, q=q, eeframe=False, readonly=True) + env.step() + endpoint = robot.fkine(q).t + for coordinate, (lower, upper) in zip( + endpoint, [env.ax.get_xlim(), env.ax.get_ylim()] + ): + assert lower < coordinate < upper + finally: + env.close() + plt.close("all") + + +def test_existing_elementary_length_sum_and_cache(): + robot = rtb.Robot(rtb.ET.tz(2) * rtb.ET.Rz() * rtb.ET.tx(-3)) + assert robot.reach == 5 + assert robot.reach == 5 + robot.base = SE3(100, 200, 300) + robot.tool = SE3(20, 30, 40) + assert robot.reach == 5 + + +@pytest.mark.parametrize("planar", [False, True]) +def test_unbounded_prismatic_includes_fixed_offset(planar): + et_type, ets_type, robot_type = ( + (rtb.ET2, rtb.ETS2, rtb.Robot2) if planar else (rtb.ET, rtb.ETS, rtb.Robot) + ) + joint = et_type.tx() + joint.offset = -2 + assert robot_type(ets_type(joint)).reach == 2 + + +@pytest.mark.parametrize("link_type", [rtb.PrismaticDH, rtb.PrismaticMDH]) +def test_unbounded_dh_prismatic_includes_fixed_offset(link_type): + robot = rtb.DHRobot([link_type(a=-0.5, offset=-2)]) + assert robot.reach == 2.5