5. Utilities

Helper functions and utilities.

5.1. Common

Common utilities for AI4Plasma.

5.1.1. Common Classes

  • Timer: Simple timer for measuring elapsed time

class ai4plasma.utils.common.Timer[source]

Bases: object

Simple timer for measuring elapsed wall-clock time.

current(print_required=True)[source]

Return current time and optionally print elapsed duration.

Parameters:

print_required (bool, optional) – If True, print the elapsed time since initialization. Default is True.

Returns:

Current timestamp.

Return type:

datetime

ai4plasma.utils.common.list2torch(x_list, require_grad=True)[source]

Convert a list of NumPy arrays to PyTorch tensors on the configured device.

Parameters:
  • x_list (list of numpy.ndarray) – List of input NumPy arrays.

  • require_grad (bool, optional) – If True, set requires_grad for each returned tensor. Default is True.

Returns:

List of converted tensors on the device from DEVICE().

Return type:

list of torch.Tensor

ai4plasma.utils.common.numpy2torch(x, require_grad=True)[source]

Convert a NumPy array to a PyTorch tensor on the configured device.

Parameters:
  • x (numpy.ndarray) – Input NumPy array.

  • require_grad (bool, optional) – If True, set requires_grad for the returned tensor. Default is True.

Returns:

Converted tensor on the device from DEVICE().

Return type:

torch.Tensor

ai4plasma.utils.common.print_runing_time(t)[source]

Print elapsed time in a human-readable unit.

Parameters:

t (float) – Time value in seconds.

ai4plasma.utils.common.set_seed(seed=2020)[source]

Set random seeds for reproducibility.

Parameters:

seed (int, optional) – Seed value used for Python, NumPy, and PyTorch RNGs. Default is 2020.

5.2. Math

Mathematical utilities and tools for neural network computations in AI4Plasma.

This module provides a collection of mathematical functions and utility classes for neural network training and inference in the AI4Plasma project. It includes error metrics computation, automatic differentiation utilities, and floating-point precision management.

5.2.1. Math Functions

  • calc_l2_err(): Compute L2 error between true and predicted values

  • calc_relative_l2_err(): Compute relative L2 error for normalized comparison

  • df_dX(): Calculate tensor derivatives using automatic differentiation

5.2.2. Math Classes

  • Real: Floating-point precision manager for cross-library compatibility

class ai4plasma.utils.math.Real(precision=32)[source]

Bases: object

Floating-point precision manager for cross-library compatibility.

Manages floating-point precision (16, 32, 64-bit) for both NumPy and PyTorch, ensuring consistent data types across different libraries and enabling easy switching between different precision levels.

precision

Current floating-point precision (16, 32, or 64).

Type:

int

real

Dictionary mapping library names (‘numpy’, ‘torch’) to their respective floating-point types.

Type:

dict

set_float_precision(precision=32) None[source]

Set floating-point precision for both NumPy and PyTorch.

Updates the floating-point types for both libraries to match the specified precision level.

Parameters:

precision (int, optional) – Precision value: 16 (half), 32 (single), or 64 (double). Default is 32. Invalid values default to 32.

set_torch_dtype(precision=32) None[source]

Set default floating-point data type for PyTorch globally.

Configures PyTorch’s default tensor dtype to use the specified floating-point precision for all subsequently created tensors without explicit dtype specification.

Parameters:

precision (int, optional) – Precision value: 16 (half), 32 (single), or 64 (double). Default is 32. Invalid values default to 32.

ai4plasma.utils.math.calc_l2_err(x_true, x_pred)[source]

Calculate L2 error between true and predicted values.

Computes the L2 (Euclidean) norm of the difference between true and predicted values, normalized by the number of elements. This metric provides a scale-dependent measure of prediction accuracy.

Parameters:
  • x_true (numpy.ndarray or torch.Tensor) – True values with shape (N,) or (N, …).

  • x_pred (numpy.ndarray or torch.Tensor) – Predicted values with same shape as x_true.

Returns:

L2 error normalized by number of elements.

Return type:

float or torch.Tensor

Raises:

TypeError – If inputs are not both numpy arrays or both torch tensors.

ai4plasma.utils.math.calc_relative_l2_err(x_true, x_pred)[source]

Calculate relative L2 error between true and predicted values.

Computes the ratio of the L2 norm of the error to the L2 norm of the true values. This provides a scale-independent error metric suitable for comparing predictions across different value ranges.

Parameters:
  • x_true (numpy.ndarray or torch.Tensor) – True values with shape (N,) or (N, …). Must have non-zero norm.

  • x_pred (numpy.ndarray or torch.Tensor) – Predicted values with same shape as x_true.

Returns:

Relative L2 error as a dimensionless quantity.

Return type:

float or torch.Tensor

Raises:

TypeError – If inputs are not both numpy arrays or both torch tensors.

ai4plasma.utils.math.df_dX(f, X, retain_graph=True, create_graph=True)[source]

Calculate derivatives df/dX using automatic differentiation.

Computes the gradient of a scalar function f with respect to input tensor X using PyTorch’s automatic differentiation. Useful for computing Jacobian matrices and derivatives in neural network loss functions.

Parameters:
  • f (torch.Tensor) – Function output tensor, typically of shape (N, 1) or scalar. Must require gradients (requires_grad=True).

  • X (torch.Tensor) – Input tensor with respect to which derivative is computed, shape (N, M) or similar.

  • retain_graph (bool, optional) – Whether to retain the computation graph after backward pass. Default is True, required for multiple backward passes or subsequent operations.

  • create_graph (bool, optional) – Whether to create a graph for computing higher-order derivatives. Default is True, enabling computation of second derivatives if needed.

Returns:

Gradient of f with respect to X. Shape depends on f and X shapes.

Return type:

torch.Tensor

5.3. Device

Device management utilities for GPU/CPU selection in AI4Plasma.

This module provides device abstraction and management utilities for seamless GPU/CPU computation in the AI4Plasma framework. It handles device selection, validation, and provides a unified interface for device configuration.

5.3.1. Device Functions

  • check_gpu(): Check if GPU is available on the system.

  • select_gpu_by_id(): Select a specific GPU by its ID.

  • torch_device(): Create a PyTorch device object.

5.3.2. Device Classes

  • Device: Centralized device management class for GPU/CPU selection and handling.

class ai4plasma.utils.device.Device(device_id=-1)[source]

Bases: object

Centralized device management for GPU/CPU selection and handling.

This class provides an abstraction layer for device management, allowing flexible switching between GPU and CPU devices with validation. It maintains device state and provides a callable interface for dynamic device retrieval.

device_id

The current device ID. Negative values indicate CPU, non-negative values indicate GPU ID.

Type:

int

device

The PyTorch device object for the current device.

Type:

torch.device

set_device(device_id=-1) None[source]

Set the device based on provided device ID.

Updates the internal device configuration to the specified device_id. Creates a new torch.device object and updates device_id attribute.

Parameters:

device_id (int, optional) – Device ID to select. If < 0, uses CPU. Non-negative values select the GPU with that ID. Defaults to -1 (CPU).

Raises:

ValueError – If device_id is invalid or GPU device_id is specified but GPU is not available.

ai4plasma.utils.device.check_gpu(print_required=False)[source]

Check if GPU is available.

Detects GPU availability on the current system using PyTorch.

Parameters:

print_required (bool, optional) – If True, prints GPU availability status to console. Defaults to False.

Returns:

True if GPU is available, False otherwise.

Return type:

bool

ai4plasma.utils.device.select_gpu_by_id(gpu_id=0)[source]

Select GPU by its ID.

Sets the active GPU using torch.cuda.set_device(). Validates GPU availability and ID validity before selection.

Parameters:

gpu_id (int, optional) – GPU ID to select. Must be a non-negative integer and less than the total number of available GPUs. Defaults to 0.

Raises:

ValueError – If gpu_id is not an integer, negative, exceeds available GPU count, or if GPU is not available on the system.

ai4plasma.utils.device.torch_device(device_id=-1)[source]

Create and return a PyTorch device object.

Generates a torch.device object configured for either GPU or CPU based on the provided device_id. Performs validation of device_id before creation.

Parameters:

device_id (int, optional) – Device ID to use. If >= 0, selects the GPU with that ID. If < 0, uses CPU. Defaults to -1 (CPU).

Returns:

A PyTorch device object configured for the specified device.

Return type:

torch.device

Raises:

ValueError – If device_id is not an integer, if a GPU device_id is specified but GPU is not available, or if device_id exceeds the number of available GPUs.

5.4. I/O

Input/Output utilities for AI4Plasma.

This module provides utility functions for handling input and output operations in the AI4Plasma project, with a focus on JSON configuration file reading and image-to-GIF conversion for training visualization.

5.4.1. IO Functions

  • read_json: Load and parse JSON configuration files

  • img2gif: Convert a sequence of images into an animated GIF

ai4plasma.utils.io.img2gif(img_file_list, gif_file, duration=500, loop=0)[source]

Convert a sequence of images into an animated GIF file.

Reads a list of image files and combines them into a single animated GIF with configurable frame timing and loop behavior. Supports all image formats supported by the imageio library.

Parameters:
  • img_file_list (list of str) – List of file paths to input images. Images will be combined in the order provided.

  • gif_file (str) – File path where the output GIF will be saved.

  • duration (int, optional) – Duration in milliseconds for each frame. Default is 500.

  • loop (int, optional) – Number of times the GIF should loop. 0 means infinite loop. Default is 0.

Return type:

None

Raises:
  • ValueError – If the img_file_list is empty.

  • FileNotFoundError – If any of the specified image files do not exist.

ai4plasma.utils.io.read_json(json_file)[source]

Read and parse a JSON configuration file.

Loads a JSON file and returns its content as a Python dictionary. Provides detailed error messages for common file operation failures.

Parameters:

json_file (str) – Path to the JSON file to be read.

Returns:

Parsed content of the JSON file as a dictionary.

Return type:

dict

Raises:
  • FileNotFoundError – If the specified JSON file does not exist.

  • json.JSONDecodeError – If the file content is not valid JSON format.

Examples

>>> config = read_json('config.json')
>>> learning_rate = config['train']['lr']