Skip to content

Commit

Permalink
Merge pull request #1065 from StanfordVL/ruff
Browse files Browse the repository at this point in the history
Enable and comply with ruff linter
  • Loading branch information
cgokmen authored Dec 27, 2024
2 parents fefe56e + 9fb980e commit 260704c
Show file tree
Hide file tree
Showing 156 changed files with 660 additions and 510 deletions.
16 changes: 7 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
repos:
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.3.0
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.8.4
hooks:
- id: black
language_version: python3.10
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
name: isort (python)
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
Expand Down
26 changes: 24 additions & 2 deletions omnigibson/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import signal
import tempfile

import nest_asyncio

from omnigibson.controllers import REGISTERED_CONTROLLERS
from omnigibson.envs import Environment, VectorEnvironment
from omnigibson.macros import gm
Expand All @@ -24,15 +26,14 @@
) # We set this in the kernel.json file

# Always enable nest_asyncio because MaterialPrim calls asyncio.run()
import nest_asyncio

nest_asyncio.apply()

__version__ = "1.1.1"

root_path = os.path.dirname(os.path.realpath(__file__))

# Store paths to example configs
# TODO: Move this elsewhere.
example_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs")

# Initialize global variables
Expand Down Expand Up @@ -142,3 +143,24 @@ def shutdown_handler(*args, **kwargs):

# Something somewhere disables the default SIGINT handler, so we need to re-enable it
signal.signal(signal.SIGINT, shutdown_handler)

__all__ = [
"ALL_SENSOR_MODALITIES",
"app",
"cleanup",
"clear",
"Environment",
"example_config_path",
"gm",
"launch",
"log",
"REGISTERED_CONTROLLERS",
"REGISTERED_OBJECTS",
"REGISTERED_ROBOTS",
"REGISTERED_SCENES",
"REGISTERED_TASKS",
"shutdown",
"sim",
"tempdir",
"VectorEnvironment",
]
5 changes: 1 addition & 4 deletions omnigibson/action_primitives/curobo.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import math
import os
from collections.abc import Iterable
from enum import Enum

Expand All @@ -11,10 +10,8 @@
from omnigibson.macros import create_module_macros
from omnigibson.object_states.factory import METALINK_PREFIXES
from omnigibson.prims.rigid_prim import RigidPrim
from omnigibson.robots.articulated_trunk_robot import ArticulatedTrunkRobot
from omnigibson.robots.holonomic_base_robot import HolonomicBaseRobot
from omnigibson.utils.constants import GROUND_CATEGORIES, JointType
from omnigibson.utils.control_utils import FKSolver
from omnigibson.utils.constants import JointType

# Gives 1 - 5% better speedup, according to https://github.com/NVlabs/curobo/discussions/245#discussioncomment-9265692
th.backends.cudnn.benchmark = True
Expand Down
18 changes: 5 additions & 13 deletions omnigibson/action_primitives/starter_semantic_action_primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
"""

import inspect
import logging
import math
import random
from functools import cached_property

import cv2
import gymnasium as gym
Expand All @@ -28,11 +26,9 @@
BaseActionPrimitiveSet,
)
from omnigibson.controllers import DifferentialDriveController, InverseKinematicsController, JointController
from omnigibson.controllers.controller_base import ControlType
from omnigibson.macros import create_module_macros
from omnigibson.objects.object_base import BaseObject
from omnigibson.objects.usd_object import USDObject
from omnigibson.robots import *
from omnigibson.robots import R1, BaseRobot, BehaviorRobot, Fetch, Freight, Husky, Locobot, Stretch, Tiago, Turtlebot
from omnigibson.robots.locomotion_robot import LocomotionRobot
from omnigibson.robots.manipulation_robot import ManipulationRobot
from omnigibson.tasks.behavior_task import BehaviorTask
Expand Down Expand Up @@ -313,11 +309,9 @@ def __init__(
self.robot.controllers["base"], (JointController, DifferentialDriveController)
), "StarterSemanticActionPrimitives only works with a JointController or DifferentialDriveController at the robot base."
if self._base_controller_is_joint:
assert not self.robot.controllers[
"base"
].use_delta_commands, (
"StarterSemanticActionPrimitives only works with a base JointController with absolute mode."
)
assert (
not self.robot.controllers["base"].use_delta_commands
), "StarterSemanticActionPrimitives only works with a base JointController with absolute mode."

self.robot_model = self.robot.model_name
self.add_context = add_context
Expand All @@ -342,7 +336,6 @@ def __init__(
quat_relative_axis_angle = T.quat2axisangle(quat_relative)
self._arm_targets[arm] = (pos_relative, quat_relative_axis_angle)
else:

arm_target = cb.to_torch(control_dict["joint_position"])[arm_ctrl.dof_idx]
self._arm_targets[arm] = arm_target

Expand Down Expand Up @@ -1171,7 +1164,6 @@ def _move_hand_direct_ik(
target_pos = target_pose[0]
target_orn = target_pose[1]
target_orn_axisangle = T.quat2axisangle(target_pose[1])
control_idx = self.robot.controller_action_idx["arm_" + self.arm]
prev_pos = prev_orn = None

# All we need to do here is save the target IK position so that empty action takes us towards it
Expand Down Expand Up @@ -1200,7 +1192,7 @@ def _move_hand_direct_ik(
pos_diff = th.norm(prev_pos - current_pos)
orn_diff = T.get_orientation_diff_in_radian(current_orn, prev_orn)
if pos_diff < 0.0003 and orn_diff < 0.01:
raise ActionPrimitiveError(ActionPrimitiveError.Reason.EXECUTION_ERROR, f"Hand is stuck")
raise ActionPrimitiveError(ActionPrimitiveError.Reason.EXECUTION_ERROR, "Hand is stuck")

prev_pos = current_pos
prev_orn = current_orn
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from omnigibson.action_primitives.starter_semantic_action_primitives import StarterSemanticActionPrimitives
from omnigibson.objects import DatasetObject
from omnigibson.robots.robot_base import BaseRobot
from omnigibson.transition_rules import REGISTERED_RULES, SlicingRule, TransitionRuleAPI
from omnigibson.transition_rules import SlicingRule


class SymbolicSemanticActionPrimitiveSet(IntEnum):
Expand Down
19 changes: 19 additions & 0 deletions omnigibson/controllers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,22 @@ def create_controller(name, **kwargs):
controller_cls = REGISTERED_CONTROLLERS[name]

return controller_cls(**kwargs)


__all__ = [
"ControlType",
"create_controller",
"DifferentialDriveController",
"GripperController",
"InverseKinematicsController",
"IsGraspingState",
"JointController",
"LocomotionController",
"ManipulationController",
"MultiFingerGripperController",
"NullJointController",
"OperationalSpaceController",
"REGISTERED_CONTROLLERS",
"REGISTERED_LOCOMOTION_CONTROLLERS",
"REGISTERED_MANIPULATION_CONTROLLERS",
]
8 changes: 5 additions & 3 deletions omnigibson/controllers/controller_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ def __init__(
# Standardize command input / output limits to be (min_array, max_array)
command_input_limits = (
self._generate_default_command_input_limits()
if type(command_input_limits) == str and command_input_limits == "default"
if type(command_input_limits) is str and command_input_limits == "default"
else command_input_limits
)
command_output_limits = (
self._generate_default_command_output_limits()
if type(command_output_limits) == str and command_output_limits == "default"
if type(command_output_limits) is str and command_output_limits == "default"
else command_output_limits
)
self._command_input_limits = (
Expand Down Expand Up @@ -451,7 +451,9 @@ def nums2array(nums, dim):
return (
nums
if isinstance(nums, cb.arr_type)
else cb.array(nums) if isinstance(nums, Iterable) else cb.ones(dim) * nums
else cb.array(nums)
if isinstance(nums, Iterable)
else cb.ones(dim) * nums
)

@property
Expand Down
2 changes: 1 addition & 1 deletion omnigibson/controllers/dd_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(
self._wheel_axle_halflength = wheel_axle_length / 2.0

# If we're using default command output limits, map this to maximum linear / angular velocities
if type(command_output_limits) == str and command_output_limits == "default":
if type(command_output_limits) is str and command_output_limits == "default":
min_vels = control_limits["velocity"][0][dof_idx]
assert (
min_vels[0] == min_vels[1]
Expand Down
21 changes: 8 additions & 13 deletions omnigibson/controllers/ik_controller.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import math
from collections.abc import Iterable

import numpy as np
import torch as th
from numba import jit

import omnigibson.utils.transform_utils as TT
import omnigibson.utils.transform_utils_np as NT
from omnigibson.controllers import ControlType, ManipulationController
from omnigibson.controllers.joint_controller import JointController
from omnigibson.utils.backend_utils import _compute_backend as cb
Expand Down Expand Up @@ -142,7 +148,7 @@ def limiter(target_pos: Array[float], target_quat: Array[float], control_dict: D
# The output orientation limits are also set to be values assuming delta commands, so those are updated too
if self.mode == "pose_absolute_ori":
if command_input_limits is not None:
if type(command_input_limits) == str and command_input_limits == "default":
if type(command_input_limits) is str and command_input_limits == "default":
command_input_limits = [
cb.array([-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi]),
cb.array([1.0, 1.0, 1.0, math.pi, math.pi, math.pi]),
Expand All @@ -156,7 +162,7 @@ def limiter(target_pos: Array[float], target_quat: Array[float], control_dict: D
cb.array(command_output_limits[0]),
cb.array(command_output_limits[1]),
]
if type(command_output_limits) == str and command_output_limits == "default":
if type(command_output_limits) is str and command_output_limits == "default":
command_output_limits = [
cb.array([-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi]),
cb.array([1.0, 1.0, 1.0, math.pi, math.pi, math.pi]),
Expand Down Expand Up @@ -371,11 +377,6 @@ def command_dim(self):
return IK_MODE_COMMAND_DIMS[self.mode]


import torch as th

import omnigibson.utils.transform_utils as TT


@th.jit.script
def _compute_ik_qpos_torch(
q: th.Tensor,
Expand Down Expand Up @@ -405,12 +406,6 @@ def _compute_ik_qpos_torch(
)


import numpy as np
from numba import jit

import omnigibson.utils.transform_utils_np as NT


# Use numba since faster
@jit(nopython=True)
def _compute_ik_qpos_numpy(
Expand Down
19 changes: 8 additions & 11 deletions omnigibson/controllers/joint_controller.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import math

import numpy as np
import torch as th
from numba import jit

from omnigibson.controllers import (
ControlType,
GripperController,
Expand Down Expand Up @@ -127,7 +131,7 @@ def __init__(
# When in delta mode, it doesn't make sense to infer output range using the joint limits (since that's an
# absolute range and our values are relative). So reject the default mode option in that case.
assert not (
self._use_delta_commands and type(command_output_limits) == str and command_output_limits == "default"
self._use_delta_commands and type(command_output_limits) is str and command_output_limits == "default"
), "Cannot use 'default' command output limits in delta commands mode of JointController. Try None instead."

# Run super init
Expand Down Expand Up @@ -210,7 +214,7 @@ def compute_control(self, goal_dict, control_dict):
if self._motor_type == "position":
# Run impedance controller -- effort = pos_err * kp + vel_err * kd
position_error = target - base_value
vel_pos_error = -control_dict[f"joint_velocity"][self.dof_idx]
vel_pos_error = -control_dict["joint_velocity"][self.dof_idx]
u = position_error * self.pos_kp + vel_pos_error * self.pos_kd
elif self._motor_type == "velocity":
# Compute command torques via PI velocity controller plus gravity compensation torques
Expand Down Expand Up @@ -252,10 +256,10 @@ def _compute_no_op_action(self, control_dict):
if self._use_delta_commands:
return cb.zeros(self.command_dim)
else:
return control_dict[f"joint_position"][self.dof_idx]
return control_dict["joint_position"][self.dof_idx]
elif self.motor_type == "velocity":
if self._use_delta_commands:
return -control_dict[f"joint_velocity"][self.dof_idx]
return -control_dict["joint_velocity"][self.dof_idx]
else:
return cb.zeros(self.command_dim)

Expand Down Expand Up @@ -293,9 +297,6 @@ def command_dim(self):
return len(self.dof_idx)


import torch as th


@th.compile
def _compute_joint_torques_torch(
u: th.Tensor,
Expand All @@ -306,10 +307,6 @@ def _compute_joint_torques_torch(
return mm[dof_idxs_mat] @ u


import numpy as np
from numba import jit


# Use numba since faster
@jit(nopython=True)
def numba_ix(arr, rows, cols):
Expand Down
2 changes: 1 addition & 1 deletion omnigibson/controllers/multi_finger_gripper_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def _compute_no_op_action(self, control_dict):
return cb.array([command_val])

if self._motor_type == "position":
command = control_dict[f"joint_position"][self.dof_idx]
command = control_dict["joint_position"][self.dof_idx]
elif self._motor_type == "velocity":
command = cb.zeros(self.command_dim)
else:
Expand Down
Loading

0 comments on commit 260704c

Please sign in to comment.