diff --git a/parol6/__init__.py b/parol6/__init__.py index 9e84d58..e0359ab 100644 --- a/parol6/__init__.py +++ b/parol6/__init__.py @@ -11,12 +11,12 @@ """ from importlib.metadata import version as _pkg_version +from typing import TYPE_CHECKING from . import PAROL6_ROBOT __version__: str = _pkg_version("parol6") from .client.async_client import AsyncRobotClient, StatusSnapshot -from .client.dry_run_client import DryRunRobotClient from .client.sync_client import RobotClient from .protocol.wire import ( CurrentActionResultStruct, @@ -63,3 +63,18 @@ "make_error", "MotionError", ] + + +if TYPE_CHECKING: + from .client.dry_run_client import DryRunRobotClient + + +def __getattr__(name: str): + """The dry-run client on first use: it brings the planner, which a robot + program does not need.""" + if name == "DryRunRobotClient": + from .client.dry_run_client import DryRunRobotClient + + globals()[name] = DryRunRobotClient + return DryRunRobotClient + raise AttributeError(f"module 'parol6' has no attribute {name!r}") diff --git a/parol6/client/async_client.py b/parol6/client/async_client.py index d972846..783cb03 100644 --- a/parol6/client/async_client.py +++ b/parol6/client/async_client.py @@ -405,8 +405,8 @@ def _bind_default_tools(self) -> None: bound: dict[str, ToolSpec] = {} for spec in _build_tools().available: bound_spec = copy.copy(spec) - bound_spec._execute = self.tool_action # type: ignore[attr-defined, ty:unresolved-attribute] - bound_spec._get_status = self._tool_status # type: ignore[attr-defined, ty:unresolved-attribute] + bound_spec._execute = self.tool_action # type: ignore[attr-defined, ty:missing-attribute] + bound_spec._get_status = self._tool_status # type: ignore[attr-defined, ty:missing-attribute] bound[spec.key] = bound_spec self._bound_tools = bound diff --git a/parol6/commands/system_commands.py b/parol6/commands/system_commands.py index 3596bf1..83cfb60 100644 --- a/parol6/commands/system_commands.py +++ b/parol6/commands/system_commands.py @@ -199,7 +199,7 @@ def do_setup(self, state: ControllerState) -> None: profile = self.p.profile.upper() if profile not in VALID_PROFILES: err = ValueError(f"Invalid profile '{self.p.profile}'") - err.robot_error = make_error( # type: ignore[attr-defined, ty:unresolved-attribute] + err.robot_error = make_error( # type: ignore[attr-defined, ty:missing-attribute] ErrorCode.SYS_PROFILE_INVALID, detail=self.p.profile, allowed=", ".join(VALID_PROFILES), diff --git a/parol6/config.py b/parol6/config.py index c29fd3c..8efff18 100644 --- a/parol6/config.py +++ b/parol6/config.py @@ -9,7 +9,7 @@ import threading from dataclasses import dataclass from pathlib import Path -from typing import Union +from typing import Any, Union, cast import numpy as np from numba import njit @@ -45,8 +45,8 @@ def _trace(self, msg, *args, **kwargs): if self.isEnabledFor(TRACE): self._log(TRACE, msg, args, **kwargs) - logging.Logger.trace = _trace # type: ignore[attr-defined, ty:unresolved-attribute] - logging.TRACE = TRACE # type: ignore[attr-defined, ty:unresolved-attribute] + logging.Logger.trace = _trace # type: ignore[attr-defined, ty:missing-attribute] + logging.TRACE = TRACE # type: ignore[attr-defined, ty:missing-attribute] TRACE_ENABLED = str(os.getenv("PAROL_TRACE", "0")).lower() in ("1", "true", "yes", "on") @@ -496,14 +496,25 @@ def _build_kinodynamic( v_steps_arr = np.asarray(v_steps, dtype=np.int32) a_steps_arr = np.asarray(a_steps, dtype=np.int32) j_steps_arr = np.asarray(j_steps, dtype=np.int32) + # The plain functions: a jitted call at import would set numba up in every + # process that imports the package, a robot program's included. v_rad = np.array( - [float(speed_steps_to_rad_scalar(v_steps_arr[i], i)) for i in range(6)] + [ + float(cast(Any, speed_steps_to_rad_scalar).py_func(v_steps_arr[i], i)) + for i in range(6) + ] ) a_rad = np.array( - [float(speed_steps_to_rad_scalar(a_steps_arr[i], i)) for i in range(6)] + [ + float(cast(Any, speed_steps_to_rad_scalar).py_func(a_steps_arr[i], i)) + for i in range(6) + ] ) j_rad = np.array( - [float(speed_steps_to_rad_scalar(j_steps_arr[i], i)) for i in range(6)] + [ + float(cast(Any, speed_steps_to_rad_scalar).py_func(j_steps_arr[i], i)) + for i in range(6) + ] ) return Kinodynamic( velocity=v_rad, @@ -520,10 +531,11 @@ def _build_joint_position(limits_deg: NDArray) -> JointPosition: limits_rad = np.deg2rad(limits_deg) # Allocate once for module init (not hot path) tmp = np.zeros(6, dtype=np.int32) + # Plain, not jitted: see _build_kinodynamic. limits_steps = np.column_stack( [ - deg_to_steps(limits_deg[:, 0], tmp).copy(), - deg_to_steps(limits_deg[:, 1], tmp).copy(), + cast(Any, deg_to_steps).py_func(limits_deg[:, 0], tmp).copy(), + cast(Any, deg_to_steps).py_func(limits_deg[:, 1], tmp).copy(), ] ) return JointPosition(deg=limits_deg.copy(), rad=limits_rad, steps=limits_steps) diff --git a/parol6/motion/streaming_executors.py b/parol6/motion/streaming_executors.py index 9257aac..33fc9b2 100644 --- a/parol6/motion/streaming_executors.py +++ b/parol6/motion/streaming_executors.py @@ -16,7 +16,7 @@ import numpy as np from numba import njit from numpy.typing import NDArray -from ruckig import ( # type: ignore[unresolved-import, ty:unresolved-import] +from ruckig import ( # type: ignore[unresolved-import, ty:import-not-found] ControlInterface, InputParameter, OutputParameter, diff --git a/parol6/motion/trajectory.py b/parol6/motion/trajectory.py index 320706c..c0fd16c 100644 --- a/parol6/motion/trajectory.py +++ b/parol6/motion/trajectory.py @@ -23,7 +23,7 @@ from numba import njit from numpy.typing import NDArray from scipy.interpolate import PPoly, make_interp_spline -from ruckig import InputParameter, Result, Ruckig, Trajectory as RuckigTrajectory # type: ignore[unresolved-import, ty:unresolved-import] +from ruckig import InputParameter, Result, Ruckig, Trajectory as RuckigTrajectory # type: ignore[unresolved-import, ty:import-not-found] import toppra.algorithm as algo import toppra.constraint as constraint diff --git a/parol6/robot.py b/parol6/robot.py index c4f23c9..cdadfa6 100644 --- a/parol6/robot.py +++ b/parol6/robot.py @@ -20,7 +20,7 @@ from importlib.resources import files as pkg_files from operator import attrgetter from pathlib import Path -from typing import Any, Literal +from typing import Any, Literal, cast import msgspec import numpy as np @@ -52,10 +52,8 @@ ) from parol6.client.async_client import AsyncRobotClient -from parol6.client.dry_run_client import DryRunRobotClient from parol6.client.sync_client import RobotClient as SyncRobotClient from parol6.config import HOME_ANGLES_DEG, LIMITS -from parol6.motion.trajectory import ProfileType from parol6.protocol.wire import PingCmd, ResponseMsg, decode_message, encode_command from parol6.tools import ( ElectricGripperConfig, @@ -454,7 +452,9 @@ def _decompose_transform( """Extract (origin_m, rpy_rad) from a 4x4 homogeneous transform.""" origin = (float(T[0, 3]), float(T[1, 3]), float(T[2, 3])) rpy_buf = np.zeros(3, dtype=np.float64) - so3_rpy(T[:3, :3], rpy_buf) + # Plain, not jitted: every RobotClient() decomposes its tools' transforms, + # and a first jitted call would set numba up in a program that needs none. + cast(Any, so3_rpy).py_func(T[:3, :3], rpy_buf) rpy = (float(rpy_buf[0]), float(rpy_buf[1]), float(rpy_buf[2])) return origin, rpy @@ -571,7 +571,7 @@ def __init__( register_plugin_tools() self._urdf_path = _resolve_urdf_path() self._mesh_dir = _resolve_mesh_dir() - self._motion_profiles = tuple(p.value.upper() for p in ProfileType) + self._motion_profiles: tuple[str, ...] | None = None cj = LIMITS.cart.jog self._cartesian_limits = CartesianKinodynamicLimits( @@ -665,6 +665,12 @@ def joint_index_mapping(self) -> tuple[int, ...]: @property def motion_profiles(self) -> tuple[str, ...]: + if self._motion_profiles is None: + # The planner's modules are a client's heaviest import, and only a + # caller that plans needs them. + from parol6.motion.trajectory import ProfileType + + self._motion_profiles = tuple(p.value.upper() for p in ProfileType) return self._motion_profiles @property @@ -1041,8 +1047,8 @@ def create_async_client(self, **kwargs: Any) -> AsyncRobotClient: bound: dict[str, ToolSpec] = {} for spec in self.tools.available: bound_spec = copy.copy(spec) - bound_spec._execute = client.tool_action # type: ignore[attr-defined, ty:unresolved-attribute] - bound_spec._get_status = client._tool_status # type: ignore[attr-defined, ty:unresolved-attribute] + bound_spec._execute = client.tool_action # type: ignore[attr-defined, ty:missing-attribute] + bound_spec._get_status = client._tool_status # type: ignore[attr-defined, ty:missing-attribute] bound[spec.key] = bound_spec client._bound_tools = bound return client @@ -1060,8 +1066,8 @@ def create_sync_client(self, **kwargs: Any) -> SyncRobotClient: async_bound: dict[str, ToolSpec] = {} for spec in self.tools.available: bound_spec = copy.copy(spec) - bound_spec._execute = client._inner.tool_action # type: ignore[attr-defined, ty:unresolved-attribute] - bound_spec._get_status = client._inner._tool_status # type: ignore[attr-defined, ty:unresolved-attribute] + bound_spec._execute = client._inner.tool_action # type: ignore[attr-defined, ty:missing-attribute] + bound_spec._get_status = client._inner._tool_status # type: ignore[attr-defined, ty:missing-attribute] async_bound[spec.key] = bound_spec client._inner._bound_tools = async_bound bound: dict[str, SyncTool] = {} @@ -1073,6 +1079,9 @@ def create_sync_client(self, **kwargs: Any) -> SyncRobotClient: def create_dry_run_client(self, **kwargs: Any) -> DryRunClient | None: initial_joints_deg: list[float] | None = kwargs.get("initial_joints_deg") initial_homed: bool = bool(kwargs.get("initial_homed", True)) + # Here, not at module level: it brings the planner. + from parol6.client.dry_run_client import DryRunRobotClient + return DryRunRobotClient( initial_joints_deg=initial_joints_deg, initial_homed=initial_homed, diff --git a/parol6/tools.py b/parol6/tools.py index f8c056e..b2d1fae 100644 --- a/parol6/tools.py +++ b/parol6/tools.py @@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, Protocol, runtime_checkable import numpy as np -from pinokin import se3_from_rpy, se3_from_trans +from pinokin import se3_from_rpy from waldoctl import ( CameraSpec, LinearMotion, @@ -554,8 +554,8 @@ def _make_tcp_transform( Pure translation — tool frame orientation matches the flange. """ - out = np.zeros((4, 4), dtype=np.float64) - se3_from_trans(x, y, z, out) + out = np.eye(4, dtype=np.float64) + out[:3, 3] = (x, y, z) return out diff --git a/pyproject.toml b/pyproject.toml index 2be4afa..1d9ab5e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,7 +126,7 @@ invalid-type-form = "ignore" [[tool.ty.overrides]] include = ["parol6/PAROL6_ROBOT.py"] [tool.ty.overrides.rules] -unresolved-import = "ignore" +import-not-found = "ignore" [tool.setuptools] include-package-data = true diff --git a/tests/unit/test_client_imports.py b/tests/unit/test_client_imports.py new file mode 100644 index 0000000..3bb05b6 --- /dev/null +++ b/tests/unit/test_client_imports.py @@ -0,0 +1,38 @@ +"""A robot program's client loads neither the planner nor numba's compiler.""" + +import json +import subprocess +import sys + +import pytest + +_PROBE = """ +import json, sys +import parol6 +parol6.RobotClient() +from numba.core.registry import CPUDispatcher +ran = sorted( + f"{name}.{attr}" + for name, module in list(sys.modules.items()) + if name.split(".")[0] in ("parol6", "pinokin") + for attr, value in list(vars(module).items()) + if isinstance(value, CPUDispatcher) and value.signatures +) +print(json.dumps({"modules": sorted(sys.modules), "jitted": ran})) +""" + + +@pytest.mark.unit +def test_a_client_loads_no_planner_and_runs_nothing_jitted() -> None: + out = subprocess.run( + [sys.executable, "-c", _PROBE], capture_output=True, text=True, check=True + ).stdout + report = json.loads(out.splitlines()[-1]) + planner = [ + m + for m in report["modules"] + if m.split(".")[0] in ("matplotlib", "toppra") + or m in ("scipy.interpolate", "scipy.optimize", "parol6.client.dry_run_client") + ] + assert not planner, planner + assert not report["jitted"], report["jitted"]