kwave.utils.matrix module

broadcast_axis(data, ndims, axis)[source]

Broadcast the given axis of the data to the specified number of dimensions.

Parameters:
  • data (ndarray) – The data to broadcast.

  • ndims (int) – The number of dimensions to broadcast the axis to.

  • axis (int) – The axis to broadcast.

Returns:

The broadcasted data.

Return type:

ndarray

expand_matrix(matrix, exp_coeff, edge_val=None)[source]

Enlarge a matrix by extending the edge values.

expandMatrix enlarges an input matrix by extension of the values at the outer faces of the matrix (endpoints in 1D, outer edges in 2D, outer surfaces in 3D). Alternatively, if an input for edge_val is given, all expanded matrix elements will have this value. The values for exp_coeff are forced to be real positive integers (or zero).

Note, indexing is done inline with other k-Wave functions using mat(x) in 1D, mat(x, y) in 2D, and mat(x, y, z) in 3D.

Parameters:
  • matrix (Num[ndarray, '...'] | Bool[ndarray, '...']) – the matrix to enlarge

  • exp_coeff (Shaped[ndarray, 'dim'] | list) –

    the number of elements to add in each dimension in 1D: [a] or [x_start, x_end] in 2D: [a] or [x, y] or

    [x_start, x_end, y_start, y_end]

    in 3D: [a] or [x, y, z] or

    [x_start, x_end, y_start, y_end, z_start, z_end] (here ‘a’ is applied to all dimensions)

  • edge_val (Real[ndarray, ' '] | number | int | float | None) – value to use in the matrix expansion

Returns:

expanded matrix

gradient_fd(f, dx=None, dim=None, deriv_order=None, accuracy_order=None)[source]

Calculate the gradient of an n-dimensional input matrix using the finite-difference method.

This function is a wrapper of the numpy gradient method for use in the k-wave library. For one-dimensional inputs, the gradient is always computed along the non-singleton dimension. For higher dimensional inputs, the gradient for singleton dimensions is returned as 0. For elements in the center of the grid, the gradient is computed using centered finite-differences. For elements on the edge of the grid, the gradient is computed using forward or backward finite-differences. The order of accuracy of the finite-difference approximation is controlled by accuracy_order (default = 2). The calculations are done using sparse multiplication, so the input matrix is always cast to double precision.

Parameters:
  • f – Input matrix.

  • dx – Array of values for the grid point spacing in each dimension. If a value for dim is given, dn is the spacing in dimension dim.

  • dim – Optional input to specify a single dimension over which to compute the gradient for

  • deriv_order – Order of the derivative to compute, e.g., use 1 to compute df/dx, 2 to compute df^2/dx^2, etc. (default = 1).

  • accuracy_order – Order of accuracy for the finite difference coefficients. Because centered differences are used, this must be set to an integer multiple of 2 (default = 2).

Returns:

A list of ndarrays (or a single ndarray if there is only one dimension) corresponding to the derivatives of f with respect to each dimension. Each derivative has the same shape as f.

Return type:

list[ndarray]

max_nd(matrix)[source]

Returns the maximum value in a n-dimensional array and its index.

Parameters:

matrix (ndarray) – n-dimensional array of values.

Returns:

A tuple containing the maximum value in the array, and a tuple containing the index of the maximum value. The index is given in the MATLAB convention, where indexing starts at 1.

Return type:

tuple[float, tuple]

min_nd(matrix)[source]

Find the minimum value and its indices in a numpy array.

Parameters:

matrix (ndarray) – A numpy array of any value type.

Returns:

A tuple containing the minimum value and a tuple of indices in the form (row, column, …).

Indices are 1-based, following the convention used in MATLAB.

Return type:

tuple[float, tuple]

Examples

>>> matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> min_nd(matrix)
(1, (1, 1))
num_dim(x)[source]

Returns the number of dimensions in x, after collapsing any singleton dimensions.

Parameters:

x (ndarray) – The input array.

Returns:

The number of dimensions in x.

Return type:

int

num_dim2(x)[source]

Get the number of dimensions of an array after collapsing singleton dimensions.

Parameters:

x (ndarray) – The input array.

Returns:

The number of dimensions of the array after collapsing singleton dimensions.

Return type:

int

resize(mat, new_size, interp_mode='linear')[source]

Resizes a matrix of spatial samples to a desired resolution or spatial sampling frequency via interpolation.

Parameters:
  • mat (ndarray) – Matrix to be resized (i.e., resampled).

  • new_size (int | list[int]) – Desired output resolution.

  • interp_mode (str) – Interpolation method.

Returns:

Resized matrix.

Return type:

ndarray

revolve2d(mat2d)[source]

Revolve a 2D numpy array in a clockwise direction to form a 3D numpy array.

Parameters:

mat2d (ndarray) – A 2D numpy array of any value type.

Returns:

A 3D numpy array formed by revolving the input array in a clockwise direction.

Return type:

ndarray

Examples

>>> mat2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> revolve2d(mat2d)
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],
       [[7, 4, 1],
        [8, 5, 2],
        [9, 6, 3]],
       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])
sort_rows(arr, index)[source]

Sort the rows of a 2D numpy array by the values in a specific column.

Parameters:
  • arr (ndarray) – A 2D numpy array.

  • index (int) – The index of the column to sort by.

Returns:

A copy of the input array with the rows sorted by the values in the specified column.

Raises:

AssertionError – If arr is not a 2D numpy array.

Return type:

ndarray

Examples

>>> arr = np.array([[3, 2, 1], [1, 3, 2], [2, 1, 3]])
>>> sort_rows(arr, 0)
array([[1, 3, 2],
       [2, 1, 3],
       [3, 2, 1]])
trim_zeros(data)[source]

Create a tight bounding box by removing zeros.

Parameters:

data (Num[ndarray, '...']) – Matrix to trim.

Returns:

Tuple containing the trimmed matrix and indices used to trim the matrix.

Raises:

ValueError – If the input data is not 1D, 2D, or 3D.

Return type:

tuple[Num[ndarray, ‘…’], list[tuple[Int[ndarray, ‘ ‘] | number | int, Int[ndarray, ‘ ‘] | number | int]]]

Example

data = np.array([[0, 0, 0, 0, 0, 0],

[0, 0, 0, 3, 0, 0], [0, 0, 1, 3, 4, 0], [0, 0, 1, 3, 4, 0], [0, 0, 1, 3, 0, 0], [0, 0, 0, 0, 0, 0]])

trimmed_data, indices = trim_zeros(data)

# Output: # trimmed_data: # [[0 3 0] # [1 3 4] # [1 3 4] # [1 3 0]] # # indices: # [(1, 4), (2, 5), (3, 5)]