Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion parol6/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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}")
4 changes: 2 additions & 2 deletions parol6/client/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion parol6/commands/system_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
28 changes: 20 additions & 8 deletions parol6/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion parol6/motion/streaming_executors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion parol6/motion/trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 18 additions & 9 deletions parol6/robot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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] = {}
Expand All @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions parol6/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/test_client_imports.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading