Source code for xgc_analysis.analysis.slicing.plotting

"""Reusable mapped R-Z diagnostic plots for XGC monitor and Python workflows."""

from __future__ import annotations

import numpy as np

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


[docs] def mesh_time_map_plot_data(time_map, *, variable: str, description: str = "", units: str = "", source_uri: str | None = None) -> PlotData: """Describe the displayed mesh slice across physics time. Parameters ---------- time_map Computed :class:`MeshSliceTimeMap` with values on time and one spatial axis. variable, description, units Diagnostic key, optional title, and physical field unit. source_uri Optional run directory or ACA URI. Returns ------- PlotData Time and spatial coordinates plus the exact pseudocolor array and selected logical steps. """ coordinate = np.asarray(time_map.coordinate, dtype=float) time_ms = np.asarray(time_map.time_s, dtype=float)*1.0e3 values = np.asarray(time_map.values, dtype=float) if values.shape != (time_ms.size, coordinate.size): raise ValueError("Time-map values do not match their coordinate axes") if not np.any(np.isfinite(values)): raise ValueError("The selected time map has no finite field values") spatial_name = "theta_star_rad" if time_map.coordinate_name == "theta" else "psi_pol_norm" variables = { spatial_name: PlotVariable(coordinate, "Poloidal angle" if spatial_name == "theta_star_rad" else "Normalized poloidal flux", spatial_name, r"\theta^*" if spatial_name == "theta_star_rad" else r"\psi_N", "rad" if spatial_name == "theta_star_rad" else "1", (spatial_name,), "coordinate"), "time_ms": PlotVariable(time_ms, "Physics time", "time_ms", "t", "ms", ("time_ms",), "coordinate"), "field": PlotVariable(values, description or variable, "field", variable.replace("_", r"\_"), units, ("time_ms", spatial_name), "map"), } return PlotData(variables, { "analysis": "mesh_slice_time_map", "quantity": variable, "description": description, "statistic": time_map.statistic, "detail": time_map.detail, "gsteps": np.asarray(time_map.gsteps).tolist(), "source_uri": source_uri, })
[docs] def plot_mesh_time_map( time_map, *, variable, description="", units="", color_bounds=None, coordinate_bounds=None, time_bounds_ms=None, plot_data: PlotData | None = None, ): """Plot a mesh slice over physics time with a normalized-psi or theta-star axis. Parameters ---------- time_map : MeshSliceTimeMap Precomputed spatial slices and their physical times. variable, description, units : str Field label, optional verbose title, and display units. color_bounds, coordinate_bounds, time_bounds_ms : tuple or None Optional color, horizontal, and millisecond axis limits. plot_data : PlotData or None Preselected data for an image sidecar; selected here when omitted. Returns ------- matplotlib.figure.Figure Contour-ready time map rendered as a pseudocolor figure. """ from matplotlib import pyplot as plt view = (plot_data if plot_data is not None else mesh_time_map_plot_data(time_map, variable=variable, description=description, units=units)) field = view.variables["field"] time_ms = view.variables["time_ms"].values coordinate = view.variables[field.dimensions[1]].values values = field.values fig, ax = plt.subplots(figsize=(8, 5.5)) image = ax.pcolormesh( coordinate, time_ms, values, shading="auto", cmap="viridis", vmin=None if color_bounds is None else color_bounds[0], vmax=None if color_bounds is None else color_bounds[1], rasterized=True, ) quantity = (f"RMS({variable} − ⟨{variable}⟩)" if time_map.statistic == "rms" else f"⟨{variable}⟩" if time_map.statistic == "average" else variable) fig.colorbar(image, ax=ax, label=f"{quantity} [{units}]" if units else quantity) ax.set_xlabel(r"$\theta^*$ (rad)" if time_map.coordinate_name == "theta" else r"$\psi_N$") ax.set_ylabel("Time (ms)") if coordinate_bounds is not None: ax.set_xlim(*coordinate_bounds) if time_bounds_ms is not None: ax.set_ylim(*time_bounds_ms) fig.suptitle(f"{description or quantity} — {time_map.detail}") fig.tight_layout() return fig
[docs] def rz_diagnostic_plot_data( plane_data, *, variable: str, description: str = "", units: str = "", view: str = "full", n_int: int = 300, r_bounds=None, z_bounds=None, show_wall: bool = True, show_mesh: bool = False, show_flux: bool = False, source_uri: str | None = None, ) -> PlotDataCollection: """Select radial profile and R-Z raster data used by a diagnostic view. The raster is interpolated with the same triangulation and linear interpolator as :meth:`Plane.plot_contour`; masked pixels are NaN in the dictionary and BP export. Parameters ---------- plane_data Scalar nodal field with its XGC plane geometry. variable, description, units Diagnostic key, optional title, and physical field unit. view Full field, surface average, RMS, residual, or split view. n_int, r_bounds, z_bounds Raster resolution and optional R/Z interpolation limits. show_wall, show_mesh, show_flux Geometry overlays to include with the map view. source_uri Optional run directory or ACA URI. Returns ------- PlotDataCollection One or two views containing the plotted radial profile and/or raster, including selected geometry overlay arrays. """ from matplotlib.tri import LinearTriInterpolator from .mesh_slicing import flux_surface_profile plane = plane_data.plane values = np.asarray(plane_data.get_data(), dtype=float) if values.shape != (plane.n_n,): raise ValueError(f"Expected one value for each of {plane.n_n} mesh vertices; got {values.shape}") if not np.any(np.isfinite(values)): raise ValueError("The selected field has no finite vertex values") if not 2 <= n_int <= 2048: raise ValueError("R-Z grid resolution must be between 2 and 2048 points per axis") if view not in {"full", "average", "rms", "residual", "split"}: raise ValueError(f"Unknown R-Z diagnostic view: {view}") metadata = {"analysis": "rz_diagnostic", "quantity": variable, "description": description, "units": units, "selected_view": view, "raster_resolution": int(n_int), "r_bounds": list(r_bounds) if r_bounds is not None else None, "z_bounds": list(z_bounds) if z_bounds is not None else None, "source_uri": source_uri} plots = {} if view != "full": average = flux_surface_profile(plane_data, "average") profile = flux_surface_profile(plane_data, "rms") if view == "rms" else average mapped = np.asarray(plane.surf_map, dtype=int) if view in {"average", "rms", "split"}: key = "rms" if view == "rms" else "average" variables = { "psi_pol_norm": PlotVariable( np.asarray(plane.psi_surf[mapped]/plane.x_psi), "Normalized poloidal flux", "psi_pol_norm", r"\psi_N", "1", ("psi_pol_norm",), "coordinate"), key: PlotVariable(np.asarray(profile[mapped]), "Flux-surface residual RMS" if key == "rms" else "Flux-surface average", key, r"\sigma" if key == "rms" else r"\langle f\rangle", units, ("psi_pol_norm",), "curve"), } plots[key] = PlotData(variables, {**metadata, "quantity": key, "curve_order": [key]}) if view in {"residual", "split"}: plane_data.flux_avg_to_surf() plane_data.flux_avg_from_surf() field = values - plane_data.flux_avg_plane else: field = values if view not in {"average", "rms"}: tri_data = plane.get_triangulation_data(n_int=n_int, R_bounds=r_bounds, Z_bounds=z_bounds) raster = np.ma.masked_invalid(LinearTriInterpolator(tri_data.triObj, field)(tri_data.RI, tri_data.ZI)) raster_values = np.asarray(np.ma.filled(raster, np.nan)) if not np.any(np.isfinite(raster_values)): raise ValueError("The selected R-Z interpolation grid contains no finite data") map_variables = { "R_m": PlotVariable(np.asarray(tri_data.RI[0, :]), "Major radius", "R_m", "R", "m", ("R_m",), "coordinate"), "Z_m": PlotVariable(np.asarray(tri_data.ZI[:, 0]), "Vertical position", "Z_m", "Z", "m", ("Z_m",), "coordinate"), "field": PlotVariable(raster_values, description or variable, "field", variable.replace("_", r"\_"), units, ("Z_m", "R_m"), "map"), } if show_wall and hasattr(plane, "wall_nodes"): wall = plane.rz[np.asarray(plane.wall_nodes, dtype=int)] if len(wall) >= 2: if not np.allclose(wall[0], wall[-1]): wall = np.vstack((wall, wall[0])) for index, axis in enumerate(("R", "Z")): name = f"wall_{axis}_m" map_variables[name] = PlotVariable( wall[:, index], f"Wall outline {axis} coordinate", name, axis, "m", ("wall_point",), "overlay") if show_mesh: for index, axis in enumerate(("R", "Z")): name = f"mesh_{axis}_m" map_variables[name] = PlotVariable( np.asarray(plane.rz[:, index]), f"Mesh vertex {axis} coordinate", name, axis, "m", ("mesh_vertex",), "overlay") map_variables["mesh_triangles"] = PlotVariable( np.asarray(plane.nd_connect_list), "Mesh triangle vertex indices", "mesh_triangles", "i", "1", ("mesh_triangle", "triangle_vertex"), "overlay") if show_flux: for index, surface in enumerate(plane.surface_plot_paths): points = plane.rz[surface] for axis_index, axis in enumerate(("R", "Z")): name = f"flux_surface_{index}_{axis}_m" map_variables[name] = PlotVariable( points[:, axis_index], f"Flux surface {index} {axis} coordinate", name, axis, "m", (f"flux_surface_{index}_point",), "overlay") map_key = "full" if view == "full" else "residual" plots[map_key] = PlotData(map_variables, { **metadata, "quantity": map_key, "show_wall": show_wall, "show_mesh": show_mesh, "show_flux": show_flux, }) return PlotDataCollection(plots)
[docs] def plot_rz_diagnostic( plane_data, *, variable: str, description: str = "", units: str = "", split_average: bool = False, view: str | None = None, n_int: int = 300, r_bounds=None, z_bounds=None, color_bounds=None, residual_color_bounds=None, profile_psi_bounds=None, profile_value_bounds=None, show_wall: bool = True, show_mesh: bool = False, show_flux: bool = False, plot_data: PlotDataCollection | None = None, ): """Plot a full field, mapped radial mean or RMS, or its R-Z residual. ``plane_data`` must hold one scalar per vertex. The surface average and residual use its existing flux-surface conversion methods. Radial views select the outer-midplane surfaces in ``Plane.surf_map``. ``view`` also accepts ``split`` for existing Python callers; the GUI presents the average and residual as separate choices. R-Z fields are mapped to the same interpolated bitmap grid exported by :func:`rz_diagnostic_plot_data`. Parameters ---------- plane_data One scalar value per mesh vertex, with its Plane geometry. variable Display name or variable key for plot labeling. description Optional descriptive color-scale label. units Physical units for plot labeling. split_average Legacy switch for a combined average-and-residual view. view Named plot view. n_int Number of R-Z raster grid points per axis. r_bounds Optional R-axis bounds in meters. z_bounds Optional Z-axis bounds in meters. color_bounds Optional field color limits. residual_color_bounds Optional residual color limits. profile_psi_bounds Optional normalized-psi axis limits. profile_value_bounds Optional profile-value axis limits. show_wall Draw the wall outline. show_mesh Draw triangular mesh edges. show_flux Draw ordered flux-surface paths. plot_data Preselected views for an image sidecar; selected here when omitted. Returns ------- matplotlib.figure.Figure rendered R-Z field or surface profile. """ from matplotlib import pyplot as plt from xgc_analysis.mesh.plotting import plot_grid_contour view = view or ("split" if split_average else "full") collection = plot_data if plot_data is not None else rz_diagnostic_plot_data( plane_data, variable=variable, description=description, units=units, view=view, n_int=n_int, r_bounds=r_bounds, z_bounds=z_bounds, show_wall=show_wall, show_mesh=show_mesh, show_flux=show_flux) if view == "split": fig, (line_ax, rz_ax) = plt.subplots(1, 2, figsize=(12, 5.5), gridspec_kw={"width_ratios": [1, 1.3]}) elif view in {"average", "rms"}: fig, line_ax = plt.subplots(figsize=(7, 5.5)) else: fig, rz_ax = plt.subplots(figsize=(7, 5.5)) if view in {"average", "rms", "split"}: key = "rms" if view == "rms" else "average" profile = collection.plots[key] line_ax.plot(profile.variables["psi_pol_norm"].values, profile.variables[key].values, linewidth=1.7) line_ax.set_xlabel(r"$\psi_N$") quantity = f"RMS({variable} − ⟨{variable}⟩)" if view == "rms" else f"⟨{variable}⟩" line_ax.set_ylabel(f"{quantity} [{units}]" if units else quantity) line_ax.set_title("Poloidal residual RMS" if view == "rms" else "Flux-surface average") line_ax.grid(alpha=0.25) if profile_psi_bounds is not None: line_ax.set_xlim(*profile_psi_bounds) if profile_value_bounds is not None: line_ax.set_ylim(*profile_value_bounds) if view not in {"average", "rms"}: map_view = collection.plots["full" if view == "full" else "residual"] variables = map_view.variables color_label = variable if view == "full" else f"{variable} − ⟨{variable}⟩" color_label = f"{color_label} [{units}]" if units else color_label bounds = color_bounds if view == "full" else residual_color_bounds plot_grid_contour( np.ma.masked_invalid(variables["field"].values), *np.meshgrid(variables["R_m"].values, variables["Z_m"].values), x_label="R (m)", y_label="Z (m)", var_name=color_label, title="R-Z field" if view == "full" else "R-Z residual", lower=None if bounds is None else bounds[0], upper=None if bounds is None else bounds[1], ax=rz_ax, render_as_image=True, cmap="viridis") if show_mesh: rz_ax.triplot(variables["mesh_R_m"].values, variables["mesh_Z_m"].values, variables["mesh_triangles"].values, linewidth=0.12, color="#263238", alpha=0.35) if "wall_R_m" in variables: rz_ax.plot(variables["wall_R_m"].values, variables["wall_Z_m"].values, color="#cc4b37", linewidth=1.1) if show_flux: indices = sorted({int(name.split("_")[2]) for name in variables if name.startswith("flux_surface_")}) for index in indices: rz_ax.plot(variables[f"flux_surface_{index}_R_m"].values, variables[f"flux_surface_{index}_Z_m"].values, color="#f4d03f", linewidth=0.55, alpha=0.75) if view not in {"average", "rms"}: if r_bounds is not None: rz_ax.set_xlim(*r_bounds) if z_bounds is not None: rz_ax.set_ylim(*z_bounds) fig.suptitle(description or variable) fig.tight_layout() return fig
[docs] def mesh_slice_plot_data( plane_data, *, view: str, variable: str, description: str = "", units: str = "", mesh_data=None, surface_indices=(), surface_index=0, n_theta=256, n_psi=256, psi_bounds=(0.1, 1.05), remove_fsa=False, line_psi_data=None, line_origin=None, line_r0=None, line_z0=None, line_slope=0.0, line_angle_deg=None, line_xaxis="R", line_points=500, line_end_ignore=5, source_uri: str | None = None, ) -> PlotData: """Select curves, maps, and strike overlays for one mesh-slice view. Parameters ---------- plane_data Scalar nodal field with its XGC plane geometry. view, variable, description, units View selector and field labels. mesh_data Full toroidal mesh values for ``surface_phi``. surface_indices, surface_index, n_theta, n_psi, psi_bounds, remove_fsa Selected surfaces and interpolation controls. line_psi_data, line_origin, line_r0, line_z0, line_slope Poloidal-flux data and line-of-sight origin/direction. line_angle_deg, line_xaxis, line_points, line_end_ignore Additional line-of-sight selection and branch controls. source_uri Optional run directory or ACA URI. Returns ------- PlotData The exact line or map arrays used by the requested mesh slice, with dimensions, units, selection metadata, and strike-line overlays. """ from .mesh_slicing import (line_of_sight, psi_theta_slice, split_line_at_psi_minimum, surface_lines, surface_phi_slice) meta = {"analysis": "mesh_slice", "view": view, "quantity": variable, "description": description, "units": units, "source_uri": source_uri, "surface_indices": list(surface_indices or ()), "surface_index": int(surface_index), "n_theta": int(n_theta), "n_psi": int(n_psi), "psi_bounds": list(psi_bounds)} variables = {} curve_order = [] if view == "surface_lines": if not surface_indices: raise ValueError("Enter at least one zero-based surface index") surface_psi = {} for index, psi_n, theta, values in surface_lines(plane_data, surface_indices): coord_name = f"surface_{index}_theta_star_rad" curve_name = f"surface_{index}_{variable}" variables[coord_name] = PlotVariable( np.asarray(theta), f"Surface {index} poloidal angle", coord_name, r"\theta^*", "rad", (coord_name,), "coordinate") variables[curve_name] = PlotVariable( np.asarray(values), description or variable, curve_name, variable.replace("_", r"\_"), units, (coord_name,), "curve", fr"surface {index}, $\psi_N$={psi_n:.3f}") curve_order.append(curve_name) surface_psi[str(index)] = float(psi_n) meta.update(curve_order=curve_order, surface_psi=surface_psi) elif view in {"surface_phi", "psi_theta"}: if view == "surface_phi": if mesh_data is None: raise ValueError("Theta-phi view requires 3D MeshData") theta, phi, mapped, psi_n = surface_phi_slice(mesh_data, surface_index, n_theta) y_name, y, y_units, y_symbol = "phi_rad", phi, "rad", r"\varphi" meta.update(surface_index=int(surface_index), psi_n=float(psi_n), phi_step=float(mesh_data.mesh.delta_phi)) else: if remove_fsa: from xgc_analysis.mesh import PlaneData plane_data.flux_avg_to_surf() plane_data.flux_avg_from_surf() residual = np.asarray(plane_data.get_data(), dtype=float) - plane_data.flux_avg_plane plane_data = PlaneData(plane_data.plane, data_array=residual) psi, theta, mapped, strike_bounds = psi_theta_slice( plane_data, n_psi=n_psi, n_theta=n_theta, psi_bounds=psi_bounds, theta_domain=(-np.pi, 2*np.pi), return_boundaries=True) y_name, y, y_units, y_symbol = "psi_pol_norm", psi, "1", r"\psi_N" meta.update(remove_fsa=bool(remove_fsa)) if strike_bounds.size: variables["strike_psi_pol_norm"] = PlotVariable( np.asarray(strike_bounds[:, 0]), "SOL strike endpoint normalized flux", "strike_psi_pol_norm", r"\psi_N", "1", ("strike_point",), "overlay") for column in (1, 2): name = f"strike_endpoint_{column}_theta_star_rad" variables[name] = PlotVariable( np.asarray(strike_bounds[:, column]), f"SOL strike endpoint {column} poloidal angle", name, r"\theta^*", "rad", ("strike_point",), "overlay") variables["theta_star_rad"] = PlotVariable( np.asarray(theta), "Poloidal angle", "theta_star_rad", r"\theta^*", "rad", ("theta_star_rad",), "coordinate") variables[y_name] = PlotVariable( np.asarray(y), "Toroidal angle" if view == "surface_phi" else "Normalized poloidal flux", y_name, y_symbol, y_units, (y_name,), "coordinate") variables["field"] = PlotVariable( np.asarray(mapped), description or variable, "field", variable.replace("_", r"\_"), units, (y_name, "theta_star_rad"), "map") meta.update(map_name="field") elif view == "line_of_sight": if line_psi_data is None: raise ValueError("Line-of-sight view requires a nodal psi PlaneData") plane = plane_data.plane if line_origin == "axis": r0, z0 = plane.axis_r, plane.axis_z elif line_origin == "xpoint": r0, z0 = plane.x_r, plane.x_z elif line_origin == "custom": if line_r0 is None or line_z0 is None: raise ValueError("Custom line origin requires both R and Z") r0, z0 = line_r0, line_z0 elif line_origin is None: r0 = plane.axis_r if line_r0 is None else line_r0 z0 = plane.axis_z if line_z0 is None else line_z0 else: raise ValueError("Line origin must be axis, xpoint, or custom") r, z, psi, values = line_of_sight( plane_data, line_psi_data, r0=r0, z0=z0, slope=line_slope, angle_degrees=line_angle_deg, n_points=line_points) if line_xaxis not in {"R", "Z", "psi"}: raise ValueError(f"Unknown line-of-sight x axis: {line_xaxis}") coord = {"R": r, "Z": z, "psi": psi}[line_xaxis] units_x = "1" if line_xaxis == "psi" else "m" symbol_x = r"\psi_N" if line_xaxis == "psi" else line_xaxis if line_xaxis == "psi": toward, away, _ = split_line_at_psi_minimum( psi, values, ignore_end_points=line_end_ignore) branches = (("toward", toward, "Toward minimum ψ_N"), ("away", away, "Away from minimum ψ_N")) else: branches = (("line", (coord, values), ""),) for name, (x, y), label in branches: coord_name = f"{name}_{line_xaxis}" curve_name = f"{name}_{variable}" variables[coord_name] = PlotVariable( np.asarray(x), f"{label or 'Sight line'} coordinate", coord_name, symbol_x, units_x, (coord_name,), "coordinate") variables[curve_name] = PlotVariable( np.asarray(y), description or variable, curve_name, variable.replace("_", r"\_"), units, (coord_name,), "curve", label) curve_order.append(curve_name) meta.update(curve_order=curve_order, line_xaxis=line_xaxis, line_origin={"R_m": float(r0), "Z_m": float(z0)}, line_slope=float(line_slope), line_angle_deg=None if line_angle_deg is None else float(line_angle_deg), line_points=int(line_points), line_end_ignore=int(line_end_ignore)) else: raise ValueError(f"Unknown mesh slice view: {view}") return PlotData(variables, meta)
[docs] def plot_mesh_slice( plane_data, *, view, variable, description="", units="", mesh_data=None, surface_indices=(), surface_index=0, n_theta=256, n_psi=256, psi_bounds=(0.1, 1.05), remove_fsa=False, color_bounds=None, theta_bounds=None, phi_bounds=None, surface_value_bounds=None, line_psi_data=None, line_origin=None, line_r0=None, line_z0=None, line_slope=0.0, line_angle_deg=None, line_xaxis="R", line_points=500, line_end_ignore=5, line_xbounds=None, line_ybounds=None, plot_data: PlotData | None = None, ): """Plot a surface, theta-phi, psi-theta, or line-of-sight mesh slice. The interpolation functions in :mod:`mesh_slicing` are also usable in Python workflows without creating a figure. Parameters ---------- plane_data One scalar value per mesh vertex, with its Plane geometry. view Named plot view. variable Display name or variable key for plot labeling. description Optional descriptive color-scale label. units Physical units for plot labeling. mesh_data Vertex data on all toroidal planes. surface_indices Zero-based indices or collection of selected flux surfaces. surface_index Zero-based selected flux-surface index. n_theta Number of points on the uniform theta-star grid. n_psi Number of points on the uniform normalized-psi grid. psi_bounds Minimum and maximum normalized psi for interpolation. remove_fsa Subtract the flux-surface average before mapping. color_bounds Optional field color limits. theta_bounds Optional theta-star axis limits in radians. phi_bounds Optional toroidal-angle axis limits in radians. surface_value_bounds Optional surface-trace value limits. line_psi_data Poloidal-flux PlaneData for line-of-sight sampling. line_origin Magnetic-axis, X-point, or custom origin selector. line_r0 Custom R coordinate in meters. line_z0 Custom Z coordinate in meters. line_slope Legacy line direction dZ/dR. line_angle_deg Line direction from +R in degrees. line_xaxis R, Z, or normalized psi horizontal axis. line_points Number of sight-line samples. line_end_ignore Endpoint samples excluded from psi-minimum search. line_xbounds Optional sight-line horizontal limits. line_ybounds Optional sight-line value limits. plot_data Preselected data for an image sidecar; selected here when omitted. Returns ------- matplotlib.figure.Figure rendered mesh slice. """ from matplotlib import pyplot as plt data = plot_data if plot_data is not None else mesh_slice_plot_data( plane_data, view=view, variable=variable, description=description, units=units, mesh_data=mesh_data, surface_indices=surface_indices, surface_index=surface_index, n_theta=n_theta, n_psi=n_psi, psi_bounds=psi_bounds, remove_fsa=remove_fsa, line_psi_data=line_psi_data, line_origin=line_origin, line_r0=line_r0, line_z0=line_z0, line_slope=line_slope, line_angle_deg=line_angle_deg, line_xaxis=line_xaxis, line_points=line_points, line_end_ignore=line_end_ignore) quantity = f"{variable} − ⟨{variable}⟩" if view == "psi_theta" and remove_fsa else variable label = f"{quantity} [{units}]" if units else quantity fig, ax = plt.subplots(figsize=(7.5, 5.5)) if view == "surface_lines": for name in data.metadata["curve_order"]: curve = data.variables[name] ax.plot(data.variables[curve.dimensions[0]].values, curve.values, label=curve.display_label) ax.set_xlabel(r"$\theta^*$ (rad)") ax.set_ylabel(label) ax.legend() ax.grid(alpha=0.25) if theta_bounds is not None: ax.set_xlim(*theta_bounds) if surface_value_bounds is not None: ax.set_ylim(*surface_value_bounds) elif view in {"surface_phi", "psi_theta"}: theta = data.variables["theta_star_rad"].values mapped = data.variables["field"].values if view == "surface_phi": phi = data.variables["phi_rad"].values extent = (theta[0], theta[0] + 2*np.pi, phi[0], phi[-1] + data.metadata["phi_step"]) ax.set_ylabel(r"$\phi$ (rad)") ax.set_title(fr"Surface {surface_index}, $\psi_N$={data.metadata['psi_n']:.3f}") if phi_bounds is not None: ax.set_ylim(*phi_bounds) else: psi = data.variables["psi_pol_norm"].values extent = (theta[0], theta[0] + n_theta*(theta[1] - theta[0]), psi[0], psi[-1]) ax.set_ylabel(r"$\psi_N$") image = ax.imshow(mapped, origin="lower", aspect="auto", extent=extent, cmap="viridis", interpolation="nearest", vmin=None if color_bounds is None else color_bounds[0], vmax=None if color_bounds is None else color_bounds[1]) fig.colorbar(image, ax=ax, label=label) if view == "psi_theta" and "strike_psi_pol_norm" in data.variables: from matplotlib import patheffects for column, name in ((1, "SOL strike endpoint 1"), (2, "SOL strike endpoint 2")): line, = ax.plot(data.variables[f"strike_endpoint_{column}_theta_star_rad"].values, data.variables["strike_psi_pol_norm"].values, color="#161616", linestyle="--", linewidth=1.4, label=name, zorder=5) line.set_path_effects([patheffects.withStroke(linewidth=3, foreground="white")]) ax.legend(loc="upper left", fontsize="small") ax.set_xlabel(r"$\theta^*$ (rad)") if theta_bounds is not None: ax.set_xlim(*theta_bounds) elif view == "line_of_sight": xlabel = {"R": "R (m)", "Z": "Z (m)", "psi": r"$\psi_N$"}[line_xaxis] for name in data.metadata["curve_order"]: curve = data.variables[name] ax.plot(data.variables[curve.dimensions[0]].values, curve.values, linewidth=1.6, color="tab:orange" if name.startswith("away_") else "tab:blue" if line_xaxis == "psi" else None, label=curve.display_label or None) if line_xaxis == "psi": ax.legend() ax.set_xlabel(xlabel) ax.set_ylabel(label) ax.grid(alpha=0.25) if line_xbounds is not None: ax.set_xlim(*line_xbounds) if line_ybounds is not None: ax.set_ylim(*line_ybounds) else: plt.close(fig) raise ValueError(f"Unknown mesh slice view: {view}") fig.suptitle(description or variable) fig.tight_layout() return fig