-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_params.py
More file actions
155 lines (127 loc) · 4.91 KB
/
Copy pathplot_params.py
File metadata and controls
155 lines (127 loc) · 4.91 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
Plot the trajectories of an objective function in the parameter space.
Usage:
plot_params <objective>
Arguments:
<objective> The key of the objective function.
Options:
-h --help Show this screen.
"""
import json
import matplotlib.pyplot as plt
import numpy as np
from docopt import docopt
from trajectories.constants import (
AGGREGATOR_ORDER,
AGGREGATORS,
INITIAL_POINTS,
LATEX_NAMES,
OBJECTIVES,
)
from trajectories.objectives import ElementWiseQuadratic, WithSPSMappingMixin
from trajectories.optimization import compute_gradient_cosine_similarities
from trajectories.pareto_utils import sample_2d_spss
from trajectories.paths import RESULTS_DIR, get_param_plots_dir, get_params_dir
from trajectories.plotters import (
AxesPlotter,
ContentLimAdjuster,
ContourCirclesPlotter,
HeatmapPlotter,
LimAdjuster,
MultiTrajPlotter,
SPSPlotter,
SquareBoxAspectSetter,
TitleSetter,
XAxisLabeller,
XTicksClearer,
YAxisLabeller,
YTicksClearer,
)
from trajectories.plotting_utils import (
compute_subplot_layout,
get_subplot_position,
get_unused_subplot_positions,
map_orders_to_indices,
)
def main():
print("Plotting in parameter space...")
arguments = docopt(__doc__)
objective_key = arguments["<objective>"]
# Read metadata.json
with open(RESULTS_DIR / objective_key / "metadata.json", "r") as f:
metadata = json.load(f)
params_dir = get_params_dir(objective_key)
param_plots_dir = get_param_plots_dir(objective_key)
param_plots_dir.mkdir(parents=True, exist_ok=True)
# This seems to be the only way to make the font be Type1, which is the only font type supported
# by ICML.
plt.rcParams.update({"text.usetex": True})
objective_key = metadata["objective_key"]
objective = OBJECTIVES[objective_key]
if objective.n_params != 2:
raise ValueError("Can only plot param trajectories for objectives with 2 params.")
initial_points = INITIAL_POINTS[objective_key]
initial_points = np.stack([np.array(point) for point in initial_points])
main_content = initial_points # The content to which the axes must be adjusted
common_plotter = SquareBoxAspectSetter()
if objective.n_values == 2 and isinstance(objective, WithSPSMappingMixin):
sps_points = sample_2d_spss(objective).numpy()
main_content = np.concatenate([main_content, sps_points])
common_plotter += SPSPlotter(sps_points)
if isinstance(objective, ElementWiseQuadratic):
common_plotter += AxesPlotter()
common_plotter += ContourCirclesPlotter()
common_plotter += LimAdjuster(xlim=(-5.0, 5.0), ylim=(-5.0, 5.0))
else:
adjust_plotter = ContentLimAdjuster(main_content)
common_plotter += adjust_plotter
if objective.n_values == 2:
similarities = compute_gradient_cosine_similarities(
objective,
x0_min=adjust_plotter.xlim[0],
x0_max=adjust_plotter.xlim[1],
x1_min=adjust_plotter.ylim[0],
x1_max=adjust_plotter.ylim[1],
n=200,
)
common_plotter += HeatmapPlotter(
values=similarities.numpy() ** 3,
x_min=adjust_plotter.xlim[0],
x_max=adjust_plotter.xlim[1],
y_min=adjust_plotter.ylim[0],
y_max=adjust_plotter.ylim[1],
vmin=-1,
vmax=1,
cmap="PiYG",
)
aggregator_keys = metadata["aggregator_keys"]
aggregator_to_X = {key: np.load(params_dir / f"{key}.npy") for key in aggregator_keys}
n_aggregators = len(aggregator_keys)
n_rows, n_cols = compute_subplot_layout(n_aggregators)
key_to_index = map_orders_to_indices(aggregator_keys, AGGREGATOR_ORDER)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 2, n_rows * 2.5))
# Ensure axes is always 2D
if n_rows == n_cols == 1:
axes = np.array([[axes]])
elif n_rows == 1:
axes = axes.reshape(1, -1)
# Hide unused subplots
unused_positions = get_unused_subplot_positions(n_aggregators, n_rows, n_cols)
for i, j in unused_positions:
axes[i][j].axis("off")
save_path = param_plots_dir / "all.pdf"
for aggregator_key, X in aggregator_to_X.items():
aggregator = AGGREGATORS[aggregator_key]
print(aggregator)
index = key_to_index[aggregator_key]
i, j = get_subplot_position(index, n_aggregators, n_rows, n_cols)
plotter = common_plotter + MultiTrajPlotter(X) + TitleSetter(LATEX_NAMES[aggregator_key])
plotter += XAxisLabeller("$x_1$") if i == n_rows - 1 else XTicksClearer()
plotter += YAxisLabeller("$x_2$") if j == 0 else YTicksClearer()
plotter(axes[i][j])
fig.tight_layout(h_pad=-2.5)
print("Saving figure")
plt.savefig(save_path, bbox_inches="tight")
print()
if __name__ == "__main__":
main()