emout.utils package

Submodules

emout.utils.eflux module

Energy-flux computation and pitch-angle classification library. Energies are handled in eV.

emout.utils.eflux.compute_energy_flux_histogram(velocities, probs, mass, energy_bins)[source]

Compute an energy-flux histogram.

Parameters:
  • velocities (np.ndarray) – Particle velocity array.

  • probs (np.ndarray) – Weight (probability / contribution) array for each particle.

  • mass (float) – Particle mass [kg].

  • energy_bins (Union[int, np.ndarray]) – Histogram bin specification. An integer sets the number of bins; an array sets the bin edges explicitly.

Returns:

Tuple of (hist, bin_edges).

Return type:

object

emout.utils.eflux.compute_energy_flux_histograms(velocities, probs, B, mass, energy_bins, pitch_ranges=None)[source]

Compute energy x energy-flux histograms for user-specified pitch-angle ranges and directions, from velocity vectors and a probability array. Energies are computed in eV.

Parameters:
  • velocities (np.ndarray) – Velocity vectors for each particle (m/s), shaped (N, 3). N is the number of samples.

  • probs (np.ndarray) – Probability or weight corresponding to each velocity vector, shaped (N,).

  • B (np.ndarray) – Magnetic field vector (T) or direction vector, shaped (3,).

  • mass (float) – Particle mass (kg).

  • energy_bins (int or np.ndarray) –

    • int: let numpy.histogram auto-generate bin edges.

    • np.ndarray: use these bin edges directly, shaped (M+1,).

  • pitch_ranges (list of (a_deg, b_deg, direction) | None) – List specifying pitch-angle ranges and directions. Each tuple has the form (a_deg, b_deg, direction) where direction is one of 'both', 'pos', 'neg'. If None, the default 6-class decomposition is used.

Returns:

histograms – Keys have the format f"{a_deg:02d}-{b_deg:02d}_{direction}". Values are (hist, bin_edges) tuples where: - hist: total energy flux (eV x v x prob) per bin, shaped (M,) - bin_edges: bin boundaries in eV, shaped (M+1,)

Return type:

dict[str, (hist, bin_edges)]

emout.utils.eflux.get_indices_in_pitch_range(velocities, B, a_deg, b_deg, direction='both')[source]

Return the indices of particles whose pitch angle falls within [a_deg, b_deg].

Parameters:
  • velocities (np.ndarray) – Velocity vectors for each particle (m/s), shaped (N, 3). N is the number of samples.

  • B (np.ndarray) – Magnetic field vector (T) or direction vector, shaped (3,). Must be non-zero.

  • a_deg (float) – Lower bound of the pitch angle (degrees). 0 <= a_deg < b_deg <= 180.

  • b_deg (float) – Upper bound of the pitch angle (degrees).

  • direction (str, default='both') –

    Sign direction of the pitch angle:
    • ’both’: all particles regardless of the sign of v dot B

    • ’pos’ : only particles with v dot B > 0 (parallel to B)

    • ’neg’ : only particles with v dot B < 0 (anti-parallel to B)

Returns:

idx – Index array of particles satisfying the angle range and direction condition.

Return type:

np.ndarray

emout.utils.eflux.plot_energy_flux(velocities, probs, B, mass, energy_bins, pitch_ranges=None, cmap='plasma')[source]

Plot the energy x energy-flux distribution for all particles and for each specified pitch-angle range, overlaid on a single axis. Energies are computed in eV.

Parameters:
  • velocities (np.ndarray) – Velocity vectors for each particle (m/s), shaped (N, 3). N is the number of samples.

  • probs (np.ndarray) – Probability or weight corresponding to each velocity vector, shaped (N,).

  • B (np.ndarray) – Magnetic field vector (T) or direction vector, shaped (3,).

  • mass (float) – Particle mass (kg).

  • energy_bins (int or np.ndarray) –

    • int: let numpy.histogram auto-generate bin edges.

    • np.ndarray: use these bin edges directly, shaped (M+1,).

  • pitch_ranges (list of (a_deg, b_deg, direction) | None) – Pitch-angle ranges and direction specifier list. None uses the default 6-class decomposition.

  • cmap (str, default='plasma') – Matplotlib colourmap name.

Returns:

fig, ax – The created Figure and Axes.

Return type:

matplotlib.figure.Figure, matplotlib.axes.Axes

emout.utils.eflux.plot_energy_fluxes(velocities_list, x, mass, energy_bins, use_probs=False, probs_list=None, cmap='viridis')[source]

Plot a 2-D heatmap (x vs Energy, colour scale = energy flux) from velocity vector lists across multiple series. The energy flux for each series is histogrammed as the sum of eV x v x (prob).

Parameters:
  • velocities_list (list[np.ndarray]) – List of length T, each element a velocity array of shape (NT, 3).

  • x (np.ndarray) – x-axis values corresponding to each velocity list, shaped (T,).

  • mass (float) – Particle mass (kg).

  • energy_bins (int or np.ndarray) –

    • int: let numpy.histogram auto-generate bin edges across all series.

    • np.ndarray: use these bin edges directly, shaped (M+1,).

  • use_probs (bool, default=False) – If True, read per-series probabilities from probs_list and include them in the energy-flux weights. If False, assume probs = np.ones(NT) (weight = eV x v only).

  • probs_list (list[np.ndarray] | None, default=None) – List of length T, each element a probability array of shape (NT,). Required when use_probs=True.

  • cmap (str, default='viridis') – Matplotlib colourmap name.

Returns:

fig, ax – The created Figure and Axes.

Return type:

matplotlib.figure.Figure, matplotlib.axes.Axes

emout.utils.emsesinp module

Parser for EMSES plasma.inp namelist files.

InpFile reads Fortran namelist parameters via f90nml and exposes them as attributes, handling sparse-array indexing and the !!key unit-conversion header.

class emout.utils.emsesinp.AttrDict(*args, **kwargs)[source]

Bases: dict

Dictionary subclass that supports attribute-style access.

class emout.utils.emsesinp.InpFile(filename=None, convkey=None)[source]

Bases: object

Manage an EMSES parameter file.

nmlf90nml.Namelist

Namelist object.

conversion(unit_from, unit_to)[source]

Apply unit conversion to relevant parameters.

Parameters:
  • unit_from (Units) – Source unit system.

  • unit_to (Units) – Target unit system.

Returns:

No return value.

Return type:

None

property dx: float

Return the conversion key dx.

Returns:

Grid width from the conversion key.

Return type:

float

remove(key, index=None)[source]

Remove a parameter.

Parameters:
  • key (str) – Group name (&groupname) or parameter name.

  • index (int, optional) – If given, remove only the element at this index.

save(filename, convkey=None)[source]

Save the parameters to a file.

Parameters:
  • filename (str or Path) – Output file path.

  • convkey (UnitConversionKey, optional) – Unit conversion key to write, by default None.

setlist(group, name, value, start_index=1)[source]

Set a list-type parameter.

Parameters:
  • group (str) – Group name (&groupname).

  • name (str) – Parameter name.

  • value (type or list(type)) – Value(s) to set.

  • start_index (int, optional) – Starting index for the list, by default 1.

property to_c: float

Return the conversion key to_c.

Returns:

Speed of light in EMSES units from the conversion key.

Return type:

float

class emout.utils.emsesinp.UnitConversionKey(dx, to_c)[source]

Bases: object

Unit conversion key.

dx

Grid width [m].

Type:

float

to_c

Speed of light in EMSES units.

Type:

float

property keytext

Return the string representation of the conversion key.

Returns:

String representation of the conversion key.

Return type:

str

classmethod load(filename)[source]

Load a unit conversion key from a file.

Read dx and to_c from the first line of the file if it matches the format !!key dx=[1.0],to_c=[10000.0].

Parameters:

filename (str or Path) – File containing the unit conversion key.

Returns:

Unit conversion key, or None if the header is absent.

Return type:

UnitConversionKey or None

emout.utils.group module

Generic grouping container with element-wise attribute delegation.

class emout.utils.group.Group(objs, attrs=None)[source]

Bases: object

Container that applies operations element-wise to a list of objects.

filter(predicate)[source]

Return a new Group containing only elements that satisfy the predicate.

Parameters:

predicate (object) – Function that decides whether to keep an element.

Returns:

New Group containing the filtered elements.

Return type:

object

foreach(callable)[source]

Apply a function to each element for its side effects.

Parameters:

callable (object) – Function to apply to each element.

Returns:

No return value.

Return type:

None

map(callable)[source]

Apply a function to each element and return a new Group.

Parameters:

callable (object) – Function to apply to each element.

Returns:

New Group containing the results.

Return type:

object

emout.utils.poisson module

Poisson-equation solver with configurable boundary conditions.

Provides the poisson() entry point and boundary-condition classes (PeriodicPoissonBoundary, DirichletPoissonBoundary, NeumannPoissonBoundary) for 1-D / 2-D / 3-D grids.

class emout.utils.poisson.DirichletPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

Fixed-value (Dirichlet) boundary condition for the Poisson solver.

correct_boundary_values(phi)[source]

Correct boundary values by assigning the fixed Dirichlet values.

Parameters:

phi (np.ndarray) – Potential array.

Returns:

No return value.

Return type:

None

property fft_backward: Callable[[ndarray], ndarray]

Return the backward FFT function for Dirichlet boundaries.

Returns:

Backward IDST callable.

Return type:

Callable[[np.ndarray], np.ndarray]

property fft_forward: Callable[[ndarray], ndarray]

Return the forward FFT function for Dirichlet boundaries.

Returns:

Forward DST callable.

Return type:

Callable[[np.ndarray], np.ndarray]

get_target_slice()[source]

Return the target slice for Dirichlet boundaries.

Returns:

Slice excluding both boundary points.

Return type:

slice

modified_wave_number(k, n)[source]

Compute the modified wave number for Dirichlet boundaries.

Parameters:
  • k (int) – Wavenumber index.

  • n (int) – Number of grid points.

Returns:

Modified wave number value.

Return type:

float

transpose_boundary_values(rho_target, dx)[source]

Transpose boundary values into the right-hand side for Dirichlet conditions.

Parameters:
  • rho_target (np.ndarray) – Charge density array for the target region.

  • dx (float) – Grid spacing.

Returns:

No return value.

Return type:

None

class emout.utils.poisson.FFT3d(forwards, backwards)[source]

Bases: object

Composite 3-D FFT that applies per-axis forward/backward transforms.

backward(data3d)[source]

Apply the backward (inverse) transform.

Parameters:

data3d (np.ndarray) – 3-D input data in frequency space.

Returns:

Transformed data in real space.

Return type:

np.ndarray

forward(data3d)[source]

Apply the forward transform.

Parameters:

data3d (np.ndarray) – 3-D input data.

Returns:

Transformed data in frequency space.

Return type:

np.ndarray

class emout.utils.poisson.NeumannPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

Zero-gradient (Neumann) boundary condition for the Poisson solver.

correct_boundary_values(phi)[source]

Correct boundary values for Neumann conditions (no-op).

Parameters:

phi (np.ndarray) – Potential array.

Returns:

No return value.

Return type:

None

property fft_backward: Callable[[ndarray], ndarray]

Return the backward FFT function for Neumann boundaries.

Returns:

Backward IDCT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

property fft_forward: Callable[[ndarray], ndarray]

Return the forward FFT function for Neumann boundaries.

Returns:

Forward DCT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

get_target_slice()[source]

Return the target slice for Neumann boundaries.

Returns:

Slice including all points.

Return type:

slice

modified_wave_number(k, n)[source]

Compute the modified wave number for Neumann boundaries.

Parameters:
  • k (int) – Wavenumber index.

  • n (int) – Number of grid points.

Returns:

Modified wave number value.

Return type:

float

transpose_boundary_values(rho_target, dx)[source]

Transpose boundary values into the right-hand side for Neumann conditions.

Parameters:
  • rho_target (np.ndarray) – Charge density array for the target region.

  • dx (float) – Grid spacing.

Returns:

No return value.

Return type:

None

class emout.utils.poisson.PeriodicPoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: PoissonBoundary

Periodic boundary condition for the Poisson solver.

correct_boundary_values(phi)[source]

Correct boundary values by copying the periodic duplicate.

Parameters:

phi (np.ndarray) – Potential array.

Returns:

No return value.

Return type:

None

property fft_backward: Callable[[ndarray], ndarray]

Return the backward FFT function for periodic boundaries.

Returns:

Backward FFT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

property fft_forward: Callable[[ndarray], ndarray]

Return the forward FFT function for periodic boundaries.

Returns:

Forward FFT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

get_target_slice()[source]

Return the target slice for periodic boundaries.

Returns:

Slice excluding the last (periodic duplicate) point.

Return type:

slice

modified_wave_number(k, n)[source]

Compute the modified wave number for periodic boundaries.

Parameters:
  • k (int) – Wavenumber index.

  • n (int) – Number of grid points.

Returns:

Modified wave number value.

Return type:

float

transpose_boundary_values(rho_target, dx)[source]

Transpose boundary values into the right-hand side (no-op for periodic).

Parameters:
  • rho_target (np.ndarray) – Charge density array for the target region.

  • dx (float) – Grid spacing.

Returns:

No return value.

Return type:

None

class emout.utils.poisson.PoissonBoundary(axis, boundary_values=(0.0, 0.0))[source]

Bases: object

Abstract base for Poisson boundary conditions.

property axis: int

Return the target axis index.

Returns:

Target axis index.

Return type:

int

property boundary_values: Tuple[float]

Return the boundary values (lower, upper).

Returns:

Boundary value pair.

Return type:

Tuple[float]

abstractmethod correct_boundary_values(phi)[source]

Correct boundary values in the potential array.

Parameters:

phi (np.ndarray) – Potential array.

Returns:

No return value.

Return type:

None

abstract property fft_backward: Callable[[ndarray], ndarray]

Return the backward FFT function for this boundary condition.

Returns:

Backward FFT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

abstract property fft_forward: Callable[[ndarray], ndarray]

Return the forward FFT function for this boundary condition.

Returns:

Forward FFT callable.

Return type:

Callable[[np.ndarray], np.ndarray]

abstractmethod get_target_slice()[source]

Return the slice selecting the interior grid points for this axis.

Returns:

Slice corresponding to the target axis.

Return type:

slice

abstractmethod modified_wave_number(k, n)[source]

Compute the modified wave number for this boundary condition.

Parameters:
  • k (int) – Wavenumber index.

  • n (int) – Number of grid points.

Returns:

Modified wave number value.

Return type:

float

abstractmethod transpose_boundary_values(rho_target, dx)[source]

Transpose (fold) boundary values into the right-hand side array.

Parameters:
  • rho_target (np.ndarray) – Charge density array for the target region.

  • dx (float) – Grid spacing.

Returns:

No return value.

Return type:

None

emout.utils.poisson.poisson(rho, dx, boundary_types=None, boundary_values=None, btypes=None, epsilon_0=8.8541878188e-12)[source]

Solve Poisson’s equation with FFT.

Parameters:
  • rho (np.ndarray) – 3-dimentional array of the charge density [C/m^3]. The shape is (nz+1, ny+1, nx+1).

  • boundary_types (List[str] of {'periodic', 'dirichlet', 'neumann'},) – the boundary condition types, by default [‘periodic’, ‘periodic’, ‘periodic’]

  • boundary_values (List[Tuple[float]]) – the boundary values [(x-lower, x-upper), (y-lower, y-upper), (z-lower, z-upper)], by default [(0., 0.), (0., 0.), (0., 0.)]

  • btypes (str) – string consisting of prefixes of boundary conditions, by default None. If this is set, it takes precedence over boundary_types.

  • dx (float, optional) – the grid width [m], by default 1.0

  • epsilon_0 (_type_, optional) – the electric constant (vacuum permittivity) [F/m], by default cn.epsilon_0

Returns:

3-dimentional of the potential [V].

Return type:

np.ndarray

emout.utils.units module

Physical unit translators and conversion system for EMSES quantities.

UnitTranslator converts between EMSES grid units and SI, while Units bundles translators for all standard field quantities derived from the simulation parameters.

class emout.utils.units.UnitTranslator(from_unit, to_unit, name=None, unit=None)[source]

Bases: object

Unit converter between two unit systems.

from_unit

Value in the source unit system.

Type:

float

to_unit

Value in the target unit system.

Type:

float

ratio

Conversion factor (target = ratio * source).

Type:

float

name

Name of the quantity (e.g. “Mass”, “Frequency”).

Type:

str or None

unit

Unit symbol (e.g. “kg”, “Hz”).

Type:

str or None

reverse(value)[source]

Perform inverse unit conversion.

Parameters:

value (float) – Value after conversion.

Returns:

Value before conversion.

Return type:

float

set_name(name, unit=None)[source]

Set the display name and unit symbol.

Parameters:
  • name (str) – Display name.

  • unit (str) – Unit symbol.

Returns:

self

Return type:

UnitTranslator

trans(value, reverse=False)[source]

Perform unit conversion.

Parameters:
  • value (float) – Value before conversion (or after conversion if reverse=True).

  • reverse (bool, optional) – If True, perform inverse conversion, by default False.

Returns:

Value after conversion (or before conversion if reverse=True).

Return type:

float

class emout.utils.units.Units(dx, to_c)[source]

Bases: object

Manage unit converters for EMSES quantities.

Convert between SI and EMSES unit systems.

B

Unit translator for Magnetic flux density [T]

C

Unit translator for Capacitance [F]

E

Unit translator for Electric field [V/m]

EC

Unit translator for Electric conductivity [S/m]

F

Unit translator for Force [N]

G

Unit translator for Conductance [S]

H

Unit translator for Magnetic field [A/m]

J

Unit translator for Current density [A/m^2]

L

Unit translator for Inductance [H]

N

Unit translator for Flux [/m^2s]

P

Unit translator for Power [W]

R

Unit translator for Resistance [Ω]

T

Unit translator for Temperature [K]

W

Unit translator for Energy [J]

a

Unit translator for Acceleration [m/s^2]

c

Unit translator for Light Speed [m/s]

dx

Grid length [m]

e

Unit translator for Napiers constant []

e0

Unit translator for FS-Permttivity [F/m]

eps

Unit translator for Permittivity [F/m]

f

Unit translator for Frequency [Hz]

i

Unit translator for Current [A]

kB

Unit translator for Boltzmann constant [J/K]

length

Unit translator for Sim-to-Real length ratio [m]

m

Unit translator for Mass [kg]

m0

Unit translator for FS-Permeablity [N/A^2]

me

Unit translator for Electron mass [kg]

mi

Unit translator for Proton mass [kg]

mu

Unit translator for Permiability [H/m]

n

Unit translator for Number density [/m^3]

phi

Unit translator for Potential [V]

pi

Unit translator for Circular constant []

q

Unit translator for Charge [C]

q_m

Unit translator for Charge-to-mass ratio [C/kg]

qe

Unit translator for Elementary charge [C]

qe_me

Unit translator for Electron charge-to-mass ratio [C/kg]

rho

Unit translator for Charge density [C/m^3]

t

Unit translator for Time [s]

to_c

Light speed in EMSES

v

Unit translator for Velocity [m/s]

w

Unit translator for Energy density [J/m^3]

emout.utils.util module

Miscellaneous helpers: regex dict, file-info parsing, interpolation, and slicing.

class emout.utils.util.DataFileInfo(filename)[source]

Bases: object

Manage metadata about a data file.

property abspath

Return the absolute path of the file.

Returns:

Absolute file path, or None if no filename was set.

Return type:

Path or None

property directory

Return the absolute path of the parent directory.

Returns:

Absolute directory path.

Return type:

Path

property filename

Return the file name.

Returns:

File name.

Return type:

Path

class emout.utils.util.QuantizedPillowWriter(fps=5, metadata=None, codec=None, bitrate=None)[source]

Bases: PillowWriter

PillowWriter wrapper that quantises each frame to 256 colours.

grab_frame(**savefig_kwargs)[source]

Grab a frame and quantise it to 256 colours.

Parameters:

**savefig_kwargs (dict) – Additional keyword arguments forwarded to savefig.

Returns:

No return value.

Return type:

None

class emout.utils.util.RegexDict[source]

Bases: dict

Dictionary that supports regular expression keys.

get(key, default=None)[source]

Return the value for key if present, otherwise return default.

Parameters:
  • key (object) – Key to look up.

  • default (object, optional) – Default value returned when the key is not found.

Returns:

Value associated with the key or the default.

Return type:

object

emout.utils.util.apply_offset(line, offset)[source]

Apply a positional offset to a coordinate array.

Parameters:
  • line (numpy.ndarray) – Coordinate values to shift.

  • offset (float or str) – "left" sets the first element to 0, "center" centres on the middle element, "right" sets the last element to 0. A numeric value is added directly.

Returns:

Shifted array (modified in-place when possible).

Return type:

numpy.ndarray

emout.utils.util.hole_mask(inp, reverse=False)[source]

Generate a boolean mask for a rectangular hole region.

Parameters:
  • inp (object) – Input parameter object providing grid and hole dimensions.

  • reverse (bool, optional) – If True, invert the mask before returning.

Returns:

Boolean mask array.

Return type:

object

emout.utils.util.interp2d(mesh, n, **kwargs)[source]

Perform bilinear interpolation on a 2-D array.

Parameters:
  • mesh (object) – 2-D mesh data to interpolate.

  • n (object) – Upsampling factor for each axis.

  • **kwargs (dict) – Additional keyword arguments forwarded to scipy.interpolate.griddata.

Returns:

Interpolated 2-D array.

Return type:

object

emout.utils.util.range_with_slice(slice_obj, maxlen)[source]

Create a range from a slice object.

Parameters:
  • slice_obj (slice) – Slice object.

  • maxlen (int) – Maximum length (used when slice values are negative).

Returns:

Range generator.

Return type:

generator

emout.utils.util.slice2tuple(slice_obj)[source]

Convert a slice object to a tuple.

Parameters:

slice_obj (slice) – Slice object.

Returns:

(start, stop, step) – Tuple containing the slice information.

Return type:

int

Module contents

Shared utilities: input-file parsing, unit conversion, and helpers.