Skip to content

Commit f515299

Browse files
authored
Change typing Optional to | to consistent with python 3.10 (#35)
1 parent bda69c3 commit f515299

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+500
-499
lines changed

embodichain/agents/rl/algo/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from __future__ import annotations
1818

19-
from typing import Dict, Any, Optional, Callable
19+
from typing import Dict, Any, Callable
2020
import torch
2121

2222

@@ -42,7 +42,7 @@ def collect_rollout(
4242
policy,
4343
obs: torch.Tensor,
4444
num_steps: int,
45-
on_step_callback: Optional[Callable] = None,
45+
on_step_callback: Callable | None = None,
4646
) -> Dict[str, Any]:
4747
"""Collect trajectories and return logging info (e.g., reward components)."""
4848
raise NotImplementedError

embodichain/agents/rl/algo/ppo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
# ----------------------------------------------------------------------------
1616

1717
import torch
18-
from typing import Dict, Any, Tuple, Callable, Optional
18+
from typing import Dict, Any, Tuple, Callable
1919

2020
from embodichain.agents.rl.utils import AlgorithmCfg
2121
from embodichain.agents.rl.buffer import RolloutBuffer
@@ -41,7 +41,7 @@ def __init__(self, cfg: PPOCfg, policy):
4141
self.policy = policy
4242
self.device = torch.device(cfg.device)
4343
self.optimizer = torch.optim.Adam(policy.parameters(), lr=cfg.learning_rate)
44-
self.buffer: Optional[RolloutBuffer] = None
44+
self.buffer: RolloutBuffer | None = None
4545
# no per-rollout aggregation for dense logging
4646

4747
def _compute_gae(
@@ -76,7 +76,7 @@ def collect_rollout(
7676
policy,
7777
obs: torch.Tensor,
7878
num_steps: int,
79-
on_step_callback: Optional[Callable] = None,
79+
on_step_callback: Callable | None = None,
8080
) -> Dict[str, Any]:
8181
"""Collect a rollout. Algorithm controls the data collection process."""
8282
if self.buffer is None:

embodichain/agents/rl/models/mlp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from __future__ import annotations
1818

1919
from functools import reduce
20-
from typing import Iterable, List, Optional, Sequence, Tuple, Union
20+
from typing import Iterable, List, Sequence, Tuple, Union
2121

2222
import torch
2323
import torch.nn as nn

embodichain/agents/rl/utils/trainer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from __future__ import annotations
1818

19-
from typing import Dict, Any, Tuple, Callable, Optional
19+
from typing import Dict, Any, Tuple, Callable
2020
import time
2121
import numpy as np
2222
import torch

embodichain/lab/gym/envs/action_bank/configurable_action.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import matplotlib.pyplot as plt
2222

2323
from copy import deepcopy
24-
from typing import Dict, Tuple, Union, List, Callable, Any, Optional
24+
from typing import Dict, Tuple, Union, List, Callable, Any
2525
from tqdm import tqdm
2626
from functools import partial
2727

embodichain/lab/gym/envs/action_bank/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import numpy as np
1717

1818
from copy import deepcopy
19-
from typing import List, Union, Optional
19+
from typing import List
2020

2121
from embodichain.utils import logger
2222
from embodichain.lab.gym.utils.misc import validation_with_process_from_name
@@ -33,7 +33,7 @@ def generate_affordance_from_src(
3333
env,
3434
src_key: str,
3535
dst_key: str,
36-
valid_funcs_name_kwargs_proc: Optional[List] = None,
36+
valid_funcs_name_kwargs_proc: list | None = None,
3737
to_array: bool = True,
3838
) -> bool:
3939
"""Generate a new affordance entry in env.affordance_datas by applying a validation and processing
@@ -43,7 +43,7 @@ def generate_affordance_from_src(
4343
env: The environment object containing affordance data.
4444
src_key (str): The key of the source affordance in env.affordance_datas.
4545
dst_key (str): The key to store the generated affordance in env.affordance_datas.
46-
valid_funcs_name_kwargs_proc (Optional[List]): A list of validation or processing functions (with kwargs)
46+
valid_funcs_name_kwargs_proc (list | None): A list of validation or processing functions (with kwargs)
4747
to apply to the source affordance. Defaults to an empty list.
4848
to_array (bool): Whether to convert the result to a numpy array before storing. Defaults to True.
4949

embodichain/lab/gym/envs/base_env.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import torch
1818
import gymnasium as gym
1919

20-
from typing import Dict, List, Union, Tuple, Any, Optional, Sequence
20+
from typing import Dict, List, Union, Tuple, Any, Sequence
2121
from functools import cached_property
2222

2323
from embodichain.lab.sim.types import EnvObs, EnvAction
@@ -41,7 +41,7 @@ class EnvCfg:
4141
sim_cfg: SimulationManagerCfg = SimulationManagerCfg()
4242
"""Simulation configuration for the environment."""
4343

44-
seed: Optional[int] = None
44+
seed: int | None = None
4545
"""The seed for the random number generator. Defaults to -1, in which case the seed is not set.
4646
4747
Note:
@@ -272,7 +272,7 @@ def _update_sim_state(self, **kwargs):
272272
# TODO: Add randomization event here.
273273
pass
274274

275-
def _initialize_episode(self, env_ids: Optional[Sequence[int]] = None, **kwargs):
275+
def _initialize_episode(self, env_ids: Sequence[int] | None = None, **kwargs):
276276
"""Initialize the simulation assets before each episode. Randomization can be performed at this stage.
277277
278278
Args:
@@ -427,7 +427,7 @@ def _step_action(self, action: EnvAction) -> EnvAction:
427427
pass
428428

429429
def reset(
430-
self, seed: Optional[int] = None, options: Optional[Dict] = None
430+
self, seed: int | None = None, options: dict | None = None
431431
) -> Tuple[EnvObs, Dict]:
432432
"""Reset the SimulationManager environment and return the observation and info.
433433

embodichain/lab/gym/envs/embodied_env.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import gymnasium as gym
2121

2222
from dataclasses import MISSING
23-
from typing import Dict, Union, Optional, Sequence, Tuple, Any, List
23+
from typing import Dict, Union, Sequence, Tuple, Any, List
2424

2525
from embodichain.lab.sim.cfg import (
2626
RobotCfg,
@@ -253,7 +253,7 @@ def get_affordance(self, key: str, default: Any = None):
253253
return self.affordance_datas.get(key, default)
254254

255255
def reset(
256-
self, seed: Optional[int] = None, options: Optional[Dict] = None
256+
self, seed: int | None = None, options: dict | None = None
257257
) -> Tuple[EnvObs, Dict]:
258258
obs, info = super().reset(seed=seed, options=options)
259259

@@ -297,7 +297,7 @@ def _update_sim_state(self, **kwargs) -> None:
297297
self.event_manager.apply(mode="interval")
298298

299299
def _initialize_episode(
300-
self, env_ids: Optional[Sequence[int]] = None, **kwargs
300+
self, env_ids: Sequence[int] | None = None, **kwargs
301301
) -> None:
302302
# apply events such as randomization for environments that need a reset
303303
if self.cfg.events:
@@ -439,28 +439,28 @@ def preview_sensor_data(
439439
plt.imshow(view)
440440
plt.savefig(f"sensor_data_{data_type}.png")
441441

442-
def create_demo_action_list(self, *args, **kwargs) -> Optional[Sequence[EnvAction]]:
442+
def create_demo_action_list(self, *args, **kwargs) -> Sequence[EnvAction] | None:
443443
"""Create a demonstration action list for the environment.
444444
445445
This function should be implemented in subclasses to generate a sequence of actions
446446
that demonstrate a specific task or behavior within the environment.
447447
448448
Returns:
449-
Optional[Sequence[EnvAction]]: A list of actions if a demonstration is available, otherwise None.
449+
Sequence[EnvAction] | None: A list of actions if a demonstration is available, otherwise None.
450450
"""
451451
raise NotImplementedError(
452452
"The method 'create_demo_action_list' must be implemented in subclasses."
453453
)
454454

455-
def to_dataset(self, id: str, save_path: str = None) -> Optional[str]:
455+
def to_dataset(self, id: str, save_path: str = None) -> str | None:
456456
"""Convert the recorded episode data to a dataset format.
457457
458458
Args:
459459
id (str): Unique identifier for the dataset.
460460
save_path (str, optional): Path to save the dataset. If None, use config or default.
461461
462462
Returns:
463-
Optional[str]: The path to the saved dataset, or None if failed.
463+
str | None: The path to the saved dataset, or None if failed.
464464
"""
465465
raise NotImplementedError(
466466
"The method 'to_dataset' will be implemented in the near future."

embodichain/lab/gym/envs/managers/observations.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import torch
2020
import os
2121
import random
22-
from typing import TYPE_CHECKING, Literal, Union, Optional, List, Dict, Sequence
22+
from typing import TYPE_CHECKING, Literal, Union, List, Dict, Sequence
2323

2424
from embodichain.lab.sim.objects import RigidObject, Articulation, Robot
2525
from embodichain.lab.sim.sensors import Camera, StereoCamera
@@ -388,7 +388,7 @@ def _project_3d_to_2d(
388388
return points_2d
389389

390390
def _get_gripper_ratio(
391-
self, control_part: str, gripper_qpos: Optional[torch.Tensor] = None
391+
self, control_part: str, gripper_qpos: torch.Tensor | None = None
392392
):
393393
robot: Robot = self._env.robot
394394
gripper_max_limit = robot.body_data.qpos_limits[
@@ -402,11 +402,11 @@ def _get_gripper_ratio(
402402

403403
def _get_robot_exteroception(
404404
self,
405-
control_part: Optional[str] = None,
405+
control_part: str | None = None,
406406
x_interval: float = 0.02,
407407
y_interval: float = 0.02,
408408
kpnts_number: int = 12,
409-
offset: Optional[Union[List, torch.Tensor]] = None,
409+
offset: list | torch.Tensor | None = None,
410410
follow_eef: bool = False,
411411
) -> torch.Tensor:
412412
"""Get the robot exteroception poses.
@@ -468,7 +468,7 @@ def _get_object_exteroception(
468468
y_interval: float = 0.02,
469469
kpnts_number: int = 12,
470470
is_arena_coord: bool = False,
471-
follow_eef: Optional[str] = None,
471+
follow_eef: str | None = None,
472472
) -> torch.Tensor:
473473
"""Get the rigid object exteroception poses.
474474

embodichain/lab/gym/envs/managers/randomization/rendering.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import torch
2020
import os
2121
import random
22-
from typing import TYPE_CHECKING, Literal, Union, Optional, Dict
22+
from typing import TYPE_CHECKING, Literal, Union, Dict
2323

2424
from embodichain.lab.sim.objects import Light, RigidObject, Articulation
2525
from embodichain.lab.sim.sensors import Camera, StereoCamera
@@ -55,11 +55,11 @@ def randomize_camera_extrinsics(
5555
env: EmbodiedEnv,
5656
env_ids: Union[torch.Tensor, None],
5757
entity_cfg: SceneEntityCfg,
58-
pos_range: Optional[tuple[list[float], list[float]]] = None,
59-
euler_range: Optional[tuple[list[float], list[float]]] = None,
60-
eye_range: Optional[tuple[list[float], list[float]]] = None,
61-
target_range: Optional[tuple[list[float], list[float]]] = None,
62-
up_range: Optional[tuple[list[float], list[float]]] = None,
58+
pos_range: tuple[list[float], list[float]] | None = None,
59+
euler_range: tuple[list[float], list[float]] | None = None,
60+
eye_range: tuple[list[float], list[float]] | None = None,
61+
target_range: tuple[list[float], list[float]] | None = None,
62+
up_range: tuple[list[float], list[float]] | None = None,
6363
) -> None:
6464
"""
6565
Randomize camera extrinsic properties (position and orientation).
@@ -177,9 +177,9 @@ def randomize_light(
177177
env: EmbodiedEnv,
178178
env_ids: Union[torch.Tensor, None],
179179
entity_cfg: SceneEntityCfg,
180-
position_range: Optional[tuple[list[float], list[float]]] = None,
181-
color_range: Optional[tuple[list[float], list[float]]] = None,
182-
intensity_range: Optional[tuple[float, float]] = None,
180+
position_range: tuple[list[float], list[float]] | None = None,
181+
color_range: tuple[list[float], list[float]] | None = None,
182+
intensity_range: tuple[float, float] | None = None,
183183
) -> None:
184184
"""Randomize light properties by adding, scaling, or setting random values.
185185
@@ -205,9 +205,9 @@ def randomize_light(
205205
env (EmbodiedEnv): The environment instance.
206206
env_ids (Union[torch.Tensor, None]): The environment IDs to apply the randomization.
207207
entity_cfg (SceneEntityCfg): The configuration of the scene entity to randomize.
208-
position_range (Optional[tuple[list[float], list[float]]]): The range for the position randomization.
209-
color_range (Optional[tuple[list[float], list[float]]]): The range for the color randomization.
210-
intensity_range (Optional[tuple[float, float]]): The range for the intensity randomization.
208+
position_range (tuple[list[float], list[float]] | None): The range for the position randomization.
209+
color_range (tuple[list[float], list[float]] | None): The range for the color randomization.
210+
intensity_range (tuple[float, float] | None): The range for the intensity randomization.
211211
"""
212212

213213
light: Light = env.sim.get_light(entity_cfg.uid)
@@ -259,10 +259,10 @@ def randomize_camera_intrinsics(
259259
env: EmbodiedEnv,
260260
env_ids: Union[torch.Tensor, None],
261261
entity_cfg: SceneEntityCfg,
262-
focal_x_range: Optional[tuple[float, float]] = None,
263-
focal_y_range: Optional[tuple[float, float]] = None,
264-
cx_range: Optional[tuple[float, float]] = None,
265-
cy_range: Optional[tuple[float, float]] = None,
262+
focal_x_range: tuple[float, float] | None = None,
263+
focal_y_range: tuple[float, float] | None = None,
264+
cx_range: tuple[float, float] | None = None,
265+
cy_range: tuple[float, float] | None = None,
266266
) -> None:
267267
"""Randomize camera intrinsic properties by adding, scaling, or setting random values.
268268
@@ -289,10 +289,10 @@ def randomize_camera_intrinsics(
289289
env (EmbodiedEnv): The environment instance.
290290
env_ids (Union[torch.Tensor, None]): The environment IDs to apply the randomization.
291291
entity_cfg (SceneEntityCfg): The configuration of the scene entity to randomize.
292-
focal_x_range (Optional[tuple[float, float]]): The range for the focal length x randomization.
293-
focal_y_range (Optional[tuple[float, float]]): The range for the focal length y randomization.
294-
cx_range (Optional[tuple[float, float]]): The range for the principal point x randomization.
295-
cy_range (Optional[tuple[float, float]]): The range for the principal point y randomization.
292+
focal_x_range (tuple[float, float] | None): The range for the focal length x randomization.
293+
focal_y_range (tuple[float, float] | None): The range for the focal length y randomization.
294+
cx_range (tuple[float, float] | None): The range for the principal point x randomization.
295+
cy_range (tuple[float, float] | None): The range for the principal point y randomization.
296296
"""
297297

298298
camera: Union[Camera, StereoCamera] = env.sim.get_sensor(entity_cfg.uid)
@@ -500,11 +500,11 @@ def __call__(
500500
env_ids: Union[torch.Tensor, None],
501501
entity_cfg: SceneEntityCfg,
502502
random_texture_prob: float = 0.5,
503-
texture_path: Optional[str] = None,
504-
base_color_range: Optional[tuple[list[float], list[float]]] = None,
505-
metallic_range: Optional[tuple[float, float]] = None,
506-
roughness_range: Optional[tuple[float, float]] = None,
507-
ior_range: Optional[tuple[float, float]] = None,
503+
texture_path: str | None = None,
504+
base_color_range: tuple[list[float], list[float]] | None = None,
505+
metallic_range: tuple[float, float] | None = None,
506+
roughness_range: tuple[float, float] | None = None,
507+
ior_range: tuple[float, float] | None = None,
508508
):
509509
from embodichain.lab.sim.utility import is_rt_enabled
510510

0 commit comments

Comments
 (0)