예제 #1
0
def Laplacian(dims,
              dirs=(0, 1),
              weights=(1, 1),
              sampling=(1, 1),
              edge=False,
              dtype='float64'):
    r"""Laplacian.

    Apply second-order centered Laplacian operator to a multi-dimensional
    array (at least 2 dimensions are required)

    Parameters
    ----------
    dims : :obj:`tuple`
        Number of samples for each dimension.
    dirs : :obj:`tuple`, optional
        Directions along which laplacian is applied.
    weights : :obj:`tuple`, optional
        Weight to apply to each direction (real laplacian operator if
        ``weights=[1,1]``)
    sampling : :obj:`tuple`, optional
        Sampling steps for each direction
    edge : :obj:`bool`, optional
        Use reduced order derivative at edges (``True``) or
        ignore them (``False``)
    dtype : :obj:`str`, optional
        Type of elements in input array.

    Returns
    -------
    l2op : :obj:`pylops.LinearOperator`
        Laplacian linear operator

    Notes
    -----
    The Laplacian operator applies a second derivative along two directions of
    a multi-dimensional array.

    For simplicity, given a two dimensional array, the Laplacian is:

    .. math::
        y[i, j] = (x[i+1, j] + x[i-1, j] + x[i, j-1] +x[i, j+1] - 4x[i, j])
                  / (dx*dy)

    """
    l2op = weights[0] * SecondDerivative(np.prod(dims),
                                         dims=dims,
                                         dir=dirs[0],
                                         sampling=sampling[0],
                                         edge=edge,
                                         dtype=dtype)
    l2op += weights[1] * SecondDerivative(np.prod(dims),
                                          dims=dims,
                                          dir=dirs[1],
                                          sampling=sampling[1],
                                          edge=edge,
                                          dtype=dtype)
    return aslinearoperator(l2op)
예제 #2
0
def Laplacian(dims,
              dirs=(0, 1),
              weights=(1, 1),
              sampling=(1, 1),
              dtype='float32'):
    r"""Laplacian.

    Apply second-order centered laplacian operator to a multi-dimensional array
    (at least 2 dimensions are required)

    Parameters
    ----------
    dims : :obj:`tuple`
        Number of samples for each dimension.
    dirs : :obj:`tuple`, optional
        Directions along which laplacian is applied.
    weights : :obj:`tuple`, optional
        Weight to apply to each direction (real laplacian operator if ``weights=[1,1]``)
    sampling : :obj:`tuple`, optional
        Sampling steps ``dx`` and ``dy`` for each direction
    dtype : :obj:`str`, optional
        Type of elements in input array.

    Returns
    -------
    l2op : LinearOperator
        Laplacian linear operator

    Notes
    -----
    The Laplacian operator applies a second derivative along two directions of a
    multi-dimensional array.

    For simplicity, given a two dimensional array, the laplacin is:

    .. math::
        y[i, j] = (x[i+1, j] + x[i-1, j] + x[i, j-1] +x[i, j+1] - 4x[i, j]) / (dx*dy)

    """
    l2op = weights[0]*SecondDerivative(np.prod(dims), dims=dims, dir=dirs[0],
                                       sampling=sampling[0], dtype=dtype) + \
           weights[1]*SecondDerivative(np.prod(dims), dims=dims, dir=dirs[1],
                                       sampling=sampling[1], dtype=dtype)

    return l2op
def test_SecondDerivative(par):
    """Dot-test and comparison with Pylops for SecondDerivative operator
    """
    np.random.seed(10)

    x = par['dx'] * np.arange(par['nx'])
    y = par['dy'] * np.arange(par['ny'])
    z = par['dz'] * np.arange(par['nz'])

    xx, yy = np.meshgrid(x, y)  # produces arrays of size (ny,nx)
    xxx, yyy, zzz = np.meshgrid(x, y, z)  # produces arrays of size (ny,nx,nz)

    # 1d
    dD2op = dSecondDerivative(par['nx'],
                              sampling=par['dx'],
                              compute=(True, True),
                              dtype='float32')
    D2op = SecondDerivative(par['nx'],
                            sampling=par['dx'],
                            edge=False,
                            dtype='float32')
    assert dottest(dD2op,
                   par['nx'],
                   par['nx'],
                   chunks=(par['nx'] // 2 + 1, par['nx'] // 2 + 1),
                   tol=1e-3)

    x = da.from_array(x, chunks=par['nx'] // 2 + 1)
    dy = dD2op * x
    y = D2op * x.compute()
    assert_array_almost_equal(y[1:-1], dy[1:-1], decimal=1)

    # 2d - derivative on 1st direction
    dD2op = dSecondDerivative(par['ny'] * par['nx'],
                              dims=(par['ny'], par['nx']),
                              dir=0,
                              sampling=par['dy'],
                              compute=(False, False),
                              dtype='float32')
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dy'],
                            edge=False,
                            dtype='float32')

    assert dottest(dD2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   chunks=((par['ny'] // 2 + 1) * (par['nx'] // 2 + 1),
                           (par['ny'] // 2 + 1) * (par['nx'] // 2 + 1)),
                   tol=1e-3)

    xx = da.from_array(xx, chunks=(par['ny'] // 2 + 1, par['nx'] // 2 + 1))
    dy = dD2op * xx.ravel()
    y = D2op * xx.compute().ravel()
    assert_array_almost_equal(y.reshape(par['ny'], par['nx'])[1:-1, 1:-1],
                              dy.reshape(par['ny'], par['nx'])[1:-1, 1:-1],
                              decimal=1)

    # 2d - derivative on 2nd direction
    dD2op = dSecondDerivative(par['ny'] * par['nx'],
                              dims=(par['ny'], par['nx']),
                              dir=1,
                              sampling=par['dy'],
                              compute=(False, False),
                              dtype='float32')
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dx'],
                            edge=False,
                            dtype='float32')

    assert dottest(dD2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   chunks=((par['ny'] // 2 + 1) * (par['nx'] // 2 + 1),
                           (par['ny'] // 2 + 1) * (par['nx'] // 2 + 1)),
                   tol=1e-3)

    yy = da.from_array(yy, chunks=(par['ny'] // 2 + 1, par['nx'] // 2 + 1))
    dy = dD2op * yy.ravel()
    y = D2op * yy.compute().ravel()
    assert_array_almost_equal(y.reshape(par['ny'], par['nx'])[1:-1, 1:-1],
                              dy.reshape(par['ny'], par['nx'])[1:-1, 1:-1],
                              decimal=1)

    # 3d - derivative on 1st direction
    dD2op = dSecondDerivative(par['nz'] * par['ny'] * par['nx'],
                              dims=(par['ny'], par['nx'], par['nz']),
                              dir=0,
                              sampling=par['dy'],
                              compute=(False, False),
                              dtype='float32')
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx'], par['nz']),
                            dir=0,
                            sampling=par['dy'],
                            edge=False,
                            dtype='float32')
    assert dottest(dD2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   chunks=((par['ny'] // 2 + 1) * (par['nx'] // 2 + 1),
                           (par['ny'] // 2 + 1) * (par['nx'] // 2 + 1)),
                   tol=1e-3)
    xxx = da.from_array(xxx,
                        chunks=(par['nz'] // 2 + 1, par['ny'] // 2 + 1,
                                par['nx'] // 2 + 1))
    dy = dD2op * xxx.ravel()
    y = D2op * xxx.compute().ravel()
    assert_array_almost_equal(y.reshape(par['nz'], par['ny'],
                                        par['nx'])[1:-1, 1:-1, 1:-1],
                              dy.reshape(par['nz'], par['ny'],
                                         par['nx'])[1:-1, 1:-1, 1:-1],
                              decimal=1)
    """
예제 #4
0
def test_SecondDerivative(par):
    """Dot-test and forward for SecondDerivative operator
    """
    # 1d
    gD1op = gSecondDerivative(par['nx'],
                              sampling=par['dx'],
                              dtype=torch.float32)
    assert dottest(gD1op, par['nx'], par['nx'], tol=1e-3)

    x = torch.from_numpy(
        (par['dx'] * np.arange(par['nx'], dtype='float32'))**2)
    D1op = SecondDerivative(par['nx'], sampling=par['dx'], dtype='float32')
    assert_array_equal((gD1op * x)[1:-1], (D1op * x.cpu().numpy())[1:-1])

    # 2d - derivative on 1st direction
    gD1op = gSecondDerivative(par['ny'] * par['nx'],
                              dims=(par['ny'], par['nx']),
                              dir=0,
                              sampling=par['dy'],
                              dtype=torch.float32)
    assert dottest(gD1op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    x = torch.from_numpy(
        (np.outer((par['dy'] * np.arange(par['ny']))**2,
                  np.ones(par['nx']))).astype(dtype='float32'))
    D1op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dy'],
                            dtype='float32')
    gy = (gD1op * x.view(-1)).reshape(par['ny'], par['nx']).cpu().numpy()
    y = (D1op * x.view(-1).cpu().numpy()).reshape(par['ny'], par['nx'])
    assert_array_equal(gy[1:-1], y[1:-1])

    # 2d - derivative on 2nd direction
    gD1op = gSecondDerivative(par['ny'] * par['nx'],
                              dims=(par['ny'], par['nx']),
                              dir=1,
                              sampling=par['dy'],
                              dtype=torch.float32)
    assert dottest(gD1op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    x = torch.from_numpy(
        (np.outer((par['dy'] * np.arange(par['ny']))**2,
                  np.ones(par['nx']))).astype(dtype='float32'))
    D1op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dy'],
                            dtype='float32')
    gy = (gD1op * x.view(-1)).reshape(par['ny'], par['nx']).cpu().numpy()
    y = (D1op * x.view(-1).cpu().numpy()).reshape(par['ny'], par['nx'])
    assert_array_equal(gy[:, 1:-1], y[:, 1:-1])

    # 3d - derivative on 1st direction
    gD1op = gSecondDerivative(par['nz'] * par['ny'] * par['nx'],
                              dims=(par['nz'], par['ny'], par['nx']),
                              dir=0,
                              sampling=par['dz'],
                              dtype=torch.float32)
    assert dottest(gD1op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = torch.from_numpy(
        (np.outer((par['dz'] * np.arange(par['nz']))**2,
                  np.ones((par['ny'], par['nx']))).astype(dtype='float32')))
    D1op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dz'],
                            dtype='float32')

    gy = (gD1op * x.view(-1)).reshape(par['nz'], par['ny'],
                                      par['nx']).cpu().numpy()
    y = (D1op * x.view(-1).cpu().numpy()).reshape(par['nz'], par['ny'],
                                                  par['nx'])
    assert_array_almost_equal(gy[1:-1], y[1:-1], decimal=5)

    # 3d - derivative on 2nd direction
    gD1op = gSecondDerivative(par['nz'] * par['ny'] * par['nx'],
                              dims=(par['nz'], par['ny'], par['nx']),
                              dir=1,
                              sampling=par['dy'],
                              dtype=torch.float32)
    assert dottest(gD1op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = torch.from_numpy((np.outer(
        (par['dz'] * np.arange(par['nz']))**2, np.ones(
            (par['ny'],
             par['nx']))).reshape(par['nz'], par['ny'],
                                  par['nx'])).astype(dtype='float32'))
    D1op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dy'],
                            dtype='float32')

    gy = (gD1op * x.view(-1)).reshape(par['nz'], par['ny'],
                                      par['nx']).cpu().numpy()
    y = (D1op * x.view(-1).cpu().numpy()).reshape(par['nz'], par['ny'],
                                                  par['nx'])
    assert_array_almost_equal(gy[1:-1], y[1:-1], decimal=5)

    # 3d - derivative on 3rd direction
    gD1op = gSecondDerivative(par['nz'] * par['ny'] * par['nx'],
                              dims=(par['nz'], par['ny'], par['nx']),
                              dir=2,
                              sampling=par['dx'],
                              dtype=torch.float32)
    assert dottest(gD1op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = torch.from_numpy((np.outer(
        (par['dz'] * np.arange(par['nz']))**2, np.ones(
            (par['ny'],
             par['nx']))).reshape(par['nz'], par['ny'],
                                  par['nx'])).astype(dtype='float32'))

    D1op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=2,
                            sampling=par['dx'],
                            dtype='float32')

    gy = (gD1op * x.view(-1)).reshape(par['nz'], par['ny'],
                                      par['nx']).cpu().numpy()
    y = (D1op * x.view(-1).cpu().numpy()).reshape(par['nz'], par['ny'],
                                                  par['nx'])
    assert_array_almost_equal(gy[1:-1], y[1:-1], decimal=5)
예제 #5
0
def test_SecondDerivative(par):
    """Dot-test and forward for SecondDerivative operator
        The test is based on the fact that the central stencil is exact for polynomials of
        degree 3.
    """

    x = par['dx'] * np.arange(par['nx'])
    y = par['dy'] * np.arange(par['ny'])
    z = par['dz'] * np.arange(par['nz'])

    xx, yy = np.meshgrid(x, y)  # produces arrays of size (ny,nx)
    xxx, yyy, zzz = np.meshgrid(x, y, z)  # produces arrays of size (ny,nx,nz)

    # 1d
    D2op = SecondDerivative(par['nx'],
                            sampling=par['dx'],
                            edge=par['edge'],
                            dtype='float32')
    assert dottest(D2op, par['nx'], par['nx'], tol=1e-3)

    # polynomial f(x) = x^3, f''(x) = 6x
    f = x**3
    dfana = 6 * x
    df = D2op * f
    assert_array_almost_equal(df[1:-1], dfana[1:-1], decimal=1)

    # 2d - derivative on 1st direction
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dy'],
                            edge=par['edge'],
                            dtype='float32')

    assert dottest(D2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    # polynomial f(x,y) = y^3, f_{yy}(x,y) = 6y
    f = yy**3
    dfana = 6 * yy
    df = D2op * f.flatten()
    df = df.reshape(par['ny'], par['nx'])
    assert_array_almost_equal(df[1:-1, :], dfana[1:-1, :], decimal=1)

    # 2d - derivative on 2nd direction
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dx'],
                            edge=par['edge'],
                            dtype='float32')

    assert dottest(D2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    # polynomial f(x,y) = x^3, f_{xx}(x,y) = 6x
    f = xx**3
    dfana = 6 * xx
    df = D2op * f.flatten()
    df = df.reshape(par['ny'], par['nx'])
    assert_array_almost_equal(df[:, 1:-1], dfana[:, 1:-1], decimal=1)

    # 3d - derivative on 1st direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx'], par['nz']),
                            dir=0,
                            sampling=par['dy'],
                            edge=par['edge'],
                            dtype='float32')

    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    # polynomial f(x,y,z) = y^3, f_{yy}(x,y,z) = 6y
    f = yyy**3
    dfana = 6 * yyy
    df = D2op * f.flatten()
    df = df.reshape(par['ny'], par['nx'], par['nz'])

    assert_array_almost_equal(df[1:-1, :, :], dfana[1:-1, :, :], decimal=1)

    # 3d - derivative on 2nd direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx'], par['nz']),
                            dir=1,
                            sampling=par['dx'],
                            edge=par['edge'],
                            dtype='float32')

    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    # polynomial f(x,y,z) = x^3, f_{xx}(x,y,z) = 6x
    f = xxx**3
    dfana = 6 * xxx
    df = D2op * f.flatten()
    df = df.reshape(par['ny'], par['nx'], par['nz'])

    assert_array_almost_equal(df[:, 1:-1, :], dfana[:, 1:-1, :], decimal=1)

    # 3d - derivative on 3rd direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx'], par['nz']),
                            dir=2,
                            sampling=par['dz'],
                            edge=par['edge'],
                            dtype='float32')

    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['ny'] * par['nx'] * par['nz'],
                   tol=1e-3)

    # polynomial f(x,y,z) = z^3, f_{zz}(x,y,z) = 6z
    f = zzz**3
    dfana = 6 * zzz
    df = D2op * f.flatten()
    df = df.reshape(par['ny'], par['nx'], par['nz'])

    assert_array_almost_equal(df[:, :, 1:-1], dfana[:, :, 1:-1], decimal=1)
예제 #6
0
def test_SecondDerivative(par):
    """Dot-test and forward for  SecondDerivative operator
    """
    # 1d
    D2op = SecondDerivative(par['nx'], sampling=par['dx'], dtype='float32')
    assert dottest(D2op, par['nx'], par['nx'], tol=1e-3)

    x = (par['dx'] * np.arange(par['nx']))**3
    yana = 6 * par['dx']**2 * np.arange(par['nx'])
    y = D2op * x
    assert_array_almost_equal(y[2:-2], yana[2:-2], decimal=1)

    # 2d - derivative on 1st direction
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dy'],
                            dtype='float32')
    assert dottest(D2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    x = np.outer((par['dy'] * np.arange(par['ny']))**3, np.ones(par['nx']))
    yana = np.outer(6 * par['dy']**2 * np.arange(par['ny']),
                    np.ones(par['nx']))
    y = D2op * x.flatten()
    y = y.reshape(par['ny'], par['nx'])
    assert_array_almost_equal(y[1:-1], yana[1:-1], decimal=1)

    # 2d - derivative on 2nd direction
    D2op = SecondDerivative(par['ny'] * par['nx'],
                            dims=(par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dx'],
                            dtype='float32')
    assert dottest(D2op,
                   par['ny'] * par['nx'],
                   par['ny'] * par['nx'],
                   tol=1e-3)

    x = np.outer((par['dy'] * np.arange(par['ny']))**3, np.ones(par['nx']))
    yana = np.zeros((par['ny'], par['nx']))
    y = D2op * x.flatten()
    y = y.reshape(par['ny'], par['nx'])
    assert_array_almost_equal(y[1:-1], yana[1:-1], decimal=1)

    # 3d - derivative on 1st direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=0,
                            sampling=par['dz'],
                            dtype='float32')
    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = np.outer((par['dz'] * np.arange(par['nz']))**3,
                 np.ones(
                     (par['ny'], par['nx']))).reshape(par['nz'], par['ny'],
                                                      par['nx'])
    yana = np.outer(6 * par['dz']**2 * np.arange(par['nz']),
                    np.ones((par['ny'],
                             par['nx']))).reshape(par['nz'], par['ny'],
                                                  par['nx'])
    y = D2op * x.flatten()
    y = y.reshape(par['nz'], par['ny'], par['nx'])
    assert_array_almost_equal(y[1:-1], yana[1:-1], decimal=1)

    # 3d - derivative on 2nd direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=1,
                            sampling=par['dy'],
                            dtype='float32')
    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = np.outer((par['dz'] * np.arange(par['nz']))**3,
                 np.ones(
                     (par['ny'], par['nx']))).reshape(par['nz'], par['ny'],
                                                      par['nx'])
    yana = np.zeros((par['nz'], par['ny'], par['nx']))
    y = D2op * x.flatten()
    y = y.reshape(par['nz'], par['ny'], par['nx'])
    assert_array_almost_equal(y[1:-1], yana[1:-1], decimal=1)

    # 3d - derivative on 3rd direction
    D2op = SecondDerivative(par['nz'] * par['ny'] * par['nx'],
                            dims=(par['nz'], par['ny'], par['nx']),
                            dir=2,
                            sampling=par['dx'],
                            dtype='float32')
    assert dottest(D2op,
                   par['nz'] * par['ny'] * par['nx'],
                   par['nz'] * par['ny'] * par['nx'],
                   tol=1e-3)

    x = np.outer((par['dz'] * np.arange(par['nz']))**3,
                 np.ones(
                     (par['ny'], par['nx']))).reshape(par['nz'], par['ny'],
                                                      par['nx'])
    yana = np.zeros((par['nz'], par['ny'], par['nx']))
    y = D2op * x.flatten()
    y = y.reshape(par['nz'], par['ny'], par['nx'])
    assert_array_almost_equal(y[1:-1], yana[1:-1], decimal=1)
예제 #7
0
def Laplacian(
        dims,
        dirs=(0, 1),
        weights=(1, 1),
        sampling=(1, 1),
        edge=False,
        dtype="float64",
        kind="centered",
):
    r"""Laplacian.

    Apply second-order centered Laplacian operator to a multi-dimensional array.

    .. note:: At least 2 dimensions are required, use
      :py:func:`pylops.SecondDerivative` for 1d arrays.

    Parameters
    ----------
    dims : :obj:`tuple`
        Number of samples for each dimension.
    dirs : :obj:`tuple`, optional
        Directions along which laplacian is applied.
    weights : :obj:`tuple`, optional
        Weight to apply to each direction (real laplacian operator if
        ``weights=[1,1]``)
    sampling : :obj:`tuple`, optional
        Sampling steps for each direction
    edge : :obj:`bool`, optional
        Use reduced order derivative at edges (``True``) or
        ignore them (``False``) for centered derivative
    dtype : :obj:`str`, optional
        Type of elements in input array.
    kind : :obj:`str`, optional
        Derivative kind (``forward``, ``centered``, or ``backward``)

    Returns
    -------
    l2op : :obj:`pylops.LinearOperator`
        Laplacian linear operator

    Raises
    ------
    ValueError
        If ``dirs``. ``weights``, and ``sampling`` do not have the same size

    Notes
    -----
    The Laplacian operator applies a second derivative along two directions of
    a multi-dimensional array.

    For simplicity, given a two dimensional array, the Laplacian is:

    .. math::
        y[i, j] = (x[i+1, j] + x[i-1, j] + x[i, j-1] +x[i, j+1] - 4x[i, j])
                  / (\Delta x \Delta y)

    """
    if not (len(dirs) == len(weights) == len(sampling)):
        raise ValueError("dirs, weights, and sampling have different size")

    l2op = weights[0] * SecondDerivative(
        np.prod(dims),
        dims=dims,
        dir=dirs[0],
        sampling=sampling[0],
        edge=edge,
        kind=kind,
        dtype=dtype,
    )

    for dir, samp, weight in zip(dirs[1:], sampling[1:], weights[1:]):
        l2op += weight * SecondDerivative(
            np.prod(dims),
            dims=dims,
            dir=dir,
            sampling=samp,
            edge=edge,
            dtype=dtype,
        )

    return aslinearoperator(l2op)
예제 #8
0
def test_SecondDerivative_forward(par):
    """Dot-test for SecondDerivative operator (forward stencil).
    Note that the analytical expression cannot be validated in this case
    """
    x = par["dx"] * np.arange(par["nx"])
    y = par["dy"] * np.arange(par["ny"])
    z = par["dz"] * np.arange(par["nz"])

    xx, yy = np.meshgrid(x, y)  # produces arrays of size (ny,nx)
    xxx, yyy, zzz = np.meshgrid(x, y, z)  # produces arrays of size (ny,nx,nz)

    # 1d
    D2op = SecondDerivative(par["nx"],
                            sampling=par["dx"],
                            edge=par["edge"],
                            kind="forward",
                            dtype="float32")
    assert dottest(D2op, par["nx"], par["nx"], tol=1e-3)

    # 2d - derivative on 1st direction
    D2op = SecondDerivative(
        par["ny"] * par["nx"],
        dims=(par["ny"], par["nx"]),
        dir=0,
        sampling=par["dy"],
        edge=par["edge"],
        kind="forward",
        dtype="float32",
    )

    assert dottest(D2op,
                   par["ny"] * par["nx"],
                   par["ny"] * par["nx"],
                   tol=1e-3)

    # 2d - derivative on 2nd direction
    D2op = SecondDerivative(
        par["ny"] * par["nx"],
        dims=(par["ny"], par["nx"]),
        dir=1,
        sampling=par["dx"],
        edge=par["edge"],
        kind="forward",
        dtype="float32",
    )

    assert dottest(D2op,
                   par["ny"] * par["nx"],
                   par["ny"] * par["nx"],
                   tol=1e-3)

    # 3d - derivative on 1st direction
    D2op = SecondDerivative(
        par["nz"] * par["ny"] * par["nx"],
        dims=(par["ny"], par["nx"], par["nz"]),
        dir=0,
        sampling=par["dy"],
        edge=par["edge"],
        kind="forward",
        dtype="float32",
    )

    assert dottest(
        D2op,
        par["nz"] * par["ny"] * par["nx"],
        par["nz"] * par["ny"] * par["nx"],
        tol=1e-3,
    )

    # 3d - derivative on 2nd direction
    D2op = SecondDerivative(
        par["nz"] * par["ny"] * par["nx"],
        dims=(par["ny"], par["nx"], par["nz"]),
        dir=1,
        sampling=par["dx"],
        edge=par["edge"],
        kind="forward",
        dtype="float32",
    )

    assert dottest(
        D2op,
        par["nz"] * par["ny"] * par["nx"],
        par["nz"] * par["ny"] * par["nx"],
        tol=1e-3,
    )

    # 3d - derivative on 3rd direction
    D2op = SecondDerivative(
        par["nz"] * par["ny"] * par["nx"],
        dims=(par["ny"], par["nx"], par["nz"]),
        dir=2,
        sampling=par["dz"],
        edge=par["edge"],
        kind="forward",
        dtype="float32",
    )

    assert dottest(
        D2op,
        par["nz"] * par["ny"] * par["nx"],
        par["ny"] * par["nx"] * par["nz"],
        tol=1e-3,
    )