Save & Load

Grids and their associated data can be persisted to disk and restored later. These functions serialise a grid’s structure and, optionally, any solution arrays defined on it, so that expensive grid constructions do not need to be repeated between sessions.

numgrids.save_grid(path: str | Path, grid: Grid, **data: NDArray) → None[source]

Save a grid and optional meshed data arrays to a .npz file.

The grid structure (axis types, parameters) is stored as compact JSON metadata. Any additional keyword arguments are stored as named arrays and will be returned by load_grid().

Parameters:
  • path (str or Path) – Destination file path. A .npz suffix is appended automatically by NumPy if not already present.

  • grid (Grid) – The grid to save.

  • **data (NDArray) – Arbitrary meshed arrays to persist alongside the grid. Each array must have shape grid.shape.

Examples

>>> save_grid("my_grid.npz", grid, temperature=T, pressure=P)
numgrids.load_grid(path: str | Path) → tuple[Grid, dict[str, NDArray]][source]

Load a grid and any saved data arrays from a .npz file.

Parameters:

path (str or Path) – Path to the .npz file (the suffix may be omitted).

Returns:

  • grid (Grid) – The reconstructed grid.

  • data (dict[str, NDArray]) – Dictionary of data arrays that were saved alongside the grid. Keys match the original keyword names passed to save_grid().

Examples

>>> grid, data = load_grid("my_grid.npz")
>>> T = data["temperature"]

xarray interoperability

Requires the optional xarray dependency (pip install numgrids[xarray]).

numgrids.to_xarray(grid: Grid, **fields: NDArray)[source]

Convert a grid and meshed arrays to an xarray.Dataset.

Each axis becomes a dimension coordinate (named after the axis, or x0, x1, … for unnamed axes). The full grid definition is stored in the attributes, so that from_xarray() can reconstruct the grid exactly – also after writing to and reading from NetCDF.

Parameters:
  • grid (Grid) – The grid.

  • **fields (NDArray) – Meshed arrays of shape grid.shape, stored as data variables.

Return type:

xarray.Dataset

Examples

>>> from numgrids import Grid, chebyshev
>>> grid = Grid(x=chebyshev(5, 0, 1))
>>> ds = to_xarray(grid, u=grid.coords ** 2)
>>> ds.to_netcdf("data.nc")
numgrids.from_xarray(obj) → tuple[Grid, dict[str, NDArray]][source]

Reconstruct a grid and data arrays from an xarray object.

Works with objects created by to_xarray() (exact round trip). For other datasets, the axis types are inferred from the coordinate values (equidistant, Chebyshev or logarithmic; periodic axes cannot be detected and are treated as non-periodic, and other axis types such as the axes on unbounded domains are not recognized).

Parameters:

obj (xarray.Dataset or xarray.DataArray)

Returns:

  • grid (Grid)

  • data (dict[str, NDArray]) – The data variables, transposed to the grid’s axis order.

VTK export

Files for ParaView, VisIt and other VTK-based tools. They are written without additional dependencies. See also Grid.to_vtk, Grid.to_vtk_series and EvolutionResult.to_vtk.

numgrids.vtk.write_vtk(path: str | Path, grid: Grid, *, binary: bool = True, close: bool = True, **fields) → Path[source]

Write meshed fields on a grid to a VTK file for ParaView or VisIt.

The file is a VTK XML StructuredGrid file (.vts). It holds the grid points in Cartesian space (for curvilinear grids via their Cartesian mapping; 1D and 2D grids lie in the plane \(z = 0\) unless the mapping embeds them in space) and the fields as point data.

For display, the grid is completed (close): periodic directions are closed by repeating their first point, so that there is no gap, and the origin of a radial() axis and the poles of a colatitude() axis are added with values from the spectral interpolation. The values at the grid points are written unchanged.

Parameters:
  • path (str or Path) – Destination file. The suffix .vts is appended if there is none.

  • grid (Grid) – The grid (at most 3 dimensions).

  • binary (bool) – Write the numbers base64-encoded (default) instead of as text. Both hold the full double precision.

  • close (bool) – Complete the grid for display as described above (default). With False, the file holds exactly the grid points.

  • **fields (NDArray or tuple of NDArray) – The fields by name. An array of grid shape is a scalar field. A tuple with one array per axis is a vector field, given by its components along the axes; it is written with its Cartesian components (see cartesian_components()). A complex scalar field psi is written as the arrays psi_real, psi_imag and psi_abs, a complex vector field as E_real and E_imag.

Returns:

The path of the file written.

Return type:

Path

Examples

>>> import os, tempfile
>>> import numpy as np
>>> from numgrids import PolarGrid, radial, periodic
>>> disk = PolarGrid(radial(8), periodic(16))
>>> R, Phi = disk.meshed_coords
>>> with tempfile.TemporaryDirectory() as folder:
...     path = write_vtk(os.path.join(folder, "disk"), disk,
...                      u=R ** 2 * np.cos(2 * Phi), v=(np.zeros(disk.shape), R))
...     path.name
'disk.vts'
numgrids.vtk.write_vtk_series(path: str | Path, grid: Grid, frames=None, t=None, *, name: str = 'u', binary: bool = True, close: bool = True, **fields) → Path[source]

Write a time series of fields as VTK files with a .pvd collection file.

Every time step is written to its own .vts file (see write_vtk()) next to the collection file: run.pvd comes with run_0000.vts, run_0001.vts, … Open the .pvd file in ParaView to get the series with its time values.

Parameters:
  • path (str or Path) – The collection file. The suffix .pvd is appended if there is none.

  • grid (Grid) – The grid (at most 3 dimensions).

  • frames (NDArray or tuple of NDArray, optional) – The values of one field in time, shape (nt, *grid.shape) (a tuple of such arrays for the components of a vector field). It is stored under name.

  • t (array_like, optional) – The time values, shape (nt,). Defaults to the frame numbers.

  • name (str) – Name of the field given by frames (default "u").

  • binary (bool) – As for write_vtk().

  • close (bool) – As for write_vtk().

  • **fields (NDArray or tuple of NDArray) – Further fields by name, each given like frames.

Returns:

The path of the collection file.

Return type:

Path

Examples

>>> import os, tempfile
>>> import numpy as np
>>> from numgrids import Grid, chebyshev
>>> grid = Grid(x=chebyshev(8, 0, 1), y=chebyshev(8, 0, 1))
>>> X, Y = grid.meshed_coords
>>> t = np.linspace(0, 1, 3)
>>> frames = np.array([np.exp(-tk) * X * Y for tk in t])
>>> with tempfile.TemporaryDirectory() as folder:
...     path = write_vtk_series(os.path.join(folder, "run.pvd"), grid, frames, t)
...     sorted(os.listdir(folder))
['run.pvd', 'run_0000.vts', 'run_0001.vts', 'run_0002.vts']
numgrids.vtk.cartesian_components(grid: Grid, *v: NDArray) → tuple[NDArray, ...][source]

Convert the components of a vector field to the Cartesian basis.

On curvilinear grids vector fields are given by their physical components along the coordinate lines, e.g. \((v_r, v_\varphi)\). This function returns the components \((v_x, v_y, \ldots)\) of the same field, one per Cartesian coordinate of the grid. The unit vectors are derived from the Cartesian mapping of the grid.

Parameters:
  • grid (Grid) – The grid. Curvilinear grids need a Cartesian mapping.

  • *v (NDArray) – The components of the vector field, one array of grid shape per axis.

Returns:

The Cartesian components (the arrays as given on a Cartesian grid).

Return type:

tuple of NDArray

Examples

A rigid rotation \(\mathbf{v} = r\,\mathbf{e}_\varphi\) is \((-y, x)\):

>>> import numpy as np
>>> from numgrids import PolarGrid, radial, periodic
>>> disk = PolarGrid(radial(8), periodic(16))
>>> R, Phi = disk.meshed_coords
>>> X, Y = disk.cartesian_coords
>>> vx, vy = cartesian_components(disk, np.zeros(disk.shape), R)
>>> bool(np.allclose(vx, -Y) and np.allclose(vy, X))
True