codex/gross-tare-net-load-boundary.py

gross-tare-net-load-boundary.py
"""Chosen load-accounting example: four jars in one crate; PNG to cwd."""
from pathlib import Path
import math

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt


def main():
    count, contents_per_jar, empty_jar, crate = 4, 0.50, 0.20, 0.80
    contents = count * contents_per_jar
    jars = count * empty_jar
    tare = jars + crate
    gross = contents + tare
    assert math.isclose(gross, 3.60)
    assert math.isclose(gross - tare, 2.00)
    assert math.isclose((gross - jars) - tare, 1.20)
    fig, ax = plt.subplots(figsize=(7, 4.8), dpi=100, facecolor="white")
    fig.subplots_adjust(left=0.12, right=0.96, bottom=0.20, top=0.74)
    ax.set_axisbelow(True)
    ax.grid(axis="y", color="#dce4e9", linewidth=0.8)
    portions = [("Contents", [contents, 0, contents], "#286c96", "white"),
                ("Empty jars", [jars, jars, 0], "#e3a654", "#28333c"),
                ("Outer crate", [crate, crate, 0], "#ccd6df", "#28333c")]
    bottom = [0.0, 0.0, 0.0]
    for label, values, color, text_color in portions:
        ax.bar(range(3), values, bottom=bottom, width=0.58,
               color=color, edgecolor="white", linewidth=1.5, label=label)
        for x, value in enumerate(values):
            if value:
                ax.text(x, bottom[x] + value / 2, f"{value:.2f} kg",
                        ha="center", va="center", fontsize=11, color=text_color)
            bottom[x] += value
    for x, value in enumerate([gross, tare, contents]):
        ax.text(x, value + 0.09, f"{value:.2f} kg", ha="center",
                fontsize=11, weight="bold", color="#172330")
    ax.set_xticks(range(3), ["Gross", "Tare", "Net contents"])
    ax.set_ylim(0, 4.05)
    ax.set_yticks([0, 1, 2, 3, 4])
    ax.set_ylabel("Mass (kg)", fontsize=11)
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.13), ncol=3,
              fontsize=10, frameon=False)
    fig.suptitle("Use the same load boundary for gross, tare and net", y=0.96,
                 fontsize=14, weight="bold", color="#172330")
    fig.text(0.5, 0.875, "Four jars: 0.50 kg contents + 0.20 kg empty jar each; outer crate: 0.80 kg",
             ha="center", fontsize=10, color="#45535d")
    fig.text(0.5, 0.815, "3.60 kg gross − 1.60 kg composite tare = 2.00 kg contents",
             ha="center", fontsize=11, color="#172330")
    fig.text(0.5, 0.025, "Chosen bookkeeping example, not measured data. Count every packaging part exactly once.",
             ha="center", fontsize=9.5, color="#45535d")
    fig.savefig(Path.cwd() / (Path(__file__).stem + ".png"), dpi=100,
                facecolor="white", transparent=False)
    plt.close(fig)


if __name__ == "__main__":
    main()