Skip to content

User Guide: Publication Diagnostic Plotting (flexmesa.plotting)

Fortran MESA's PGSTAR subsystem relies on PGPLOT and an interactive X11 server to render diagnostic windows during a run. In FlexMESA, the flexmesa.plotting and flexmesa.colors subpackages provide headless, scriptable matplotlib routines styled for astronomical journals (Computer Modern typography, inward ticks on all four axes, frameless legends, and colorblind-safe Okabe-Ito palettes). Every plotting function returns (fig, ax) (or (fig, axes) for multi-panel layouts) so you can customize annotations or save 300 dpi PNG and vector PDF figures directly.


1. Configuring the Journal Plot Style (use_mesa_plot_style, figsize)

Calling plotting.use_mesa_plot_style() applies plotting.mesa_rc_params() globally, while plotting.figsize(layout="single" | "double" | "grid") returns standard journal column dimensions in inches:

from flexmesa import plotting

plotting.use_mesa_plot_style()
rc = plotting.mesa_rc_params()
print(
    f"Single-column figsize = {plotting.figsize('single')}, "
    f"Double-column figsize = {plotting.figsize('double')}, "
    f"xtick.direction = {rc['xtick.direction']!r}"
)

2. Stellar Structure & Evolutionary Track Plots

flexmesa.plotting provides three core functions for single-star structure and evolutionary tracks:

  1. Hertzsprung-Russell Diagram (plotting.plot_hr_diagram): Plots \(\log_{10}(L/L_\odot)\) against inverted \(\log_{10}(T_{\mathrm{eff}}/\mathrm{K})\), optionally coloring points along the track by a third scalar such as central hydrogen fraction \(X_c\) (color_val, vmin, vmax).
  2. Central Temperature-Density Diagram (plotting.plot_tc_rhoc_diagram): Plots \(\log_{10}(T_c/\mathrm{K})\) against \(\log_{10}(\rho_c/\mathrm{g\,cm^{-3}})\) with reference hydrogen, helium, and carbon ignition curves (show_burn_lines=True).
  3. Kippenhahn Convective & Burning History (plotting.plot_kippenhahn): Shades convective, overshooting, semiconvective, and thermohaline zones alongside nuclear energy generation \(\log_{10}(\epsilon_{\mathrm{nuc}})\) in enclosed mass coordinates \(m/M_\odot\) versus stellar age (Myr).
import matplotlib.pyplot as plt
import numpy as np
from flexmesa import plotting, star

model = star.StarModel.from_zams(initial_mass=2.0, initial_z=0.02)
n_steps, n_grid = 5, 80
q_grid = np.linspace(0.01, 1.0, n_grid)

ages_myr, log_teff, log_l, log_rhoc, log_tc, xc = [], [], [], [], [], []
mass_grid = q_grid * 2.0
mix_grid = np.zeros((n_grid, n_steps))
eps_grid = np.zeros((n_grid, n_steps))

for i in range(n_steps):
    if i > 0:
        model.evolve_step(do_remesh=False, use_bcyclic=True)
    row = model.history_row()
    ages_myr.append(row.star_age * 1.0e-6)
    log_teff.append(row.log_teff)
    log_l.append(row.log_l)
    log_rhoc.append(row.log_center_rho)
    log_tc.append(row.log_center_t)
    xc.append(row.center_h1)

    q_inc = np.asarray(model.q)[::-1]
    mix_grid[:, i] = np.interp(q_grid, q_inc, np.asarray(model.mixing_type)[::-1])
    eps_grid[:, i] = np.log10(
        np.maximum(np.interp(q_grid, q_inc, np.asarray(model.eps_nuc)[::-1]), 1.0)
    )

fig1, _ = plotting.plot_hr_diagram(np.array(log_teff), np.array(log_l), color_val=np.array(xc))
plt.close(fig1)

fig2, _ = plotting.plot_tc_rhoc_diagram(np.array(log_rhoc), np.array(log_tc))
plt.close(fig2)

fig3, _ = plotting.plot_kippenhahn(
    np.array(ages_myr), mass_grid, mix_grid, eps_nuc_grid=eps_grid
)
plt.close(fig3)
print("Rendered HR, Tc-rhoc, and Kippenhahn diagnostic figures.")

3. Asteroseismic, Binary & Synthetic Photometry Figures

For asteroseismology, binary evolution, and synthetic photometry, flexmesa.plotting and flexmesa.colors provide four specialized visualization workflows:

  • Propagation Diagram (plotting.plot_propagation_diagram): Plots the Brunt-Väisälä buoyancy frequency \(N(r)\) and Lamb acoustic frequencies \(S_\ell(r) = \sqrt{\ell(\ell+1)}\,c_s(r)/r\) for \(\ell \in \{1, 2\}\) in microhertz (\(\mu\mathrm{Hz}\)) against fractional radius \(r/R_\star\).
  • Echelle Diagram (plotting.plot_echelle_diagram): Plots mode frequencies \(\nu_{n\ell}\) against reduced frequency \(\nu_{n\ell} \bmod \Delta\nu\), overlaying observed error bars, uncorrected adiabatic model frequencies, and surface-corrected model frequencies.
  • Frequency Separation Ratios (plotting.plot_separation_ratios): Plots the 5-point core-probing ratios \(r_{010}(\nu)\) and \(r_{02}(\nu)\) with observational error bars.
  • Binary Evolution Multi-Panel (plotting.plot_binary_evolution): Renders orbital period \(P_{\mathrm{orb}}\), mass-transfer rate \(\log_{10}|\dot{M}_{\mathrm{RLOF}}|\), and eccentricity \(e(t)\) versus binary age.
import matplotlib.pyplot as plt
import numpy as np
from flexmesa import astero, colors, plotting, star

model = star.StarModel.from_zams(initial_mass=1.0, initial_z=0.02)
r_cm = np.asarray(model.r)
cs_cm_s = np.asarray(model.csound)

# 1. Asteroseismic propagation, echelle, and separation-ratio plots
fig_prop, _ = plotting.plot_propagation_diagram(
    r_cm / r_cm[0], np.asarray(model.brunt_n2), cs_cm_s, r_cm, nu_max_uhz=3090.0
)
plt.close(fig_prop)

orders = np.arange(17, 23, dtype=np.float64)
l0_obs = 135.0 * (orders + 1.44)
l1_obs = 135.0 * (orders + 0.50 + 1.42)
l2_obs = l0_obs - 9.0
sigs = np.full_like(l0_obs, 0.2)

fig_ech, _ = plotting.plot_echelle_diagram(
    l0_obs, sigs, delta_nu=135.0, model_freqs_uncorr=l0_obs + 3.0, model_freqs_corr=l0_obs + 0.1
)
plt.close(fig_ech)

r010 = astero.eval_ratios_r01_r10(l0_obs, sigs, l1_obs, sigs)
r02, sig_r02 = astero.eval_ratios_r02(l0_obs, sigs, l1_obs, sigs, l2_obs, sigs)
fig_rat, _ = plotting.plot_separation_ratios(
    l0_obs[1:-1],
    r010["r01"],
    r010["sig_r01"],
    r010_model=r010["r01"],
    freqs_r02=l0_obs[1:],
    r02_obs=r02,
    r02_sigmas=sig_r02,
    r02_model=r02,
)
plt.close(fig_rat)

# 2. Synthetic Kurucz SED and Johnson UBVRIJM photometry
wave_aa, flux_cgs = colors.eval_sed(
    teff=float(model.teff),
    log_g=4.44,
    metallicity=0.0,
    r=float(r_cm[0]),
)
mags_vega = colors.eval_colors(
    teff=float(model.teff),
    log_g=4.44,
    metallicity=0.0,
    r=float(r_cm[0]),
    mag_system="Vega",
)
print(
    f"Kurucz SED ({len(wave_aa)} wavelength bins): "
    f"Johnson V = {float(mags_vega[2]):.3f} mag, B - V = {float(mags_vega[1] - mags_vega[2]):.3f} mag"
)

Synthetic Kurucz SED and Johnson filter curves

Figure 1: Kurucz (2003) synthetic spectral energy distributions at \(T_{\mathrm{eff}} = 5920\,\mathrm{K}\) (\([\mathrm{M/H}] = 0.0\)) and \(T_{\mathrm{eff}} = 5770\,\mathrm{K}\) (\([\mathrm{M/H}] = -0.4\)) with Johnson \(B\), \(V\), \(R\) filter passbands (left), paired with synthetic \((B - V)\) color indices across \(T_{\mathrm{eff}} \in [5760, 5990]\,\mathrm{K}\) at \(\log g = 4.25\) comparing Safe Rust and JAX (right).


4. Saved-Output PGSTAR, Kippenhahn, PGBINARY & Grid Panels (flexmesa plot)

Every file-based diagnostic and comparison builder in flexmesa.plotting reads strictly from saved ASCII outputs (history.data, binary_history.data, profileN.data, bundled MESA 26.4.1 data/star_data/plot_info/*.data guide curves, and stored MESA 26.4.1 references in benchmarks/history_harness/reference_histories/) without recomputing physics inside plotting code (#173). Whenever a reference file is supplied, the figure title or subtitle records the reference provenance alongside the candidate run.

  • Kippenhahn & RTI Evolution Diagrams (plotting.plot_history_kippenhahn, plotting.plot_profile_kippenhahn, plotting.plot_rti_history): Renders convective, overshoot, semiconvective, thermohaline, rotational, Rayleigh-Taylor, and leftover-convective mixing zones, signed nuclear burning and neutrino cooling regions, core mass boundaries (he_core_mass through fe_core_mass), and optional right-axis luminosities across mass, q, or radius versus model_number or star_age (including log_xaxis and time_from_present), plus dedicated Rayleigh-Taylor Instability (rti) tracks from rti_type_*, mix_type_* == 6, or profile mixing_type/alpha_RTI.
  • Radial pgstar Profile & Nucleosynthesis Panels (plotting.pgstar_panels, plotting.pgstar_summary, plotting.pgstar_extra, plotting.pgstar_nucleosyn): Ports TRho_Profile (plotting.plot_trho_profile), 22-category nuclear reaction Power (plotting.plot_power_profile), ranked multi-isotope Abundance (plotting.plot_abundance_profile), log-diffusivity Mixing with all seven rotational diffusion curves (D_ST, D_visc, D_DSI, D_SH, D_SSI, D_ES, D_GSF; plotting.plot_mixing_profile), magnetic and rotational Dynamo (plotting.plot_dynamo_profile), Network chart of nuclides (plotting.plot_network_chart), stable-isotope Production factors (plotting.plot_production_profile), normalized Summary_Profile (plotting.plot_summary_profile), Summary_Burn (plotting.plot_summary_burn_profile), and dual-axis Profile_Panels<N> (plotting.plot_profile_custom_panels).
  • Evolutionary Tracks, Photometric CMDs, Text Summaries & Grid<N> Composer (plotting.pgstar_grid, plotting.pgstar_text, plotting.pgstar_extra): Ports History_Track<N> plus all 14 named two-column presets (plotting.plot_history_track, plotting.plot_dpg_dnu, and pgstar_grid.TRACK_PRESETS, including HR, TRho, TmaxRho, logg_Teff, logg_logT, logL_Teff, and dPg_dnu), Color_magnitude<N> (plotting.plot_color_magnitude, plotting.parse_inlist_cmd_spec), Summary_History (plotting.plot_summary_history), History_Panels<N> (plotting.plot_history_panels), Text_Summary<N> (plotting.plot_text_summary, plotting.plot_pgbinary_text_summary, plotting.parse_inlist_text_summary_spec), and multi-panel Grid<N> layouts (plotting.plot_pgstar_grid and plotting.parse_inlist_grid_spec), including upstream's default Grid1, Grid2, Grid3, and Grid4.
  • Interacting Binary pgbinary Panels (plotting.pgbinary_panels): Ports 2D Keplerian orbit and dimensionless Roche-lobe equipotential snapshots (plotting.plot_pgbinary_orbit), arbitrary component window embedding for Star1/Star2 (plotting.plot_pgbinary_star), normalized Summary_History (plotting.plot_pgbinary_summary_history), binary Text_Summary<N> (plotting.plot_pgbinary_text_summary), and synchronized 6-panel binary diagnostics with donor/accretor HR tracks (plotting.plot_pgbinary_panels).

From the command line, flexmesa plot exposes subcommands for every saved-output and live-watch workflow:

flexmesa plot compare 1.3M_ms_high_Z --out compare_1.3M.png
flexmesa plot compare evolve_both_stars --flexmesa-dir out_binary/ --out compare_bin.png
flexmesa plot profile LOGS/profile1.data --panel trho --out trho_profile1.png
flexmesa plot profile LOGS/profile1.data --panel dynamo --out dynamo_profile1.png
flexmesa plot profile LOGS/profile1.data --panel network --out network_profile1.png
flexmesa plot profile LOGS/profile1.data --panel production --out production_profile1.png
flexmesa plot kipp --history LOGS/history.data --yaxis mass --show-luminosities --out kipp.png
flexmesa plot rti --history LOGS/history.data --out rti.png
flexmesa plot binary --binary-history binary_history.data --out pgbinary_panels.png
flexmesa plot track LOGS/history.data --preset dPg_dnu --out dpg_dnu.png
flexmesa plot cmd LOGS/history.data --x1 abs_mag_B --x2 abs_mag_V --y abs_mag_V --out cmd.png
flexmesa plot text-summary LOGS/history.data --out text_summary.png
flexmesa plot grid --inlist inlist_pgstar --history LOGS/history.data --profile LOGS/profile1.data --out grid1.png
flexmesa plot watch LOGS/ --out-dir live_frames/ --panels HR,TRho,Text_Summary1 --poll-interval 1.0

In Python, call the corresponding builders directly to inspect or customize (fig, ax) / (fig, axes) objects:

import matplotlib.pyplot as plt
from flexmesa import plotting
from flexmesa.testing import case_manifest

ref_root = case_manifest.repo_root() / "benchmarks" / "history_harness" / "reference_histories"
ref_star = ref_root / "star" / "1.3M_ms_high_Z.data"
ref_bin = ref_root / "binary" / "evolve_both_stars.data"

fig_cmp, axes_cmp = plotting.plot_case_comparison(
    "1.3M_ms_high_Z",
    suite="star",
    flexmesa_history=ref_star,
    mesa_history=ref_star,
)
plt.close(fig_cmp)

fig_kipp, _ = plotting.plot_history_kippenhahn(
    ref_star, xaxis="star_age", yaxis="q", log_xaxis=True
)
plt.close(fig_kipp)

fig_trk, _ = plotting.plot_history_track(
    ref_star, preset="HR", ref_history_path=ref_star
)
plt.close(fig_trk)

fig_ts, _ = plotting.plot_text_summary(ref_star)
plt.close(fig_ts)

fig_orb, _ = plotting.plot_pgbinary_orbit(ref_bin)
plt.close(fig_orb)

fig_sum, _ = plotting.plot_pgbinary_summary_history(
    ref_bin, mesa_binary_history=ref_bin
)
plt.close(fig_sum)
print("Rendered comparison, Kippenhahn, track, text-summary, orbit, and binary summary figures:", axes_cmp.shape)

plotting.plot_pgbinary_orbit requires binary_separation, rl_1, and rl_2 plus orbital eccentricity information. When eccentricity is present in binary_history.data, it is read directly. When eccentricity is omitted (the upstream default in binary/defaults/binary_history_columns.list), plot_pgbinary_orbit recovers the exact Keplerian eccentricity from J_orb, star_1_mass, star_2_mass, and binary_separation (binary/private/binary_utils.f90:190-191) without assuming a circular orbit. If neither eccentricity nor J_orb is available, plot_pgbinary_orbit raises MissingOrbitColumnsError and the 6-panel plotting.plot_pgbinary_panels figure notes in its orbit cell that the orbit was not drawn. Kippenhahn mixing zones are shaded only from the mix_type_* history columns; a history without them shows none.

plotting.render_case_panels(inlist_paths, history_path=..., profile_path=..., out_dir=...) draws every panel that a case's &pgstar or &pgbinary settings enable (<Panel>_win_flag or <Panel>_file_flag set to .true.), one figure per panel, with Grid<N> windows keeping their row and column layout. plotting.enabled_panels lists them without drawing, and plotting.case_inlist_paths(case_dir) collects a test-suite case's inlist* files. Layout and styling are approximate. A panel that cannot be drawn is never dropped silently: each PanelResult carries a status (rendered, partial, unavailable, or unsupported) with the reason, the figure (or the failed Grid<N> cell) shows a "column or data not available" note, and strict=True raises PanelUnavailableError instead. The test-suite panel counts that order this work are in notes/audit/pgstar_inventory_26_4_1.md.


5. Live-Evolution Plotting (LiveEvolutionPlotter & watch_logs)

To emit updated figures while an evolution runs without X11 or PGPLOT, attach plotting.LiveEvolutionPlotter as an extras object (implementing extras_startup, extras_finish_step, and extras_after_evolve for single stars, plus extras_binary_startup, finish_step, and extras_binary_after_evolve for binaries) or poll an active LOGS/ directory with plotting.watch_logs (or flexmesa plot watch). Every frame is written atomically via temporary file rename (with an optional frame_latest.png copy), and each Matplotlib figure is closed inside a finally block so long runs leak zero figures:

import pathlib
import shutil
import tempfile
from flexmesa import plotting
from flexmesa.testing import case_manifest

ref_star = (
    case_manifest.repo_root()
    / "benchmarks"
    / "history_harness"
    / "reference_histories"
    / "star"
    / "1.3M_ms_high_Z.data"
)

with tempfile.TemporaryDirectory() as tmp:
    logs_dir = pathlib.Path(tmp) / "LOGS"
    out_dir = pathlib.Path(tmp) / "frames"
    logs_dir.mkdir(parents=True)
    shutil.copyfile(ref_star, logs_dir / "history.data")

    plotter = plotting.LiveEvolutionPlotter(
        out_dir,
        logs_dir=logs_dir,
        panels=("HR", "TRho", "Text_Summary1"),
        file_cnt=1,
        dpi=100,
    )
    assert plotter.extras_finish_step({"model_number": 1}) == "keep_going"
    print(f"Emitted {len(plotter.frames)} live frame(s), latest={plotter.frames[0].latest_path.name}")

For the full mapping of upstream pgstar.defaults, pgbinary.defaults, and astero_pgstar.defaults windows (pgstar_coverage.build_pgstar_coverage_report) onto flexmesa.plotting builders, see the PGSTAR & PGBINARY Coverage Report and the I/O, Plotting & Benchmark API Reference.