diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 24c3772e..2959d641 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,20 +2,20 @@ ci: autoupdate_schedule: quarterly repos: - repo: https://github.com/BlankSpruce/gersemi-pre-commit - rev: 0.27.7 + rev: 0.29.2 hooks: - id: gersemi - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.15.20 + rev: v0.16.10 hooks: - id: ruff-check - id: ruff-format - repo: https://github.com/pappasam/toml-sort - rev: v0.24.4 + rev: v0.25.0 hooks: - id: toml-sort-fix - repo: https://github.com/pre-commit/mirrors-clang-format - rev: v22.1.5 + rev: v23.1.2 hooks: - id: clang-format args: diff --git a/doc/configure.py b/doc/configure.py index 43a4756c..5e230aa6 100755 --- a/doc/configure.py +++ b/doc/configure.py @@ -71,10 +71,10 @@ # ############# README ############################### -from __future__ import print_function -import re import os +import re import sys + from doxygen_xml_parser import Index @@ -165,7 +165,7 @@ def substitute(istr, ostr): currentClass = None currentNamespace = None index = None - for line in map(lambda s: s.rstrip(), istr): + for line in (s.rstrip() for s in istr): for match in nsPattern.finditer(line): currentNamespace = match.group("namespace") index = indexFromNamespace(currentNamespace) @@ -185,9 +185,9 @@ def substitute(istr, ostr): line = line.replace( match.group(0), make_doc_string(escape(b), escape(d)) ) - except Exception as e: + except Exception as e: # noqa: BLE001 print( - "Failed to find class doc for {0}: {1}".format(cn, e), + f"Failed to find class doc for {cn}: {e}", file=sys.stderr, ) line = line.replace(match.group(0), '"' + cn + '"') @@ -209,7 +209,7 @@ def substitute(istr, ostr): ) except IndexError as e: print( - "Failed to find documentation of method {0}::{1}".format(cn, mn), + f"Failed to find documentation of method {cn}::{mn}", file=sys.stderr, ) line = line.replace(match.group(0), '"' + str(e) + '", ""') diff --git a/doc/doxygen_xml_parser.py b/doc/doxygen_xml_parser.py index 85148562..1b28763d 100644 --- a/doc/doxygen_xml_parser.py +++ b/doc/doxygen_xml_parser.py @@ -1,7 +1,7 @@ -from __future__ import print_function -from lxml import etree -from os import path import sys +from os import path + +from lxml import etree class Index: diff --git a/doc/fix_stubs/__init__.py b/doc/fix_stubs/__init__.py index 9d4201f1..1fbb4213 100644 --- a/doc/fix_stubs/__init__.py +++ b/doc/fix_stubs/__init__.py @@ -10,4 +10,4 @@ from ._fixer import fix_file from ._overrides import SETTER_TYPE_OVERRIDES -__all__ = ["fix_file", "main", "SETTER_TYPE_OVERRIDES"] +__all__ = ["SETTER_TYPE_OVERRIDES", "fix_file", "main"] diff --git a/doc/fix_stubs/_cli.py b/doc/fix_stubs/_cli.py index e2e22f07..ea59cbfb 100644 --- a/doc/fix_stubs/_cli.py +++ b/doc/fix_stubs/_cli.py @@ -75,7 +75,7 @@ def main() -> None: setter_overrides=setter_overrides, method_overrides=method_overrides, ) - except Exception as e: + except Exception as e: # noqa: BLE001 print(f"error: failed to fix {f}: {e}", file=sys.stderr) continue total_files += 1 diff --git a/doc/fix_stubs/_fixer.py b/doc/fix_stubs/_fixer.py index 5b57a08b..bd8f1b82 100644 --- a/doc/fix_stubs/_fixer.py +++ b/doc/fix_stubs/_fixer.py @@ -31,9 +31,7 @@ def fix_file( fixed = 0 for cls in tree: for fn in cls.functions: - if fn.from_docstring: - fixed += 1 - elif fn.setter_overloads: + if fn.from_docstring or fn.setter_overloads: fixed += 1 new_content = render_file(header, tree) diff --git a/doc/fix_stubs/_models.py b/doc/fix_stubs/_models.py index 9fd29878..fe4b36d4 100644 --- a/doc/fix_stubs/_models.py +++ b/doc/fix_stubs/_models.py @@ -163,7 +163,7 @@ def __init__(self, is_module: bool = False): self.bases: list[str] = [] self.docstring = "" self.functions: list[Function] = [] - self.nested_classes: list["ClassI"] = [] + self.nested_classes: list[ClassI] = [] self.is_module = is_module self.extra_lines: list[str] = [] diff --git a/doc/fix_stubs/_overrides.py b/doc/fix_stubs/_overrides.py index e738af31..c9f74c75 100644 --- a/doc/fix_stubs/_overrides.py +++ b/doc/fix_stubs/_overrides.py @@ -74,7 +74,7 @@ def load_method_overrides(path: Path | None) -> dict[str, _MethodSig]: raw = json.loads(path.read_text()) if not isinstance(raw, dict): - raise ValueError(f"{path}: expected a JSON object, got {type(raw).__name__}") + raise TypeError(f"{path}: expected a JSON object, got {type(raw).__name__}") for key, value in raw.items(): entries = value if isinstance(value, list) else [value] diff --git a/doc/fix_stubs/_parser.py b/doc/fix_stubs/_parser.py index 7f9c5324..e3f45ba2 100644 --- a/doc/fix_stubs/_parser.py +++ b/doc/fix_stubs/_parser.py @@ -5,6 +5,7 @@ """ from __future__ import annotations + import sys from pathlib import Path diff --git a/doc/gen_api_md.py b/doc/gen_api_md.py old mode 100644 new mode 100755 index 023f4fb9..3b0f4a9e --- a/doc/gen_api_md.py +++ b/doc/gen_api_md.py @@ -3,12 +3,12 @@ from __future__ import annotations +import argparse import ast import html as _html import keyword import re import sys -import argparse from pathlib import Path # --------------------------------------------------------------------------- @@ -251,7 +251,7 @@ def _parse_stub(stub_path: Path) -> ast.Module | None: source = _KW_PARAM_RE.sub(r"\1\2_\3", source) return ast.parse(source) - except Exception: + except Exception: # noqa: BLE001 return None @@ -822,12 +822,11 @@ def render_class( node = group[0] if node.name in SKIP_NAMES or is_setter(node): continue - if node.name == "__init__": - if any( - get_docstring(ov) and NOT_INSTANTIABLE.search(get_docstring(ov)) - for ov in group - ): - continue + if node.name == "__init__" and any( + get_docstring(ov) and NOT_INSTANTIABLE.search(get_docstring(ov)) + for ov in group + ): + continue sig = _sig_cell(group, class_index, current_page) if owner != qualified_class: sig += f" *(inherited from {_type_link(owner, class_index, current_page)})*" @@ -906,10 +905,9 @@ def generate_module_md( if pending_funcs: func_groups.append(pending_funcs) pending_funcs = [item] - elif isinstance(item, ast.ClassDef): - if pending_funcs: - func_groups.append(pending_funcs) - pending_funcs = [] + elif isinstance(item, ast.ClassDef) and pending_funcs: + func_groups.append(pending_funcs) + pending_funcs = [] if pending_funcs: func_groups.append(pending_funcs) diff --git a/src/pyhpp/__init__.py b/src/pyhpp/__init__.py index a7ffa60d..6dc4f2fb 100644 --- a/src/pyhpp/__init__.py +++ b/src/pyhpp/__init__.py @@ -6,4 +6,4 @@ category=RuntimeWarning, ) -import eigenpy # noqa: E402, F401 +import eigenpy # noqa: F401 diff --git a/src/pyhpp/core/static_stability_constraint_factory.py b/src/pyhpp/core/static_stability_constraint_factory.py index f97a6b50..b26bd103 100644 --- a/src/pyhpp/core/static_stability_constraint_factory.py +++ b/src/pyhpp/core/static_stability_constraint_factory.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # # Copyright (c) 2025 CNRS # Author: Paul Sardin @@ -29,7 +28,7 @@ # DAMAGE. import numpy as np -from pinocchio import Quaternion, SE3 +from pinocchio import SE3, Quaternion # # This class provides tools to create static stability constraints @@ -55,7 +54,7 @@ def _getCOM(self, com): def createSlidingStabilityConstraint( self, prefix, comName, leftAnkle, rightAnkle, q0 ): - created_constraints = dict() + created_constraints = {} _tfs = self.robot.getJointsPosition(q0, [leftAnkle, rightAnkle]) Ml = SE3(Quaternion(np.array(_tfs[0][3:7])), np.array(_tfs[0][0:3])) @@ -112,7 +111,7 @@ def createSlidingStabilityConstraint( def createStaticStabilityConstraint( self, prefix, comName, leftAnkle, rightAnkle, q0, maskCom=[True] * 3 ): - created_constraints = dict() + created_constraints = {} _tfs = self.robot.getJointsPosition(q0, [leftAnkle, rightAnkle]) Ml = SE3(Quaternion(np.array(_tfs[0][3:7])), np.array(_tfs[0][0:3])) @@ -158,7 +157,7 @@ def createStaticStabilityConstraint( def createAlignedCOMStabilityConstraint( self, prefix, comName, leftAnkle, rightAnkle, q0, sliding ): - created_constraints = dict() + created_constraints = {} _tfs = self.robot.getJointsPosition(q0, [leftAnkle, rightAnkle]) Ml = SE3(Quaternion(np.array(_tfs[0][3:7])), np.array(_tfs[0][0:3])) diff --git a/src/pyhpp/manipulation/constraint_graph_factory.py b/src/pyhpp/manipulation/constraint_graph_factory.py index cdb4faf8..1f2ace4a 100644 --- a/src/pyhpp/manipulation/constraint_graph_factory.py +++ b/src/pyhpp/manipulation/constraint_graph_factory.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # # Copyright (c) 2025 CNRS # Author: Paul Sardin @@ -30,8 +29,9 @@ import abc import re -import sys + import numpy as np + from pyhpp.constraints import Implicit, LockedJoint @@ -45,7 +45,17 @@ class Constraints: \\li numerical constraint, """ - def __init__(self, grasps=[], pregrasps=[], numConstraints=[], lockedJoints=[]): + def __init__( + self, grasps=None, pregrasps=None, numConstraints=None, lockedJoints=None + ): + if lockedJoints is None: + lockedJoints = [] + if numConstraints is None: + numConstraints = [] + if pregrasps is None: + pregrasps = [] + if grasps is None: + grasps = [] if isinstance(grasps, str): raise TypeError("argument grasps should be a list of strings") if isinstance(pregrasps, str): @@ -134,10 +144,10 @@ def __init__(self, grippers, handles, grasps): factory and whose values are lists of handles also registered in the factory """ - self.possibleGrasps = list() + self.possibleGrasps = [] for ig, gripper in enumerate(grippers): - handles_ = grasps.get(gripper, list()) - handleIndices = list() + handles_ = grasps.get(gripper, []) + handleIndices = [] handleIndices = list(map(handles.index, handles_)) self.possibleGrasps.append(handleIndices) @@ -157,7 +167,7 @@ def __init__(self): param grasps the set of grasp to validate return False if one validation fails, True otherwise """ - self.graspValidations_ = list() + self.graspValidations_ = [] def __call__(self, grasps): for gv in self.graspValidations_: @@ -212,15 +222,7 @@ def __call__(self, grasps): return self.defaultAcceptation -if sys.version_info.major == 2: - - class ABC: - """Python 2.7 equivalent to abc.ABC Python 3 class.""" - - __metaclass__ = abc.ABCMeta - -else: - from abc import ABC +from abc import ABC class GraphFactoryAbstract(ABC): @@ -276,25 +278,25 @@ def __init__(self): # # \name Internal variables # \{ - self.states = dict() + self.states = {} self.transitions = set() # Recursion-visited memo for all nGrasps, accepted or rejected. # Separate from self.states, which only holds created State objects. self._visitedGrasps = set() # # the handle names - self.handles = tuple() # strings + self.handles = () # strings # # the gripper names - self.grippers = tuple() # strings + self.grippers = () # strings # # the names of contact on the environment - self.envContacts = tuple() # strings + self.envContacts = () # strings # # the object names - self.objects = tuple() # strings + self.objects = () # strings # # See \\ref setObjects - self.handlesPerObjects = tuple() # object index to handle indixes + self.handlesPerObjects = () # object index to handle indixes # # See \\ref setObjects - self.objectFromHandle = tuple() # handle index to object index + self.objectFromHandle = () # handle index to object index # # See \\ref setObjects - self.contactsPerObjects = tuple() # object index to contact names + self.contactsPerObjects = () # object index to contact names # # \} # # \name Main API @@ -394,7 +396,6 @@ def makeLoopTransition(self, state): Create a loop transition. \\param state: an object returned by \\ref makeState which represent the state """ - pass def transitionIsAllowed(self, stateFrom, stateTo): """ @@ -413,7 +414,6 @@ def makeTransition(self, stateFrom, stateTo, ig): - \\f$ stateFrom.grasps[i_g] \neq stateTo.grasps[i_g] \\f$ - \\f$ \\forall i \neq i_g, stateFrom.grasps[i] = stateTo.grasps[i] \\f$ """ - pass # # \} @@ -536,8 +536,8 @@ class ConstraintFactoryAbstract(ABC): """ def __init__(self, graphfactory): - self._grasp = dict() - self._placement = dict() + self._grasp = {} + self._placement = {} self.graphfactory = graphfactory @@ -684,10 +684,12 @@ def _removeEmptyConstraints(self, constraints): gfields = ("grasp", "graspComplement", "preGrasp") pfields = ("placement", "placementComplement", "prePlacement") - def __init__(self, graphfactory, graph, constraints=dict()): + def __init__(self, graphfactory, graph, constraints=None): + if constraints is None: + constraints = {} super().__init__(graphfactory) self.graph = graph - self.available_constraints = dict() + self.available_constraints = {} self.registerConstraints(constraints) def registerConstraint(self, constraint, constraint_name): @@ -882,12 +884,13 @@ def __init__(self, factory, grasps, state_obj, name): # default distance between object and surface in preplacement configuration defaultPreplaceDist = 0.05 # See methods setPreplacementDistance and getPreplacementDistance - preplaceDistance = dict() - def __init__(self, graph, constraints=dict()): + def __init__(self, graph, constraints=None): """ \\param graph an instance of ConstraintGraph """ + if constraints is None: + constraints = {} super().__init__() # Stores the constraints in a child class of ConstraintFactoryAbstract @@ -900,6 +903,7 @@ def __init__(self, graph, constraints=dict()): self.preplaceGuide = False self.state_objects = {} self.edge_objects = {} + self.preplaceDistance = {} # # \name Default functions # \{ @@ -1202,7 +1206,7 @@ def _createWaypointState(name, constraints): forward_trans, backward_trans = wTransitionObjects[i + 1] self.graph.setShort(forward_trans, True) - forward_trans_back, backward_trans_back = wTransitionObjects[i] + _forward_trans_back, backward_trans_back = wTransitionObjects[i] self.graph.setShort(backward_trans_back, True) else: diff --git a/src/pyhpp/manipulation/security_margins.py b/src/pyhpp/manipulation/security_margins.py index cf687817..8c35385d 100644 --- a/src/pyhpp/manipulation/security_margins.py +++ b/src/pyhpp/manipulation/security_margins.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # # Copyright (c) 2020 CNRS, Airbus SAS # Author: Florent Lamiraux @@ -31,20 +30,20 @@ class SecurityMargins: defaultMargin = 0.0 - separators = ["/"] def __init__(self, problem, factory, robotsAndObjects, robot): self.problem = problem self.robot = robot self.factory = factory self.robotsAndObjects = robotsAndObjects - self.marginMatrix = dict() + self.marginMatrix = {} + self.separators = ["/"] self.computeJoints() self.computeGrippers() self.computePossibleContacts() def computeJoints(self): - self.robotToJoints = dict() + self.robotToJoints = {} model = self.robot.model() jointNames = list(model.names) for ro in self.robotsAndObjects: @@ -56,7 +55,7 @@ def computeJoints(self): ) ) self.robotToJoints["universe"] = ["universe"] - self.jointToRobot = dict() + self.jointToRobot = {} for ro, joints in self.robotToJoints.items(): for j in joints: self.jointToRobot[j] = ro @@ -65,7 +64,7 @@ def _getChildJoints(self, jointName): model = self.robot.model() try: jointId = model.getJointId(jointName) - except Exception: + except Exception: # noqa: BLE001 return [] childNames = [] @@ -86,8 +85,8 @@ def _getGripperJoint(self, gripperName): return None def computeGrippers(self): - self.gripperToRobot = dict() - self.gripperToJoints = dict() + self.gripperToRobot = {} + self.gripperToJoints = {} for g in self.factory.grippers: j = self._getGripperJoint(g) if j is not None and j in self.jointToRobot: @@ -103,9 +102,9 @@ def computeGrippers(self): break def computePossibleContacts(self): - self.contactSurfaces = dict() - for k in self.robotToJoints.keys(): - self.contactSurfaces[k] = list() + self.contactSurfaces = {} + for k in self.robotToJoints: + self.contactSurfaces[k] = [] for io, obj_name in enumerate(self.factory.objects): if io < len(self.factory.contactsPerObjects): @@ -128,7 +127,7 @@ def computePossibleContacts(self): if not found: self.contactSurfaces["universe"].append(surface_name) - self.possibleContacts = list() + self.possibleContacts = [] for o1, l1 in self.contactSurfaces.items(): for o2, l2 in self.contactSurfaces.items(): if o1 != o2 and len(l1) > 0 and len(l2) > 0: diff --git a/src/pyhpp/pinocchio/utils.py b/src/pyhpp/pinocchio/utils.py index fade1353..28697ce2 100644 --- a/src/pyhpp/pinocchio/utils.py +++ b/src/pyhpp/pinocchio/utils.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # # Copyright (c) 2025 CNRS # Author: Florent Lamiraux diff --git a/src/pyhpp/tools/xacro.py b/src/pyhpp/tools/xacro.py index 9bf04c25..34c50240 100644 --- a/src/pyhpp/tools/xacro.py +++ b/src/pyhpp/tools/xacro.py @@ -1,7 +1,6 @@ import os import sys - try: # python 2 _basestr = basestring encoding = {"encoding": "utf-8"} @@ -19,7 +18,7 @@ def process_xacro(*args): # If AMENT_PREFIX_PATH is defined (ROS 2), pass the content to retrieve resources ament_prefix_path = os.getenv("AMENT_PREFIX_PATH") if ament_prefix_path is not None: - dirs = list(map(lambda s: s + "/share", ament_prefix_path.split(":"))) + dirs = [s + "/share" for s in ament_prefix_path.split(":")] # open and process file doc = xacro.process_file(retrieve_resource(input_file_name, dirs), **vars(opts)) diff --git a/tests/integration/benchmark_utils.py b/tests/integration/benchmark_utils.py old mode 100644 new mode 100755 index 51d5c440..65655d66 --- a/tests/integration/benchmark_utils.py +++ b/tests/integration/benchmark_utils.py @@ -7,8 +7,12 @@ import datetime as dt from argparse import ArgumentParser +from collections.abc import Callable from dataclasses import dataclass, field -from typing import Callable, Optional, Any +from typing import Any +from zoneinfo import ZoneInfo + +TZ = ZoneInfo("Europe/Paris") def create_benchmark_parser(description: str = "HPP Benchmark") -> ArgumentParser: @@ -96,9 +100,9 @@ class BenchmarkRunner: def __init__( self, solve_func: Callable[[], Any], - reset_func: Optional[Callable[[], None]] = None, - get_nodes_func: Optional[Callable[[], int]] = None, - get_path_length_func: Optional[Callable[[], float]] = None, + reset_func: Callable[[], None] | None = None, + get_nodes_func: Callable[[], int] | None = None, + get_path_length_func: Callable[[], float] | None = None, ): self.solve_func = solve_func self.reset_func = reset_func @@ -115,9 +119,9 @@ def _run_single(self) -> BenchmarkResult: self.reset_func() try: - t1 = dt.datetime.now() + t1 = dt.datetime.now(tz=TZ) path = self.solve_func() - t2 = dt.datetime.now() + t2 = dt.datetime.now(tz=TZ) result.success = True result.time_elapsed = t2 - t1 @@ -128,7 +132,7 @@ def _run_single(self) -> BenchmarkResult: if self.get_path_length_func and path is not None: result.path_length = self.get_path_length_func() - except Exception as e: + except Exception as e: # noqa: BLE001 result.error_message = str(e) print(f"Failed to plan path: {e}") diff --git a/tests/integration/construction-set-m-rrt.py b/tests/integration/construction-set-m-rrt.py old mode 100644 new mode 100755 index 91629a60..a316f22d --- a/tests/integration/construction-set-m-rrt.py +++ b/tests/integration/construction-set-m-rrt.py @@ -1,26 +1,24 @@ #!/usr/bin/env python3 +import re from math import pi, sqrt + import numpy as np -import re -import typing as T +from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pinocchio import SE3, Quaternion -from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory, Rule -from pyhpp.manipulation import Device, Graph, Problem, urdf, ManipulationPlanner -from pyhpp.core import Straight, Progressive, ProgressiveProjector from pyhpp.constraints import ( - Transformation, - ComparisonTypes, ComparisonType, + ComparisonTypes, Implicit, LockedJoint, + Transformation, ) -from pinocchio import SE3, Quaternion - +from pyhpp.core import Progressive, ProgressiveProjector, Straight +from pyhpp.manipulation import Device, Graph, ManipulationPlanner, Problem, urdf +from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory, Rule from pyhpp.manipulation.security_margins import SecurityMargins -from benchmark_utils import create_benchmark_parser, run_benchmark_main - parser = create_benchmark_parser("Construction Set M-RRT Benchmark") parser.add_argument( "--bigGraph", @@ -32,7 +30,7 @@ args = parser.parse_args() -class StateName(object): +class StateName: noGrasp = "free" def __init__(self, grasps): @@ -43,7 +41,7 @@ def __init__(self, grasps): self.grasps = set() else: g1 = [s.strip(" ") for s in grasps.split(":")] - self.grasps = set([tuple(s.split(" grasps ")) for s in g1]) + self.grasps = {tuple(s.split(" grasps ")) for s in g1} else: raise TypeError("expecting a set of pairs (gripper, handle) or a string") @@ -92,7 +90,7 @@ def __ne__(self, other): ground_pose = SE3(rotation=np.identity(3), translation=np.array([0, 0, 0])) urdf.loadModel(robot, 0, "ground", "anchor", ground_urdf, ground_srdf, ground_pose) -objects = list() +objects = [] for i in range(nSphere): sphere_pose = SE3(rotation=np.identity(3), translation=np.array([0, 0, 0])) urdf.loadModel( @@ -161,7 +159,7 @@ def __ne__(self, other): cg.errorThreshold(1e-4) cg.maxIterations(40) -constraints = dict() +constraints = {} for i in range(nSphere): placementName = f"place_sphere{i}" @@ -318,8 +316,8 @@ def __ne__(self, other): def makeRule(grasps): - _grippers = list() - _handles = list() + _grippers = [] + _handles = [] for g, h in grasps: _grippers.append(g) _handles.append(h) @@ -330,15 +328,15 @@ def makeRule(grasps): return Rule(grippers=_grippers, handles=_handles, link=True) -def forbidExcept(g: str, h: T.List[str]) -> T.List[Rule]: +def forbidExcept(g: str, h: list[str]) -> list[Rule]: gRegex = re.compile(g) hRegex = [re.compile(handle) for handle in h] - forbiddenList: T.List[Rule] = list() + forbiddenList: list[Rule] = [] idForbidGrippers = [i for i in range(len(grippers)) if gRegex.match(grippers[i])] forbidHandles = [ handle for handle in allHandles - if not any([handlePattern.match(handle) for handlePattern in hRegex]) + if not any(handlePattern.match(handle) for handlePattern in hRegex) ] for id in idForbidGrippers: for handle in forbidHandles: @@ -350,7 +348,7 @@ def forbidExcept(g: str, h: T.List[str]) -> T.List[Rule]: q0_r0 = [pi / 6, -pi / 2, pi / 2, 0, 0, 0] q0_r1 = q0_r0[::] -q0_spheres = list() +q0_spheres = [] i = 0 y = 0.04 while i < nSphere: @@ -358,7 +356,7 @@ def forbidExcept(g: str, h: T.List[str]) -> T.List[Rule]: i += 1 y = -y -q0_cylinders = list() +q0_cylinders = [] i = 0 y = -0.04 while i < nCylinder: @@ -366,10 +364,10 @@ def forbidExcept(g: str, h: T.List[str]) -> T.List[Rule]: i += 1 y = -y -q0 = np.array(q0_r0 + q0_r1 + sum(q0_spheres, []) + sum(q0_cylinders, [])) +q0 = np.array(q0_r0 + q0_r1 + sum(q0_spheres, []) + sum(q0_cylinders, [])) # noqa: RUF017 if not args.bigGraph: - nodes = list() - rules = list() + nodes = [] + rules = [] grasps = set() nodes.append(StateName(grasps)) rules.append(makeRule(grasps=grasps)) @@ -437,7 +435,7 @@ def forbidExcept(g: str, h: T.List[str]) -> T.List[Rule]: nodes.append(nodes[-1]) else: - rules = list() + rules = [] rules.extend(forbidExcept("^r0/gripper$", ["^sphere\\d*/handle$"])) rules.extend(forbidExcept("^r1/gripper$", ["^cylinder0*/handle$"])) diff --git a/tests/integration/pr2-in-iai-kitchen.py b/tests/integration/pr2-in-iai-kitchen.py old mode 100644 new mode 100755 index c2d1e54b..dd2b5243 --- a/tests/integration/pr2-in-iai-kitchen.py +++ b/tests/integration/pr2-in-iai-kitchen.py @@ -1,12 +1,11 @@ #!/usr/bin/env python3 import numpy as np - -from pyhpp.core import Problem, DiffusingPlanner, Dichotomy, Straight -from pyhpp.pinocchio import Device, urdf +from benchmark_utils import create_benchmark_parser, run_benchmark_main from pinocchio import SE3 -from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pyhpp.core import Dichotomy, DiffusingPlanner, Problem, Straight +from pyhpp.pinocchio import Device, urdf parser = create_benchmark_parser("PR2 Navigation in IAI Kitchen Benchmark") args = parser.parse_args() diff --git a/tests/integration/romeo-placard.py b/tests/integration/romeo-placard.py old mode 100644 new mode 100755 index 0e2b0c6b..d140fe4d --- a/tests/integration/romeo-placard.py +++ b/tests/integration/romeo-placard.py @@ -1,17 +1,16 @@ #!/usr/bin/env python3 import numpy as np +from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pinocchio import SE3 -from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory, Rule -from pyhpp.manipulation import Device, Graph, Problem, urdf, ManipulationPlanner -from pyhpp.core import Straight, ProgressiveProjector from pyhpp.constraints import LockedJoint +from pyhpp.core import ProgressiveProjector, Straight from pyhpp.core.static_stability_constraint_factory import ( StaticStabilityConstraintsFactory, ) -from pinocchio import SE3 - -from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pyhpp.manipulation import Device, Graph, ManipulationPlanner, Problem, urdf +from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory, Rule parser = create_benchmark_parser("Romeo Placard Humanoid Manipulation Benchmark") args = parser.parse_args() @@ -57,8 +56,8 @@ cg.errorThreshold(2e-4) cg.maxIterations(40) -constraints = dict() -graphConstraints = dict() +constraints = {} +graphConstraints = {} leftHandOpen = { "LHand": 1, @@ -92,7 +91,7 @@ # Lock left hand -locklhand = list() +locklhand = [] for j, v in leftHandOpen.items(): joint_name = "romeo/" + j locklhand.append(joint_name) @@ -105,7 +104,7 @@ graphConstraints[joint_name] = cs # Lock right hand -lockrhand = list() +lockrhand = [] for j, v in rightHandOpen.items(): joint_name = "romeo/" + j lockrhand.append(joint_name) diff --git a/tests/integration/test_benchmarks.py b/tests/integration/test_benchmarks.py old mode 100644 new mode 100755 index 84ee36b0..e884f101 --- a/tests/integration/test_benchmarks.py +++ b/tests/integration/test_benchmarks.py @@ -30,6 +30,7 @@ def main(): result = subprocess.run( [sys.executable, str(script), "-N", "1"], cwd=str(folder), + check=False, ) if result.returncode != 0: diff --git a/tests/integration/ur3-spheres-spf.py b/tests/integration/ur3-spheres-spf.py old mode 100644 new mode 100755 index 20b7619d..74af4c30 --- a/tests/integration/ur3-spheres-spf.py +++ b/tests/integration/ur3-spheres-spf.py @@ -6,29 +6,28 @@ # from math import pi + import numpy as np +from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pinocchio import SE3, Quaternion -from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory +from pyhpp.constraints import ( + ComparisonType, + ComparisonTypes, + Implicit, + LockedJoint, + Transformation, +) +from pyhpp.core import Dichotomy, Straight from pyhpp.manipulation import ( Device, Graph, Problem, ProgressiveProjector, - urdf, StatesPathFinder, + urdf, ) -from pyhpp.core import Dichotomy, Straight - -from pyhpp.constraints import ( - Transformation, - ComparisonTypes, - ComparisonType, - Implicit, - LockedJoint, -) -from pinocchio import SE3, Quaternion - -from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory parser = create_benchmark_parser("UR3 Spheres StatesPathFinder Benchmark") args = parser.parse_args() @@ -66,20 +65,20 @@ ) # Load spheres to be manipulated -objects = list() +objects = [] sphere_pose = SE3(rotation=np.identity(3), translation=np.array([0, 0, 0])) for i in range(nSphere): urdf.loadModel( robot, 0, - "sphere{0}".format(i), + f"sphere{i}", "freeflyer", sphere_urdf, sphere_srdf, sphere_pose, ) robot.setJointBounds( - "sphere{0}/root_joint".format(i), + f"sphere{i}/root_joint", [ -1.0, 1.0, @@ -97,7 +96,7 @@ 1.0001, ], ) - objects.append("sphere{0}".format(i)) + objects.append(f"sphere{i}") model = robot.model() @@ -108,13 +107,13 @@ cg.errorThreshold(1e-4) cg.maxIterations(40) -constraints = dict() +constraints = {} ## Grippers grippers = ["ur3/gripper"] ## Handles -handlesPerObject = [["sphere{0}/handle".format(i)] for i in range(nSphere)] +handlesPerObject = [[f"sphere{i}/handle"] for i in range(nSphere)] contactsPerObject = [[] for i in range(nSphere)] ## Constraints @@ -124,11 +123,11 @@ h.mask = [True, True, True, False, True, True] # placement constraint - placementName = "place_sphere{0}".format(i) + placementName = f"place_sphere{i}" Id = SE3.Identity() q = Quaternion(1, 0, 0, 0) ballPlacement = SE3(q, np.array([0, 0, 0.02])) - joint = robot.model().getJointId("sphere{0}/root_joint".format(i)) + joint = robot.model().getJointId(f"sphere{i}/root_joint") pc = Transformation( placementName, robot, @@ -176,7 +175,7 @@ ) ll = LockedJoint( robot, - "sphere{0}/root_joint".format(i), + f"sphere{i}/root_joint", np.array([0, 0, 0.02, 0, 0, 0, 1]), cts, ) @@ -188,11 +187,11 @@ ) # preplacement constraint - preplacementName = "preplace_sphere{0}".format(i) + preplacementName = f"preplace_sphere{i}" Id = SE3.Identity() q = Quaternion(1, 0, 0, 0) ballPrePlacement = SE3(q, np.array([0, 0, 0.1])) - joint = robot.model().getJointId("sphere{0}/root_joint".format(i)) + joint = robot.model().getJointId(f"sphere{i}/root_joint") pc = Transformation( preplacementName, robot, @@ -270,13 +269,13 @@ # cg.setWeight(cg.getTransition(e), 100) for i in range(nSphere): - e = cg.getTransition("ur3/gripper > sphere{}/handle | f_23".format(i)) + e = cg.getTransition(f"ur3/gripper > sphere{i}/handle | f_23") cg.addNumericalConstraintsToTransition( - e, [constraints["place_sphere{}/complement".format(i)]] + e, [constraints[f"place_sphere{i}/complement"]] ) - e = cg.getTransition("ur3/gripper < sphere{}/handle | 0-{}_32".format(i, i)) + e = cg.getTransition(f"ur3/gripper < sphere{i}/handle | 0-{i}_32") cg.addNumericalConstraintsToTransition( - e, [constraints["place_sphere{}/complement".format(i)]] + e, [constraints[f"place_sphere{i}/complement"]] ) problem.steeringMethod(Straight(problem)) diff --git a/tests/integration/ur3-spheres.py b/tests/integration/ur3-spheres.py index 5db12b04..b325af97 100644 --- a/tests/integration/ur3-spheres.py +++ b/tests/integration/ur3-spheres.py @@ -1,27 +1,26 @@ from math import pi + import numpy as np +from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pinocchio import SE3, Quaternion -from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory +from pyhpp.constraints import ( + ComparisonType, + ComparisonTypes, + Implicit, + LockedJoint, + Transformation, +) +from pyhpp.core import Dichotomy, Straight from pyhpp.manipulation import ( Device, Graph, + ManipulationPlanner, Problem, ProgressiveProjector, urdf, - ManipulationPlanner, ) -from pyhpp.core import Dichotomy, Straight - -from pyhpp.constraints import ( - Transformation, - ComparisonTypes, - ComparisonType, - Implicit, - LockedJoint, -) -from pinocchio import SE3, Quaternion - -from benchmark_utils import create_benchmark_parser, run_benchmark_main +from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory parser = create_benchmark_parser("UR3 Spheres Manipulation Benchmark") args = parser.parse_args() @@ -40,21 +39,21 @@ urdf.loadModel(robot, 0, "ur3", "anchor", ur3_urdf, ur3_srdf, ur3_pose) # Load sphere to be manipulated -objects = list() +objects = [] nSphere = 2 sphere_pose = SE3(rotation=np.identity(3), translation=np.array([0, 0, 0])) for i in range(nSphere): urdf.loadModel( robot, 0, - "sphere{0}".format(i), + f"sphere{i}", "freeflyer", sphere_urdf, sphere_srdf, sphere_pose, ) robot.setJointBounds( - "sphere{0}/root_joint".format(i), + f"sphere{i}/root_joint", [ -1.0, 1.0, @@ -72,7 +71,7 @@ 1.0001, ], ) - objects.append("sphere{0}".format(i)) + objects.append(f"sphere{i}") urdf.loadModel( robot, @@ -92,18 +91,18 @@ problem = Problem(robot) cg = Graph("graph", robot, problem) -constraints = dict() +constraints = {} for i in range(nSphere): o = objects[i] h = robot.handles()[o + "/handle"] h.mask = [True, True, True, False, True, True] # placement constraint - placementName = "place_sphere{0}".format(i) + placementName = f"place_sphere{i}" Id = SE3.Identity() q = Quaternion(1, 0, 0, 0) ballPlacement = SE3(q, np.array([0, 0, 0.02])) - joint = robot.model().getJointId("sphere{0}/root_joint".format(i)) + joint = robot.model().getJointId(f"sphere{i}/root_joint") pc = Transformation( placementName, robot, @@ -150,7 +149,7 @@ ) ll = LockedJoint( robot, - "sphere{0}/root_joint".format(i), + f"sphere{i}/root_joint", np.array([0, 0, 0.02, 0, 0, 0, 1]), cts, ) @@ -161,11 +160,11 @@ constraints[placementName + "/hold"], ) - preplacementName = "preplace_sphere{0}".format(i) + preplacementName = f"preplace_sphere{i}" Id = SE3.Identity() q = Quaternion(1, 0, 0, 0) ballPrePlacement = SE3(q, np.array([0, 0, 0.1])) - joint = robot.model().getJointId("sphere{0}/root_joint".format(i)) + joint = robot.model().getJointId(f"sphere{i}/root_joint") pc = Transformation( preplacementName, robot, @@ -229,7 +228,7 @@ ] grippers = ["ur3/gripper"] -handlesPerObject = [["sphere{0}/handle".format(i)] for i in range(nSphere)] +handlesPerObject = [[f"sphere{i}/handle"] for i in range(nSphere)] contactsPerObject = [[] for i in range(nSphere)] cg.maxIterations(40) @@ -249,13 +248,13 @@ # cg.setWeight(cg.getTransition(e), 100) for i in range(nSphere): - e = cg.getTransition("ur3/gripper > sphere{}/handle | f_23".format(i)) + e = cg.getTransition(f"ur3/gripper > sphere{i}/handle | f_23") cg.addNumericalConstraintsToTransition( - e, [constraints["place_sphere{}/complement".format(i)]] + e, [constraints[f"place_sphere{i}/complement"]] ) - e = cg.getTransition("ur3/gripper < sphere{}/handle | 0-{}_32".format(i, i)) + e = cg.getTransition(f"ur3/gripper < sphere{i}/handle | 0-{i}_32") cg.addNumericalConstraintsToTransition( - e, [constraints["place_sphere{}/complement".format(i)]] + e, [constraints[f"place_sphere{i}/complement"]] ) problem.steeringMethod(Straight(problem)) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py old mode 100644 new mode 100755 index 26cbcfa3..2eed8bad --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -6,23 +6,24 @@ # Test fixtures for hpp-python unit tests. # Provides factory functions that create test objects. -import numpy as np from math import pi + +import numpy as np from pinocchio import SE3, Quaternion -from pyhpp.pinocchio import Device as CoreDevice, urdf as core_urdf -from pyhpp.core import Problem as CoreProblem -from pyhpp.manipulation import Device, urdf, Graph, Problem -from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory -from pyhpp.manipulation.security_margins import SecurityMargins from pyhpp.constraints import ( - Transformation, - ComparisonTypes, ComparisonType, + ComparisonTypes, Implicit, LockedJoint, + Transformation, ) - +from pyhpp.core import Problem as CoreProblem +from pyhpp.manipulation import Device, Graph, Problem, urdf +from pyhpp.manipulation.constraint_graph_factory import ConstraintGraphFactory +from pyhpp.manipulation.security_margins import SecurityMargins +from pyhpp.pinocchio import Device as CoreDevice +from pyhpp.pinocchio import urdf as core_urdf UR5_URDF = "package://example-robot-data/robots/ur_description/urdf/ur5_joint_limited_robot.urdf" UR5_SRDF = "package://example-robot-data/robots/ur_description/srdf/ur5_joint_limited_robot.srdf" diff --git a/tests/unit/test_configuration_shooter.py b/tests/unit/test_configuration_shooter.py old mode 100644 new mode 100755 index 8a0029a2..459d34c6 --- a/tests/unit/test_configuration_shooter.py +++ b/tests/unit/test_configuration_shooter.py @@ -5,7 +5,9 @@ # import unittest + import numpy as np + from unit.conftest import create_ur5_problem diff --git a/tests/unit/test_constraint_factory.py b/tests/unit/test_constraint_factory.py old mode 100644 new mode 100755 index 375f4c15..7a636208 --- a/tests/unit/test_constraint_factory.py +++ b/tests/unit/test_constraint_factory.py @@ -5,10 +5,11 @@ # import unittest -from unit.conftest import create_constraint_graph_setup + from pyhpp.manipulation.constraint_graph_factory import ( Constraints, ) +from unit.conftest import create_constraint_graph_setup class TestConstraintFactoryBuildGrasp(unittest.TestCase): @@ -104,21 +105,21 @@ def test_build_grasp_invalid_gripper_raises(self): """Building grasp with non-existent gripper should raise.""" cf = self.factory.constraints - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 cf.buildGrasp("nonexistent/gripper", "sphere0/handle") def test_build_grasp_invalid_handle_raises(self): """Building grasp with non-existent handle should raise.""" cf = self.factory.constraints - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 cf.buildGrasp("ur3/gripper", "nonexistent/handle") def test_build_placement_invalid_object_raises(self): """Building placement with non-existent object should raise.""" cf = self.factory.constraints - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 cf.buildPlacement("nonexistent_object") def test_grasp_constraints_not_empty(self): diff --git a/tests/unit/test_constraint_graph_factory.py b/tests/unit/test_constraint_graph_factory.py old mode 100644 new mode 100755 index 6d4efed2..3b9cab0c --- a/tests/unit/test_constraint_graph_factory.py +++ b/tests/unit/test_constraint_graph_factory.py @@ -5,11 +5,12 @@ # import unittest + from pyhpp.manipulation.constraint_graph_factory import ( - PossibleGrasps, GraspIsAllowed, - Rules, + PossibleGrasps, Rule, + Rules, ) diff --git a/tests/unit/test_device.py b/tests/unit/test_device.py old mode 100644 new mode 100755 index d255daab..0edd4c6b --- a/tests/unit/test_device.py +++ b/tests/unit/test_device.py @@ -5,10 +5,11 @@ # import unittest + import numpy as np from pinocchio import SE3 -from pyhpp.pinocchio import Device, urdf +from pyhpp.pinocchio import Device, urdf UR5_URDF = "package://example-robot-data/robots/ur_description/urdf/ur5_joint_limited_robot.urdf" UR5_SRDF = "package://example-robot-data/robots/ur_description/srdf/ur5_joint_limited_robot.srdf" @@ -80,7 +81,7 @@ def test_set_joint_bounds_multiple_dof(self): def test_set_joint_bounds_invalid_size_raises(self): robot = create_ur5_device() - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 robot.setJointBounds("ur5/shoulder_pan_joint", [-1.0]) @@ -157,7 +158,7 @@ def test_rank_values_are_valid_indices(self): ranks = robot.rankInConfiguration - for joint_name, rank in ranks.items(): + for rank in ranks.values(): self.assertGreaterEqual(rank, 0) self.assertLess(rank, robot.configSize()) @@ -170,13 +171,13 @@ def test_get_joint_position_invalid_frame_raises(self): robot.computeForwardKinematics(1) robot.computeFramesForwardKinematics() - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 robot.getJointPosition("nonexistent_joint") def test_set_joint_bounds_invalid_joint_raises(self): robot = create_ur5_device() - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 robot.setJointBounds("nonexistent_joint", [-1.0, 1.0]) diff --git a/tests/unit/test_differentiable_function.py b/tests/unit/test_differentiable_function.py old mode 100644 new mode 100755 index 65b03ccc..c5022c08 --- a/tests/unit/test_differentiable_function.py +++ b/tests/unit/test_differentiable_function.py @@ -5,9 +5,11 @@ # import unittest + import numpy as np -from pyhpp.pinocchio import LiegroupElement + from pyhpp.constraints import DifferentiableFunction +from pyhpp.pinocchio import LiegroupElement class DoubleFunction(DifferentiableFunction): diff --git a/tests/unit/test_doxygen_xml_parser.py b/tests/unit/test_doxygen_xml_parser.py old mode 100644 new mode 100755 index 91edced4..8df15f0b --- a/tests/unit/test_doxygen_xml_parser.py +++ b/tests/unit/test_doxygen_xml_parser.py @@ -10,7 +10,6 @@ from doc.doxygen_xml_parser import ClassDoc - DOXYGEN_XML = """\ diff --git a/tests/unit/test_handles_grippers.py b/tests/unit/test_handles_grippers.py old mode 100644 new mode 100755 index 7754e857..1e9417a0 --- a/tests/unit/test_handles_grippers.py +++ b/tests/unit/test_handles_grippers.py @@ -5,9 +5,10 @@ # import unittest + from pinocchio import SE3 -from pyhpp.manipulation import Device, urdf +from pyhpp.manipulation import Device, urdf UR3_URDF = "package://example-robot-data/robots/ur_description/urdf/ur3_gripper.urdf" UR3_SRDF = "package://example-robot-data/robots/ur_description/srdf/ur3_gripper.srdf" diff --git a/tests/unit/test_interpolated_path.py b/tests/unit/test_interpolated_path.py index c1923bdd..efb4afd6 100644 --- a/tests/unit/test_interpolated_path.py +++ b/tests/unit/test_interpolated_path.py @@ -3,6 +3,7 @@ import unittest import numpy as np + from pyhpp.core import InterpolatedPath, interval from pyhpp.core.path import Vector from unit.conftest import create_ur5_problem diff --git a/tests/unit/test_liegroup.py b/tests/unit/test_liegroup.py old mode 100644 new mode 100755 index bd8135b7..bbc49296 --- a/tests/unit/test_liegroup.py +++ b/tests/unit/test_liegroup.py @@ -5,8 +5,10 @@ # import unittest + import numpy as np -from pyhpp.pinocchio import LiegroupSpace, LiegroupElement + +from pyhpp.pinocchio import LiegroupElement, LiegroupSpace class TestLiegroupSpace(unittest.TestCase): diff --git a/tests/unit/test_path.py b/tests/unit/test_path.py old mode 100644 new mode 100755 index f1fa399b..5df5a2af --- a/tests/unit/test_path.py +++ b/tests/unit/test_path.py @@ -5,9 +5,11 @@ # import unittest + import numpy as np -from unit.conftest import create_ur5_problem + import pyhpp.core.path +from unit.conftest import create_ur5_problem class TestPathMethods(unittest.TestCase): diff --git a/tests/unit/test_path_optimizer.py b/tests/unit/test_path_optimizer.py old mode 100644 new mode 100755 index 3bd470b4..1902f69d --- a/tests/unit/test_path_optimizer.py +++ b/tests/unit/test_path_optimizer.py @@ -5,10 +5,12 @@ # import unittest + import numpy as np -from unit.conftest import create_ur5_problem -from pyhpp.core import RandomShortcut, SimpleShortcut + import pyhpp.core.path +from pyhpp.core import RandomShortcut, SimpleShortcut +from unit.conftest import create_ur5_problem class TestPathOptimizerInstantiation(unittest.TestCase): diff --git a/tests/unit/test_path_planner.py b/tests/unit/test_path_planner.py old mode 100644 new mode 100755 index fe34ff5a..6d80f2dc --- a/tests/unit/test_path_planner.py +++ b/tests/unit/test_path_planner.py @@ -5,13 +5,15 @@ # import unittest + import numpy as np -from unit.conftest import create_ur5_problem + from pyhpp.core import ( - DiffusingPlanner, BiRRTPlanner, + DiffusingPlanner, VisibilityPrmPlanner, ) +from unit.conftest import create_ur5_problem class TestPathPlannerInstantiation(unittest.TestCase): @@ -56,7 +58,7 @@ def test_max_iterations_defaults_to_zero(self): class TestPathPlannerSolve(unittest.TestCase): def test_birrt_solves_simple_path(self): """BiRRT should find a path between nearby collision-free configurations.""" - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_init = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) q_goal = np.array([0.5, -1.57, -1.8, 0.0, 0.8, 0.0]) @@ -79,31 +81,31 @@ class TestPathPlannerNegativeCases(unittest.TestCase): def test_solve_without_goal_raises(self): """Solving without a goal configuration should raise an error.""" - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_init = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) problem.initConfig(q_init) planner = BiRRTPlanner(problem) planner.maxIterations(10) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa B017 planner.solve() def test_solve_without_init_raises(self): """Solving without an initial configuration should raise an error.""" - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_goal = np.array([0.5, -1.57, -1.8, 0.0, 0.8, 0.0]) problem.addGoalConfig(q_goal) planner = BiRRTPlanner(problem) planner.maxIterations(10) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa B017 planner.solve() def test_max_iterations_zero_limits_exploration(self): """Planner with zero max iterations should do minimal exploration.""" - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_init = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) q_goal = np.array([3.0, -1.57, -1.8, 0.0, 0.8, 0.0]) problem.initConfig(q_init) @@ -114,8 +116,8 @@ def test_max_iterations_zero_limits_exploration(self): try: planner.solve() - except Exception: - pass + except Exception as e: # noqa: BLE001 + print(e) roadmap = planner.roadmap() self.assertLessEqual(len(roadmap.nodes()), 2) diff --git a/tests/unit/test_path_projector.py b/tests/unit/test_path_projector.py old mode 100644 new mode 100755 index 3e169977..4fbca0d8 --- a/tests/unit/test_path_projector.py +++ b/tests/unit/test_path_projector.py @@ -5,12 +5,14 @@ # import unittest + import numpy as np -from unit.conftest import create_ur5_problem + from pyhpp.core import ( - Progressive, GlobalProjector, + Progressive, ) +from unit.conftest import create_ur5_problem class TestPathProjectorInstantiation(unittest.TestCase): diff --git a/tests/unit/test_path_validation.py b/tests/unit/test_path_validation.py old mode 100644 new mode 100755 index 4be7d432..91dc1c76 --- a/tests/unit/test_path_validation.py +++ b/tests/unit/test_path_validation.py @@ -5,7 +5,9 @@ # import unittest + import numpy as np + from unit.conftest import create_ur5_problem @@ -21,7 +23,7 @@ def test_collision_free_path_is_valid(self): steer = self.problem.steeringMethod() path = steer(q1, q2) - is_valid, valid_part, report = self.problem.pathValidation().validate( + is_valid, _valid_part, _report = self.problem.pathValidation().validate( path, False ) self.assertTrue(is_valid) @@ -33,7 +35,7 @@ def test_zero_length_path_returns_valid_part(self): steer = self.problem.steeringMethod() path = steer(q1, q1) - is_valid, valid_part, report = self.problem.pathValidation().validate( + _is_valid, valid_part, _report = self.problem.pathValidation().validate( path, False ) self.assertIsNotNone(valid_part) @@ -66,7 +68,7 @@ def test_valid_part_never_none(self): steer = self.problem.steeringMethod() path = steer(q1, q2) - is_valid, valid_part, report = self.problem.pathValidation().validate( + _is_valid, valid_part, _report = self.problem.pathValidation().validate( path, False ) @@ -80,7 +82,7 @@ def test_valid_part_length_less_than_or_equal_original(self): steer = self.problem.steeringMethod() path = steer(q1, q2) - is_valid, valid_part, report = self.problem.pathValidation().validate( + _is_valid, valid_part, _report = self.problem.pathValidation().validate( path, False ) @@ -94,7 +96,7 @@ def test_reverse_flag_produces_valid_result(self): steer = self.problem.steeringMethod() path = steer(q1, q2) - is_valid, valid_part, report = self.problem.pathValidation().validate( + is_valid, valid_part, _report = self.problem.pathValidation().validate( path, True ) diff --git a/tests/unit/test_position_constraint.py b/tests/unit/test_position_constraint.py old mode 100644 new mode 100755 index 3800ed3e..6452440a --- a/tests/unit/test_position_constraint.py +++ b/tests/unit/test_position_constraint.py @@ -5,11 +5,13 @@ # import unittest + import numpy as np -from pinocchio import SE3, StdVec_Bool as Mask -from pyhpp.pinocchio import Device, LiegroupElement, urdf -from pyhpp.constraints import Position +from pinocchio import SE3 +from pinocchio import StdVec_Bool as Mask +from pyhpp.constraints import Position +from pyhpp.pinocchio import Device, LiegroupElement, urdf UR5_URDF = "package://example-robot-data/robots/ur_description/urdf/ur5_joint_limited_robot.urdf" UR5_SRDF = "package://example-robot-data/robots/ur_description/srdf/ur5_joint_limited_robot.srdf" diff --git a/tests/unit/test_problem.py b/tests/unit/test_problem.py old mode 100644 new mode 100755 index 00e08977..1b50096f --- a/tests/unit/test_problem.py +++ b/tests/unit/test_problem.py @@ -5,43 +5,45 @@ # import unittest + import numpy as np from pinocchio import SE3 + from pyhpp.manipulation import Problem as ManipulationProblem from unit.conftest import create_ur3_robot, create_ur5_problem class TestProblemAccessors(unittest.TestCase): def test_steering_method_returns_object(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() sm = problem.steeringMethod() self.assertIsNotNone(sm) def test_distance_returns_object(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() distance = problem.distance() self.assertIsNotNone(distance) def test_configuration_shooter_returns_object(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() shooter = problem.configurationShooter() self.assertIsNotNone(shooter) def test_path_validation_returns_object(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() pv = problem.pathValidation() self.assertIsNotNone(pv) def test_config_validation_returns_object(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() cv = problem.configValidation() @@ -50,7 +52,7 @@ def test_config_validation_returns_object(self): class TestProblemDirectPath(unittest.TestCase): def test_direct_path_without_validation(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_start = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) q_end = np.array([0.1, -1.57, -1.8, 0.0, 0.8, 0.0]) @@ -58,26 +60,26 @@ def test_direct_path_without_validation(self): self.assertIsInstance(result, tuple) self.assertEqual(len(result), 3) - valid, path, report = result + valid, path, _report = result self.assertTrue(valid) self.assertIsNotNone(path) def test_direct_path_with_validation(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() problem.addConfigValidation("JointBoundValidation") q_start = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) q_end = np.array([0.1, -1.57, -1.8, 0.0, 0.8, 0.0]) - valid, path, report = problem.directPath(q_start, q_end, True) + valid, _path, _report = problem.directPath(q_start, q_end, True) self.assertIsInstance(valid, bool) def test_direct_path_endpoints_match(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q_start = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) q_end = np.array([0.5, -1.57, -1.8, 0.0, 0.8, 0.0]) - valid, path, report = problem.directPath(q_start, q_end, False) + _valid, path, _report = problem.directPath(q_start, q_end, False) np.testing.assert_array_almost_equal(path.initial(), q_start) np.testing.assert_array_almost_equal(path.end(), q_end) @@ -85,33 +87,33 @@ def test_direct_path_endpoints_match(self): class TestProblemConstraintProjection(unittest.TestCase): def test_error_threshold_settable(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() problem.errorThreshold = 1e-6 self.assertAlmostEqual(problem.errorThreshold, 1e-6) def test_max_iter_projection_settable(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() problem.maxIterProjection = 50 self.assertEqual(problem.maxIterProjection, 50) def test_apply_constraints_returns_tuple(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() q = np.array([0.0, -1.57, -1.8, 0.0, 0.8, 0.0]) result = problem.applyConstraints(q) self.assertIsInstance(result, tuple) self.assertEqual(len(result), 3) - success, output, residual = result + success, output, _residual = result self.assertIsInstance(success, bool) self.assertEqual(len(output), len(q)) def test_add_numerical_constraints_updates_active_constraint_set(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() active_constraints = problem.getConstraints() constraint = problem.createTransformationConstraint( "test_constraint", @@ -141,7 +143,7 @@ def test_projection_defaults_match_core_problem(self): class TestProblemTransformationConstraints(unittest.TestCase): def test_create_transformation_constraint(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() M = SE3.Identity() mask = [True, True, True, True, True, True] @@ -152,7 +154,7 @@ def test_create_transformation_constraint(self): self.assertIsNotNone(constraint) def test_create_relative_transformation_constraint(self): - problem, robot = create_ur5_problem() + problem, _robot = create_ur5_problem() M = SE3.Identity() mask = [True, True, True, True, True, True] diff --git a/tests/unit/test_roadmap.py b/tests/unit/test_roadmap.py old mode 100644 new mode 100755 index 9f5a5969..378a1068 --- a/tests/unit/test_roadmap.py +++ b/tests/unit/test_roadmap.py @@ -5,9 +5,11 @@ # import unittest + import numpy as np -from unit.conftest import create_ur5_problem + from pyhpp.core import Roadmap, WeighedDistance +from unit.conftest import create_ur5_problem class TestRoadmap(unittest.TestCase): diff --git a/tests/unit/test_security_margins.py b/tests/unit/test_security_margins.py old mode 100644 new mode 100755 index 92c4fd7d..6af9eb5c --- a/tests/unit/test_security_margins.py +++ b/tests/unit/test_security_margins.py @@ -5,11 +5,12 @@ # import unittest + +from pyhpp.manipulation.security_margins import SecurityMargins from unit.conftest import ( - create_security_margins_instance, create_constraint_graph_setup, + create_security_margins_instance, ) -from pyhpp.manipulation.security_margins import SecurityMargins class TestSecurityMarginsCorrectness(unittest.TestCase): diff --git a/tests/unit/test_static_stability.py b/tests/unit/test_static_stability.py old mode 100644 new mode 100755 index d777dd4c..cfe781a2 --- a/tests/unit/test_static_stability.py +++ b/tests/unit/test_static_stability.py @@ -5,13 +5,14 @@ # import unittest + import numpy as np from pinocchio import SE3 -from pyhpp.manipulation import Device, Problem, urdf from pyhpp.core.static_stability_constraint_factory import ( StaticStabilityConstraintsFactory, ) +from pyhpp.manipulation import Device, Problem, urdf def load_romeo(): diff --git a/tests/unit/test_steering_method.py b/tests/unit/test_steering_method.py old mode 100644 new mode 100755 index ac396c93..b7cf6323 --- a/tests/unit/test_steering_method.py +++ b/tests/unit/test_steering_method.py @@ -5,7 +5,9 @@ # import unittest + import numpy as np + from unit.conftest import create_ur5_problem