-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench_matplotlib_xarray.py
More file actions
173 lines (140 loc) · 4.56 KB
/
Copy pathbench_matplotlib_xarray.py
File metadata and controls
173 lines (140 loc) · 4.56 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""
Benchmark PyGMT and matplotlib when plotting a Cartesian 2-D xarray DataArray.
"""
import statistics
import time
from pathlib import Path
import numpy as np
import pygmt
import xarray as xr
from pygmt.params import Axis, Frame, Position
import matplotlib.pyplot as plt # noqa: E402
OUTPUT_DIR = Path("plots/xarray")
REPEATS = 10
INCS = (0.05, 0.01, 0.005)
REGION = [-5, 5, -5, 5]
CMAP = "turbo"
def ackley(x, y):
"""Ackley function."""
return (
-20 * np.exp(-0.2 * np.sqrt(0.5 * (x**2 + y**2)))
- np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y)))
+ np.exp(1)
+ 20
)
def create_dataarray(inc: float) -> xr.DataArray:
"""Create a Cartesian 2-D DataArray using the Ackley function."""
x = np.arange(REGION[0], REGION[1] + inc, inc)
y = np.arange(REGION[2], REGION[3] + inc, inc)
xx, yy = np.meshgrid(x, y)
return xr.DataArray(
ackley(xx, yy),
coords={"y": y, "x": x},
dims=("y", "x"),
name="ackley",
)
def plot_matplotlib(data: xr.DataArray):
"""Create a Cartesian 2-D image plot with matplotlib."""
fig, ax = plt.subplots(figsize=(6, 6), dpi=300)
image = ax.imshow(
data.values,
origin="lower",
extent=[REGION[0], REGION[1], REGION[2], REGION[3]],
cmap=CMAP,
)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Ackley function")
return fig
def save_matplotlib(fig, output: Path) -> None:
"""Save a matplotlib figure and release it."""
fig.savefig(output)
plt.close(fig)
def plot_pygmt(data: xr.DataArray) -> pygmt.Figure:
"""Create a Cartesian 2-D image plot with PyGMT."""
fig = pygmt.Figure()
fig.grdimage(
grid=data,
region=REGION,
projection="X6i/6i",
cmap=CMAP,
frame=Frame(
axes="WSne",
title="Ackley function",
xaxis=Axis(annot=True, tick=True, label="x"),
yaxis=Axis(annot=True, tick=True, label="y"),
),
)
return fig
def save_pygmt(fig: pygmt.Figure, output: Path) -> None:
"""Save a PyGMT figure."""
fig.savefig(output)
def benchmark(
name: str,
plot_func,
save_func,
data: xr.DataArray,
output_dir: Path,
repeats: int,
) -> tuple[list[float], list[float]]:
"""Time repeated xarray plot creation and figure export runs."""
output_dir.mkdir(parents=True, exist_ok=True)
# Warm up each backend once before recording timings.
fig = plot_func(data)
save_func(fig, output_dir / f"{name}_warmup.png")
plot_timings = []
save_timings = []
for run_id in range(repeats):
output = output_dir / f"{name}_{run_id + 1}.pdf"
start = time.perf_counter()
fig = plot_func(data)
plot_timings.append(time.perf_counter() - start)
start = time.perf_counter()
save_func(fig, output)
save_timings.append(time.perf_counter() - start)
return plot_timings, save_timings
def format_summary(name: str, timings: list[float]) -> str:
"""Format benchmark timing statistics."""
mean = statistics.fmean(timings)
median = statistics.median(timings)
minimum = min(timings)
maximum = max(timings)
return (
f"{name:10s} "
f"mean={mean:.4f}s "
f"median={median:.4f}s "
f"min={minimum:.4f}s "
f"max={maximum:.4f}s"
)
def main() -> None:
"""Run the Cartesian xarray plotting benchmark."""
print(f"Running {REPEATS} timed run(s) per backend")
print(f"Writing PNG files to {OUTPUT_DIR}")
for inc in INCS:
data = create_dataarray(inc)
inc_label = f"inc_{inc:g}".replace(".", "p")
print(f"Grid increment: {inc:g}")
print("Benchmarking matplotlib...", flush=True)
plot_timings, save_timings = benchmark(
name=f"matplotlib_{inc_label}",
plot_func=plot_matplotlib,
save_func=save_matplotlib,
data=data,
output_dir=OUTPUT_DIR,
repeats=REPEATS,
)
print(format_summary("matplotlib plot", plot_timings))
print(format_summary("matplotlib savefig", save_timings))
print("Benchmarking pygmt...", flush=True)
plot_timings, save_timings = benchmark(
name=f"pygmt_{inc_label}",
plot_func=plot_pygmt,
save_func=save_pygmt,
data=data,
output_dir=OUTPUT_DIR,
repeats=REPEATS,
)
print(format_summary("pygmt plot", plot_timings))
print(format_summary("pygmt savefig", save_timings))
if __name__ == "__main__":
main()