Esempio n. 1
0
    def test_rotation_invariance(self):
        """test invariance to theta when epsilon=1.0"""

        for type in ['FD', 'FE']:
            expected = diffusion_stencil_2d(epsilon=1.0, theta=0.0, type=type)
            for theta in [np.pi/8, np.pi/4, np.pi/3, np.pi/2, np.pi]:
                result = diffusion_stencil_2d(epsilon=1.0,
                                              theta=theta, type=type)
                assert_almost_equal(result, expected)
Esempio n. 2
0
    def test_simple_finite_difference(self):
        # isotropic
        stencil = [[0.0, -1.0, 0.0], [-1.0, 4.0, -1.0], [0.0, -1.0, 0.0]]
        assert_equal(diffusion_stencil_2d(epsilon=1.0, theta=0.0, type='FD'),
                     stencil)

        # weak horizontal
        stencil = [[0.0, -1.0, 0.0], [-0.5, 3.0, -0.5], [0.0, -1.0, 0.0]]
        assert_almost_equal(
            diffusion_stencil_2d(epsilon=0.5, theta=0.0, type='FD'), stencil)

        # weak vertical
        stencil = [[0.0, -0.5, 0.0], [-1.0, 3.0, -1.0], [0.0, -0.5, 0.0]]
        assert_almost_equal(
            diffusion_stencil_2d(epsilon=0.5, theta=pi / 2, type='FD'),
            stencil)
Esempio n. 3
0
 def test_simple_finite_element(self):
     # isotropic
     stencil = np.array([[-1.0, -1.0, -1.0],
                         [-1.0, 8.0, -1.0],
                         [-1.0, -1.0, -1.0]]) / 3.0
     assert_almost_equal(diffusion_stencil_2d(epsilon=1.0, theta=0.0,
                         type='FE'), stencil)
Esempio n. 4
0
def build_poisson(n, epsilon, theta, randomize):
    data = {}
    h = 1. / float(n + 1)

    print "Assembling diffusion using Q1 on a regular mesh with epsilon = " + \
          str(epsilon) + " and theta = " + str(theta) + " ..."
    stencil = diffusion_stencil_2d(type='FE', epsilon=epsilon, theta=theta)
    A = stencil_grid(stencil, (n, n), format='csr')
    X, Y = meshgrid(linspace(h, 1.0 - h, n), linspace(h, 1.0 - h, n))
    data['X'] = X
    data['Y'] = Y

    if randomize:
        print "Random diagonal scaling..."
        D = my_rand(A.shape[0], 1)
        D[D < 0.] -= 1e-3
        D[D >= 0.] += 1e-3
        data['D'] = D
        D_inv = 1. / D
        data['D_inv'] = D_inv
        A = scale_rows(A, D)
        A = scale_columns(A, D)

    if symmetric_scale:
        symmetric_rescaling(A, copy=False)

    print "Ratio of largest to smallest (in magnitude) diagonal element in A: %1.3e"% \
          (abs(A.diagonal()).max() / abs(A.diagonal()).min())
    data['A'] = A
    print 'Generate initial guess (which is random)...'
    data['x0'] = my_rand(data['A'].shape[0], 1)
    print 'Generate rhs (which is zero)...'
    data['b'] = numpy.zeros((data['A'].shape[0], 1))

    return data
Esempio n. 5
0
 def test_zero_sum(self):
     """test that stencil entries sum to zero"""
     for type in ['FD', 'FE']:
         for theta in [np.pi/8, np.pi/5, np.pi/4, np.pi/3, np.pi/2, np.pi]:
             for epsilon in [0.001, 0.01, 1.0]:
                 stencil = diffusion_stencil_2d(epsilon=epsilon,
                                                theta=theta, type=type)
                 assert_almost_equal(stencil.sum(), 0.0)
Esempio n. 6
0
    def test_simple_finite_difference(self):
        # isotropic
        stencil = [[0.0, -1.0, 0.0],
                   [-1.0, 4.0, -1.0],
                   [0.0, -1.0, 0.0]]
        assert_equal(diffusion_stencil_2d(epsilon=1.0, theta=0.0,
                     type='FD'), stencil)

        # weak horizontal
        stencil = [[0.0, -1.0, 0.0],
                   [-0.5, 3.0, -0.5],
                   [0.0, -1.0, 0.0]]
        assert_almost_equal(diffusion_stencil_2d(epsilon=0.5, theta=0.0,
                            type='FD'), stencil)

        # weak vertical
        stencil = [[0.0, -0.5, 0.0],
                   [-1.0, 3.0, -1.0],
                   [0.0, -0.5, 0.0]]
        assert_almost_equal(diffusion_stencil_2d(epsilon=0.5, theta=np.pi/2,
                            type='FD'), stencil)
Esempio n. 7
0
from copy import deepcopy

# ------------------------------------------------------------------------- #
# ------------------------------------------------------------------------- #

SOC = 'evol'
SOC_drop = 4.0
SA = 1  # Use SA type coarsening or CR
pow_G = 1
epsilon = 0.1
theta = 3.0 * math.pi / 16.0
N = 40
n = N * N
grid_dims = [N, N]
stencil = diffusion_stencil_2d(epsilon, theta)
A = stencil_grid(stencil, grid_dims, format='csr')
[d, d, A] = symmetric_rescaling(A)
A = csr_matrix(A)
B = np.kron(np.ones((A.shape[0] / 1, 1), dtype=A.dtype), np.eye(1))
tol = 1e-12  # Drop tolerance for singular values

if SA:
    if SOC == 'evol':
        C = evolution_strength_of_connection(A, B, epsilon=SOC_drop, k=2)
    else:
        SOC = 'symm'
        C = symmetric_strength_of_connection(A, theta=SOC_drop)

    AggOp, Cpts = standard_aggregation(C)
else:
Esempio n. 8
0
#------------------------------------------------------------------
# Step 1: import scipy and pyamg packages
#------------------------------------------------------------------
from numpy import meshgrid, linspace
from scipy import rand, pi
from scipy.linalg import norm
from pyamg import *
from pyamg.gallery import stencil_grid
from pyamg.gallery.diffusion import diffusion_stencil_2d

#------------------------------------------------------------------
# Step 2: setup up the system using pyamg.gallery
#------------------------------------------------------------------
n=200
X,Y = meshgrid(linspace(0,1,n),linspace(0,1,n))
stencil = diffusion_stencil_2d(type='FE',epsilon=0.001,theta=pi/3)
A = stencil_grid(stencil, (n,n), format='csr')
b = rand(A.shape[0])                     # pick a random right hand side

#------------------------------------------------------------------
# Step 3: setup of the multigrid hierarchy
#------------------------------------------------------------------
ml = smoothed_aggregation_solver(A)      # construct the multigrid hierarchy

#------------------------------------------------------------------
# Step 4: solve the system
#------------------------------------------------------------------
res1 = []
x = ml.solve(b, tol=1e-12, residuals=res1)# solve Ax=b to a tolerance of 1e-12

#------------------------------------------------------------------
Esempio n. 9
0
# task1.3
from pyamg.gallery.diffusion import diffusion_stencil_2d
from pyamg.gallery import stencil_grid
sten = diffusion_stencil_2d(type='FD', \
       epsilon=0.001, theta=3.1416/3.0)
A = stencil_grid(sten, (100, 100), format='csr')

# task1.4
from pyamg import *
ml = smoothed_aggregation_solver(A)

# task1.5
from numpy import ones
b = ones((A.shape[0], 1))
res = []
x = ml.solve(b, tol=1e-8, \
    residuals=res)

from pylab import *
semilogy(res[1:])
xlabel('iteration')
ylabel('residual norm')
title('Residual History')
show()
            'sweep': 'symmetric',
            'iterations': 1
        })
    smooth = ('energy', {'maxiter': 9, 'degree': 3})  # Prolongation Smoother
    classic_theta = 0.0  # Classic Strength Measure
    #    Drop Tolerance
    evolution_theta = 4.0  # evolution Strength Measure
    #    Drop Tolerance

    for n in nlist:
        nx = n
        ny = n
        print "Running Grid = (%d x %d)" % (nx, ny)

        # Rotated Anisotropic Diffusion Operator
        stencil = diffusion_stencil_2d(type='FE', epsilon=epsilon, theta=theta)
        A = stencil_grid(stencil, (nx, ny), format='csr')

        # Random initial guess, zero RHS
        x0 = scipy.rand(A.shape[0])
        b = numpy.zeros((A.shape[0], ))

        # Classic SA strength measure
        ml = smoothed_aggregation_solver(A,
                                         max_coarse=mcoarse,
                                         coarse_solver='pinv2',
                                         presmoother=prepost,
                                         postsmoother=prepost,
                                         smooth=smooth,
                                         strength=('symmetric', {
                                             'theta': classic_theta
Esempio n. 11
0
#------------------------------------------------------------------
# Step 1: import scipy and pyamg packages
#------------------------------------------------------------------
from numpy import meshgrid, linspace
from scipy import rand, pi
from scipy.linalg import norm
from pyamg import *
from pyamg.gallery import stencil_grid
from pyamg.gallery.diffusion import diffusion_stencil_2d

#------------------------------------------------------------------
# Step 2: setup up the system using pyamg.gallery
#------------------------------------------------------------------
n=200
X,Y = meshgrid(linspace(0,1,n),linspace(0,1,n))
stencil = diffusion_stencil_2d(type='FE',epsilon=0.001,theta=pi/3)
A = stencil_grid(stencil, (n,n), format='csr')
b = rand(A.shape[0])                     # pick a random right hand side

#------------------------------------------------------------------
# Step 3: setup of the multigrid hierarchy
#------------------------------------------------------------------
ml = smoothed_aggregation_solver(A)      # construct the multigrid hierarchy

#------------------------------------------------------------------
# Step 4: solve the system
#------------------------------------------------------------------
res1 = []
x = ml.solve(b, tol=1e-12, residuals=res1)# solve Ax=b to a tolerance of 1e-12

#------------------------------------------------------------------
Esempio n. 12
0
from pyamg.gallery.diffusion import diffusion_stencil_2d
from pyamg.gallery import stencil_grid
from numpy import set_printoptions

set_printoptions(precision=2)
sten = diffusion_stencil_2d(type="FD", epsilon=0.001, theta=3.1416 / 3.0)
A = stencil_grid(sten, (100, 100), format="csr")
# print the matrix stencil
print(A[5050, :].data)
print(sten)
Esempio n. 13
0
# task1.3
from pyamg.gallery.diffusion import diffusion_stencil_2d
from pyamg.gallery import stencil_grid
sten = diffusion_stencil_2d(type='FD', \
       epsilon=0.001, theta=3.1416/3.0)
A = stencil_grid(sten, (100,100), format='csr')

# task1.4
from pyamg import *
ml = smoothed_aggregation_solver(A)

# task1.5
from numpy import ones
b = ones((A.shape[0],1))
res = []
x = ml.solve(b, tol=1e-8, \
    residuals=res)

from pylab import *
semilogy(res[1:])
xlabel('iteration')
ylabel('residual norm')
title('Residual History')
show()
    epsilon = 0.001  # Anisotropic coefficient
    mcoarse = 10  # Max coarse grid size
    prepost = ("gauss_seidel", {"sweep": "symmetric", "iterations": 1})  # pre/post smoother
    smooth = ("energy", {"maxiter": 9, "degree": 3})  # Prolongation Smoother
    classic_theta = 0.0  # Classic Strength Measure
    #    Drop Tolerance
    evolution_theta = 4.0  # evolution Strength Measure
    #    Drop Tolerance

    for n in nlist:
        nx = n
        ny = n
        print "Running Grid = (%d x %d)" % (nx, ny)

        # Rotated Anisotropic Diffusion Operator
        stencil = diffusion_stencil_2d(type="FE", epsilon=epsilon, theta=theta)
        A = stencil_grid(stencil, (nx, ny), format="csr")

        # Random initial guess, zero RHS
        x0 = scipy.rand(A.shape[0])
        b = numpy.zeros((A.shape[0],))

        # Classic SA strength measure
        ml = smoothed_aggregation_solver(
            A,
            max_coarse=mcoarse,
            coarse_solver="pinv2",
            presmoother=prepost,
            postsmoother=prepost,
            smooth=smooth,
            strength=("symmetric", {"theta": classic_theta}),
Esempio n. 15
0
                              CSR matrix for basic rotated anisotropic diffusion
                              BSR matrix for basic 2D linearized elasticity
                              CSR matrix for a nonsymmetric recirculating flow problem  

Many more solver parameters may be specified than outlined in the below
examples.  Only the most basic are shown.

Run with 
    >>> python demo.py
and examine the on-screen output and file output.
'''
from scipy import pi
from pyamg import gallery
from pyamg.gallery import diffusion
stencil = diffusion.diffusion_stencil_2d(type='FE',
                                         epsilon=0.001,
                                         theta=2 * pi / 16.0)
A = gallery.stencil_grid(stencil, (50, 50), format='csr')

from pyamg import gallery
from solver_diagnostics import solver_diagnostics
from scipy import pi
from pyamg.gallery import diffusion

choice = input('\nThere are four different test problems.  Enter \n' + \
               '1:  Isotropic diffusion example\n' + \
               '2:  Anisotropic diffusion example\n' + \
               '3:  Elasticity example\n' + \
               '4:  Nonsymmetric flow example\n\n ')

if choice == 1: