Skip to content

fd_grad

fd_grad(gs, h)

Finite difference gradient on a grid

Given a regular finite-difference grid described by the number of nodes on each side, the grid spacing and a desired direction, construct a sparse matrix to compute gradients with each component defined on its respective staggered grid

Parameters:

Name Type Description Default
gs numpy int array

Grid size [nx,ny(,nz)]

required
h numpy double array

Spacing between grid points [hx,hy(,hz)]

required

Returns:

Name Type Description
G scipy sparse.csr_matrix

Sparse matrix of concatenated partial derivatives

See Also

fd_partial_derivative, fd_interpolate.

Notes

For any function f defined on a gs by gs grid, G @ f contains the directional derivatives on a staggered grid, the first gs1 rows are d/dx, while the latter gs0 are d/dy

Examples:

gs = np.array([19,15])
h = 1.0/(gs-1)
# Compute gradient matrix
G = gpytoolbox.fd_grad(gs=gs,h=h)
Source code in src/gpytoolbox/fd_grad.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def fd_grad(gs,h):
    """Finite difference gradient on a grid

    Given a regular finite-difference grid described by the number of nodes on each side, the grid spacing and a desired direction, construct a sparse matrix to compute gradients with each component defined on its respective staggered grid

    Parameters
    ----------
    gs : numpy int array
        Grid size [nx,ny(,nz)]
    h : numpy double array
        Spacing between grid points [hx,hy(,hz)]

    Returns
    -------
    G : scipy sparse.csr_matrix
        Sparse matrix of concatenated partial derivatives

    See Also
    --------
    fd_partial_derivative, fd_interpolate.

    Notes
    -----
    For any function f defined on a gs by gs grid, G @ f contains the directional derivatives on a staggered grid, the first gs[1](gs[0]-1) rows are d/dx, while the latter gs[0](gs[1]-1) are d/dy

    Examples
    --------
    ```python
    gs = np.array([19,15])
    h = 1.0/(gs-1)
    # Compute gradient matrix
    G = gpytoolbox.fd_grad(gs=gs,h=h)
    ```
    """

    dim = gs.shape[0]
    Dx =  fd_partial_derivative(gs=gs,h=h,direction=0)
    Dy =  fd_partial_derivative(gs=gs,h=h,direction=1)
    if dim==3:
        Dz =  fd_partial_derivative(gs=gs,h=h,direction=2)
        return vstack((Dx,Dy,Dz))
    return vstack((Dx,Dy))