def test_sh_jacobi(self):
        # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1)
        conv = lambda n, p: gamma(n + 1) * gamma(n + p) / gamma(2 * n + p)
        psub = np.poly1d([2, -1])
        q = 4 * rand()
        p = q - 1 + 2 * rand()
        #print "shifted jacobi p,q = ", p, q
        G0 = orth.sh_jacobi(0, p, q)
        G1 = orth.sh_jacobi(1, p, q)
        G2 = orth.sh_jacobi(2, p, q)
        G3 = orth.sh_jacobi(3, p, q)
        G4 = orth.sh_jacobi(4, p, q)
        G5 = orth.sh_jacobi(5, p, q)
        ge0 = orth.jacobi(0, p - q, q - 1)(psub) * conv(0, p)
        ge1 = orth.jacobi(1, p - q, q - 1)(psub) * conv(1, p)
        ge2 = orth.jacobi(2, p - q, q - 1)(psub) * conv(2, p)
        ge3 = orth.jacobi(3, p - q, q - 1)(psub) * conv(3, p)
        ge4 = orth.jacobi(4, p - q, q - 1)(psub) * conv(4, p)
        ge5 = orth.jacobi(5, p - q, q - 1)(psub) * conv(5, p)

        assert_array_almost_equal(G0.c, ge0.c, 13)
        assert_array_almost_equal(G1.c, ge1.c, 13)
        assert_array_almost_equal(G2.c, ge2.c, 13)
        assert_array_almost_equal(G3.c, ge3.c, 13)
        assert_array_almost_equal(G4.c, ge4.c, 13)
        assert_array_almost_equal(G5.c, ge5.c, 13)
示例#2
0
    def test_sh_jacobi(self):
        # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1)
        conv = lambda n,p: gamma(n+1)*gamma(n+p)/gamma(2*n+p)
        psub = np.poly1d([2,-1])
        q = 4*rand()
        p = q-1 + 2*rand()
        #print "shifted jacobi p,q = ", p, q
        G0 = orth.sh_jacobi(0,p,q)
        G1 = orth.sh_jacobi(1,p,q)
        G2 = orth.sh_jacobi(2,p,q)
        G3 = orth.sh_jacobi(3,p,q)
        G4 = orth.sh_jacobi(4,p,q)
        G5 = orth.sh_jacobi(5,p,q)
        ge0 = orth.jacobi(0,p-q,q-1)(psub) * conv(0,p)
        ge1 = orth.jacobi(1,p-q,q-1)(psub) * conv(1,p)
        ge2 = orth.jacobi(2,p-q,q-1)(psub) * conv(2,p)
        ge3 = orth.jacobi(3,p-q,q-1)(psub) * conv(3,p)
        ge4 = orth.jacobi(4,p-q,q-1)(psub) * conv(4,p)
        ge5 = orth.jacobi(5,p-q,q-1)(psub) * conv(5,p)

        assert_array_almost_equal(G0.c,ge0.c,13)
        assert_array_almost_equal(G1.c,ge1.c,13)
        assert_array_almost_equal(G2.c,ge2.c,13)
        assert_array_almost_equal(G3.c,ge3.c,13)
        assert_array_almost_equal(G4.c,ge4.c,13)
        assert_array_almost_equal(G5.c,ge5.c,13)
示例#3
0
    def test_minimal_residual(self):
        # Ensure repeatability
        random.seed(0)

        self.definite_cases.extend(self.spd_cases)

        for case in self.definite_cases:
            A = case['A']
            maxiter = case['maxiter']
            x0 = rand(A.shape[0], )
            b = zeros_like(x0)
            reduction_factor = case['reduction_factor']
            if A.dtype != complex:

                # This function should always decrease (assuming zero RHS)
                fvals = []

                def callback(x):
                    fvals.append(
                        sqrt(dot(ravel(x), ravel(A * x.reshape(-1, 1)))))

                #
                (x, flag) = minimal_residual(A,
                                             b,
                                             x0=x0,
                                             tol=1e-16,
                                             maxiter=maxiter,
                                             callback=callback)
                actual_factor = (norm(ravel(b) - ravel(A * x.reshape(-1, 1))) /
                                 norm(ravel(b) - ravel(A * x0.reshape(-1, 1))))
                assert (actual_factor < reduction_factor)
                if A.dtype != complex:
                    for i in range(len(fvals) - 1):
                        assert (fvals[i + 1] <= fvals[i])

        # Test preconditioning
        A = pyamg.gallery.poisson((10, 10), format='csr')
        x0 = rand(A.shape[0], 1)
        b = zeros_like(x0)
        fvals = []

        def callback(x):
            fvals.append(sqrt(dot(ravel(x), ravel(A * x.reshape(-1, 1)))))

        #
        resvec = []
        sa = pyamg.smoothed_aggregation_solver(A)
        (x, flag) = minimal_residual(A,
                                     b,
                                     x0,
                                     tol=1e-8,
                                     maxiter=20,
                                     residuals=resvec,
                                     M=sa.aspreconditioner(),
                                     callback=callback)
        assert (resvec[-1] < 1e-8)
        for i in range(len(fvals) - 1):
            assert (fvals[i + 1] <= fvals[i])
示例#4
0
    def test_steepest_descent(self):
        # Ensure repeatability
        random.seed(0)

        for case in self.spd_cases:
            A = case['A']
            b = case['b']
            x0 = case['x0']
            maxiter = case['maxiter']
            reduction_factor = case['reduction_factor']

            # This function should always decrease
            fvals = []

            def callback(x):
                fvals.append(0.5 * dot(ravel(x), ravel(A * x.reshape(-1, 1))) -
                             dot(ravel(b), ravel(x)))

            (x, flag) = steepest_descent(A,
                                         b,
                                         x0=x0,
                                         tol=1e-16,
                                         maxiter=maxiter,
                                         callback=callback)
            actual_factor = (norm(ravel(b) - ravel(A * x.reshape(-1, 1))) /
                             norm(ravel(b) - ravel(A * x0.reshape(-1, 1))))
            assert (actual_factor < reduction_factor)

            if A.dtype != complex:
                for i in range(len(fvals) - 1):
                    assert (fvals[i + 1] <= fvals[i])

        # Test preconditioning
        A = pyamg.gallery.poisson((10, 10), format='csr')
        b = rand(A.shape[0], 1)
        x0 = rand(A.shape[0], 1)
        fvals = []

        def callback(x):
            fvals.append(0.5 * dot(ravel(x), ravel(A * x.reshape(-1, 1))) -
                         dot(ravel(b), ravel(x)))

        resvec = []
        sa = pyamg.smoothed_aggregation_solver(A)
        (x, flag) = steepest_descent(A,
                                     b,
                                     x0,
                                     tol=1e-8,
                                     maxiter=20,
                                     residuals=resvec,
                                     M=sa.aspreconditioner(),
                                     callback=callback)
        assert (resvec[-1] < 1e-8)
        for i in range(len(fvals) - 1):
            assert (fvals[i + 1] <= fvals[i])
示例#5
0
    def test_minimal_residual(self):
        # Ensure repeatability
        random.seed(0)

        self.definite_cases.extend(self.spd_cases)

        for case in self.definite_cases:
            A = case['A']
            maxiter = case['maxiter']
            x0 = rand(A.shape[0],)
            b = zeros_like(x0)
            reduction_factor = case['reduction_factor']
            if A.dtype != complex:

                # This function should always decrease (assuming zero RHS)
                fvals = []

                def callback(x):
                    fvals.append(sqrt(dot(ravel(x),
                                 ravel(A*x.reshape(-1, 1)))))
                #
                (x, flag) = minimal_residual(A, b, x0=x0,
                                             tol=1e-16, maxiter=maxiter,
                                             callback=callback)
                actual_factor = (norm(ravel(b) - ravel(A*x.reshape(-1, 1))) /
                                 norm(ravel(b) - ravel(A*x0.reshape(-1, 1))))
                assert(actual_factor < reduction_factor)
                if A.dtype != complex:
                    for i in range(len(fvals)-1):
                        assert(fvals[i+1] <= fvals[i])

        # Test preconditioning
        A = pyamg.gallery.poisson((10, 10), format='csr')
        x0 = rand(A.shape[0], 1)
        b = zeros_like(x0)
        fvals = []

        def callback(x):
            fvals.append(sqrt(dot(ravel(x), ravel(A*x.reshape(-1, 1)))))
        #
        resvec = []
        sa = pyamg.smoothed_aggregation_solver(A)
        (x, flag) = minimal_residual(A, b, x0, tol=1e-8, maxiter=20,
                                     residuals=resvec, M=sa.aspreconditioner(),
                                     callback=callback)
        assert(resvec[-1] < 1e-8)
        for i in range(len(fvals)-1):
            assert(fvals[i+1] <= fvals[i])
    def test_gegenbauer(self):
        a = 5 * rand() - 0.5
        if np.any(a == 0):
            a = -0.2
        Ca0 = orth.gegenbauer(0, a)
        Ca1 = orth.gegenbauer(1, a)
        Ca2 = orth.gegenbauer(2, a)
        Ca3 = orth.gegenbauer(3, a)
        Ca4 = orth.gegenbauer(4, a)
        Ca5 = orth.gegenbauer(5, a)

        assert_array_almost_equal(Ca0.c, array([1]), 13)
        assert_array_almost_equal(Ca1.c, array([2 * a, 0]), 13)
        assert_array_almost_equal(Ca2.c, array([2 * a * (a + 1), 0, -a]), 13)
        assert_array_almost_equal(
            Ca3.c,
            array([4 * orth.poch(a, 3), 0, -6 * a * (a + 1), 0]) / 3.0, 11)
        assert_array_almost_equal(
            Ca4.c,
            array([
                4 * orth.poch(a, 4), 0, -12 * orth.poch(a, 3), 0, 3 * a *
                (a + 1)
            ]) / 6.0, 11)
        assert_array_almost_equal(
            Ca5.c,
            array([
                4 * orth.poch(a, 5), 0, -20 * orth.poch(a, 4), 0,
                15 * orth.poch(a, 3), 0
            ]) / 15.0, 11)
示例#7
0
文件: test.py 项目: fritzo/goftests
def _test_scipy_stats(name):
    if name in known_failures:
        raise SkipTest('known failure')
    dist = getattr(scipy.stats, name)
    try:
        params = default_params[name]
    except KeyError:
        params = [tuple(1.0 + rand(dist.numargs))]
    for param in params:
        print 'param = {}'.format(param)
        dim = get_dim(dist.rvs(*param))
        sample_count = 100 + 1000 * dim
        samples = list(dist.rvs(*param, size=sample_count))

        if hasattr(dist, 'pmf'):
            probs = [dist.pmf(sample, *param) for sample in samples]
            probs_dict = dict(izip(samples, probs))
            gof = discrete_goodness_of_fit(samples, probs_dict, plot=True)
        else:
            probs = [dist.pdf(sample, *param) for sample in samples]
            gof = auto_density_goodness_of_fit(samples, probs, plot=True)
        assert_greater(gof, TEST_FAILURE_RATE)

        gof = mixed_density_goodness_of_fit(samples, probs, plot=True)
        assert_greater(gof, TEST_FAILURE_RATE)
示例#8
0
文件: test.py 项目: jfinkels/goftests
 def dist_params(self):
     # If there are no parameters, then we provide a random one.
     if self.params is None:
         params = [tuple(1 + rand(self.dist.numargs))]
     else:
         params = self.params
     return params
示例#9
0
 def dist_params(self):
     # If there are no parameters, then we provide a random one.
     if self.params is None:
         params = [tuple(1 + rand(self.dist.numargs))]
     else:
         params = self.params
     return params
示例#10
0
    def test_prefilter(self):
        """Check that using prefilter reduces NNZ in P"""
        np.random.seed(0)  # make tests repeatable
        cases = []

        # Simple, real-valued diffusion problems
        X = load_example('airfoil')
        A = X['A'].tocsr()
        B = X['B']

        cases.append((A, B,
                     ('energy', {'krylov': 'cg', 'degree': 2, 'maxiter': 3}),
                     {'theta': 0.05}) )

        cases.append((A, B,
                     ('energy', {'krylov': 'gmres', 'degree': 2, 'maxiter': 3}),
                     {'k': 3}) )


        cases.append((A.tobsr(blocksize=(2, 2)), 
                     np.hstack((B, np.random.rand(B.shape[0],1))),
                     ('energy', {'krylov': 'cg', 'degree': 2, 'maxiter': 3}),
                     {'theta': 0.1}) )

        # Simple, imaginary-valued problems
        iA = 1.0j * A
        iB = 1.0 + rand(iA.shape[0], 2) + 1.0j * (1.0 + rand(iA.shape[0], 2))

        cases.append((iA, B, 
                     ('energy', {'krylov': 'cg', 'degree': 2, 'maxiter': 3}),
                     {'theta': 0.05}) )

        cases.append((iA, iB, 
                     ('energy', {'krylov': 'gmres', 'degree': 2, 'maxiter': 3}),
                     {'k': 3}) )


        cases.append((A.tobsr(blocksize=(2, 2)), 
                     np.hstack((B, np.random.rand(B.shape[0],1))),
                     ('energy', {'krylov': 'cg', 'degree': 2, 'maxiter': 3}),
                     {'theta': 0.1}) )
        
        for A, B, smooth, prefilter in cases:
            ml_nofilter = rootnode_solver(A, B=B, max_coarse=1, max_levels=2, smooth=smooth, keep=True)
            smooth[1]['prefilter'] = prefilter
            ml_filter = rootnode_solver(A, B=B, max_coarse=1, max_levels=2, smooth=smooth, keep=True)
            assert_equal(ml_nofilter.levels[0].P.nnz > ml_filter.levels[0].P.nnz, True)
示例#11
0
 def test_random_rect_real(self):
     sz = (20, 15)
     a = rand(*sz)
     fn = self.fn
     mmwrite(fn, a)
     assert_equal(mminfo(fn), (20, 15, 300, 'array', 'real', 'general'))
     b = mmread(fn)
     assert_array_almost_equal(a, b)
示例#12
0
    def setUp(self):
        self.cases = []

        # Poisson problems in 2D
        for N in [2, 3, 5, 7, 8]:
            A = poisson((N, N), format='csr')
            A.data = A.data + 0.001j * rand(A.nnz)
            self.cases.append(A)
示例#13
0
    def test_steepest_descent(self):
        # Ensure repeatability
        random.seed(0)

        for case in self.spd_cases:
            A = case['A']
            b = case['b']
            x0 = case['x0']
            maxiter = case['maxiter']
            reduction_factor = case['reduction_factor']

            # This function should always decrease
            fvals = []

            def callback(x):
                fvals.append(0.5*dot(ravel(x), ravel(A*x.reshape(-1, 1))) -
                             dot(ravel(b), ravel(x)))

            (x, flag) = steepest_descent(A, b, x0=x0, tol=1e-16,
                                         maxiter=maxiter, callback=callback)
            actual_factor = (norm(ravel(b) - ravel(A*x.reshape(-1, 1))) /
                             norm(ravel(b) - ravel(A*x0.reshape(-1, 1))))
            assert(actual_factor < reduction_factor)

            if A.dtype != complex:
                for i in range(len(fvals)-1):
                    assert(fvals[i+1] <= fvals[i])

        # Test preconditioning
        A = pyamg.gallery.poisson((10, 10), format='csr')
        b = rand(A.shape[0], 1)
        x0 = rand(A.shape[0], 1)
        fvals = []

        def callback(x):
            fvals.append(0.5*dot(ravel(x), ravel(A*x.reshape(-1, 1))) -
                         dot(ravel(b), ravel(x)))

        resvec = []
        sa = pyamg.smoothed_aggregation_solver(A)
        (x, flag) = steepest_descent(A, b, x0, tol=1e-8, maxiter=20,
                                     residuals=resvec, M=sa.aspreconditioner(),
                                     callback=callback)
        assert(resvec[-1] < 1e-8)
        for i in range(len(fvals)-1):
            assert(fvals[i+1] <= fvals[i])
示例#14
0
    def setUp(self):
        self.cases = []

        # Poisson problems in 2D
        for N in [2, 3, 5, 7, 8]:
            A = poisson((N, N), format='csr')
            A.data = A.data + 0.001j*rand(A.nnz)
            self.cases.append(A)
示例#15
0
 def test_random_rect_real(self):
     sz = (20,15)
     a = rand(*sz)
     fn = self.fn
     mmwrite(fn,a)
     assert_equal(mminfo(fn),(20,15,300,'array','real','general'))
     b = mmread(fn)
     assert_array_almost_equal(a,b)
示例#16
0
 def test_random_symmetric_real(self):
     sz = (20,20)
     a = rand(*sz)
     a = a + transpose(a)
     fn = self.fn
     mmwrite(fn,a)
     assert_equal(mminfo(fn),(20,20,400,'array','real','symmetric'))
     b = mmread(fn)
     assert_array_almost_equal(a,b)
示例#17
0
 def test_random_symmetric_real(self):
     sz = (20, 20)
     a = rand(*sz)
     a = a + transpose(a)
     fn = self.fn
     mmwrite(fn, a)
     assert_equal(mminfo(fn), (20, 20, 400, 'array', 'real', 'symmetric'))
     b = mmread(fn)
     assert_array_almost_equal(a, b)
示例#18
0
    def setUp(self):
        self.cases = []

        # random matrices
        numpy.random.seed(0)
        for N in [2, 3, 5]:
            self.cases.append(csr_matrix(rand(N, N)))

        # Poisson problems in 1D and 2D
        for N in [2, 3, 5, 7, 10, 11, 19]:
            self.cases.append(poisson((N, ), format='csr'))
        for N in [2, 3, 5, 7, 8]:
            self.cases.append(poisson((N, N), format='csr'))

        for name in ['knot', 'airfoil', 'bar']:
            ex = load_example(name)
            self.cases.append(ex['A'].tocsr())
示例#19
0
    def setUp(self):
        self.cases = []

        # random matrices
        numpy.random.seed(0)
        for N in [2, 3, 5]:
            self.cases.append(csr_matrix(rand(N, N)))

        # Poisson problems in 1D and 2D
        for N in [2, 3, 5, 7, 10, 11, 19]:
            self.cases.append(poisson((N,), format='csr'))
        for N in [2, 3, 5, 7, 8]:
            self.cases.append(poisson((N, N), format='csr'))

        for name in ['knot', 'airfoil', 'bar']:
            ex = load_example(name)
            self.cases.append(ex['A'].tocsr())
示例#20
0
    def test_gegenbauer(self):
        a = 5*rand()-0.5
        if np.any(a==0): a = -0.2
        Ca0 = orth.gegenbauer(0,a)
        Ca1 = orth.gegenbauer(1,a)
        Ca2 = orth.gegenbauer(2,a)
        Ca3 = orth.gegenbauer(3,a)
        Ca4 = orth.gegenbauer(4,a)
        Ca5 = orth.gegenbauer(5,a)

        assert_array_almost_equal(Ca0.c,array([1]),13)
        assert_array_almost_equal(Ca1.c,array([2*a,0]),13)
        assert_array_almost_equal(Ca2.c,array([2*a*(a+1),0,-a]),13)
        assert_array_almost_equal(Ca3.c,array([4*orth.poch(a,3),0,-6*a*(a+1),
                                               0])/3.0,11)
        assert_array_almost_equal(Ca4.c,array([4*orth.poch(a,4),0,-12*orth.poch(a,3),
                                               0,3*a*(a+1)])/6.0,11)
        assert_array_almost_equal(Ca5.c,array([4*orth.poch(a,5),0,-20*orth.poch(a,4),
                                               0,15*orth.poch(a,3),0])/15.0,11)
示例#21
0
def test_ppf_and_isf_all_distributions():     
    for dist in dists:
        distfunc = getattr(stats, dist)
        nargs = distfunc.numargs
        for check_fun in [check_distribution_ppf, check_distribution_isf]:
            if dist == 'erlang':
                args = (4,)+tuple(rand(2))
            elif dist == 'frechet':
                args = tuple(2*rand(1))+(0,)+tuple(2*rand(2))
            elif dist == 'triang':
                args = tuple(rand(nargs))
            elif dist == 'reciprocal':
                vals = rand(nargs)
                vals[1] = vals[0] + 1.0
                args = tuple(vals)
            elif dist == 'vonmises':
                yield check_fun, dist, (10,)
                yield check_fun, dist, (101,)
                args = tuple(1.0+rand(nargs))
            else:
                args = tuple(1.0+rand(nargs))
            yield check_fun, dist, args
示例#22
0
def test_all_distributions():
    for dist in dists:
        distfunc = getattr(stats, dist)
        nargs = distfunc.numargs
        alpha = 0.01
        if dist == 'fatiguelife':
            alpha = 0.001
        if dist == 'erlang':
            args = (4,)+tuple(rand(2))
        elif dist == 'frechet':
            args = tuple(2*rand(1))+(0,)+tuple(2*rand(2))
        elif dist == 'triang':
            args = tuple(rand(nargs))
        elif dist == 'reciprocal':
            vals = rand(nargs)
            vals[1] = vals[0] + 1.0
            args = tuple(vals)
        elif dist == 'vonmises':
            yield check_distribution, dist, (10,), alpha
            yield check_distribution, dist, (101,), alpha
            args = tuple(1.0+rand(nargs))
        else:
            args = tuple(1.0+rand(nargs))
        yield check_distribution, dist, args, alpha
示例#23
0
 def test_random_rectangular_float(self):
     sz = (20, 15)
     a = rand(*sz)
     self.check(a, (20, 15, 300, 'array', 'real', 'general'))
示例#24
0
文件: test.py 项目: fritzo/goftests
    discrete, continuous = split_discrete_continuous(example['mixed'])
    assert_equal(discrete, example['discrete'])
    assert_almost_equal(continuous, example['continuous'])


def test_split_continuous_discrete():
    for i in xrange(len(split_examples)):
        yield split_example, i


seed_all(0)
default_params = {
    'bernoulli': [(0.2,)],
    'binom': [(40, 0.4)],
    'dirichlet': [
        (1.0 + rand(2),),
        (1.0 + rand(3),),
        (1.0 + rand(4),),
    ],
    'erlang': [(7,)],
    'dlaplace': [(0.8,)],
    'frechet': [tuple(2 * rand(1)) + (0,) + tuple(2 * rand(2))],
    'geom': [(0.1,)],
    'hypergeom': [(40, 14, 24)],
    'logser': [(0.9,)],
    'multivariate_normal': [
        (numpy.ones(1), numpy.eye(1)),
        (numpy.ones(2), numpy.eye(2)),
        (numpy.ones(3), numpy.eye(3)),
    ],
    'nbinom': [(40, 0.4)],
示例#25
0
 def test_all_outliers(self):
     r = rand(100)+1.
     H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
     assert_array_equal(H, 0)
示例#26
0
class TestVonMises(ContinuousTestBase, TestCase):

    dist = scipy.stats.vonmises

    params = [tuple(1.0 + rand(1))]
示例#27
0
 def test_all_outliers(self):
     r = rand(100) + 1. + 1e6  # histogramdd rounds by decimal=6
     H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
     assert_array_equal(H, 0)
from PIL import Image

import scipy.io as sio
from numpy.testing import rand


def get():
    datadict = sio.loadmat('data/test_32x32.mat')
    y = datadict['y'].reshape(datadict['y'].shape[0], )
    return datadict['X'].transpose((3, 0, 1, 2)), y


if __name__ == "__main__":
    X, Y = get()
    for data in X[0:2]:
        img = Image.fromarray(data, 'RGB')
        img.save('my' + str(rand(0)) + '.png')
        print(Y[0])
        img.show()
示例#29
0
def random(size):
    return rand(*size)
示例#30
0
 def test_random_rectangular_float(self):
     sz = (20, 15)
     a = rand(*sz)
     self.check(a, (20, 15, 300, 'array', 'real', 'general'))
示例#31
0
 def test_random_symmetric_float(self):
     sz = (20, 20)
     a = rand(*sz)
     a = a + transpose(a)
     self.check(a, (20, 20, 400, 'array', 'real', 'symmetric'))
示例#32
0
 def test_random_rectangular_float(self):
     sz = (20, 15)
     a = rand(*sz)
     a = scipy.sparse.csr_matrix(a)
     self.check(a, (20, 15, 300, 'coordinate', 'real', 'general'))
示例#33
0
 def test_random_symmetric_float(self):
     sz = (20, 20)
     a = rand(*sz)
     a = a + transpose(a)
     a = scipy.sparse.csr_matrix(a)
     self.check(a, (20, 20, 210, 'coordinate', 'real', 'symmetric'))
示例#34
0
    def test_range(self):
        """Check that P*R=B"""
        np.random.seed(0)  # make tests repeatable

        cases = []

        # Simple, real-valued diffusion problems
        X = load_example('airfoil')
        A = X['A'].tocsr()
        B = X['B']
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'local'})))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'block'})))

        cases.append((A, B, ('energy', {'maxiter': 3})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, B, ('energy', {'krylov': 'gmres', 'degree': 2})))

        A = poisson((10, 10), format='csr')
        B = np.ones((A.shape[0], 1))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'diagonal'})))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'local'})))

        cases.append((A, B, 'energy'))
        cases.append((A, B, ('energy', {'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr', 'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'gmres'})))

        # Simple, imaginary-valued problems
        iA = 1.0j * A
        iB = 1.0 + rand(iA.shape[0], 2) + 1.0j * (1.0 + rand(iA.shape[0], 2))

        cases.append((iA, B, ('jacobi',
                              {'filter': True, 'weighting': 'diagonal'})))
        cases.append((iA, B, ('jacobi',
                              {'filter': True, 'weighting': 'block'})))
        cases.append((iA, iB, ('jacobi',
                               {'filter': True, 'weighting': 'local'})))
        cases.append((iA, iB, ('jacobi',
                               {'filter': True, 'weighting': 'block'})))

        cases.append((iA.tobsr(blocksize=(5, 5)), B,
                     ('jacobi', {'filter': True, 'weighting': 'block'})))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB,
                     ('jacobi', {'filter': True, 'weighting': 'block'})))

        cases.append((iA, B, ('energy', {'krylov': 'cgnr', 'degree': 2})))
        cases.append((iA, iB, ('energy', {'krylov': 'cgnr'})))
        cases.append((iA.tobsr(blocksize=(5, 5)), B,
                     ('energy',
                      {'krylov': 'cgnr', 'degree': 2, 'maxiter': 3})))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB,
                     ('energy', {'krylov': 'cgnr'})))

        cases.append((iA, B, ('energy', {'krylov': 'gmres'})))
        cases.append((iA, iB, ('energy', {'krylov': 'gmres', 'degree': 2})))
        cases.append((iA.tobsr(blocksize=(5, 5)), B,
                     ('energy',
                      {'krylov': 'gmres', 'degree': 2, 'maxiter': 3})))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB,
                     ('energy', {'krylov': 'gmres'})))

        # Simple, imaginary-valued problems
        iA = A + 1.0j * scipy.sparse.eye(A.shape[0], A.shape[1])

        cases.append((iA, B, ('jacobi',
                              {'filter': True, 'weighting': 'local'})))
        cases.append((iA, B, ('jacobi',
                              {'filter': True, 'weighting': 'block'})))
        cases.append((iA, iB, ('jacobi',
                               {'filter': True, 'weighting': 'diagonal'})))
        cases.append((iA, iB, ('jacobi',
                               {'filter': True, 'weighting': 'block'})))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB,
                     ('jacobi', {'filter': True, 'weighting': 'block'})))

        cases.append((iA, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB,
                     ('energy', {'krylov': 'cgnr'})))

        cases.append((iA, B, ('energy', {'krylov': 'gmres'})))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB,
                     ('energy',
                      {'krylov': 'gmres', 'degree': 2, 'maxiter': 3})))

        A = gauge_laplacian(10, spacing=1.0, beta=0.21)
        B = np.ones((A.shape[0], 1))
        cases.append((A, iB, ('jacobi',
                              {'filter': True, 'weighting': 'diagonal'})))
        cases.append((A, iB, ('jacobi',
                              {'filter': True, 'weighting': 'local'})))

        cases.append((A, B, ('energy', {'krylov': 'cg'})))
        cases.append((A, iB, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, iB, ('energy', {'krylov': 'gmres'})))

        cases.append((A.tobsr(blocksize=(2, 2)), B,
                     ('energy',
                      {'krylov': 'cgnr', 'degree': 2, 'maxiter': 3})))
        cases.append((A.tobsr(blocksize=(2, 2)), iB,
                     ('energy', {'krylov': 'cg'})))
        cases.append((A.tobsr(blocksize=(2, 2)), B,
                     ('energy',
                      {'krylov': 'gmres', 'degree': 2, 'maxiter': 3})))

        #
        A, B = linear_elasticity((10, 10))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'diagonal'})))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'local'})))
        cases.append((A, B, ('jacobi',
                             {'filter': True, 'weighting': 'block'})))

        cases.append((A, B, ('energy', {'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, B, ('energy', {'krylov': 'gmres', 'degree': 2})))

        # Classic SA cases
        for A, B, smooth in cases:
            ml = smoothed_aggregation_solver(A, B=B, max_coarse=1,
                                             max_levels=2, smooth=smooth)
            P = ml.levels[0].P
            B = ml.levels[0].B
            R = ml.levels[1].B
            assert_almost_equal(P * R, B)

        def blocksize(A):
            # Helper Function: return the blocksize of a matrix
            if isspmatrix_bsr(A):
                return A.blocksize[0]
            else:
                return 1

        # Root-node cases
        counter = 0
        for A, B, smooth in cases:
            counter += 1

            if isinstance(smooth, tuple):
                smoother = smooth[0]
            else:
                smoother = smooth

            if smoother == 'energy' and (B.shape[1] >= blocksize(A)):
                ic = [('gauss_seidel_nr',
                       {'sweep': 'symmetric', 'iterations': 4}), None]
                ml = rootnode_solver(A, B=B, max_coarse=1, max_levels=2,
                                     smooth=smooth,
                                     improve_candidates=ic,
                                     keep=True, symmetry='nonsymmetric')
                T = ml.levels[0].T.tocsr()
                Cpts = ml.levels[0].Cpts
                Bf = ml.levels[0].B
                Bf_H = ml.levels[0].BH
                Bc = ml.levels[1].B
                P = ml.levels[0].P.tocsr()

                # P should preserve B in its range, wherever P
                # has enough nonzeros
                mask = ((P.indptr[1:] - P.indptr[:-1]) >= B.shape[1])
                assert_almost_equal((P*Bc)[mask, :], Bf[mask, :])
                assert_almost_equal((P*Bc)[mask, :], Bf_H[mask, :])

                # P should be the identity at Cpts
                I = eye(T.shape[1], T.shape[1], format='csr', dtype=T.dtype)
                I2 = P[Cpts, :]
                assert_almost_equal(I.data, I2.data)
                assert_equal(I.indptr, I2.indptr)
                assert_equal(I.indices, I2.indices)

                # T should be the identity at Cpts
                I2 = T[Cpts, :]
                assert_almost_equal(I.data, I2.data)
                assert_equal(I.indptr, I2.indptr)
                assert_equal(I.indices, I2.indices)
示例#35
0
    def test_prefilter(self):
        """Check that using prefilter reduces NNZ in P"""
        np.random.seed(0)  # make tests repeatable
        cases = []

        # Simple, real-valued diffusion problems
        X = load_example('airfoil')
        A = X['A'].tocsr()
        B = X['B']

        cases.append((A, B, ('energy', {
            'krylov': 'cg',
            'degree': 2,
            'maxiter': 3
        }), {
            'theta': 0.05
        }))

        cases.append((A, B, ('energy', {
            'krylov': 'gmres',
            'degree': 2,
            'maxiter': 3
        }), {
            'k': 3
        }))

        cases.append((A.tobsr(blocksize=(2, 2)),
                      np.hstack((B, np.random.rand(B.shape[0],
                                                   1))), ('energy', {
                                                       'krylov': 'cg',
                                                       'degree': 2,
                                                       'maxiter': 3
                                                   }), {
                                                       'theta': 0.1
                                                   }))

        # Simple, imaginary-valued problems
        iA = 1.0j * A
        iB = 1.0 + rand(iA.shape[0], 2) + 1.0j * (1.0 + rand(iA.shape[0], 2))

        cases.append((iA, B, ('energy', {
            'krylov': 'cg',
            'degree': 2,
            'maxiter': 3
        }), {
            'theta': 0.05
        }))

        cases.append((iA, iB, ('energy', {
            'krylov': 'gmres',
            'degree': 2,
            'maxiter': 3
        }), {
            'k': 3
        }))

        cases.append((A.tobsr(blocksize=(2, 2)),
                      np.hstack((B, np.random.rand(B.shape[0],
                                                   1))), ('energy', {
                                                       'krylov': 'cg',
                                                       'degree': 2,
                                                       'maxiter': 3
                                                   }), {
                                                       'theta': 0.1
                                                   }))

        for A, B, smooth, prefilter in cases:
            ml_nofilter = rootnode_solver(A,
                                          B=B,
                                          max_coarse=1,
                                          max_levels=2,
                                          smooth=smooth,
                                          keep=True)
            smooth[1]['prefilter'] = prefilter
            ml_filter = rootnode_solver(A,
                                        B=B,
                                        max_coarse=1,
                                        max_levels=2,
                                        smooth=smooth,
                                        keep=True)
            assert_equal(
                ml_nofilter.levels[0].P.nnz > ml_filter.levels[0].P.nnz, True)
示例#36
0
 def test_random_symmetric_float(self):
     sz = (20, 20)
     a = rand(*sz)
     a = a + transpose(a)
     self.check(a, (20, 20, 400, 'array', 'real', 'symmetric'))
示例#37
0
 def test_random_rectangular_float(self):
     sz = (20, 15)
     a = rand(*sz)
     a = scipy.sparse.csr_matrix(a)
     self.check(a, (20, 15, 300, 'coordinate', 'real', 'general'))
示例#38
0
class TestTriangular(ContinuousTestBase, TestCase):

    dist = scipy.stats.triang

    params = [tuple(rand(1))]
示例#39
0
 def test_random_symmetric_float(self):
     sz = (20, 20)
     a = rand(*sz)
     a = a + transpose(a)
     a = scipy.sparse.csr_matrix(a)
     self.check(a, (20, 20, 210, 'coordinate', 'real', 'symmetric'))
示例#40
0
class TestReciprocal(ContinuousTestBase, TestCase):

    dist = scipy.stats.reciprocal

    params = [tuple(numpy.array([0, 1]) + rand(1)[0])]
示例#41
0
    def test_range(self):
        """Check that P*R=B"""
        numpy.random.seed(0)  # make tests repeatable

        cases = []

        # Simple, real-valued diffusion problems
        X = load_example('airfoil')
        A = X['A'].tocsr()
        B = X['B']
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))

        cases.append((A, B, ('energy', {'maxiter': 3})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, B, ('energy', {'krylov': 'gmres', 'degree': 2})))

        A = poisson((10, 10), format='csr')
        B = ones((A.shape[0], 1))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'diagonal'
        })))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))

        cases.append((A, B, 'energy'))
        cases.append((A, B, ('energy', {'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr', 'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'gmres'})))

        # Simple, imaginary-valued problems
        iA = 1.0j * A
        iB = 1.0 + rand(iA.shape[0], 2) + 1.0j * (1.0 + rand(iA.shape[0], 2))

        cases.append((iA, B, ('jacobi', {
            'filter': True,
            'weighting': 'diagonal'
        })))
        cases.append((iA, B, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))
        cases.append((iA, iB, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))
        cases.append((iA, iB, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))

        cases.append((iA.tobsr(blocksize=(5, 5)), B, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))

        cases.append((iA, B, ('energy', {'krylov': 'cgnr', 'degree': 2})))
        cases.append((iA, iB, ('energy', {'krylov': 'cgnr'})))
        cases.append((iA.tobsr(blocksize=(5, 5)), B, ('energy', {
            'krylov': 'cgnr',
            'degree': 2,
            'maxiter': 3
        })))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB, ('energy', {
            'krylov': 'cgnr'
        })))

        cases.append((iA, B, ('energy', {'krylov': 'gmres'})))
        cases.append((iA, iB, ('energy', {'krylov': 'gmres', 'degree': 2})))
        cases.append((iA.tobsr(blocksize=(5, 5)), B, ('energy', {
            'krylov': 'gmres',
            'degree': 2,
            'maxiter': 3
        })))
        cases.append((iA.tobsr(blocksize=(5, 5)), iB, ('energy', {
            'krylov': 'gmres'
        })))

        # Simple, imaginary-valued problems
        iA = A + 1.0j * scipy.sparse.eye(A.shape[0], A.shape[1])

        cases.append((iA, B, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))
        cases.append((iA, B, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))
        cases.append((iA, iB, ('jacobi', {
            'filter': True,
            'weighting': 'diagonal'
        })))
        cases.append((iA, iB, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))

        cases.append((iA, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB, ('energy', {
            'krylov': 'cgnr'
        })))

        cases.append((iA, B, ('energy', {'krylov': 'gmres'})))
        cases.append((iA.tobsr(blocksize=(4, 4)), iB, ('energy', {
            'krylov': 'gmres',
            'degree': 2,
            'maxiter': 3
        })))

        A = gauge_laplacian(10, spacing=1.0, beta=0.21)
        B = ones((A.shape[0], 1))
        cases.append((A, iB, ('jacobi', {
            'filter': True,
            'weighting': 'diagonal'
        })))
        cases.append((A, iB, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))

        cases.append((A, B, ('energy', {'krylov': 'cg'})))
        cases.append((A, iB, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, iB, ('energy', {'krylov': 'gmres'})))

        cases.append((A.tobsr(blocksize=(2, 2)), B, ('energy', {
            'krylov': 'cgnr',
            'degree': 2,
            'maxiter': 3
        })))
        cases.append((A.tobsr(blocksize=(2, 2)), iB, ('energy', {
            'krylov': 'cg'
        })))
        cases.append((A.tobsr(blocksize=(2, 2)), B, ('energy', {
            'krylov': 'gmres',
            'degree': 2,
            'maxiter': 3
        })))

        #
        A, B = linear_elasticity((10, 10))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'diagonal'
        })))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'local'
        })))
        cases.append((A, B, ('jacobi', {
            'filter': True,
            'weighting': 'block'
        })))

        cases.append((A, B, ('energy', {'degree': 2})))
        cases.append((A, B, ('energy', {'krylov': 'cgnr'})))
        cases.append((A, B, ('energy', {'krylov': 'gmres', 'degree': 2})))

        # Classic SA cases
        for A, B, smooth in cases:
            ml = smoothed_aggregation_solver(A,
                                             B=B,
                                             max_coarse=1,
                                             max_levels=2,
                                             smooth=smooth)
            P = ml.levels[0].P
            B = ml.levels[0].B
            R = ml.levels[1].B
            assert_almost_equal(P * R, B)

        def blocksize(A):
            # Helper Function: return the blocksize of a matrix
            if isspmatrix_bsr(A):
                return A.blocksize[0]
            else:
                return 1

        # Root-node cases
        counter = 0
        for A, B, smooth in cases:
            counter += 1

            if isinstance(smooth, tuple):
                smoother = smooth[0]
            else:
                smoother = smooth

            if smoother == 'energy' and (B.shape[1] >= blocksize(A)):
                ic = [('gauss_seidel_nr', {
                    'sweep': 'symmetric',
                    'iterations': 4
                }), None]
                ml = rootnode_solver(A,
                                     B=B,
                                     max_coarse=1,
                                     max_levels=2,
                                     smooth=smooth,
                                     improve_candidates=ic,
                                     keep=True,
                                     symmetry='nonsymmetric')
                T = ml.levels[0].T.tocsr()
                Cpts = ml.levels[0].Cpts
                Bf = ml.levels[0].B
                Bf_H = ml.levels[0].BH
                Bc = ml.levels[1].B
                P = ml.levels[0].P.tocsr()

                # P should preserve B in its range, wherever P
                # has enough nonzeros
                mask = ((P.indptr[1:] - P.indptr[:-1]) >= B.shape[1])
                assert_almost_equal((P * Bc)[mask, :], Bf[mask, :])
                assert_almost_equal((P * Bc)[mask, :], Bf_H[mask, :])

                # P should be the identity at Cpts
                I = eye(T.shape[1], T.shape[1], format='csr', dtype=T.dtype)
                I2 = P[Cpts, :]
                assert_almost_equal(I.data, I2.data)
                assert_equal(I.indptr, I2.indptr)
                assert_equal(I.indices, I2.indices)

                # T should be the identity at Cpts
                I2 = T[Cpts, :]
                assert_almost_equal(I.data, I2.data)
                assert_equal(I.indptr, I2.indptr)
                assert_equal(I.indices, I2.indices)
示例#42
0
 def test_all_outliers(self):
     r = rand(100) + 1. + 1e6 # histogramdd rounds by decimal=6
     H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
     assert_array_equal(H, 0)
示例#43
0
def random(size):
    return rand(*size)
示例#44
0
 def test_all_outliers(self):
     r = rand(100) + 1.
     H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
     assert_array_equal(H, 0)