diff --git a/CHANGELOG.md b/CHANGELOG.md index acaa8a2..27708bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ All notable changes to CableXSec are recorded in this file. The format follows ## [Unreleased] +### Changed + +- **Figures use a MATLAB-style look** (`cablexsec.plotting.style`): + - MATLAB's default line colours in MATLAB's order (`MATLAB_ORDER`; `COLORS` maps the names to those hues); + - a Helvetica or Arial face at 10 pt; + - a closed box with inward ticks on all sides and no grid; + - a square, opaque legend. +- **Labels carry true Greek letters and sub- and superscripts** in the same face (κ, EI_min, σ_A, m⁻¹), with numerals upright. The new `style.LABELS` holds the standard axis labels. +- **The tutorial and how-to scripts apply the style.** Their figures were plain matplotlib defaults before; they are regenerated. The examples follow the same labels. + ### Added - `bonded_face: outer` on the outermost helical layer (gap G8): the outer face diff --git a/doc/howto/figures/howto_04_section_stress.png b/doc/howto/figures/howto_04_section_stress.png index 006a977..4d627a9 100644 Binary files a/doc/howto/figures/howto_04_section_stress.png and b/doc/howto/figures/howto_04_section_stress.png differ diff --git a/doc/howto/scripts/howto_04_section_stress.py b/doc/howto/scripts/howto_04_section_stress.py index c8922ea..b7e6521 100644 --- a/doc/howto/scripts/howto_04_section_stress.py +++ b/doc/howto/scripts/howto_04_section_stress.py @@ -16,7 +16,9 @@ import numpy as np import cablexsec as cx +from cablexsec.plotting.style import LABELS, SIGNED_CMAP, apply_style +apply_style() # the MATLAB-style figures of every CableXSec plot FIGURES = ( Path(sys.argv[1]) if len(sys.argv) > 1 @@ -62,15 +64,15 @@ xy[:, 1], c=layer.sigma_Pa.reshape(-1) / 1e6, s=4 if layer.kind != "wires" else 10, - cmap="coolwarm", + cmap=SIGNED_CMAP, vmin=-300, vmax=300, ) -fig.colorbar(marks, ax=ax, label="longitudinal stress [MPa]") +fig.colorbar(marks, ax=ax, label=r"Longitudinal stress $\sigma_{zz}$ [MPa]") ax.set_aspect("equal") -ax.set_xlabel("x [mm]") -ax.set_ylabel("y [mm]") -ax.set_title("T = 100 kN, curvature 0.1 1/m towards +y", fontsize=9) +ax.set_xlabel(LABELS["x_mm"]) +ax.set_ylabel(LABELS["y_mm"]) +ax.set_title(r"$T$ = 100 kN, $\kappa$ = 0.1 m$^{\mathrm{-1}}$ towards $+y$", fontsize=9) fig.tight_layout() FIGURES.mkdir(parents=True, exist_ok=True) -fig.savefig(FIGURES / "howto_04_section_stress.png", dpi=150) +fig.savefig(FIGURES / "howto_04_section_stress.png", dpi=200) diff --git a/doc/tutorials/figures/tutorial_01_first_cable.png b/doc/tutorials/figures/tutorial_01_first_cable.png index 2600740..baa103c 100644 Binary files a/doc/tutorials/figures/tutorial_01_first_cable.png and b/doc/tutorials/figures/tutorial_01_first_cable.png differ diff --git a/doc/tutorials/figures/tutorial_02_measured_loop.png b/doc/tutorials/figures/tutorial_02_measured_loop.png index da9ad24..2b75fc7 100644 Binary files a/doc/tutorials/figures/tutorial_02_measured_loop.png and b/doc/tutorials/figures/tutorial_02_measured_loop.png differ diff --git a/doc/tutorials/figures/tutorial_02_sensitivity.png b/doc/tutorials/figures/tutorial_02_sensitivity.png index f2f8014..f0b0f86 100644 Binary files a/doc/tutorials/figures/tutorial_02_sensitivity.png and b/doc/tutorials/figures/tutorial_02_sensitivity.png differ diff --git a/doc/tutorials/figures/tutorial_03_damage_circumference.png b/doc/tutorials/figures/tutorial_03_damage_circumference.png index d43b49c..a3c0d74 100644 Binary files a/doc/tutorials/figures/tutorial_03_damage_circumference.png and b/doc/tutorials/figures/tutorial_03_damage_circumference.png differ diff --git a/doc/tutorials/figures/tutorial_03_governing_fibre_stress.png b/doc/tutorials/figures/tutorial_03_governing_fibre_stress.png index a9e9fe6..41b1145 100644 Binary files a/doc/tutorials/figures/tutorial_03_governing_fibre_stress.png and b/doc/tutorials/figures/tutorial_03_governing_fibre_stress.png differ diff --git a/doc/tutorials/figures/tutorial_04_slip_amplitude.png b/doc/tutorials/figures/tutorial_04_slip_amplitude.png index 1162bec..52e17e9 100644 Binary files a/doc/tutorials/figures/tutorial_04_slip_amplitude.png and b/doc/tutorials/figures/tutorial_04_slip_amplitude.png differ diff --git a/doc/tutorials/figures/tutorial_04_swt_depth.png b/doc/tutorials/figures/tutorial_04_swt_depth.png index fb3931a..deea462 100644 Binary files a/doc/tutorials/figures/tutorial_04_swt_depth.png and b/doc/tutorials/figures/tutorial_04_swt_depth.png differ diff --git a/doc/tutorials/scripts/tutorial_01_first_cable.py b/doc/tutorials/scripts/tutorial_01_first_cable.py index 0687255..7401c30 100644 --- a/doc/tutorials/scripts/tutorial_01_first_cable.py +++ b/doc/tutorials/scripts/tutorial_01_first_cable.py @@ -23,7 +23,9 @@ slip_onset_curvature, ) from cablexsec.mechanics.radial_cable import solve_cable_radial_states +from cablexsec.plotting.style import COLORS, LABELS, apply_style +apply_style() # the MATLAB-style figures of every CableXSec plot FIGURES = ( Path(sys.argv[1]) if len(sys.argv) > 1 @@ -97,33 +99,49 @@ radial = solve_cable_radial_states(cable, sweep) fig, (ax_contact, ax_bending) = plt.subplots(1, 2, figsize=(9.0, 3.8)) for i, (layer, colour) in enumerate( - zip(cable.helical_layers, ("C0", "C1"), strict=True) + zip(cable.helical_layers, (COLORS["BLUE"], COLORS["ORANGE"]), strict=True) ): p_bounded = [specs[i].contact_pressure_Pa / 1e6 for specs in bounded] p_solved = [s.armour_contact_pressure()[layer.name] / 1e6 for s in radial] - ax_contact.plot(sweep / 1e3, p_bounded, "-", c=colour, label=f"{layer.name}") + label = layer.name.replace("_", " ") + ax_contact.plot(sweep / 1e3, p_bounded, "-", c=colour, label=label) ax_contact.plot(sweep / 1e3, p_solved, "--", c=colour) -ax_contact.set_xlabel("tension [kN]") -ax_contact.set_ylabel("armour contact pressure P1 + P2 [MPa]") +ax_contact.set_xlabel(LABELS["tension_kN"]) +ax_contact.set_ylabel(r"Armour contact pressure $P_\mathrm{1} + P_\mathrm{2}$ [MPa]") ax_contact.set_title("Solid: bounded chain; dashed: solved") ax_contact.legend(loc="upper left") kappa = np.linspace(0.0, 0.02, 401) -for tension, colour in ((0.0, "black"), (100e3, "tab:red")): +for tension, colour in ((0.0, COLORS["BLUE"]), (100e3, COLORS["ORANGE"])): loop = cx.compute_mkappa(cable, kappa, tension_N=tension) ax_bending.plot( - kappa, loop.moment_Nm, color=colour, label=f"T = {tension / 1e3:.0f} kN" + kappa, loop.moment_Nm, color=colour, label=rf"$T$ = {tension / 1e3:.0f} kN" ) for spec in cx.cable_to_mkappa_specs(cable, tension, contact_model="bounded"): onset = slip_onset_curvature(spec) ax_bending.plot(onset, np.interp(onset, kappa, loop.moment_Nm), "o", c=colour) -ax_bending.plot(kappa, stiffness.ei_min_Nm2 * kappa, "--", c="grey", label="full slip") -ax_bending.plot(kappa, stiffness.ei_max_Nm2 * kappa, ":", c="grey", label="no slip") +ax_bending.plot( + kappa, + stiffness.ei_min_Nm2 * kappa, + "--", + c=COLORS["GREY"], + lw=1.0, + label=r"full slip, $EI_\mathrm{min}$", +) +ax_bending.plot( + kappa, + stiffness.ei_max_Nm2 * kappa, + ":", + c=COLORS["GREY"], + lw=1.0, + label=r"no slip, $EI_\mathrm{max}$", +) ax_bending.set_ylim(0.0, 700.0) -ax_bending.set_xlabel("curvature [1/m]") -ax_bending.set_ylabel("bending moment [N m]") +ax_bending.set_xticks(np.linspace(0.0, 0.02, 5)) +ax_bending.set_xlabel(LABELS["curvature"]) +ax_bending.set_ylabel(LABELS["moment_Nm"]) ax_bending.set_title("First loading; dots: slip onset") ax_bending.legend(loc="lower right") fig.tight_layout() FIGURES.mkdir(parents=True, exist_ok=True) -fig.savefig(FIGURES / "tutorial_01_first_cable.png", dpi=150) +fig.savefig(FIGURES / "tutorial_01_first_cable.png", dpi=200) print(f"wrote {(FIGURES / 'tutorial_01_first_cable.png').name}") diff --git a/doc/tutorials/scripts/tutorial_02_bending_hysteresis.py b/doc/tutorials/scripts/tutorial_02_bending_hysteresis.py index ed3945e..4cb98b6 100644 --- a/doc/tutorials/scripts/tutorial_02_bending_hysteresis.py +++ b/doc/tutorials/scripts/tutorial_02_bending_hysteresis.py @@ -22,7 +22,9 @@ import cablexsec as cx from cablexsec.analysis.curve_comparison import cycle_work, insert_cycle_crossings from cablexsec.mechanics.papailiou import slip_onset_curvature +from cablexsec.plotting.style import COLORS, LABELS, apply_style +apply_style() # the MATLAB-style figures of every CableXSec plot REPOSITORY = Path(__file__).resolve().parents[3] MEASURED = REPOSITORY / "validation" / "paper_data" / "menard_fig16b_ordered.csv" FIGURES = ( @@ -97,30 +99,39 @@ def describe(label, result, spec): # [step-figures] FIGURES.mkdir(parents=True, exist_ok=True) fig, ax = plt.subplots(figsize=(5.0, 4.0)) -ax.plot(kappa_test, moment_test, "o", ms=3, mfc="none", c="grey", label="measured") -ax.plot(path, loop.moment_Nm[second], c="black", label="CableXSec") -ax.set_xlabel("curvature [1/m]") +ax.plot( + kappa_test, + moment_test, + "o", + ms=3, + mfc="none", + c=COLORS["BLACK"], + mew=0.6, + label="measured", +) +ax.plot(path, loop.moment_Nm[second], c=COLORS["BLUE"], label="CableXSec") +ax.set_xlabel(LABELS["curvature"]) ax.set_xticks([-0.1, -0.05, 0.0, 0.05, 0.1]) -ax.set_ylabel("bending moment [N m]") +ax.set_ylabel(LABELS["moment_Nm"]) ax.set_title("Ménard and Cartraud (2023), range (b)") ax.legend(loc="upper left") fig.tight_layout() -fig.savefig(FIGURES / "tutorial_02_measured_loop.png", dpi=150) +fig.savefig(FIGURES / "tutorial_02_measured_loop.png", dpi=200) print(f"wrote {(FIGURES / 'tutorial_02_measured_loop.png').name}") fig, (ax_mu, ax_p) = plt.subplots(1, 2, figsize=(9.0, 3.8), sharey=True) for mu, result in friction_loops.items(): - ax_mu.plot(kappa[cycle], result.moment_Nm[cycle], label=f"mu = {mu}") + ax_mu.plot(kappa[cycle], result.moment_Nm[cycle], label=rf"$\mu$ = {mu}") for pressure, result in clamping_loops.items(): - label = f"p0 = {pressure / 1e6:.2f} MPa" + label = rf"$p_\mathrm{{0}}$ = {pressure / 1e6:.2f} MPa" ax_p.plot(kappa[cycle], result.moment_Nm[cycle], label=label) -ax_mu.set_title("Friction coefficient (p0 = 0.30 MPa)") -ax_p.set_title("Initial pressure p0 (mu = 0.2)") -ax_mu.set_ylabel("bending moment [N m]") +ax_mu.set_title(r"Friction coefficient ($p_\mathrm{0}$ = 0.30 MPa)") +ax_p.set_title(r"Initial pressure $p_\mathrm{0}$ ($\mu$ = 0.2)") +ax_mu.set_ylabel(LABELS["moment_Nm"]) for axis in (ax_mu, ax_p): - axis.set_xlabel("curvature [1/m]") + axis.set_xlabel(LABELS["curvature"]) axis.set_xticks([-0.1, -0.05, 0.0, 0.05, 0.1]) axis.legend(loc="upper left") fig.tight_layout() -fig.savefig(FIGURES / "tutorial_02_sensitivity.png", dpi=150) +fig.savefig(FIGURES / "tutorial_02_sensitivity.png", dpi=200) print(f"wrote {(FIGURES / 'tutorial_02_sensitivity.png').name}") diff --git a/doc/tutorials/scripts/tutorial_03_global_to_fatigue.py b/doc/tutorials/scripts/tutorial_03_global_to_fatigue.py index 46e05d4..f2f6187 100644 --- a/doc/tutorials/scripts/tutorial_03_global_to_fatigue.py +++ b/doc/tutorials/scripts/tutorial_03_global_to_fatigue.py @@ -27,7 +27,9 @@ from cablexsec.analysis.fast_rainflow import fibre_fatigue from cablexsec.analysis.fatigue import rainflow_cycles, wire_stress_field from cablexsec.cable_adapters import cable_to_fatigue_layers +from cablexsec.plotting.style import COLORS, LABELS, apply_style +apply_style() # the MATLAB-style figures of every CableXSec plot REPOSITORY = Path(__file__).resolve().parents[3] FIGURES = ( Path(sys.argv[1]) @@ -208,29 +210,34 @@ for name, damage in fatigue.D_total_per_wire.items(): count = damage.size ax.plot(360.0 * np.arange(count) / count, damage, label=name.replace("_", " ")) -ax.axvline(fatigue.phi_critical_deg, color="0.5", linewidth=0.8, linestyle="--") -ax.set_xlabel("wire azimuth from e1 [deg]") -ax.set_ylabel("Miner damage over the record") +ax.axvline( + fatigue.phi_critical_deg, color=COLORS["GREY"], linewidth=1.0, linestyle="--" +) +ax.set_xlabel(r"Wire azimuth from $\mathbf{e}_\mathrm{1}$, $\varphi$ [$^\circ$]") +ax.set_ylabel(r"Miner damage over the record, $D$ [–]") ax.set_xlim(0.0, 360.0) ax.set_xticks(np.arange(0, 361, 45)) ax.set_ylim(bottom=0.0) ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) -ax.legend(frameon=False, loc="lower center") -fig.savefig(FIGURES / "tutorial_03_damage_circumference.png", dpi=150) +ax.legend(loc="lower center") +fig.savefig(FIGURES / "tutorial_03_damage_circumference.png", dpi=200) plt.close(fig) print("wrote tutorial_03_damage_circumference.png") fig, ax = plt.subplots(figsize=(6.4, 3.0), layout="constrained") window = series.time_s <= 120.0 -ax.plot(series.time_s[window], stress[window] / 1e6, linewidth=0.9) -ax.set_xlabel("time [s]") -ax.set_ylabel("fibre stress [MPa]") +ax.plot( + series.time_s[window], stress[window] / 1e6, color=COLORS["BLUE"], linewidth=1.0 +) +ax.set_xlabel(LABELS["time"]) +ax.set_ylabel(r"Fibre stress $\sigma$ [MPa]") ax.set_xlim(0.0, 120.0) ax.set_title( - f"{fatigue.critical_layer.replace('_', ' ')}, wire at " - f"{fatigue.phi_critical_deg:.0f} deg, fibre {fatigue.fibre_critical_deg:.0f} deg", + rf"{fatigue.critical_layer.replace('_', ' ')}, wire at " + rf"{fatigue.phi_critical_deg:.0f}$^\circ$, " + rf"fibre {fatigue.fibre_critical_deg:.0f}$^\circ$", fontsize=10, ) -fig.savefig(FIGURES / "tutorial_03_governing_fibre_stress.png", dpi=150) +fig.savefig(FIGURES / "tutorial_03_governing_fibre_stress.png", dpi=200) plt.close(fig) print("wrote tutorial_03_governing_fibre_stress.png") diff --git a/doc/tutorials/scripts/tutorial_04_contact_and_fretting.py b/doc/tutorials/scripts/tutorial_04_contact_and_fretting.py index bd23786..96b4f25 100644 --- a/doc/tutorials/scripts/tutorial_04_contact_and_fretting.py +++ b/doc/tutorials/scripts/tutorial_04_contact_and_fretting.py @@ -33,6 +33,7 @@ reduced_shear_modulus, solve_contact, ) +from cablexsec.plotting.style import COLORS, LABELS, apply_style FIGURES = ( Path(sys.argv[1]) @@ -274,8 +275,12 @@ def contact_cycle(x_over_a, z_over_b): f"plane normal {tilt:.0f} deg from the wire axis" ) # [step-figures] +apply_style() # the MATLAB-style figures of every CableXSec plot fig, ax = plt.subplots(figsize=(6.4, 4.0), layout="constrained") -for name, colour in (("inner_armour", "C0"), ("outer_armour", "C1")): +for name, colour in ( + ("inner_armour", COLORS["BLUE"]), + ("outer_armour", COLORS["ORANGE"]), +): face_name = faces[name] full = fretting.faces[face_name] label = name.replace("_", " ") @@ -288,24 +293,36 @@ def contact_cycle(x_over_a, z_over_b): ) stations, amplitude = friction_slip[name] ax.plot(stations, amplitude * 1e6, color=colour, label=f"{label}, friction law") -ax.set_xlabel("wire azimuth from e1 [deg]") -ax.set_ylabel("slip amplitude [µm]") +ax.set_xlabel(r"Wire azimuth from $\mathbf{e}_\mathrm{1}$, $\varphi$ [$^\circ$]") +ax.set_ylabel(LABELS["slip_um"]) ax.set_xlim(0.0, 360.0) ax.set_xticks(np.arange(0, 361, 45)) ax.set_ylim(bottom=0.0) -fig.legend(frameon=False, fontsize=8, ncols=2, loc="outside lower center") -fig.savefig(FIGURES / "tutorial_04_slip_amplitude.png", dpi=150) +fig.legend(fontsize=8, ncols=2, loc="outside lower center") +fig.savefig(FIGURES / "tutorial_04_slip_amplitude.png", dpi=200) plt.close(fig) print("wrote tutorial_04_slip_amplitude.png") fig, ax = plt.subplots(figsize=(6.4, 3.2), layout="constrained") -ax.plot(depths, np.array(profile) / 1e6, marker="o", label="next to the crossing") -ax.axhline(bulk_only / 1e6, color="0.4", linestyle="--", label="bulk cycle alone") -ax.set_xlabel("depth z / b at x = -1.1 a") -ax.set_ylabel("SWT indicator [MPa]") +ax.plot( + depths, + np.array(profile) / 1e6, + marker="o", + color=COLORS["BLUE"], + label="next to the crossing", +) +ax.axhline( + bulk_only / 1e6, + color=COLORS["GREY"], + linestyle="--", + linewidth=1.0, + label="bulk cycle alone", +) +ax.set_xlabel(r"Depth $z/b$ at $x = -1.1\,a$ [–]") +ax.set_ylabel(r"SWT indicator $\sigma_\mathrm{max}\,\varepsilon_\mathrm{a}$ [MPa]") ax.set_xlim(0.0, 1.05) ax.set_ylim(bottom=0.0) -ax.legend(frameon=False) -fig.savefig(FIGURES / "tutorial_04_swt_depth.png", dpi=150) +ax.legend() +fig.savefig(FIGURES / "tutorial_04_swt_depth.png", dpi=200) plt.close(fig) print("wrote tutorial_04_swt_depth.png") diff --git a/doc/user_guide.md b/doc/user_guide.md index 9049349..ade19c4 100644 --- a/doc/user_guide.md +++ b/doc/user_guide.md @@ -146,6 +146,29 @@ for screening. `cablexsec.plotting.build_dashboard` writes a standalone HTML viewer of stress, moment–curvature, capacity and fatigue results. +### 2.8 Figures + +`cablexsec.plotting` draws the standard figures from result objects: + +- `plot_mkappa` and `plot_mkappa_validation_suite`: moment–curvature loops; +- `plot_cross_section`: the section, by material or coloured by a stress component; +- `plot_stress_distribution` and `plot_stress_timeseries`: per-wire stress; +- `plot_damage_split` and `plot_fretting_polar`: fatigue; +- `plot_capacity_envelope` and `plot_temperature_gradient`: capacity and temperature. + +Every figure uses one MATLAB-style look (`cablexsec.plotting.style`): + +- MATLAB's default line colours, in MATLAB's order (`MATLAB_ORDER`; named in `COLORS`); +- a Helvetica or Arial face; +- a closed box with inward ticks and no grid; +- symbols with true Greek letters and sub- and superscripts, such as κ, EI_min and m⁻¹. + +`style.LABELS` holds the standard axis labels, for example +`LABELS["curvature"]` and `LABELS["moment_kNm"]`. Use them in your own scripts +too. Apply the look to your own figures with `style.apply_style()`, or for +one block with `with style.use_style():`. The limitations of a result are +printed on its figure verbatim. + ## 3. Reading results - **{term}`Provenance `.** Every result keeps its `provenance`: method, citations, diff --git a/examples/demo_02_mkappa_validation.py b/examples/demo_02_mkappa_validation.py index 95c97da..e8ce7e6 100644 --- a/examples/demo_02_mkappa_validation.py +++ b/examples/demo_02_mkappa_validation.py @@ -16,7 +16,7 @@ from _console import configure_console import cablexsec as cx -from cablexsec.plotting.style import COLORS, apply_style +from cablexsec.plotting.style import COLORS, LABELS, apply_style configure_console() @@ -48,10 +48,10 @@ def main() -> None: apply_style() fig, ax = plt.subplots(figsize=(5, 4)) - ax.plot(mk.kappa_1_m * 1e3, mk.moment_Nm, color=COLORS["BLACK"], label="CableXSec") - ax.set_xlabel(r"curvature $\kappa$ [$10^{-3}$ m$^{-1}$]") - ax.set_ylabel("moment [N·m]") - ax.set_title("Ménard cable — M–κ loop (EI_min comparison, A11)") + ax.plot(mk.kappa_1_m * 1e3, mk.moment_Nm, color=COLORS["BLUE"], label="CableXSec") + ax.set_xlabel(LABELS["curvature_milli"]) + ax.set_ylabel(LABELS["moment_Nm"]) + ax.set_title(r"Ménard cable — $M$–$\kappa$ loop ($EI_\mathrm{min}$ check, A11)") ax.legend() fig.savefig(OUT / "demo_02_mkappa.png") print(f"saved {OUT / 'demo_02_mkappa.png'}") diff --git a/examples/demo_03_stress_distribution.py b/examples/demo_03_stress_distribution.py index 6b61ff9..898ff76 100644 --- a/examples/demo_03_stress_distribution.py +++ b/examples/demo_03_stress_distribution.py @@ -15,7 +15,7 @@ from _console import configure_console import cablexsec as cx -from cablexsec.plotting.style import COLORS, apply_style +from cablexsec.plotting.style import COLORS, LABELS, apply_style configure_console() @@ -51,14 +51,14 @@ def main() -> None: phi = sr.phi_deg[name] fig, ax = plt.subplots(figsize=(6, 4)) for comp, col, lab in [ - (sr.sigma_A_Pa, COLORS["GREEN"], r"$\sigma_A$"), - (sr.sigma_B_Pa, COLORS["BLUE"], r"$\sigma_B$"), - (sr.sigma_f_Pa, COLORS["ORANGE"], r"$\sigma_f$"), - (sr.sigma_total_Pa, COLORS["BLACK"], r"$\sigma_{total}$"), + (sr.sigma_A_Pa, COLORS["BLUE"], r"$\sigma_\mathrm{A}$"), + (sr.sigma_B_Pa, COLORS["ORANGE"], r"$\sigma_\mathrm{B}$"), + (sr.sigma_f_Pa, COLORS["YELLOW"], r"$\sigma_\mathrm{f}$"), + (sr.sigma_total_Pa, COLORS["PURPLE"], r"$\sigma_\mathrm{total}$"), ]: ax.plot(phi, comp[name] / mpa, color=col, label=lab) - ax.set_xlabel(r"wire azimuth $\varphi$ [deg]") - ax.set_ylabel("stress [MPa]") + ax.set_xlabel(LABELS["azimuth"]) + ax.set_ylabel(LABELS["stress"]) ax.set_title(f"Per-wire stress — {name} (analytically verified)") ax.legend(ncol=2) fig.savefig(OUT / "demo_03_stress_distribution.png") diff --git a/examples/demo_05_fatigue_damage.py b/examples/demo_05_fatigue_damage.py index 6bd175f..4edeaed 100644 --- a/examples/demo_05_fatigue_damage.py +++ b/examples/demo_05_fatigue_damage.py @@ -16,7 +16,7 @@ from _console import configure_console import cablexsec as cx -from cablexsec.plotting.style import COLORS, apply_style +from cablexsec.plotting.style import COLORS, LABELS, apply_style configure_console() @@ -58,11 +58,11 @@ def main() -> None: phi, fat.D_bulk_per_wire[crit], width=360 / n, - color=COLORS["BLACK"], - label="D_bulk", + color=COLORS["BLUE"], + label=r"$D_\mathrm{bulk}$", ) - ax.set_xlabel(r"wire azimuth $\varphi$ [deg]") - ax.set_ylabel("Miner damage (history)") + ax.set_xlabel(LABELS["azimuth"]) + ax.set_ylabel(r"Miner damage over the history, $D$ [–]") ax.set_title(f"Fatigue damage per wire — {crit}") ax.legend() fig.savefig(OUT / "demo_05_fatigue_damage.png") diff --git a/examples/rig_test_gauge_plan.py b/examples/rig_test_gauge_plan.py index d5bf201..8913b0e 100644 --- a/examples/rig_test_gauge_plan.py +++ b/examples/rig_test_gauge_plan.py @@ -21,7 +21,7 @@ from _console import configure_console import cablexsec as cx -from cablexsec.plotting.style import apply_style +from cablexsec.plotting.style import LABELS, apply_style configure_console() @@ -69,20 +69,23 @@ def main() -> None: axes[0].plot( res.time_s, g.total, - label=f"{g.location.layer} {g.angle_deg:.0f} deg, x={g.location.x_m:.2f} m", + label=( + f"{g.location.layer.replace('_', ' ')} {g.angle_deg:.0f}$^\\circ$, " + f"$x$ = {g.location.x_m:.2f} m" + ), ) - axes[0].set_xlabel("time [s]") - axes[0].set_ylabel("wire strain [microstrain]") + axes[0].set_xlabel(LABELS["time"]) + axes[0].set_ylabel(r"Wire strain $\varepsilon$ [$\mu\varepsilon$]") axes[0].legend(fontsize=7) for station in res.stations: r = res.retained axes[1].plot( station.kappa_1_m[r], station.moment_Nm[r] / 1e3, - label=f"x = {station.x_m:.1f} m", + label=f"$x$ = {station.x_m:.1f} m", ) - axes[1].set_xlabel("curvature [1/m]") - axes[1].set_ylabel("moment [kN m]") + axes[1].set_xlabel(LABELS["curvature"]) + axes[1].set_ylabel(LABELS["moment_kNm"]) axes[1].legend() fig.tight_layout() path = OUT / "rig_test_gauge_plan.png" diff --git a/src/cablexsec/plotting/capacity.py b/src/cablexsec/plotting/capacity.py index fca2c9a..e82cdf4 100644 --- a/src/cablexsec/plotting/capacity.py +++ b/src/cablexsec/plotting/capacity.py @@ -10,6 +10,7 @@ from cablexsec.plotting.style import ( COLORS, + LABELS, annotate_provenance, use_style, ) @@ -23,9 +24,9 @@ # Mechanism -> house colour (the shared plotting convention). _MECH_COLOR = { - "wire_yield": COLORS["BLACK"], - "bird_caging": COLORS["RED"], - "polymer_crush": COLORS["BLUE"], + "wire_yield": COLORS["BLUE"], + "bird_caging": COLORS["ORANGE"], + "polymer_crush": COLORS["PURPLE"], "conductor": COLORS["GREEN"], } @@ -36,8 +37,8 @@ def plot_capacity_envelope(result: CapacityResult) -> Figure: Panel (a): the curvature capacity ``κ_max`` vs tension — the operating envelope — with each segment coloured by its governing mechanism. Panel (b): the tension-driven usage factors (bird-caging, polymer crush, conductor) vs - tension, with the UF = 1.0 (thick black) and UF = 0.8 (green dashed) - reference lines. The result's limitations are annotated verbatim. + tension, with the U = 1.0 (black) and U = 0.8 (grey dashed) reference + lines. The result's limitations are annotated verbatim. Returns ------- @@ -54,7 +55,6 @@ def plot_capacity_envelope(result: CapacityResult) -> Figure: t_kN, result.kappa_max_1_m, color=COLORS["BLACK"], - lw=1.6, zorder=2, label="capacity boundary", ) @@ -70,25 +70,23 @@ def plot_capacity_envelope(result: CapacityResult) -> Figure: label=mech.replace("_", " "), zorder=3, ) - axa.set_xlabel("tension [kN]") - axa.set_ylabel(r"curvature capacity $\kappa_{max}$ [1/m]") - axa.set_title("(a) capacity envelope") + axa.set_xlabel(LABELS["tension_kN"]) + axa.set_ylabel(r"Curvature capacity $\kappa_\mathrm{max}$ [m$^{\mathrm{-1}}$]") + axa.set_title("(a) Capacity envelope") axa.legend(loc="best", fontsize=8) # (b) tension-driven usage factors. axb.plot( t_kN, result.uf_bird_caging, - color=COLORS["RED"], - lw=1.3, + color=COLORS["ORANGE"], label="bird-caging", ) if np.any(np.isfinite(result.uf_polymer_crush)): axb.plot( t_kN, result.uf_polymer_crush, - color=COLORS["BLUE"], - lw=1.3, + color=COLORS["PURPLE"], label="polymer crush", ) else: @@ -100,16 +98,14 @@ def plot_capacity_envelope(result: CapacityResult) -> Figure: ha="right", va="bottom", fontsize=7, - color=COLORS["BLUE"], + color=COLORS["PURPLE"], ) - axb.plot( - t_kN, result.uf_conductor, color=COLORS["GREEN"], lw=1.3, label="conductor" - ) - axb.axhline(1.0, color=COLORS["BLACK"], lw=1.6, label="UF = 1.0") - axb.axhline(0.8, color=COLORS["GREEN"], ls="--", lw=0.9, label="UF = 0.8") - axb.set_xlabel("tension [kN]") - axb.set_ylabel("usage factor [-]") - axb.set_title("(b) tension-driven usage factors") + axb.plot(t_kN, result.uf_conductor, color=COLORS["GREEN"], label="conductor") + axb.axhline(1.0, color=COLORS["BLACK"], lw=1.0, label=r"$U$ = 1.0") + axb.axhline(0.8, color=COLORS["GREY"], ls="--", lw=1.0, label=r"$U$ = 0.8") + axb.set_xlabel(LABELS["tension_kN"]) + axb.set_ylabel(r"Usage factor $U$ [–]") + axb.set_title("(b) Tension-driven usage factors") axb.legend(loc="best", fontsize=8) annotate_provenance(axb, result.provenance, loc="lower right", max_items=2) diff --git a/src/cablexsec/plotting/cross_section.py b/src/cablexsec/plotting/cross_section.py index eb3c3d4..20f84ae 100644 --- a/src/cablexsec/plotting/cross_section.py +++ b/src/cablexsec/plotting/cross_section.py @@ -18,6 +18,7 @@ from cablexsec.plotting.style import ( COLORS, FIGSIZE, + LABELS, SIGNED_CMAP, annotate_provenance, material_color, @@ -97,8 +98,8 @@ def plot_cross_section( ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) ax.set_aspect("equal") - ax.set_xlabel("x [m]") - ax.set_ylabel("y [m]") + ax.set_xlabel(LABELS["x_m"]) + ax.set_ylabel(LABELS["y_m"]) ax.set_title(title or f"{cable.cable.name} — cross-section") # Legend for the marker convention only when stress-coloured. if stress_result is not None: @@ -106,7 +107,7 @@ def plot_cross_section( [], [], facecolors=COLORS["GREY"], edgecolors="k", label="stuck wire" ) ax.scatter([], [], facecolors="none", edgecolors="k", label="slipping wire") - ax.legend(loc="upper right", fontsize=8, frameon=True, framealpha=0.9) + ax.legend(loc="upper right", fontsize=8) annotate_provenance(ax, stress_result.provenance, loc="lower left") # keep the unused import referenced for static checkers _ = (Circle, Annulus) @@ -223,10 +224,10 @@ def _draw_layer( def _component_label(component: str) -> str: """Pretty label for a stress component field name.""" names = { - "sigma_total_Pa": r"$\sigma_{total}$ [MPa]", - "sigma_A_Pa": r"$\sigma_A$ [MPa]", - "sigma_B_Pa": r"$\sigma_B$ [MPa]", - "sigma_f_Pa": r"$\sigma_f$ [MPa]", + "sigma_total_Pa": r"$\sigma_\mathrm{total}$ [MPa]", + "sigma_A_Pa": r"$\sigma_\mathrm{A}$ [MPa]", + "sigma_B_Pa": r"$\sigma_\mathrm{B}$ [MPa]", + "sigma_f_Pa": r"$\sigma_\mathrm{f}$ [MPa]", "sigma_vm_Pa": "Axial/contact indicator [MPa]", } return names.get(component, component) diff --git a/src/cablexsec/plotting/fatigue.py b/src/cablexsec/plotting/fatigue.py index 54c0cc8..92df43f 100644 --- a/src/cablexsec/plotting/fatigue.py +++ b/src/cablexsec/plotting/fatigue.py @@ -46,10 +46,10 @@ def plot_damage_split(result: FatigueResult) -> Figure: # (a) per-layer critical-wire damage split (log scale). parts = [ - ("bulk", result.D_bulk_per_wire, COLORS["BLACK"]), - ("fretting", result.D_fretting_per_wire, COLORS["RED"]), - ("termination", result.D_term_per_wire, COLORS["BLUE"]), - ("total", result.D_total_per_wire, COLORS["GREEN"]), + ("bulk", result.D_bulk_per_wire, COLORS["BLUE"]), + ("fretting", result.D_fretting_per_wire, COLORS["ORANGE"]), + ("termination", result.D_term_per_wire, COLORS["YELLOW"]), + ("total", result.D_total_per_wire, COLORS["PURPLE"]), ] x = np.arange(len(layers)) w = 0.2 @@ -60,8 +60,8 @@ def plot_damage_split(result: FatigueResult) -> Figure: axa.set_yscale("log") axa.set_xticks(x) axa.set_xticklabels(layers, fontsize=8, rotation=15) - axa.set_ylabel("damage per wire [-]") - axa.set_title("(a) damage split (critical wire)") + axa.set_ylabel(r"Miner damage per wire $D$ [–]") + axa.set_title("(a) Damage split (critical wire)") axa.legend(loc="best", fontsize=8) # (b) polar D_total(φ) for the critical layer. @@ -76,10 +76,9 @@ def plot_damage_split(result: FatigueResult) -> Figure: axb.plot( np.append(phi, phi[0]), np.append(d, d[0]), - color=COLORS["BLACK"], - lw=1.3, + color=COLORS["BLUE"], ) - axb.set_title(f"(b) $D_{{total}}(\\varphi)$ — {name}", fontsize=10) + axb.set_title(rf"(b) $D_\mathrm{{total}}(\varphi)$ — {name}", fontsize=10) annotate_provenance( axa, @@ -97,10 +96,10 @@ def plot_fretting_polar(result: StressResult, *, layer: str | None = None) -> Fi r"""Polar fretting distribution: 2D-Mindlin (uniform) vs loxodromic (zeros). Visualises the **rotation-invariance theorem**: the 2D vectorial Mindlin slip - gives a fretting amplitude **uniform** around the cross-section (black + gives a fretting amplitude **uniform** around the cross-section (blue circle), while the loxodromic (1D, neutral-axis-projected) model gives an amplitude ``∝ |cos(φ − φ_bend)|`` with **zeros at the neutral-axis wires** - (red dashed) — a qualitative failure the loxodromic model cannot avoid. The + (orange dashed) — a qualitative failure the loxodromic model cannot avoid. The per-wire azimuths and bending plane come from the :class:`StressResult`. Returns @@ -125,22 +124,20 @@ def plot_fretting_polar(result: StressResult, *, layer: str | None = None) -> Fi ax.plot( np.append(phi_s, phi_s[0]), np.append(uniform[order], uniform[order][0]), - color=COLORS["BLACK"], - lw=1.6, + color=COLORS["BLUE"], label="2D Mindlin (uniform)", ) ax.plot( np.append(phi_s, phi_s[0]), np.append(loxo[order], loxo[order][0]), - color=COLORS["RED"], + color=COLORS["ORANGE"], ls="--", - lw=1.4, - label="loxodromic ($|\\cos|$, zeros at NA)", + label=r"loxodromic ($|\cos(\varphi - \varphi_\mathrm{b})|$, zeros at NA)", ) # mark the neutral-axis wires (loxodromic zeros) na = np.abs(np.abs(np.cos(phi - phi_bend))) < 0.05 if np.any(na): - ax.scatter(phi[na], loxo[na], c=COLORS["RED"], s=30, zorder=5) + ax.scatter(phi[na], loxo[na], c=COLORS["ORANGE"], s=30, zorder=5) ax.set_rlim(0, 1.15) # type: ignore[attr-defined] # polar axes ax.set_title(f"Fretting amplitude shape — {name}", fontsize=10, pad=14) ax.legend(loc="upper right", bbox_to_anchor=(1.18, 1.10), fontsize=8) diff --git a/src/cablexsec/plotting/mkappa.py b/src/cablexsec/plotting/mkappa.py index 5d71435..220bfa7 100644 --- a/src/cablexsec/plotting/mkappa.py +++ b/src/cablexsec/plotting/mkappa.py @@ -12,6 +12,7 @@ from cablexsec.plotting.style import ( COLORS, FIGSIZE, + LABELS, annotate_provenance, use_style, ) @@ -38,9 +39,10 @@ def plot_mkappa( ) -> Axes: """Plot a model M-κ loop (public ``MkappaResult``), optionally vs experiment. - Solid black model loop; grey EI_max (dotted) / EI_min (dashed) reference - slopes; red open circles for experiment. The result's limitations are - annotated verbatim (e.g. the Papailiou-vs-Coulomb engine caveat). + Model loop in the first MATLAB colour; grey EI_max (dotted) / EI_min + (dashed) reference slopes; black open circles for experiment. The + result's limitations are annotated verbatim (e.g. the Papailiou-vs-Coulomb + engine caveat). Parameters ---------- @@ -69,8 +71,7 @@ def plot_mkappa( ax.plot( kappa, moment_kNm, - color=COLORS["BLACK"], - lw=1.6, + color=COLORS["BLUE"], label="CableXSec model", zorder=3, ) @@ -82,7 +83,7 @@ def plot_mkappa( color=COLORS["GREY"], ls=":", lw=1.0, - label=r"EI$_{max}$ (stuck)", + label=r"$EI_\mathrm{max}$ (stuck)", ) ax.plot( k_line, @@ -90,7 +91,7 @@ def plot_mkappa( color=COLORS["GREY"], ls="--", lw=1.0, - label=r"EI$_{min}$ (slip)", + label=r"$EI_\mathrm{min}$ (full slip)", ) if exp_kappa is not None and exp_moment_kNm is not None: @@ -101,7 +102,7 @@ def plot_mkappa( marker="o", ms=3.0, mfc="none", - mec=COLORS["RED"], + mec=COLORS["BLACK"], mew=0.7, label="Experiment", zorder=2, @@ -114,15 +115,16 @@ def plot_mkappa( ax.axhline(0.0, color=COLORS["GREY"], lw=0.5) ax.axvline(0.0, color=COLORS["GREY"], lw=0.5) - ax.set_xlabel(r"Curvature $\kappa$ [1/m]") - ax.set_ylabel(r"Bending moment $M$ [kN$\cdot$m]") + ax.set_xlabel(LABELS["curvature"]) + ax.set_ylabel(LABELS["moment_kNm"]) if title: ax.set_title(title) - ax.legend(loc="upper left", frameon=True, framealpha=0.9, fontsize=8) + ax.legend(loc="upper left", fontsize=8) txt = ( - f"$W_{{diss}}$ = {result.W_diss_J_per_m:.0f} J/m\n" - f"EI$_{{app}}$ = {result.EI_apparent_Nm2 / 1e3:.0f} kN$\\cdot$m$^2$" + rf"$W_\mathrm{{diss}}$ = {result.W_diss_J_per_m:.0f} J/m" + "\n" + rf"$EI_\mathrm{{app}}$ = {result.EI_apparent_Nm2 / 1e3:.0f} " + r"kN$\cdot$m$^\mathrm{2}$" ) ax.text( 0.97, @@ -135,7 +137,7 @@ def plot_mkappa( bbox={ "facecolor": "white", "edgecolor": COLORS["GREY"], - "boxstyle": "round,pad=0.3", + "boxstyle": "square,pad=0.3", }, ) if annotate: @@ -147,7 +149,7 @@ def plot_mkappa_validation_suite( results: dict[str, MkappaResult], *, experiments: dict[str, tuple[FloatArray, FloatArray]] | None = None, - suptitle: str = "M-κ validation suite", + suptitle: str = r"$M$–$\kappa$ validation suite", ) -> Figure: """Grid of M-κ loops (one per benchmark) with an error/summary table. diff --git a/src/cablexsec/plotting/stress.py b/src/cablexsec/plotting/stress.py index cbf2886..88fb750 100644 --- a/src/cablexsec/plotting/stress.py +++ b/src/cablexsec/plotting/stress.py @@ -14,6 +14,7 @@ from cablexsec.plotting.style import ( COLORS, FIGSIZE, + LABELS, SIGNED_CMAP, annotate_provenance, signed_norm, @@ -33,11 +34,11 @@ # (field, label, signed?) for the six panels, in reading order. _PANELS = [ - ("sigma_A_Pa", r"$\sigma_A$ (tension)", True), - ("sigma_B_Pa", r"$\sigma_B$ (bending)", True), - ("sigma_f_Pa", r"$\sigma_f$ (friction)", True), - ("sigma_T_Pa", r"$\sigma_T$ (thermal)", True), - ("sigma_total_Pa", r"$\sigma_{total}$", True), + ("sigma_A_Pa", r"$\sigma_\mathrm{A}$ (tension)", True), + ("sigma_B_Pa", r"$\sigma_\mathrm{B}$ (bending)", True), + ("sigma_f_Pa", r"$\sigma_\mathrm{f}$ (friction)", True), + ("sigma_T_Pa", r"$\sigma_\mathrm{T}$ (thermal)", True), + ("sigma_total_Pa", r"$\sigma_\mathrm{total}$", True), ("sigma_vm_Pa", "Axial/contact indicator", False), ] @@ -160,7 +161,7 @@ def _panel( ax.axhline(0.0, color=COLORS["GREY"], lw=0.5) ax.set_xlim(0, 360) ax.set_xticks([0, 90, 180, 270, 360]) - ax.set_xlabel(r"azimuth $\varphi$ [deg]", fontsize=9) + ax.set_xlabel(LABELS["azimuth"], fontsize=9) ax.set_ylabel(f"{label} [MPa]", fontsize=9) @@ -199,7 +200,7 @@ def plot_stress_timeseries( col[i].plot( t, series.curvature_x_1_m, - color=COLORS["BLACK"], + color=COLORS["BLUE"], lw=1.0, label=r"$\kappa_x$", ) @@ -207,37 +208,39 @@ def plot_stress_timeseries( col[i].plot( t, series.curvature_y_1_m, - color=COLORS["RED"], + color=COLORS["ORANGE"], lw=1.0, label=r"$\kappa_y$", ) - col[i].set_ylabel(r"$\kappa$ [1/m]", fontsize=9) + col[i].set_ylabel(r"$\kappa$ [m$^{\mathrm{-1}}$]", fontsize=9) col[i].legend(loc="upper right", fontsize=8) i += 1 if have_sig: assert sigma_crit_Pa is not None - col[i].plot(t, sigma_crit_Pa / 1e6, color=COLORS["BLACK"], lw=1.0) + col[i].plot(t, sigma_crit_Pa / 1e6, color=COLORS["BLUE"], lw=1.0) if sigma_y_Pa is not None: for s in (sigma_y_Pa, -sigma_y_Pa): col[i].axhline(s / 1e6, color=COLORS["RED"], ls="--", lw=0.8) - col[i].set_ylabel(r"$\sigma_{total}$ [MPa]", fontsize=9) + col[i].set_ylabel(r"$\sigma_\mathrm{total}$ [MPa]", fontsize=9) i += 1 if have_del: assert delta_star_um is not None col[i].plot(t, delta_star_um, color=COLORS["BLUE"], lw=1.0) - col[i].axhline(3.0, color=COLORS["GREEN"], ls="--", lw=0.8, label="3 µm Cu") col[i].axhline( - 5.0, color=COLORS["RED"], ls="--", lw=0.8, label="5 µm steel" + 3.0, color=COLORS["GREEN"], ls="--", lw=0.8, label="3 µm (Cu)" + ) + col[i].axhline( + 5.0, color=COLORS["RED"], ls="--", lw=0.8, label="5 µm (steel)" ) col[i].set_ylabel(r"$\delta^*$ [µm]", fontsize=9) col[i].legend(loc="upper right", fontsize=8) i += 1 - col[i].plot(t, series.tension_N / 1e3, color=COLORS["GREEN"], lw=1.0) - col[i].set_ylabel("tension [kN]", fontsize=9) - col[-1].set_xlabel("time [s]") + col[i].plot(t, series.tension_N / 1e3, color=COLORS["PURPLE"], lw=1.0) + col[i].set_ylabel(r"$T$ [kN]", fontsize=9) + col[-1].set_xlabel(LABELS["time"]) annotate_provenance(col[0], series.provenance, loc="upper left", max_items=2) fig.tight_layout() return fig diff --git a/src/cablexsec/plotting/style.py b/src/cablexsec/plotting/style.py index f1632ce..372befe 100644 --- a/src/cablexsec/plotting/style.py +++ b/src/cablexsec/plotting/style.py @@ -1,11 +1,22 @@ # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University -"""Publication-ready MATLAB-style plotting settings. +"""MATLAB-style plotting settings for every CableXSec figure. -All CableXSec figures share one visual style: a fixed six-colour palette, -Times New Roman serif at 11 pt, inward ticks, light grid, and 300 DPI output. -Apply it once at the top of a figure script with :func:`apply_style`, or scope -it to a block with :func:`use_style`. +The style follows MATLAB's default axes (R2014b and later): + +- the seven-colour ``lines`` order (blue, orange, yellow, purple, green, cyan, + dark red) as the line cycle; +- a sans-serif face (Helvetica, Arial or their metric clones) at 10 pt, axis + labels and titles at 11 pt; +- a closed box with inward ticks on all four sides, dark-grey axes, no grid; +- a square-cornered, opaque legend box. + +Symbols are typeset with matplotlib's mathtext in the same sans-serif face, so +labels carry Greek letters and true sub- and superscripts (``$\\kappa$``, +``$EI_\\mathrm{min}$``, ``m$^{\\mathrm{-1}}$``). Numerals inside math are +set upright with ``\\mathrm``, variables in italic. :data:`LABELS` holds the +standard axis labels. Apply the style once with :func:`apply_style`, or scope it with +:func:`use_style`. Examples -------- @@ -35,7 +46,9 @@ __all__ = [ "COLORS", "FIGSIZE", + "LABELS", "MATERIAL_COLORS", + "MATLAB_ORDER", "SIGNED_CMAP", "STYLE", "annotate_provenance", @@ -46,17 +59,35 @@ "use_style", ] -# Standard colour palette. Use these names, never ad-hoc hex codes. +#: MATLAB's default ``lines`` colour order (R2014b and later), in cycle order. +MATLAB_ORDER: tuple[str, ...] = ( + "#0072BD", # blue + "#D95319", # orange + "#EDB120", # yellow + "#7E2F8E", # purple + "#77AC30", # green + "#4DBEEE", # cyan + "#A2142F", # dark red +) + +# Named colours. Use these names, never ad-hoc hex codes. The hues are those of +# MATLAB_ORDER; BLACK and GREY are for references, data markers and outlines. COLORS: dict[str, str] = { - "BLACK": "#000000", # primary lines, critical results - "RED": "#CC0000", # warning, critical, threshold, hot - "BLUE": "#0000CC", # primary data, reference, cold - "GREEN": "#006600", # safe, secondary data - "GREY": "#666666", # reference lines, minor data - "ORANGE": "#CC6600", # tertiary data + "BLUE": MATLAB_ORDER[0], # primary model result + "ORANGE": MATLAB_ORDER[1], # second series, measured data + "YELLOW": MATLAB_ORDER[2], + "PURPLE": MATLAB_ORDER[3], + "GREEN": MATLAB_ORDER[4], # safe, secondary data + "CYAN": MATLAB_ORDER[5], + "RED": MATLAB_ORDER[6], # warning, critical, threshold, hot + "BLACK": "#000000", # measured markers, outlines + "GREY": "#808080", # reference lines, minor data } -# Canonical figure sizes [inches] — one width language across the paper. +#: MATLAB's axes and text colour, ``[0.15 0.15 0.15]``. +_AXES_GREY = "#262626" + +# Canonical figure sizes [inches]. FIGSIZE: dict[str, tuple[float, float]] = { "single": (5.0, 4.2), # one-panel figure "wide": (7.0, 3.6), # time-series / wide aspect @@ -65,8 +96,28 @@ "suite": (9.0, 6.5), # validation-suite grid } -# The ONE signed-field colormap: blue (-) -> white (0) -> red (+), built from -# the house palette. Diverging fields use THIS, never rainbow/jet (which encodes +#: Standard axis labels, with symbols and SI units. +LABELS: dict[str, str] = { + "curvature": r"Curvature $\kappa$ [m$^{\mathrm{-1}}$]", + "curvature_milli": r"Curvature $\kappa$ [$10^{\mathrm{-3}}$ m$^{\mathrm{-1}}$]", + "moment_Nm": r"Bending moment $M$ [N$\cdot$m]", + "moment_kNm": r"Bending moment $M$ [kN$\cdot$m]", + "tension_kN": r"Tension $T$ [kN]", + "time": r"Time $t$ [s]", + "azimuth": r"Wire azimuth $\varphi$ [$^\circ$]", + "radius_mm": r"Radius $r$ [mm]", + "temperature": r"Temperature $T$ [$^\circ$C]", + "stress": r"Stress $\sigma$ [MPa]", + "x_mm": r"$x$ [mm]", + "y_mm": r"$y$ [mm]", + "x_m": r"$x$ [m]", + "y_m": r"$y$ [m]", + "damage": r"Miner damage $D$ [–]", + "slip_um": r"Slip amplitude $\delta$ [µm]", +} + +# The ONE signed-field colormap: blue (-) -> white (0) -> dark red (+), from the +# MATLAB hues. Diverging fields use THIS, never rainbow/jet (which encodes # magnitude as hue and is unreadable for sign). SIGNED_CMAP: Colormap = LinearSegmentedColormap.from_list( "cablexsec_signed", [COLORS["BLUE"], "#FFFFFF", COLORS["RED"]], N=256 @@ -74,63 +125,97 @@ # Material -> fill colour for the by-material cross-section view. MATERIAL_COLORS: dict[str, str] = { - "steel": COLORS["GREY"], - "copper": COLORS["ORANGE"], - "cu": COLORS["ORANGE"], - "xlpe": COLORS["BLUE"], - "hdpe": "#BBBBBB", - "pp": "#DDDDDD", - "lead": "#444444", - "aluminium": "#AAAAAA", - "al": "#AAAAAA", + "steel": "#8C8C8C", + "copper": "#D9874A", + "cu": "#D9874A", + "xlpe": "#9CC3E4", + "epr": "#9CC3E4", + "hdpe": "#BFBFBF", + "mdpe": "#CFCFCF", + "ldpe": "#DCDCDC", + "pp": "#E6E6E6", + "lead": "#4D4D4D", + "aluminium": "#A6A6A6", + "al": "#A6A6A6", } # Matplotlib rcParams for the house style. STYLE: dict[str, object] = { - "font.family": "serif", - "font.serif": ["Times New Roman", "DejaVu Serif"], - "font.size": 11, + # Text: MATLAB's Helvetica, with Arial and metric clones as fallbacks. + "font.family": "sans-serif", + "font.sans-serif": [ + "Helvetica", + "Arial", + "Liberation Sans", + "Nimbus Sans", + "DejaVu Sans", + ], + "font.size": 10, "axes.labelsize": 11, "axes.titlesize": 11, + "axes.titleweight": "bold", "xtick.labelsize": 10, "ytick.labelsize": 10, - "legend.fontsize": 10, - "figure.dpi": 300, - "savefig.dpi": 300, - "savefig.bbox": "tight", - "savefig.pad_inches": 0.05, - "lines.linewidth": 1.5, - "lines.markersize": 6, - "axes.linewidth": 0.8, + "legend.fontsize": 9, + "text.color": _AXES_GREY, + "text.usetex": False, + # Symbols in the same sans-serif face as the text. + "mathtext.fontset": "custom", + "mathtext.rm": "sans", + "mathtext.it": "sans:italic", + "mathtext.bf": "sans:bold", + "mathtext.sf": "sans", + "mathtext.default": "it", + "axes.unicode_minus": True, + # an axis offset reads x10^-8, as in MATLAB, not 1e-8 + "axes.formatter.use_mathtext": True, + # Axes: closed box, inward ticks on all sides, no grid. + "axes.linewidth": 0.6, + "axes.edgecolor": _AXES_GREY, + "axes.labelcolor": _AXES_GREY, + "axes.spines.top": True, + "axes.spines.right": True, + "axes.grid": False, + "grid.color": _AXES_GREY, + "grid.alpha": 0.15, + "grid.linewidth": 0.5, + "axes.prop_cycle": cycler(color=list(MATLAB_ORDER)), + "axes.facecolor": "white", "xtick.direction": "in", "ytick.direction": "in", + "xtick.top": True, + "ytick.right": True, + "xtick.color": _AXES_GREY, + "ytick.color": _AXES_GREY, "xtick.major.size": 4, "ytick.major.size": 4, - "axes.grid": True, - "grid.alpha": 0.3, - "grid.linewidth": 0.5, - "grid.color": "#999999", - "axes.spines.top": True, - "axes.spines.right": True, + "xtick.major.width": 0.6, + "ytick.major.width": 0.6, + "xtick.minor.visible": False, + "ytick.minor.visible": False, + # Lines and markers. + "lines.linewidth": 1.5, + "lines.markersize": 6, + "lines.markeredgewidth": 0.8, + "patch.linewidth": 0.6, + # Legend: square, opaque, thin dark edge. + "legend.frameon": True, + "legend.fancybox": False, + "legend.framealpha": 1.0, + "legend.edgecolor": _AXES_GREY, + "legend.shadow": False, + # Figure and output. "figure.facecolor": "white", - "axes.facecolor": "white", - "text.usetex": False, - # Default colour cycle follows the house palette. - "axes.prop_cycle": cycler( - color=[ - COLORS["BLACK"], - COLORS["RED"], - COLORS["BLUE"], - COLORS["GREEN"], - COLORS["GREY"], - COLORS["ORANGE"], - ] - ), + "figure.dpi": 150, + "savefig.dpi": 300, + "savefig.bbox": "tight", + "savefig.pad_inches": 0.05, + "savefig.facecolor": "white", } def apply_style() -> None: - """Apply the CableXSec house style to the global matplotlib rcParams.""" + """Apply the CableXSec MATLAB-style settings to the global rcParams.""" cast(Any, mpl.rcParams).update(STYLE) @@ -219,7 +304,7 @@ def annotate_provenance( bbox={ "facecolor": "white", "edgecolor": COLORS["GREY"], - "boxstyle": "round,pad=0.25", + "boxstyle": "square,pad=0.25", "alpha": 0.92, "linewidth": 0.5, }, diff --git a/src/cablexsec/plotting/thermal.py b/src/cablexsec/plotting/thermal.py index 5e4b213..4d14838 100644 --- a/src/cablexsec/plotting/thermal.py +++ b/src/cablexsec/plotting/thermal.py @@ -9,6 +9,7 @@ from cablexsec.plotting.style import ( COLORS, FIGSIZE, + LABELS, annotate_provenance, use_style, ) @@ -47,9 +48,7 @@ def plot_temperature_gradient( _, ax = plt.subplots(figsize=FIGSIZE["single"]) r_mm = result.r_m * 1e3 - ax.plot( - r_mm, result.T_C, color=COLORS["BLACK"], lw=1.6, zorder=3, label=r"$T(r)$" - ) + ax.plot(r_mm, result.T_C, color=COLORS["BLUE"], zorder=3, label=r"$T(r)$") if cable is not None: for lyr in cable.layers: @@ -63,25 +62,25 @@ def plot_temperature_gradient( result.T_conductor_C, color=COLORS["RED"], ls="--", - lw=0.9, - label=f"conductor {result.T_conductor_C:.1f} °C", + lw=1.0, + label=rf"conductor {result.T_conductor_C:.1f} $^\circ$C", ) ax.axhline( result.T_armour_C, - color=COLORS["BLUE"], + color=COLORS["ORANGE"], ls="--", - lw=0.9, - label=f"armour {result.T_armour_C:.1f} °C", + lw=1.0, + label=rf"armour {result.T_armour_C:.1f} $^\circ$C", ) - ax.set_xlabel("radius [mm]") - ax.set_ylabel("temperature [°C]") + ax.set_xlabel(LABELS["radius_mm"]) + ax.set_ylabel(LABELS["temperature"]) ax.set_title("Radial temperature gradient") ax.legend(loc="upper right", fontsize=8) lines = [ f"$P$ = {result.P_total_W_m:.1f} W/m", - f"$T_{{cond}}$ = {result.T_conductor_C:.1f} °C", + rf"$T_\mathrm{{cond}}$ = {result.T_conductor_C:.1f} $^\circ$C", ] if current_A is not None: lines.insert(0, f"$I$ = {current_A:.0f} A") @@ -96,7 +95,7 @@ def plot_temperature_gradient( bbox={ "facecolor": "white", "edgecolor": COLORS["GREY"], - "boxstyle": "round,pad=0.3", + "boxstyle": "square,pad=0.3", }, ) annotate_provenance(ax, result.provenance, loc="upper left", max_items=2) diff --git a/tests/test_plotting_style.py b/tests/test_plotting_style.py index a1b00ce..85bfcc5 100644 --- a/tests/test_plotting_style.py +++ b/tests/test_plotting_style.py @@ -10,47 +10,70 @@ matplotlib.use("Agg") # headless backend for CI import matplotlib as mpl # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 from cablexsec.plotting import style # noqa: E402 -EXPECTED_PALETTE = { - "BLACK": "#000000", - "RED": "#CC0000", - "BLUE": "#0000CC", - "GREEN": "#006600", - "GREY": "#666666", - "ORANGE": "#CC6600", -} +#: MATLAB's default ``lines`` colour order (R2014b and later). +MATLAB_LINES = ( + "#0072BD", + "#D95319", + "#EDB120", + "#7E2F8E", + "#77AC30", + "#4DBEEE", + "#A2142F", +) # Test-taxonomy category. pytestmark = pytest.mark.analytical_sanity -def test_palette_exact() -> None: - assert style.COLORS == EXPECTED_PALETTE +def test_colour_order_is_matlab_lines() -> None: + assert style.MATLAB_ORDER == MATLAB_LINES + style.apply_style() + cycle = mpl.rcParams["axes.prop_cycle"].by_key()["color"] + assert tuple(c.upper() for c in cycle) == MATLAB_LINES + +def test_named_colours_are_matlab_hues() -> None: + hues = {k: v for k, v in style.COLORS.items() if k not in ("BLACK", "GREY")} + assert set(hues.values()) == set(MATLAB_LINES) + assert style.COLORS["BLUE"] == MATLAB_LINES[0] -def test_apply_style_sets_rcparams() -> None: + +def test_apply_style_sets_the_matlab_axes() -> None: style.apply_style() - assert mpl.rcParams["font.size"] == 11 - assert mpl.rcParams["savefig.dpi"] == 300 - assert mpl.rcParams["figure.dpi"] == 300 + assert mpl.rcParams["font.family"] == ["sans-serif"] + assert mpl.rcParams["font.sans-serif"][:2] == ["Helvetica", "Arial"] + assert mpl.rcParams["font.size"] == 10 + assert mpl.rcParams["axes.grid"] is False assert mpl.rcParams["xtick.direction"] == "in" assert mpl.rcParams["ytick.direction"] == "in" + assert mpl.rcParams["xtick.top"] is True + assert mpl.rcParams["ytick.right"] is True + assert mpl.rcParams["legend.fancybox"] is False + assert mpl.rcParams["savefig.dpi"] == 300 assert mpl.rcParams["text.usetex"] is False - assert "Times New Roman" in mpl.rcParams["font.serif"] + assert mpl.rcParams["mathtext.fontset"] == "custom" def test_use_style_restores_rcparams() -> None: mpl.rcParams["font.size"] = 7.0 with style.use_style(): - assert mpl.rcParams["font.size"] == 11 + assert mpl.rcParams["font.size"] == 10 assert mpl.rcParams["font.size"] == 7.0 -def test_prop_cycle_uses_palette() -> None: - style.apply_style() - cycle_colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"] - assert cycle_colors[0] == "#000000" - assert set(EXPECTED_PALETTE.values()) == set(cycle_colors) +def test_standard_labels_render_with_symbols() -> None: + """Every standard label is valid mathtext and keeps numerals upright.""" + with style.use_style(): + fig, ax = plt.subplots() + for text in style.LABELS.values(): + ax.set_xlabel(text) + fig.canvas.draw() # raises on invalid mathtext + plt.close(fig) + assert r"\kappa" in style.LABELS["curvature"] + assert r"m$^{\mathrm{-1}}$" in style.LABELS["curvature"] + assert "1/m" not in "".join(style.LABELS.values()) diff --git a/validation/validation_report.md b/validation/validation_report.md index 845780a..5bec003 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -79,7 +79,7 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1318 passed` +- analytical_sanity: `1319 passed` - independent_method: `92 passed` - full_scale: `59 passed`