Load derived gyrokinetic quantities

Download and unzip the example bundle, then run the Python script or pgkyl commands below from the extracted directory. In a source checkout, first run python tests/generate_test_data.py to create the small synthetic inputs.

pg.gk.load_quantity and its CLI command gk_load_quantity resolve the source files and compute a named quantity. This example loads three electron quantities at frame 0:

\[v_{t,e} = \sqrt{T_e/m_e}, \qquad \phi_{\mathrm{norm}} = e\phi/T_e, \qquad \rho_e = \frac{\sqrt{m_e T_e}}{|q_e| B}.\]

Temperature is in joules, potential in volts, magnetic field in tesla, mass in kilograms, and charge in coulombs. Thermal speed is in m/s, normalized potential is dimensionless, and Larmor radius is in metres. Here vt uses the convention without a factor of two under the square root.

The generated simulation prefix is gk_quantity_1d_p1. Its sources are:

  • gk_quantity_1d_p1-elc_MaxwellianMoments_0.gkyl: density, parallel flow, and temperature divided by mass; metadata supplies electron mass and charge.

  • gk_quantity_1d_p1-field_0.gkyl: electrostatic potential.

  • gk_quantity_1d_p1-geo_int_bmag.gkyl: frame-independent magnetic field.

Supply species="elc" (CLI: --species elc) for all three requests: even phi_norm needs a species to choose the temperature. The e in its definition is the positive elementary charge. When source metadata lacks mass or charge, pass mass=.../charge=... in Python or --mass .../--charge ... on the CLI, using the simulation’s units.

The synthetic fields are constant within each cell of a p1 modal basis. The script checks the results against their analytic values. Calculations preserve modal DG representation; interpolate supplies point values after the calculation. Python returns a list of datasets, including when only one species and frame are requested. The CLI adds those datasets to the command chain for subsequent operations and plotting.

The website build executes both interfaces and compares all three plots.

Python script

python examples/scripts/12_gk_load_quantity.py
"""Load thermal speed, normalized potential, and Larmor radius by name.

Run ``python tests/generate_test_data.py`` first, then:
    MPLBACKEND=Agg python examples/scripts/12_gk_load_quantity.py

The synthetic electron profiles use SI units, with temperature rising from
20 to 30 eV, potential varying sinusoidally, and magnetic field from 1 to
1.5 T. The MaxwellianMoments file stores [density, upar, T/m], plus electron
mass and charge metadata. All sources share the same 1D grid and p1 basis;
their slopes vanish within each cell, making the nonlinear checks exact.
"""

from __future__ import annotations

import matplotlib

matplotlib.use("Agg")

import numpy as np
from scipy import constants

import postgkyl as pg

from _example_paths import TEST_DATA, prepare_output_dir

OUTPUT_DIR = prepare_output_dir()
NAME = "gk_quantity_1d_p1"
PATH = str(TEST_DATA / "generated")

# Each call returns a list, even for one species and one frame. The loader
# finds the required source files by simulation name, species, and frame.
# Mass and charge come from the moments metadata; for files without them,
# pass mass=... and charge=... in the simulation's unit system.
vt, = pg.gk.load_quantity("vt", "elc", NAME, "0", path=PATH)

# The potential is species independent, but its normalization needs the
# electron temperature, so supply "elc" here too. e is the positive
# elementary charge: phi_norm = e*phi/T_e, even for negative-charge electrons.
phi_norm, = pg.gk.load_quantity("phi_norm",
                                "elc",
                                NAME,
                                "0",
                                path=PATH,
                                label=r"$e\phi/T_e$")

# The magnetic geometry file has no frame suffix and is loaded automatically.
larmor_radius, = pg.gk.load_quantity("larmor_radius",
                                     "elc",
                                     NAME,
                                     "0",
                                     path=PATH)

for quantity, data in (("vt", vt), ("phi_norm", phi_norm), ("larmor_radius",
                                                            larmor_radius)):
  # All arithmetic happens on native modal fields. Interpolate only after
  # computing the quantity, to obtain point values for checking and plotting.
  assert data.ctx["value_form"] == "modal"
  samples = data.interpolate(num_interp=1)
  x = 0.5 * (samples.grid[0][1:] + samples.grid[0][:-1])
  temperature = constants.elementary_charge * (20.0 + 10.0 * x)
  potential = 5.0 * np.sin(2 * np.pi * x)
  bmag = 1.0 + 0.5 * x
  expected = {
      "vt":
      np.sqrt(temperature / constants.electron_mass),
      "phi_norm":
      constants.elementary_charge * potential / temperature,
      "larmor_radius":
      np.sqrt(constants.electron_mass * temperature) /
      (constants.elementary_charge * bmag),
  }
  np.testing.assert_allclose(samples.values.ravel(),
                             expected[quantity],
                             rtol=1e-12,
                             atol=1e-14)
  fig = samples.plot(title=f"Electron {quantity}",
                     xlabel="x [m]",
                     ylabel=data.get_label(),
                     no_show=True)
  fig.savefig(OUTPUT_DIR / f"12_gk_load_quantity_{quantity}.png")

print("12_gk_load_quantity: vt, phi_norm, larmor_radius OK")

Equivalent CLI commands

Run from the extracted example bundle (or repository root). Create an output directory first:

mkdir -p output
pgkyl gk_load_quantity --quantity vt --species elc --name gk_quantity_1d_p1 --frame 0 \
    --path tests/test_data/generated interpolate --num_interp 1 plot --title 'Electron vt' \
    --xlabel 'x [m]' --ylabel '$v_{t,e}$ (m/s)' --no_show --dpi 100 --saveas \
    output/12_gk_load_quantity_vt.png

12_gk_load_quantity_vt.png: Identical pixels (1 frame(s)) and timing.

Python and CLI outputs
Python output for 12_gk_load_quantity_vt.png CLI output for 12_gk_load_quantity_vt.png
pgkyl gk_load_quantity --quantity phi_norm --species elc --name gk_quantity_1d_p1 --frame 0 \
    --path tests/test_data/generated --label '$e\phi/T_e$' interpolate --num_interp 1 plot \
    --title 'Electron phi_norm' --xlabel 'x [m]' --ylabel '$e\phi/T_e$' --no_show --dpi 100 \
    --saveas output/12_gk_load_quantity_phi_norm.png

12_gk_load_quantity_phi_norm.png: Identical pixels (1 frame(s)) and timing.

Python and CLI outputs
Python output for 12_gk_load_quantity_phi_norm.png CLI output for 12_gk_load_quantity_phi_norm.png
pgkyl gk_load_quantity --quantity larmor_radius --species elc --name gk_quantity_1d_p1 \
    --frame 0 --path tests/test_data/generated interpolate --num_interp 1 plot --title \
    'Electron larmor_radius' --xlabel 'x [m]' --ylabel '$\rho_{e}$ (m)' --no_show --dpi 100 \
    --saveas output/12_gk_load_quantity_larmor_radius.png

12_gk_load_quantity_larmor_radius.png: Identical pixels (1 frame(s)) and timing.

Python and CLI outputs
Python output for 12_gk_load_quantity_larmor_radius.png CLI output for 12_gk_load_quantity_larmor_radius.png