Welcome to NLLGrid’s documentation!

Reading and writing of NonLinLoc grid files.

copyright:
2013-2026 Claudio Satriano <satriano@ipgp.fr>,

Natalia Poiata <poiata@ipgp.fr>, Robert Pickle <rpickle@gmail.com>

license:

GNU General Public License v3.0 or later (https://www.gnu.org/licenses/gpl-3.0-standalone.html)

class nllgrid.NLLGrid(basename=None, nx=1, ny=1, nz=1, x_orig=0.0, y_orig=0.0, z_orig=0.0, dx=1.0, dy=1.0, dz=1.0)[source]

Class for manipulating NonLinLoc grid files.

It provides methods to read and write grid files, compute statistics and plot.

Parameters:
  • basename (str, optional) – The name of the grid file.

  • nx (int, optional) – Number of grid points in x direction.

  • ny (int, optional) – Number of grid points in y direction.

  • nz (int, optional) – Number of grid points in z direction.

  • x_orig (float, optional) – X coordinate of the lower left point in map view.

  • y_orig (float, optional) – Y coordinate of the lower left point in map view.

  • z_orig (float, optional) – Z coordinate of the shallowest point.

  • dx (float, optional) – Spacing of grid points in x direction.

  • dy (float, optional) – Spacing of grid points in y direction.

  • dz (float, optional) – Spacing of grid points in z direction.

Public Data Attributes:

basename

The name of the grid file

nx

Number of grid points in x direction

ny

Number of grid points in y direction

nz

Number of grid points in z direction

x_orig

X coordinate of the lower left point in map view

y_orig

Y coordinate of the lower left point in map view

z_orig

Z coordinate of the shallowest point

dx

Spacing of grid points in x direction

dy

Spacing of grid points in y direction

dz

Spacing of grid points in z direction

first_std_paral

Latitude of the first standard parallel for LAMBERT projection

second_std_paral

Latitude of the second standard parallel for LAMBERT projection

map_rot

Rotation angle of the grid in map view, counter-clockwise

station

Name of the station

sta_x

X coordinate of the station

sta_y

Y coordinate of the station

sta_z

Z coordinate of the station

xyz_mean

Coordinates of the grid mean point

xyz_cov

Covariance matrix of the grid

ellipsoid

The 68% confidence ellipsoid for the grid

array

The grid data as a 3D numpy array.

type

The type of the grid as a string

float_type

The datatype for floating point numbers (FLOAT or DOUBLE)

proj_name

The name of the projection

proj_ellipsoid

The name of the projection ellipsoid

orig_lon

The longitude of the grid origin

orig_lat

The latitude of the grid origin

proj_function

The projection function to perform direct and inverse projections

Public Methods:

__init__([basename, nx, ny, nz, x_orig, ...])

Initialize a NLLGrid object.

__str__()

Return a string representation of the object.

__getitem__(key)

Return the value at the given index.

remove_extension(basename)

Remove '.hdr' or '.buf' suffixes, if present.

init_array()

Initialize the grid array to zeros.

read_hdr_file([basename])

Read header file of NLL grid format.

read_buf_file([basename])

Read buf file as a 3d array.

write_hdr_file([basename])

Write header file in NLL grid format.

write_buf_file([basename])

Write buffer file as a 3D array.

get_transform_line()

Get the transform line in NLL hdr format.

get_xyz(i, j, k)

Get cartesian coordinates (x, y, z) for grid indexes (i, j, k).

get_ijk(x, y, z)

Get grid indexes (i, j, k) for cartesian coordinates (x, y, z).

get_ijk_max()

Return the indexes (i, j, k) of the grid max point.

get_ijk_min()

Return the indexes (i,j,k) of the grid min point.

get_xyz_max()

Return the coordinates (x,y,z) of the grid max point.

get_xyz_min()

Return the coordinates (x,y,z) of the grid min point.

get_ijk_mean()

Return the indexes (i,j,k) of the grid mean point.

get_xyz_mean()

Calculate and return the mean (x,y,z) coordinate of the grid.

get_xyz_cov()

Return the covariance matrix of the grid with respect to the mean point in (x,y,z).

get_xyz_ellipsoid()

Return the 68% confidence ellipsoid.

get_value(x, y, z[, array])

Get the grid value at specified cartesian coordinates (x, y, z).

get_extent()

Get the grid extent in cartesian units.

get_xy_extent()

Get the grid xy extent in cartesian units.

get_xz_extent()

Get the grid xz extent in cartesian units.

get_zx_extent()

Get the grid zx extent in cartesian units.

get_yz_extent()

Get the grid yz extent in cartesian units.

get_zy_extent()

Get the grid zy extent in cartesian units.

max()

Get the maximum value of the grid.

resample(dx, dy, dz)

Resample the grid to the specified resolution.

get_plot_axes([figure, ax_xy])

Get the axes for the three projections and colorbar axis.

plot([slice_index, handle, figure, ax_xy, ...])

Plot the grid using three orthogonal projections.

plot_3D_point(axes, point[, color])

Plot a 3D point on the grid in three different projections.

plot_ellipsoid(axes[, ellipsoid, mean_xyz])

Plot an ellipsoid on the grid.

project(lon, lat)

Project longitude and latitude coordinates into grid coordinates.

iproject(x, y)

Convert grid coordinates to longitude and latitude.

horizontal_recenter()

Move the origin of the grid's cartesian coordinate system to the grid center.

horizontal_rotate(angle[, fill_value])

Rotate the grid horizontally around its center counterclockwise by a given angle.

nudge(direction[, num_layers])

'Nudge' a grid's dimensions by expanding or contracting in any direction, by any number of 2D layers.

copy()

Generate a copy of the grid.

Private Data Attributes:

_NLLGrid__array

_NLLGrid__type

_NLLGrid__float_type

_NLLGrid__np_float_type

_NLLGrid__orig_lon

_NLLGrid__orig_lat

_NLLGrid__proj_name

_NLLGrid__proj_ellipsoid

_NLLGrid__proj_function

Private Methods:

_repr_pretty_(p, _cycle)

Pretty print.


first_std_paral = None

Latitude of the first standard parallel for LAMBERT projection

second_std_paral = None

Latitude of the second standard parallel for LAMBERT projection

map_rot = 0.0

Rotation angle of the grid in map view, counter-clockwise

station = None

Name of the station

sta_x = None

X coordinate of the station

sta_y = None

Y coordinate of the station

sta_z = None

Z coordinate of the station

xyz_mean = None

Coordinates of the grid mean point

xyz_cov = None

Covariance matrix of the grid

ellipsoid = None

The 68% confidence ellipsoid for the grid

basename = None

The name of the grid file

nx = 1.0

Number of grid points in x direction

ny = 1.0

Number of grid points in y direction

nz = 1.0

Number of grid points in z direction

x_orig = 0.0

X coordinate of the lower left point in map view

y_orig = 0.0

Y coordinate of the lower left point in map view

z_orig = 0.0

Z coordinate of the shallowest point

dx = 1.0

Spacing of grid points in x direction

dy = 1.0

Spacing of grid points in y direction

dz = 1.0

Spacing of grid points in z direction

property array

The grid data as a 3D numpy array.

property type

The type of the grid as a string

property float_type

The datatype for floating point numbers (FLOAT or DOUBLE)

property proj_name

The name of the projection

property proj_ellipsoid

The name of the projection ellipsoid

property orig_lon

The longitude of the grid origin

property orig_lat

The latitude of the grid origin

remove_extension(basename)[source]

Remove ‘.hdr’ or ‘.buf’ suffixes, if present.

Parameters:

basename (str) – The basename of the grid file.

Returns:

The basename without the ‘.hdr’ or ‘.buf’ suffixes.

Return type:

str

Example

>>> grd = NLLGrid()
>>> grd.remove_extension('test.hdr')
'test'
>>> grd.remove_extension('test.buf')
'test'
>>> grd.remove_extension('test')
'test'
init_array()[source]

Initialize the grid array to zeros.

Return type:

None

Note

This method sets the array attribute of the NLLGrid instance to a 3D numpy array of shape (self.nx, self.ny, self.nz) and data type float, filled with zeros.

Example

>>> grd = NLLGrid(nx=20, ny=20, nz=30, dx=2., dy=2., dz=2.)
>>> grd.init_array()
>>> grd.array[2, 4, 10] = 3.
read_hdr_file(basename=None)[source]

Read header file of NLL grid format.

The header file provides information about the 3D grid such as the number of gridpoints in each dimension, the origin, the cell spacing, the type of grid, the data type of the values, and the geographic projection.

Parameters:

basename (str, optional) – Basename of the header file or full file name. If provided, the basename attribute of the class instance will be updated. If not provided, the basename attribute of the class instance will be used.

Return type:

None

Raises:

FileNotFoundError – If the header file is not found.

Example

>>> grd = NLLGrid()
>>> grd.read_hdr_file('test.hdr')
>>> print(grd)
basename: test
nx: 2 ny: 301 nz: 61
x_orig: 0.0 y_orig: 0.0 z_orig: -3.0
dx: 5.0 dy: 5.0 dz: 5.0
grid_type: SLOW_LEN
float_type: FLOAT
transform: TRANSFORM  LAMBERT RefEllipsoid Clarke-1880
LatOrig 15.000000  LongOrig -61.000000  FirstStdParal 10.000000
SecondStdParal 20.000000  RotCW 0.000000
read_buf_file(basename=None)[source]

Read buf file as a 3d array.

The buffer file is a binary representation of the 3D array stored in the array attribute of the class instance.

Parameters:

basename (str, optional) – Basename of the buffer file or full file name. If provided, the basename attribute of the class instance will be updated. If not provided, the basename attribute of the class instance will be used.

Raises:

Example

>>> grd = NLLGrid()
>>> grd.read_buf_file('test.buf')
>>> print(grd)
basename: test
nx: 1 ny: 1 nz: 1
x_orig: 0.0 y_orig: 0.0 z_orig: 0.0
dx: 1.0 dy: 1.0 dz: 1.0
grid_type: None
float_type: FLOAT
transform: None
write_hdr_file(basename=None)[source]

Write header file in NLL grid format.

The header file provides information about the 3D grid such as the number of gridpoints in each dimension, the origin, the cell spacing, the type of grid, the data type of the values, and the geographic projection.

Parameters:

basename (str, optional) – Base name of the header file. If not provided, the basename attribute of the class instance will be used.

Return type:

None

write_buf_file(basename=None)[source]

Write buffer file as a 3D array.

The buffer file is a binary representation of the 3D array stored in the array attribute of the class instance.

Parameters:

basename (str, optional) – Base name of the buffer file. If not provided, the basename attribute of the class instance will be used.

Raises:

NotImplementedError – If the grid type is ‘ANGLE’ or ‘ANGLE2D’. Writing buf file is not supported for these grid types.

Return type:

None

get_transform_line()[source]

Get the transform line in NLL hdr format.

Returns:

line – A string representing the transform line in NLL hdr format.

Return type:

str

get_xyz(i, j, k)[source]

Get cartesian coordinates (x, y, z) for grid indexes (i, j, k).

Parameters:
  • i (int) – The index along the x-axis.

  • j (int) – The index along the y-axis.

  • k (int) – The index along the z-axis.

Returns:

  • x (float) – The x-coordinate in cartesian space.

  • y (float) – The y-coordinate in cartesian space.

  • z (float) – The z-coordinate in cartesian space.

get_ijk(x, y, z)[source]

Get grid indexes (i, j, k) for cartesian coordinates (x, y, z).

Parameters:
  • x (float) – The x-coordinate in cartesian space.

  • y (float) – The y-coordinate in cartesian space.

  • z (float) – The z-coordinate in cartesian space.

Returns:

  • i (int) – The index along the x-axis.

  • j (int) – The index along the y-axis.

  • k (int) – The index along the z-axis.

get_ijk_max()[source]

Return the indexes (i, j, k) of the grid max point.

Returns:

The 3D index of the grid max point. Returns None if self.array is None.

Return type:

tuple of ints or None

get_ijk_min()[source]

Return the indexes (i,j,k) of the grid min point.

Returns:

The 3D index of the grid min point. Returns None if self.array is None.

Return type:

tuple of ints or None

get_xyz_max()[source]

Return the coordinates (x,y,z) of the grid max point.

Returns:

The 3D coordinates of the grid max point. Returns None if self.array is None.

Return type:

tuple of float or None

get_xyz_min()[source]

Return the coordinates (x,y,z) of the grid min point.

Returns:

The 3D coordinates of the grid min point. Returns None if self.array is None.

Return type:

tuple of float or None

get_ijk_mean()[source]

Return the indexes (i,j,k) of the grid mean point.

get_xyz_mean()[source]

Calculate and return the mean (x,y,z) coordinate of the grid.

Returns:

xmean, ymean, zmean – Mean x, y, and z coordinates, respectively.

Return type:

float

Note

If the grid array is not set, None is returned.

get_xyz_cov()[source]

Return the covariance matrix of the grid with respect to the mean point in (x,y,z).

Returns:

cov – The covariance matrix of the grid with respect to the mean point in (x,y,z). If the grid is None, returns None.

Return type:

numpy.ndarray, shape (3,3)

get_xyz_ellipsoid()[source]

Return the 68% confidence ellipsoid.

Calculates the 68% confidence ellipsoid from the covariance matrix obtained by get_xyz_cov(). The calculated ellipsoid object is stored as an instance attribute ellipsoid.

Returns:

The 68% confidence ellipsoid.

Return type:

Ellipsoid3D

Note

This method is a python translation of the CalcErrorEllipsoid() function from the NonLinLoc package, written by Anthony Lomax.

get_value(x, y, z, array=None)[source]

Get the grid value at specified cartesian coordinates (x, y, z).

Parameters:
  • x (float) – The x coordinate.

  • y (float) – The y coordinate.

  • z (float) – The z coordinate.

  • array (numpy.ndarray, optional) – The 3D array to use, by default None. If not provided, the instance’s array attribute is used.

Returns:

value – The grid value at the specified cartesian coordinates. If the grid type is ‘ANGLE’ or ‘ANGLE2D’, a tuple of (azimuth, dip, quality) is returned.

Return type:

float or tuple of 3 float values

Raises:
  • NotImplementedError – If the grid type is ‘ANGLE’ or ‘ANGLE2D’ and an array argument is provided.

  • ValueError – If the specified coordinates are outside of the grid’s extent.

get_extent()[source]

Get the grid extent in cartesian units.

Returns:

extent – Tuple of x_min, x_max, y_min, y_max, z_min, z_max values in cartesian units (generally km).

Return type:

tuple

get_xy_extent()[source]

Get the grid xy extent in cartesian units.

Returns:

extent – Tuple of x_min, x_max, y_min, y_max values in cartesian units (generally km).

Return type:

tuple

get_xz_extent()[source]

Get the grid xz extent in cartesian units.

Returns:

extent – Tuple of x_min, x_max, z_min, z_max values in cartesian units (generally km).

Return type:

tuple

get_zx_extent()[source]

Get the grid zx extent in cartesian units.

Returns:

extent – Tuple of z_min, z_max, x_min, x_max values in cartesian units (generally km).

Return type:

tuple

get_yz_extent()[source]

Get the grid yz extent in cartesian units.

Returns:

extent – Tuple of y_min, y_max, z_min, z_max values in cartesian units (generally km).

Return type:

tuple

get_zy_extent()[source]

Get the grid zy extent in cartesian units.

Returns:

extent – Tuple of z_min, z_max, y_min, y_max values in cartesian units (generally km).

Return type:

tuple

max()[source]

Get the maximum value of the grid.

Returns:

The maximum value of the grid.

Return type:

float

Note

If the grid type is ‘ANGLE’ or ‘ANGLE2D’, the maximum value of self.dip is returned. Otherwise, the maximum value of self.array

resample(dx, dy, dz)[source]

Resample the grid to the specified resolution.

Parameters:
  • dx (float) – The new x-resolution of the grid.

  • dy (float) – The new y-resolution of the grid.

  • dz (float) – The new z-resolution of the grid.

Raises:

NotImplementedError – If the grid type is ‘ANGLE’ or ‘ANGLE2D’, as resampling is not implemented for these grid types.

get_plot_axes(figure=None, ax_xy=None)[source]

Get the axes for the three projections and colorbar axis.

Parameters:
  • figure (object, optional) – Matplotlib figure object. The default is None.

  • ax_xy (object, optional) – Matplotlib axis object for x-y projection. The default is None.

Returns:

  • ax_xy (object) – Matplotlib axis object for x-y projection.

  • ax_xz (object) – Matplotlib axis object for x-z projection.

  • ax_zy (object) – Matplotlib axis object for z-y projection.

  • ax_cb (object) – Matplotlib axis object for colorbar.

Note

Requires matplotlib. If ax_xy is not provided, a new figure and axis will be created. If figure is not provided, the figure will be obtained from ax_xy.

plot(slice_index=None, handle=False, figure=None, ax_xy=None, vmin=None, vmax=None, cmap=None, line_color='white', array=None, isolines=False, isolines_levels=10, isolines_kwargs=None)[source]

Plot the grid using three orthogonal projections.

Parameters:
  • slice_index (int or str, optional) – Index of the slice to plot. Use ‘max’ or ‘min’ to plot the slice at the grid’s maximum or minimum value, respectively. Leave it to None to use the grid’s middle slice.

  • handle (bool, optional) – Whether to return the handle of the plot. The default is False.

  • figure (object, optional) – Matplotlib figure object. The default is None.

  • ax_xy (object, optional) – Matplotlib axis object for x-y projection. The default is None.

  • vmin (float, optional) – Lower limit for the color scale. Leave it to None to use the minimum value of the grid.

  • vmax (float, optional) – Upper limit for the color scale. Leave it to None to use the maximum value of the grid.

  • cmap (object, optional) – Colormap to use for the plot. Leave it to None to use the default Matplotlib colormap.

  • line_color (str, optional) – Color of the grid lines. The default is ‘white’.

  • array (array_like, optional) – Array to plot. Leave it to None to use the grid’s array attribute.

  • isolines (bool, optional) – Whether to overlay contour isolines on the plotted slices. The default is False.

  • isolines_levels (int or array-like, optional) – Number of contour levels or explicit contour levels to use. The default is 10.

  • isolines_kwargs (dict, optional) – Extra keyword arguments passed to matplotlib.axes.Axes.contour. If not provided, a default style is used.

Returns:

fig – Matplotlib figure object.

Return type:

object

Note

Requires matplotlib. If ax_xy is not provided, a new figure and axis will be created. If figure is not provided, the figure will be obtained from ax_xy.

plot_3D_point(axes, point, color='red')[source]

Plot a 3D point on the grid in three different projections.

Parameters:
  • axes (tuple of matplotlib.axes.Axes) – Tuple of 3 axes objects to plot the point.

  • point (tuple of float) – Tuple of the 3 point grid coordinates.

  • color (str, optional) – Color of the point. Default is ‘red’.

Raises:

NotImplementedError – If the grid is not 3D.

plot_ellipsoid(axes, ellipsoid=None, mean_xyz=None)[source]

Plot an ellipsoid on the grid.

Parameters:
  • axes (tuple of matplotlib.axes.Axes) – Tuple of 3 axes objects to plot the ellipsoid.

  • ellipsoid (object, optional) – Ellipsoid to plot. Default is None, in which case self.get_xyz_ellipsoid() is called.

  • mean_xyz (tuple of floats, optional) – Mean of the ellipsoid. Default is None, in which case self.get_xyz_mean() is called.

Raises:

NotImplementedError – If the grid is not 3D.

Note

This method is supported only for 3D grids. The method uses the Vect3D, ellipsiod2Axes, and toEllipsoid3D functions from the ellipsoid module.

property proj_function

The projection function to perform direct and inverse projections

project(lon, lat)[source]

Project longitude and latitude coordinates into grid coordinates.

Parameters:
  • lon (float or array-like) – The longitude coordinates to be projected.

  • lat (float or array-like) – The latitude coordinates to be projected.

Returns:

  • float or array-like – The projected grid x-coordinates.

  • float or array-like – The projected grid y-coordinates.

iproject(x, y)[source]

Convert grid coordinates to longitude and latitude.

Parameters:
  • x (float or array_like) – x-coordinate(s) in the grid’s cartesian coordinate system.

  • y (float or array_like) – y-coordinate(s) in the grid’s cartesian coordinate system.

Returns:

horizontal_recenter()[source]

Move the origin of the grid’s cartesian coordinate system to the grid center.

This operation updates the values of x_orig and y_orig.

Return type:

None

Note

If a geographical projection is available, the geographical coordinates of the grid center (the new (0, 0) point) are redefined. The absolute position of the grid in space does not change, but the grid projection is updated (orig_lon and orig_lat). Vertical coordinates are not modified.

horizontal_rotate(angle, fill_value=0.0)[source]

Rotate the grid horizontally around its center counterclockwise by a given angle.

Parameters:
  • angle (float) – Angle in degrees to rotate the grid counterclockwise.

  • fill_value (float, optional) – Value to fill with beyond the grid edge, by default 0.0.

Return type:

None

Note

The grid is recentered using the horizontal_recenter() method before rotation. The rotation is performed using the scipy.ndimage.rotate() function. The map_rot attribute is updated by adding angle.

nudge(direction, num_layers=1)[source]

‘Nudge’ a grid’s dimensions by expanding or contracting in any direction, by any number of 2D layers. The output grid is also recentered.

Parameters:
  • direction (char) –

    Cardinal direction to adjust, either “east”, “west”, “north”, “south”, as well as “up” or “down”, or simply “e”, “w”, “n”, “s”, “u”, “d”.

    West-East is axis 0, or the first “X” element of the array, with east at index -1.

    North-South is axis 1, or the second “Y” element, with north at index 0.

    Up-Down is axis 2, the third “Z” element, with the surface being index 0.

  • num_layers (int, default 1) – Number of layers to add (positive number) or subtract (negative). If positive, the layer values are duplicated from the outermost layer.

Return type:

None

Example

If a grid p_vel originally has shape (37, 175, 70),

>>> p_vel.nudge('north', 3)

will add three duplicated 2D layers of p_vel.array[:, 0, :] to the “north” side, giving the new array a shape of (37, 178, 70). 2D slices p_vel.array[:, 0, :] to p_vel.array[:, 3, :] will be identical.

copy()[source]

Generate a copy of the grid.

Returns:

A copy of the grid.

Return type:

Grid

Note

The copy is a deep copy, so that the array is copied and not just referenced.

Indices and tables