diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..1d417a4abc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# The kinematic model fixtures are a pinned copy of rdk's, so GitHub collapses them in a diff. This lives here and not in the +# .gitattributes inside the fixture directory so that the copy stays identical to rdk. +tests/data/kinematic_models/** linguist-generated diff --git a/src/viam/components/arm/arm.py b/src/viam/components/arm/arm.py index bacf23d113..8cefce63dc 100644 --- a/src/viam/components/arm/arm.py +++ b/src/viam/components/arm/arm.py @@ -8,6 +8,8 @@ from viam.components import KinematicsReturn from viam.components.component_base import ComponentBase +from viam.errors import MethodNotImplementedError +from viam.proto.common import KinematicModel from viam.proto.component.arm import ( GetPropertiesResponse, JointAccelerations, @@ -417,7 +419,6 @@ async def is_moving(self) -> bool: """ ... - @abc.abstractmethod async def get_kinematics( self, *, @@ -430,6 +431,9 @@ async def get_kinematics( """ Get the kinematics information associated with the arm. + .. deprecated:: 0.86.0 + Use ``get_kinematic_model``, which returns the typed model. A new arm implements that method and leaves this one alone. + :: my_arm = Arm.from_robot(robot=machine, name="my_arm") @@ -458,7 +462,49 @@ async def get_kinematics( For more information, see `Arm component `_. """ - ... + raise MethodNotImplementedError("get_kinematics") + + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: dict[str, Any] | None = None, + timeout: float | None = None, + **kwargs, + ) -> KinematicModel: + """ + Get the kinematic model of the arm: its links, joints with their limits, output frames and properties. + Lengths are in millimeters and angles in degrees. + + :: + + my_arm = Arm.from_robot(robot=machine, name="my_arm") + + model = await my_arm.get_kinematic_model() + + for joint in model.joints: + print(joint.id, joint.limits.min, joint.limits.max, joint.limits.max_velocity) + + A module implements this by returning the model it holds, which ``viam.kinematics.read_kinematic_model_file`` reads from a + kinematic model file. It may ignore the two flags and return every mesh, since the server drops the bytes a request did not + ask for and fills the deprecated file fields for a client that predates the model. + + Args: + include_collision_meshes (bool): Include collision mesh bytes. Otherwise a collision mesh carries only its path and + content type. + include_visual_meshes (bool): Include visual mesh bytes. Otherwise a visual mesh carries only its path and content type. + With neither flag set a server sends every mesh whole, as it did before the flags existed, so set one to leave the + other out. + + Raises: + NotSupportedError: If the arm is served by a machine that predates the model and sent only the kinematics file, which + ``get_kinematics`` still returns. + + Returns: + KinematicModel: The kinematic model of the arm. + """ + raise MethodNotImplementedError("get_kinematic_model") @abc.abstractmethod async def get_3d_models(self, *, extra: dict[str, Any] | None = None, timeout: float | None = None, **kwargs) -> Mapping[str, Mesh]: diff --git a/src/viam/components/arm/client.py b/src/viam/components/arm/client.py index a7a6054b36..a403bd80bf 100644 --- a/src/viam/components/arm/client.py +++ b/src/viam/components/arm/client.py @@ -4,6 +4,7 @@ from grpclib.client import Channel from viam.components import KinematicsReturn +from viam.errors import NotSupportedError from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -14,6 +15,7 @@ GetKinematicsResponse, GetStatusRequest, GetStatusResponse, + KinematicModel, Mesh, ) from viam.proto.component.arm import ( @@ -290,6 +292,27 @@ async def get_kinematics( return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath, response.model) return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath) + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + md = kwargs.get("metadata", self.Metadata()).proto + request = GetKinematicsRequest( + name=self.name, + include_collision_meshes=include_collision_meshes, + include_visual_meshes=include_visual_meshes, + extra=dict_to_struct(extra), + ) + response: GetKinematicsResponse = await self.client.GetKinematics(request, timeout=timeout, metadata=md) + if not response.HasField("model"): + raise NotSupportedError(f"arm {self.name} sent no kinematic model, only the kinematics file that get_kinematics returns") + return response.model + async def get_3d_models( self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs ) -> Mapping[str, Mesh]: diff --git a/src/viam/components/arm/service.py b/src/viam/components/arm/service.py index f45edd3147..f87bc51e9b 100644 --- a/src/viam/components/arm/service.py +++ b/src/viam/components/arm/service.py @@ -4,6 +4,7 @@ from grpclib import GRPCError, Status from grpclib.server import Stream +from viam.kinematics import kinematics_response from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -249,22 +250,7 @@ async def GetKinematics(self, stream: Stream[GetKinematicsRequest, GetKinematics assert request is not None arm = self.get_resource(request.name) timeout = stream.deadline.time_remaining() if stream.deadline else None - kinematics = await arm.get_kinematics( - include_collision_meshes=request.include_collision_meshes, - include_visual_meshes=request.include_visual_meshes, - extra=struct_to_dict(request.extra), - timeout=timeout, - metadata=stream.metadata, - ) - model = None - if len(kinematics) == 2: - format, kinematics_data = kinematics - meshes = {} - elif len(kinematics) == 3: - format, kinematics_data, meshes = kinematics - else: - format, kinematics_data, meshes, model = kinematics - response = GetKinematicsResponse(format=format, kinematics_data=kinematics_data, meshes_by_urdf_filepath=meshes, model=model) + response = await kinematics_response(arm, request, timeout=timeout, metadata=stream.metadata) await stream.send_message(response) async def Get3DModels(self, stream: Stream[Get3DModelsRequest, Get3DModelsResponse]) -> None: diff --git a/src/viam/components/gantry/client.py b/src/viam/components/gantry/client.py index 8ccd1fadf1..8a86d9c242 100644 --- a/src/viam/components/gantry/client.py +++ b/src/viam/components/gantry/client.py @@ -3,6 +3,7 @@ from grpclib.client import Channel from viam.components import KinematicsReturn +from viam.errors import NotSupportedError from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -11,6 +12,7 @@ GetKinematicsResponse, GetStatusRequest, GetStatusResponse, + KinematicModel, ) from viam.proto.component.gantry import ( GantryServiceStub, @@ -151,6 +153,27 @@ async def get_kinematics( return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath, response.model) return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath) + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + md = kwargs.get("metadata", self.Metadata()).proto + request = GetKinematicsRequest( + name=self.name, + include_collision_meshes=include_collision_meshes, + include_visual_meshes=include_visual_meshes, + extra=dict_to_struct(extra), + ) + response: GetKinematicsResponse = await self.client.GetKinematics(request, timeout=timeout, metadata=md) + if not response.HasField("model"): + raise NotSupportedError(f"gantry {self.name} sent no kinematic model, only the kinematics file that get_kinematics returns") + return response.model + async def get_geometries(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> List[Geometry]: md = kwargs.get("metadata", self.Metadata()) return await get_geometries(self.client, self.name, extra, timeout, md) diff --git a/src/viam/components/gantry/gantry.py b/src/viam/components/gantry/gantry.py index 3a615254ab..f5aeca246d 100644 --- a/src/viam/components/gantry/gantry.py +++ b/src/viam/components/gantry/gantry.py @@ -3,6 +3,8 @@ from viam.components import KinematicsReturn from viam.components.component_base import ComponentBase +from viam.errors import MethodNotImplementedError +from viam.proto.common import KinematicModel from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT @@ -155,7 +157,6 @@ async def is_moving(self) -> bool: """ ... - @abc.abstractmethod async def get_kinematics( self, *, @@ -168,6 +169,9 @@ async def get_kinematics( """ Get the kinematics information associated with the gantry. + .. deprecated:: 0.86.0 + Use ``get_kinematic_model``, which returns the typed model. A new gantry implements that method and leaves this one alone. + :: my_gantry = Gantry.from_robot(robot=machine, name="my_gantry") @@ -195,4 +199,46 @@ async def get_kinematics( For more information, see `Arm component `_. """ - ... + raise MethodNotImplementedError("get_kinematics") + + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + """ + Get the kinematic model of the gantry: its links, joints with their limits, output frames and properties. + Lengths are in millimeters and angles in degrees. + + :: + + my_gantry = Gantry.from_robot(robot=machine, name="my_gantry") + + model = await my_gantry.get_kinematic_model() + + for joint in model.joints: + print(joint.id, joint.limits.min, joint.limits.max, joint.limits.max_velocity) + + A module implements this by returning the model it holds, which ``viam.kinematics.read_kinematic_model_file`` reads from a + kinematic model file. It may ignore the two flags and return every mesh, since the server drops the bytes a request did not + ask for and fills the deprecated file fields for a client that predates the model. + + Args: + include_collision_meshes (bool): Include collision mesh bytes. Otherwise a collision mesh carries only its path and + content type. + include_visual_meshes (bool): Include visual mesh bytes. Otherwise a visual mesh carries only its path and content type. + With neither flag set a server sends every mesh whole, as it did before the flags existed, so set one to leave the + other out. + + Raises: + NotSupportedError: If the gantry is served by a machine that predates the model and sent only the kinematics file, which + ``get_kinematics`` still returns. + + Returns: + KinematicModel: The kinematic model of the gantry. + """ + raise MethodNotImplementedError("get_kinematic_model") diff --git a/src/viam/components/gantry/service.py b/src/viam/components/gantry/service.py index d034f2a946..b942e71246 100644 --- a/src/viam/components/gantry/service.py +++ b/src/viam/components/gantry/service.py @@ -1,5 +1,6 @@ from grpclib.server import Stream +from viam.kinematics import kinematics_response from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -126,22 +127,7 @@ async def GetKinematics(self, stream: Stream[GetKinematicsRequest, GetKinematics assert request is not None gantry = self.get_resource(request.name) timeout = stream.deadline.time_remaining() if stream.deadline else None - kinematics = await gantry.get_kinematics( - include_collision_meshes=request.include_collision_meshes, - include_visual_meshes=request.include_visual_meshes, - extra=struct_to_dict(request.extra), - timeout=timeout, - metadata=stream.metadata, - ) - model = None - if len(kinematics) == 2: - format, data = kinematics - meshes = {} - elif len(kinematics) == 3: - format, data, meshes = kinematics - else: - format, data, meshes, model = kinematics - response = GetKinematicsResponse(format=format, kinematics_data=data, meshes_by_urdf_filepath=meshes, model=model) + response = await kinematics_response(gantry, request, timeout=timeout, metadata=stream.metadata) await stream.send_message(response) async def GetGeometries(self, stream: Stream[GetGeometriesRequest, GetGeometriesResponse]) -> None: diff --git a/src/viam/components/gripper/client.py b/src/viam/components/gripper/client.py index 8b77299b01..a8e963c020 100644 --- a/src/viam/components/gripper/client.py +++ b/src/viam/components/gripper/client.py @@ -3,6 +3,7 @@ from grpclib.client import Channel from viam.components import KinematicsReturn +from viam.errors import NotSupportedError from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -11,6 +12,7 @@ GetKinematicsResponse, GetStatusRequest, GetStatusResponse, + KinematicModel, ) from viam.proto.component.gripper import ( GetCurrentInputsRequest, @@ -138,6 +140,27 @@ async def get_kinematics( return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath, response.model) return (response.format, response.kinematics_data, response.meshes_by_urdf_filepath) + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + md = kwargs.get("metadata", self.Metadata()).proto + request = GetKinematicsRequest( + name=self.name, + include_collision_meshes=include_collision_meshes, + include_visual_meshes=include_visual_meshes, + extra=dict_to_struct(extra), + ) + response: GetKinematicsResponse = await self.client.GetKinematics(request, timeout=timeout, metadata=md) + if not response.HasField("model"): + raise NotSupportedError(f"gripper {self.name} sent no kinematic model, only the kinematics file that get_kinematics returns") + return response.model + async def get_current_inputs( self, *, diff --git a/src/viam/components/gripper/gripper.py b/src/viam/components/gripper/gripper.py index a8fc356bb2..3100253263 100644 --- a/src/viam/components/gripper/gripper.py +++ b/src/viam/components/gripper/gripper.py @@ -4,6 +4,8 @@ from viam.components import KinematicsReturn from viam.components.component_base import ComponentBase +from viam.errors import MethodNotImplementedError +from viam.proto.common import KinematicModel from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT @@ -153,7 +155,6 @@ async def is_moving(self) -> bool: """ ... - @abc.abstractmethod async def get_kinematics( self, *, @@ -166,6 +167,9 @@ async def get_kinematics( """ Get the kinematics information associated with the gripper. + .. deprecated:: 0.86.0 + Use ``get_kinematic_model``, which returns the typed model. A new gripper implements that method and leaves this one alone. + :: my_gripper = Gripper.from_robot(robot=machine, name="my_gripper") @@ -193,7 +197,49 @@ async def get_kinematics( For more information, see `Gripper component `_. """ - ... + raise MethodNotImplementedError("get_kinematics") + + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + """ + Get the kinematic model of the gripper: its links, joints with their limits, output frames and properties. + Lengths are in millimeters and angles in degrees. + + :: + + my_gripper = Gripper.from_robot(robot=machine, name="my_gripper") + + model = await my_gripper.get_kinematic_model() + + for joint in model.joints: + print(joint.id, joint.limits.min, joint.limits.max, joint.limits.max_velocity) + + A module implements this by returning the model it holds, which ``viam.kinematics.read_kinematic_model_file`` reads from a + kinematic model file. It may ignore the two flags and return every mesh, since the server drops the bytes a request did not + ask for and fills the deprecated file fields for a client that predates the model. + + Args: + include_collision_meshes (bool): Include collision mesh bytes. Otherwise a collision mesh carries only its path and + content type. + include_visual_meshes (bool): Include visual mesh bytes. Otherwise a visual mesh carries only its path and content type. + With neither flag set a server sends every mesh whole, as it did before the flags existed, so set one to leave the + other out. + + Raises: + NotSupportedError: If the gripper is served by a machine that predates the model and sent only the kinematics file, which + ``get_kinematics`` still returns. + + Returns: + KinematicModel: The kinematic model of the gripper. + """ + raise MethodNotImplementedError("get_kinematic_model") @abc.abstractmethod async def get_current_inputs( diff --git a/src/viam/components/gripper/service.py b/src/viam/components/gripper/service.py index 07db134773..1097829304 100644 --- a/src/viam/components/gripper/service.py +++ b/src/viam/components/gripper/service.py @@ -1,5 +1,6 @@ from grpclib.server import Stream +from viam.kinematics import kinematics_response from viam.proto.common import ( DoCommandRequest, DoCommandResponse, @@ -120,21 +121,7 @@ async def GetKinematics(self, stream: Stream[GetKinematicsRequest, GetKinematics assert request is not None gripper = self.get_resource(request.name) timeout = stream.deadline.time_remaining() if stream.deadline else None - kinematics = await gripper.get_kinematics( - include_collision_meshes=request.include_collision_meshes, - include_visual_meshes=request.include_visual_meshes, - extra=struct_to_dict(request.extra), - timeout=timeout, - ) - model = None - if len(kinematics) == 2: - format, kinematics_data = kinematics - meshes = {} - elif len(kinematics) == 3: - format, kinematics_data, meshes = kinematics - else: - format, kinematics_data, meshes, model = kinematics - response = GetKinematicsResponse(format=format, kinematics_data=kinematics_data, meshes_by_urdf_filepath=meshes, model=model) + response = await kinematics_response(gripper, request, timeout=timeout) await stream.send_message(response) async def GetCurrentInputs(self, stream: Stream[GetCurrentInputsRequest, GetCurrentInputsResponse]) -> None: diff --git a/src/viam/kinematics.py b/src/viam/kinematics.py new file mode 100644 index 0000000000..c260119ba7 --- /dev/null +++ b/src/viam/kinematics.py @@ -0,0 +1,503 @@ +""" +Helpers for the ``KinematicModel`` message that arms, gantries and grippers serve from ``get_kinematic_model``. + +A module usually keeps its kinematics in a kinematic model file, which is the proto JSON of the message, reads it once with +``read_kinematic_model_file``, narrows it to its resource config with ``narrow_joint_limits`` and returns the result:: + + from viam.kinematics import narrow_joint_limits, read_kinematic_model_file + + model = read_kinematic_model_file("my_arm.json") + model = narrow_joint_limits(model, {"shoulder": {"min": -90, "max": 90}}) + +Lengths in the message are millimeters and angles are degrees. +""" + +import base64 +import json +import math +import ntpath +import os +import posixpath +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union + +from google.protobuf import json_format +from google.protobuf.message import Message + +from viam.errors import MethodNotImplementedError, NotSupportedError +from viam.proto.common import ( + Geometry, + GetKinematicsRequest, + GetKinematicsResponse, + JointType, + KinematicModel, + KinematicsFileFormat, + Mesh, +) +from viam.utils import struct_to_dict + +__all__ = [ + "narrow_joint_limits", + "read_kinematic_model_file", +] + +_WORLD = "world" + +_LIMIT_FIELDS = ("min", "max", "max_velocity", "max_acceleration") + + +def read_kinematic_model_file(path: Union[str, "os.PathLike[str]"]) -> KinematicModel: + """ + Read a kinematic model file into the message it encodes. + + :: + + from viam.kinematics import read_kinematic_model_file + + model = read_kinematic_model_file("my_arm.json") + for joint in model.joints: + print(joint.id, joint.limits.min, joint.limits.max) + + A mesh that names a path and carries no bytes is read from that path, relative to the model file, and comes back with its bytes, + its path as written and its content type taken from the extension. A mesh that already carries bytes is left alone. + + Args: + path (Union[str, os.PathLike[str]]): The kinematic model file. + + Raises: + OSError: If the model file cannot be read. + ValueError: If the file is not a valid model. The read is strict, so an unknown field, a number that is not finite, a parent + that is not in the model, a cycle, a mimic of something that is not a joint and a mesh that cannot be read all fail it. + + Returns: + KinematicModel: The model, with every mesh inline. + """ + path = os.fspath(path) + with open(path, "rb") as f: + data = f.read() + try: + return _parse_kinematic_model(data, os.path.dirname(path)) + except ValueError as e: + raise ValueError(f"kinematic model file {path}: {e}") from e + + +def _parse_kinematic_model(data: Union[bytes, str], mesh_dir: str) -> KinematicModel: + try: + doc = json.loads(data, object_pairs_hook=_unique_keys, parse_constant=_reject_constant, parse_float=_parse_float) + except OverflowError as e: + raise ValueError(str(e)) from e + except ValueError as e: + raise ValueError(f"malformed JSON: {e}") from e + if not isinstance(doc, dict): + raise ValueError("malformed JSON: a kinematic model is a JSON object") + model = KinematicModel() + try: + json_format.ParseDict(doc, model) + except json_format.ParseError as e: + raise ValueError(str(e)) from e + _reject_non_finite(model, "") + _validate(model) + _load_meshes(model, mesh_dir) + return model + + +def _unique_keys(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]: + out: Dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ValueError(f"duplicate key {key!r}") + out[key] = value + return out + + +def _reject_constant(token: str) -> float: + # the json module reads a bare NaN or Infinity, which is not JSON and which the other SDKs refuse + raise ValueError(f"{token} is not a JSON value") + + +def _parse_float(token: str) -> float: + # a literal too large for a double reads as infinity, which a file is not allowed to say any other way either + value = float(token) + if math.isinf(value): + raise OverflowError(f"{token} is infinite, leave a bound out to make it unbounded") + return value + + +def _reject_non_finite(msg: Message, prefix: str) -> None: + # proto JSON reads the strings "Infinity", "-Infinity" and "NaN" into a double, and a file has to leave a bound out to say unbounded + for fd, value in msg.ListFields(): + name = prefix + fd.name + if fd.message_type is not None and fd.message_type.GetOptions().map_entry: + items = [(f"{name}[{k}]", v) for k, v in value.items()] + elif isinstance(value, (Message, float, int, str, bytes)): + items = [(name, value)] + else: + items = [(f"{name}[{i}]", v) for i, v in enumerate(value)] + for item_name, item in items: + if isinstance(item, Message): + _reject_non_finite(item, item_name + ".") + elif isinstance(item, float) and not math.isfinite(item): + what = "not a number" if math.isnan(item) else "infinite" + raise ValueError(f"{item_name} is {what}, leave a bound out to make it unbounded") + + +def _validate(model: KinematicModel) -> None: + nodes = [("link", link.id, link.parent) for link in model.links] + nodes += [("joint", joint.id, joint.parent) for joint in model.joints] + if not nodes: + raise ValueError("model has no links or joints") + kinds: Dict[str, str] = {} + parents: Dict[str, str] = {} + for kind, id, parent in nodes: + if id == "": + raise ValueError(f"a {kind} has no id") + if id == _WORLD: + raise ValueError(f'a {kind} cannot use the reserved id "{_WORLD}"') + other = kinds.get(id) + if other == kind: + raise ValueError(f'{kind} "{id}" is defined twice') + if other is not None: + raise ValueError(f'"{id}" names both a {other} and a {kind}') + kinds[id] = kind + parents[id] = parent + # a reader that builds frames treats a parent it does not know as the world, so a misspelled parent has to be caught here or the + # link quietly moves to the root + for kind, id, parent in nodes: + if parent not in ("", _WORLD) and parent not in kinds: + raise ValueError(f'{kind} "{id}": parent "{parent}" is not a link or joint in the model') + for _, id, _ in nodes: + seen = set() + cur = id + while cur not in ("", _WORLD): + if cur in seen: + raise ValueError(f'{kinds[cur]} "{cur}" is its own ancestor') + seen.add(cur) + cur = parents[cur] + for joint in model.joints: + if not joint.HasField("mimic"): + continue + if joint.mimic.joint == joint.id: + raise ValueError(f'joint "{joint.id}" mimics itself') + if kinds.get(joint.mimic.joint) != "joint": + raise ValueError(f'joint "{joint.id}" mimics "{joint.mimic.joint}", which is not a joint in the model') + if any(joint.limits.HasField(field) for field in _LIMIT_FIELDS): + raise ValueError(f'joint "{joint.id}" is a mimic joint and cannot carry limits, it takes them from the joint it mimics') + + +def _mesh_of(geometry: Geometry) -> Optional[Mesh]: + return geometry.mesh if geometry.WhichOneof("geometry_type") == "mesh" else None + + +def _load_meshes(model: KinematicModel, mesh_dir: str) -> None: + # a file is read once, however many links name it + cache: Dict[str, bytes] = {} + for link in model.links: + for role, geometries in (("collision", link.collision), ("visual", link.visual)): + for i, geometry in enumerate(geometries): + try: + _load_mesh(_mesh_of(geometry), role == "collision", mesh_dir, cache) + except ValueError as e: + raise ValueError(f'link "{link.id}" {role} geometry {i}: {e}') from e + for joint in model.joints: + if not joint.HasField("geometry"): + continue + try: + _load_mesh(_mesh_of(joint.geometry), True, mesh_dir, cache) + except ValueError as e: + raise ValueError(f'joint "{joint.id}" geometry: {e}') from e + + +def _extension(source: str) -> str: + base = source.rsplit("/", 1)[-1] + return base.rsplit(".", 1)[1].lower() if "." in base else "" + + +def _load_mesh(mesh: Optional[Mesh], collision: bool, mesh_dir: str, cache: Dict[str, bytes]) -> None: + if mesh is None: + return + source = mesh.original_file_source_path_diagnostic + has_bytes = len(mesh.mesh) > 0 + if not has_bytes and source == "": + raise ValueError("mesh has neither bytes nor a source path") + content_type = mesh.content_type.lower() + if content_type == "model/gltf-binary": + # the MIME spelling a viewer sends, which the message documents as glb + content_type = "glb" + ext = _extension(source) + if not has_bytes: + # the path has to survive a module install and a trip over the wire, so it is relative, uses forward slashes and is not a URI + if "://" in source: + raise ValueError(f'mesh path "{source}" is a URI, paths are relative to the model file') + if "\\" in source: + raise ValueError(f'mesh path "{source}" uses backslashes, use forward slashes') + if posixpath.isabs(source) or ntpath.isabs(source): + raise ValueError(f'mesh path "{source}" is absolute, paths are relative to the model file') + if ext == "": + raise ValueError(f'mesh path "{source}" has no extension to take the content type from') + if content_type not in ("", ext): + raise ValueError(f'mesh content type "{mesh.content_type}" disagrees with the extension of "{source}"') + content_type = ext + elif content_type == "": + # a mesh that carries its bytes keeps whatever path it was written out with, which can still name the content type + content_type = ext + if content_type == "": + raise ValueError("inline mesh bytes need a content type") + # a collision mesh gets parsed by whoever plans with the model, a visual mesh never does, so only the first is held to a format + if collision and content_type not in ("stl", "ply"): + raise ValueError(f'collision mesh content type "{content_type}" is not stl or ply') + mesh.content_type = content_type + if has_bytes: + return + if source not in cache: + resolved = os.path.normpath(os.path.join(mesh_dir, source)) + try: + with open(resolved, "rb") as f: + cache[source] = f.read() + except OSError as e: + raise ValueError(f'failed to read mesh "{source}" at {resolved}: {e}') from e + mesh.mesh = cache[source] + + +def narrow_joint_limits(model: KinematicModel, limits: Mapping[str, Mapping[str, float]]) -> KinematicModel: + """ + Narrow the joint limits of a model to what a resource's configuration asks of each joint. + + The argument is keyed by joint id and takes the attribute shape a module is expected to accept, in the units of the message: + degrees, degrees per second and degrees per second squared for a revolute joint, millimeters for a prismatic one. A key left out + leaves that limit as it is:: + + from viam.kinematics import narrow_joint_limits + from viam.utils import struct_to_dict + + attributes = struct_to_dict(config.attributes) + # "joint_limits": {"joint_2": {"min": -31, "max": -29}, "joint_3": {"max_velocity": 30}} + model = narrow_joint_limits(model, attributes.get("joint_limits", {})) + + Position, velocity and acceleration are checked on their own. A joint the model has no bound for accepts any value, and a min + equal to max locks a joint where it stands. + + Args: + model (KinematicModel): The model to narrow. It is not modified. + limits (Mapping[str, Mapping[str, float]]): For each joint id, any of ``min``, ``max``, ``max_velocity`` and + ``max_acceleration``. + + Raises: + ValueError: If a value would widen a limit the model already holds, since a widened limit is the one that reaches hardware, + and also if a joint is not in the model, a joint is a mimic joint, a value is not a finite number, a speed is negative + or a min ends up above its max. The error names the joint. + + Returns: + KinematicModel: A copy of the model with the narrowed limits. + """ + out = KinematicModel() + out.CopyFrom(model) + joints = {joint.id: joint for joint in out.joints} + # ids in order, so the joint an error names does not change from one run to the next + for id in sorted(limits): + request = limits[id] + if not isinstance(request, Mapping): + raise ValueError(f'joint "{id}": limits have to be a mapping, got {type(request).__name__}') + for field, value in request.items(): + if field not in _LIMIT_FIELDS: + raise ValueError(f'joint "{id}": unknown limit "{field}", expected one of {", ".join(_LIMIT_FIELDS)}') + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError(f'joint "{id}": {field} must be a finite number, got {value!r}') + for field in ("max_velocity", "max_acceleration"): + if request.get(field, 0) < 0: + raise ValueError(f'joint "{id}": {field} cannot be negative, got {request[field]}') + joint = joints.get(id) + if joint is None: + raise ValueError(f'no joint "{id}" in model "{model.name}"') + if joint.HasField("mimic"): + raise ValueError(f'joint "{id}" is a mimic joint and cannot carry limits, it takes them from the joint it mimics') + + # a bound that has been through radians and back no longer lands on the degrees it started from, so we accept a value up to + # the bound as the error prints it as well as the bound itself. That way neither a value copied out of a message nor the + # model's own limit handed back is refused. + for field in _LIMIT_FIELDS: + if field not in request or not joint.limits.HasField(field): + continue + value = request[field] + exact = getattr(joint.limits, field) + bound = round(exact, 6) + if field == "min" and value < min(exact, bound): + raise ValueError(f'joint "{id}": min {value} is below the model\'s min {bound}') + if field != "min" and value > max(exact, bound): + raise ValueError(f'joint "{id}": {field} {value} is above the model\'s {field} {bound}') + for field, value in request.items(): + setattr(joint.limits, field, value) + if joint.limits.HasField("min") and joint.limits.HasField("max") and joint.limits.min > joint.limits.max: + raise ValueError(f'joint "{id}": min {joint.limits.min} is above max {joint.limits.max}') + # a continuous joint is a revolute joint with neither bound, so it stops being one as soon as it has either + if joint.type == JointType.JOINT_TYPE_CONTINUOUS and (joint.limits.HasField("min") or joint.limits.HasField("max")): + joint.type = JointType.JOINT_TYPE_REVOLUTE + return out + + +class _NotWritable(Exception): + pass + + +def _sva_file(model: KinematicModel) -> Optional[bytes]: + """ + Write the model as the SVA JSON file a client that predates the message reads from the deprecated bytes fields. Visual geometry + is left out, since that file never had a place for it. Returns None for a model the file cannot describe, which is a joint with + no position bound, a collision mesh without its bytes, a point cloud geometry or a joint with no type. + """ + try: + doc: Dict[str, Any] = {"name": model.name, "kinematic_param_type": "SVA"} + doc["links"] = [_sva_link(link) for link in model.links] + doc["joints"] = [_sva_joint(joint) for joint in model.joints] + if model.output_frames: + doc["output_frames"] = list(model.output_frames) + return json.dumps(doc, allow_nan=False).encode() + except (_NotWritable, ValueError): + return None + + +def _sva_vector(v) -> Dict[str, float]: + return {"x": v.x, "y": v.y, "z": v.z} + + +def _sva_link(link) -> Dict[str, Any]: + out: Dict[str, Any] = {"id": link.id, "translation": _sva_vector(link.pose.translation)} + if link.parent: + out["parent"] = link.parent + # the file keeps whichever representation the model has and takes degrees only for an orientation vector + which = link.pose.WhichOneof("orientation") + if which == "quaternion": + q = link.pose.quaternion + out["orientation"] = {"type": "quaternion", "value": {"W": q.w, "X": q.x, "Y": q.y, "Z": q.z}} + elif which == "orientation_vector": + ov = link.pose.orientation_vector + out["orientation"] = {"type": "ov_degrees", "value": {"th": ov.theta, "x": ov.o_x, "y": ov.o_y, "z": ov.o_z}} + elif which == "euler_angles": + e = link.pose.euler_angles + value = {"roll": math.radians(e.roll), "pitch": math.radians(e.pitch), "yaw": math.radians(e.yaw)} + out["orientation"] = {"type": "euler_angles", "value": value} + elif which == "axis_angles": + aa = link.pose.axis_angles + out["orientation"] = {"type": "axis_angles", "value": {"th": math.radians(aa.theta), "x": aa.rx, "y": aa.ry, "z": aa.rz}} + geometries = [_sva_geometry(g) for g in link.collision] + # the first geometry stays under the key a reader that knows only one geometry per link looks at + if geometries: + out["geometry"] = geometries[0] + if len(geometries) > 1: + out["geometries"] = geometries[1:] + return out + + +def _sva_joint(joint) -> Dict[str, Any]: + if joint.type in (JointType.JOINT_TYPE_REVOLUTE, JointType.JOINT_TYPE_CONTINUOUS): + joint_type = "revolute" + elif joint.type == JointType.JOINT_TYPE_PRISMATIC: + joint_type = "prismatic" + else: + raise _NotWritable() + out: Dict[str, Any] = {"id": joint.id, "type": joint_type, "parent": joint.parent, "axis": _sva_vector(joint.axis)} + if joint.HasField("mimic"): + out["mimic"] = {"joint": joint.mimic.joint, "multiplier": joint.mimic.multiplier, "offset": joint.mimic.offset} + else: + # JSON has no infinity, so a joint with a bound left out cannot be written + if not (joint.limits.HasField("min") and joint.limits.HasField("max")): + raise _NotWritable() + out["min"] = joint.limits.min + out["max"] = joint.limits.max + for field in ("max_velocity", "max_acceleration"): + if joint.limits.HasField(field): + out[field] = getattr(joint.limits, field) + if joint.HasField("geometry"): + out["geometry"] = _sva_geometry(joint.geometry) + return out + + +def _sva_geometry(geometry: Geometry) -> Dict[str, Any]: + out: Dict[str, Any] = {} + which = geometry.WhichOneof("geometry_type") + if which == "box": + out.update(type="box", **_sva_vector(geometry.box.dims_mm)) + elif which == "sphere": + out.update(type="sphere", r=geometry.sphere.radius_mm) + elif which == "capsule": + out.update(type="capsule", r=geometry.capsule.radius_mm, l=geometry.capsule.length_mm) + elif which == "mesh" and geometry.mesh.mesh: + out.update(type="mesh", mesh_data=base64.b64encode(geometry.mesh.mesh).decode(), mesh_content_type=geometry.mesh.content_type) + if geometry.mesh.original_file_source_path_diagnostic: + out["mesh_file_path"] = geometry.mesh.original_file_source_path_diagnostic + else: + raise _NotWritable() + center = geometry.center + out["translation"] = _sva_vector(center) + # an unset orientation and the identity both read as no orientation + if not (center.o_x == 0 and center.o_y == 0 and center.o_z >= 0 and center.theta == 0): + out["orientation"] = {"type": "ov_degrees", "value": {"th": center.theta, "x": center.o_x, "y": center.o_y, "z": center.o_z}} + if geometry.label: + out["label"] = geometry.label + return out + + +def _drop_mesh_bytes(geometries) -> None: + for geometry in geometries: + if geometry.WhichOneof("geometry_type") == "mesh": + geometry.mesh.ClearField("mesh") + + +async def kinematics_response(resource, request: GetKinematicsRequest, **kwargs) -> GetKinematicsResponse: + """ + Build the GetKinematics reply for an arm, gantry or gripper, which is shared by their three servers. + + A request that asks for either mesh role comes from a client that reads the typed model, so its reply carries the model alone, + with bytes only for the roles asked for and every other mesh reduced to its path and content type. A request with no flags may + come from a client that predates them, so it gets the deprecated file fields beside the model, with every mesh whole. The file + is what the resource returns from get_kinematics when it still implements it, and otherwise it is written from the model. + """ + collision, visual = request.include_collision_meshes, request.include_visual_meshes + extra = struct_to_dict(request.extra) + model: Optional[KinematicModel] = None + try: + served = await resource.get_kinematic_model( + include_collision_meshes=collision or not visual, + include_visual_meshes=visual or not collision, + extra=extra, + **kwargs, + ) + except (MethodNotImplementedError, NotSupportedError): + # a resource that forwards to an arm on a machine that predates the model has none to give, and still has the file + pass + else: + # we work on a copy, since a resource is free to hand out the one model it holds, and name it for the resource, since that is + # what every client addresses it by + model = KinematicModel() + model.CopyFrom(served) + model.name = request.name + + if model is not None and (collision or visual): + for link in model.links: + if not collision: + _drop_mesh_bytes(link.collision) + if not visual: + _drop_mesh_bytes(link.visual) + if not collision: + _drop_mesh_bytes(joint.geometry for joint in model.joints) + return GetKinematicsResponse(model=model) + + format, data, meshes = KinematicsFileFormat.KINEMATICS_FILE_FORMAT_UNSPECIFIED, b"", {} + try: + kinematics = await resource.get_kinematics( + include_collision_meshes=collision, + include_visual_meshes=visual, + extra=extra, + **kwargs, + ) + except (MethodNotImplementedError, NotSupportedError): + if model is None: + raise + file = _sva_file(model) + if file is not None: + format, data = KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, file + else: + format, data = kinematics[0], kinematics[1] + if len(kinematics) > 2: + meshes = kinematics[2] + if model is None and len(kinematics) > 3: + model = kinematics[3] + return GetKinematicsResponse(format=format, kinematics_data=data, meshes_by_urdf_filepath=meshes, model=model) diff --git a/tests/data/kinematic_models/.gitattributes b/tests/data/kinematic_models/.gitattributes new file mode 100644 index 0000000000..515593f2b9 --- /dev/null +++ b/tests/data/kinematic_models/.gitattributes @@ -0,0 +1,4 @@ +# The runner compares the mesh bytes a model loads against expected.json, so a checkout must not +# rewrite the line endings of the text based mesh formats. +*.ply -text +*.glb -text diff --git a/tests/data/kinematic_models/README.md b/tests/data/kinematic_models/README.md new file mode 100644 index 0000000000..2094d10a13 --- /dev/null +++ b/tests/data/kinematic_models/README.md @@ -0,0 +1,81 @@ +# Kinematic model fixtures + +One directory of kinematic model files with what a loader has to make of each, shared by the +Go, C++ and Python SDKs so the three loaders agree. The Go runner is +`referenceframe/kinematic_model_fixtures_test.go`. The other SDKs keep a pinned copy of this +directory and run the same checks with their own loader. + +## Layout + +Every case is a directory holding `model.json`, the kinematic model file under test, with any +meshes it names beside it by relative path. A case ends in exactly one of two ways. + +- `expected.json` is the message the loader has to produce, as proto JSON of + `viam.common.v1.KinematicModel`, with every mesh's bytes inline and its content type in the + extension spelling. Parse it with the protobuf JSON parser of the SDK and compare messages, + do not compare text. +- `error.json` says the loader has to refuse the file, with the reason as a `kind` from the table + below and `mentions`, strings the error message has to contain, usually the id or path at + fault. The wording of the message is the SDK's own. + +A runner walks the directory, loads each `model.json` through the SDK's loader, and checks +whichever file is present. A case with neither is a mistake. + +## Expected files + +`expected.json` is written by the Go loader. After a deliberate change to the loader, regenerate +with + +``` +go test ./referenceframe/ -run TestKinematicModelFixtures -update-kinematic-model-fixtures +``` + +and read the diff, since every SDK compares against the same files. A loader that produces +something else on an existing case is wrong until the fixture is changed on purpose. + +Two things the expected files pin that are easy to get wrong. A mesh named by path comes back +with its bytes inline and the path kept as it was written, and a content type is lowercased, +taken from the extension when absent, with `model/gltf-binary` read as `glb`. + +## Error kinds + +| kind | the file | +|---|---| +| `unknown_field` | has a field the message does not have, usually a typo | +| `infinite` | has an infinite number | +| `nan` | has a number that is not a number | +| `malformed_json` | is not JSON | +| `empty_model` | has no links and no joints | +| `missing_id` | has a link or joint without an id | +| `reserved_id` | uses `world` as an id | +| `shared_id` | uses one id for a link and a joint | +| `duplicate_id` | uses one id twice for the same kind | +| `missing_parent` | names a parent that is not in the model | +| `cycle` | has a link or joint that is its own ancestor | +| `mimic_self` | has a joint that mimics itself | +| `mimic_not_joint` | has a joint that mimics something that is not a joint | +| `mimic_with_limits` | has a mimic joint carrying limits of its own | +| `mesh_missing` | names a mesh file that is not there | +| `mesh_path_absolute` | names a mesh by an absolute path | +| `mesh_path_uri` | names a mesh by a URI, `package://` or `file://` | +| `mesh_path_backslash` | names a mesh with backslashes in the path | +| `content_type_mismatch` | gives a mesh a content type its extension disagrees with | +| `collision_format` | has a collision mesh that is not STL or PLY | +| `mesh_no_extension` | names a mesh by a path with no extension to take the type from | +| `inline_without_type` | has mesh bytes inline with no content type | +| `mesh_empty` | has a mesh with neither bytes nor a path | + +## The cases + +Handwritten: `single_link`, `orientations` for every orientation form a link pose can take, +`geometries` for every shape a collision or visual can be, `mesh_by_path` for meshes read from +beside the file including a shared path, a `..` in a path and the `model/gltf-binary` alias, and +`prismatic_with_properties` for a prismatic joint with its own geometry, velocity and +acceleration limits and component properties. + +Written by `viam kinematics convert`: `dh_converted` from `testfiles/ur5eDH.json`, +`mimic_gripper_converted` from `testfiles/test_mimic_gripper.json`, `urdf_converted` from a URDF +with a collision mesh and a visual referenced through `package://`, and +`continuous_joint_converted` from a URDF with a continuous joint. + +Every `error_*` case holds the smallest file that fails for its kind. diff --git a/tests/data/kinematic_models/continuous_joint_converted/expected.json b/tests/data/kinematic_models/continuous_joint_converted/expected.json new file mode 100644 index 0000000000..9391654a73 --- /dev/null +++ b/tests/data/kinematic_models/continuous_joint_converted/expected.json @@ -0,0 +1,32 @@ +{ + "name": "spinner", + "links": [ + { + "id": "base", + "pose": { + "translation": { + "z": 100 + }, + "euler_angles": {} + } + }, + { + "id": "tip", + "parent": "spin", + "pose": { + "translation": {} + } + } + ], + "joints": [ + { + "id": "spin", + "parent": "base", + "type": "JOINT_TYPE_CONTINUOUS", + "axis": { + "z": 1 + }, + "limits": {} + } + ] +} diff --git a/tests/data/kinematic_models/continuous_joint_converted/model.json b/tests/data/kinematic_models/continuous_joint_converted/model.json new file mode 100644 index 0000000000..9391654a73 --- /dev/null +++ b/tests/data/kinematic_models/continuous_joint_converted/model.json @@ -0,0 +1,32 @@ +{ + "name": "spinner", + "links": [ + { + "id": "base", + "pose": { + "translation": { + "z": 100 + }, + "euler_angles": {} + } + }, + { + "id": "tip", + "parent": "spin", + "pose": { + "translation": {} + } + } + ], + "joints": [ + { + "id": "spin", + "parent": "base", + "type": "JOINT_TYPE_CONTINUOUS", + "axis": { + "z": 1 + }, + "limits": {} + } + ] +} diff --git a/tests/data/kinematic_models/dh_converted/expected.json b/tests/data/kinematic_models/dh_converted/expected.json new file mode 100644 index 0000000000..5c01a5ae61 --- /dev/null +++ b/tests/data/kinematic_models/dh_converted/expected.json @@ -0,0 +1,154 @@ +{ + "name": "UR5e", + "links": [ + { + "id": "base", + "parent": "base_j", + "pose": { + "translation": { + "z": 162.5 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": 0.7071067811865475 + } + } + }, + { + "id": "shoulder", + "parent": "shoulder_j", + "pose": { + "translation": { + "x": -425 + }, + "quaternion": { + "w": 1 + } + } + }, + { + "id": "elbow", + "parent": "elbow_j", + "pose": { + "translation": { + "x": -392.2 + }, + "quaternion": { + "w": 1 + } + } + }, + { + "id": "wrist_1", + "parent": "wrist_1_j", + "pose": { + "translation": { + "z": 133.3 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": 0.7071067811865475 + } + } + }, + { + "id": "wrist_2", + "parent": "wrist_2_j", + "pose": { + "translation": { + "z": 99.69999999999999 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": -0.7071067811865475 + } + } + }, + { + "id": "wrist_3", + "parent": "wrist_3_j", + "pose": { + "translation": { + "z": 99.6 + }, + "quaternion": { + "w": 1 + } + } + } + ], + "joints": [ + { + "id": "base_j", + "parent": "world", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "shoulder_j", + "parent": "base", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "elbow_j", + "parent": "shoulder", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -180, + "max": 180 + } + }, + { + "id": "wrist_1_j", + "parent": "elbow", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "wrist_2_j", + "parent": "wrist_1", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "wrist_3_j", + "parent": "wrist_2", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + } + ] +} diff --git a/tests/data/kinematic_models/dh_converted/model.json b/tests/data/kinematic_models/dh_converted/model.json new file mode 100644 index 0000000000..5c01a5ae61 --- /dev/null +++ b/tests/data/kinematic_models/dh_converted/model.json @@ -0,0 +1,154 @@ +{ + "name": "UR5e", + "links": [ + { + "id": "base", + "parent": "base_j", + "pose": { + "translation": { + "z": 162.5 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": 0.7071067811865475 + } + } + }, + { + "id": "shoulder", + "parent": "shoulder_j", + "pose": { + "translation": { + "x": -425 + }, + "quaternion": { + "w": 1 + } + } + }, + { + "id": "elbow", + "parent": "elbow_j", + "pose": { + "translation": { + "x": -392.2 + }, + "quaternion": { + "w": 1 + } + } + }, + { + "id": "wrist_1", + "parent": "wrist_1_j", + "pose": { + "translation": { + "z": 133.3 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": 0.7071067811865475 + } + } + }, + { + "id": "wrist_2", + "parent": "wrist_2_j", + "pose": { + "translation": { + "z": 99.69999999999999 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": -0.7071067811865475 + } + } + }, + { + "id": "wrist_3", + "parent": "wrist_3_j", + "pose": { + "translation": { + "z": 99.6 + }, + "quaternion": { + "w": 1 + } + } + } + ], + "joints": [ + { + "id": "base_j", + "parent": "world", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "shoulder_j", + "parent": "base", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "elbow_j", + "parent": "shoulder", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -180, + "max": 180 + } + }, + { + "id": "wrist_1_j", + "parent": "elbow", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "wrist_2_j", + "parent": "wrist_1", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + }, + { + "id": "wrist_3_j", + "parent": "wrist_2", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -360, + "max": 360 + } + } + ] +} diff --git a/tests/data/kinematic_models/error_collision_mesh_format/error.json b/tests/data/kinematic_models/error_collision_mesh_format/error.json new file mode 100644 index 0000000000..5fffe6aebe --- /dev/null +++ b/tests/data/kinematic_models/error_collision_mesh_format/error.json @@ -0,0 +1,6 @@ +{ + "kind": "collision_format", + "mentions": [ + "glb" + ] +} diff --git a/tests/data/kinematic_models/error_collision_mesh_format/meshes/part.glb b/tests/data/kinematic_models/error_collision_mesh_format/meshes/part.glb new file mode 100644 index 0000000000..9e00702bd1 --- /dev/null +++ b/tests/data/kinematic_models/error_collision_mesh_format/meshes/part.glb @@ -0,0 +1 @@ +glTF \ No newline at end of file diff --git a/tests/data/kinematic_models/error_collision_mesh_format/model.json b/tests/data/kinematic_models/error_collision_mesh_format/model.json new file mode 100644 index 0000000000..1d29c79352 --- /dev/null +++ b/tests/data/kinematic_models/error_collision_mesh_format/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"original_file_source_path_diagnostic": "meshes/part.glb"}}]}]} diff --git a/tests/data/kinematic_models/error_content_type_mismatch/error.json b/tests/data/kinematic_models/error_content_type_mismatch/error.json new file mode 100644 index 0000000000..d198596fd2 --- /dev/null +++ b/tests/data/kinematic_models/error_content_type_mismatch/error.json @@ -0,0 +1,7 @@ +{ + "kind": "content_type_mismatch", + "mentions": [ + "stl", + "meshes/part.ply" + ] +} diff --git a/tests/data/kinematic_models/error_content_type_mismatch/meshes/part.ply b/tests/data/kinematic_models/error_content_type_mismatch/meshes/part.ply new file mode 100644 index 0000000000..8afc312b16 --- /dev/null +++ b/tests/data/kinematic_models/error_content_type_mismatch/meshes/part.ply @@ -0,0 +1,13 @@ +ply +format ascii 1.0 +element vertex 3 +property float x +property float y +property float z +element face 1 +property list uchar int vertex_indices +end_header +0 0 0 +1 0 0 +0 1 0 +3 0 1 2 diff --git a/tests/data/kinematic_models/error_content_type_mismatch/model.json b/tests/data/kinematic_models/error_content_type_mismatch/model.json new file mode 100644 index 0000000000..9f0d620232 --- /dev/null +++ b/tests/data/kinematic_models/error_content_type_mismatch/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"content_type": "stl", "original_file_source_path_diagnostic": "meshes/part.ply"}}]}]} diff --git a/tests/data/kinematic_models/error_cycle/error.json b/tests/data/kinematic_models/error_cycle/error.json new file mode 100644 index 0000000000..7352ae2ad4 --- /dev/null +++ b/tests/data/kinematic_models/error_cycle/error.json @@ -0,0 +1,4 @@ +{ + "kind": "cycle", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_cycle/model.json b/tests/data/kinematic_models/error_cycle/model.json new file mode 100644 index 0000000000..ec4eba28c8 --- /dev/null +++ b/tests/data/kinematic_models/error_cycle/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "a", "parent": "b"}, {"id": "b", "parent": "a"}]} diff --git a/tests/data/kinematic_models/error_duplicate_id/error.json b/tests/data/kinematic_models/error_duplicate_id/error.json new file mode 100644 index 0000000000..f201604e83 --- /dev/null +++ b/tests/data/kinematic_models/error_duplicate_id/error.json @@ -0,0 +1,6 @@ +{ + "kind": "duplicate_id", + "mentions": [ + "a" + ] +} diff --git a/tests/data/kinematic_models/error_duplicate_id/model.json b/tests/data/kinematic_models/error_duplicate_id/model.json new file mode 100644 index 0000000000..26742cd7c0 --- /dev/null +++ b/tests/data/kinematic_models/error_duplicate_id/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "a"}, {"id": "a"}]} diff --git a/tests/data/kinematic_models/error_empty_model/error.json b/tests/data/kinematic_models/error_empty_model/error.json new file mode 100644 index 0000000000..ec63f5ee62 --- /dev/null +++ b/tests/data/kinematic_models/error_empty_model/error.json @@ -0,0 +1,4 @@ +{ + "kind": "empty_model", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_empty_model/model.json b/tests/data/kinematic_models/error_empty_model/model.json new file mode 100644 index 0000000000..6191dd872b --- /dev/null +++ b/tests/data/kinematic_models/error_empty_model/model.json @@ -0,0 +1 @@ +{"name": "m"} diff --git a/tests/data/kinematic_models/error_infinite_limit/error.json b/tests/data/kinematic_models/error_infinite_limit/error.json new file mode 100644 index 0000000000..d16ca05d88 --- /dev/null +++ b/tests/data/kinematic_models/error_infinite_limit/error.json @@ -0,0 +1,6 @@ +{ + "kind": "infinite", + "mentions": [ + "max" + ] +} diff --git a/tests/data/kinematic_models/error_infinite_limit/model.json b/tests/data/kinematic_models/error_infinite_limit/model.json new file mode 100644 index 0000000000..2320d214b9 --- /dev/null +++ b/tests/data/kinematic_models/error_infinite_limit/model.json @@ -0,0 +1,2 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}], + "joints": [{"id": "j", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}, "limits": {"max": "Infinity"}}]} diff --git a/tests/data/kinematic_models/error_inline_mesh_without_type/error.json b/tests/data/kinematic_models/error_inline_mesh_without_type/error.json new file mode 100644 index 0000000000..91e4abfad0 --- /dev/null +++ b/tests/data/kinematic_models/error_inline_mesh_without_type/error.json @@ -0,0 +1,4 @@ +{ + "kind": "inline_without_type", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_inline_mesh_without_type/model.json b/tests/data/kinematic_models/error_inline_mesh_without_type/model.json new file mode 100644 index 0000000000..e23805997d --- /dev/null +++ b/tests/data/kinematic_models/error_inline_mesh_without_type/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"mesh": "cGx5"}}]}]} diff --git a/tests/data/kinematic_models/error_link_and_joint_share_id/error.json b/tests/data/kinematic_models/error_link_and_joint_share_id/error.json new file mode 100644 index 0000000000..1fb01d7188 --- /dev/null +++ b/tests/data/kinematic_models/error_link_and_joint_share_id/error.json @@ -0,0 +1,6 @@ +{ + "kind": "shared_id", + "mentions": [ + "a" + ] +} diff --git a/tests/data/kinematic_models/error_link_and_joint_share_id/model.json b/tests/data/kinematic_models/error_link_and_joint_share_id/model.json new file mode 100644 index 0000000000..def25a5d3f --- /dev/null +++ b/tests/data/kinematic_models/error_link_and_joint_share_id/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "a"}], "joints": [{"id": "a", "type": "JOINT_TYPE_REVOLUTE"}]} diff --git a/tests/data/kinematic_models/error_malformed_json/error.json b/tests/data/kinematic_models/error_malformed_json/error.json new file mode 100644 index 0000000000..04bd165a9b --- /dev/null +++ b/tests/data/kinematic_models/error_malformed_json/error.json @@ -0,0 +1,4 @@ +{ + "kind": "malformed_json", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_malformed_json/model.json b/tests/data/kinematic_models/error_malformed_json/model.json new file mode 100644 index 0000000000..29e7dfc5d5 --- /dev/null +++ b/tests/data/kinematic_models/error_malformed_json/model.json @@ -0,0 +1 @@ +{"name": "m" "links": [{"id": "base", "parent": "world"}]} diff --git a/tests/data/kinematic_models/error_mesh_empty/error.json b/tests/data/kinematic_models/error_mesh_empty/error.json new file mode 100644 index 0000000000..a2e8f0b768 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_empty/error.json @@ -0,0 +1,4 @@ +{ + "kind": "mesh_empty", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_mesh_empty/model.json b/tests/data/kinematic_models/error_mesh_empty/model.json new file mode 100644 index 0000000000..4d538afb7f --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_empty/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {}}]}]} diff --git a/tests/data/kinematic_models/error_mesh_missing/error.json b/tests/data/kinematic_models/error_mesh_missing/error.json new file mode 100644 index 0000000000..c4a6a1b521 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_missing/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mesh_missing", + "mentions": [ + "meshes/gone.ply" + ] +} diff --git a/tests/data/kinematic_models/error_mesh_missing/model.json b/tests/data/kinematic_models/error_mesh_missing/model.json new file mode 100644 index 0000000000..6ee7c8c184 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_missing/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"original_file_source_path_diagnostic": "meshes/gone.ply"}}]}]} diff --git a/tests/data/kinematic_models/error_mesh_path_absolute/error.json b/tests/data/kinematic_models/error_mesh_path_absolute/error.json new file mode 100644 index 0000000000..8124b6c6f8 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_absolute/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mesh_path_absolute", + "mentions": [ + "/meshes/part.ply" + ] +} diff --git a/tests/data/kinematic_models/error_mesh_path_absolute/model.json b/tests/data/kinematic_models/error_mesh_path_absolute/model.json new file mode 100644 index 0000000000..1b1a49d463 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_absolute/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"original_file_source_path_diagnostic": "/meshes/part.ply"}}]}]} diff --git a/tests/data/kinematic_models/error_mesh_path_backslash/error.json b/tests/data/kinematic_models/error_mesh_path_backslash/error.json new file mode 100644 index 0000000000..b74e6004be --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_backslash/error.json @@ -0,0 +1,4 @@ +{ + "kind": "mesh_path_backslash", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_mesh_path_backslash/model.json b/tests/data/kinematic_models/error_mesh_path_backslash/model.json new file mode 100644 index 0000000000..20e53a419d --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_backslash/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"original_file_source_path_diagnostic": "meshes\\part.ply"}}]}]} diff --git a/tests/data/kinematic_models/error_mesh_path_no_extension/error.json b/tests/data/kinematic_models/error_mesh_path_no_extension/error.json new file mode 100644 index 0000000000..fc6e5ee25c --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_no_extension/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mesh_no_extension", + "mentions": [ + "meshes/part" + ] +} diff --git a/tests/data/kinematic_models/error_mesh_path_no_extension/meshes/part b/tests/data/kinematic_models/error_mesh_path_no_extension/meshes/part new file mode 100644 index 0000000000..0d758c9c7b --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_no_extension/meshes/part @@ -0,0 +1 @@ +? \ No newline at end of file diff --git a/tests/data/kinematic_models/error_mesh_path_no_extension/model.json b/tests/data/kinematic_models/error_mesh_path_no_extension/model.json new file mode 100644 index 0000000000..f109033618 --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_no_extension/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "visual": [{"mesh": {"original_file_source_path_diagnostic": "meshes/part"}}]}]} diff --git a/tests/data/kinematic_models/error_mesh_path_uri/error.json b/tests/data/kinematic_models/error_mesh_path_uri/error.json new file mode 100644 index 0000000000..118f14352b --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_uri/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mesh_path_uri", + "mentions": [ + "package://m/part.ply" + ] +} diff --git a/tests/data/kinematic_models/error_mesh_path_uri/model.json b/tests/data/kinematic_models/error_mesh_path_uri/model.json new file mode 100644 index 0000000000..1f7ba8d5fd --- /dev/null +++ b/tests/data/kinematic_models/error_mesh_path_uri/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "collision": [{"mesh": {"original_file_source_path_diagnostic": "package://m/part.ply"}}]}]} diff --git a/tests/data/kinematic_models/error_mimic_not_a_joint/error.json b/tests/data/kinematic_models/error_mimic_not_a_joint/error.json new file mode 100644 index 0000000000..0915496c41 --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_not_a_joint/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mimic_not_joint", + "mentions": [ + "base" + ] +} diff --git a/tests/data/kinematic_models/error_mimic_not_a_joint/model.json b/tests/data/kinematic_models/error_mimic_not_a_joint/model.json new file mode 100644 index 0000000000..99aead60fe --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_not_a_joint/model.json @@ -0,0 +1,2 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}], + "joints": [{"id": "j", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}, "mimic": {"joint": "base"}}]} diff --git a/tests/data/kinematic_models/error_mimic_self/error.json b/tests/data/kinematic_models/error_mimic_self/error.json new file mode 100644 index 0000000000..1afc1228fa --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_self/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mimic_self", + "mentions": [ + "j" + ] +} diff --git a/tests/data/kinematic_models/error_mimic_self/model.json b/tests/data/kinematic_models/error_mimic_self/model.json new file mode 100644 index 0000000000..0fd84a0f87 --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_self/model.json @@ -0,0 +1,2 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}], + "joints": [{"id": "j", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}, "mimic": {"joint": "j"}}]} diff --git a/tests/data/kinematic_models/error_mimic_with_limits/error.json b/tests/data/kinematic_models/error_mimic_with_limits/error.json new file mode 100644 index 0000000000..09ab0a5054 --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_with_limits/error.json @@ -0,0 +1,6 @@ +{ + "kind": "mimic_with_limits", + "mentions": [ + "j2" + ] +} diff --git a/tests/data/kinematic_models/error_mimic_with_limits/model.json b/tests/data/kinematic_models/error_mimic_with_limits/model.json new file mode 100644 index 0000000000..2819181cf8 --- /dev/null +++ b/tests/data/kinematic_models/error_mimic_with_limits/model.json @@ -0,0 +1,3 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}], "joints": [ + {"id": "j", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}}, + {"id": "j2", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}, "mimic": {"joint": "j"}, "limits": {"max": 10}}]} diff --git a/tests/data/kinematic_models/error_missing_id/error.json b/tests/data/kinematic_models/error_missing_id/error.json new file mode 100644 index 0000000000..49dc824437 --- /dev/null +++ b/tests/data/kinematic_models/error_missing_id/error.json @@ -0,0 +1,4 @@ +{ + "kind": "missing_id", + "mentions": [] +} diff --git a/tests/data/kinematic_models/error_missing_id/model.json b/tests/data/kinematic_models/error_missing_id/model.json new file mode 100644 index 0000000000..c1d193f7e0 --- /dev/null +++ b/tests/data/kinematic_models/error_missing_id/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"parent": "world"}]} diff --git a/tests/data/kinematic_models/error_missing_parent/error.json b/tests/data/kinematic_models/error_missing_parent/error.json new file mode 100644 index 0000000000..cfd06e6811 --- /dev/null +++ b/tests/data/kinematic_models/error_missing_parent/error.json @@ -0,0 +1,7 @@ +{ + "kind": "missing_parent", + "mentions": [ + "tool", + "bsae" + ] +} diff --git a/tests/data/kinematic_models/error_missing_parent/model.json b/tests/data/kinematic_models/error_missing_parent/model.json new file mode 100644 index 0000000000..41c3f63062 --- /dev/null +++ b/tests/data/kinematic_models/error_missing_parent/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}, {"id": "tool", "parent": "bsae"}]} diff --git a/tests/data/kinematic_models/error_nan_limit/error.json b/tests/data/kinematic_models/error_nan_limit/error.json new file mode 100644 index 0000000000..1ff0510349 --- /dev/null +++ b/tests/data/kinematic_models/error_nan_limit/error.json @@ -0,0 +1,6 @@ +{ + "kind": "nan", + "mentions": [ + "min" + ] +} diff --git a/tests/data/kinematic_models/error_nan_limit/model.json b/tests/data/kinematic_models/error_nan_limit/model.json new file mode 100644 index 0000000000..64b46acfec --- /dev/null +++ b/tests/data/kinematic_models/error_nan_limit/model.json @@ -0,0 +1,2 @@ +{"name": "m", "links": [{"id": "base", "parent": "world"}], + "joints": [{"id": "j", "parent": "base", "type": "JOINT_TYPE_REVOLUTE", "axis": {"z": 1}, "limits": {"min": "NaN"}}]} diff --git a/tests/data/kinematic_models/error_reserved_id/error.json b/tests/data/kinematic_models/error_reserved_id/error.json new file mode 100644 index 0000000000..2f15a48f43 --- /dev/null +++ b/tests/data/kinematic_models/error_reserved_id/error.json @@ -0,0 +1,6 @@ +{ + "kind": "reserved_id", + "mentions": [ + "world" + ] +} diff --git a/tests/data/kinematic_models/error_reserved_id/model.json b/tests/data/kinematic_models/error_reserved_id/model.json new file mode 100644 index 0000000000..35c0ceab58 --- /dev/null +++ b/tests/data/kinematic_models/error_reserved_id/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "world"}]} diff --git a/tests/data/kinematic_models/error_unknown_field/error.json b/tests/data/kinematic_models/error_unknown_field/error.json new file mode 100644 index 0000000000..705b0a1c4f --- /dev/null +++ b/tests/data/kinematic_models/error_unknown_field/error.json @@ -0,0 +1,6 @@ +{ + "kind": "unknown_field", + "mentions": [ + "colision" + ] +} diff --git a/tests/data/kinematic_models/error_unknown_field/model.json b/tests/data/kinematic_models/error_unknown_field/model.json new file mode 100644 index 0000000000..9896080593 --- /dev/null +++ b/tests/data/kinematic_models/error_unknown_field/model.json @@ -0,0 +1 @@ +{"name": "m", "links": [{"id": "base", "parent": "world", "colision": []}]} diff --git a/tests/data/kinematic_models/geometries/expected.json b/tests/data/kinematic_models/geometries/expected.json new file mode 100644 index 0000000000..7274f56160 --- /dev/null +++ b/tests/data/kinematic_models/geometries/expected.json @@ -0,0 +1,82 @@ +{ + "name": "geometries", + "links": [ + { + "id": "base", + "parent": "world", + "collision": [ + { + "center": { + "x": 10, + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 20, + "y": 30, + "z": 40 + } + }, + "label": "box" + }, + { + "center": { + "y": 10, + "o_z": 1 + }, + "sphere": { + "radius_mm": 15 + }, + "label": "sphere" + }, + { + "center": { + "z": 10, + "o_x": 1, + "theta": 90 + }, + "capsule": { + "radius_mm": 5, + "length_mm": 50 + }, + "label": "capsule" + }, + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK" + }, + "label": "mesh" + } + ], + "visual": [ + { + "center": { + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 22, + "y": 32, + "z": 42 + } + }, + "label": "shell" + }, + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "glb", + "mesh": "Z2xURiB2aXN1YWwgYnl0ZXM=" + }, + "label": "skin" + } + ] + } + ] +} diff --git a/tests/data/kinematic_models/geometries/model.json b/tests/data/kinematic_models/geometries/model.json new file mode 100644 index 0000000000..46558a3b8b --- /dev/null +++ b/tests/data/kinematic_models/geometries/model.json @@ -0,0 +1,82 @@ +{ + "name": "geometries", + "links": [ + { + "id": "base", + "parent": "world", + "collision": [ + { + "center": { + "x": 10, + "o_z": 1 + }, + "label": "box", + "box": { + "dims_mm": { + "x": 20, + "y": 30, + "z": 40 + } + } + }, + { + "center": { + "y": 10, + "o_z": 1 + }, + "label": "sphere", + "sphere": { + "radius_mm": 15 + } + }, + { + "center": { + "z": 10, + "o_x": 1, + "theta": 90 + }, + "label": "capsule", + "capsule": { + "radius_mm": 5, + "length_mm": 50 + } + }, + { + "center": { + "o_z": 1 + }, + "label": "mesh", + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK" + } + } + ], + "visual": [ + { + "center": { + "o_z": 1 + }, + "label": "shell", + "box": { + "dims_mm": { + "x": 22, + "y": 32, + "z": 42 + } + } + }, + { + "center": { + "o_z": 1 + }, + "label": "skin", + "mesh": { + "content_type": "glb", + "mesh": "Z2xURiB2aXN1YWwgYnl0ZXM=" + } + } + ] + } + ] +} diff --git a/tests/data/kinematic_models/mesh_by_path/expected.json b/tests/data/kinematic_models/mesh_by_path/expected.json new file mode 100644 index 0000000000..a57d2b5563 --- /dev/null +++ b/tests/data/kinematic_models/mesh_by_path/expected.json @@ -0,0 +1,63 @@ +{ + "name": "mesh_by_path", + "links": [ + { + "id": "base", + "parent": "world", + "collision": [ + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK", + "original_file_source_path_diagnostic": "meshes/part.ply" + }, + "label": "part" + } + ], + "visual": [ + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "glb", + "mesh": "Z2xURiB2aXN1YWwgYnl0ZXM=", + "original_file_source_path_diagnostic": "meshes/shell.glb" + }, + "label": "shell" + } + ] + }, + { + "id": "tip", + "parent": "base", + "collision": [ + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK", + "original_file_source_path_diagnostic": "meshes/part.ply" + }, + "label": "part_again" + }, + { + "center": { + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK", + "original_file_source_path_diagnostic": "meshes/../meshes/part.ply" + }, + "label": "up_and_down" + } + ] + } + ] +} diff --git a/tests/data/kinematic_models/mesh_by_path/meshes/part.ply b/tests/data/kinematic_models/mesh_by_path/meshes/part.ply new file mode 100644 index 0000000000..8afc312b16 --- /dev/null +++ b/tests/data/kinematic_models/mesh_by_path/meshes/part.ply @@ -0,0 +1,13 @@ +ply +format ascii 1.0 +element vertex 3 +property float x +property float y +property float z +element face 1 +property list uchar int vertex_indices +end_header +0 0 0 +1 0 0 +0 1 0 +3 0 1 2 diff --git a/tests/data/kinematic_models/mesh_by_path/meshes/shell.glb b/tests/data/kinematic_models/mesh_by_path/meshes/shell.glb new file mode 100644 index 0000000000..610378f556 --- /dev/null +++ b/tests/data/kinematic_models/mesh_by_path/meshes/shell.glb @@ -0,0 +1 @@ +glTF visual bytes \ No newline at end of file diff --git a/tests/data/kinematic_models/mesh_by_path/model.json b/tests/data/kinematic_models/mesh_by_path/model.json new file mode 100644 index 0000000000..d1200d5f8c --- /dev/null +++ b/tests/data/kinematic_models/mesh_by_path/model.json @@ -0,0 +1,57 @@ +{ + "name": "mesh_by_path", + "links": [ + { + "id": "base", + "parent": "world", + "collision": [ + { + "center": { + "o_z": 1 + }, + "label": "part", + "mesh": { + "original_file_source_path_diagnostic": "meshes/part.ply" + } + } + ], + "visual": [ + { + "center": { + "o_z": 1 + }, + "label": "shell", + "mesh": { + "content_type": "model/gltf-binary", + "original_file_source_path_diagnostic": "meshes/shell.glb" + } + } + ] + }, + { + "id": "tip", + "parent": "base", + "collision": [ + { + "center": { + "o_z": 1 + }, + "label": "part_again", + "mesh": { + "content_type": "PLY", + "original_file_source_path_diagnostic": "meshes/part.ply" + } + }, + { + "center": { + "o_z": 1 + }, + "label": "up_and_down", + "mesh": { + "original_file_source_path_diagnostic": "meshes/../meshes/part.ply" + } + } + ] + } + ] +} diff --git a/tests/data/kinematic_models/mimic_gripper_converted/expected.json b/tests/data/kinematic_models/mimic_gripper_converted/expected.json new file mode 100644 index 0000000000..0f80ce522d --- /dev/null +++ b/tests/data/kinematic_models/mimic_gripper_converted/expected.json @@ -0,0 +1,100 @@ +{ + "name": "test_mimic_gripper", + "links": [ + { + "id": "base", + "parent": "world", + "pose": { + "translation": {} + } + }, + { + "id": "tcp", + "parent": "base", + "pose": { + "translation": { + "z": 30 + } + } + }, + { + "id": "left_finger", + "parent": "left_joint", + "pose": { + "translation": { + "z": 30 + } + }, + "collision": [ + { + "center": { + "z": 15, + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 30 + } + }, + "label": "left_finger" + } + ] + }, + { + "id": "right_finger", + "parent": "right_joint", + "pose": { + "translation": { + "z": 30 + } + }, + "collision": [ + { + "center": { + "z": 15, + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 30 + } + }, + "label": "right_finger" + } + ] + } + ], + "joints": [ + { + "id": "left_joint", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "y": 1 + }, + "limits": { + "min": 0, + "max": 50 + } + }, + { + "id": "right_joint", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "y": -1 + }, + "mimic": { + "joint": "left_joint", + "multiplier": 1 + } + } + ], + "output_frames": [ + "tcp" + ] +} diff --git a/tests/data/kinematic_models/mimic_gripper_converted/model.json b/tests/data/kinematic_models/mimic_gripper_converted/model.json new file mode 100644 index 0000000000..0f80ce522d --- /dev/null +++ b/tests/data/kinematic_models/mimic_gripper_converted/model.json @@ -0,0 +1,100 @@ +{ + "name": "test_mimic_gripper", + "links": [ + { + "id": "base", + "parent": "world", + "pose": { + "translation": {} + } + }, + { + "id": "tcp", + "parent": "base", + "pose": { + "translation": { + "z": 30 + } + } + }, + { + "id": "left_finger", + "parent": "left_joint", + "pose": { + "translation": { + "z": 30 + } + }, + "collision": [ + { + "center": { + "z": 15, + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 30 + } + }, + "label": "left_finger" + } + ] + }, + { + "id": "right_finger", + "parent": "right_joint", + "pose": { + "translation": { + "z": 30 + } + }, + "collision": [ + { + "center": { + "z": 15, + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 30 + } + }, + "label": "right_finger" + } + ] + } + ], + "joints": [ + { + "id": "left_joint", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "y": 1 + }, + "limits": { + "min": 0, + "max": 50 + } + }, + { + "id": "right_joint", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "y": -1 + }, + "mimic": { + "joint": "left_joint", + "multiplier": 1 + } + } + ], + "output_frames": [ + "tcp" + ] +} diff --git a/tests/data/kinematic_models/orientations/expected.json b/tests/data/kinematic_models/orientations/expected.json new file mode 100644 index 0000000000..813f7c4633 --- /dev/null +++ b/tests/data/kinematic_models/orientations/expected.json @@ -0,0 +1,65 @@ +{ + "name": "orientations", + "links": [ + { + "id": "identity", + "parent": "world", + "pose": { + "translation": { + "x": 1, + "y": 2, + "z": 3 + } + } + }, + { + "id": "quaternion", + "parent": "identity", + "pose": { + "translation": { + "z": 10 + }, + "quaternion": { + "w": 0.7071067811865476, + "z": 0.7071067811865476 + } + } + }, + { + "id": "orientation_vector", + "parent": "quaternion", + "pose": { + "translation": { + "x": 5 + }, + "orientation_vector": { + "o_y": 1, + "theta": 45 + } + } + }, + { + "id": "euler_angles", + "parent": "orientation_vector", + "pose": { + "euler_angles": { + "roll": 90, + "yaw": -30 + } + } + }, + { + "id": "axis_angles", + "parent": "euler_angles", + "pose": { + "translation": { + "y": -4 + }, + "axis_angles": { + "rx": 1, + "theta": 180 + } + } + } + ] +} diff --git a/tests/data/kinematic_models/orientations/model.json b/tests/data/kinematic_models/orientations/model.json new file mode 100644 index 0000000000..034ad2cf0a --- /dev/null +++ b/tests/data/kinematic_models/orientations/model.json @@ -0,0 +1,72 @@ +{ + "name": "orientations", + "links": [ + { + "id": "identity", + "parent": "world", + "pose": { + "translation": { + "x": 1, + "y": 2, + "z": 3 + } + } + }, + { + "id": "quaternion", + "parent": "identity", + "pose": { + "translation": { + "z": 10 + }, + "quaternion": { + "w": 0.7071067811865476, + "x": 0, + "y": 0, + "z": 0.7071067811865476 + } + } + }, + { + "id": "orientation_vector", + "parent": "quaternion", + "pose": { + "translation": { + "x": 5 + }, + "orientation_vector": { + "o_x": 0, + "o_y": 1, + "o_z": 0, + "theta": 45 + } + } + }, + { + "id": "euler_angles", + "parent": "orientation_vector", + "pose": { + "euler_angles": { + "roll": 90, + "pitch": 0, + "yaw": -30 + } + } + }, + { + "id": "axis_angles", + "parent": "euler_angles", + "pose": { + "translation": { + "y": -4 + }, + "axis_angles": { + "rx": 1, + "ry": 0, + "rz": 0, + "theta": 180 + } + } + } + ] +} diff --git a/tests/data/kinematic_models/prismatic_with_properties/expected.json b/tests/data/kinematic_models/prismatic_with_properties/expected.json new file mode 100644 index 0000000000..8186d53b0e --- /dev/null +++ b/tests/data/kinematic_models/prismatic_with_properties/expected.json @@ -0,0 +1,46 @@ +{ + "name": "slider", + "links": [ + { + "id": "base", + "parent": "world" + }, + { + "id": "tip", + "parent": "slide" + } + ], + "joints": [ + { + "id": "slide", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "x": 1 + }, + "limits": { + "min": 0, + "max": 500, + "max_velocity": 100, + "max_acceleration": 1000 + }, + "geometry": { + "center": { + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 10 + } + }, + "label": "carriage" + } + } + ], + "properties": { + "operating_freq_hz": 100, + "max_linear_tcp_speed_mm_per_sec": 250 + } +} diff --git a/tests/data/kinematic_models/prismatic_with_properties/model.json b/tests/data/kinematic_models/prismatic_with_properties/model.json new file mode 100644 index 0000000000..b5cc51bade --- /dev/null +++ b/tests/data/kinematic_models/prismatic_with_properties/model.json @@ -0,0 +1,46 @@ +{ + "name": "slider", + "links": [ + { + "id": "base", + "parent": "world" + }, + { + "id": "tip", + "parent": "slide" + } + ], + "joints": [ + { + "id": "slide", + "parent": "base", + "type": "JOINT_TYPE_PRISMATIC", + "axis": { + "x": 1 + }, + "limits": { + "min": 0, + "max": 500, + "max_velocity": 100, + "max_acceleration": 1000 + }, + "geometry": { + "center": { + "o_z": 1 + }, + "label": "carriage", + "box": { + "dims_mm": { + "x": 10, + "y": 10, + "z": 10 + } + } + } + } + ], + "properties": { + "operating_freq_hz": 100, + "max_linear_tcp_speed_mm_per_sec": 250 + } +} diff --git a/tests/data/kinematic_models/single_link/expected.json b/tests/data/kinematic_models/single_link/expected.json new file mode 100644 index 0000000000..84b2b7da40 --- /dev/null +++ b/tests/data/kinematic_models/single_link/expected.json @@ -0,0 +1,9 @@ +{ + "name": "single_link", + "links": [ + { + "id": "base", + "parent": "world" + } + ] +} diff --git a/tests/data/kinematic_models/single_link/model.json b/tests/data/kinematic_models/single_link/model.json new file mode 100644 index 0000000000..84b2b7da40 --- /dev/null +++ b/tests/data/kinematic_models/single_link/model.json @@ -0,0 +1,9 @@ +{ + "name": "single_link", + "links": [ + { + "id": "base", + "parent": "world" + } + ] +} diff --git a/tests/data/kinematic_models/urdf_converted/expected.json b/tests/data/kinematic_models/urdf_converted/expected.json new file mode 100644 index 0000000000..5cb723c6b5 --- /dev/null +++ b/tests/data/kinematic_models/urdf_converted/expected.json @@ -0,0 +1,79 @@ +{ + "name": "converted", + "links": [ + { + "id": "base", + "pose": { + "translation": { + "z": 100 + }, + "euler_angles": { + "yaw": 89.99999846476551 + } + }, + "collision": [ + { + "center": { + "z": 50, + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "mesh": "cGx5CmZvcm1hdCBhc2NpaSAxLjAKZWxlbWVudCB2ZXJ0ZXggMwpwcm9wZXJ0eSBmbG9hdCB4CnByb3BlcnR5IGZsb2F0IHkKcHJvcGVydHkgZmxvYXQgegplbGVtZW50IGZhY2UgMQpwcm9wZXJ0eSBsaXN0IHVjaGFyIGludCB2ZXJ0ZXhfaW5kaWNlcwplbmRfaGVhZGVyCjAgMCAwCjEgMCAwCjAgMSAwCjMgMCAxIDIK", + "original_file_source_path_diagnostic": "meshes/model/collision/base.ply" + }, + "label": "base" + } + ], + "visual": [ + { + "center": { + "z": 10, + "o_z": 1 + }, + "mesh": { + "content_type": "glb", + "mesh": "Z2xURiB2aXN1YWwgYnl0ZXM=", + "original_file_source_path_diagnostic": "meshes/model/visual/base.glb" + } + } + ] + }, + { + "id": "tip", + "parent": "j1", + "pose": { + "translation": {} + }, + "collision": [ + { + "center": { + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 20, + "y": 20, + "z": 20 + } + }, + "label": "tip" + } + ] + } + ], + "joints": [ + { + "id": "j1", + "parent": "base", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -89.95437383553926, + "max": 89.95437383553926 + } + } + ] +} diff --git a/tests/data/kinematic_models/urdf_converted/meshes/model/collision/base.ply b/tests/data/kinematic_models/urdf_converted/meshes/model/collision/base.ply new file mode 100644 index 0000000000..8afc312b16 --- /dev/null +++ b/tests/data/kinematic_models/urdf_converted/meshes/model/collision/base.ply @@ -0,0 +1,13 @@ +ply +format ascii 1.0 +element vertex 3 +property float x +property float y +property float z +element face 1 +property list uchar int vertex_indices +end_header +0 0 0 +1 0 0 +0 1 0 +3 0 1 2 diff --git a/tests/data/kinematic_models/urdf_converted/meshes/model/visual/base.glb b/tests/data/kinematic_models/urdf_converted/meshes/model/visual/base.glb new file mode 100644 index 0000000000..610378f556 --- /dev/null +++ b/tests/data/kinematic_models/urdf_converted/meshes/model/visual/base.glb @@ -0,0 +1 @@ +glTF visual bytes \ No newline at end of file diff --git a/tests/data/kinematic_models/urdf_converted/model.json b/tests/data/kinematic_models/urdf_converted/model.json new file mode 100644 index 0000000000..e6b407c014 --- /dev/null +++ b/tests/data/kinematic_models/urdf_converted/model.json @@ -0,0 +1,77 @@ +{ + "name": "converted", + "links": [ + { + "id": "base", + "pose": { + "translation": { + "z": 100 + }, + "euler_angles": { + "yaw": 89.99999846476551 + } + }, + "collision": [ + { + "center": { + "z": 50, + "o_z": 1 + }, + "mesh": { + "content_type": "ply", + "original_file_source_path_diagnostic": "meshes/model/collision/base.ply" + }, + "label": "base" + } + ], + "visual": [ + { + "center": { + "z": 10, + "o_z": 1 + }, + "mesh": { + "content_type": "glb", + "original_file_source_path_diagnostic": "meshes/model/visual/base.glb" + } + } + ] + }, + { + "id": "tip", + "parent": "j1", + "pose": { + "translation": {} + }, + "collision": [ + { + "center": { + "o_z": 1 + }, + "box": { + "dims_mm": { + "x": 20, + "y": 20, + "z": 20 + } + }, + "label": "tip" + } + ] + } + ], + "joints": [ + { + "id": "j1", + "parent": "base", + "type": "JOINT_TYPE_REVOLUTE", + "axis": { + "z": 1 + }, + "limits": { + "min": -89.95437383553926, + "max": 89.95437383553926 + } + } + ] +} diff --git a/tests/mocks/components.py b/tests/mocks/components.py index 9ffdd8aefd..67913673b3 100644 --- a/tests/mocks/components.py +++ b/tests/mocks/components.py @@ -32,13 +32,14 @@ from viam.components.sensor import Sensor from viam.components.servo import Servo from viam.components.switch import Switch -from viam.errors import ResourceNotFoundError +from viam.errors import MethodNotImplementedError, ResourceNotFoundError from viam.media.video import CameraMimeType, NamedImage, ViamImage from viam.proto.common import ( AudioInfo, Capsule, Geometry, GeoPoint, + KinematicModel, Mesh, Orientation, Pose, @@ -180,6 +181,24 @@ async def get_kinematics( self.timeout = timeout return self.kinematics + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + model = getattr(self, "kinematic_model", None) + if model is None: + raise MethodNotImplementedError("get_kinematic_model") + self.include_collision_meshes = include_collision_meshes + self.include_visual_meshes = include_visual_meshes + self.extra = extra + self.timeout = timeout + return model + async def get_geometries(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> List[Geometry]: self.extra = extra self.timeout = timeout @@ -695,6 +714,24 @@ async def get_kinematics( self.timeout = timeout return self.kinematics + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + model = getattr(self, "kinematic_model", None) + if model is None: + raise MethodNotImplementedError("get_kinematic_model") + self.include_collision_meshes = include_collision_meshes + self.include_visual_meshes = include_visual_meshes + self.extra = extra + self.timeout = timeout + return model + async def get_geometries(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> List[Geometry]: self.extra = extra self.timeout = timeout @@ -785,6 +822,24 @@ async def get_kinematics( self.timeout = timeout return self.kinematics + async def get_kinematic_model( + self, + *, + include_collision_meshes: bool = False, + include_visual_meshes: bool = False, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> KinematicModel: + model = getattr(self, "kinematic_model", None) + if model is None: + raise MethodNotImplementedError("get_kinematic_model") + self.include_collision_meshes = include_collision_meshes + self.include_visual_meshes = include_visual_meshes + self.extra = extra + self.timeout = timeout + return model + async def do_command(self, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]: return {"command": command} diff --git a/tests/test_kinematics.py b/tests/test_kinematics.py new file mode 100644 index 0000000000..dc3974378f --- /dev/null +++ b/tests/test_kinematics.py @@ -0,0 +1,447 @@ +import base64 +import json +import math +import os +from typing import Any, Dict + +import pytest +from google.protobuf import json_format +from grpclib import GRPCError +from grpclib.testing import ChannelFor + +from viam.components import KinematicsReturn +from viam.components.arm import Arm, ArmClient, ArmRPCService +from viam.components.gantry import GantryClient, GantryRPCService +from viam.components.gripper import GripperClient, GripperRPCService +from viam.errors import MethodNotImplementedError, NotSupportedError +from viam.kinematics import _sva_file, narrow_joint_limits, read_kinematic_model_file +from viam.proto.common import ( + Geometry, + GetKinematicsRequest, + GetKinematicsResponse, + JointLimits, + JointType, + KinematicJoint, + KinematicLink, + KinematicModel, + KinematicsFileFormat, + LinkPose, + Mesh, + MimicJoint, + Orientation, + Pose, + RectangularPrism, + Sphere, + Vector3, +) +from viam.proto.component.arm import ArmServiceStub +from viam.resource.manager import ResourceManager + +from .mocks.components import MockArm, MockGantry, MockGripper + +# A pinned copy of referenceframe/testfiles/kinematic_models in rdk, taken at cefbb7080. The README in it is the contract, and the +# Go, C++ and Python loaders are all held to the same files, so refresh the whole directory from rdk rather than editing a case here. +FIXTURES = os.path.join(os.path.dirname(__file__), "data", "kinematic_models") + +# What our loader says for each error kind the fixtures name. The kinds are listed in the fixture README, the wording is our own. +ERROR_KINDS = { + "unknown_field": "no field named", + "infinite": "is infinite", + "nan": "is not a number", + "malformed_json": "malformed JSON", + "empty_model": "no links or joints", + "missing_id": "has no id", + "reserved_id": "reserved id", + "shared_id": "names both a link and a joint", + "duplicate_id": "is defined twice", + "missing_parent": "is not a link or joint", + "cycle": "its own ancestor", + "mimic_self": "mimics itself", + "mimic_not_joint": "which is not a joint", + "mimic_with_limits": "cannot carry limits", + "mesh_missing": "failed to read mesh", + "mesh_path_absolute": "is absolute", + "mesh_path_uri": "is a URI", + "mesh_path_backslash": "uses backslashes", + "content_type_mismatch": "disagrees", + "collision_format": "is not stl or ply", + "mesh_no_extension": "has no extension", + "inline_without_type": "need a content type", + "mesh_empty": "neither bytes nor a source path", +} + +CASES = sorted(entry for entry in os.listdir(FIXTURES) if os.path.isdir(os.path.join(FIXTURES, entry))) + + +def expected_model(case: str) -> KinematicModel: + with open(os.path.join(FIXTURES, case, "expected.json")) as f: + return json_format.Parse(f.read(), KinematicModel()) + + +class TestFixtures: + def test_all_cases_present(self): + assert len(CASES) == 32 + + @pytest.mark.parametrize("case", CASES) + def test_case(self, case: str): + model_path = os.path.join(FIXTURES, case, "model.json") + error_path = os.path.join(FIXTURES, case, "error.json") + if os.path.exists(error_path): + with open(error_path) as f: + want = json.load(f) + with pytest.raises(ValueError) as raised: + read_kinematic_model_file(model_path) + message = str(raised.value) + assert ERROR_KINDS[want["kind"]] in message + for mention in want["mentions"]: + assert mention in message + return + assert read_kinematic_model_file(model_path) == expected_model(case) + + def test_missing_file(self): + with pytest.raises(OSError): + read_kinematic_model_file(os.path.join(FIXTURES, "nothing_here.json")) + + def test_bare_constants_are_not_json(self, tmp_path): + path = tmp_path / "model.json" + path.write_text('{"links": [{"id": "a"}], "joints": [{"id": "j", "limits": {"min": NaN}}]}') + with pytest.raises(ValueError, match="malformed JSON"): + read_kinematic_model_file(path) + + def test_literal_too_large_for_a_double(self, tmp_path): + path = tmp_path / "model.json" + path.write_text('{"links": [{"id": "a"}], "joints": [{"id": "j", "limits": {"max": 1e999}}]}') + with pytest.raises(ValueError, match="is infinite"): + read_kinematic_model_file(path) + + def test_duplicate_key(self, tmp_path): + path = tmp_path / "model.json" + path.write_text('{"name": "a", "name": "b", "links": [{"id": "a"}]}') + with pytest.raises(ValueError, match="duplicate key"): + read_kinematic_model_file(path) + + +def planar_arm() -> KinematicModel: + return KinematicModel( + name="planar", + links=[ + KinematicLink(id="base", parent="world"), + KinematicLink(id="upper", parent="shoulder", pose=LinkPose(translation=Vector3(x=100))), + ], + joints=[ + KinematicJoint( + id="shoulder", + parent="base", + type=JointType.JOINT_TYPE_REVOLUTE, + axis=Vector3(z=1), + limits=JointLimits(min=-180, max=180, max_velocity=90), + ), + KinematicJoint(id="wrist", parent="upper", type=JointType.JOINT_TYPE_CONTINUOUS, axis=Vector3(z=1)), + KinematicJoint( + id="follower", + parent="wrist", + type=JointType.JOINT_TYPE_REVOLUTE, + axis=Vector3(z=1), + mimic=MimicJoint(joint="wrist", multiplier=-1), + ), + ], + ) + + +class TestNarrowJointLimits: + def test_narrows_and_leaves_the_input_alone(self): + model = planar_arm() + out = narrow_joint_limits(model, {"shoulder": {"min": -90, "max_velocity": 30, "max_acceleration": 400}}) + assert model == planar_arm() + shoulder = out.joints[0].limits + assert (shoulder.min, shoulder.max, shoulder.max_velocity, shoulder.max_acceleration) == (-90, 180, 30, 400) + assert out.joints[1] == model.joints[1] + + def test_empty_request_changes_nothing(self): + assert narrow_joint_limits(planar_arm(), {}) == planar_arm() + assert narrow_joint_limits(planar_arm(), {"shoulder": {}}) == planar_arm() + + def test_lock_in_place(self): + out = narrow_joint_limits(planar_arm(), {"shoulder": {"min": 10, "max": 10}}) + assert (out.joints[0].limits.min, out.joints[0].limits.max) == (10, 10) + + def test_bounding_a_continuous_joint_makes_it_revolute(self): + out = narrow_joint_limits(planar_arm(), {"wrist": {"max_velocity": 10}}) + assert out.joints[1].type == JointType.JOINT_TYPE_CONTINUOUS + out = narrow_joint_limits(planar_arm(), {"wrist": {"min": -720}}) + assert out.joints[1].type == JointType.JOINT_TYPE_REVOLUTE + assert out.joints[1].limits.min == -720 + assert not out.joints[1].limits.HasField("max") + + def test_bound_that_went_through_radians(self): + model = planar_arm() + model.joints[0].limits.max = math.degrees(math.radians(180)) + 1e-9 + out = narrow_joint_limits(model, {"shoulder": {"max": 180}}) + assert out.joints[0].limits.max == 180 + + @pytest.mark.parametrize("field,value", [("min", -math.degrees(2.0)), ("max", math.degrees(2.0)), ("max_velocity", math.degrees(1.1))]) + def test_the_models_own_limit_is_not_a_widening(self, field: str, value: float): + model = planar_arm() + setattr(model.joints[0].limits, field, value) + assert narrow_joint_limits(model, {"shoulder": {field: value}}) == model + assert narrow_joint_limits(model, {"shoulder": {field: round(value, 6)}}).joints[0].limits.HasField(field) + + @pytest.mark.parametrize( + "limits,says", + [ + ({"shoulder": {"min": -181}}, 'joint "shoulder": min -181 is below'), + ({"shoulder": {"max": 180.5}}, 'joint "shoulder": max 180.5 is above'), + ({"shoulder": {"max_velocity": 91}}, 'joint "shoulder": max_velocity 91 is above'), + ({"shoulder": {"min": 10, "max": 5}}, 'joint "shoulder": min 10.0 is above max 5.0'), + ({"shoulder": {"max_velocity": -1}}, "cannot be negative"), + ({"shoulder": {"max": float("inf")}}, "must be a finite number"), + ({"shoulder": {"max": float("nan")}}, "must be a finite number"), + ({"shoulder": {"max": "10"}}, "must be a finite number"), + ({"shoulder": {"maximum": 10}}, 'unknown limit "maximum"'), + ({"shoulder": 10}, "have to be a mapping"), + ({"elbow": {"max": 10}}, 'no joint "elbow" in model "planar"'), + ({"base": {"max": 10}}, 'no joint "base"'), + ({"follower": {"max": 10}}, "mimic joint"), + # ids are taken in order, so the first bad joint is the one named + ({"shoulder": {"min": -181}, "elbow": {"max": 10}}, "elbow"), + ], + ) + def test_refused(self, limits: Dict[str, Any], says: str): + model = planar_arm() + with pytest.raises(ValueError) as raised: + narrow_joint_limits(model, limits) + assert says in str(raised.value) + assert model == planar_arm() + + +class TestSVAFile: + def test_document(self): + model = planar_arm() + model.joints[1].limits.min = -360 + model.joints[1].limits.max = 360 + model.output_frames.append("upper") + model.links[0].collision.append(Geometry(center=Pose(z=5, o_z=1), box=RectangularPrism(dims_mm=Vector3(x=1, y=2, z=3)), label="b")) + model.links[0].collision.append(Geometry(center=Pose(o_x=1, theta=90), sphere=Sphere(radius_mm=4))) + model.links[0].visual.append(Geometry(mesh=Mesh(content_type="glb", mesh=b"glb"))) + model.links[1].pose.orientation_vector.CopyFrom(Orientation(o_z=1, theta=45)) + model.links[1].collision.append( + Geometry(mesh=Mesh(content_type="ply", mesh=b"ply", original_file_source_path_diagnostic="a/b.ply")) + ) + file = _sva_file(model) + assert file is not None + assert json.loads(file) == { + "name": "planar", + "kinematic_param_type": "SVA", + "output_frames": ["upper"], + "links": [ + { + "id": "base", + "parent": "world", + "translation": {"x": 0, "y": 0, "z": 0}, + "geometry": {"type": "box", "x": 1, "y": 2, "z": 3, "translation": {"x": 0, "y": 0, "z": 5}, "label": "b"}, + "geometries": [ + { + "type": "sphere", + "r": 4, + "translation": {"x": 0, "y": 0, "z": 0}, + "orientation": {"type": "ov_degrees", "value": {"th": 90, "x": 1, "y": 0, "z": 0}}, + } + ], + }, + { + "id": "upper", + "parent": "shoulder", + "translation": {"x": 100, "y": 0, "z": 0}, + "orientation": {"type": "ov_degrees", "value": {"th": 45, "x": 0, "y": 0, "z": 1}}, + "geometry": { + "type": "mesh", + "mesh_data": base64.b64encode(b"ply").decode(), + "mesh_content_type": "ply", + "mesh_file_path": "a/b.ply", + "translation": {"x": 0, "y": 0, "z": 0}, + }, + }, + ], + "joints": [ + { + "id": "shoulder", + "type": "revolute", + "parent": "base", + "axis": {"x": 0, "y": 0, "z": 1}, + "min": -180, + "max": 180, + "max_velocity": 90, + }, + {"id": "wrist", "type": "revolute", "parent": "upper", "axis": {"x": 0, "y": 0, "z": 1}, "min": -360, "max": 360}, + { + "id": "follower", + "type": "revolute", + "parent": "wrist", + "axis": {"x": 0, "y": 0, "z": 1}, + "mimic": {"joint": "wrist", "multiplier": -1, "offset": 0}, + }, + ], + } + + def test_unbounded_joint_has_no_file(self): + assert _sva_file(planar_arm()) is None + + def test_collision_mesh_without_bytes_has_no_file(self): + model = KinematicModel(links=[KinematicLink(id="a", collision=[Geometry(mesh=Mesh(content_type="ply"))])]) + assert _sva_file(model) is None + + @pytest.mark.parametrize("case", [case for case in CASES if not case.startswith("error_")]) + def test_fixtures(self, case: str): + model = expected_model(case) + bounded = all(j.HasField("mimic") or (j.limits.HasField("min") and j.limits.HasField("max")) for j in model.joints) + file = _sva_file(model) + assert (file is not None) == bounded + if file is not None: + doc = json.loads(file) + assert [link["id"] for link in doc["links"]] == [link.id for link in model.links] + assert [joint["id"] for joint in doc["joints"]] == [joint.id for joint in model.joints] + + +def bounded_arm() -> KinematicModel: + model = planar_arm() + del model.joints[1:] + model.links[0].collision.append( + Geometry(label="c", mesh=Mesh(content_type="ply", mesh=b"ply", original_file_source_path_diagnostic="c.ply")) + ) + model.links[0].visual.append( + Geometry(label="v", mesh=Mesh(content_type="glb", mesh=b"glb", original_file_source_path_diagnostic="v.glb")) + ) + return model + + +class ModelOnlyArm(MockArm): + """An arm written against the typed model, which leaves the deprecated get_kinematics alone.""" + + get_kinematics = Arm.get_kinematics + + +@pytest.fixture +def arm() -> MockArm: + arm = MockArm("arm") + arm.kinematics = (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_URDF, b"", {}) + return arm + + +@pytest.fixture +def model_arm() -> ModelOnlyArm: + arm = ModelOnlyArm("arm") + arm.kinematic_model = bounded_arm() + return arm + + +async def get_kinematics(arm: MockArm, **flags: bool) -> GetKinematicsResponse: + async with ChannelFor([ArmRPCService(ResourceManager([arm]))]) as channel: + return await ArmServiceStub(channel).GetKinematics(GetKinematicsRequest(name=arm.name, **flags)) + + +class TestService: + async def test_file_only_resource(self, arm: MockArm): + for flags in ({}, {"include_collision_meshes": True}): + response = await get_kinematics(arm, **flags) + assert (response.format, response.kinematics_data) == (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_URDF, b"") + assert not response.HasField("model") + + async def test_no_flags_serves_file_and_whole_model(self, model_arm: ModelOnlyArm): + response = await get_kinematics(model_arm) + want = bounded_arm() + want.name = "arm" + assert response.model == want + assert response.format == KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA + doc = json.loads(response.kinematics_data) + assert doc["name"] == "arm" + assert doc["joints"][0]["max_velocity"] == 90 + assert doc["links"][0]["geometry"]["mesh_data"] == base64.b64encode(b"ply").decode() + # the resource is asked for every mesh, since a client that sends no flags expects them whole + assert (model_arm.include_collision_meshes, model_arm.include_visual_meshes) == (True, True) + # and the model it holds is not the one we renamed + assert model_arm.kinematic_model.name == "planar" + + @pytest.mark.parametrize("collision,visual", [(True, False), (False, True), (True, True)]) + async def test_flags_serve_the_model_alone(self, model_arm: ModelOnlyArm, collision: bool, visual: bool): + response = await get_kinematics(model_arm, include_collision_meshes=collision, include_visual_meshes=visual) + assert response.kinematics_data == b"" + assert response.format == KinematicsFileFormat.KINEMATICS_FILE_FORMAT_UNSPECIFIED + base = response.model.links[0] + assert base.collision[0].mesh.mesh == (b"ply" if collision else b"") + assert base.visual[0].mesh.mesh == (b"glb" if visual else b"") + # a mesh that lost its bytes still says where it came from + assert base.collision[0].mesh.original_file_source_path_diagnostic == "c.ply" + assert base.visual[0].mesh.content_type == "glb" + assert (model_arm.include_collision_meshes, model_arm.include_visual_meshes) == (collision, visual) + assert model_arm.kinematic_model == bounded_arm() + + async def test_unbounded_model_has_no_file(self, model_arm: ModelOnlyArm): + model_arm.kinematic_model = planar_arm() + response = await get_kinematics(model_arm) + assert response.kinematics_data == b"" + assert len(response.model.joints) == 3 + + async def test_resource_with_both(self, arm: MockArm): + arm.kinematic_model = bounded_arm() + response = await get_kinematics(arm) + assert (response.format, response.kinematics_data) == (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_URDF, b"") + assert response.model.name == "arm" + assert response.model.joints == bounded_arm().joints + + async def test_resource_forwarding_to_a_server_without_a_model(self, arm: MockArm): + class Forwarding(MockArm): + async def get_kinematic_model(self, **kwargs) -> KinematicModel: + raise NotSupportedError("the arm behind this one sent no kinematic model") + + forwarding = Forwarding("arm") + forwarding.kinematics = arm.kinematics + for flags in ({}, {"include_visual_meshes": True}): + response = await get_kinematics(forwarding, **flags) + assert response.kinematics_data == b"" + assert not response.HasField("model") + + async def test_resource_with_neither(self): + class Bare(ModelOnlyArm): + get_kinematic_model = Arm.get_kinematic_model + + bare = Bare("arm") + with pytest.raises(MethodNotImplementedError): + await bare.get_kinematics() + with pytest.raises(MethodNotImplementedError): + await bare.get_kinematic_model() + with pytest.raises(GRPCError): + await get_kinematics(bare) + + +class TestClient: + async def test_arm(self, model_arm: ModelOnlyArm): + async with ChannelFor([ArmRPCService(ResourceManager([model_arm]))]) as channel: + client = ArmClient(model_arm.name, channel) + model = await client.get_kinematic_model(include_collision_meshes=True, extra={"1": "2"}, timeout=1.1) + assert model.joints == bounded_arm().joints + assert model.links[0].collision[0].mesh.mesh == b"ply" + assert model.links[0].visual[0].mesh.mesh == b"" + assert model_arm.extra == {"1": "2"} + assert model_arm.timeout is not None + + # the deprecated call still answers, from the file the server wrote out of the model + kinematics: KinematicsReturn = await client.get_kinematics() + assert kinematics[0] == KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA + assert len(kinematics) == 4 + + async def test_server_without_a_model(self, arm: MockArm): + async with ChannelFor([ArmRPCService(ResourceManager([arm]))]) as channel: + with pytest.raises(NotSupportedError, match="sent no kinematic model"): + await ArmClient(arm.name, channel).get_kinematic_model() + + async def test_gantry_and_gripper(self): + gantry = MockGantry("gantry", [1], [2]) + gripper = MockGripper("gripper") + gantry.kinematic_model = bounded_arm() + gripper.kinematic_model = bounded_arm() + async with ChannelFor([GantryRPCService(ResourceManager([gantry])), GripperRPCService(ResourceManager([gripper]))]) as channel: + for client in (GantryClient("gantry", channel), GripperClient("gripper", channel)): + model = await client.get_kinematic_model(include_visual_meshes=True) + assert model.name == client.name + assert model.links[0].visual[0].mesh.mesh == b"glb" + assert model.links[0].collision[0].mesh.mesh == b""