瀏覽代碼

Merge pull request #203 from rodrigodelazcano/pyright

Add pyright to pre-commit
Mark Towers 2 年之前
父節點
當前提交
364eff2a06

+ 1 - 4
.github/workflows/pre-commit.yml

@@ -1,10 +1,7 @@
 # https://pre-commit.com
 # This GitHub Action assumes that the repo contains a valid .pre-commit-config.yaml file.
 name: pre-commit
-on:
-  pull_request:
-  push:
-    branches: [master]
+on: [pull_request, push]
 jobs:
   pre-commit:
     runs-on: ubuntu-latest

+ 11 - 11
.pre-commit-config.yaml

@@ -40,14 +40,14 @@ repos:
     hooks:
       - id: pyupgrade
         args: ["--py37-plus"]
-#  - repo: local
-#    hooks:
-#      - id: pyright
-#        name: pyright
-#        entry: pyright
-#        language: node
-#        pass_filenames: false
-#        types: [python]
-#        additional_dependencies: ["pyright"]
-#        args:
-#          - --project=pyproject.toml
+  - repo: local
+    hooks:
+      - id: pyright
+        name: pyright
+        entry: pyright
+        language: node
+        pass_filenames: false
+        types: [python]
+        additional_dependencies: ["pyright"]
+        args:
+          - --project=pyproject.toml

+ 3 - 1
gym_minigrid/envs/crossing.py

@@ -1,5 +1,7 @@
 import itertools as itt
 
+import numpy as np
+
 from gym_minigrid.minigrid import Goal, Grid, Lava, MiniGridEnv, Wall
 from gym_minigrid.register import register
 
@@ -30,7 +32,7 @@ class CrossingEnv(MiniGridEnv):
         self.grid.wall_rect(0, 0, width, height)
 
         # Place the agent in the top-left corner
-        self.agent_pos = (1, 1)
+        self.agent_pos = np.array((1, 1))
         self.agent_dir = 0
 
         # Place a goal square in the bottom-right corner

+ 6 - 0
gym_minigrid/envs/fetch.py

@@ -41,6 +41,12 @@ class FetchEnv(MiniGridEnv):
                 obj = Key(objColor)
             elif objType == "ball":
                 obj = Ball(objColor)
+            else:
+                raise ValueError(
+                    "{} object type given. Object type can only be of values key and ball.".format(
+                        objType
+                    )
+                )
 
             self.place_obj(obj)
             objs.append(obj)

+ 0 - 1
gym_minigrid/envs/fourrooms.py

@@ -65,7 +65,6 @@ class FourRoomsEnv(MiniGridEnv):
             self.place_obj(Goal())
 
         self.mission = "reach the goal"
-        self.mission = "Reach the goal"
 
     def step(self, action):
         obs, reward, done, info = MiniGridEnv.step(self, action)

+ 6 - 0
gym_minigrid/envs/gotoobject.py

@@ -46,6 +46,12 @@ class GoToObjectEnv(MiniGridEnv):
                 obj = Ball(objColor)
             elif objType == "box":
                 obj = Box(objColor)
+            else:
+                raise ValueError(
+                    "{} object type given. Object type can only be of values key, ball and box.".format(
+                        objType
+                    )
+                )
 
             pos = self.place_obj(obj)
             objs.append((objType, objColor))

+ 1 - 1
gym_minigrid/envs/lavagap.py

@@ -30,7 +30,7 @@ class LavaGapEnv(MiniGridEnv):
         self.grid.wall_rect(0, 0, width, height)
 
         # Place the agent in the top-left corner
-        self.agent_pos = (1, 1)
+        self.agent_pos = np.array((1, 1))
         self.agent_dir = 0
 
         # Place a goal square in the bottom-right corner

+ 3 - 1
gym_minigrid/envs/memory.py

@@ -1,3 +1,5 @@
+import numpy as np
+
 from gym_minigrid.minigrid import Ball, Grid, Key, MiniGridEnv, Wall
 from gym_minigrid.register import register
 
@@ -58,7 +60,7 @@ class MemoryEnv(MiniGridEnv):
             self.grid.set(hallway_end + 2, j, Wall())
 
         # Fix the player's start position and orientation
-        self.agent_pos = (self._rand_int(1, hallway_end + 1), height // 2)
+        self.agent_pos = np.array((self._rand_int(1, hallway_end + 1), height // 2))
         self.agent_dir = 0
 
         # Place objects

+ 1 - 1
gym_minigrid/envs/obstructedmaze.py

@@ -71,7 +71,7 @@ class ObstructedMazeEnv(RoomGrid):
         if locked:
             obj = Key(door.color)
             if key_in_box:
-                box = Box(self.box_color) if key_in_box else None
+                box = Box(self.box_color)
                 box.contains = obj
                 obj = box
             self.place_in_room(i, j, obj)

+ 6 - 0
gym_minigrid/envs/playground.py

@@ -62,6 +62,12 @@ class PlaygroundEnv(MiniGridEnv):
                 obj = Ball(objColor)
             elif objType == "box":
                 obj = Box(objColor)
+            else:
+                raise ValueError(
+                    "{} object type given. Object type can only be of values key, ball and box.".format(
+                        objType
+                    )
+                )
             self.place_obj(obj)
 
         # No explicit mission in this environment

+ 6 - 0
gym_minigrid/envs/putnear.py

@@ -57,6 +57,12 @@ class PutNearEnv(MiniGridEnv):
                 obj = Ball(objColor)
             elif objType == "box":
                 obj = Box(objColor)
+            else:
+                raise ValueError(
+                    "{} object type given. Object type can only be of values key, ball and box.".format(
+                        objType
+                    )
+                )
 
             pos = self.place_obj(obj, reject_fn=near_obj)
 

+ 29 - 25
gym_minigrid/minigrid.py

@@ -18,6 +18,7 @@ from gym_minigrid.rendering import (
     point_in_triangle,
     rotate_fn,
 )
+from gym_minigrid.window import Window
 
 TILE_PIXELS = 32
 
@@ -252,8 +253,15 @@ class Door(WorldObj):
             state = 0
         elif self.is_locked:
             state = 2
+        # if door is closed and unlocked
         elif not self.is_open:
             state = 1
+        else:
+            raise ValueError(
+                "There is no possible state encoding for the state:\n -Door Open: {}\n -Door Closed: {}\n -Door Locked: {}".format(
+                    self.is_open, not self.is_open, self.is_locked
+                )
+            )
 
         return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], state)
 
@@ -580,17 +588,17 @@ class Grid:
 
         return grid, vis_mask
 
-    def process_vis(grid, agent_pos):
-        mask = np.zeros(shape=(grid.width, grid.height), dtype=bool)
+    def process_vis(self, agent_pos):
+        mask = np.zeros(shape=(self.width, self.height), dtype=bool)
 
         mask[agent_pos[0], agent_pos[1]] = True
 
-        for j in reversed(range(0, grid.height)):
-            for i in range(0, grid.width - 1):
+        for j in reversed(range(0, self.height)):
+            for i in range(0, self.width - 1):
                 if not mask[i, j]:
                     continue
 
-                cell = grid.get(i, j)
+                cell = self.get(i, j)
                 if cell and not cell.see_behind():
                     continue
 
@@ -599,11 +607,11 @@ class Grid:
                     mask[i + 1, j - 1] = True
                     mask[i, j - 1] = True
 
-            for i in reversed(range(1, grid.width)):
+            for i in reversed(range(1, self.width)):
                 if not mask[i, j]:
                     continue
 
-                cell = grid.get(i, j)
+                cell = self.get(i, j)
                 if cell and not cell.see_behind():
                     continue
 
@@ -612,10 +620,10 @@ class Grid:
                     mask[i - 1, j - 1] = True
                     mask[i, j - 1] = True
 
-        for j in range(0, grid.height):
-            for i in range(0, grid.width):
+        for j in range(0, self.height):
+            for i in range(0, self.width):
                 if not mask[i, j]:
-                    grid.set(i, j, None)
+                    self.set(i, j, None)
 
         return mask
 
@@ -652,13 +660,13 @@ class MiniGridEnv(gym.Env):
 
     def __init__(
         self,
-        grid_size=None,
-        width=None,
-        height=None,
-        max_steps=100,
-        see_through_walls=False,
-        agent_view_size=7,
-        render_mode=None,
+        grid_size: int = None,
+        width: int = None,
+        height: int = None,
+        max_steps: int = 100,
+        see_through_walls: bool = False,
+        agent_view_size: int = 7,
+        render_mode: str = None,
         **kwargs
     ):
         # Can't set both grid_size and width/height
@@ -703,8 +711,7 @@ class MiniGridEnv(gym.Env):
         # Range of possible rewards
         self.reward_range = (0, 1)
 
-        # Window to use for human rendering mode
-        self.window = None
+        self.window: Window = None
 
         # Environment configuration
         self.width = width
@@ -713,8 +720,8 @@ class MiniGridEnv(gym.Env):
         self.see_through_walls = see_through_walls
 
         # Current position and direction of the agent
-        self.agent_pos = None
-        self.agent_dir = None
+        self.agent_pos: np.ndarray = None
+        self.agent_dir: int = None
 
         # Initialize the state
         self.reset()
@@ -1122,7 +1129,6 @@ class MiniGridEnv(gym.Env):
                 reward = self._reward()
             if fwd_cell is not None and fwd_cell.type == "lava":
                 done = True
-
         # Pick up an object
         elif action == self.actions.pickup:
             if fwd_cell and fwd_cell.can_pickup():
@@ -1245,9 +1251,7 @@ class MiniGridEnv(gym.Env):
             return
 
         if mode == "human" and not self.window:
-            import gym_minigrid.window
-
-            self.window = gym_minigrid.window.Window("gym_minigrid")
+            self.window = Window("gym_minigrid")
             self.window.show(block=False)
 
         # Compute which cells are visible to the agent

+ 11 - 5
gym_minigrid/roomgrid.py

@@ -1,3 +1,5 @@
+import numpy as np
+
 from gym_minigrid.minigrid import COLOR_NAMES, Ball, Box, Door, Grid, Key, MiniGridEnv
 
 
@@ -69,7 +71,7 @@ class RoomGrid(MiniGridEnv):
         num_cols=3,
         max_steps=100,
         agent_view_size=7,
-        **kwargs
+        **kwargs,
     ):
         assert room_size > 0
         assert room_size >= 3
@@ -91,7 +93,7 @@ class RoomGrid(MiniGridEnv):
             max_steps=max_steps,
             see_through_walls=False,
             agent_view_size=agent_view_size,
-            **kwargs
+            **kwargs,
         )
 
     def room_from_pos(self, x, y):
@@ -163,9 +165,11 @@ class RoomGrid(MiniGridEnv):
                     room.door_pos[3] = room.neighbors[3].door_pos[1]
 
         # The agent starts in the middle, facing right
-        self.agent_pos = (
-            (self.num_cols // 2) * (self.room_size - 1) + (self.room_size // 2),
-            (self.num_rows // 2) * (self.room_size - 1) + (self.room_size // 2),
+        self.agent_pos = np.array(
+            (
+                (self.num_cols // 2) * (self.room_size - 1) + (self.room_size // 2),
+                (self.num_rows // 2) * (self.room_size - 1) + (self.room_size // 2),
+            )
         )
         self.agent_dir = 0
 
@@ -203,6 +207,8 @@ class RoomGrid(MiniGridEnv):
             obj = Ball(color)
         elif kind == "box":
             obj = Box(color)
+        else:
+            raise f"{kind} object kind is not available in this environment."
 
         return self.place_in_room(i, j, obj)
 

+ 3 - 5
gym_minigrid/window.py

@@ -13,9 +13,7 @@ class Window:
     """
 
     def __init__(self, title):
-        self.fig = None
-
-        self.imshow_obj = None
+        self.no_image_shown = True
 
         # Create the figure and axes
         self.fig, self.ax = plt.subplots()
@@ -44,9 +42,9 @@ class Window:
 
         # If no image has been shown yet,
         # show the first image of the environment
-        if self.imshow_obj is None:
+        if self.no_image_shown:
             self.imshow_obj = self.ax.imshow(img, interpolation="bilinear")
-
+            self.no_image_shown = False
         # Update the image data
         self.imshow_obj.set_data(img)
 

+ 6 - 3
gym_minigrid/wrappers.py

@@ -387,8 +387,7 @@ class FlatObsWrapper(gym.ObservationWrapper):
             dtype="uint8",
         )
 
-        self.cachedStr = None
-        self.cachedArray = None
+        self.cachedStr: str = None
 
     def observation(self, obs):
         image = obs["image"]
@@ -410,6 +409,10 @@ class FlatObsWrapper(gym.ObservationWrapper):
                     chNo = ord(ch) - ord("a")
                 elif ch == " ":
                     chNo = ord("z") - ord("a") + 1
+                else:
+                    raise ValueError(
+                        f"Character {ch} is not available in mission string."
+                    )
                 assert chNo < self.numCharCodes, "%s : %d" % (ch, chNo)
                 strArray[idx, chNo] = 1
 
@@ -464,7 +467,7 @@ class DirectionObsWrapper(gym.ObservationWrapper):
 
     def __init__(self, env, type="slope"):
         super().__init__(env)
-        self.goal_position = None
+        self.goal_position: tuple = None
         self.type = type
 
     def reset(self):

+ 35 - 0
pyproject.toml

@@ -0,0 +1,35 @@
+[tool.pyright]
+
+include = [
+    "gym_minigrid/**",
+]
+
+exclude = [
+    "**/node_modules",
+    "**/__pycache__",
+
+   #"gym_minigrid/**",
+]
+
+strict = [
+
+]
+
+typeCheckingMode = "basic"
+pythonVersion = "3.7"
+typeshedPath = "typeshed"
+enableTypeIgnoreComments = true
+
+# This is required as the CI pre-commit does not download the module (i.e. numpy)
+#   Therefore, we have to ignore missing imports
+reportMissingImports = "none"
+
+reportUnknownMemberType = "none"
+reportUnknownParameterType = "none"
+reportUnknownVariableType = "none"
+reportUnknownArgumentType = "none"
+reportPrivateUsage = "warning"
+reportUntypedFunctionDecorator = "none"
+reportMissingTypeStubs = false
+reportUnboundVariable = "warning"
+reportGeneralTypeIssues ="none"