codex/typesetting-glue-adjustment.py

typesetting-glue-adjustment.py
"""Draw original finite-glue examples; write the PNG into the current directory."""
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch, Rectangle


BOX_WIDTHS = (8, 6, 10)
NOMINAL_GAPS = (3, 3)
STRETCH = (1, 3)
SHRINK = (1, 1)


def adjust(target):
    natural = sum(BOX_WIDTHS) + sum(NOMINAL_GAPS)
    difference = target - natural
    coefficients = STRETCH if difference >= 0 else SHRINK
    ratio = difference / sum(coefficients)
    gaps = tuple(g + ratio * c for g, c in zip(NOMINAL_GAPS, coefficients))
    assert abs(sum(BOX_WIDTHS) + sum(gaps) - target) < 1e-10
    return ratio, gaps


def main():
    fig, ax = plt.subplots(figsize=(9, 4.8), dpi=100, facecolor="white")
    fig.subplots_adjust(left=0.075, right=0.94, bottom=0.21, top=0.72)
    fig.suptitle("Adjust the spaces, preserve the boxes", y=0.96,
                 fontsize=17, weight="bold", color="#172330")
    fig.text(0.5, 0.86,
             "Nominal gaps: (3, 3)    Stretch: (1, 3)    Shrink: (1, 1)",
             ha="center", fontsize=11, color="#45535d")
    colors = ("#347ea8", "#329185", "#8866a7")
    for y, target, label in [(2, 30, "Natural"), (1, 32, "Stretch"), (0, 28, "Shrink")]:
        ratio, gaps = adjust(target)
        x = 0
        for i, width in enumerate(BOX_WIDTHS):
            ax.add_patch(Rectangle((x, y - 0.20), width, 0.40,
                                   facecolor=colors[i], edgecolor="white"))
            ax.text(x + width / 2, y, str(width), ha="center", va="center",
                    color="white", fontsize=12)
            x += width
            if i < len(gaps):
                gap = gaps[i]
                ax.add_patch(Rectangle((x, y - 0.20), gap, 0.40,
                                       facecolor="#f5dfb6", edgecolor="#b48237"))
                ax.text(x + gap / 2, y, f"{gap:g}", ha="center", va="center",
                        fontsize=11, color="#573d1d")
                x += gap
        ax.vlines(target, y - 0.32, y + 0.32, color="#172330", linewidth=1.2)
        ax.text(0, y + 0.36, f"{label}: width {target}, ratio r = {ratio:g}",
                fontsize=11, color="#172330")
    ax.set_xlim(-0.2, 33)
    ax.set_ylim(-0.45, 2.65)
    ax.set_yticks([])
    ax.set_xticks(range(0, 33, 4))
    ax.set_xlabel("Horizontal position (arbitrary consistent units)", fontsize=10)
    for side in ["left", "right", "top"]:
        ax.spines[side].set_visible(False)
    ax.spines["bottom"].set_color("#9aabb5")
    fig.legend(handles=[Patch(facecolor=colors[0], label="Rigid box"),
                        Patch(facecolor="#f5dfb6", edgecolor="#b48237", label="Adjustable glue")],
               loc="lower center", bbox_to_anchor=(0.5, 0.045), ncol=2,
               frameon=False, fontsize=10)
    fig.text(0.5, 0.018, "Original schematic; finite glue of one order only.",
             ha="center", fontsize=9, color="#45535d")
    fig.savefig(Path.cwd() / (Path(__file__).stem + ".png"),
                dpi=100, facecolor="white", transparent=False)
    plt.close(fig)


if __name__ == "__main__":
    main()