-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.py
142 lines (110 loc) · 3.85 KB
/
helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from enum import Enum
from typing import List, Tuple
import gymnasium
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
ALPHA_VALUE = 0.7
TEXT_FONT_SIZE = 10
def create_environment(env_name: str):
"""Create a Gymnasium environment.
Args:
env_name (str): Name of the environment
Returns:
gymnasium.Env: Gymnasium environment
"""
env = gymnasium.make(
env_name,
is_slippery=False,
render_mode="rgb_array",
)
return env
def generate_interpolation_factors(
img: np.ndarray, matrix: np.ndarray
) -> Tuple[int, int]:
"""
Generates the interpolation factors for a given matrix.
"""
return img.shape[0] // matrix.shape[0], img.shape[1] // matrix.shape[1]
def generate_checkerboard(
img: np.ndarray, v: np.ndarray
) -> Tuple[np.ndarray, Tuple[int, int]]:
"""
Generates a checkerboard pattern by mapping matrix V onto image img.
"""
interpolation_factor_x, interpolation_factor_y = generate_interpolation_factors(
img, v
)
# Broadcasting the smaller matrix V to the size of img
checkerboard = np.repeat(
np.repeat(v, interpolation_factor_y, axis=0), interpolation_factor_x, axis=1
)
return checkerboard, (interpolation_factor_x, interpolation_factor_y)
def generate_colormap():
"""
Generates a default colormap.
"""
return LinearSegmentedColormap.from_list(
"custom_cmap", [(0, "red"), (0.5, "white"), (1, "green")]
)
def add_labels(
ax, shape: Tuple[int, int], labels: List, interpolation_factors: Tuple[int, int]
):
"""
Adds labels to the cells of the visualization.
Parameters:
ax (matplotlib.axes.Axes): The axes on which to add labels.
shape (tuple): The shape of the grid.
labels (list): The labels to add.
interpolation_factors (tuple): The interpolation factors for positioning labels.
"""
for i in range(shape[0]):
for j in range(shape[1]):
ax.text(
interpolation_factors[0] * (j + 0.5),
interpolation_factors[1] * (i + 0.5),
labels[i, j],
ha="center",
va="center",
fontsize=TEXT_FONT_SIZE,
fontweight="bold",
alpha=ALPHA_VALUE,
)
def visualize_v(env, v: np.ndarray, ax, title: str) -> None:
"""Visualizes the value function v of the given environment."""
v = v.reshape(env.unwrapped.desc.shape)
v_img, interp_factors = generate_checkerboard(env.render(), v)
v_img = ax.imshow(v_img, cmap=generate_colormap(), alpha=0.5)
labels = np.vectorize(lambda x: f"{x:.2f}")(v)
add_labels(ax, env.unwrapped.desc.shape, labels, interp_factors)
visualize_env(env, ax, title)
def visualize_p(
env, v: np.ndarray, p: np.ndarray, action: Enum, ax, title: str
) -> None:
"""Visualizes the policy p and the of the given environment."""
if v is None:
interp_factors = generate_interpolation_factors(
env.render(), p.reshape(env.unwrapped.desc.shape)
)
else:
v = v.reshape(env.unwrapped.desc.shape)
v_img, interp_factors = generate_checkerboard(env.render(), v)
v_img = ax.imshow(v_img, cmap=generate_colormap(), alpha=0.5)
s = np.arange(env.unwrapped.observation_space.n)
labels = np.vectorize(lambda x: action(p[x]).name)(s).reshape(
env.unwrapped.desc.shape
)
add_labels(ax, env.unwrapped.desc.shape, labels, interp_factors)
visualize_env(env, ax, title)
def visualize_env(env, ax, title: str) -> None:
"""
Visualizes the FrozenLake environment.
"""
ax.imshow(env.render(), alpha=ALPHA_VALUE)
ax.axis("off")
ax.set_title(title)
class DPType(Enum):
"""
Enum for the different types of dynamic programming.
"""
VALUE_ITERATION = 0
POLICY_ITERATION = 1