Source code for xgc_analysis.analysis.transport.neoclassical_plots

"""Plot and explicitly save neoclassical transport comparisons."""

from __future__ import annotations

from pathlib import Path
import numpy as np

from xgc_analysis.analysis.plot_data import PlotData, PlotDataCollection, PlotVariable

from .neoclassical import E_CHARGE, NeoResult, PLOT_GROUPS, PROFILE_INFO, XGC_UNCERTAINTY


_CURVE_LABELS = {
    "jpar_plasma": "XGC", "jpar_efit": "EFIT", "jboot_sauter": "Sauter",
    "sauter_total": "Sauter + Ohmic", "xgc_bootstrap_estimate": "XGC bootstrap estimate",
    "hh_bootstrap": "Hinton–Hazeltine bootstrap", "jpar_plasma_hh": "Hinton–Hazeltine",
    "ptl_flux_HH": "Hinton–Hazeltine", "heatflux_i_CH": "Chang–Hinton",
    "heatflux_e_HH": "Hinton–Hazeltine", "energy_flux_hh": "Hinton–Hazeltine",
    "D_HH": "Hinton–Hazeltine", "chi_i_ch": "Chang–Hinton",
    "chi_e_hh": "Hinton–Hazeltine",
}
_DERIVED_INFO = {
    "sauter_total": ("Sauter bootstrap plus Ohmic parallel current", "A m^-2", r"j_{\parallel,\mathrm{S+Ohm}}"),
    "xgc_bootstrap_estimate": ("XGC bootstrap-current estimate after Ohmic subtraction", "A m^-2", r"j_{\parallel,\mathrm{XGC-Ohm}}"),
    "hh_bootstrap": ("Hinton–Hazeltine bootstrap current after Ohmic subtraction", "A m^-2", r"j_{\parallel,\mathrm{HH-Ohm}}"),
    "energy_flux_hh": ("Hinton–Hazeltine electron energy flux", "W m^-2", r"Q_{e,\mathrm{HH}}"),
}
_DERIVED_INPUTS = {
    "sauter_total": ("jboot_sauter", "jpar_ohmic"),
    "xgc_bootstrap_estimate": ("jpar_plasma", "jpar_ohmic"),
    "hh_bootstrap": ("jpar_plasma_hh", "jpar_ohmic_hh"),
    "energy_flux_hh": ("heatflux_e_HH", "T_e", "ptl_flux_HH"),
}
_SYMBOLS = {
    "psi_pol_norm": r"\psi_{N}", "jpar_plasma": r"j_{\parallel,\mathrm{XGC}}",
    "jpar_efit": r"j_{\parallel,\mathrm{EFIT}}", "jboot_sauter": r"j_{\mathrm{boot,S}}",
    "jpar_plasma_hh": r"j_{\parallel,\mathrm{HH}}", "ptl_flux_e": r"\Gamma_{e}",
    "ptl_flux_HH": r"\Gamma_{e,\mathrm{HH}}", "D_eff": r"D_{e}", "D_HH": r"D_{\mathrm{HH}}",
    "heatflux_i": r"q_{i}", "heatflux_e": r"q_{e}", "heatflux_i_CH": r"q_{i,\mathrm{CH}}",
    "heatflux_e_HH": r"q_{e,\mathrm{HH}}", "enflux_i_gc": r"Q_{i}", "enflux_e": r"Q_{e}",
    "chi_i": r"\chi_{i}", "chi_e": r"\chi_{e}", "chi_i_ch": r"\chi_{i,\mathrm{CH}}",
    "chi_e_hh": r"\chi_{e,\mathrm{HH}}",
}


[docs] def neoclassical_plot_data(result: NeoResult, quantity: str, *, xlim=None, ylim=None, show_uncertainty: bool = True, uncertainty_sigma: float = 1.0, source_uri: str | None = None) -> PlotData: """Select and describe every array actually used by one neoclassical plot. Derived curves and temporal-spread bounds are calculated here so the figure, standalone dictionary, and BP sidecar share identical data. Parameters ---------- result Computed neoclassical profiles and averaging provenance. quantity One key from ``PLOT_GROUPS``. xlim, ylim Optional axis bounds; these alter the view, not the stored curve extent. show_uncertainty, uncertainty_sigma Whether to display a band and its standard-deviation multiplier. source_uri Optional run directory or ACA URI supplied by the caller. Returns ------- PlotData Named coordinate, selected curves, and displayed uncertainty arrays. """ if quantity not in PLOT_GROUPS: raise KeyError(f"Unknown neoclassical plot quantity: {quantity}") if not np.isfinite(uncertainty_sigma) or uncertainty_sigma < 0: raise ValueError("Uncertainty width must be a finite nonnegative sigma multiple") title, _, order = PLOT_GROUPS[quantity] psi = np.asarray(result.profiles["psi_pol_norm"]) description, units = PROFILE_INFO["psi_pol_norm"] variables = { "psi_pol_norm": PlotVariable(psi, description, "psi_pol_norm", _SYMBOLS["psi_pol_norm"], units, ("psi_pol_norm",), "coordinate") } derived = { "sauter_total": lambda: result.profiles["jboot_sauter"] + result.profiles["jpar_ohmic"], "xgc_bootstrap_estimate": lambda: result.profiles["jpar_plasma"] - result.profiles["jpar_ohmic"], "hh_bootstrap": lambda: result.profiles["jpar_plasma_hh"] - result.profiles["jpar_ohmic_hh"], "energy_flux_hh": lambda: result.profiles["heatflux_e_HH"] + 2.5*E_CHARGE*result.profiles["T_e"]*result.profiles["ptl_flux_HH"], } selected = [] for name in order: if name not in result.profiles and ( name not in derived or not all(dep in result.profiles for dep in _DERIVED_INPUTS[name])): continue values = np.asarray(result.profiles[name] if name in result.profiles else derived[name]()) if values.shape != psi.shape: raise ValueError(f"{name} has shape {values.shape}; expected {psi.shape}") long_name, units = PROFILE_INFO[name] if name in PROFILE_INFO else _DERIVED_INFO[name][:2] symbol = _SYMBOLS[name] if name in _SYMBOLS else _DERIVED_INFO[name][2] variables[name] = PlotVariable(values, long_name, name, symbol, units, ("psi_pol_norm",), "curve", _CURVE_LABELS.get(name, "XGC")) selected.append(name) sigma_name = XGC_UNCERTAINTY.get(name) if show_uncertainty and uncertainty_sigma > 0 and result.sample_count > 1 and sigma_name in result.profiles: sigma = np.asarray(result.profiles[sigma_name]) if sigma.shape != psi.shape: raise ValueError(f"{sigma_name} has shape {sigma.shape}; expected {psi.shape}") sigma_long_name, _ = PROFILE_INFO[sigma_name] variables[f"{name}_sigma"] = PlotVariable( sigma, sigma_long_name, f"{name}_sigma", rf"\sigma\left({symbol}\right)", units, ("psi_pol_norm",), "standard_deviation", related_to=name) width = uncertainty_sigma*sigma for suffix, bound, role in (("lower", values-width, "band_lower"), ("upper", values+width, "band_upper")): variables[f"{name}_band_{suffix}"] = PlotVariable( bound, f"{suffix.capitalize()} bound of displayed temporal spread for {name}", f"{name}_band_{suffix}", symbol, units, ("psi_pol_norm",), role, related_to=name) if not selected: raise ValueError(f"No profiles available for neoclassical quantity {quantity}") metadata = { "analysis": "neoclassical_transport", "quantity": quantity, "title": title, "curve_order": selected, "source_product": result.source, "source_uri": source_uri, "gstep_range": list(result.gstep_range), "time_range_s": list(result.time_range_s), "sample_count": result.sample_count, "flux_surface_average": result.fsa, "smoothing_sigma_surfaces": result.smoothing_sigma_surfaces, "denominator_smoothing_sigma_surfaces": result.denominator_smoothing_sigma_surfaces, "current_drive": result.current_drive, "plot_options": { "xlim": list(xlim) if xlim is not None else None, "ylim": list(ylim) if ylim is not None else None, "show_uncertainty": bool(show_uncertainty), "uncertainty_sigma": float(uncertainty_sigma), }, } return PlotData(variables, metadata)
[docs] def neoclassical_transport_data(result: NeoResult, *, show_uncertainty: bool = True, uncertainty_sigma: float = 1.0, source_uri: str | None = None) -> PlotDataCollection: """Collect every available neoclassical plot in one exportable result. Each view uses :func:`neoclassical_plot_data`, so derived curves and temporal-spread arrays match the individual figure sidecars. Shared coordinates and curves are stored once in dictionary and BP exports. Parameters ---------- result Computed neoclassical profiles and averaging provenance. show_uncertainty, uncertainty_sigma Whether to include displayed temporal-spread bands and their width. source_uri Optional run directory or ACA URI supplied by the caller. Returns ------- PlotDataCollection All available plot views with named variables and per-view metadata. """ return PlotDataCollection({ quantity: neoclassical_plot_data( result, quantity, show_uncertainty=show_uncertainty, uncertainty_sigma=uncertainty_sigma, source_uri=source_uri) for quantity in PLOT_GROUPS if any(name in result.profiles or (name in _DERIVED_INPUTS and all(dep in result.profiles for dep in _DERIVED_INPUTS[name])) for name in PLOT_GROUPS[quantity][2]) })
[docs] def plot_neoclassical_plot_data(plot_data: PlotData): """Make a neoclassical Figure from the same arrays written to its BP sidecar. Parameters ---------- plot_data View selected by :func:`neoclassical_plot_data`. Returns ------- matplotlib.figure.Figure Figure owned by the caller. """ from matplotlib import pyplot as plt metadata = plot_data.metadata psi = plot_data.variables["psi_pol_norm"].values fig, ax = plt.subplots(figsize=(8.5, 6.375)) for name in metadata["curve_order"]: variable = plot_data.variables[name] line, = ax.plot(psi, variable.values, label=variable.display_label, linewidth=2) lower = plot_data.variables.get(f"{name}_band_lower") upper = plot_data.variables.get(f"{name}_band_upper") if lower is not None and upper is not None: ax.fill_between(psi, lower.values, upper.values, color=line.get_color(), alpha=0.18, linewidth=0) average_label = " | line FSA" if metadata["flux_surface_average"] == "line" else "" start, end = metadata["gstep_range"] quantity = metadata["quantity"] _, axis_unit, _ = PLOT_GROUPS[quantity] ax.set(xlabel=r"$\psi_N$", ylabel=axis_unit, title=f"{metadata['title']} | gsteps {start}–{end}{average_label}") options = metadata["plot_options"] if options["xlim"] is not None: ax.set_xlim(*options["xlim"]) if options["ylim"] is not None: ax.set_ylim(*options["ylim"]) ax.grid(alpha=.25) ax.legend() fig.tight_layout() return fig
[docs] def plot_neoclassical_transport(result: NeoResult, quantity: str, *, xlim=None, ylim=None, show_uncertainty: bool = True, uncertainty_sigma: float = 1.0): """Plot XGC and analytical curves with optional temporal-spread bands. The band is the selected multiple of the standard deviation across time samples, as in the IDL plots. It is not a standard error or a confidence interval for the time-averaged value. The bootstrap band covers variation in XGC current only, not uncertainty in the modeled Ohmic subtraction. Parameters ---------- result : NeoResult Computed transport comparison. quantity : str One key from the plotted transport quantities. xlim, ylim : pair, optional Axis bounds; ``None`` leaves Matplotlib autoscaling in effect. show_uncertainty : bool Whether to shade temporal spread of the XGC curve. uncertainty_sigma : float Number of temporal standard deviations in the shaded band. Returns ------- matplotlib.figure.Figure Figure ready for display or SVG export. """ plot_data = neoclassical_plot_data( result, quantity, xlim=xlim, ylim=ylim, show_uncertainty=show_uncertainty, uncertainty_sigma=uncertainty_sigma) return plot_neoclassical_plot_data(plot_data)
[docs] def save_neoclassical_svg_plots(result: NeoResult, directory: str | Path, *, quantities=None, show_uncertainty: bool = True, uncertainty_sigma: float = 1.0) -> list[Path]: """Write selected comparison plots as standalone SVG files. Parameters ---------- result Previously computed analysis result. directory Directory where SVG files are written. quantities Optional subset of plot quantity names; all are used by default. show_uncertainty Shade the temporal spread when plotting. uncertainty_sigma Width of the shaded band in standard deviations. Returns ------- list[Path] paths of written SVG plots. """ from matplotlib import pyplot as plt directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) output = [] for quantity in quantities or PLOT_GROUPS: fig = plot_neoclassical_transport(result, quantity, show_uncertainty=show_uncertainty, uncertainty_sigma=uncertainty_sigma) path = directory / f"neoclassical_{quantity}.svg" fig.savefig(path, format="svg") plt.close(fig) output.append(path) return output