def solveWithRes(A, U, R):
    A = todia(A)
    d = foldMatFor(A)
    diagonalize = compose(todia, d.dot)
    undiagonalize = compose(lambda x: x.A[0], d.todense().I.dot)
    diaA = diagonalize(A)
    fp(diaA)
    ret = diaA.todense().I.dot(d.dot(U-R)).A[0]
    return ret
    def test_scale_and_combine_FGG_01(self):
        self.FGG.scale_and_combine_operators()
        ref = self.F.operators[(0,1)].copy()
        tst = self.FGG.operators[(0,1)].immigrate()
        npt.assert_array_almost_equal(tst.D.data, ref.D.data, decimal=14)
        tst.D *= 0
        ref.D *= 0
        npt.assert_equal(tst, ref)

        dom = np.random.random(self.FGG.grid.shape)
        ref = self.FGG.operators[(0,1)].apply(dom.copy())
        tst = self.F.operators[(0,1)].apply(dom)
        fp(ref - tst, 'e')
        npt.assert_array_almost_equal(tst, ref, decimal=14)
Beispiel #3
0
    def test_to_csr(self):
        A = self.F.operators[0].copy()
        A.R = None
        A.axis = 1
        A.dirichlet = (None, None)
        A.is_mixed_derivative = True
        B = BOG.BandedOperator(A)
        B = B.immigrate()
        B.D = B.D.tocsr()

        ref = A.apply(self.v2)
        tst = B.apply(self.v2)

        fp(ref - tst, 'e')

        npt.assert_array_almost_equal(ref, tst, decimal=12)

        B = BOG.BandedOperator(A)
        tst = B.apply(self.v2)

        fp(tst)
        fp(ref)
        fp(tst - ref, 'e')

        npt.assert_array_almost_equal(ref, tst, decimal=12)
    def test_scale_and_combine_FGG_01(self):
        self.FGG.scale_and_combine_operators()
        ref = self.F.operators[(0, 1)].copy()
        tst = self.FGG.operators[(0, 1)].immigrate()
        npt.assert_array_almost_equal(tst.D.data, ref.D.data, decimal=14)
        tst.D *= 0
        ref.D *= 0
        npt.assert_equal(tst, ref)

        dom = np.random.random(self.FGG.grid.shape)
        ref = self.FGG.operators[(0, 1)].apply(dom.copy())
        tst = self.F.operators[(0, 1)].apply(dom)
        fp(ref - tst, 'e')
        npt.assert_array_almost_equal(tst, ref, decimal=14)
Beispiel #5
0
 def test_derivative_solve_0(self):
     x = np.linspace(0,1,500)
     B = BO.for_vector(x)
     B.D.data[1,:] += 1
     B.D.data[1,0] = B.D.data[1,-1] = 2
     BG = BOG.BandedOperator(B)
     ref = np.e**x
     tst = BG.apply(ref) / 2
     fp(ref - tst, 'e')
     npt.assert_allclose(tst, ref, rtol=1e-4, atol=1e-6,
                         err_msg="d/dx (apply) not accurate")
     # fp(B.D.data)
     tst = BG.solve(ref) * 2
     npt.assert_allclose(ref, tst, rtol=1e-4, atol=1e-6,
                         err_msg="integral (solve) not accurate")
Beispiel #6
0
    def test_axis_1_derivative_2(self):
        B = self.F.simple_operators[(1,1)]
        BG = BOG.for_vector(self.F.grid.mesh[1],
                            self.F.grid.shape[0], 2, 1, 0).immigrate()


        fp(B.D.data)
        print
        fp(BG.D.data)
        print
        fp(B.D.data - BG.D.data)

        print B.D.offsets
        fp(B.D)
        print BG.D.offsets
        fp(BG.D)

        npt.assert_array_equal(B.D.data, BG.D.data)
        npt.assert_equal(B, BG)
Beispiel #7
0
    def test_combine_operators_1(self):
        ref = self.F.operators[1]
        npt.assert_array_equal([1, 0, -1, -2], ref.D.offsets)
        npt.assert_equal(ref.bottom_fold_status, "CAN_FOLD")
        fst = self.FG.simple_operators[(1, )]
        snd = self.FG.simple_operators[(1, 1)]
        tst = (fst + snd) + 0.5
        tst = tst.immigrate()
        npt.assert_array_equal([1, 0, -1, -2], tst.D.offsets)
        npt.assert_equal(tst.bottom_fold_status, "CAN_FOLD")
        tst.derivative = ref.derivative
        fp(tst.D.data - ref.D.data, 'e')

        tstD = tst.D.data
        refD = ref.D.data
        npt.assert_array_almost_equal(tstD, refD)

        tst.D.data *= 0
        ref.D.data *= 0
        npt.assert_equal(tst, ref)
    def test_combine_operators_1(self):
        ref = self.F.operators[1]
        npt.assert_array_equal([1, 0, -1, -2], ref.D.offsets)
        npt.assert_equal(ref.bottom_fold_status, "CAN_FOLD")
        fst = self.FG.simple_operators[(1,)]
        snd = self.FG.simple_operators[(1,1)]
        tst = (fst + snd) + 0.5
        tst = tst.immigrate()
        npt.assert_array_equal([1, 0, -1, -2], tst.D.offsets)
        npt.assert_equal(tst.bottom_fold_status, "CAN_FOLD")
        tst.derivative = ref.derivative
        fp(tst.D.data - ref.D.data, 'e')

        tstD = tst.D.data
        refD = ref.D.data
        npt.assert_array_almost_equal(tstD, refD)

        tst.D.data *= 0
        ref.D.data *= 0
        npt.assert_equal(tst, ref)
Beispiel #9
0
    def test_csr_solve(self):
        raise unittest.SkipTest
        A = self.F.operators[1].copy() + 1
        Tri = BOG.BandedOperator(A)
        A.diagonalize()
        Tri.diagonalize()

        # ref = A.apply(self.F.grid.domain[-1])
        # tst = Tri.apply(self.FG.grid.domain[-1])

        # fp(tst - ref, 'e')
        # npt.assert_array_almost_equal(ref, tst, decimal=11)

        A.is_mixed_derivative = True

        Csr = BOG.BandedOperator(A)

        # ref = Tri.immigrate()
        # tst = Csr.immigrate()
        # fp(tst.D.data)
        # fp(tst.D.indices)
        # fp(tst.D.indptr)
        # tst.is_mixed_derivative = False
        # npt.assert_equal(tst, ref)

        # domT = self.FG.gpugrid.copy(True)
        # domC = self.FG.gpugrid.copy(True)
        # domT = SizedArrayPtr(self.F.grid.domain[-1])
        # domC = SizedArrayPtr(self.F.grid.domain[-1])

        # Csr.solve_(domC, True)
        # tst = Csr.immigrate().solve(domC.to_numpy())
        # Tri.solve_(domT, True)

        tst = domC.to_numpy()
        ref = domT.to_numpy()

        print "Ref"
        fp(ref)
        print "Test"
        fp(tst)
        print "Diff"
        fp(tst - ref)

        npt.assert_array_almost_equal(ref, tst, decimal=11)
        assert False
    def test_csr_solve(self):
        raise unittest.SkipTest
        A = self.F.operators[1].copy() + 1
        Tri = BOG.BandedOperator(A)
        A.diagonalize()
        Tri.diagonalize()

        # ref = A.apply(self.F.grid.domain[-1])
        # tst = Tri.apply(self.FG.grid.domain[-1])

        # fp(tst - ref, 'e')
        # npt.assert_array_almost_equal(ref, tst, decimal=11)

        A.is_mixed_derivative = True

        Csr = BOG.BandedOperator(A)

        # ref = Tri.immigrate()
        # tst = Csr.immigrate()
        # fp(tst.D.data)
        # fp(tst.D.indices)
        # fp(tst.D.indptr)
        # tst.is_mixed_derivative = False
        # npt.assert_equal(tst, ref)

        # domT = self.FG.gpugrid.copy(True)
        # domC = self.FG.gpugrid.copy(True)
        # domT = SizedArrayPtr(self.F.grid.domain[-1])
        # domC = SizedArrayPtr(self.F.grid.domain[-1])

        # Csr.solve_(domC, True)
        # tst = Csr.immigrate().solve(domC.to_numpy())
        # Tri.solve_(domT, True)

        tst = domC.to_numpy()
        ref = domT.to_numpy()

        print "Ref"
        fp(ref)
        print "Test"
        fp(tst)
        print "Diff"
        fp(tst - ref)

        npt.assert_array_almost_equal(ref, tst, decimal=11)
        assert False
 def test_diagonalize(self):
     B = self.B.copy()
     print "ref pre"
     fp(self.B.D)
     fp(self.B.D.data)
     print "tst"
     fp(B.D)
     fp(B.D.data)
     B.diagonalize()
     print "tst mid"
     fp(B.D)
     fp(B.D.data)
     B.undiagonalize()
     npt.assert_(not B.is_tridiagonal())
     print "ref after"
     fp(self.B.D)
     fp(self.B.D.data)
     print "tst"
     fp(B.D)
     fp(B.D.data)
     npt.assert_array_equal(self.B.D.data, B.D.data, err_msg="Diagonalize roundtrip doesn't preserve operator matrix.")
     npt.assert_(B == self.B, msg="Diagonalize roundtrip doesn't preserve operator.")
Beispiel #12
0
    def test_numpy_vs_operators(self):
        spots = np.linspace(0, 1, 4)
        vars = np.linspace(0, 10, 4)
        # spots = self.G.mesh[0]
        # vars = self.G.mesh[1]
        G = Grid.Grid((spots, vars), initializer=lambda x0, x1: x1 * 1)
        coeffs = {
            (): lambda t: 0,
            (0, ): lambda t, *dim: dim[0],
            (0, 0): lambda t, *dim: dim[0],
            (1, ): lambda t, *dim: 0 * dim[1],
            (1, 1): lambda t, *dim: dim[1],
            (0, 1): lambda t, *dim: dim[0] * dim[1]
        }
        bounds = {
            (0, ): ((None, lambda *x: None), (None, lambda *x: 3)),
            (0, 0): ((None, lambda *x: None), (None, lambda *x: 3)),
            (1, ): ((None, lambda *x: None), (None, lambda *x: 1)),
            (1, 1): ((None, lambda *x: None), (None, lambda *x: 1)),
        }
        F = FD.FiniteDifferenceEngineADI(G,
                                         coefficients=coeffs,
                                         boundaries=bounds,
                                         force_bandwidth=None)
        F.init()

        cb = utils.clear_boundary
        g = F.grid.domain[-1]

        op_ = {'delta': {}, 'grid_delta': {}, 'derivative': {}}
        np_ = {'delta': {}, 'grid_delta': {}, 'derivative': {}}

        dims = coeffs.keys()
        dims.remove(())

        for dim in dims:
            op_['grid_delta'][dim] = F.simple_operators[dim].copy()
            op_['grid_delta'][dim].R = None

        op_['delta'][(0, )] = op_['grid_delta'][(0, )].deltas[:, np.newaxis]
        op_['delta'][(1, )] = op_['grid_delta'][(1, )].deltas

        x = F.grid.mesh[0]
        y = F.grid.mesh[1]
        np_['delta'][(0, )] = np.gradient(x)[:, np.newaxis]
        np_['delta'][(1, )] = np.gradient(y)
        np_['delta'][(0, )][0, 0] = np.nan
        np_['delta'][(1, )][0] = np.nan

        for f in (op_, np_):
            f['delta'][(0, 0)] = f['delta'][(0, )]**2
            f['delta'][(1, 1)] = f['delta'][(1, )]**2
            f['delta'][(0, 1)] = f['delta'][(1, )] * f['delta'][(0, )]
            f['delta'][(1, 0)] = f['delta'][(1, )] * f['delta'][(0, )]

        np_['grid_delta'][(0, )], np_['grid_delta'][(1, )] = np.gradient(g)
        for fst in [0, 1]:
            np_['grid_delta'][(fst,
                               0)], np_['grid_delta'][(fst, 1)] = np.gradient(
                                   np_['grid_delta'][(fst, )])

        Y, X = np.meshgrid(y, x)
        for dim in dims:
            op_['derivative'][dim] = cb(op_['grid_delta'][dim].apply(g),
                                        inplace=True)
            npt.assert_(op_['derivative'][dim].shape == g.shape)
            np_['derivative'][dim] = cb(np_['grid_delta'][dim] /
                                        np_['delta'][dim],
                                        inplace=True)
            np_['derivative'][dim] *= F.coefficients[dim](0, X, Y)
            op_['derivative'][dim] *= F.coefficients[dim](0, X, Y)

        np_['derivative'][(1, 0)] = cb(np_['grid_delta'][(1, 0)] /
                                       np_['delta'][(1, 0)],
                                       inplace=True)
        np_['derivative'][(1, 0)] *= F.coefficients[(0, 1)](0, X, Y)

        for dim in dims:
            for x in ('delta', 'derivative'):
                msg = "Comparing %s in dimension %s" % (x, dim)
                try:
                    npt.assert_array_almost_equal(op_[x][dim],
                                                  np_[x][dim],
                                                  decimal=7,
                                                  err_msg=msg)
                except AssertionError:
                    print msg, op_['grid_delta'][dim].axis
                    fp((op_['grid_delta'][dim]).D.data)
                    fp((op_[x][dim]), fmt='f')
                    fp((np_[x][dim]), fmt='f')
                    fp((op_[x][dim] - np_[x][dim]), fmt='f')
                # npt.assert_allclose(op_[x][dim], np_[x][dim], err_msg=msg)
                npt.assert_array_almost_equal(op_[x][dim],
                                              np_[x][dim],
                                              decimal=7,
                                              err_msg=msg)

        npt.assert_array_almost_equal(np_['derivative'][(0, 1)],
                                      np_['derivative'][(1, 0)],
                                      err_msg=msg)
    def test_numpy_vs_operators(self):
        spots = np.linspace(0, 1, 4)
        vars = np.linspace(0, 10, 4)
        # spots = self.G.mesh[0]
        # vars = self.G.mesh[1]
        G = Grid.Grid((spots, vars), initializer=lambda x0, x1: x1 * 1)
        coeffs = {
            (): lambda t: 0,
            (0,): lambda t, *dim: dim[0],
            (0, 0): lambda t, *dim: dim[0],
            (1,): lambda t, *dim: 0 * dim[1],
            (1, 1): lambda t, *dim: dim[1],
            (0, 1): lambda t, *dim: dim[0] * dim[1],
        }
        bounds = {
            (0,): ((None, lambda *x: None), (None, lambda *x: 3)),
            (0, 0): ((None, lambda *x: None), (None, lambda *x: 3)),
            (1,): ((None, lambda *x: None), (None, lambda *x: 1)),
            (1, 1): ((None, lambda *x: None), (None, lambda *x: 1)),
        }
        F = FD.FiniteDifferenceEngineADI(G, coefficients=coeffs, boundaries=bounds, force_bandwidth=None)
        F.init()

        cb = utils.clear_boundary
        g = F.grid.domain[-1]

        op_ = {"delta": {}, "grid_delta": {}, "derivative": {}}
        np_ = {"delta": {}, "grid_delta": {}, "derivative": {}}

        dims = coeffs.keys()
        dims.remove(())

        for dim in dims:
            op_["grid_delta"][dim] = F.simple_operators[dim].copy()
            op_["grid_delta"][dim].R = None

        op_["delta"][(0,)] = op_["grid_delta"][(0,)].deltas[:, np.newaxis]
        op_["delta"][(1,)] = op_["grid_delta"][(1,)].deltas

        x = F.grid.mesh[0]
        y = F.grid.mesh[1]
        np_["delta"][(0,)] = np.gradient(x)[:, np.newaxis]
        np_["delta"][(1,)] = np.gradient(y)
        np_["delta"][(0,)][0, 0] = np.nan
        np_["delta"][(1,)][0] = np.nan

        for f in (op_, np_):
            f["delta"][(0, 0)] = f["delta"][(0,)] ** 2
            f["delta"][(1, 1)] = f["delta"][(1,)] ** 2
            f["delta"][(0, 1)] = f["delta"][(1,)] * f["delta"][(0,)]
            f["delta"][(1, 0)] = f["delta"][(1,)] * f["delta"][(0,)]

        np_["grid_delta"][(0,)], np_["grid_delta"][(1,)] = np.gradient(g)
        for fst in [0, 1]:
            np_["grid_delta"][(fst, 0)], np_["grid_delta"][(fst, 1)] = np.gradient(np_["grid_delta"][(fst,)])

        Y, X = np.meshgrid(y, x)
        for dim in dims:
            op_["derivative"][dim] = cb(op_["grid_delta"][dim].apply(g), inplace=True)
            npt.assert_(op_["derivative"][dim].shape == g.shape)
            np_["derivative"][dim] = cb(np_["grid_delta"][dim] / np_["delta"][dim], inplace=True)
            np_["derivative"][dim] *= F.coefficients[dim](0, X, Y)
            op_["derivative"][dim] *= F.coefficients[dim](0, X, Y)

        np_["derivative"][(1, 0)] = cb(np_["grid_delta"][(1, 0)] / np_["delta"][(1, 0)], inplace=True)
        np_["derivative"][(1, 0)] *= F.coefficients[(0, 1)](0, X, Y)

        for dim in dims:
            for x in ("delta", "derivative"):
                msg = "Comparing %s in dimension %s" % (x, dim)
                try:
                    npt.assert_array_almost_equal(op_[x][dim], np_[x][dim], decimal=7, err_msg=msg)
                except AssertionError:
                    print msg, op_["grid_delta"][dim].axis
                    fp((op_["grid_delta"][dim]).D.data)
                    fp((op_[x][dim]), fmt="f")
                    fp((np_[x][dim]), fmt="f")
                    fp((op_[x][dim] - np_[x][dim]), fmt="f")
                # npt.assert_allclose(op_[x][dim], np_[x][dim], err_msg=msg)
                npt.assert_array_almost_equal(op_[x][dim], np_[x][dim], decimal=7, err_msg=msg)

        npt.assert_array_almost_equal(np_["derivative"][(0, 1)], np_["derivative"][(1, 0)], err_msg=msg)