Skip to content

Commit

Permalink
not use default mutable object
Browse files Browse the repository at this point in the history
  • Loading branch information
neka-nat committed Aug 28, 2022
1 parent b8a53e3 commit 3e5612f
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 36 deletions.
4 changes: 4 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[flake8]
max-line-length = 119
exclude = __init__.py,__pycache__
ignore = E121,E123,E126,E133,E226,E203,E241,E242,E704,W503,W504,W505,E127,E266,E402,W605,W391,E701,E731
17 changes: 10 additions & 7 deletions kinpy/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _find_frame_recursive(name: str, frame: frame.Frame) -> Optional[frame.Frame
if child.name == name:
return child
ret = Chain._find_frame_recursive(name, child)
if not ret is None:
if ret is not None:
return ret
return None

Expand All @@ -31,7 +31,7 @@ def _find_link_recursive(name: str, frame: frame.Frame) -> Optional[frame.Frame]
if child.link.name == name:
return child.link
ret = Chain._find_link_recursive(name, child)
if not ret is None:
if ret is not None:
return ret
return None

Expand All @@ -55,13 +55,14 @@ def get_joint_parameter_names(self, exclude_fixed: bool = True) -> List[str]:

def add_frame(self, frame: frame.Frame, parent_name: str) -> None:
frame = self.find_frame(parent_name)
if not frame is None:
if frame is not None:
frame.add_child(frame)

@staticmethod
def _forward_kinematics(
root: frame.Frame, th_dict: Dict[str, float], world: transform.Transform = transform.Transform()
root: frame.Frame, th_dict: Dict[str, float], world: Optional[transform.Transform] = None
) -> Dict[str, transform.Transform]:
world = world or transform.Transform()
link_transforms = {}
trans = world * root.get_transform(th_dict.get(root.joint.name, 0.0))
link_transforms[root.link.name] = trans * root.link.offset
Expand All @@ -70,8 +71,9 @@ def _forward_kinematics(
return link_transforms

def forward_kinematics(
self, th: Union[Dict[str, float], List[float]], world=transform.Transform()
self, th: Union[Dict[str, float], List[float]], world: Optional[transform.Transform] = None
) -> Dict[str, transform.Transform]:
world = world or transform.Transform()
if not isinstance(th, dict):
jn = self.get_joint_parameter_names()
assert len(jn) == len(th)
Expand Down Expand Up @@ -111,7 +113,7 @@ def _generate_serial_chain_recurse(root_frame: frame.Frame, end_frame_name: str)
return [child]
else:
frames = SerialChain._generate_serial_chain_recurse(child, end_frame_name)
if not frames is None:
if frames is not None:
return [child] + frames
return None

Expand All @@ -124,8 +126,9 @@ def get_joint_parameter_names(self, exclude_fixed: bool = True) -> List[str]:
return names

def forward_kinematics(
self, th: List[float], world: transform.Transform = transform.Transform(), end_only: bool = True
self, th: List[float], world: Optional[transform.Transform] = None, end_only: bool = True
) -> Union[transform.Transform, Dict[str, transform.Transform]]:
world = world or transform.Transform()
cnt = 0
link_transforms = {}
trans = world
Expand Down
30 changes: 17 additions & 13 deletions kinpy/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ class Visual(object):

def __init__(
self,
offset: transform.Transform = transform.Transform(),
offset: Optional[transform.Transform] = None,
geom_type: Optional[str] = None,
geom_param: Any = None,
) -> None:
self.offset = offset
self.offset = offset or transform.Transform()
self.geom_type = geom_type
self.geom_param = geom_param

Expand All @@ -26,11 +26,11 @@ def __repr__(self) -> None:

class Link(object):
def __init__(
self, name: Optional[str] = None, offset: transform.Transform = transform.Transform(), visuals: List = []
self, name: Optional[str] = None, offset: Optional[transform.Transform] = None, visuals: Optional[List] = None
) -> None:
self.name = name
self.offset = offset
self.visuals = visuals
self.offset = offset or transform.Transform()
self.visuals = visuals or []

def __repr__(self) -> None:
return "Link(name='{0}', offset={1}, visuals={2})".format(self.name, self.offset, self.visuals)
Expand All @@ -42,17 +42,17 @@ class Joint(object):
def __init__(
self,
name: Optional[str] = None,
offset: transform.Transform = transform.Transform(),
offset: Optional[transform.Transform] = None,
joint_type: str = "fixed",
axis: List = [0.0, 0.0, 1.0],
axis: Optional[List[float]] = None,
) -> None:
self.name = name
self.offset = offset
self.offset = offset or transform.Transform()
self.joint_type = joint_type
if self.joint_type != "fixed" and axis is None:
self.axis = np.array([0.0, 0.0, 1.0])
else:
self.axis = np.array(axis)
self.axis = np.array(axis) if axis is not None else np.array([0.0, 0.0, 1.0])

def __repr__(self) -> None:
return "Joint(name='{0}', offset={1}, joint_type='{2}', axis={3})".format(
Expand All @@ -62,12 +62,16 @@ def __repr__(self) -> None:

class Frame(object):
def __init__(
self, name: Optional[str] = None, link: Link = Link(), joint: Joint = Joint(), children: List["Frame"] = []
self,
name: Optional[str] = None,
link: Optional[Link] = None,
joint: Optional[Joint] = None,
children: Optional[List["Frame"]] = None,
) -> None:
self.name = "None" if name is None else name
self.link = link
self.joint = joint
self.children = children
self.link = link or Link()
self.joint = joint or Joint()
self.children = children or []

def __str__(self, level: int = 0) -> str:
ret = " \t" * level + self.name + "\n"
Expand Down
8 changes: 5 additions & 3 deletions kinpy/jacobian.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from typing import Any, List
from typing import Any, List, Optional
import numpy as np

from . import transform


def calc_jacobian(serial_chain: Any, th: List[float], tool: transform.Transform = transform.Transform()) -> np.ndarray:
def calc_jacobian(serial_chain: Any, th: List[float], tool: Optional[transform.Transform] = None) -> np.ndarray:
tool = tool or transform.Transform()
ndof = len(th)
j_fl = np.zeros((6, ndof))
cur_transform = tool.matrix()
Expand Down Expand Up @@ -32,8 +33,9 @@ def calc_jacobian(serial_chain: Any, th: List[float], tool: transform.Transform


def calc_jacobian_frames(
serial_chain: Any, th: List[float], link_name: str, tool: transform.Transform = transform.Transform()
serial_chain: Any, th: List[float], link_name: str, tool: Optional[transform.Transform] = None
) -> np.ndarray:
tool = tool or transform.Transform()
ndof = len(th)
j_fl = np.zeros((6, ndof))
cur_transform = tool.matrix()
Expand Down
14 changes: 9 additions & 5 deletions kinpy/mjcf.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from typing import Dict
from typing import Dict, Optional
from . import chain, frame, mjcf_parser, transform


JOINT_TYPE_MAP: Dict[str, str] = {"hinge": "revolute", "slide": "prismatic"}


def geoms_to_visuals(geom, base=transform.Transform()):
def geoms_to_visuals(geom, base: Optional[transform.Transform] = None):
base = base or transform.Transform()
visuals = []
for g in geom:
if g.type == "capsule":
Expand All @@ -20,11 +21,13 @@ def geoms_to_visuals(geom, base=transform.Transform()):
return visuals


def body_to_link(body, base=transform.Transform()):
def body_to_link(body, base: Optional[transform.Transform] = None):
base = base or transform.Transform()
return frame.Link(body.name, offset=base * transform.Transform(body.quat, body.pos))


def joint_to_joint(joint, base=transform.Transform()):
def joint_to_joint(joint, base: Optional[transform.Transform] = None):
base = base or transform.Transform()
return frame.Joint(
joint.name,
offset=base * transform.Transform(pos=joint.pos),
Expand All @@ -33,7 +36,8 @@ def joint_to_joint(joint, base=transform.Transform()):
)


def add_composite_joint(root_frame, joints, base=transform.Transform()):
def add_composite_joint(root_frame, joints, base: Optional[transform.Transform] = None):
base = base or transform.Transform()
if len(joints) > 0:
root_frame.children = root_frame.children + [
frame.Frame(link=frame.Link(name=root_frame.link.name + "_child"), joint=joint_to_joint(joints[0], base))
Expand Down
8 changes: 6 additions & 2 deletions kinpy/transform.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Union
from typing import List, Optional, Union
import numpy as np
import transformations as tf

Expand All @@ -14,7 +14,11 @@ class Transform(object):
The translation parameter.
"""

def __init__(self, rot: Union[List, np.ndarray] = [1.0, 0.0, 0.0, 0.0], pos: np.ndarray = np.zeros(3)) -> None:
def __init__(self, rot: Union[List, np.ndarray, None] = None, pos: Optional[np.ndarray] = None) -> None:
if rot is None:
rot = [1.0, 0.0, 0.0, 0.0]
if pos is None:
pos = np.zeros(3)
if rot is None:
self.rot = np.array([1.0, 0.0, 0.0, 0.0])
elif len(rot) == 3:
Expand Down
17 changes: 11 additions & 6 deletions kinpy/visualizer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, List, Tuple
from typing import Dict, List, Optional, Tuple
import os

import numpy as np
Expand Down Expand Up @@ -83,33 +83,38 @@ def load_stl(self, filename: str) -> None:
reader.SetFileName(filename)
return reader

def add_cylinder(self, radius: float, height: float, tf: transform.Transform = transform.Transform()):
def add_cylinder(self, radius: float, height: float, tf: Optional[transform.Transform] = None) -> None:
tf = tf or transform.Transform()
cylinder = vtk.vtkCylinderSource()
cylinder.SetResolution(20)
cylinder.SetRadius(radius)
cylinder.SetHeight(height)
self.add_shape_source(cylinder, tf)

def add_box(self, size: List[float], tf: transform.Transform = transform.Transform()) -> None:
def add_box(self, size: List[float], tf: Optional[transform.Transform] = None) -> None:
tf = tf or transform.Transform()
cube = vtk.vtkCubeSource()
cube.SetXLength(size[0])
cube.SetYLength(size[1])
cube.SetZLength(size[2])
self.add_shape_source(cube, tf)

def add_sphere(self, radius: float, tf: transform.Transform = transform.Transform()) -> None:
def add_sphere(self, radius: float, tf: Optional[transform.Transform] = None) -> None:
tf = tf or transform.Transform()
sphere = vtk.vtkSphereSource()
sphere.SetRadius(radius)
self.add_shape_source(sphere, tf)

def add_capsule(
self, radius: float, fromto: np.ndarray, tf: transform.Transform = transform.Transform(), step: float = 0.05
self, radius: float, fromto: np.ndarray, tf: Optional[transform.Transform] = None, step: float = 0.05
) -> None:
tf = tf or transform.Transform()
for t in np.arange(0.0, 1.0, step):
trans = transform.Transform(pos=t * fromto[:3] + (1.0 - t) * fromto[3:])
self.add_sphere(radius, tf * trans)

def add_mesh(self, filename: str, tf: transform.Transform = transform.Transform()) -> None:
def add_mesh(self, filename: str, tf: Optional[transform.Transform] = None) -> None:
tf = tf or transform.Transform()
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext == ".stl":
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ vtk = "^9.0.1"
twine = "^3.3.0"
isort = "^5.9.3"
black = "^22.6.0"
flake8 = "^5.0.4"
flake8-bugbear = "^22.8.23"

[build-system]
requires = ["poetry-core>=1.0.0", "setuptools"]
Expand Down

0 comments on commit 3e5612f

Please sign in to comment.