From bc3de2987da95cbfa8869be8f105d712a89bf868 Mon Sep 17 00:00:00 2001 From: Andrea Ostuni Date: Wed, 3 Jan 2024 13:27:03 +0100 Subject: [PATCH] formatting and sorting --- examples/panda_pick_and_place.py | 4 +- examples/python/launch_cartpole.py | 2 +- python/gym_gz/__init__.py | 2 +- python/gym_gz/base/task.py | 4 +- python/gym_gz/randomizers/abc.py | 4 +- .../randomizers/gazebo_env_randomizer.py | 8 +++- python/gym_gz/runtimes/gazebo_runtime.py | 37 +++++++++++----- python/gym_gz/runtimes/realtime_runtime.py | 43 +++++++++++++++---- .../tasks/cartpole_continuous_balancing.py | 4 +- .../tasks/cartpole_continuous_swingup.py | 2 +- .../tasks/cartpole_discrete_balancing.py | 2 +- .../tasks/pendulum_swingup.py | 2 +- scenario/bindings/__init__.py | 4 +- .../.python/test_pendulum_wrt_ground_truth.py | 12 +++--- tests/.python/test_runtimes.py | 8 ++-- tests/test_gym_gz/test_reproducibility.py | 2 +- tests/test_scenario/test_link_velocities.py | 1 - tests/test_scenario/test_model.py | 4 +- 18 files changed, 90 insertions(+), 55 deletions(-) diff --git a/examples/panda_pick_and_place.py b/examples/panda_pick_and_place.py index 5b6c3d30..b61458b3 100644 --- a/examples/panda_pick_and_place.py +++ b/examples/panda_pick_and_place.py @@ -246,9 +246,7 @@ def move_fingers( gazebo.run(paused=True) # Insert the Panda manipulator -panda = gym_gz_environments.models.panda.Panda( - world=world, position=[-0.1, 0, 1.0] -) +panda = gym_gz_environments.models.panda.Panda(world=world, position=[-0.1, 0, 1.0]) # Disable joint velocity limits _ = [j.to_gazebo().set_velocity_limit(1_000) for j in panda.joints()] diff --git a/examples/python/launch_cartpole.py b/examples/python/launch_cartpole.py index 27698157..e0f4ab74 100755 --- a/examples/python/launch_cartpole.py +++ b/examples/python/launch_cartpole.py @@ -20,8 +20,8 @@ def make_env_from_id(env_id: str, **kwargs) -> gym.Env: - import gymnasium as gym import gym_gz_environments + import gymnasium as gym return gym.make(env_id, **kwargs) diff --git a/python/gym_gz/__init__.py b/python/gym_gz/__init__.py index 8574e1da..f1098003 100644 --- a/python/gym_gz/__init__.py +++ b/python/gym_gz/__init__.py @@ -19,8 +19,8 @@ def initialize_verbosity() -> None: - import gymnasium as gym import gym_gz.utils.logger + import gymnasium as gym import scenario diff --git a/python/gym_gz/base/task.py b/python/gym_gz/base/task.py index 037d7cf6..244ef743 100644 --- a/python/gym_gz/base/task.py +++ b/python/gym_gz/base/task.py @@ -7,7 +7,6 @@ import gymnasium as gym import numpy as np -from gymnasium.utils import seeding from gym_gz.utils.typing import ( Action, ActionSpace, @@ -16,6 +15,7 @@ Reward, SeedList, ) +from gymnasium.utils import seeding from scenario import core @@ -208,7 +208,7 @@ def is_terminated(self) -> bool: Returns: True if the environment terminated, False otherwise. """ - + @abc.abstractmethod def is_truncated(self) -> bool: """ diff --git a/python/gym_gz/randomizers/abc.py b/python/gym_gz/randomizers/abc.py index 641c5a4a..c45ff00c 100644 --- a/python/gym_gz/randomizers/abc.py +++ b/python/gym_gz/randomizers/abc.py @@ -118,9 +118,7 @@ def randomize_model( class ModelDescriptionRandomizer(abc.ABC): @abc.abstractmethod - def randomize_model_description( - self, task: gym_gz.base.task.Task, **kwargs - ) -> str: + def randomize_model_description(self, task: gym_gz.base.task.Task, **kwargs) -> str: """ Randomize the model description. diff --git a/python/gym_gz/randomizers/gazebo_env_randomizer.py b/python/gym_gz/randomizers/gazebo_env_randomizer.py index c21ab29d..65221eb4 100644 --- a/python/gym_gz/randomizers/gazebo_env_randomizer.py +++ b/python/gym_gz/randomizers/gazebo_env_randomizer.py @@ -72,7 +72,9 @@ def __init__( # gym.Env methods # =============== - def reset(self, seed: int = None, options : Dict = {}, **kwargs) -> typing.ResetReturn: + def reset( + self, seed: int = None, options: Dict = {}, **kwargs + ) -> typing.ResetReturn: # Reset the physics if self._physics_randomizer.physics_expired() and seed is None: @@ -94,7 +96,9 @@ def reset(self, seed: int = None, options : Dict = {}, **kwargs) -> typing.Reset self._physics_randomizer.increase_rollout_counter() # Reset the task through the TaskRandomizer - self.randomize_task(task=self.env.unwrapped.task, gazebo=self.env.unwrapped.gazebo, **kwargs) + self.randomize_task( + task=self.env.unwrapped.task, gazebo=self.env.unwrapped.gazebo, **kwargs + ) ok_paused_run = self.env.unwrapped.gazebo.run(paused=True) diff --git a/python/gym_gz/runtimes/gazebo_runtime.py b/python/gym_gz/runtimes/gazebo_runtime.py index 2ef56500..d268f3cf 100644 --- a/python/gym_gz/runtimes/gazebo_runtime.py +++ b/python/gym_gz/runtimes/gazebo_runtime.py @@ -2,16 +2,25 @@ # This software may be modified and distributed under the terms of the # GNU Lesser General Public License v2.1 or any later version. -from typing import Optional, Dict +from typing import Dict, Optional +import gym_gz_models import gymnasium as gym import numpy as np - -import gym_gz_models from gym_gz import base from gym_gz.base import runtime from gym_gz.utils import logger -from gym_gz.utils.typing import Action, Info, Observation, Reward, SeedList, State, Terminated, Truncated, ResetReturn +from gym_gz.utils.typing import ( + Action, + Info, + Observation, + ResetReturn, + Reward, + SeedList, + State, + Terminated, + Truncated, +) from scenario import gazebo as scenario @@ -143,9 +152,17 @@ def step(self, action: Action) -> State: # Get info info = self.task.get_info() - return State((Observation(observation), Reward(reward), Terminated(terminated), Truncated(truncated), Info(info))) + return State( + ( + Observation(observation), + Reward(reward), + Terminated(terminated), + Truncated(truncated), + Info(info), + ) + ) - def reset(self, seed: int = None, options : Dict = {}, **kwargs) -> ResetReturn: + def reset(self, seed: int = None, options: Dict = {}, **kwargs) -> ResetReturn: self.seed(seed) @@ -170,8 +187,8 @@ def reset(self, seed: int = None, options : Dict = {}, **kwargs) -> ResetReturn: # Render the environment if self.render_mode == "human": self.render() - - return ResetReturn((Observation(observation), Info(info))) + + return ResetReturn((Observation(observation), Info(info))) def render(self, **kwargs) -> None: mode = self.render_mode @@ -282,9 +299,7 @@ def world(self) -> scenario.World: if self._world_sdf == "": # Insert the ground plane - ok_ground = world.insert_model( - gym_gz_models.get_model_file("ground_plane") - ) + ok_ground = world.insert_model(gym_gz_models.get_model_file("ground_plane")) if not ok_ground: raise RuntimeError("Failed to insert the ground plane") diff --git a/python/gym_gz/runtimes/realtime_runtime.py b/python/gym_gz/runtimes/realtime_runtime.py index 0e407ace..9168d1a4 100644 --- a/python/gym_gz/runtimes/realtime_runtime.py +++ b/python/gym_gz/runtimes/realtime_runtime.py @@ -2,10 +2,22 @@ # This software may be modified and distributed under the terms of the # GNU Lesser General Public License v2.1 or any later version. -from gym_gz.base import runtime, task -from gym_gz.utils.typing import Action, Done, Info, Observation, State, Terminated, Truncated, ResetReturn, Dict from typing import Optional +from gym_gz.base import runtime, task +from gym_gz.utils.typing import ( + Action, + Dict, + Done, + Info, + Observation, + ResetReturn, + State, + Terminated, + Truncated, +) + + class RealTimeRuntime(runtime.Runtime): """ Implementation of :py:class:`~gym_gz.base.runtime.Runtime` for real-time @@ -15,7 +27,14 @@ class RealTimeRuntime(runtime.Runtime): This class is not yet complete. """ - def __init__(self, task_cls: type, robot_cls: type, agent_rate: float, render_mode: Optional[str] = None, **kwargs): + def __init__( + self, + task_cls: type, + robot_cls: type, + agent_rate: float, + render_mode: Optional[str] = None, + **kwargs + ): # Build the environment task_object = task_cls(**kwargs) @@ -27,7 +46,7 @@ def __init__(self, task_cls: type, robot_cls: type, agent_rate: float, render_mo # Render mode self.render_mode = render_mode - + super().__init__(task=task_object, agent_rate=agent_rate) raise NotImplementedError @@ -72,17 +91,25 @@ def step(self, action: Action) -> State: # Check termination terminated = self.task.is_terminated() - #Check truncation + # Check truncation truncated = self.task.is_truncated() - return State((observation, reward, Terminated(terminated), Truncated(truncated), Info({}))) + return State( + ( + observation, + reward, + Terminated(terminated), + Truncated(truncated), + Info({}), + ) + ) - def reset(self, seed: int = None, options : Dict = {}, **kwargs) -> ResetReturn: + def reset(self, seed: int = None, options: Dict = {}, **kwargs) -> ResetReturn: # Get the observation observation = self.task.get_observation() - return ResetReturn((observation, Info({}))) + return ResetReturn((observation, Info({}))) def render(self, **kwargs) -> None: mode = self.render_mode diff --git a/python/gym_gz_environments/tasks/cartpole_continuous_balancing.py b/python/gym_gz_environments/tasks/cartpole_continuous_balancing.py index 8b64d6f4..d4ed9a5e 100644 --- a/python/gym_gz_environments/tasks/cartpole_continuous_balancing.py +++ b/python/gym_gz_environments/tasks/cartpole_continuous_balancing.py @@ -13,8 +13,8 @@ ActionSpace, Observation, ObservationSpace, - Reward, ResetReturn, + Reward, ) from scenario import core as scenario @@ -125,7 +125,7 @@ def is_terminated(self) -> bool: terminated = not self.reset_space.contains(observation) return terminated - + def is_truncated(self) -> bool: return False diff --git a/python/gym_gz_environments/tasks/cartpole_continuous_swingup.py b/python/gym_gz_environments/tasks/cartpole_continuous_swingup.py index 5f09e82e..da1c92cc 100644 --- a/python/gym_gz_environments/tasks/cartpole_continuous_swingup.py +++ b/python/gym_gz_environments/tasks/cartpole_continuous_swingup.py @@ -128,7 +128,7 @@ def is_terminated(self) -> bool: terminated = not self.reset_space.contains(observation) return terminated - + def is_truncated(self) -> bool: return False diff --git a/python/gym_gz_environments/tasks/cartpole_discrete_balancing.py b/python/gym_gz_environments/tasks/cartpole_discrete_balancing.py index 7039bb64..171201e3 100644 --- a/python/gym_gz_environments/tasks/cartpole_discrete_balancing.py +++ b/python/gym_gz_environments/tasks/cartpole_discrete_balancing.py @@ -124,7 +124,7 @@ def is_terminated(self) -> bool: terminated = not self.reset_space.contains(observation) return terminated - + def is_truncated(self) -> bool: return False diff --git a/python/gym_gz_environments/tasks/pendulum_swingup.py b/python/gym_gz_environments/tasks/pendulum_swingup.py index 8464da2b..0076ba0d 100644 --- a/python/gym_gz_environments/tasks/pendulum_swingup.py +++ b/python/gym_gz_environments/tasks/pendulum_swingup.py @@ -99,7 +99,7 @@ def is_terminated(self) -> bool: terminated = not self.observation_space.contains(observation) return terminated - + def is_truncated(self) -> bool: return False diff --git a/scenario/bindings/__init__.py b/scenario/bindings/__init__.py index a43f456b..273696f1 100644 --- a/scenario/bindings/__init__.py +++ b/scenario/bindings/__init__.py @@ -212,9 +212,7 @@ def import_gazebo() -> None: def create_home_dot_folder() -> None: # Make sure that the dot folder in the user's home exists - Path("~/.gz/gazebo").expanduser().mkdir( - mode=0o755, parents=True, exist_ok=True - ) + Path("~/.gz/gazebo").expanduser().mkdir(mode=0o755, parents=True, exist_ok=True) # =================== diff --git a/tests/.python/test_pendulum_wrt_ground_truth.py b/tests/.python/test_pendulum_wrt_ground_truth.py index 7116d58d..a4640c23 100644 --- a/tests/.python/test_pendulum_wrt_ground_truth.py +++ b/tests/.python/test_pendulum_wrt_ground_truth.py @@ -2,16 +2,17 @@ # This software may be modified and distributed under the terms of the # GNU Lesser General Public License v2.1 or any later version. +from typing import Dict, Optional + import gymnasium as gym import numpy as np import pytest -from gymnasium.envs import registry -from gymnasium.envs.registration import register from gym_gz.robots.sim import gazebo, pybullet from gym_gz.tasks.pendulum_swingup import PendulumSwingUp from gym_gz.utils import logger -from gym_gz.utils.typing import Observation, Reward, State -from typing import Dict, Optional +from gym_gz.utils.typing import Observation, Reward, State +from gymnasium.envs import registry +from gymnasium.envs.registration import register # Set verbosity logger.set_level(gym.logger.DEBUG) @@ -70,7 +71,7 @@ def step(self, action: np.ndarray) -> State: return State((Observation(observation), Reward(0.0), False, {})) - def reset(self, seed: int = None, options: Dict ={}, **kwargs): + def reset(self, seed: int = None, options: Dict = {}, **kwargs): # Use set_state_from_obs pass @@ -134,7 +135,6 @@ def template_pendulum_wrt_ground_truth(env_name: str, max_error_in_deg: float): # env.render('human') # time.sleep(5) - for epoch in range(10): # Reset the environment logger.info("Resetting the environment") diff --git a/tests/.python/test_runtimes.py b/tests/.python/test_runtimes.py index ecd87326..43716040 100644 --- a/tests/.python/test_runtimes.py +++ b/tests/.python/test_runtimes.py @@ -5,12 +5,12 @@ import gymnasium as gym import numpy as np import pytest -from gymnasium.envs import registry -from gymnasium.envs.registration import register from gym_gz.robots.sim import gazebo, pybullet from gym_gz.tasks.cartpole_discrete import CartPoleDiscrete from gym_gz.tasks.pendulum_swingup import PendulumSwingUp from gym_gz.utils import logger +from gymnasium.envs import registry +from gymnasium.envs.registration import register # Set verbosity logger.set_level(gym.logger.DEBUG) @@ -49,9 +49,7 @@ }, ) -if "CartPoleDiscrete-Gz-PyTest-v0" not in [ - spec.id for spec in list(registry.all()) -]: +if "CartPoleDiscrete-Gz-PyTest-v0" not in [spec.id for spec in list(registry.all())]: register( id="CartPoleDiscrete-Gz-PyTest-v0", entry_point="gym_gz.runtimes.gazebo_runtime:GazeboRuntime", diff --git a/tests/test_gym_gz/test_reproducibility.py b/tests/test_gym_gz/test_reproducibility.py index 9d220f2f..8a02db75 100644 --- a/tests/test_gym_gz/test_reproducibility.py +++ b/tests/test_gym_gz/test_reproducibility.py @@ -16,8 +16,8 @@ def make_env(**kwargs) -> gym.Env: - import gymnasium as gym import gym_gz_environments + import gymnasium as gym return gym.make("CartPoleDiscreteBalancing-Gazebo-v0", **kwargs) diff --git a/tests/test_scenario/test_link_velocities.py b/tests/test_scenario/test_link_velocities.py index f80fb4a9..04be8202 100644 --- a/tests/test_scenario/test_link_velocities.py +++ b/tests/test_scenario/test_link_velocities.py @@ -264,7 +264,6 @@ def test_linear_acceleration( if (np.absolute(np.array(world_linear_acceleration())) > 100.0).any(): continue - # Test the world acceleration (MIXED) assert world_linear_acceleration() == pytest.approx(world_acceleration, abs=0.5) diff --git a/tests/test_scenario/test_model.py b/tests/test_scenario/test_model.py index 93297af3..1a34d0d2 100644 --- a/tests/test_scenario/test_model.py +++ b/tests/test_scenario/test_model.py @@ -33,9 +33,7 @@ def get_model( model_urdf = gym_gz_models.get_model_file(gym_gz_models_name) - assert world.insert_model( - model_urdf, core.Pose_identity(), gym_gz_models_name - ) + assert world.insert_model(model_urdf, core.Pose_identity(), gym_gz_models_name) # Get the model and cast it to a Gazebo model model = world.get_model(gym_gz_models_name).to_gazebo()