idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
20,300
def _GetUsers ( self , key_path_suffix ) : user_key_name , _ , key_path_suffix = key_path_suffix . partition ( definitions . KEY_PATH_SEPARATOR ) if user_key_name == '.DEFAULT' : search_key_name = 'S-1-5-18' else : search_key_name = user_key_name user_profile_list_key = self . GetKeyByPath ( self . _USER_PROFILE_LIST_K...
Virtual key callback to determine the users sub keys .
20,301
def _GetFileByPath ( self , key_path_upper ) : key_path_prefix , registry_file = self . _GetCachedFileByPath ( key_path_upper ) if not registry_file : for mapping in self . _GetFileMappingsByPath ( key_path_upper ) : try : registry_file = self . _OpenFile ( mapping . windows_path ) except IOError : registry_file = None...
Retrieves a Windows Registry file for a specific path .
20,302
def _GetFileMappingsByPath ( self , key_path_upper ) : candidate_mappings = [ ] for mapping in self . _REGISTRY_FILE_MAPPINGS_NT : if key_path_upper . startswith ( mapping . key_path_prefix . upper ( ) ) : candidate_mappings . append ( mapping ) candidate_mappings . sort ( key = lambda mapping : len ( mapping . key_pat...
Retrieves the Windows Registry file mappings for a specific path .
20,303
def _OpenFile ( self , path ) : if not self . _registry_file_reader : return None return self . _registry_file_reader . Open ( path , ascii_codepage = self . _ascii_codepage )
Opens a Windows Registry file .
20,304
def GetRegistryFileMapping ( self , registry_file ) : if not registry_file : return '' candidate_mappings = [ ] for mapping in self . _REGISTRY_FILE_MAPPINGS_NT : if not mapping . unique_key_paths : continue match = True for key_path in mapping . unique_key_paths : registry_key = registry_file . GetKeyByPath ( key_path...
Determines the Registry file mapping based on the content of the file .
20,305
def GetRootKey ( self ) : root_registry_key = virtual . VirtualWinRegistryKey ( '' ) for mapped_key in self . _MAPPED_KEYS : key_path_segments = key_paths . SplitKeyPath ( mapped_key ) if not key_path_segments : continue registry_key = root_registry_key for name in key_path_segments [ : - 1 ] : sub_registry_key = regis...
Retrieves the Windows Registry root key .
20,306
def MapFile ( self , key_path_prefix , registry_file ) : self . _registry_files [ key_path_prefix . upper ( ) ] = registry_file registry_file . SetKeyPathPrefix ( key_path_prefix )
Maps the Windows Registry file to a specific key path prefix .
20,307
def GetRootKey ( self ) : regf_key = self . _regf_file . get_root_key ( ) if not regf_key : return None return REGFWinRegistryKey ( regf_key , key_path = self . _key_path_prefix )
Retrieves the root key .
20,308
def Open ( self , file_object ) : self . _file_object = file_object self . _regf_file . open_file_object ( self . _file_object ) return True
Opens the Windows Registry file using a file - like object .
20,309
def SplitKeyPath ( key_path , path_separator = definitions . KEY_PATH_SEPARATOR ) : return list ( filter ( None , key_path . split ( path_separator ) ) )
Splits the key path into path segments .
20,310
def _GetKeyFromRegistry ( self ) : if not self . _registry : return try : self . _registry_key = self . _registry . GetKeyByPath ( self . _key_path ) except RuntimeError : pass if not self . _registry_key : return for sub_registry_key in self . _registry_key . GetSubkeys ( ) : self . AddSubkey ( sub_registry_key ) if s...
Determines the key from the Windows Registry .
20,311
def GetValues ( self ) : if not self . _registry_key and self . _registry : self . _GetKeyFromRegistry ( ) if self . _registry_key : return self . _registry_key . GetValues ( ) return iter ( [ ] )
Retrieves all values within the key .
20,312
def perform ( self ) : payload_class_str = self . _payload [ "class" ] payload_class = self . safe_str_to_class ( payload_class_str ) payload_class . resq = self . resq args = self . _payload . get ( "args" ) metadata = dict ( args = args ) if self . enqueue_timestamp : metadata [ "enqueue_timestamp" ] = self . enqueue...
This method converts payload into args and calls the perform method on the payload class .
20,313
def fail ( self , exception ) : fail = failure . create ( exception , self . _queue , self . _payload , self . _worker ) fail . save ( self . resq ) return fail
This method provides a way to fail a job and will use whatever failure backend you ve provided . The default is the RedisBackend .
20,314
def retry ( self , payload_class , args ) : retry_every = getattr ( payload_class , 'retry_every' , None ) retry_timeout = getattr ( payload_class , 'retry_timeout' , 0 ) if retry_every : now = ResQ . _current_time ( ) first_attempt = self . _payload . get ( "first_attempt" , now ) retry_until = first_attempt + timedel...
This method provides a way to retry a job after a failure . If the jobclass defined by the payload containes a retry_every attribute then pyres will attempt to retry the job until successful or until timeout defined by retry_timeout on the payload class .
20,315
def reserve ( cls , queues , res , worker = None , timeout = 10 ) : if isinstance ( queues , string_types ) : queues = [ queues ] queue , payload = res . pop ( queues , timeout = timeout ) if payload : return cls ( queue , payload , res , worker )
Reserve a job on one of the queues . This marks this job so that other workers will not pick it up .
20,316
def my_import ( name ) : mod = __import__ ( name ) components = name . split ( '.' ) for comp in components [ 1 : ] : mod = getattr ( mod , comp ) return mod
Helper function for walking import calls when searching for classes by string names .
20,317
def safe_str_to_class ( s ) : lst = s . split ( "." ) klass = lst [ - 1 ] mod_list = lst [ : - 1 ] module = "." . join ( mod_list ) if not module : module = klass mod = my_import ( module ) if hasattr ( mod , klass ) : return getattr ( mod , klass ) else : raise ImportError ( '' )
Helper function to map string class names to module classes .
20,318
def str_to_class ( s ) : lst = s . split ( "." ) klass = lst [ - 1 ] mod_list = lst [ : - 1 ] module = "." . join ( mod_list ) try : mod = __import__ ( module ) if hasattr ( mod , klass ) : return getattr ( mod , klass ) else : return None except ImportError : return None
Alternate helper function to map string class names to module classes .
20,319
def info ( self ) : pending = 0 for q in self . queues ( ) : pending += self . size ( q ) return { 'pending' : pending , 'processed' : Stat ( 'processed' , self ) . get ( ) , 'queues' : len ( self . queues ( ) ) , 'workers' : len ( self . workers ( ) ) , 'failed' : Stat ( 'failed' , self ) . get ( ) , 'servers' : [ '%s...
Returns a dictionary of the current status of the pending jobs processed no . of queues no . of workers no . of failed jobs .
20,320
def _shutdown_minions ( self ) : setproctitle ( 'pyres_manager: Waiting on children to shutdown.' ) for minion in self . _workers . values ( ) : minion . terminate ( ) minion . join ( )
send the SIGNINT signal to each worker in the pool .
20,321
def work ( self , interval = 5 ) : self . _setproctitle ( "Starting" ) logger . info ( "starting" ) self . startup ( ) while True : if self . _shutdown : logger . info ( 'shutdown scheduled' ) break self . register_worker ( ) job = self . reserve ( interval ) if job : self . fork_worker ( job ) else : if interval == 0 ...
Invoked by run method . work listens on a list of queues and sleeps for interval time .
20,322
def fork_worker ( self , job ) : logger . debug ( 'picked up job' ) logger . debug ( 'job details: %s' % job ) self . before_fork ( job ) self . child = os . fork ( ) if self . child : self . _setproctitle ( "Forked %s at %s" % ( self . child , datetime . datetime . now ( ) ) ) logger . info ( 'Forked %s at %s' % ( sel...
Invoked by work method . fork_worker does the actual forking to create the child process that will process the job . It s also responsible for monitoring the child process and handling hangs and crashes .
20,323
def save ( self , resq = None ) : if not resq : resq = ResQ ( ) data = { 'failed_at' : datetime . datetime . now ( ) . strftime ( '%Y/%m/%d %H:%M:%S' ) , 'payload' : self . _payload , 'exception' : self . _exception . __class__ . __name__ , 'error' : self . _parse_message ( self . _exception ) , 'backtrace' : self . _p...
Saves the failed Job into a failed Redis queue preserving all its original enqueud info .
20,324
def make_csr ( A ) : if not ( isspmatrix_csr ( A ) or isspmatrix_bsr ( A ) ) : try : A = csr_matrix ( A ) print ( 'Implicit conversion of A to CSR in pyamg.blackbox.make_csr' ) except BaseException : raise TypeError ( 'Argument A must have type csr_matrix or\ bsr_matrix, or be convertible to csr_matr...
Convert A to CSR if A is not a CSR or BSR matrix already .
20,325
def solver ( A , config ) : A = make_csr ( A ) try : return smoothed_aggregation_solver ( A , B = config [ 'B' ] , BH = config [ 'BH' ] , smooth = config [ 'smooth' ] , strength = config [ 'strength' ] , max_levels = config [ 'max_levels' ] , max_coarse = config [ 'max_coarse' ] , coarse_solver = config [ 'coarse_solve...
Generate an SA solver given matrix A and a configuration .
20,326
def solve ( A , b , x0 = None , tol = 1e-5 , maxiter = 400 , return_solver = False , existing_solver = None , verb = True , residuals = None ) : A = make_csr ( A ) if existing_solver is None : config = solver_configuration ( A , B = None , verb = verb ) existing_solver = solver ( A , config ) else : if existing_solver ...
Solve Ax = b .
20,327
def find_comments ( fname , ch ) : with open ( fname , 'r' ) as inf : fdata = inf . readlines ( ) comments = { } for f in ch . functions : lineno = f [ 'line_number' ] - 1 lineptr = lineno - 1 if f [ 'template' ] : lineptr -= 1 start = lineptr while fdata [ lineptr ] . startswith ( '//' ) or fdata [ lineptr ] . startsw...
Find the comments for a function .
20,328
def fit_candidates ( AggOp , B , tol = 1e-10 ) : if not isspmatrix_csr ( AggOp ) : raise TypeError ( 'expected csr_matrix for argument AggOp' ) B = np . asarray ( B ) if B . dtype not in [ 'float32' , 'float64' , 'complex64' , 'complex128' ] : B = np . asarray ( B , dtype = 'float64' ) if len ( B . shape ) != 2 : raise...
Fit near - nullspace candidates to form the tentative prolongator .
20,329
def _rand_sparse ( m , n , density , format = 'csr' ) : nnz = max ( min ( int ( m * n * density ) , m * n ) , 0 ) row = np . random . randint ( low = 0 , high = m - 1 , size = nnz ) col = np . random . randint ( low = 0 , high = n - 1 , size = nnz ) data = np . ones ( nnz , dtype = float ) return sp . sparse . csr_matr...
Construct base function for sprand sprandn .
20,330
def sprand ( m , n , density , format = 'csr' ) : m , n = int ( m ) , int ( n ) A = _rand_sparse ( m , n , density , format = 'csr' ) A . data = sp . rand ( A . nnz ) return A . asformat ( format )
Return a random sparse matrix .
20,331
def linear_elasticity ( grid , spacing = None , E = 1e5 , nu = 0.3 , format = None ) : if len ( grid ) == 2 : return q12d ( grid , spacing = spacing , E = E , nu = nu , format = format ) else : raise NotImplemented ( 'no support for grid=%s' % str ( grid ) )
Linear elasticity problem discretizes with Q1 finite elements on a regular rectangular grid .
20,332
def q12d_local ( vertices , lame , mu ) : M = lame + 2 * mu R_11 = np . matrix ( [ [ 2 , - 2 , - 1 , 1 ] , [ - 2 , 2 , 1 , - 1 ] , [ - 1 , 1 , 2 , - 2 ] , [ 1 , - 1 , - 2 , 2 ] ] ) / 6.0 R_12 = np . matrix ( [ [ 1 , 1 , - 1 , - 1 ] , [ - 1 , - 1 , 1 , 1 ] , [ - 1 , - 1 , 1 , 1 ] , [ 1 , 1 , - 1 , - 1 ] ] ) / 4.0 R_22 =...
Local stiffness matrix for two dimensional elasticity on a square element .
20,333
def p12d_local ( vertices , lame , mu ) : assert ( vertices . shape == ( 3 , 2 ) ) A = np . vstack ( ( np . ones ( ( 1 , 3 ) ) , vertices . T ) ) PhiGrad = inv ( A ) [ : , 1 : ] R = np . zeros ( ( 3 , 6 ) ) R [ [ [ 0 ] , [ 2 ] ] , [ 0 , 2 , 4 ] ] = PhiGrad . T R [ [ [ 2 ] , [ 1 ] ] , [ 1 , 3 , 5 ] ] = PhiGrad . T C = m...
Local stiffness matrix for P1 elements in 2d .
20,334
def write_basic_mesh ( Verts , E2V = None , mesh_type = 'tri' , pdata = None , pvdata = None , cdata = None , cvdata = None , fname = 'output.vtk' ) : if E2V is None : mesh_type = 'vertex' map_type_to_key = { 'vertex' : 1 , 'tri' : 5 , 'quad' : 9 , 'tet' : 10 , 'hex' : 12 } if mesh_type not in map_type_to_key : raise V...
Write mesh file for basic types of elements .
20,335
def set_attributes ( d , elm ) : for key in d : elm . setAttribute ( key , d [ key ] )
Set attributes from dictionary of values .
20,336
def eliminate_local_candidates ( x , AggOp , A , T , Ca = 1.0 , ** kwargs ) : if not ( isspmatrix_csr ( AggOp ) or isspmatrix_csc ( AggOp ) ) : raise TypeError ( 'AggOp must be a CSR or CSC matrix' ) else : AggOp = AggOp . tocsc ( ) ndof = max ( x . shape ) nPDEs = int ( ndof / AggOp . shape [ 0 ] ) def aggregate_wise_...
Eliminate canidates locally .
20,337
def poisson ( grid , spacing = None , dtype = float , format = None , type = 'FD' ) : grid = tuple ( grid ) N = len ( grid ) if N < 1 or min ( grid ) < 1 : raise ValueError ( 'invalid grid shape: %s' % str ( grid ) ) if type == 'FD' : stencil = np . zeros ( ( 3 , ) * N , dtype = dtype ) for i in range ( N ) : stencil [...
Return a sparse matrix for the N - dimensional Poisson problem .
20,338
def norm ( x , pnorm = '2' ) : x = np . ravel ( x ) if pnorm == '2' : return np . sqrt ( np . inner ( x . conj ( ) , x ) . real ) elif pnorm == 'inf' : return np . max ( np . abs ( x ) ) else : raise ValueError ( 'Only the 2-norm and infinity-norm are supported' )
2 - norm of a vector .
20,339
def approximate_spectral_radius ( A , tol = 0.01 , maxiter = 15 , restart = 5 , symmetric = None , initial_guess = None , return_vector = False ) : if not hasattr ( A , 'rho' ) or return_vector : symmetric = False if maxiter < 1 : raise ValueError ( 'expected maxiter > 0' ) if restart < 0 : raise ValueError ( 'expected...
Approximate the spectral radius of a matrix .
20,340
def condest ( A , tol = 0.1 , maxiter = 25 , symmetric = False ) : r [ evect , ev , H , V , breakdown_flag ] = _approximate_eigenvalues ( A , tol , maxiter , symmetric ) return np . max ( [ norm ( x ) for x in ev ] ) / min ( [ norm ( x ) for x in ev ] )
r Estimates the condition number of A .
20,341
def cond ( A ) : if A . shape [ 0 ] != A . shape [ 1 ] : raise ValueError ( 'expected square matrix' ) if sparse . isspmatrix ( A ) : A = A . todense ( ) from scipy . linalg import svd U , Sigma , Vh = svd ( A ) return np . max ( Sigma ) / min ( Sigma )
Return condition number of A .
20,342
def ishermitian ( A , fast_check = True , tol = 1e-6 , verbose = False ) : r if not sparse . isspmatrix ( A ) : A = np . asmatrix ( A ) if fast_check : x = sp . rand ( A . shape [ 0 ] , 1 ) y = sp . rand ( A . shape [ 0 ] , 1 ) if A . dtype == complex : x = x + 1.0j * sp . rand ( A . shape [ 0 ] , 1 ) y = y + 1.0j * sp...
r Return True if A is Hermitian to within tol .
20,343
def pinv_array ( a , cond = None ) : n = a . shape [ 0 ] m = a . shape [ 1 ] if m == 1 : zero_entries = ( a == 0.0 ) . nonzero ( ) [ 0 ] a [ zero_entries ] = 1.0 a [ : ] = 1.0 / a a [ zero_entries ] = 0.0 del zero_entries else : gelss , gelss_lwork = get_lapack_funcs ( ( 'gelss' , 'gelss_lwork' ) , ( np . ones ( ( 1 , ...
Calculate the Moore - Penrose pseudo inverse of each block of the three dimensional array a .
20,344
def distance_strength_of_connection ( A , V , theta = 2.0 , relative_drop = True ) : if sparse . isspmatrix_bsr ( A ) : sn = int ( A . shape [ 0 ] / A . blocksize [ 0 ] ) u = np . ones ( ( A . data . shape [ 0 ] , ) ) A = sparse . csr_matrix ( ( u , A . indices , A . indptr ) , shape = ( sn , sn ) ) if not sparse . iss...
Distance based strength - of - connection .
20,345
def classical_strength_of_connection ( A , theta = 0.0 , norm = 'abs' ) : if sparse . isspmatrix_bsr ( A ) : blocksize = A . blocksize [ 0 ] else : blocksize = 1 if not sparse . isspmatrix_csr ( A ) : warn ( "Implicit conversion of A to csr" , sparse . SparseEfficiencyWarning ) A = sparse . csr_matrix ( A ) if ( theta ...
Classical Strength Measure .
20,346
def symmetric_strength_of_connection ( A , theta = 0 ) : if theta < 0 : raise ValueError ( 'expected a positive theta' ) if sparse . isspmatrix_csr ( A ) : Sp = np . empty_like ( A . indptr ) Sj = np . empty_like ( A . indices ) Sx = np . empty_like ( A . data ) fn = amg_core . symmetric_strength_of_connection fn ( A ....
Symmetric Strength Measure .
20,347
def relaxation_vectors ( A , R , k , alpha ) : n = A . shape [ 0 ] x = np . random . rand ( n * R ) - 0.5 x = np . reshape ( x , ( n , R ) , order = 'F' ) b = np . zeros ( ( n , 1 ) ) for r in range ( 0 , R ) : jacobi ( A , x [ : , r ] , b , iterations = k , omega = alpha ) return x
Generate test vectors by relaxing on Ax = 0 for some random vectors x .
20,348
def affinity_distance ( A , alpha = 0.5 , R = 5 , k = 20 , epsilon = 4.0 ) : if not sparse . isspmatrix_csr ( A ) : A = sparse . csr_matrix ( A ) if alpha < 0 : raise ValueError ( 'expected alpha>0' ) if R <= 0 or not isinstance ( R , int ) : raise ValueError ( 'expected integer R>0' ) if k <= 0 or not isinstance ( k ,...
Affinity Distance Strength Measure .
20,349
def algebraic_distance ( A , alpha = 0.5 , R = 5 , k = 20 , epsilon = 2.0 , p = 2 ) : if not sparse . isspmatrix_csr ( A ) : A = sparse . csr_matrix ( A ) if alpha < 0 : raise ValueError ( 'expected alpha>0' ) if R <= 0 or not isinstance ( R , int ) : raise ValueError ( 'expected integer R>0' ) if k <= 0 or not isinsta...
Algebraic Distance Strength Measure .
20,350
def distance_measure_common ( A , func , alpha , R , k , epsilon ) : x = relaxation_vectors ( A , R , k , alpha ) d = func ( x ) ( rows , cols ) = A . nonzero ( ) weak = np . where ( rows == cols ) [ 0 ] d [ weak ] = 0 C = sparse . csr_matrix ( ( d , ( rows , cols ) ) , shape = A . shape ) C . eliminate_zeros ( ) amg_c...
Create strength of connection matrixfrom a function applied to relaxation vectors .
20,351
def jacobi_prolongation_smoother ( S , T , C , B , omega = 4.0 / 3.0 , degree = 1 , filter = False , weighting = 'diagonal' ) : if weighting == 'block' : if sparse . isspmatrix_csr ( S ) : weighting = 'diagonal' elif sparse . isspmatrix_bsr ( S ) : if S . blocksize [ 0 ] == 1 : weighting = 'diagonal' if filter : if spa...
Jacobi prolongation smoother .
20,352
def richardson_prolongation_smoother ( S , T , omega = 4.0 / 3.0 , degree = 1 ) : weight = omega / approximate_spectral_radius ( S ) P = T for i in range ( degree ) : P = P - weight * ( S * P ) return P
Richardson prolongation smoother .
20,353
def matrix_asformat ( lvl , name , format , blocksize = None ) : desired_matrix = name + format M = getattr ( lvl , name ) if format == 'bsr' : desired_matrix += str ( blocksize [ 0 ] ) + str ( blocksize [ 1 ] ) if hasattr ( lvl , desired_matrix ) : pass elif M . format == format and format != 'bsr' : setattr ( lvl , d...
Set a matrix to a specific format .
20,354
def regular_triangle_mesh ( nx , ny ) : nx , ny = int ( nx ) , int ( ny ) if nx < 2 or ny < 2 : raise ValueError ( 'minimum mesh dimension is 2: %s' % ( ( nx , ny ) , ) ) Vert1 = np . tile ( np . arange ( 0 , nx - 1 ) , ny - 1 ) + np . repeat ( np . arange ( 0 , nx * ( ny - 1 ) , nx ) , nx - 1 ) Vert3 = np . tile ( np ...
Construct a regular triangular mesh in the unit square .
20,355
def check_input ( Verts = None , E2V = None , Agg = None , A = None , splitting = None , mesh_type = None ) : if Verts is not None : if not np . issubdtype ( Verts . dtype , np . floating ) : raise ValueError ( 'Verts should be of type float' ) if E2V is not None : if not np . issubdtype ( E2V . dtype , np . integer ) ...
Check input for local functions .
20,356
def MIS ( G , weights , maxiter = None ) : if not isspmatrix_csr ( G ) : raise TypeError ( 'expected csr_matrix' ) G = remove_diagonal ( G ) mis = np . empty ( G . shape [ 0 ] , dtype = 'intc' ) mis [ : ] = - 1 fn = amg_core . maximal_independent_set_parallel if maxiter is None : fn ( G . shape [ 0 ] , G . indptr , G ....
Compute a maximal independent set of a graph in parallel .
20,357
def preprocess ( S , coloring_method = None ) : if not isspmatrix_csr ( S ) : raise TypeError ( 'expected csr_matrix' ) if S . shape [ 0 ] != S . shape [ 1 ] : raise ValueError ( 'expected square matrix, shape=%s' % ( S . shape , ) ) N = S . shape [ 0 ] S = csr_matrix ( ( np . ones ( S . nnz , dtype = 'int8' ) , S . in...
Preprocess splitting functions .
20,358
def load_example ( name ) : if name not in example_names : raise ValueError ( 'no example with name (%s)' % name ) else : return loadmat ( os . path . join ( example_dir , name + '.mat' ) , struct_as_record = True )
Load an example problem by name .
20,359
def stencil_grid ( S , grid , dtype = None , format = None ) : S = np . asarray ( S , dtype = dtype ) grid = tuple ( grid ) if not ( np . asarray ( S . shape ) % 2 == 1 ) . all ( ) : raise ValueError ( 'all stencil dimensions must be odd' ) if len ( grid ) != np . ndim ( S ) : raise ValueError ( 'stencil dimension must...
Construct a sparse matrix form a local matrix stencil .
20,360
def _CRsweep ( A , B , Findex , Cindex , nu , thetacr , method ) : n = A . shape [ 0 ] numax = nu z = np . zeros ( ( n , ) ) e = deepcopy ( B [ : , 0 ] ) e [ Cindex ] = 0.0 enorm = norm ( e ) rhok = 1 it = 0 while True : if method == 'habituated' : gauss_seidel ( A , e , z , iterations = 1 ) e [ Cindex ] = 0.0 elif met...
Perform CR sweeps on a target vector .
20,361
def binormalize ( A , tol = 1e-5 , maxiter = 10 ) : if not isspmatrix ( A ) : raise TypeError ( 'expecting sparse matrix A' ) if A . dtype == complex : raise NotImplementedError ( 'complex A not implemented' ) n = A . shape [ 0 ] it = 0 x = np . ones ( ( n , 1 ) ) . ravel ( ) B = A . multiply ( A ) . tocsc ( ) d = B . ...
Binormalize matrix A . Attempt to create unit l_1 norm rows .
20,362
def rowsum_stdev ( x , beta ) : r n = x . size betabar = ( 1.0 / n ) * np . dot ( x , beta ) stdev = np . sqrt ( ( 1.0 / n ) * np . sum ( np . power ( np . multiply ( x , beta ) - betabar , 2 ) ) ) return stdev / betabar
r Compute row sum standard deviation .
20,363
def mls_polynomial_coefficients ( rho , degree ) : roots = rho / 2.0 * ( 1.0 - np . cos ( 2 * np . pi * ( np . arange ( degree , dtype = 'float64' ) + 1 ) / ( 2.0 * degree + 1.0 ) ) ) roots = 1.0 / roots S = np . poly ( roots ) [ : : - 1 ] SSA_max = rho / ( ( 2.0 * degree + 1.0 ) ** 2 ) S_hat = np . polymul ( S , S ) S...
Determine the coefficients for a MLS polynomial smoother .
20,364
def steepest_descent ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : A , M , x , b , postprocess = make_system ( A , M , x0 , b ) import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._steepest_descent' ) if maxiter is None :...
Steepest descent algorithm .
20,365
def demo ( ) : A = poisson ( ( 100 , 100 ) , format = 'csr' ) B = None b = sp . rand ( A . shape [ 0 ] , 1 ) mls = smoothed_aggregation_solver ( A , B = B ) print ( mls ) standalone_residuals = [ ] x = mls . solve ( b , tol = 1e-10 , accel = None , residuals = standalone_residuals ) accelerated_residuals = [ ] x = mls ...
Outline basic demo .
20,366
def lloyd_aggregation ( C , ratio = 0.03 , distance = 'unit' , maxiter = 10 ) : if ratio <= 0 or ratio > 1 : raise ValueError ( 'ratio must be > 0.0 and <= 1.0' ) if not ( isspmatrix_csr ( C ) or isspmatrix_csc ( C ) ) : raise TypeError ( 'expected csr_matrix or csc_matrix' ) if distance == 'unit' : data = np . ones_li...
Aggregate nodes using Lloyd Clustering .
20,367
def cr ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : A , M , x , b , postprocess = make_system ( A , M , x0 , b ) import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._cr' ) if maxiter is None : maxiter = int ( 1.3 * len (...
Conjugate Residual algorithm .
20,368
def BSR_Get_Row ( A , i ) : blocksize = A . blocksize [ 0 ] BlockIndx = int ( i / blocksize ) rowstart = A . indptr [ BlockIndx ] rowend = A . indptr [ BlockIndx + 1 ] localRowIndx = i % blocksize indys = A . data [ rowstart : rowend , localRowIndx , : ] . nonzero ( ) z = A . data [ rowstart : rowend , localRowIndx , :...
Return row i in BSR matrix A .
20,369
def BSR_Row_WriteScalar ( A , i , x ) : blocksize = A . blocksize [ 0 ] BlockIndx = int ( i / blocksize ) rowstart = A . indptr [ BlockIndx ] rowend = A . indptr [ BlockIndx + 1 ] localRowIndx = i % blocksize indys = A . data [ rowstart : rowend , localRowIndx , : ] . nonzero ( ) A . data [ rowstart : rowend , localRow...
Write a scalar at each nonzero location in row i of BSR matrix A .
20,370
def BSR_Row_WriteVect ( A , i , x ) : blocksize = A . blocksize [ 0 ] BlockIndx = int ( i / blocksize ) rowstart = A . indptr [ BlockIndx ] rowend = A . indptr [ BlockIndx + 1 ] localRowIndx = i % blocksize x = x . __array__ ( ) . reshape ( ( max ( x . shape ) , ) ) indys = A . data [ rowstart : rowend , localRowIndx ,...
Overwrite the nonzeros in row i of BSR matrix A with the vector x .
20,371
def direct_interpolation ( A , C , splitting ) : if not isspmatrix_csr ( A ) : raise TypeError ( 'expected csr_matrix for A' ) if not isspmatrix_csr ( C ) : raise TypeError ( 'expected csr_matrix for C' ) C = C . copy ( ) C . data [ : ] = 1.0 C = C . multiply ( A ) Pp = np . empty_like ( A . indptr ) amg_core . rs_dire...
Create prolongator using direct interpolation .
20,372
def apply_givens ( Q , v , k ) : for j in range ( k ) : Qloc = Q [ j ] v [ j : j + 2 ] = np . dot ( Qloc , v [ j : j + 2 ] )
Apply the first k Givens rotations in Q to v .
20,373
def diffusion_stencil_2d ( epsilon = 1.0 , theta = 0.0 , type = 'FE' ) : eps = float ( epsilon ) theta = float ( theta ) C = np . cos ( theta ) S = np . sin ( theta ) CS = C * S CC = C ** 2 SS = S ** 2 if ( type == 'FE' ) : a = ( - 1 * eps - 1 ) * CC + ( - 1 * eps - 1 ) * SS + ( 3 * eps - 3 ) * CS b = ( 2 * eps - 4 ) *...
Rotated Anisotropic diffusion in 2d of the form .
20,374
def _symbolic_rotation_helper ( ) : from sympy import symbols , Matrix cpsi , spsi = symbols ( 'cpsi, spsi' ) cth , sth = symbols ( 'cth, sth' ) cphi , sphi = symbols ( 'cphi, sphi' ) Rpsi = Matrix ( [ [ cpsi , spsi , 0 ] , [ - spsi , cpsi , 0 ] , [ 0 , 0 , 1 ] ] ) Rth = Matrix ( [ [ 1 , 0 , 0 ] , [ 0 , cth , sth ] , [...
Use SymPy to generate the 3D rotation matrix and products for diffusion_stencil_3d .
20,375
def _symbolic_product_helper ( ) : from sympy import symbols , Matrix D11 , D12 , D13 , D21 , D22 , D23 , D31 , D32 , D33 = symbols ( 'D11, D12, D13, D21, D22, D23, D31, D32, D33' ) D = Matrix ( [ [ D11 , D12 , D13 ] , [ D21 , D22 , D23 ] , [ D31 , D32 , D33 ] ] ) grad = Matrix ( [ [ 'dx' , 'dy' , 'dz' ] ] ) . T div = ...
Use SymPy to generate the 3D products for diffusion_stencil_3d .
20,376
def make_system ( A , x , b , formats = None ) : if formats is None : pass elif formats == [ 'csr' ] : if sparse . isspmatrix_csr ( A ) : pass elif sparse . isspmatrix_bsr ( A ) : A = A . tocsr ( ) else : warn ( 'implicit conversion to CSR' , sparse . SparseEfficiencyWarning ) A = sparse . csr_matrix ( A ) else : if sp...
Return A x b suitable for relaxation or raise an exception .
20,377
def sor ( A , x , b , omega , iterations = 1 , sweep = 'forward' ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] ) x_old = np . empty_like ( x ) for i in range ( iterations ) : x_old [ : ] = x gauss_seidel ( A , x , b , iterations = 1 , sweep = sweep ) x *= omega x_old *= ( 1 - omega ) x += x_old
Perform SOR iteration on the linear system Ax = b .
20,378
def schwarz ( A , x , b , iterations = 1 , subdomain = None , subdomain_ptr = None , inv_subblock = None , inv_subblock_ptr = None , sweep = 'forward' ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' ] ) A . sort_indices ( ) if subdomain is None and inv_subblock is not None : raise ValueError ( "inv_subblock...
Perform Overlapping multiplicative Schwarz on the linear system Ax = b .
20,379
def gauss_seidel ( A , x , b , iterations = 1 , sweep = 'forward' ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] ) if sparse . isspmatrix_csr ( A ) : blocksize = 1 else : R , C = A . blocksize if R != C : raise ValueError ( 'BSR blocks must be square' ) blocksize = R if sweep == 'forward' : row_s...
Perform Gauss - Seidel iteration on the linear system Ax = b .
20,380
def jacobi ( A , x , b , iterations = 1 , omega = 1.0 ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] ) sweep = slice ( None ) ( row_start , row_stop , row_step ) = sweep . indices ( A . shape [ 0 ] ) if ( row_stop - row_start ) * row_step <= 0 : return temp = np . empty_like ( x ) [ omega ] = typ...
Perform Jacobi iteration on the linear system Ax = b .
20,381
def block_jacobi ( A , x , b , Dinv = None , blocksize = 1 , iterations = 1 , omega = 1.0 ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] ) A = A . tobsr ( blocksize = ( blocksize , blocksize ) ) if Dinv is None : Dinv = get_block_diag ( A , blocksize = blocksize , inv_flag = True ) elif Dinv . sh...
Perform block Jacobi iteration on the linear system Ax = b .
20,382
def block_gauss_seidel ( A , x , b , iterations = 1 , sweep = 'forward' , blocksize = 1 , Dinv = None ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] ) A = A . tobsr ( blocksize = ( blocksize , blocksize ) ) if Dinv is None : Dinv = get_block_diag ( A , blocksize = blocksize , inv_flag = True ) el...
Perform block Gauss - Seidel iteration on the linear system Ax = b .
20,383
def polynomial ( A , x , b , coefficients , iterations = 1 ) : A , x , b = make_system ( A , x , b , formats = None ) for i in range ( iterations ) : from pyamg . util . linalg import norm if norm ( x ) == 0 : residual = b else : residual = ( b - A * x ) h = coefficients [ 0 ] * residual for c in coefficients [ 1 : ] :...
Apply a polynomial smoother to the system Ax = b .
20,384
def gauss_seidel_indexed ( A , x , b , indices , iterations = 1 , sweep = 'forward' ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' ] ) indices = np . asarray ( indices , dtype = 'intc' ) if sweep == 'forward' : row_start , row_stop , row_step = 0 , len ( indices ) , 1 elif sweep == 'backward' : row_start ,...
Perform indexed Gauss - Seidel iteration on the linear system Ax = b .
20,385
def jacobi_ne ( A , x , b , iterations = 1 , omega = 1.0 ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' ] ) sweep = slice ( None ) ( row_start , row_stop , row_step ) = sweep . indices ( A . shape [ 0 ] ) temp = np . zeros_like ( x ) Dinv = get_diagonal ( A , norm_eq = 2 , inv = True ) [ omega ] = type_pre...
Perform Jacobi iterations on the linear system A A . H x = A . H b .
20,386
def gauss_seidel_ne ( A , x , b , iterations = 1 , sweep = 'forward' , omega = 1.0 , Dinv = None ) : A , x , b = make_system ( A , x , b , formats = [ 'csr' ] ) if Dinv is None : Dinv = np . ravel ( get_diagonal ( A , norm_eq = 2 , inv = True ) ) if sweep == 'forward' : row_start , row_stop , row_step = 0 , len ( x ) ,...
Perform Gauss - Seidel iterations on the linear system A A . H x = b .
20,387
def gauss_seidel_nr ( A , x , b , iterations = 1 , sweep = 'forward' , omega = 1.0 , Dinv = None ) : A , x , b = make_system ( A , x , b , formats = [ 'csc' ] ) if Dinv is None : Dinv = np . ravel ( get_diagonal ( A , norm_eq = 1 , inv = True ) ) if sweep == 'forward' : col_start , col_stop , col_step = 0 , len ( x ) ,...
Perform Gauss - Seidel iterations on the linear system A . H A x = A . H b .
20,388
def schwarz_parameters ( A , subdomain = None , subdomain_ptr = None , inv_subblock = None , inv_subblock_ptr = None ) : if hasattr ( A , 'schwarz_parameters' ) : if subdomain is not None and subdomain_ptr is not None : if np . array ( A . schwarz_parameters [ 0 ] == subdomain ) . all ( ) and np . array ( A . schwarz_p...
Set Schwarz parameters .
20,389
def cg ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : A , M , x , b , postprocess = make_system ( A , M , x0 , b ) import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._cg' ) if maxiter is None : maxiter = int ( 1.3 * len (...
Conjugate Gradient algorithm .
20,390
def bicgstab ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : A , M , x , b , postprocess = make_system ( A , M , x0 , b ) import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._bicgstab' ) if maxiter is None : maxiter = len (...
Biconjugate Gradient Algorithm with Stabilization .
20,391
def operator_complexity ( self ) : return sum ( [ level . A . nnz for level in self . levels ] ) / float ( self . levels [ 0 ] . A . nnz )
Operator complexity of this multigrid hierarchy .
20,392
def grid_complexity ( self ) : return sum ( [ level . A . shape [ 0 ] for level in self . levels ] ) / float ( self . levels [ 0 ] . A . shape [ 0 ] )
Grid complexity of this multigrid hierarchy .
20,393
def aspreconditioner ( self , cycle = 'V' ) : from scipy . sparse . linalg import LinearOperator shape = self . levels [ 0 ] . A . shape dtype = self . levels [ 0 ] . A . dtype def matvec ( b ) : return self . solve ( b , maxiter = 1 , cycle = cycle , tol = 1e-12 ) return LinearOperator ( shape , matvec , dtype = dtype...
Create a preconditioner using this multigrid cycle .
20,394
def __solve ( self , lvl , x , b , cycle ) : A = self . levels [ lvl ] . A self . levels [ lvl ] . presmoother ( A , x , b ) residual = b - A * x coarse_b = self . levels [ lvl ] . R * residual coarse_x = np . zeros_like ( coarse_b ) if lvl == len ( self . levels ) - 2 : coarse_x [ : ] = self . coarse_solver ( self . l...
Multigrid cycling .
20,395
def maximal_independent_set ( G , algo = 'serial' , k = None ) : G = asgraph ( G ) N = G . shape [ 0 ] mis = np . empty ( N , dtype = 'intc' ) mis [ : ] = - 1 if k is None : if algo == 'serial' : fn = amg_core . maximal_independent_set_serial fn ( N , G . indptr , G . indices , - 1 , 1 , 0 , mis ) elif algo == 'paralle...
Compute a maximal independent vertex set for a graph .
20,396
def vertex_coloring ( G , method = 'MIS' ) : G = asgraph ( G ) N = G . shape [ 0 ] coloring = np . empty ( N , dtype = 'intc' ) if method == 'MIS' : fn = amg_core . vertex_coloring_mis fn ( N , G . indptr , G . indices , coloring ) elif method == 'JP' : fn = amg_core . vertex_coloring_jones_plassmann fn ( N , G . indpt...
Compute a vertex coloring of a graph .
20,397
def bellman_ford ( G , seeds , maxiter = None ) : G = asgraph ( G ) N = G . shape [ 0 ] if maxiter is not None and maxiter < 0 : raise ValueError ( 'maxiter must be positive' ) if G . dtype == complex : raise ValueError ( 'Bellman-Ford algorithm only defined for real\ weights' ) seeds = np . as...
Bellman - Ford iteration .
20,398
def lloyd_cluster ( G , seeds , maxiter = 10 ) : G = asgraph ( G ) N = G . shape [ 0 ] if G . dtype . kind == 'c' : G = np . abs ( G ) if np . isscalar ( seeds ) : seeds = np . random . permutation ( N ) [ : seeds ] seeds = seeds . astype ( 'intc' ) else : seeds = np . array ( seeds , dtype = 'intc' ) if len ( seeds ) ...
Perform Lloyd clustering on graph with weighted edges .
20,399
def breadth_first_search ( G , seed ) : G = asgraph ( G ) N = G . shape [ 0 ] order = np . empty ( N , G . indptr . dtype ) level = np . empty ( N , G . indptr . dtype ) level [ : ] = - 1 BFS = amg_core . breadth_first_search BFS ( G . indptr , G . indices , int ( seed ) , order , level ) return order , level
Breadth First search of a graph .