예제 #1
0
def test_eigs(par):
    """Eigenvalues and condition number estimate with ARPACK"""
    # explicit=True
    diag = np.arange(par["nx"], 0,
                     -1) + par["imag"] * np.arange(par["nx"], 0, -1)
    Op = MatrixMult(
        np.vstack((np.diag(diag), np.zeros(
            (par["ny"] - par["nx"], par["nx"])))))
    eigs = Op.eigs()
    assert_array_almost_equal(diag[:eigs.size], eigs, decimal=3)

    cond = Op.cond()
    assert_array_almost_equal(np.real(cond), par["nx"], decimal=3)

    # explicit=False
    Op = Diagonal(diag, dtype=par["dtype"])
    if par["ny"] > par["nx"]:
        Op = VStack([Op, Zero(par["ny"] - par["nx"], par["nx"])])
    eigs = Op.eigs()
    assert_array_almost_equal(diag[:eigs.size], eigs, decimal=3)

    # uselobpcg cannot be used for square non-symmetric complex matrices
    if np.iscomplex(Op):
        eigs1 = Op.eigs(uselobpcg=True)
        assert_array_almost_equal(eigs, eigs1, decimal=3)

    cond = Op.cond()
    assert_array_almost_equal(np.real(cond), par["nx"], decimal=3)

    if np.iscomplex(Op):
        cond1 = Op.cond(uselobpcg=True, niter=100)
        assert_array_almost_equal(np.real(cond), np.real(cond1), decimal=3)
예제 #2
0
def test_VStack(par):
    """Dot-test and inversion for VStack operator"""
    np.random.seed(0)
    G1 = np.random.normal(0, 10, (par["ny"], par["nx"])).astype(par["dtype"])
    G2 = np.random.normal(0, 10, (par["ny"], par["nx"])).astype(par["dtype"])
    x = np.ones(par["nx"]) + par["imag"] * np.ones(par["nx"])

    Vop = VStack(
        [MatrixMult(G1, dtype=par["dtype"]), MatrixMult(G2, dtype=par["dtype"])],
        dtype=par["dtype"],
    )
    assert dottest(
        Vop, 2 * par["ny"], par["nx"], complexflag=0 if par["imag"] == 0 else 3
    )

    xlsqr = lsqr(Vop, Vop * x, damp=1e-20, iter_lim=300, atol=1e-8, btol=1e-8, show=0)[
        0
    ]
    assert_array_almost_equal(x, xlsqr, decimal=4)

    # use numpy matrix directly in the definition of the operator
    V1op = VStack([G1, MatrixMult(G2, dtype=par["dtype"])], dtype=par["dtype"])
    assert dottest(
        V1op, 2 * par["ny"], par["nx"], complexflag=0 if par["imag"] == 0 else 3
    )

    # use scipy matrix directly in the definition of the operator
    G1 = sp_random(par["ny"], par["nx"], density=0.4).astype("float32")
    V2op = VStack([G1, MatrixMult(G2, dtype=par["dtype"])], dtype=par["dtype"])
    assert dottest(
        V2op, 2 * par["ny"], par["nx"], complexflag=0 if par["imag"] == 0 else 3
    )
예제 #3
0
def test_HStack(par):
    """Dot-test and inversion for HStack operator with numpy array as input
    """
    np.random.seed(0)
    G1 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    G2 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    x = np.ones(2 * par['nx']) + par['imag'] * np.ones(2 * par['nx'])

    Hop = HStack([G1, MatrixMult(G2, dtype=par['dtype'])], dtype=par['dtype'])
    assert dottest(Hop,
                   par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)

    xlsqr = lsqr(Hop, Hop * x, damp=1e-20, iter_lim=300, show=0)[0]
    assert_array_almost_equal(x, xlsqr, decimal=4)

    # use numpy matrix directly in the definition of the operator
    H1op = HStack([G1, MatrixMult(G2, dtype=par['dtype'])], dtype=par['dtype'])
    assert dottest(H1op,
                   par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)

    # use scipy matrix directly in the definition of the operator
    G1 = sp_random(par['ny'], par['nx'], density=0.4).astype('float32')
    H2op = HStack([G1, MatrixMult(G2, dtype=par['dtype'])], dtype=par['dtype'])
    assert dottest(H2op,
                   par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)
예제 #4
0
def test_BlockDiag_multiproc(par):
    """Single and multiprocess consistentcy for BlockDiag operator
    """
    np.random.seed(0)
    nproc = 2
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    x = np.ones(4 * par['nx']) + par['imag'] * np.ones(4 * par['nx'])
    y = np.ones(4 * par['ny']) + par['imag'] * np.ones(4 * par['ny'])

    BDop = BlockDiag([MatrixMult(G, dtype=par['dtype'])] * 4,
                     dtype=par['dtype'])
    BDmultiop = BlockDiag([MatrixMult(G, dtype=par['dtype'])] * 4,
                          nproc=nproc,
                          dtype=par['dtype'])
    assert dottest(BDmultiop,
                   4 * par['ny'],
                   4 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)
    # forward
    assert_array_almost_equal(BDop * x, BDmultiop * x, decimal=4)
    # adjoint
    assert_array_almost_equal(BDop.H * y, BDmultiop.H * y, decimal=4)

    # close pool
    BDmultiop.pool.close()
예제 #5
0
def test_realimag(par):
    """Real/imag extraction"""
    M = np.random.normal(0, 1, (
        par["ny"], par["nx"])) + 1j * np.random.normal(0, 1,
                                                       (par["ny"], par["nx"]))
    Op = MatrixMult(M, dtype=np.complex128)

    Opr = Op.toreal()
    Opi = Op.toimag()

    # forward
    x = np.arange(par["nx"])
    y = Op * x
    yr = Opr * x
    yi = Opi * x

    assert_array_equal(np.real(y), yr)
    assert_array_equal(np.imag(y), yi)

    # adjoint
    y = np.arange(par["ny"]) + 1j * np.arange(par["ny"])
    x = Op.H * y
    xr = Opr.H * y
    xi = Opi.H * y

    assert_array_equal(np.real(x), xr)
    assert_array_equal(np.imag(x), -xi)
예제 #6
0
def test_RegularizedInversion(par):
    """Solve regularized inversion in least squares sense
    """
    np.random.seed(10)
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \
        par['imag']*np.random.normal(0, 10,
                                     (par['ny'], par['nx'])).astype('float32')
    Gop = MatrixMult(G, dtype=par['dtype'])
    Reg = MatrixMult(np.eye(par['nx']), dtype=par['dtype'])
    Weigth = Diagonal(np.ones(par['ny']), dtype=par['dtype'])
    x = np.ones(par['nx']) + par['imag']*np.ones(par['nx'])
    x0 = np.random.normal(0, 10, par['nx']) + \
         par['imag']*np.random.normal(0, 10, par['nx']) if par['x0'] else None
    y = Gop*x

    # regularized inversion with regularization
    xinv = RegularizedInversion(Gop, [Reg], y, epsRs=[1e-8], x0=x0,
                                returninfo=False,
                                **dict(damp=0, iter_lim=200, show=0))
    assert_array_almost_equal(x, xinv, decimal=3)
    # regularized inversion with weight
    xinv = RegularizedInversion(Gop, None, y, Weight=Weigth,
                                x0=x0,
                                returninfo=False,
                                **dict(damp=0, iter_lim=200, show=0))
    assert_array_almost_equal(x, xinv, decimal=3)
    # regularized inversion with regularization
    xinv = RegularizedInversion(Gop, [Reg], y, Weight=Weigth,
                                epsRs=[1e-8], x0=x0,
                                returninfo=False,
                                **dict(damp=0, iter_lim=200, show=0))
    assert_array_almost_equal(x, xinv, decimal=3)
예제 #7
0
def test_NormalEquationsInversion(par):
    """Solve normal equations in least squares sense
    """
    np.random.seed(10)
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \
        par['imag']*np.random.normal(0, 10,
                                     (par['ny'], par['nx'])).astype('float32')
    Gop = MatrixMult(G, dtype=par['dtype'])

    Reg = MatrixMult(np.eye(par['nx']), dtype=par['dtype'])
    Weigth = Diagonal(np.ones(par['ny']), dtype=par['dtype'])
    x = np.ones(par['nx']) + par['imag']*np.ones(par['nx'])
    x0 = np.random.normal(0, 10, par['nx']) + \
         par['imag']*np.random.normal(0, 10, par['nx']) if par['x0'] else None
    y = Gop*x

    # normal equations with regularization
    xinv = NormalEquationsInversion(Gop, [Reg], y, epsI=0,
                                    epsRs=[1e-8], x0=x0,
                                    returninfo=False,
                                    **dict(maxiter=200, tol=1e-10))
    assert_array_almost_equal(x, xinv, decimal=3)
    # normal equations with weight
    xinv = NormalEquationsInversion(Gop, None, y, Weight=Weigth, epsI=0,
                                    x0=x0, returninfo=False,
                                    **dict(maxiter=200, tol=1e-10))
    assert_array_almost_equal(x, xinv, decimal=3)
    # normal equations with weight and small regularization
    xinv = NormalEquationsInversion(Gop, [Reg], y, Weight=Weigth, epsI=0,
                                    epsRs=[1e-8], x0=x0, returninfo=False,
                                    **dict(maxiter=200, tol=1e-10))
    assert_array_almost_equal(x, xinv, decimal=3)
예제 #8
0
def test_Block(par):
    """Dot-test and inversion for Block operator
    """
    np.random.seed(10)
    G11 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G12 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G21 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G22 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])

    x = np.ones(2 * par['nx']) + par['imag'] * np.ones(2 * par['nx'])

    Bop = Block([[
        MatrixMult(G11, dtype=par['dtype']),
        MatrixMult(G12, dtype=par['dtype'])
    ],
                 [
                     MatrixMult(G21, dtype=par['dtype']),
                     MatrixMult(G22, dtype=par['dtype'])
                 ]],
                dtype=par['dtype'])
    assert dottest(Bop,
                   2 * par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)

    xlsqr = lsqr(Bop, Bop * x, damp=1e-20, iter_lim=500, show=0)[0]
    assert_array_almost_equal(x, xlsqr, decimal=3)
예제 #9
0
def test_HStack_incosistent_columns(par):
    """Check error is raised if operators with different number of rows
    are passed to VStack
    """
    G1 = np.random.normal(0, 10, (par["ny"], par["nx"])).astype(par["dtype"])
    G2 = np.random.normal(0, 10, (par["ny"] + 1, par["nx"])).astype(par["dtype"])
    with pytest.raises(ValueError):
        HStack(
            [MatrixMult(G1, dtype=par["dtype"]), MatrixMult(G2, dtype=par["dtype"])],
            dtype=par["dtype"],
        )
예제 #10
0
def test_VStack_incosistent_columns(par):
    """Check error is raised if operators with different number of columns
    are passed to VStack
    """
    G1 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G2 = np.random.normal(0, 10,
                          (par['ny'], par['nx'] + 1)).astype(par['dtype'])
    with pytest.raises(ValueError):
        VStack([
            MatrixMult(G1, dtype=par['dtype']),
            MatrixMult(G2, dtype=par['dtype'])
        ],
               dtype=par['dtype'])
예제 #11
0
def test_conj(par):
    """Complex conjugation operator"""
    M = 1j * np.ones((par["ny"], par["nx"]))
    Op = MatrixMult(M, dtype=np.complex128)
    Opconj = Op.conj()

    x = np.arange(par["nx"]) + par["imag"] * np.arange(par["nx"])
    y = Opconj * x

    # forward
    assert_array_almost_equal(Opconj * x, np.dot(M.conj(), x))

    # adjoint
    assert_array_almost_equal(Opconj.H * y, np.dot(M.T, y))
예제 #12
0
def test_HStack(par):
    """Dot-test and inversion for HStack operator
    """
    np.random.seed(10)
    G1 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    G2 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    x = np.ones(2*par['nx']) + par['imag']*np.ones(2*par['nx'])

    Hop = HStack([MatrixMult(G1, dtype=par['dtype']),
                  MatrixMult(G2, dtype=par['dtype'])],
                 dtype=par['dtype'])
    assert dottest(Hop, par['ny'], 2*par['nx'], complexflag=0 if par['imag'] == 0 else 3)

    xlsqr = lsqr(Hop, Hop * x, damp=1e-20, iter_lim=300, show=0)[0]
    assert_array_almost_equal(x, xlsqr, decimal=4)
예제 #13
0
def test_Block_multiproc(par):
    """Single and multiprocess consistentcy for Block operator
    """
    np.random.seed(0)
    nproc = 2
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    Gvert = [MatrixMult(G, dtype=par['dtype'])] * 2
    Ghor = [Gvert] * 4
    print(Ghor)
    x = np.ones(2 * par['nx']) + par['imag'] * np.ones(2 * par['nx'])
    y = np.ones(4 * par['ny']) + par['imag'] * np.ones(4 * par['ny'])

    Bop = Block(Ghor, dtype=par['dtype'])
    Bmultiop = Block(Ghor, nproc=nproc, dtype=par['dtype'])
    assert dottest(Bmultiop,
                   4 * par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)
    # forward
    assert_array_almost_equal(Bop * x, Bmultiop * x, decimal=3)
    # adjoint
    assert_array_almost_equal(Bop.H * y, Bmultiop.H * y, decimal=3)

    # close pool
    Bmultiop.pool.close()
예제 #14
0
파일: VStack.py 프로젝트: mrava87/pylops
 def __init__(self, ops, nproc=1, dtype=None):
     self.ops = ops
     nops = np.zeros(len(self.ops), dtype=int)
     for iop, oper in enumerate(ops):
         if not isinstance(oper, (LinearOperator, spLinearOperator)):
             self.ops[iop] = MatrixMult(oper, dtype=oper.dtype)
         nops[iop] = self.ops[iop].shape[0]
     self.nops = int(nops.sum())
     mops = [oper.shape[1] for oper in self.ops]
     if len(set(mops)) > 1:
         raise ValueError("operators have different number of columns")
     self.mops = int(mops[0])
     self.nnops = np.insert(np.cumsum(nops), 0, 0)
     # create pool for multiprocessing
     self._nproc = nproc
     self.pool = None
     if self.nproc > 1:
         self.pool = mp.Pool(processes=nproc)
     self.shape = (self.nops, self.mops)
     if dtype is None:
         self.dtype = _get_dtype(self.ops)
     else:
         self.dtype = np.dtype(dtype)
     self.explicit = False
     self.clinear = all(
         [getattr(oper, "clinear", True) for oper in self.ops])
예제 #15
0
def test_WeightedInversion(par):
    """Compare results for normal equations and regularized inversion
    when used to solve weighted least square inversion
    """
    np.random.seed(10)
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \
        par['imag'] * np.random.normal(0, 10, (par['ny'], par['nx'])).astype(
            'float32')
    Gop = MatrixMult(G, dtype=par['dtype'])
    w = np.arange(par['ny'])
    w1 = np.sqrt(w)
    Weigth = Diagonal(w, dtype=par['dtype'])
    Weigth1 = Diagonal(w1, dtype=par['dtype'])
    x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])
    y = Gop * x

    xne = NormalEquationsInversion(Gop, None, y, Weight=Weigth,
                                   returninfo=False,
                                   **dict(maxiter=5, tol=1e-10))
    xreg = RegularizedInversion(Gop, None, y, Weight=Weigth1,
                                returninfo=False,
                                **dict(damp=0, iter_lim=5, show=0))
    print(xne)
    print(xreg)
    assert_array_almost_equal(xne, xreg, decimal=3)
예제 #16
0
 def __init__(self, ops, nproc=1, dtype=None):
     self.ops = ops
     mops = np.zeros(len(ops), dtype=np.int)
     nops = np.zeros(len(ops), dtype=np.int)
     for iop, oper in enumerate(ops):
         if not isinstance(oper, (LinearOperator, spLinearOperator)):
             self.ops[iop] = MatrixMult(oper, dtype=oper.dtype)
         nops[iop] = self.ops[iop].shape[0]
         mops[iop] = self.ops[iop].shape[1]
     self.nops = int(nops.sum())
     self.mops = int(mops.sum())
     self.nnops = np.insert(np.cumsum(nops), 0, 0)
     self.mmops = np.insert(np.cumsum(mops), 0, 0)
     # create pool for multiprocessing
     self._nproc = nproc
     self.pool = None
     if self.nproc > 1:
         self.pool = mp.Pool(processes=nproc)
     self.shape = (self.nops, self.mops)
     if dtype is None:
         self.dtype = _get_dtype(ops)
     else:
         self.dtype = np.dtype(dtype)
     self.explicit = False
     self.clinear = all(
         [getattr(oper, 'clinear', True) for oper in self.ops])
예제 #17
0
def test_BlockDiag_rlinear(par):
    """BlockDiag operator applied to mix of R-linear and C-linear operators
    """
    np.random.seed(0)
    if np.dtype(par['dtype']).kind == 'c':
        G = ((np.random.normal(0, 10, (par['ny'], par['nx'])) +
              1j * np.random.normal(0, 10, (par['ny'], par['nx']))).astype(
                  par['dtype']))
    else:
        G = np.random.normal(0, 10,
                             (par['ny'], par['nx'])).astype(par['dtype'])
    Rop = Real(dims=(par['nx'], ), dtype=par['dtype'])

    BDop = BlockDiag([Rop, MatrixMult(G, dtype=par['dtype'])],
                     dtype=par['dtype'])
    assert BDop.clinear == False
    assert dottest(BDop,
                   par['nx'] + par['ny'],
                   2 * par['nx'],
                   complexflag=0 if par['imag'] == 0 else 3)
    # forward
    x = np.random.randn(
        2 * par['nx']) + par['imag'] * np.random.randn(2 * par['nx'])
    expected = np.concatenate([np.real(x[:par['nx']]), G @ x[par['nx']:]])
    assert_array_almost_equal(expected, BDop * x, decimal=4)
예제 #18
0
def test_Sliding3D(par):
    """Dot-test and inverse for Sliding3D operator"""
    Op = MatrixMult(
        np.ones((par["nwiny"] * par["nwinx"] * par["nt"],
                 par["ny"] * par["nx"] * par["nt"])))

    Slid = Sliding3D(
        Op,
        dims=(par["ny"] * par["winsy"], par["nx"] * par["winsx"], par["nt"]),
        dimsd=(par["npy"], par["npx"], par["nt"]),
        nwin=(par["nwiny"], par["nwinx"]),
        nover=(par["novery"], par["noverx"]),
        nop=(par["ny"], par["nx"]),
        tapertype=par["tapertype"],
    )
    assert dottest(
        Slid,
        par["npy"] * par["npx"] * par["nt"],
        par["ny"] * par["nx"] * par["nt"] * par["winsy"] * par["winsx"],
    )
    x = np.ones(
        (par["ny"] * par["nx"] * par["winsy"] * par["winsx"], par["nt"]))
    y = Slid * x.ravel()

    xinv = LinearOperator(Slid) / y
    assert_array_almost_equal(x.ravel(), xinv)
예제 #19
0
def test_lsqr(par):
    """Compare local Pylops and scipy LSQR
    """
    np.random.seed(10)

    A = np.random.normal(0, 10, (par['ny'], par['nx'])) + \
        par['imag'] * np.random.normal(0, 10, (par['ny'], par['nx']))
    Aop = MatrixMult(A, dtype=par['dtype'])

    x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])
    if par['x0']:
        x0 = np.random.normal(0, 10, par['nx']) + \
             par['imag'] * np.random.normal(0, 10, par['nx'])
    else:
        x0 = None
    y = Aop * x
    if par['x0']:
        y_sp = y - Aop * x0
    else:
        y_sp = y.copy()
    xinv = lsqr(Aop, y, x0, niter=par['nx'])[0]
    xinv_sp = sp_lsqr(Aop, y_sp, iter_lim=par['nx'])[0]
    if par['x0']:
        xinv_sp += x0

    assert_array_almost_equal(xinv, x, decimal=4)
    assert_array_almost_equal(xinv_sp, x, decimal=4)
예제 #20
0
def test_IRLS(par):
    """Invert problem with IRLS
    """
    np.random.seed(10)
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \
        par['imag']*np.random.normal(0, 10, (par['ny'],
                                             par['nx'])).astype('float32')
    Gop = MatrixMult(G, dtype=par['dtype'])
    x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])
    x0 = np.random.normal(0, 10, par['nx']) + \
         par['imag']*np.random.normal(0, 10, par['nx']) if par['x0'] else None
    y = Gop * x

    # add outlier
    y[par['ny'] - 2] *= 5

    # normal equations with regularization
    xinv, _ = IRLS(Gop,
                   y,
                   10,
                   threshR=False,
                   epsR=1e-2,
                   epsI=0,
                   x0=x0,
                   tolIRLS=1e-3,
                   returnhistory=False)
    assert_array_almost_equal(x, xinv, decimal=3)
예제 #21
0
def test_memoize_evals(par):
    """Check nevals counter when same model/data vectors are inputted
    to the operator
    """
    A = np.random.normal(
        0, 10, (par["ny"],
                par["nx"])).astype("float32") + par["imag"] * np.random.normal(
                    0, 10, (par["ny"], par["nx"])).astype("float32")
    Aop = MatrixMult(A, dtype=par["dtype"])
    Amemop = MemoizeOperator(Aop, max_neval=2)

    # 1st evaluation
    Amemop * np.ones(par["nx"])
    assert Amemop.neval == 1
    # repeat 1st evaluation multiple times
    for _ in range(2):
        Amemop * np.ones(par["nx"])
    assert Amemop.neval == 1
    # 2nd evaluation
    Amemop * np.full(par["nx"], 2)  # same
    assert Amemop.neval == 2
    # 3rd evaluation (np.ones goes out of store)
    Amemop * np.full(par["nx"], 3)  # same
    assert Amemop.neval == 3
    # 4th evaluation
    Amemop * np.ones(par["nx"])
    assert Amemop.neval == 4
예제 #22
0
def test_conj(par):
    """Complex conjugation
    """
    M = 1j * np.ones((par['ny'], par['nx']))
    Op = MatrixMult(M, dtype=np.complex)
    Opconj = Op.conj()

    x = np.arange(par['nx']) + \
        par['imag'] * np.arange(par['nx'])
    y = Opconj * x

    # forward
    assert_array_almost_equal(Opconj * x, np.dot(M.conj(), x))

    # adjoint
    assert_array_almost_equal(Opconj.H * y, np.dot(M.T, y))
예제 #23
0
def test_rlinear(par):
    """R-linear"""
    np.random.seed(123)
    if np.dtype(par["dtype"]).kind == "c":
        M = (np.random.randn(par["ny"], par["nx"]) +
             1j * np.random.randn(par["ny"], par["nx"])).astype(par["dtype"])
    else:
        M = np.random.randn(par["ny"], par["nx"]).astype(par["dtype"])

    OpM = MatrixMult(M, dtype=par["dtype"])
    OpR_left = Real(par["ny"], dtype=par["dtype"])
    OpR_right = Real(par["nx"], dtype=par["dtype"])

    Op_left = OpR_left * OpM
    Op_right = OpM * OpR_right

    assert Op_left.clinear == False
    assert Op_right.clinear == False

    # forward
    x = np.random.randn(par["nx"])
    y_left = Op_left * x
    y_right = Op_right * x

    assert_array_equal(np.real(M @ x), y_left)
    assert_array_equal(M @ np.real(x), y_right)

    # adjoint (dot product test)
    for complexflag in range(4):
        assert dottest(Op_left, par["ny"], par["nx"], complexflag=complexflag)
        assert dottest(Op_right, par["ny"], par["nx"], complexflag=complexflag)
예제 #24
0
def _sincinterp(M, iava, dims=None, dir=0, dtype='float64'):
    """Sinc interpolation.
    """
    ncp = get_array_module(iava)

    _checkunique(iava)

    # create sinc interpolation matrix
    nreg = M if dims is None else dims[dir]
    ireg = ncp.arange(nreg)
    sinc = ncp.tile(iava[:, np.newaxis], (1, nreg)) - \
           ncp.tile(ireg, (len(iava), 1))
    sinc = ncp.sinc(sinc)

    # identify additional dimensions and create MatrixMult operator
    otherdims = None
    if dims is not None:
        otherdims = ncp.array(dims)
        otherdims = ncp.roll(otherdims, -dir)
        otherdims = otherdims[1:]
    Op = MatrixMult(sinc, dims=otherdims, dtype=dtype)

    # create Transpose operator that brings dir to first dimension
    if dir > 0:
        axes = np.arange(len(dims), dtype=np.int)
        axes = np.roll(axes, -dir)
        dimsd =  list(dims)
        dimsd[dir] = len(iava)
        Top = Transpose(dims, axes=axes, dtype=dtype)
        T1op = Transpose(dimsd, axes=axes, dtype=dtype)
        Op = T1op.H * Op * Top
    return Op
예제 #25
0
def test_Kroneker(par):
    """Dot-test and inversion for Kronecker operator
    """
    np.random.seed(10)
    G1 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G2 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    x = np.ones(par['nx']**2) + par['imag'] * np.ones(par['nx']**2)

    Kop = Kronecker(MatrixMult(G1, dtype=par['dtype']),
                    MatrixMult(G2, dtype=par['dtype']),
                    dtype=par['dtype'])
    assert dottest(Kop,
                   par['ny']**2,
                   par['nx']**2,
                   complexflag=0 if par['imag'] == 0 else 3)

    xlsqr = lsqr(Kop, Kop * x, damp=1e-20, iter_lim=300, show=0)[0]
    assert_array_almost_equal(x, xlsqr, decimal=2)
예제 #26
0
def test_MatrixMult_complexcast(par):
    """Automatic upcasting of MatrixMult operator dtype based on complex
    matrix
    """
    np.random.seed(10)
    G = rand(par["ny"], par["nx"],
             density=0.75).astype("float32") + par["imag"] * rand(
                 par["ny"], par["nx"], density=0.75).astype("float32")

    Gop = MatrixMult(G, dtype="float32")
    assert Gop.dtype == "complex64"
예제 #27
0
def test_VStack(par):
    """Dot-test and comparison with pylops for VStack operator
    """
    np.random.seed(10)
    G1 = da.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    G2 = da.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
    x = da.ones(par['nx']) + par['imag']*da.ones(par['nx'])
    dops = [dMatrixMult(G1, dtype=par['dtype']),
            dMatrixMult(G2, dtype=par['dtype'])]
    ops = [MatrixMult(G1.compute(), dtype=par['dtype']),
           MatrixMult(G2.compute(), dtype=par['dtype'])]
    dVop = dVStack(dops, compute=(True, True), dtype=par['dtype'])
    Vop = VStack(ops, dtype=par['dtype'])
    assert dottest(dVop, 2*par['ny'], par['nx'],
                   chunks=(2*par['ny'], par['nx']),
                   complexflag=0 if par['imag'] == 0 else 3)

    dy = dVop * x.ravel()
    y = Vop * x.ravel().compute()
    assert_array_almost_equal(dy, y, decimal=4)
예제 #28
0
def test_HStack(par):
    """Dot-test and inversion for HStack operator
    """
    np.random.seed(10)
    G1 = da.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    G2 = da.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    x = da.ones(2 * par['nx']) + par['imag'] * da.ones(2 * par['nx'])
    dops = [dMatrixMult(G1, dtype=par['dtype']),
            dMatrixMult(G2, dtype=par['dtype'])]
    ops = [MatrixMult(G1.compute(), dtype=par['dtype']),
           MatrixMult(G2.compute(), dtype=par['dtype'])]
    dHop = dHStack(dops, compute=(True, True), dtype=par['dtype'])
    Hop = HStack(ops, dtype=par['dtype'])
    assert dottest(dHop, par['ny'], 2*par['nx'],
                   chunks=(par['ny'], 2*par['nx']),
                   complexflag=0 if par['imag'] == 0 else 3)

    dy = dHop * x.ravel()
    y = Hop * x.ravel().compute()
    assert_array_almost_equal(dy, y, decimal=4)
예제 #29
0
파일: test_eigs.py 프로젝트: mrava87/pylops
def test_power_iteration(par):
    """Max eigenvalue computation with power iteration method vs. scipy methods"""
    np.random.seed(10)

    A = np.random.randn(par["n"], par["n"]) + par["imag"] * np.random.randn(
        par["n"], par["n"])
    A1 = np.conj(A.T) @ A

    # non-symmetric
    Aop = MatrixMult(A)
    eig = power_iteration(Aop, niter=200, tol=0)[0]
    eig_np = np.max(np.abs(np.linalg.eig(A)[0]))

    assert np.abs(np.abs(eig) - eig_np) < 1e-3

    # symmetric
    A1op = MatrixMult(A1)
    eig = power_iteration(A1op, niter=200, tol=0)[0]
    eig_np = np.max(np.abs(np.linalg.eig(A1)[0]))

    assert np.abs(np.abs(eig) - eig_np) < 1e-3
예제 #30
0
def test_MatrixMult(par):
    """Dot-test and inversion for test_MatrixMult operator
    """
    np.random.seed(10)
    G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \
        par['imag']*np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32')
    Gop = MatrixMult(G, dtype=par['dtype'])
    assert dottest(Gop, par['ny'], par['nx'], complexflag=0 if par['imag'] == 0 else 3)

    x = np.ones(par['nx']) + par['imag']*np.ones(par['nx'])
    xlsqr = lsqr(Gop, Gop*x, damp=1e-20, iter_lim=300, show=0)[0]
    assert_array_almost_equal(x, xlsqr, decimal=4)