test / plot_chunk_metrics.py
chenzeyang1's picture
Upload plot_chunk_metrics.py
2368727 verified
Raw
History Blame Contribute Delete
5.8 kB
"""Narrow portrait chart for a text-wrapped paper figure.
Usage: python plot_chunk_metrics.py [--output-dir output/chunk_metrics]
Dependencies: matplotlib, numpy.
Data are copied exactly from the user's chunk-size measurements.
The two linear y axes display delta_1 on the supplied 93--97 scale and
AbsRel on the supplied 6.5--8.5 scale. The bar display starts at 93;
the tick labels show this nonzero baseline explicitly. No normalization,
smoothing, interpolation, uncertainty bands, or axis breaks are applied.
"""
from pathlib import Path
import argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
CHUNK = np.array([5, 7, 9, 11, 13])
DELTA1 = np.array([93.83, 95.16, 96.0, 95.72, 94.5])
ABSREL = np.array([8.17, 7.6, 6.8, 7.33, 7.74])
SELECTED_CHUNK = 9
BLUE, GREEN, LINE = "#426B8D", "#58AA78", "#49414F"
GREEN_TEXT = "#34764C"
def serif_font(size, bold=False):
weight = "bold" if bold else "normal"
for family in ("Times New Roman", "Liberation Serif"):
try:
path = font_manager.findfont(
font_manager.FontProperties(family=family, weight=weight),
fallback_to_default=False)
return font_manager.FontProperties(fname=path, size=size)
except ValueError:
pass
root = Path("/opt/codex/runtimes/codex-primary-runtime/dependencies/native/libreoffice-headless/libreoffice/share/fonts/truetype")
bundled = root / ("LiberationSerif-Bold.ttf" if bold else "LiberationSerif-Regular.ttf")
if bundled.exists():
return font_manager.FontProperties(fname=str(bundled), size=size)
return font_manager.FontProperties(family="DejaVu Serif", weight=weight, size=size)
def draw(out):
out.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({
"font.family": "DejaVu Serif", "font.size": 10,
"mathtext.fontset": "stix", "pdf.fonttype": 42,
"ps.fonttype": 42, "svg.fonttype": "path", "hatch.linewidth": .55,
})
# The reference portrait is 330 by 519: aspect ratio about 0.636.
fig, left = plt.subplots(figsize=(3.45, 5.40))
fig.subplots_adjust(left=.175, right=.825, bottom=.12, top=.845)
right = left.twinx()
left.set_facecolor("#F5F7FA")
left.axvspan(SELECTED_CHUNK-.78, SELECTED_CHUNK+.78,
facecolor=GREEN, alpha=.14, edgecolor="none", zorder=0)
# Shared horizontal grid: left 93/94/95/96/97 aligns exactly with
# right 6.5/7.0/7.5/8.0/8.5 on the linear coordinate axes.
left.set(xlim=(4, 14), ylim=(93, 97))
right.set_ylim(6.5, 8.5)
left.set_yticks([93, 94, 95, 96, 97])
right.set_yticks([6.5, 7.0, 7.5, 8.0, 8.5])
right.set_yticklabels(["6.5", "7.0", "7.5", "8.0", "8.5"])
left.set_axisbelow(True)
left.yaxis.grid(True, color="#D8DDE4", lw=.65, ls=(0, (4, 3)))
for chunk, delta in zip(CHUNK, DELTA1):
chosen = chunk == SELECTED_CHUNK
color = GREEN if chosen else BLUE
left.bar(chunk, delta-93, bottom=93, width=1.05,
facecolor="white", edgecolor=color, lw=1.6,
hatch="///" if chosen else "...", zorder=3)
right.plot(CHUNK, ABSREL, color=LINE, lw=1.8, marker="o",
markersize=5.3, markerfacecolor="white",
markeredgecolor=LINE, markeredgewidth=1.4, zorder=5)
selected = int(np.flatnonzero(CHUNK == SELECTED_CHUNK)[0])
right.plot(CHUNK[selected], ABSREL[selected], ls="", marker="*",
markersize=14, markerfacecolor=GREEN,
markeredgecolor="white", markeredgewidth=1.0, zorder=7)
left.set_xticks(CHUNK)
left.tick_params(axis="x", length=3.2, width=.8, pad=6, labelsize=11)
left.tick_params(axis="y", colors=BLUE, length=3, width=.8, pad=4, labelsize=10)
right.tick_params(axis="y", colors=LINE, length=3, width=.8, pad=4, labelsize=10)
left.get_xticklabels()[selected].set_color(GREEN_TEXT)
left.get_xticklabels()[selected].set_weight("bold")
left.set_xlabel("Chunk Size", fontproperties=serif_font(14), labelpad=8)
left.set_ylabel(r"$\delta_1$ ↑", fontproperties=serif_font(15), color=BLUE, labelpad=7)
right.set_ylabel("AbsRel ↓", fontproperties=serif_font(14), color=LINE, labelpad=7)
for ax in (left, right):
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_linewidth(.9)
left.spines["left"].set_color(BLUE)
left.spines["left"].set_linewidth(1.0)
left.spines["right"].set_visible(False)
right.spines["left"].set_visible(False)
right.spines["right"].set_color(LINE)
right.spines["right"].set_linewidth(1.0)
legend_handles = [
Patch(facecolor="white", edgecolor=BLUE, hatch="...", lw=1.2, label=r"$\delta_1$ ↑"),
Line2D([], [], color=LINE, lw=1.8, marker="o", ms=4.8,
markerfacecolor="white", markeredgewidth=1.2, label="AbsRel ↓"),
]
fig.legend(handles=legend_handles, loc="upper center", bbox_to_anchor=(.5, .923),
ncol=2, frameon=False, columnspacing=1.25, handlelength=1.6,
handletextpad=.55, prop=serif_font(11))
fig.suptitle("Chunk Size Ablation", y=.983,
fontproperties=serif_font(16, bold=True), color="#202830")
for ext in ("pdf", "svg", "png"):
fig.savefig(out / f"chunk_size_metrics.{ext}", dpi=450, facecolor="white")
plt.close(fig)
print(f"Saved 3.45 x 5.40 inch figure to {out}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path,
default=Path(__file__).resolve().parent / "output" / "chunk_metrics")
draw(parser.parse_args().output_dir)