Skip to content

Commit

Permalink
✨ 🐛 Switch to 3.10+ typing style
Browse files Browse the repository at this point in the history
⬆️ Bump up_aries dependency for hierarchical numerical
  • Loading branch information
MathisFederico committed Feb 26, 2024
1 parent 8b0b826 commit 450f148
Show file tree
Hide file tree
Showing 45 changed files with 379 additions and 385 deletions.
1 change: 1 addition & 0 deletions .github/workflows/python-coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ jobs:
git submodule update --init --recursive
python -m pip install --upgrade pip
pip install -e .[all,dev]
pip install --force https://github.com/plaans/aries/releases/download/latest/up_aries.tar.gz
- name: Setup java for ENHSP
uses: actions/setup-java@v2
with:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/python-tests-all-optdeps.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
git submodule update --init --recursive
python -m pip install --upgrade pip
pip install .[all,dev]
pip install --force https://github.com/plaans/aries/releases/download/latest/up_aries.tar.gz
- name: Setup java for ENHSP
uses: actions/setup-java@v2
with:
Expand Down
2 changes: 2 additions & 0 deletions src/hcraft/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
"""

from __future__ import annotations

import hcraft.state as state
import hcraft.solving_behaviors as solving_behaviors
import hcraft.purpose as purpose
Expand Down
32 changes: 16 additions & 16 deletions src/hcraft/behaviors/behaviors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
""" Module for handcrafted Behavior with HEBGraph in any HierarchyCraft environment. """

from typing import TYPE_CHECKING, Dict, List, Optional, Union
from typing import TYPE_CHECKING

import numpy as np
from hebg import Behavior, HEBGraph
Expand Down Expand Up @@ -29,7 +29,7 @@ def __init__(
self,
item: Item,
env: "HcraftEnv",
all_behaviors: Dict[str, Behavior],
all_behaviors: dict[str, Behavior],
):
super().__init__(name=self.get_name(item))
self.env = env
Expand Down Expand Up @@ -66,7 +66,7 @@ def __init__(
self,
item: Item,
env: "HcraftEnv",
all_behaviors: Dict[str, Behavior],
all_behaviors: dict[str, Behavior],
):
super().__init__(name=self.get_name(item))
self.env = env
Expand Down Expand Up @@ -107,8 +107,8 @@ def __init__(
self,
item: Item,
env: "HcraftEnv",
all_behaviors: Dict[str, Behavior],
zone: Optional[Zone] = None,
all_behaviors: dict[str, Behavior],
zone: Zone | None = None,
):
self.item = item
self.zone = zone
Expand All @@ -117,7 +117,7 @@ def __init__(
self.all_behaviors = all_behaviors

@staticmethod
def get_name(item: Item, zone: Optional[Zone] = None) -> str:
def get_name(item: Item, zone: Zone | None = None) -> str:
"""Get the name of the behavior to reach a zone."""
return f"Place {item.name}{_zones_str(zone)}"

Expand Down Expand Up @@ -163,11 +163,11 @@ def _zone_item_is_required(self, transformation: "Transformation") -> bool:

def _zone_item_is_in(
self,
zone_items: Optional[List[Stack]],
destination_items: Optional[List[Stack]],
zones_items: Optional[Dict[Zone, List[Stack]]],
zone: Optional[Zone],
destination: Optional[Zone],
zone_items: list[Stack] | None,
destination_items: list[Stack] | None,
zones_items: dict[Zone, list[Stack]] | None,
zone: Zone | None,
destination: Zone | None,
) -> bool:
zone_is_valid = self.zone is None or zone is None or zone == self.zone
if zone_is_valid and self._item_is_in_stack(zone_items):
Expand All @@ -183,7 +183,7 @@ def _zone_item_is_in(
return False

def _zone_item_in_dict_of_stacks(
self, dict_of_stack: Optional[Dict["Zone", List["Stack"]]]
self, dict_of_stack: dict["Zone", list["Stack"]] | None
) -> bool:
if dict_of_stack is None:
return False
Expand All @@ -194,7 +194,7 @@ def _zone_item_in_dict_of_stacks(
stacks.extend(zone_stacks)
return self._item_is_in_stack(stacks)

def _item_is_in_stack(self, stacks: Optional[List["Stack"]]) -> bool:
def _item_is_in_stack(self, stacks: list["Stack"] | None) -> bool:
return stacks is not None and self.item in [stack.item for stack in stacks]


Expand All @@ -206,7 +206,7 @@ def __init__(
self,
zone: Zone,
env: "HcraftEnv",
all_behaviors: Dict[str, Behavior],
all_behaviors: dict[str, Behavior],
):
super().__init__(name=self.get_name(zone))
self.env = env
Expand Down Expand Up @@ -239,7 +239,7 @@ def __init__(
self,
env: "HcraftEnv",
transformation: "Transformation",
all_behaviors: Dict[str, Behavior],
all_behaviors: dict[str, Behavior],
):
super().__init__(name=self.get_name(transformation))
self.env = env
Expand Down Expand Up @@ -339,7 +339,7 @@ def _add_place_item(
graph: HEBGraph,
env: "HcraftEnv",
stack: Stack,
zone: Optional[Zone] = None,
zone: Zone | None = None,
) -> HasZoneItem:
has_item_in_zone = HasZoneItem(env, stack, zone)
image = np.array(load_or_create_image(stack, env.world.resources_path))
Expand Down
6 changes: 3 additions & 3 deletions src/hcraft/behaviors/feature_conditions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
""" Module to define FeatureCondition nodes for the HEBGraph of the HierarchyCraft environment. """

from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING

import numpy as np
from hebg import FeatureCondition
Expand Down Expand Up @@ -86,7 +86,7 @@ class HasZoneItem(FeatureCondition):
"""FeatureCondition to check if a Zone has the given property."""

def __init__(
self, env: "HcraftEnv", stack: Stack, zone: Optional[Zone] = None
self, env: "HcraftEnv", stack: Stack, zone: Zone | None = None
) -> None:
image = np.array(load_or_create_image(stack, env.world.resources_path))
super().__init__(name=self.get_name(stack, zone), image=image, complexity=1)
Expand All @@ -101,7 +101,7 @@ def __init__(
self.state = env.state

@staticmethod
def get_name(stack: Stack, zone: Optional[Zone] = None) -> str:
def get_name(stack: Stack, zone: Zone | None = None) -> str:
"""Name of the HasZoneItem feature condition given stack and optional zone."""
zone_str = "Current zone" if zone is None else zone.name.capitalize()
quantity_str = _quantity_str(stack.quantity)
Expand Down
17 changes: 8 additions & 9 deletions src/hcraft/behaviors/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
""" Module for utility functions to apply on handcrafted Behavior. """

from typing import Dict, Set, Union

from hebg import Behavior, HEBGraph

Expand All @@ -15,15 +14,15 @@

def get_items_in_graph(
graph: HEBGraph,
all_behaviors: Dict[str, Union[GetItem, ReachZone]] = None,
) -> Set[Item]:
all_behaviors: dict[str, GetItem | ReachZone] = None,
) -> set[Item]:
"""Get items in a HierarchyCraft HEBGraph.
Args:
graph (HEBGraph): An of the HierarchyCraft environment.
Returns:
Set[Item]: Set of items that appears in the given graph.
set[Item]: Set of items that appears in the given graph.
"""
all_behaviors = all_behaviors if all_behaviors is not None else {}
items_in_graph = set()
Expand All @@ -42,16 +41,16 @@ def get_items_in_graph(

def get_zones_items_in_graph(
graph: HEBGraph,
all_behaviors: Dict[str, Union[GetItem, ReachZone]] = None,
) -> Set[Item]:
all_behaviors: dict[str, GetItem | ReachZone] = None,
) -> set[Item]:
"""Get properties in a HierarchyCraft HEBGraph.
Args:
graph (HEBGraph): An HEBehavior graph of the HierarchyCraft environment.
all_behaviors (Dict[str, Union[GetItem, ReachZone]): References to all known behaviors.
graph: An HEBehavior graph of the HierarchyCraft environment.
all_behaviors: References to all known behaviors.
Returns:
Set[Item]: Set of zone items that appears in the given graph.
set[Item]: Set of zone items that appears in the given graph.
"""
all_behaviors = all_behaviors if all_behaviors is not None else {}
zone_items_in_graph = set()
Expand Down
5 changes: 2 additions & 3 deletions src/hcraft/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from argparse import ArgumentParser, Namespace, _SubParsersAction
from typing import List, Optional

from hcraft.elements import Item
from hcraft.env import HcraftEnv
Expand All @@ -19,7 +18,7 @@
from hcraft.task import GetItemTask


def hcraft_cli(args: Optional[List[str]] = None) -> HcraftEnv:
def hcraft_cli(args: list[str] | None = None) -> HcraftEnv:
"""Parse arguments to build a hcraft environment.
Args:
Expand Down Expand Up @@ -289,7 +288,7 @@ def _random_sub_parser(subparsers: "_SubParsersAction[ArgumentParser]") -> None:

def _randomhcraft_from_cli(args: Namespace) -> RandomHcraftEnv:
window = _window_from_cli(args)
n_items_per_n_inputs: Optional[dict] = {
n_items_per_n_inputs: dict | None = {
n_inputs: getattr(args, f"n_items_{n_inputs}") for n_inputs in range(5)
}
if n_items_per_n_inputs is not None and sum(n_items_per_n_inputs.values()) == 1:
Expand Down
32 changes: 16 additions & 16 deletions src/hcraft/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@
"""

import collections
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Union

import numpy as np

Expand Down Expand Up @@ -303,11 +303,11 @@ class HcraftEnv(Env):
def __init__(
self,
world: "World",
purpose: Optional[Union[Purpose, List["Task"], "Task"]] = None,
purpose: Union[Purpose, list["Task"], "Task"] | None = None,
invalid_reward: float = -1.0,
render_window: Optional[HcraftWindow] = None,
render_window: HcraftWindow | None = None,
name: str = "HierarchyCraft",
max_step: Optional[int] = None,
max_step: int | None = None,
) -> None:
"""
Args:
Expand All @@ -318,14 +318,14 @@ def __init__(
Defaults to -1.0.
render_window: Window using to render the environment with pygame.
name: Name of the environement. Defaults to 'HierarchyCraft'.
max_step: (Optional[int], optional): Maximum number of steps before episode truncation.
max_step: (int | None, optional): Maximum number of steps before episode truncation.
If None, never truncates the episode. Defaults to None.
"""
self.world = world
self.invalid_reward = invalid_reward
self.max_step = max_step
self.name = name
self._all_behaviors: Optional[Dict[str, Behavior]] = None
self._all_behaviors: dict[str, Behavior] | None = None

self.render_window = render_window
self.render_mode = "rgb_array"
Expand All @@ -335,8 +335,8 @@ def __init__(
self.current_score = 0.0
self.cumulated_score = 0.0
self.episodes = 0
self.task_successes: Optional[SuccessCounter] = None
self.terminal_successes: Optional[SuccessCounter] = None
self.task_successes: SuccessCounter | None = None
self.terminal_successes: SuccessCounter | None = None

if purpose is None:
purpose = Purpose(None)
Expand All @@ -358,7 +358,7 @@ def terminated(self) -> bool:
return self.purpose.is_terminal(self.state)

@property
def observation_space(self) -> Union[BoxSpace, TupleSpace]: # type: ignore [override]
def observation_space(self) -> BoxSpace | TupleSpace: # type: ignore [override]
"""Observation space for the Agent."""
obs_space = BoxSpace(
low=np.array(
Expand Down Expand Up @@ -387,7 +387,7 @@ def action_masks(self) -> np.ndarray:
"""Return boolean mask of valid actions."""
return np.array([t.is_valid(self.state) for t in self.world.transformations])

def step(self, action: int) -> Tuple[Any, float, bool, dict]: # type: ignore [override]
def step(self, action: int) -> tuple[Any, float, bool, dict]: # type: ignore [override]
"""Perform one step in the environment given the index of a wanted transformation.
If the selected transformation can be performed, the state is updated and
Expand Down Expand Up @@ -428,8 +428,8 @@ def step(self, action: int) -> Tuple[Any, float, bool, dict]: # type: ignore [o
return self._step_output(reward, terminated, truncated)

def render( # type: ignore [override]
self, mode: Optional[str] = None, **_kwargs: dict
) -> Union[str, np.ndarray]:
self, mode: str | None = None, **_kwargs: dict
) -> str | np.ndarray:
"""Render the observation of the agent in a format depending on `render_mode`."""
if mode is not None:
self.render_mode = mode
Expand All @@ -443,8 +443,8 @@ def render( # type: ignore [override]
def reset( # type: ignore [override]
self,
*,
seed: Optional[int] = None,
options: Optional[dict] = None,
seed: int | None = None,
options: dict | None = None,
) -> np.ndarray:
"""Resets the state of the environement.
Expand Down Expand Up @@ -478,7 +478,7 @@ def close(self):
self.render_window.close()

@property
def all_behaviors(self) -> Dict[str, "Behavior"]:
def all_behaviors(self) -> dict[str, "Behavior"]:
"""All solving behaviors using hebg."""
if self._all_behaviors is None:
self._all_behaviors = build_all_solving_behaviors(self)
Expand Down Expand Up @@ -550,7 +550,7 @@ def planning_problem(

def _step_output(
self, reward: float, terminated: bool, truncated: bool
) -> Tuple[Any, float, bool, dict]:
) -> tuple[Any, float, bool, dict]:
infos = {
"action_is_legal": self.action_masks(),
"score": self.current_score,
Expand Down
6 changes: 3 additions & 3 deletions src/hcraft/examples/light_recursive.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from hcraft.world import world_from_transformations


from typing import Any, List, Union
from typing import Any


# gym is an optional dependency
Expand Down Expand Up @@ -58,7 +58,7 @@ def __init__(self, n_items: int = 6, n_required_previous: int = 2, **kwargs: Any
kwargs["purpose"] = GetItemTask(items[-1])
super().__init__(world, name=env_name, **kwargs)

def _transformations(self, items: List[Item]) -> List[Transformation]:
def _transformations(self, items: list[Item]) -> list[Transformation]:
"""Build recipes to make every item accessible.
Args:
Expand All @@ -72,7 +72,7 @@ def _transformations(self, items: List[Item]) -> List[Transformation]:

for index, item in enumerate(items):
low_id = max(0, index - self.n_required_previous)
inventory_changes: List[Union[Use, Yield]] = [Yield(PLAYER, item)]
inventory_changes: list[Use | Yield] = [Yield(PLAYER, item)]
if index > 0:
inventory_changes += [
Use(PLAYER, items[item_id], consume=1)
Expand Down
3 changes: 1 addition & 2 deletions src/hcraft/examples/minecraft/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
.. include:: ../../../../docs/images/requirements_graphs/MineHcraft.html
</div>
"""
from typing import Optional
from hcraft.elements import Item

import hcraft.examples.minecraft.items as items
Expand Down Expand Up @@ -47,7 +46,7 @@ def _to_camel_case(name: str) -> str:

def _register_minehcraft_single_item(
item: Item,
name: Optional[str] = None,
name: str | None = None,
success_reward: float = 10.0,
timestep_reward: float = -0.1,
reward_shaping: RewardShaping = RewardShaping.REQUIREMENTS_ACHIVEMENTS,
Expand Down
Loading

0 comments on commit 450f148

Please sign in to comment.