def smoothed_aggregation_helmholtz_solver(A, planewaves, use_constant=(True, {'last_level':0}), symmetry='symmetric', strength='symmetric', aggregate='standard', smooth=('energy', {'krylov': 'gmres'}), presmoother=('gauss_seidel_nr',{'sweep':'symmetric'}), postsmoother=('gauss_seidel_nr',{'sweep':'symmetric'}), improve_candidates='default', max_levels = 10, max_coarse = 100, **kwargs): """ Create a multilevel solver using Smoothed Aggregation (SA) for a 2D Helmholtz operator Parameters ---------- A : {csr_matrix, bsr_matrix} Sparse NxN matrix in CSR or BSR format planewaves : { list } [pw_0, pw_1, ..., pw_n], where the k-th tuple pw_k is of the form (fn, args). fn is a callable and args is a dictionary of arguments for fn. This k-th tuple is used to define any new planewaves (i.e., new coarse grid basis functions) to be appended to the existing B_k at that level. The function fn must return functions defined on the finest level, i.e., a collection of vector(s) of length A.shape[0]. These vectors are then restricted to the appropriate level, where they enrich the coarse space. Instead of a tuple, None can be used to stipulate no introduction of planewaves at that level. If len(planewaves) < max_levels, the last entry is used to define coarser level planewaves. use_constant : {tuple} Tuple of the form (bool, {'last_level':int}). The boolean denotes whether to introduce the constant in B at level 0. 'last_level' denotes the final level to use the constant in B. That is, if 'last_level' is 1, then the vector in B corresponding to the constant on level 0 is dropped from B at level 2. This is important, because using constant based interpolation beyond the Nyquist rate will result in poor solver performance. symmetry : {string} 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note that for the strictly real case, symmetric and hermitian are the same Note that this flag does not denote definiteness of the operator. strength : ['symmetric', 'classical', 'evolution', ('predefined', {'C' : csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined strength matrix on each level. aggregate : ['standard', 'lloyd', 'naive', ('predefined', {'AggOp' : csr_matrix})] Method used to aggregate nodes. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined aggregation on each level. smooth : ['jacobi', 'richardson', 'energy', None] Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('jacobi',{'filter' : True }). See notes below for varying this parameter on a per level basis. presmoother : {tuple, string, list} : default ('block_gauss_seidel', {'sweep':'symmetric'}) Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. See notes below for varying this parameter on a per level basis. postsmoother : {tuple, string, list} Same as presmoother, except defines the postsmoother. improve_candidates : {list} : default [('block_gauss_seidel', {'sweep':'symmetric'}), None] The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse : {integer} : default 500 Maximum number of variables permitted on the coarse grid. Other Parameters ---------------- coarse_solver : ['splu','lu', ... ] Solver used at the coarsest level of the MG hierarchy Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, smoothed_aggregation_solver Notes ----- - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the ith entry defines the method at the ith level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric',{'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Examples -------- >>> from pyamg import smoothed_aggregation_helmholtz_solver, poisson >>> from scipy.sparse.linalg import cg >>> from scipy import rand >>> A = poisson((100,100), format='csr') # matrix >>> b = rand(A.shape[0]) # random RHS >>> ml = smoothed_aggregation_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x,info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1] L. N. Olson and J. B. Schroder. Smoothed Aggregation for Helmholtz Problems. Numerical Linear Algebra with Applications. pp. 361--386. 17 (2010). """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): raise TypeError('argument A must have type csr_matrix or bsr_matrix') A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and (symmetry != 'nonsymmetric'): raise ValueError('expected \'symmetric\', \'nonsymmetric\' or \'hermitian\' for the symmetry parameter ') A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') ## # Preprocess and extend planewaves to length max_levels planewaves = preprocess_planewaves(planewaves, max_levels) # Check that the user has defined functions for B at each level use_const, args = unpack_arg(use_constant) first_planewave_level = -1 for pw in planewaves: first_planewave_level += 1 if pw is not None: break ## if (use_const == False) and (planewaves[0] == None): raise ValueError('No functions defined for B on the finest level, ' + \ 'either use_constant must be true, or planewaves must be defined for level 0') elif (use_const == True) and (args['last_level'] < first_planewave_level-1): raise ValueError('Some levels have no function(s) defined for B. ' + \ 'Change use_constant and/or planewave arguments.') ## # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates = levelize_smooth_or_improve_candidates(improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) ## # Start first level levels = [] levels.append( multilevel_solver.level() ) levels[-1].A = A # matrix levels[-1].B = numpy.zeros((A.shape[0],0)) # place-holder for near-nullspace candidates zeros_0 = numpy.zeros((levels[0].A.shape[0],), dtype=A.dtype) while len(levels) < max_levels and levels[-1].A.shape[0] > max_coarse: A = levels[0].A A_l = levels[-1].A zeros_l = numpy.zeros((levels[-1].A.shape[0],), dtype=A.dtype) ## # Generate additions to n-th level candidates if planewaves[len(levels)-1] != None: fn, args = unpack_arg(planewaves[len(levels)-1]) Bcoarse2 = numpy.array(fn(**args)) ## # As in alpha-SA, relax the candidates before restriction if improve_candidates[0] is not None: Bcoarse2 = relaxation_as_linear_operator(improve_candidates[0], A, zeros_0)*Bcoarse2 ## # Restrict Bcoarse2 to current level for i in range(len(levels)-1): Bcoarse2 = levels[i].R*Bcoarse2 # relax after restriction if improve_candidates[len(levels)-1] is not None: Bcoarse2 =relaxation_as_linear_operator(improve_candidates[len(levels)-1],A_l,zeros_l)*Bcoarse2 else: Bcoarse2 = numpy.zeros((A_l.shape[0],0),dtype=A.dtype) ## # Deal with the use of constant in interpolation use_const, args = unpack_arg(use_constant) if use_const and len(levels) == 1: # If level 0, and the constant is to be used in interpolation levels[0].B = numpy.hstack( (numpy.ones((A.shape[0],1), dtype=A.dtype), Bcoarse2) ) elif use_const and args['last_level'] == len(levels)-2: # If the previous level was the last level to use the constant, then remove the # coarse grid function based on the constant from B levels[-1].B = numpy.hstack( (levels[-1].B[:,1:], Bcoarse2) ) else: levels[-1].B = numpy.hstack((levels[-1].B, Bcoarse2)) ## # Create and Append new level extend_hierarchy(levels, strength, aggregate, smooth, [None for i in range(max_levels)] ,keep=True) ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def smoothed_aggregation_solver(A, B=None, BH=None, symmetry='hermitian', strength='symmetric', aggregate='standard', smooth=('jacobi', { 'omega': 4.0 / 3.0 }), presmoother=('block_gauss_seidel', { 'sweep': 'symmetric' }), postsmoother=('block_gauss_seidel', { 'sweep': 'symmetric' }), improve_candidates=[('block_gauss_seidel', { 'sweep': 'symmetric', 'iterations': 4 }), None], max_levels=10, max_coarse=10, diagonal_dominance=False, keep=False, **kwargs): """Create a multilevel solver using classical-style Smoothed Aggregation (SA). Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix in CSR or BSR format B : None, array_like Right near-nullspace candidates stored in the columns of an NxK array. The default value B=None is equivalent to B=ones((N,1)) BH : None, array_like Left near-nullspace candidates stored in the columns of an NxK array. BH is only used if symmetry is 'nonsymmetric'. The default value B=None is equivalent to BH=B.copy() symmetry : string 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note, in the strictly real case, symmetric and hermitian are the same. Note, this flag does not denote definiteness of the operator. strength : string or list Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. Choose from 'symmetric', 'classical', 'evolution', 'algebraic_distance', 'affinity', ('predefined', {'C' : csr_matrix}), None aggregate : string or list Method used to aggregate nodes. Choose from 'standard', 'lloyd', 'naive', ('predefined', {'AggOp' : csr_matrix}) smooth : list Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('jacobi',{'filter' : True }). Choose from 'jacobi', 'richardson', 'energy', None presmoother : tuple, string, list Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. postsmoother : tuple, string, list Same as presmoother, except defines the postsmoother. improve_candidates : tuple, string, list The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. If tuple or string, then this single relaxation descriptor defines improve_candidates on all levels. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : integer Maximum number of levels to be used in the multilevel solver. max_coarse : integer Maximum number of variables permitted on the coarse grid. diagonal_dominance : bool, tuple If True (or the first tuple entry is True), then avoid coarsening diagonally dominant rows. The second tuple entry requires a dictionary, where the key value 'theta' is used to tune the diagonal dominance threshold. keep : bool Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), and aggregation (AggOp) are kept. Other Parameters ---------------- cycle_type : ['V','W','F'] Structrure of multigrid cycle coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, classical.ruge_stuben_solver, aggregation.smoothed_aggregation_solver Notes ----- - This method implements classical-style SA, not root-node style SA (see aggregation.rootnode_solver). - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - At each level, four steps are executed in order to define the coarser level operator. 1. Matrix A is given and used to derive a strength matrix, C. 2. Based on the strength matrix, indices are grouped or aggregated. 3. The aggregates define coarse nodes and a tentative prolongation operator T is defined by injection 4. The tentative prolongation operator is smoothed by a relaxation scheme to improve the quality and extent of interpolation from the aggregates to fine nodes. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the i-th entry defines the method at the i-th level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Examples -------- >>> from pyamg import smoothed_aggregation_solver >>> from pyamg.gallery import poisson >>> from scipy.sparse.linalg import cg >>> import numpy as np >>> A = poisson((100,100), format='csr') # matrix >>> b = np.ones((A.shape[0])) # RHS >>> ml = smoothed_aggregation_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x,info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1996VaMaBr] Vanek, P. and Mandel, J. and Brezina, M., "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", Computing, vol. 56, no. 3, pp. 179--196, 1996. http://citeseer.ist.psu.edu/vanek96algebraic.html """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except BaseException: raise TypeError( 'Argument A must have type csr_matrix or bsr_matrix, or be convertible to csr_matrix' ) A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and\ (symmetry != 'nonsymmetric'): raise ValueError( 'expected \'symmetric\', \'nonsymmetric\' or \'hermitian\' for the symmetry parameter ' ) A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Right near nullspace candidates use constant for each variable as default if B is None: B = np.kron( np.ones((int(A.shape[0] / blocksize(A)), 1), dtype=A.dtype), np.eye(blocksize(A), dtype=A.dtype)) else: B = np.asarray(B, dtype=A.dtype) if len(B.shape) == 1: B = B.reshape(-1, 1) if B.shape[0] != A.shape[0]: raise ValueError( 'The near null-space modes B have incorrect dimensions for matrix A' ) if B.shape[1] < blocksize(A): warn( 'Having less target vectors, B.shape[1], than blocksize of A can degrade convergence factors.' ) # Left near nullspace candidates if A.symmetry == 'nonsymmetric': if BH is None: BH = B.copy() else: BH = np.asarray(BH, dtype=A.dtype) if len(BH.shape) == 1: BH = BH.reshape(-1, 1) if BH.shape[1] != B.shape[1]: raise ValueError( 'The number of left and right near null-space modes B and BH, must be equal' ) if BH.shape[0] != A.shape[0]: raise ValueError( 'The near null-space modes BH have incorrect dimensions for matrix A' ) # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates =\ levelize_smooth_or_improve_candidates(improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Construct multilevel structure levels = [] levels.append(multilevel_solver.level()) levels[-1].A = A # matrix # Append near nullspace candidates levels[-1].B = B # right candidates if A.symmetry == 'nonsymmetric': levels[-1].BH = BH # left candidates while len(levels) < max_levels and\ int(levels[-1].A.shape[0]/blocksize(levels[-1].A)) > max_coarse: extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, diagonal_dominance, keep) ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def smoothed_aggregation_helmholtz_solver(A, planewaves, use_constant=(True, { 'last_level': 0 }), symmetry='symmetric', strength='symmetric', aggregate='standard', smooth=('energy', { 'krylov': 'gmres' }), presmoother=('gauss_seidel_nr', { 'sweep': 'symmetric' }), postsmoother=('gauss_seidel_nr', { 'sweep': 'symmetric' }), improve_candidates='default', max_levels=10, max_coarse=100, **kwargs): """ Create a multilevel solver using Smoothed Aggregation (SA) for a 2D Helmholtz operator Parameters ---------- A : {csr_matrix, bsr_matrix} Sparse NxN matrix in CSR or BSR format planewaves : { list } [pw_0, pw_1, ..., pw_n], where the k-th tuple pw_k is of the form (fn, args). fn is a callable and args is a dictionary of arguments for fn. This k-th tuple is used to define any new planewaves (i.e., new coarse grid basis functions) to be appended to the existing B_k at that level. The function fn must return functions defined on the finest level, i.e., a collection of vector(s) of length A.shape[0]. These vectors are then restricted to the appropriate level, where they enrich the coarse space. Instead of a tuple, None can be used to stipulate no introduction of planewaves at that level. If len(planewaves) < max_levels, the last entry is used to define coarser level planewaves. use_constant : {tuple} Tuple of the form (bool, {'last_level':int}). The boolean denotes whether to introduce the constant in B at level 0. 'last_level' denotes the final level to use the constant in B. That is, if 'last_level' is 1, then the vector in B corresponding to the constant on level 0 is dropped from B at level 2. This is important, because using constant based interpolation beyond the Nyquist rate will result in poor solver performance. symmetry : {string} 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note that for the strictly real case, symmetric and hermitian are the same Note that this flag does not denote definiteness of the operator. strength : ['symmetric', 'classical', 'evolution', ('predefined', {'C' : csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined strength matrix on each level. aggregate : ['standard', 'lloyd', 'naive', ('predefined', {'AggOp' : csr_matrix})] Method used to aggregate nodes. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined aggregation on each level. smooth : ['jacobi', 'richardson', 'energy', None] Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('jacobi',{'filter' : True }). See notes below for varying this parameter on a per level basis. presmoother : {tuple, string, list} : default ('block_gauss_seidel', {'sweep':'symmetric'}) Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. See notes below for varying this parameter on a per level basis. postsmoother : {tuple, string, list} Same as presmoother, except defines the postsmoother. improve_candidates : {list} : default [('block_gauss_seidel', {'sweep':'symmetric'}), None] The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse : {integer} : default 500 Maximum number of variables permitted on the coarse grid. Other Parameters ---------------- coarse_solver : ['splu','lu', ... ] Solver used at the coarsest level of the MG hierarchy Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, smoothed_aggregation_solver Notes ----- - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the ith entry defines the method at the ith level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric',{'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Examples -------- >>> from pyamg import smoothed_aggregation_helmholtz_solver, poisson >>> from scipy.sparse.linalg import cg >>> from scipy import rand >>> A = poisson((100,100), format='csr') # matrix >>> b = rand(A.shape[0]) # random RHS >>> ml = smoothed_aggregation_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x,info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1] L. N. Olson and J. B. Schroder. Smoothed Aggregation for Helmholtz Problems. Numerical Linear Algebra with Applications. pp. 361--386. 17 (2010). """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): raise TypeError('argument A must have type csr_matrix or bsr_matrix') A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and ( symmetry != 'nonsymmetric'): raise ValueError( 'expected \'symmetric\', \'nonsymmetric\' or \'hermitian\' for the symmetry parameter ' ) A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') ## # Preprocess and extend planewaves to length max_levels planewaves = preprocess_planewaves(planewaves, max_levels) # Check that the user has defined functions for B at each level use_const, args = unpack_arg(use_constant) first_planewave_level = -1 for pw in planewaves: first_planewave_level += 1 if pw is not None: break ## if (use_const == False) and (planewaves[0] == None): raise ValueError('No functions defined for B on the finest level, ' + \ 'either use_constant must be true, or planewaves must be defined for level 0') elif (use_const == True) and (args['last_level'] < first_planewave_level - 1): raise ValueError('Some levels have no function(s) defined for B. ' + \ 'Change use_constant and/or planewave arguments.') ## # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates = levelize_smooth_or_improve_candidates( improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) ## # Start first level levels = [] levels.append(multilevel_solver.level()) levels[-1].A = A # matrix levels[-1].B = numpy.zeros( (A.shape[0], 0)) # place-holder for near-nullspace candidates zeros_0 = numpy.zeros((levels[0].A.shape[0], ), dtype=A.dtype) while len(levels) < max_levels and levels[-1].A.shape[0] > max_coarse: A = levels[0].A A_l = levels[-1].A zeros_l = numpy.zeros((levels[-1].A.shape[0], ), dtype=A.dtype) ## # Generate additions to n-th level candidates if planewaves[len(levels) - 1] != None: fn, args = unpack_arg(planewaves[len(levels) - 1]) Bcoarse2 = numpy.array(fn(**args)) ## # As in alpha-SA, relax the candidates before restriction if improve_candidates[0] is not None: Bcoarse2 = relaxation_as_linear_operator( improve_candidates[0], A, zeros_0) * Bcoarse2 ## # Restrict Bcoarse2 to current level for i in range(len(levels) - 1): Bcoarse2 = levels[i].R * Bcoarse2 # relax after restriction if improve_candidates[len(levels) - 1] is not None: Bcoarse2 = relaxation_as_linear_operator( improve_candidates[len(levels) - 1], A_l, zeros_l) * Bcoarse2 else: Bcoarse2 = numpy.zeros((A_l.shape[0], 0), dtype=A.dtype) ## # Deal with the use of constant in interpolation use_const, args = unpack_arg(use_constant) if use_const and len(levels) == 1: # If level 0, and the constant is to be used in interpolation levels[0].B = numpy.hstack((numpy.ones((A.shape[0], 1), dtype=A.dtype), Bcoarse2)) elif use_const and args['last_level'] == len(levels) - 2: # If the previous level was the last level to use the constant, then remove the # coarse grid function based on the constant from B levels[-1].B = numpy.hstack((levels[-1].B[:, 1:], Bcoarse2)) else: levels[-1].B = numpy.hstack((levels[-1].B, Bcoarse2)) ## # Create and Append new level extend_hierarchy(levels, strength, aggregate, smooth, [None for i in range(max_levels)], keep=True) ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def smoothed_aggregation_solver(A, B=None, BH=None, symmetry='hermitian', strength='symmetric', aggregate='standard', smooth=('jacobi', {'omega': 4.0/3.0}), presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), improve_candidates=[('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None], max_levels = 10, max_coarse = 10, diagonal_dominance=False, keep=False, **kwargs): """ Create a multilevel solver using classical-style Smoothed Aggregation (SA) Parameters ---------- A : {csr_matrix, bsr_matrix} Sparse NxN matrix in CSR or BSR format B : {None, array_like} Right near-nullspace candidates stored in the columns of an NxK array. The default value B=None is equivalent to B=ones((N,1)) BH : {None, array_like} Left near-nullspace candidates stored in the columns of an NxK array. BH is only used if symmetry is 'nonsymmetric'. The default value B=None is equivalent to BH=B.copy() symmetry : {string} 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note, in the strictly real case, symmetric and hermitian are the same Note, this flag does not denote definiteness of the operator. strength : {list} : default ['symmetric', 'classical', 'evolution', 'algebraic_distance', 'affinity', ('predefined', {'C' : csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined strength matrix on each level. aggregate : {list} : default ['standard', 'lloyd', 'naive', ('predefined', {'AggOp' : csr_matrix})] Method used to aggregate nodes. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined aggregation on each level. smooth : {list} : default ['jacobi', 'richardson', 'energy', None] Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('jacobi',{'filter' : True }). See notes below for varying this parameter on a per level basis. presmoother : {tuple, string, list} : default ('block_gauss_seidel', {'sweep':'symmetric'}) Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. See notes below for varying this parameter on a per level basis. postsmoother : {tuple, string, list} Same as presmoother, except defines the postsmoother. improve_candidates : {tuple, string, list} : default [('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None] The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. If tuple or string, then this single relaxation descriptor defines improve_candidates on all levels. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse : {integer} : default 500 Maximum number of variables permitted on the coarse grid. diagonal_dominance : {bool, tuple} : default False If True (or the first tuple entry is True), then avoid coarsening diagonally dominant rows. The second tuple entry requires a dictionary, where the key value 'theta' is used to tune the diagonal dominance threshold. keep : {bool} : default False Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), and aggregation (AggOp) are kept. Other Parameters ---------------- cycle_type : ['V','W','F'] Structrure of multigrid cycle coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. setup_complexity : bool For a detailed, more accurate setup complexity, pass in 'setup_complexity' = True. This will slow down performance, but increase accuracy of complexity count. Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, classical.ruge_stuben_solver, aggregation.smoothed_aggregation_solver Notes ----- - This method implements classical-style SA, not root-node style SA (see aggregation.rootnode_solver). - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - At each level, four steps are executed in order to define the coarser level operator. 1. Matrix A is given and used to derive a strength matrix, C. 2. Based on the strength matrix, indices are grouped or aggregated. 3. The aggregates define coarse nodes and a tentative prolongation operator T is defined by injection 4. The tentative prolongation operator is smoothed by a relaxation scheme to improve the quality and extent of interpolation from the aggregates to fine nodes. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the i-th entry defines the method at the i-th level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Examples -------- >>> from pyamg import smoothed_aggregation_solver >>> from pyamg.gallery import poisson >>> from scipy.sparse.linalg import cg >>> import numpy as np >>> A = poisson((100,100), format='csr') # matrix >>> b = np.ones((A.shape[0])) # RHS >>> ml = smoothed_aggregation_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x,info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1] Vanek, P. and Mandel, J. and Brezina, M., "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", Computing, vol. 56, no. 3, pp. 179--196, 1996. http://citeseer.ist.psu.edu/vanek96algebraic.html """ if ('setup_complexity' in kwargs): if kwargs['setup_complexity'] == True: mat_mat_complexity.__detailed__ = True del kwargs['setup_complexity'] if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except: raise TypeError('Argument A must have type csr_matrix or ' 'bsr_matrix, or be convertible to csr_matrix') A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and\ (symmetry != 'nonsymmetric'): raise ValueError('expected \'symmetric\', \'nonsymmetric\' or ' 'hermitian\' for the symmetry parameter ') A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Right near nullspace candidates use constant for each variable as default if B is None: B = np.kron(np.ones((int(A.shape[0]/blocksize(A)), 1), dtype=A.dtype), np.eye(blocksize(A))) else: B = np.asarray(B, dtype=A.dtype) if len(B.shape) == 1: B = B.reshape(-1, 1) if B.shape[0] != A.shape[0]: raise ValueError('The near null-space modes B have incorrect \ dimensions for matrix A') if B.shape[1] < blocksize(A): warn('Having less target vectors, B.shape[1], than \ blocksize of A can degrade convergence factors.') # Left near nullspace candidates if A.symmetry == 'nonsymmetric': if BH is None: BH = B.copy() else: BH = np.asarray(BH, dtype=A.dtype) if len(BH.shape) == 1: BH = BH.reshape(-1, 1) if BH.shape[1] != B.shape[1]: raise ValueError('The number of left and right near \ null-space modes B and BH, must be equal') if BH.shape[0] != A.shape[0]: raise ValueError('The near null-space modes BH have \ incorrect dimensions for matrix A') # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates =\ levelize_smooth_or_improve_candidates(improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Construct multilevel structure levels = [] levels.append(multilevel_solver.level()) levels[-1].A = A # matrix # Append near nullspace candidates levels[-1].B = B # right candidates if A.symmetry == 'nonsymmetric': levels[-1].BH = BH # left candidates while len(levels) < max_levels and\ int(levels[-1].A.shape[0]/blocksize(levels[-1].A)) > max_coarse: extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, diagonal_dominance, keep) # Construct and return multilevel hierarchy ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def adaptive_sa_solver(A, initial_candidates=None, symmetry='hermitian', pdef=True, num_candidates=1, candidate_iters=5, improvement_iters=0, epsilon=0.1, max_levels=10, max_coarse=10, aggregate='standard', prepostsmoother=('gauss_seidel', { 'sweep': 'symmetric' }), smooth=('jacobi', {}), strength='symmetric', coarse_solver='pinv2', eliminate_local=(False, { 'Ca': 1.0 }), keep=False, **kwargs): """ Create a multilevel solver using Adaptive Smoothed Aggregation (aSA) Parameters ---------- A : {csr_matrix, bsr_matrix} Square matrix in CSR or BSR format initial_candidates : {None, n x m dense matrix} If a matrix, then this forms the basis for the first m candidates. Also in this case, the initial setup stage is skipped, because this provides the first candidate(s). If None, then a random initial guess and relaxation are used to inform the initial candidate. symmetry : {string} 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian Note that for the strictly real case, these two options are the same Note that this flag does not denote definiteness of the operator pdef : {bool} True or False, whether A is known to be positive definite. num_candidates : {integer} : default 1 Number of near-nullspace candidates to generate candidate_iters : {integer} : default 5 Number of smoothing passes/multigrid cycles used at each level of the adaptive setup phase improvement_iters : {integer} : default 0 Number of times each candidate is improved epsilon : {float} : default 0.1 Target convergence factor max_levels : {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse : {integer} : default 500 Maximum number of variables permitted on the coarse grid. prepostsmoother : {string or dict} Pre- and post-smoother used in the adaptive method strength : ['symmetric', 'classical', 'evolution', ('predefined', {'C': csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. See smoothed_aggregation_solver(...) documentation. aggregate : ['standard', 'lloyd', 'naive', ('predefined', {'AggOp': csr_matrix})] Method used to aggregate nodes. See smoothed_aggregation_solver(...) documentation. smooth : ['jacobi', 'richardson', 'energy', None] Method used used to smooth the tentative prolongator. See smoothed_aggregation_solver(...) documentation coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. eliminate_local : {tuple} Length 2 tuple. If the first entry is True, then eliminate candidates where they aren't needed locally, using the second entry of the tuple to contain arguments to local elimination routine. Given the rigid sparse data structures, this doesn't help much, if at all, with complexity. Its more of a diagnostic utility. keep: {bool} : default False Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), and aggregation (AggOp) are kept. Returns ------- multilevel_solver : multilevel_solver Smoothed aggregation solver with adaptively generated candidates Notes ----- - Floating point value representing the "work" required to generate the solver. This value is the total cost of just relaxation, relative to the fine grid. The relaxation method used is assumed to symmetric Gauss-Seidel. - Unlike the standard Smoothed Aggregation (SA) method, adaptive SA does not require knowledge of near-nullspace candidate vectors. Instead, an adaptive procedure computes one or more candidates 'from scratch'. This approach is useful when no candidates are known or the candidates have been invalidated due to changes to matrix A. Examples -------- >>> from pyamg.gallery import stencil_grid >>> from pyamg.aggregation import adaptive_sa_solver >>> import numpy as np >>> A=stencil_grid([[-1,-1,-1],[-1,8.0,-1],[-1,-1,-1]],\ (31,31),format='csr') >>> [asa,work] = adaptive_sa_solver(A,num_candidates=1) >>> residuals=[] >>> x=asa.solve(b=np.ones((A.shape[0],)), x0=np.ones((A.shape[0],)),\ residuals=residuals) References ---------- .. [1] Brezina, Falgout, MacLachlan, Manteuffel, McCormick, and Ruge "Adaptive Smoothed Aggregation ($\alpha$SA) Multigrid" SIAM Review Volume 47, Issue 2 (2005) http://www.cs.umn.edu/~maclach/research/aSA2.pdf """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except: raise TypeError('Argument A must have type csr_matrix or\ bsr_matrix, or be convertible to csr_matrix') A = A.asfptype() if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Track work in terms of relaxation work = np.zeros((1, )) # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Develop initial candidate(s). Note that any predefined aggregation is # preserved. if initial_candidates is None: B, aggregate, strength =\ initial_setup_stage(A, symmetry, pdef, candidate_iters, epsilon, max_levels, max_coarse, aggregate, prepostsmoother, smooth, strength, work) # Normalize B B = (1.0 / norm(B, 'inf')) * B num_candidates -= 1 else: # Otherwise, use predefined candidates B = initial_candidates num_candidates -= B.shape[1] # Generate Aggregation and Strength Operators (the brute force way) sa = smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, strength=strength, max_levels=max_levels, max_coarse=max_coarse, aggregate=aggregate, coarse_solver=coarse_solver, improve_candidates=None, keep=True, **kwargs) if len(sa.levels) > 1: # Set strength-of-connection and aggregation aggregate = [('predefined', { 'AggOp': sa.levels[i].AggOp.tocsr() }) for i in range(len(sa.levels) - 1)] strength = [('predefined', { 'C': sa.levels[i].C.tocsr() }) for i in range(len(sa.levels) - 1)] # Develop additional candidates for i in range(num_candidates): x = general_setup_stage( smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=True, **kwargs), symmetry, candidate_iters, prepostsmoother, smooth, eliminate_local, coarse_solver, work) # Normalize x and add to candidate list x = x / norm(x, 'inf') if np.isinf(x[0]) or np.isnan(x[0]): raise ValueError('Adaptive candidate is all 0.') B = np.hstack((B, x.reshape(-1, 1))) # Improve candidates if B.shape[1] > 1 and improvement_iters > 0: b = np.zeros((A.shape[0], 1), dtype=A.dtype) for i in range(improvement_iters): for j in range(B.shape[1]): # Run a V-cycle built on everything except candidate j, while # using candidate j as the initial guess x0 = B[:, 0] B = B[:, 1:] sa_temp =\ smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=True, **kwargs) x = sa_temp.solve(b, x0=x0, tol=float(np.finfo(np.float).tiny), maxiter=candidate_iters, cycle='V') work[:] += 2 * sa_temp.operator_complexity() *\ sa_temp.levels[0].A.nnz * candidate_iters # Apply local elimination elim, elim_kwargs = unpack_arg(eliminate_local) if elim is True: x = x / norm(x, 'inf') eliminate_local_candidates(x, sa_temp.levels[0].AggOp, A, sa_temp.levels[0].T, **elim_kwargs) # Normalize x and add to candidate list x = x / norm(x, 'inf') if np.isinf(x[0]) or np.isnan(x[0]): raise ValueError('Adaptive candidate is all 0.') B = np.hstack((B, x.reshape(-1, 1))) elif improvement_iters > 0: # Special case for improving a single candidate max_levels = len(aggregate) + 1 max_coarse = 0 for i in range(improvement_iters): B, aggregate, strength =\ initial_setup_stage(A, symmetry, pdef, candidate_iters, epsilon, max_levels, max_coarse, aggregate, prepostsmoother, smooth, strength, work, initial_candidate=B) # Normalize B B = (1.0 / norm(B, 'inf')) * B return [ smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=keep, **kwargs), work[0] / A.nnz ]
def adaptive_sa_solver(A, initial_candidates=None, symmetry='hermitian', pdef=True, num_candidates=1, candidate_iters=5, improvement_iters=0, epsilon=0.1, max_levels=10, max_coarse=10, aggregate='standard', prepostsmoother=('gauss_seidel', {'sweep': 'symmetric'}), smooth=('jacobi', {}), strength='symmetric', coarse_solver='pinv2', eliminate_local=(False, {'Ca': 1.0}), keep=False, **kwargs): """Create a multilevel solver using Adaptive Smoothed Aggregation (aSA). Parameters ---------- A : csr_matrix, bsr_matrix Square matrix in CSR or BSR format initial_candidates : None, n x m dense matrix If a matrix, then this forms the basis for the first m candidates. Also in this case, the initial setup stage is skipped, because this provides the first candidate(s). If None, then a random initial guess and relaxation are used to inform the initial candidate. symmetry : string 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian Note that for the strictly real case, these two options are the same Note that this flag does not denote definiteness of the operator pdef : bool True or False, whether A is known to be positive definite. num_candidates : integer Number of near-nullspace candidates to generate candidate_iters : integer Number of smoothing passes/multigrid cycles used at each level of the adaptive setup phase improvement_iters : integer Number of times each candidate is improved epsilon : float Target convergence factor max_levels : integer Maximum number of levels to be used in the multilevel solver. max_coarse : integer Maximum number of variables permitted on the coarse grid. prepostsmoother : string or dict Pre- and post-smoother used in the adaptive method strength : ['symmetric', 'classical', 'evolution', ('predefined', {'C': csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. See smoothed_aggregation_solver(...) documentation. aggregate : ['standard', 'lloyd', 'naive', ('predefined', {'AggOp': csr_matrix})] Method used to aggregate nodes. See smoothed_aggregation_solver(...) documentation. smooth : ['jacobi', 'richardson', 'energy', None] Method used used to smooth the tentative prolongator. See smoothed_aggregation_solver(...) documentation coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. eliminate_local : tuple Length 2 tuple. If the first entry is True, then eliminate candidates where they aren't needed locally, using the second entry of the tuple to contain arguments to local elimination routine. Given the rigid sparse data structures, this doesn't help much, if at all, with complexity. Its more of a diagnostic utility. keep: bool Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), and aggregation (AggOp) are kept. Returns ------- multilevel_solver : multilevel_solver Smoothed aggregation solver with adaptively generated candidates Notes ----- - Floating point value representing the "work" required to generate the solver. This value is the total cost of just relaxation, relative to the fine grid. The relaxation method used is assumed to symmetric Gauss-Seidel. - Unlike the standard Smoothed Aggregation (SA) method, adaptive SA does not require knowledge of near-nullspace candidate vectors. Instead, an adaptive procedure computes one or more candidates 'from scratch'. This approach is useful when no candidates are known or the candidates have been invalidated due to changes to matrix A. Examples -------- >>> from pyamg.gallery import stencil_grid >>> from pyamg.aggregation import adaptive_sa_solver >>> import numpy as np >>> A=stencil_grid([[-1,-1,-1],[-1,8.0,-1],[-1,-1,-1]], (31,31),format='csr') >>> [asa,work] = adaptive_sa_solver(A,num_candidates=1) >>> residuals=[] >>> x=asa.solve(b=np.ones((A.shape[0],)), x0=np.ones((A.shape[0],)), residuals=residuals) References ---------- .. [1] Brezina, Falgout, MacLachlan, Manteuffel, McCormick, and Ruge "Adaptive Smoothed Aggregation (alpha SA) Multigrid" SIAM Review Volume 47, Issue 2 (2005) """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except BaseException: raise TypeError('Argument A must have type csr_matrix or\ bsr_matrix, or be convertible to csr_matrix') A = A.asfptype() if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Track work in terms of relaxation work = np.zeros((1,)) # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Develop initial candidate(s). Note that any predefined aggregation is # preserved. if initial_candidates is None: B, aggregate, strength =\ initial_setup_stage(A, symmetry, pdef, candidate_iters, epsilon, max_levels, max_coarse, aggregate, prepostsmoother, smooth, strength, work) # Normalize B B = (1.0/norm(B, 'inf')) * B num_candidates -= 1 else: # Otherwise, use predefined candidates B = initial_candidates num_candidates -= B.shape[1] # Generate Aggregation and Strength Operators (the brute force way) sa = smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, strength=strength, max_levels=max_levels, max_coarse=max_coarse, aggregate=aggregate, coarse_solver=coarse_solver, improve_candidates=None, keep=True, **kwargs) if len(sa.levels) > 1: # Set strength-of-connection and aggregation aggregate = [('predefined', {'AggOp': sa.levels[i].AggOp.tocsr()}) for i in range(len(sa.levels) - 1)] strength = [('predefined', {'C': sa.levels[i].C.tocsr()}) for i in range(len(sa.levels) - 1)] # Develop additional candidates for i in range(num_candidates): x = general_setup_stage( smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=True, **kwargs), symmetry, candidate_iters, prepostsmoother, smooth, eliminate_local, coarse_solver, work) # Normalize x and add to candidate list x = x/norm(x, 'inf') if np.isinf(x[0]) or np.isnan(x[0]): raise ValueError('Adaptive candidate is all 0.') B = np.hstack((B, x.reshape(-1, 1))) # Improve candidates if B.shape[1] > 1 and improvement_iters > 0: b = np.zeros((A.shape[0], 1), dtype=A.dtype) for i in range(improvement_iters): for j in range(B.shape[1]): # Run a V-cycle built on everything except candidate j, while # using candidate j as the initial guess x0 = B[:, 0] B = B[:, 1:] sa_temp =\ smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=True, **kwargs) x = sa_temp.solve(b, x0=x0, tol=float(np.finfo(np.float).tiny), maxiter=candidate_iters, cycle='V') work[:] += 2 * sa_temp.operator_complexity() *\ sa_temp.levels[0].A.nnz * candidate_iters # Apply local elimination elim, elim_kwargs = unpack_arg(eliminate_local) if elim is True: x = x/norm(x, 'inf') eliminate_local_candidates(x, sa_temp.levels[0].AggOp, A, sa_temp.levels[0].T, **elim_kwargs) # Normalize x and add to candidate list x = x/norm(x, 'inf') if np.isinf(x[0]) or np.isnan(x[0]): raise ValueError('Adaptive candidate is all 0.') B = np.hstack((B, x.reshape(-1, 1))) elif improvement_iters > 0: # Special case for improving a single candidate max_levels = len(aggregate) + 1 max_coarse = 0 for i in range(improvement_iters): B, aggregate, strength =\ initial_setup_stage(A, symmetry, pdef, candidate_iters, epsilon, max_levels, max_coarse, aggregate, prepostsmoother, smooth, strength, work, initial_candidate=B) # Normalize B B = (1.0/norm(B, 'inf'))*B return [smoothed_aggregation_solver(A, B=B, symmetry=symmetry, presmoother=prepostsmoother, postsmoother=prepostsmoother, smooth=smooth, coarse_solver=coarse_solver, aggregate=aggregate, strength=strength, improve_candidates=None, keep=keep, **kwargs), work[0]/A.nnz]
def rootnode_solver(A, B=None, BH=None, symmetry='hermitian', strength='symmetric', aggregate='standard', smooth='energy', presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), improve_candidates=('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), max_levels = 10, max_coarse = 10, diagonal_dominance=False, keep=False, **kwargs): """ Create a multilevel solver using root-node based Smoothed Aggregation (SA). See the notes below, for the major differences with the classical-style smoothed aggregation solver in aggregation.smoothed_aggregation_solver. Parameters ---------- A : {csr_matrix, bsr_matrix} Sparse NxN matrix in CSR or BSR format B : {None, array_like} Right near-nullspace candidates stored in the columns of an NxK array. K must be >= the blocksize of A (see reference [2]). The default value B=None is equivalent to choosing the constant over each block-variable, B=np.kron(np.ones((A.shape[0]/blocksize(A), 1)), np.eye(blocksize(A))) BH : {None, array_like} Left near-nullspace candidates stored in the columns of an NxK array. BH is only used if symmetry is 'nonsymmetric'. K must be >= the blocksize of A (see reference [2]). The default value B=None is equivalent to choosing the constant over each block-variable, B=np.kron(np.ones((A.shape[0]/blocksize(A), 1)), np.eye(blocksize(A))) symmetry : {string} 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note that for the strictly real case, symmetric and hermitian are the same Note that this flag does not denote definiteness of the operator. strength : {list} : default ['symmetric', 'classical', 'evolution', 'algebraic_distance', 'affinity', ('predefined', {'C' : csr_matrix}), None] Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined strength matrix on each level. aggregate : {list} : default ['standard', 'lloyd', 'naive', ('predefined', {'AggOp' : csr_matrix})] Method used to aggregate nodes. See notes below for varying this parameter on a per level basis. Also, see notes below for using a predefined aggregation on each level. smooth : {list} : default ['energy', None] Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('energy',{'krylov' : 'gmres'}). Only 'energy' and None are valid prolongation smoothing options. See notes below for varying this parameter on a per level basis. presmoother : {tuple, string, list} : default ('block_gauss_seidel', {'sweep':'symmetric'}) Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. See notes below for varying this parameter on a per level basis. postsmoother : {tuple, string, list} Same as presmoother, except defines the postsmoother. improve_candidates : {tuple, string, list} : default [('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None] The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. If tuple or string, then this single relaxation descriptor defines improve_candidates on all levels. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : {integer} : default 10 Maximum number of levels to be used in the multilevel solver. max_coarse : {integer} : default 500 Maximum number of variables permitted on the coarse grid. diagonal_dominance : {bool, tuple} : default False If True (or the first tuple entry is True), then avoid coarsening diagonally dominant rows. The second tuple entry requires a dictionary, where the key value 'theta' is used to tune the diagonal dominance threshold. keep : {bool} : default False Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), aggregation (AggOp), and arrays storing the C-points (Cpts) and F-points (Fpts) are kept at each level. Other Parameters ---------------- cycle_type : ['V','W','F'] Structrure of multigrid cycle coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. setup_complexity : bool For a detailed, more accurate setup complexity, pass in 'setup_complexity' = True. This will slow down performance, but increase accuracy of complexity count. Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, aggregation.smoothed_aggregation_solver, classical.ruge_stuben_solver Notes ----- - Root-node style SA differs from classical SA primarily by preserving and identity block in the interpolation operator, P. Each aggregate has a "root-node" or "center-node" associated with it, and this root-node is injected from the coarse grid to the fine grid. The injection corresponds to the identity block. - Only smooth={'energy', None} is supported for prolongation smoothing. See reference [2] below for more details on why the 'energy' prolongation smoother is the natural counterpart to root-node style SA. - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - At each level, four steps are executed in order to define the coarser level operator. 1. Matrix A is given and used to derive a strength matrix, C. 2. Based on the strength matrix, indices are grouped or aggregated. 3. The aggregates define coarse nodes and a tentative prolongation operator T is defined by injection 4. The tentative prolongation operator is smoothed by a relaxation scheme to improve the quality and extent of interpolation from the aggregates to fine nodes. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the i-th entry defines the method at the i-th level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Because this is a root-nodes solver, if a member of the predefined aggregation list is predefined, it must be of the form ('predefined', {'AggOp' : Agg, 'Cnodes' : Cnodes}). Examples -------- >>> from pyamg import rootnode_solver >>> from pyamg.gallery import poisson >>> from scipy.sparse.linalg import cg >>> import numpy as np >>> A = poisson((100, 100), format='csr') # matrix >>> b = np.ones((A.shape[0])) # RHS >>> ml = rootnode_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x, info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1] Vanek, P. and Mandel, J. and Brezina, M., "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", Computing, vol. 56, no. 3, pp. 179--196, 1996. http://citeseer.ist.psu.edu/vanek96algebraic.html .. [2] Olson, L. and Schroder, J. and Tuminaro, R., "A general interpolation strategy for algebraic multigrid using energy minimization", SIAM Journal on Scientific Computing (SISC), vol. 33, pp. 966--991, 2011. """ if ('setup_complexity' in kwargs): if kwargs['setup_complexity'] == True: mat_mat_complexity.__detailed__ = True del kwargs['setup_complexity'] if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except: raise TypeError('Argument A must have type csr_matrix, \ bsr_matrix, or be convertible to csr_matrix') A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and \ (symmetry != 'nonsymmetric'): raise ValueError('expected \'symmetric\', \'nonsymmetric\' \ or \'hermitian\' for the symmetry parameter ') A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Right near nullspace candidates use constant for each variable as default if B is None: B = np.kron(np.ones((int(A.shape[0]/blocksize(A)), 1), dtype=A.dtype), np.eye(blocksize(A))) else: B = np.asarray(B, dtype=A.dtype) if len(B.shape) == 1: B = B.reshape(-1, 1) if B.shape[0] != A.shape[0]: raise ValueError('The near null-space modes B have incorrect \ dimensions for matrix A') if B.shape[1] < blocksize(A): raise ValueError('B.shape[1] must be >= the blocksize of A') # Left near nullspace candidates if A.symmetry == 'nonsymmetric': if BH is None: BH = B.copy() else: BH = np.asarray(BH, dtype=A.dtype) if len(BH.shape) == 1: BH = BH.reshape(-1, 1) if BH.shape[1] != B.shape[1]: raise ValueError('The number of left and right near \ null-space modes B and BH, must be equal') if BH.shape[0] != A.shape[0]: raise ValueError('The near null-space modes BH have \ incorrect dimensions for matrix A') # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates =\ levelize_smooth_or_improve_candidates(improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Construct multilevel structure levels = [] levels.append(multilevel_solver.level()) levels[-1].A = A # matrix # Append near nullspace candidates levels[-1].B = B # right candidates if A.symmetry == 'nonsymmetric': levels[-1].BH = BH # left candidates while len(levels) < max_levels and \ int(levels[-1].A.shape[0]/blocksize(levels[-1].A)) > max_coarse: extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, diagonal_dominance, keep) # Construct and return multilevel hierarchy ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def rootnode_solver(A, B=None, BH=None, symmetry='hermitian', strength='symmetric', aggregate='standard', smooth='energy', presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), improve_candidates=('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), max_levels=10, max_coarse=10, diagonal_dominance=False, keep=False, **kwargs): """Create a multilevel solver using root-node based Smoothed Aggregation (SA). See the notes below, for the major differences with the classical-style smoothed aggregation solver in aggregation.smoothed_aggregation_solver. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix in CSR or BSR format B : None, array_like Right near-nullspace candidates stored in the columns of an NxK array. K must be >= the blocksize of A (see reference [2011OlScTu]_). The default value B=None is equivalent to choosing the constant over each block-variable, B=np.kron(np.ones((A.shape[0]/blocksize(A), 1)), np.eye(blocksize(A))) BH : None, array_like Left near-nullspace candidates stored in the columns of an NxK array. BH is only used if symmetry is 'nonsymmetric'. K must be >= the blocksize of A (see reference [2011OlScTu]_). The default value B=None is equivalent to choosing the constant over each block-variable, B=np.kron(np.ones((A.shape[0]/blocksize(A), 1)), np.eye(blocksize(A))) symmetry : string 'symmetric' refers to both real and complex symmetric 'hermitian' refers to both complex Hermitian and real Hermitian 'nonsymmetric' i.e. nonsymmetric in a hermitian sense Note that for the strictly real case, symmetric and hermitian are the same Note that this flag does not denote definiteness of the operator. strength : list Method used to determine the strength of connection between unknowns of the linear system. Method-specific parameters may be passed in using a tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None, all nonzero entries of the matrix are considered strong. aggregate : list Method used to aggregate nodes. smooth : list Method used to smooth the tentative prolongator. Method-specific parameters may be passed in using a tuple, e.g. smooth= ('energy',{'krylov' : 'gmres'}). Only 'energy' and None are valid prolongation smoothing options. presmoother : tuple, string, list Defines the presmoother for the multilevel cycling. The default block Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix is CSR or is a BSR matrix with blocksize of 1. See notes below for varying this parameter on a per level basis. postsmoother : tuple, string, list Same as presmoother, except defines the postsmoother. improve_candidates : tuple, string, list The ith entry defines the method used to improve the candidates B on level i. If the list is shorter than max_levels, then the last entry will define the method for all levels lower. If tuple or string, then this single relaxation descriptor defines improve_candidates on all levels. The list elements are relaxation descriptors of the form used for presmoother and postsmoother. A value of None implies no action on B. max_levels : integer Maximum number of levels to be used in the multilevel solver. max_coarse : integer Maximum number of variables permitted on the coarse grid. diagonal_dominance : bool, tuple If True (or the first tuple entry is True), then avoid coarsening diagonally dominant rows. The second tuple entry requires a dictionary, where the key value 'theta' is used to tune the diagonal dominance threshold. keep : bool Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C), tentative prolongation (T), aggregation (AggOp), and arrays storing the C-points (Cpts) and F-points (Fpts) are kept at each level. Other Parameters ---------------- cycle_type : ['V','W','F'] Structrure of multigrid cycle coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ] Solver used at the coarsest level of the MG hierarchy. Optionally, may be a tuple (fn, args), where fn is a string such as ['splu', 'lu', ...] or a callable function, and args is a dictionary of arguments to be passed to fn. Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators See Also -------- multilevel_solver, aggregation.smoothed_aggregation_solver, classical.ruge_stuben_solver Notes ----- - Root-node style SA differs from classical SA primarily by preserving and identity block in the interpolation operator, P. Each aggregate has a "root-node" or "center-node" associated with it, and this root-node is injected from the coarse grid to the fine grid. The injection corresponds to the identity block. - Only smooth={'energy', None} is supported for prolongation smoothing. See reference [2011OlScTu]_ below for more details on why the 'energy' prolongation smoother is the natural counterpart to root-node style SA. - The additional parameters are passed through as arguments to multilevel_solver. Refer to pyamg.multilevel_solver for additional documentation. - At each level, four steps are executed in order to define the coarser level operator. 1. Matrix A is given and used to derive a strength matrix, C. 2. Based on the strength matrix, indices are grouped or aggregated. 3. The aggregates define coarse nodes and a tentative prolongation operator T is defined by injection 4. The tentative prolongation operator is smoothed by a relaxation scheme to improve the quality and extent of interpolation from the aggregates to fine nodes. - The parameters smooth, strength, aggregate, presmoother, postsmoother can be varied on a per level basis. For different methods on different levels, use a list as input so that the i-th entry defines the method at the i-th level. If there are more levels in the hierarchy than list entries, the last entry will define the method for all levels lower. Examples are: smooth=[('jacobi', {'omega':1.0}), None, 'jacobi'] presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor'] aggregate=['standard', 'naive'] strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})] - Predefined strength of connection and aggregation schemes can be specified. These options are best used together, but aggregation can be predefined while strength of connection is not. For predefined strength of connection, use a list consisting of tuples of the form ('predefined', {'C' : C0}), where C0 is a csr_matrix and each degree-of-freedom in C0 represents a supernode. For instance to predefine a three-level hierarchy, use [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ]. Similarly for predefined aggregation, use a list of tuples. For instance to predefine a three-level hierarchy, use [('predefined', {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] == A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a csr_matrix. Because this is a root-nodes solver, if a member of the predefined aggregation list is predefined, it must be of the form ('predefined', {'AggOp' : Agg, 'Cnodes' : Cnodes}). Examples -------- >>> from pyamg import rootnode_solver >>> from pyamg.gallery import poisson >>> from scipy.sparse.linalg import cg >>> import numpy as np >>> A = poisson((100, 100), format='csr') # matrix >>> b = np.ones((A.shape[0])) # RHS >>> ml = rootnode_solver(A) # AMG solver >>> M = ml.aspreconditioner(cycle='V') # preconditioner >>> x, info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG References ---------- .. [1996VaMa] Vanek, P. and Mandel, J. and Brezina, M., "Algebraic Multigrid by Smoothed Aggregation for Second and Fourth Order Elliptic Problems", Computing, vol. 56, no. 3, pp. 179--196, 1996. http://citeseer.ist.psu.edu/vanek96algebraic.html .. [2011OlScTu] Olson, L. and Schroder, J. and Tuminaro, R., "A general interpolation strategy for algebraic multigrid using energy minimization", SIAM Journal on Scientific Computing (SISC), vol. 33, pp. 966--991, 2011. """ if not (isspmatrix_csr(A) or isspmatrix_bsr(A)): try: A = csr_matrix(A) warn("Implicit conversion of A to CSR", SparseEfficiencyWarning) except BaseException: raise TypeError('Argument A must have type csr_matrix, \ bsr_matrix, or be convertible to csr_matrix') A = A.asfptype() if (symmetry != 'symmetric') and (symmetry != 'hermitian') and \ (symmetry != 'nonsymmetric'): raise ValueError('expected \'symmetric\', \'nonsymmetric\' \ or \'hermitian\' for the symmetry parameter ') A.symmetry = symmetry if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') # Right near nullspace candidates use constant for each variable as default if B is None: B = np.kron(np.ones((int(A.shape[0]/blocksize(A)), 1), dtype=A.dtype), np.eye(blocksize(A))) else: B = np.asarray(B, dtype=A.dtype) if len(B.shape) == 1: B = B.reshape(-1, 1) if B.shape[0] != A.shape[0]: raise ValueError('The near null-space modes B have incorrect \ dimensions for matrix A') if B.shape[1] < blocksize(A): raise ValueError('B.shape[1] must be >= the blocksize of A') # Left near nullspace candidates if A.symmetry == 'nonsymmetric': if BH is None: BH = B.copy() else: BH = np.asarray(BH, dtype=A.dtype) if len(BH.shape) == 1: BH = BH.reshape(-1, 1) if BH.shape[1] != B.shape[1]: raise ValueError('The number of left and right near \ null-space modes B and BH, must be equal') if BH.shape[0] != A.shape[0]: raise ValueError('The near null-space modes BH have \ incorrect dimensions for matrix A') # Levelize the user parameters, so that they become lists describing the # desired user option on each level. max_levels, max_coarse, strength =\ levelize_strength_or_aggregation(strength, max_levels, max_coarse) max_levels, max_coarse, aggregate =\ levelize_strength_or_aggregation(aggregate, max_levels, max_coarse) improve_candidates =\ levelize_smooth_or_improve_candidates(improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) # Construct multilevel structure levels = [] levels.append(multilevel_solver.level()) levels[-1].A = A # matrix # Append near nullspace candidates levels[-1].B = B # right candidates if A.symmetry == 'nonsymmetric': levels[-1].BH = BH # left candidates while len(levels) < max_levels and \ int(levels[-1].A.shape[0]/blocksize(levels[-1].A)) > max_coarse: extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, diagonal_dominance, keep) ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def setup_complexity(sa, strength, smooth, improve_candidates, aggregate, presmoother, postsmoother, keep, max_levels, max_coarse, coarse_solver, symmetry): ''' Given a solver hierarchy, sa, and all of the setup parameters, compute abstractly the "work" required to form the solver hierarchy ''' max_levels, max_coarse, strength = levelize_strength_or_aggregation( strength, max_levels, max_coarse) max_levels, max_coarse, aggregate = levelize_strength_or_aggregation( aggregate, max_levels, max_coarse) improve_candidates = levelize_smooth_or_improve_candidates( improve_candidates, max_levels) smooth = levelize_smooth_or_improve_candidates(smooth, max_levels) work = 0.0 nlevels = len(sa.levels) ## # Convert everything to list if isinstance(presmoother, tuple): presmoother = [presmoother] if isinstance(postsmoother, tuple): postsmoother = [postsmoother] if isinstance(presmoother, str): presmoother = [(presmoother, {})] if isinstance(postsmoother, str): postsmoother = [(postsmoother, {})] ## # Repeat final smoothing strategy till end of hiearchy for i in range(len(presmoother), len(sa.levels)): presmoother.append(presmoother[-1]) for i in range(len(postsmoother), len(sa.levels)): postsmoother.append(postsmoother[-1]) for i, lvl in enumerate(sa.levels): ## # Compute work for smoothing P if i < nlevels - 1: fn, kwargs = unpack_arg(smooth[i]) ## # Account for the mat-mat mult A*P try: ## # This is if you're using energy-min, then # account for the roughly 6 mat-mat additions maxiter = kwargs['maxiter'] work += 6 * lvl.P.nnz * maxiter except: maxiter = 1 work += lvl.A.nnz * (lvl.P.nnz / float(lvl.P.shape[0])) * maxiter ## # Account for constraint enforcement mat-vec operations #work += lvl.P.nnz*lvl.B.shape[1] ## # Compute work for computing SoC if i < nlevels - 1: fn, kwargs = unpack_arg(strength[i]) #work += lvl.A.nnz*(lvl.A.nnz/float(lvl.A.shape[0])) ## # Compute the work for kwargs['k'] > 2 # (nnz to compute) * (average stencil size in matrix that you're multiplying) if fn == 'evolution': work += lvl.A.nnz * ((lvl.A**(int(kwargs['k'] / 2))).nnz / float(lvl.A.shape[0])) ## # Compute work for computing RAP if i < nlevels - 1: work += lvl.A.nnz * (lvl.P.nnz / float(lvl.P.shape[0])) * 2 ## # Compute work for any Schwarz relaxation if i < nlevels - 1: fn1, kwargs1 = unpack_arg(presmoother[i]) fn2, kwargs2 = unpack_arg(postsmoother[i]) if (fn1 == 'schwarz') or (fn2 == 'schwarz'): S = lvl.A if (fn1 == 'strength_based_schwarz') or ( fn2 == 'strength_based_schwarz'): S = lvl.C ## if ((fn1.find('schwarz') > 0) or (fn2.find('schwarz') > 0)): rowlen = S.indptr[1:] - S.indptr[:-1] work += sum(rowlen**3) ## # Compute work for smoothing B if i < nlevels - 1: fn, kwargs = unpack_arg(improve_candidates[i]) if fn is not None: ## # Compute cost multiplier for relaxation method cost_factor = 1 if fn.endswith(('nr', 'ne')): cost_factor *= 2 if kwargs.has_key('sweep'): if kwargs['sweep'] == 'symmetric': cost_factor *= 2 if kwargs.has_key('iterations'): cost_factor *= kwargs['iterations'] if kwargs.has_key('degree'): cost_factor *= kwargs['degree'] work += cost_factor * lvl.A.nnz * lvl.B.shape[1] return work / float(sa.levels[0].A.nnz)