code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not self._registry_key and self._registry: self._GetKeyFromRegistry() if self._registry_key: return self._registry_key.number_of_values return 0
def number_of_values(self)
int: number of values within the key.
6.208014
4.960492
1.251492
if not self._registry_key and self._registry: self._GetKeyFromRegistry() if not self._registry_key: return None return self._registry_key.offset
def offset(self)
int: offset of the key within the Windows Registry file or None.
6.953155
4.350715
1.598164
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 self._key_path == 'HKEY_LOCAL_MACHINE\\System': sub_registry_key = VirtualWinRegistryKey( 'CurrentControlSet', registry=self._registry) self.AddSubkey(sub_registry_key) self._registry = None
def _GetKeyFromRegistry(self)
Determines the key from the Windows Registry.
2.952046
2.904042
1.01653
# This is an optimized way to combine the path segments into a single path # and combine multiple successive path separators to one. # Split all the path segments based on the path (segment) separator. path_segments = [ segment.split(definitions.KEY_PATH_SEPARATOR) for segment in path_segments] # Flatten the sublists into one list. path_segments = [ element for sublist in path_segments for element in sublist] # Remove empty path segments. path_segments = filter(None, path_segments) return definitions.KEY_PATH_SEPARATOR.join(path_segments)
def _JoinKeyPath(self, path_segments)
Joins the path segments into key path. Args: path_segments (list[str]): Windows Registry key path segments. Returns: str: key path.
4.28977
4.293951
0.999026
name = registry_key.name.upper() if name in self._subkeys: raise KeyError( 'Subkey: {0:s} already exists.'.format(registry_key.name)) self._subkeys[name] = registry_key key_path = self._JoinKeyPath([self._key_path, registry_key.name]) registry_key._key_path = key_path
def AddSubkey(self, registry_key)
Adds a subkey. Args: registry_key (WinRegistryKey): Windows Registry subkey. Raises: KeyError: if the subkey already exists.
3.016269
3.062953
0.984759
if not self._registry_key and self._registry: self._GetKeyFromRegistry() subkeys = list(self._subkeys.values()) if index < 0 or index >= len(subkeys): raise IndexError('Index out of bounds.') return subkeys[index]
def GetSubkeyByIndex(self, index)
Retrieves a subkey by index. Args: index (int): index of the subkey. Returns: WinRegistryKey: Windows Registry subkey or None if not found. Raises: IndexError: if the index is out of bounds.
4.283079
4.01524
1.066706
if not self._registry_key and self._registry: self._GetKeyFromRegistry() return self._subkeys.get(name.upper(), None)
def GetSubkeyByName(self, name)
Retrieves a subkey by name. Args: name (str): name of the subkey. Returns: WinRegistryKey: Windows Registry subkey or None if not found.
7.510651
8.257252
0.909582
if not self._registry_key and self._registry: self._GetKeyFromRegistry() subkey = self for path_segment in key_paths.SplitKeyPath(key_path): subkey = subkey.GetSubkeyByName(path_segment) if not subkey: break return subkey
def GetSubkeyByPath(self, key_path)
Retrieves a subkey by path. Args: key_path (str): path of the subkey. Returns: WinRegistryKey: Windows Registry subkey or None if not found.
4.21911
4.186928
1.007686
if not self._registry_key and self._registry: self._GetKeyFromRegistry() return iter(self._subkeys.values())
def GetSubkeys(self)
Retrieves all subkeys within the key. Returns: generator[WinRegistryKey]: Windows Registry subkey generator.
11.354643
10.213557
1.111723
if not self._registry_key and self._registry: self._GetKeyFromRegistry() if not self._registry_key: return None return self._registry_key.GetValueByName(name)
def GetValueByName(self, name)
Retrieves a value by name. Args: name (str): name of the value or an empty string for the default value. Returns: WinRegistryValue: Windows Registry value or None if not found.
4.630648
4.833452
0.958042
if not self._registry_key and self._registry: self._GetKeyFromRegistry() if self._registry_key: return self._registry_key.GetValues() return iter([])
def GetValues(self)
Retrieves all values within the key. Returns: generator[WinRegistryValue]: Windows Registry value generator.
6.755425
5.68084
1.189159
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_timestamp before_perform = getattr(payload_class, "before_perform", None) metadata["failed"] = False metadata["perform_timestamp"] = time.time() check_after = True try: if before_perform: payload_class.before_perform(metadata) return payload_class.perform(*args) except Exception as e: metadata["failed"] = True metadata["exception"] = e if not self.retry(payload_class, args): metadata["retried"] = False raise else: metadata["retried"] = True logging.exception("Retry scheduled after error in %s", self._payload) finally: after_perform = getattr(payload_class, "after_perform", None) if after_perform: payload_class.after_perform(metadata) delattr(payload_class,'resq')
def perform(self)
This method converts payload into args and calls the ``perform`` method on the payload class. Before calling ``perform``, a ``before_perform`` class method is called, if it exists. It takes a dictionary as an argument; currently the only things stored on the dictionary are the args passed into ``perform`` and a timestamp of when the job was enqueued. Similarly, an ``after_perform`` class method is called after ``perform`` is finished. The metadata dictionary contains the same data, plus a timestamp of when the job was performed, a ``failed`` boolean value, and if it did fail, a ``retried`` boolean value. This method is called after retry, and is called regardless of whether an exception is ultimately thrown by the perform method.
3.57103
2.920266
1.222844
fail = failure.create(exception, self._queue, self._payload, self._worker) fail.save(self.resq) return fail
def fail(self, exception)
This method provides a way to fail a job and will use whatever failure backend you've provided. The default is the ``RedisBackend``.
24.901924
18.239759
1.365255
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 + timedelta(seconds=retry_timeout) retry_at = now + timedelta(seconds=retry_every) if retry_at < retry_until: self.resq.enqueue_at(retry_at, payload_class, *args, **{'first_attempt':first_attempt}) return True return False
def retry(self, payload_class, args)
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.
3.331301
2.944157
1.131496
if isinstance(queues, string_types): queues = [queues] queue, payload = res.pop(queues, timeout=timeout) if payload: return cls(queue, payload, res, worker)
def reserve(cls, queues, res, worker=None, timeout=10)
Reserve a job on one of the queues. This marks this job so that other workers will not pick it up.
5.259002
4.952698
1.061846
mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
def my_import(name)
Helper function for walking import calls when searching for classes by string names.
1.686846
2.036741
0.828208
lst = s.split(".") klass = lst[-1] mod_list = lst[:-1] module = ".".join(mod_list) # ruby compatibility kludge: resque sends just a class name and # not a module name so if I use resque to queue a ruby class # called "Worker" then pyres will throw a "ValueError: Empty # module name" exception. To avoid that, if there's no module in # the json then we'll use the classname as a module name. if not module: module = klass mod = my_import(module) if hasattr(mod, klass): return getattr(mod, klass) else: raise ImportError('')
def safe_str_to_class(s)
Helper function to map string class names to module classes.
8.592941
8.609467
0.998081
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
def str_to_class(s)
Alternate helper function to map string class names to module classes.
2.490106
2.447507
1.017405
queue = getattr(klass,'queue', None) if queue: class_name = '%s.%s' % (klass.__module__, klass.__name__) self.enqueue_from_string(class_name, queue, *args) else: logger.warning("unable to enqueue job with class %s" % str(klass))
def enqueue(self, klass, *args)
Enqueue a job into a specific queue. Make sure the class you are passing has **queue** attribute and a **perform** method on it.
3.421487
3.064738
1.116405
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()), #'working' : len(self.working()), 'failed' : Stat('failed',self).get(), 'servers' : ['%s:%s' % (self.host, self.port)] }
def info(self)
Returns a dictionary of the current status of the pending jobs, processed, no. of queues, no. of workers, no. of failed jobs.
4.125624
3.273299
1.260387
setproctitle('pyres_manager: Waiting on children to shutdown.') for minion in self._workers.values(): minion.terminate() minion.join()
def _shutdown_minions(self)
send the SIGNINT signal to each worker in the pool.
10.362395
7.936402
1.305679
body = dedent().format(exception=self._exception, traceback=self._traceback, queue=self._queue, payload=self._payload, worker=self._worker) return MIMEText(body)
def create_message(self)
Returns a message body to send in this email. Should be from email.mime.*
9.024909
7.749551
1.164572
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: break #procline @paused ? "Paused" : "Waiting for #{@queues.join(',')}" self._setproctitle("Waiting") #time.sleep(interval) self.unregister_worker()
def work(self, interval=5)
Invoked by ``run`` method. ``work`` listens on a list of queues and sleeps for ``interval`` time. ``interval`` -- Number of seconds the worker will wait until processing the next job. Default is "5". Whenever a worker finds a job on the queue it first calls ``reserve`` on that job to make sure another worker won't run it, then *forks* itself to work on that job.
9.081614
8.426468
1.077749
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' % (self.child, datetime.datetime.now())) try: start = datetime.datetime.now() # waits for the result or times out while True: pid, status = os.waitpid(self.child, os.WNOHANG) if pid != 0: if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0: break if os.WIFSTOPPED(status): logger.warning("Process stopped by signal %d" % os.WSTOPSIG(status)) else: if os.WIFSIGNALED(status): raise CrashError("Unexpected exit by signal %d" % os.WTERMSIG(status)) raise CrashError("Unexpected exit status %d" % os.WEXITSTATUS(status)) time.sleep(0.5) now = datetime.datetime.now() if self.timeout and ((now - start).seconds > self.timeout): os.kill(self.child, signal.SIGKILL) os.waitpid(-1, os.WNOHANG) raise TimeoutError("Timed out after %d seconds" % self.timeout) except OSError as ose: import errno if ose.errno != errno.EINTR: raise ose except JobError: self._handle_job_exception(job) finally: # If the child process' job called os._exit manually we need to # finish the clean up here. if self.job(): self.done_working(job) logger.debug('done waiting') else: self._setproctitle("Processing %s since %s" % (job, datetime.datetime.now())) logger.info('Processing %s since %s' % (job, datetime.datetime.now())) self.after_fork(job) # re-seed the Python PRNG after forking, otherwise # all job process will share the same sequence of # random numbers random.seed() self.process(job) os._exit(0) self.child = None
def fork_worker(self, job)
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. Finally, the ``process`` method actually processes the job by eventually calling the Job instance's ``perform`` method.
3.091402
3.091745
0.999889
cmd = "ps -A -o pid,command | grep pyres_worker | grep -v grep" output = commands.getoutput(cmd) if output: return map(lambda l: l.strip().split(' ')[0], output.split("\n")) else: return []
def worker_pids(cls)
Returns an array of all pids (as strings) of the workers on this machine. Used when pruning dead workers.
3.810805
3.509505
1.085853
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._parse_traceback(self._traceback), 'queue' : self._queue } if self._worker: data['worker'] = self._worker data = ResQ.encode(data) resq.redis.rpush('resque:failed', data)
def save(self, resq=None)
Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info.
3.329597
2.981561
1.116729
# Convert to CSR or BSR if necessary 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_matrix') if A.shape[0] != A.shape[1]: raise TypeError('Argument A must be a square') A = A.asfptype() return A
def make_csr(A)
Convert A to CSR, if A is not a CSR or BSR matrix already. Parameters ---------- A : array, matrix, sparse matrix (n x n) matrix to convert to CSR Returns ------- A : csr_matrix, bsr_matrix If A is csr_matrix or bsr_matrix, then do nothing and return A. Else, convert A to CSR if possible and return. Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.blackbox import make_csr >>> A = poisson((40,40),format='csc') >>> Acsr = make_csr(A) Implicit conversion of A to CSR in pyamg.blackbox.make_csr
3.558001
3.418993
1.040658
# Ensure acceptable format of A A = make_csr(A) config = {} # Detect symmetry if ishermitian(A, fast_check=True): config['symmetry'] = 'hermitian' if verb: print(" Detected a Hermitian matrix") else: config['symmetry'] = 'nonsymmetric' if verb: print(" Detected a non-Hermitian matrix") # Symmetry dependent parameters if config['symmetry'] == 'hermitian': config['smooth'] = ('energy', {'krylov': 'cg', 'maxiter': 3, 'degree': 2, 'weighting': 'local'}) config['presmoother'] = ('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 1}) config['postsmoother'] = ('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 1}) else: config['smooth'] = ('energy', {'krylov': 'gmres', 'maxiter': 3, 'degree': 2, 'weighting': 'local'}) config['presmoother'] = ('gauss_seidel_nr', {'sweep': 'symmetric', 'iterations': 2}) config['postsmoother'] = ('gauss_seidel_nr', {'sweep': 'symmetric', 'iterations': 2}) # Determine near null-space modes B if B is None: # B is the constant for each variable in a node if isspmatrix_bsr(A) and A.blocksize[0] > 1: bsize = A.blocksize[0] config['B'] = np.kron(np.ones((int(A.shape[0] / bsize), 1), dtype=A.dtype), np.eye(bsize)) else: config['B'] = np.ones((A.shape[0], 1), dtype=A.dtype) elif (isinstance(B, type(np.zeros((1,)))) or isinstance(B, type(sp.mat(np.zeros((1,)))))): if len(B.shape) == 1: B = B.reshape(-1, 1) if (B.shape[0] != A.shape[0]) or (B.shape[1] == 0): raise TypeError('Invalid dimensions of B, B.shape[0] must equal \ A.shape[0]') else: config['B'] = np.array(B, dtype=A.dtype) else: raise TypeError('Invalid B') if config['symmetry'] == 'hermitian': config['BH'] = None else: config['BH'] = config['B'].copy() # Set non-symmetry related parameters config['strength'] = ('evolution', {'k': 2, 'proj_type': 'l2', 'epsilon': 3.0}) config['max_levels'] = 15 config['max_coarse'] = 500 config['coarse_solver'] = 'pinv' config['aggregate'] = 'standard' config['keep'] = False return config
def solver_configuration(A, B=None, verb=True)
Generate a dictionary of SA parameters for an arbitray matrix A. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix (n x n) matrix to invert, CSR or BSR format preferred for efficiency B : None, array Near null-space modes used to construct the smoothed aggregation solver If None, the constant vector is used If (n x m) array, then B is passed to smoothed_aggregation_solver verb : bool If True, print verbose output during runtime Returns ------- config : dict A dictionary of solver configuration parameters that one uses to generate a smoothed aggregation solver Notes ----- The config dictionary contains the following parameter entries: symmetry, smooth, presmoother, postsmoother, B, strength, max_levels, max_coarse, coarse_solver, aggregate, keep. See smoothed_aggregtion_solver for each parameter's description. Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg import solver_configuration >>> A = poisson((40,40),format='csr') >>> solver_config = solver_configuration(A,verb=False)
2.821602
2.520133
1.119624
# Convert A to acceptable format A = make_csr(A) # Generate smoothed aggregation solver 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_solver'], symmetry=config['symmetry'], aggregate=config['aggregate'], presmoother=config['presmoother'], postsmoother=config['postsmoother'], keep=config['keep']) except BaseException: raise TypeError('Failed generating smoothed_aggregation_solver')
def solver(A, config)
Generate an SA solver given matrix A and a configuration. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix Matrix to invert, CSR or BSR format preferred for efficiency config : dict A dictionary of solver configuration parameters that is used to generate a smoothed aggregation solver Returns ------- ml : smoothed_aggregation_solver smoothed aggregation hierarchy Notes ----- config must contain the following parameter entries for smoothed_aggregation_solver: symmetry, smooth, presmoother, postsmoother, B, strength, max_levels, max_coarse, coarse_solver, aggregate, keep Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg import solver_configuration,solver >>> A = poisson((40,40),format='csr') >>> config = solver_configuration(A,verb=False) >>> ml = solver(A,config)
3.71285
2.625505
1.414147
with open(fname, 'r') as inf: fdata = inf.readlines() comments = {} for f in ch.functions: lineno = f['line_number'] - 1 # zero based indexing # set starting position lineptr = lineno - 1 if f['template']: lineptr -= 1 start = lineptr # find the top of the comment block while fdata[lineptr].startswith('//') or\ fdata[lineptr].startswith('/*') or\ fdata[lineptr].startswith(' *'): lineptr -= 1 lineptr += 1 comment = fdata[lineptr:(start + 1)] comment = [c[3:].rstrip() for c in comment] comments[f['name']] = '\n'.join(comment).strip() return comments
def find_comments(fname, ch)
Find the comments for a function. fname: filename ch: CppHeaderParser parse tree The function must look like /* * comments * comments */ template<class I, ...> void somefunc(...){ -or- /* * comments * comments */ void somefunc(...){ -or- with // style comments Then, take off the first three spaces
3.810029
3.921546
0.971563
indent = ' ' # temlpate and function name if func['template']: fdef = func['template'] + '\n' else: fdef = '' newcall = func['returns'] + ' _' + func['name'] + '(' fdef += newcall + '\n' # function parameters # for each parameter # if it's an array # - replace with py::array_t # - skip the next _size argument # - save in a list of arrays # else replicate i = 0 arraylist = [] needsize = False while i < len(func['parameters']): p = func['parameters'][i] i += 1 # check if pointer/array if p['pointer'] or p['array']: paramtype = p['raw_type'] const = '' if p['constant']: const = 'const ' param = 'py::array_t<{}> &'.format(paramtype) + ' ' + p['name'] arraylist.append((const, paramtype, p['name'])) needsize = True elif '_size' not in p['name'] and needsize: # not a size, but needed one raise ValueError( 'Expecting a _size parameter for {}'.format( p['name'])) elif '_size' in p['name']: # just size, skip it needsize = False continue else: # if not a pointer, just copy it param = p['type'] + ' ' + p['name'] fdef += '{:>25},\n'.format(param) # set width to 25 fdef = fdef.strip()[:-1] # trim comma and newline fdef += '\n' + ' ' * len(newcall) + ')' fdef += '\n{\n' # make a list of python objects for a in arraylist: if 'const' in a[0]: unchecked = '.unchecked();\n' else: unchecked = '.mutable_unchecked();\n' fdef += indent fdef += "auto py_" + a[2] + ' = ' + a[2] + unchecked # make a list of pointers to the arrays for a in arraylist: if 'const' in a[0]: data = '.data();\n' else: data = '.mutable_data();\n' fdef += indent fdef += a[0] + a[1] + ' *_' + a[2] + ' = py_' + a[2] + data # get the template signature if len(arraylist) > 0: fdef += '\n' if func['template']: template = func['template'] template = template.replace('template', '').replace( 'class ', '') # template <class T> ----> <T> else: template = '' newcall = ' return ' + func['name'] + template + '(' fdef += newcall + '\n' # function parameters for p in func['parameters']: if '_size' in p['name']: fdef = fdef.strip() name, s = p['name'].split('_size') if s == '': s = '0' fdef += " {}.shape({})".format(name, s) else: if p['pointer'] or p['array']: name = '_' + p['name'] else: name = p['name'] fdef += '{:>25}'.format(name) fdef += ',\n' fdef = fdef.strip()[:-1] fdef += '\n' + ' ' * len(newcall) + ');\n}' return fdef
def build_function(func)
Build a function from a templated function. The function must look like template<class I, class T, ...> void func(const p[], p_size, ...) rules: - a pointer or array p is followed by int p_size - all arrays are templated - non arrays are basic types: int, double, complex, etc - all functions are straight up c++
3.465949
3.443664
1.006471
headerfilename = os.path.splitext(headerfile)[0] indent = ' ' plugin = '' # plugin += '#define NC py::arg().noconvert()\n' # plugin += '#define YC py::arg()\n' plugin += 'PYBIND11_MODULE({}, m) {{\n'.format(headerfilename) plugin += indent + 'm.doc() = R"pbdoc(\n' plugin += indent + 'Pybind11 bindings for {}\n\n'.format(headerfile) plugin += indent + 'Methods\n' plugin += indent + '-------\n' for f in ch.functions: for func in inst: if f['name'] in func['functions']: plugin += indent + f['name'] + '\n' plugin += indent + ')pbdoc";\n\n' plugin += indent + 'py::options options;\n' plugin += indent + 'options.disable_function_signatures();\n\n' unbound = [] bound = [] for f in ch.functions: # for each function: # - find the entry in the instantiation list # - note any array parameters to the function # - for each type, instantiate found = False for func in inst: if f['name'] in func['functions']: found = True types = func['types'] if not found: # print('Could not find {}'.format(f['name'])) unbound.append(f['name']) continue else: bound.append(f['name']) # find all parameter names and mark if array argnames = [] for p in f['parameters']: array = False if p['pointer'] or p['array']: array = True # skip "_size" parameters if '_size' in p['name']: continue else: argnames.append((p['name'], array)) ntypes = len(types) for i, t in enumerate(types): # add the function call with each template instname = f['name'] # check the remaps for remap in remaps: if f['name'] in remap: instname = remap[f['name']] if t is not None: # templated function typestr = '<' + ', '.join(t) + '>' else: # not a templated function typestr = '' plugin += indent + \ 'm.def("{}", &_{}{},\n'.format(instname, f['name'], typestr) # name the arguments pyargnames = [] for p, array in argnames: convert = '' if array: convert = '.noconvert()' pyargnames.append('py::arg("{}"){}'.format(p, convert)) argstring = indent + ', '.join(pyargnames) plugin += indent + argstring # add the docstring to the last if i == ntypes - 1: plugin += ',\nR"pbdoc(\n{})pbdoc");\n'.format( comments[f['name']]) else: plugin += ');\n' plugin += '\n' plugin += '}\n' # plugin += '#undef NC\n' # plugin += '#undef YC\n' return plugin, bound, unbound
def build_plugin(headerfile, ch, comments, inst, remaps)
Take a header file (headerfile) and a parse tree (ch) and build the pybind11 plugin headerfile: somefile.h ch: parse tree from CppHeaderParser comments: a dictionary of comments inst: files to instantiate remaps: list of remaps
3.859527
3.869522
0.997417
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) # duplicate (i,j) entries will be summed together return sp.sparse.csr_matrix((data, (row, col)), shape=(m, n))
def _rand_sparse(m, n, density, format='csr')
Construct base function for sprand, sprandn.
2.618152
2.68174
0.976289
m, n = int(m), int(n) # get sparsity pattern A = _rand_sparse(m, n, density, format='csr') # replace data with random values A.data = sp.rand(A.nnz) return A.asformat(format)
def sprand(m, n, density, format='csr')
Return a random sparse matrix. Parameters ---------- m, n : int shape of the result density : float target a matrix with nnz(A) = m*n*density, 0<=density<=1 format : string sparse matrix format to return, e.g. 'csr', 'coo', etc. Return ------ A : sparse matrix m x n sparse matrix Examples -------- >>> from pyamg.gallery import sprand >>> A = sprand(5,5,3/5.0)
3.948091
5.553779
0.710884
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))
def linear_elasticity(grid, spacing=None, E=1e5, nu=0.3, format=None)
Linear elasticity problem discretizes with Q1 finite elements on a regular rectangular grid. Parameters ---------- grid : tuple length 2 tuple of grid sizes, e.g. (10, 10) spacing : tuple length 2 tuple of grid spacings, e.g. (1.0, 0.1) E : float Young's modulus nu : float Poisson's ratio format : string Format of the returned sparse matrix (eg. 'csr', 'bsr', etc.) Returns ------- A : csr_matrix FE Q1 stiffness matrix B : array rigid body modes See Also -------- linear_elasticity_p1 Notes ----- - only 2d for now Examples -------- >>> from pyamg.gallery import linear_elasticity >>> A, B = linear_elasticity((4, 4)) References ---------- .. [1] J. Alberty, C. Carstensen, S. A. Funken, and R. KloseDOI "Matlab implementation of the finite element method in elasticity" Computing, Volume 69, Issue 3 (November 2002) Pages: 239 - 263 http://www.math.hu-berlin.de/~cc/
4.144897
4.972847
0.833506
X, Y = tuple(grid) if X < 1 or Y < 1: raise ValueError('invalid grid shape') if dirichlet_boundary: X += 1 Y += 1 pts = np.mgrid[0:X+1, 0:Y+1] pts = np.hstack((pts[0].T.reshape(-1, 1) - X / 2.0, pts[1].T.reshape(-1, 1) - Y / 2.0)) if spacing is None: DX, DY = 1, 1 else: DX, DY = tuple(spacing) pts *= [DX, DY] # compute local stiffness matrix lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter mu = E / (2 + 2*nu) # shear modulus vertices = np.array([[0, 0], [DX, 0], [DX, DY], [0, DY]]) K = q12d_local(vertices, lame, mu) nodes = np.arange((X+1)*(Y+1)).reshape(X+1, Y+1) LL = nodes[:-1, :-1] Id = (2*LL).repeat(K.size).reshape(-1, 8, 8) J = Id.copy() Id += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1)) J += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1)).T V = np.tile(K, (X*Y, 1)) Id = np.ravel(Id) J = np.ravel(J) V = np.ravel(V) # sum duplicates A = coo_matrix((V, (Id, J)), shape=(pts.size, pts.size)).tocsr() A = A.tobsr(blocksize=(2, 2)) del Id, J, V, LL, nodes B = np.zeros((2 * (X+1)*(Y+1), 3)) B[0::2, 0] = 1 B[1::2, 1] = 1 B[0::2, 2] = -pts[:, 1] B[1::2, 2] = pts[:, 0] if dirichlet_boundary: mask = np.zeros((X+1, Y+1), dtype='bool') mask[1:-1, 1:-1] = True mask = np.ravel(mask) data = np.zeros(((X-1)*(Y-1), 2, 2)) data[:, 0, 0] = 1 data[:, 1, 1] = 1 indices = np.arange((X-1)*(Y-1)) indptr = np.concatenate((np.array([0]), np.cumsum(mask))) P = bsr_matrix((data, indices, indptr), shape=(2*(X+1)*(Y+1), 2*(X-1)*(Y-1))) Pt = P.T A = P.T * A * P B = Pt * B return A.asformat(format), B
def q12d(grid, spacing=None, E=1e5, nu=0.3, dirichlet_boundary=True, format=None)
Q1 elements in 2 dimensions. See Also -------- linear_elasticity
2.525306
2.61023
0.967465
M = lame + 2*mu # P-wave modulus 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 = np.matrix([[2, 1, -1, -2], [1, 2, -2, -1], [-1, -2, 2, 1], [-2, -1, 1, 2]]) / 6.0 F = inv(np.vstack((vertices[1] - vertices[0], vertices[3] - vertices[0]))) K = np.zeros((8, 8)) # stiffness matrix E = F.T * np.matrix([[M, 0], [0, mu]]) * F K[0::2, 0::2] = E[0, 0] * R_11 + E[0, 1] * R_12 +\ E[1, 0] * R_12.T + E[1, 1] * R_22 E = F.T * np.matrix([[mu, 0], [0, M]]) * F K[1::2, 1::2] = E[0, 0] * R_11 + E[0, 1] * R_12 +\ E[1, 0] * R_12.T + E[1, 1] * R_22 E = F.T * np.matrix([[0, mu], [lame, 0]]) * F K[1::2, 0::2] = E[0, 0] * R_11 + E[0, 1] * R_12 +\ E[1, 0] * R_12.T + E[1, 1] * R_22 K[0::2, 1::2] = K[1::2, 0::2].T K /= det(F) return K
def q12d_local(vertices, lame, mu)
Local stiffness matrix for two dimensional elasticity on a square element. Parameters ---------- lame : Float Lame's first parameter mu : Float shear modulus See Also -------- linear_elasticity Notes ----- Vertices should be listed in counter-clockwise order:: [3]----[2] | | | | [0]----[1] Degrees of freedom are enumerated as follows:: [x=6,y=7]----[x=4,y=5] | | | | [x=0,y=1]----[x=2,y=3]
1.733591
1.790577
0.968175
assert(vertices.shape == (3, 2)) A = np.vstack((np.ones((1, 3)), vertices.T)) PhiGrad = inv(A)[:, 1:] # gradients of basis functions R = np.zeros((3, 6)) R[[[0], [2]], [0, 2, 4]] = PhiGrad.T R[[[2], [1]], [1, 3, 5]] = PhiGrad.T C = mu*np.array([[2, 0, 0], [0, 2, 0], [0, 0, 1]]) +\ lame*np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]]) K = det(A)/2.0*np.dot(np.dot(R.T, C), R) return K
def p12d_local(vertices, lame, mu)
Local stiffness matrix for P1 elements in 2d.
2.9587
2.919102
1.013565
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 ValueError('unknown mesh_type=%s' % mesh_type) key = map_type_to_key[mesh_type] if mesh_type == 'vertex': uidx = np.arange(0, Verts.shape[0]).reshape((Verts.shape[0], 1)) E2V = {key: uidx} else: E2V = {key: E2V} if cdata is not None: cdata = {key: cdata} if cvdata is not None: cvdata = {key: cvdata} write_vtu(Verts=Verts, Cells=E2V, pdata=pdata, pvdata=pvdata, cdata=cdata, cvdata=cvdata, fname=fname)
def write_basic_mesh(Verts, E2V=None, mesh_type='tri', pdata=None, pvdata=None, cdata=None, cvdata=None, fname='output.vtk')
Write mesh file for basic types of elements. Parameters ---------- fname : {string} file to be written, e.g. 'mymesh.vtu' Verts : {array} coordinate array (N x D) E2V : {array} element index array (Nel x Nelnodes) mesh_type : {string} type of elements: tri, quad, tet, hex (all 3d) pdata : {array} scalar data on vertices (N x Nfields) pvdata : {array} vector data on vertices (3*Nfields x N) cdata : {array} scalar data on cells (Nfields x Nel) cvdata : {array} vector data on cells (3*Nfields x Nel) Returns ------- writes a .vtu file for use in Paraview Notes ----- The difference between write_basic_mesh and write_vtu is that write_vtu is more general and requires dictionaries of cell information. write_basic_mesh calls write_vtu Examples -------- >>> import numpy as np >>> from pyamg.vis import write_basic_mesh >>> Verts = np.array([[0.0,0.0], ... [1.0,0.0], ... [2.0,0.0], ... [0.0,1.0], ... [1.0,1.0], ... [2.0,1.0], ... [0.0,2.0], ... [1.0,2.0], ... [2.0,2.0], ... [0.0,3.0], ... [1.0,3.0], ... [2.0,3.0]]) >>> E2V = np.array([[0,4,3], ... [0,1,4], ... [1,5,4], ... [1,2,5], ... [3,7,6], ... [3,4,7], ... [4,8,7], ... [4,5,8], ... [6,10,9], ... [6,7,10], ... [7,11,10], ... [7,8,11]]) >>> pdata=np.ones((12,2)) >>> pvdata=np.ones((12*3,2)) >>> cdata=np.ones((12,2)) >>> cvdata=np.ones((3*12,2)) >>> write_basic_mesh(Verts, E2V=E2V, mesh_type='tri',pdata=pdata, pvdata=pvdata, cdata=cdata, cvdata=cvdata, fname='test.vtu') See Also -------- write_vtu
2.172957
2.298222
0.945495
for key in d: elm.setAttribute(key, d[key])
def set_attributes(d, elm)
Set attributes from dictionary of values.
3.85175
3.696877
1.041893
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_inner_product(z, AggOp, nPDEs, ndof): z = np.ravel(z)*np.ravel(z) innerp = np.zeros((1, AggOp.shape[1]), dtype=z.dtype) for j in range(nPDEs): innerp += z[slice(j, ndof, nPDEs)].reshape(1, -1) * AggOp return innerp.reshape(-1, 1) def get_aggregate_weights(AggOp, A, z, nPDEs, ndof): rho = approximate_spectral_radius(A) zAz = np.dot(z.reshape(1, -1), A*z.reshape(-1, 1)) card = nPDEs*(AggOp.indptr[1:]-AggOp.indptr[:-1]) weights = (np.ravel(card)*zAz)/(A.shape[0]*rho) return weights.reshape(-1, 1) # Run test 1, which finds where x is small relative to its energy weights = Ca*get_aggregate_weights(AggOp, A, x, nPDEs, ndof) mask1 = aggregate_wise_inner_product(x, AggOp, nPDEs, ndof) <= weights # Run test 2, which finds where x is already approximated # accurately by the existing T projected_x = x - T*(T.T*x) mask2 = aggregate_wise_inner_product(projected_x, AggOp, nPDEs, ndof) <= weights # Combine masks and zero out corresponding aggregates in x mask = np.ravel(mask1 + mask2).nonzero()[0] if mask.shape[0] > 0: mask = nPDEs*AggOp[:, mask].indices for j in range(nPDEs): x[mask+j] = 0.0
def eliminate_local_candidates(x, AggOp, A, T, Ca=1.0, **kwargs)
Eliminate canidates locally. Helper function that determines where to eliminate candidates locally on a per aggregate basis. Parameters --------- x : array n x 1 vector of new candidate AggOp : CSR or CSC sparse matrix Aggregation operator for the level that x was generated for A : sparse matrix Operator for the level that x was generated for T : sparse matrix Tentative prolongation operator for the level that x was generated for Ca : scalar Constant threshold parameter to decide when to drop candidates Returns ------- Nothing, x is modified in place
3.776643
3.797379
0.994539
grid = tuple(grid) N = len(grid) # grid dimension if N < 1 or min(grid) < 1: raise ValueError('invalid grid shape: %s' % str(grid)) # create N-dimension Laplacian stencil if type == 'FD': stencil = np.zeros((3,) * N, dtype=dtype) for i in range(N): stencil[(1,)*i + (0,) + (1,)*(N-i-1)] = -1 stencil[(1,)*i + (2,) + (1,)*(N-i-1)] = -1 stencil[(1,)*N] = 2*N if type == 'FE': stencil = -np.ones((3,) * N, dtype=dtype) stencil[(1,)*N] = 3**N - 1 return stencil_grid(stencil, grid, format=format)
def poisson(grid, spacing=None, dtype=float, format=None, type='FD')
Return a sparse matrix for the N-dimensional Poisson problem. The matrix represents a finite Difference approximation to the Poisson problem on a regular n-dimensional grid with unit grid spacing and Dirichlet boundary conditions. Parameters ---------- grid : tuple of integers grid dimensions e.g. (100,100) Notes ----- The matrix is symmetric and positive definite (SPD). Examples -------- >>> from pyamg.gallery import poisson >>> # 4 nodes in one dimension >>> poisson( (4,) ).todense() matrix([[ 2., -1., 0., 0.], [-1., 2., -1., 0.], [ 0., -1., 2., -1.], [ 0., 0., -1., 2.]]) >>> # rectangular two dimensional grid >>> poisson( (2,3) ).todense() matrix([[ 4., -1., 0., -1., 0., 0.], [-1., 4., -1., 0., -1., 0.], [ 0., -1., 4., 0., 0., -1.], [-1., 0., 0., 4., -1., 0.], [ 0., -1., 0., -1., 4., -1.], [ 0., 0., -1., 0., -1., 4.]])
2.959188
3.090037
0.957655
# TODO check dimensions of x # TODO speedup complex case 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')
def norm(x, pnorm='2')
2-norm of a vector. Parameters ---------- x : array_like Vector of complex or real values pnorm : string '2' calculates the 2-norm 'inf' calculates the infinity-norm Returns ------- n : float 2-norm of a vector Notes ----- - currently 1+ order of magnitude faster than scipy.linalg.norm(x), which calls sqrt(numpy.sum(real((conjugate(x)*x)),axis=0)) resulting in an extra copy - only handles the 2-norm and infinity-norm for vectors See Also -------- scipy.linalg.norm : scipy general matrix or vector norm
3.896376
4.114705
0.946939
if sparse.isspmatrix_csr(A) or sparse.isspmatrix_csc(A): # avoid copying index and ptr arrays abs_A = A.__class__((np.abs(A.data), A.indices, A.indptr), shape=A.shape) return (abs_A * np.ones((A.shape[1]), dtype=A.dtype)).max() elif sparse.isspmatrix(A): return (abs(A) * np.ones((A.shape[1]), dtype=A.dtype)).max() else: return np.dot(np.abs(A), np.ones((A.shape[1],), dtype=A.dtype)).max()
def infinity_norm(A)
Infinity norm of a matrix (maximum absolute row sum). Parameters ---------- A : csr_matrix, csc_matrix, sparse, or numpy matrix Sparse or dense matrix Returns ------- n : float Infinity norm of the matrix Notes ----- - This serves as an upper bound on spectral radius. - csr and csc avoid a deep copy - dense calls scipy.linalg.norm See Also -------- scipy.linalg.norm : dense matrix norms Examples -------- >>> import numpy as np >>> from scipy.sparse import spdiags >>> from pyamg.util.linalg import infinity_norm >>> n=10 >>> e = np.ones((n,1)).ravel() >>> data = [ -1*e, 2*e, -1*e ] >>> A = spdiags(data,[-1,0,1],n,n) >>> print infinity_norm(A) 4.0
2.706429
3.04825
0.887863
return norm(np.ravel(b) - A*np.ravel(x))
def residual_norm(A, x, b)
Compute ||b - A*x||.
6.743385
4.900672
1.376012
from scipy.linalg import get_blas_funcs fn = get_blas_funcs(['axpy'], [x, y])[0] fn(x, y, a)
def axpy(x, y, a=1.0)
Quick level-1 call to BLAS y = a*x+y. Parameters ---------- x : array_like nx1 real or complex vector y : array_like nx1 real or complex vector a : float real or complex scalar Returns ------- y : array_like Input variable y is rewritten Notes ----- The call to get_blas_funcs automatically determines the prefix for the blas call.
4.295396
3.531342
1.216364
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])
def condest(A, tol=0.1, maxiter=25, symmetric=False)
r"""Estimates the condition number of A. Parameters ---------- A : {dense or sparse matrix} e.g. array, matrix, csr_matrix, ... tol : {float} Approximation tolerance, currently not used maxiter: {int} Max number of Arnoldi/Lanczos iterations symmetric : {bool} If symmetric use the far more efficient Lanczos algorithm, Else use Arnoldi Returns ------- Estimate of cond(A) with \|lambda_max\| / \|lambda_min\| through the use of Arnoldi or Lanczos iterations, depending on the symmetric flag Notes ----- The condition number measures how large of a change in the the problems solution is caused by a change in problem's input. Large condition numbers indicate that small perturbations and numerical errors are magnified greatly when solving the system. Examples -------- >>> import numpy as np >>> from pyamg.util.linalg import condest >>> c = condest(np.array([[1.,0.],[0.,2.]])) >>> print c 2.0
11.84176
21.166513
0.559457
if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') if sparse.isspmatrix(A): A = A.todense() # 2-Norm Condition Number from scipy.linalg import svd U, Sigma, Vh = svd(A) return np.max(Sigma)/min(Sigma)
def cond(A)
Return condition number of A. Parameters ---------- A : {dense or sparse matrix} e.g. array, matrix, csr_matrix, ... Returns ------- 2-norm condition number through use of the SVD Use for small to moderate sized dense matrices. For large sparse matrices, use condest. Notes ----- The condition number measures how large of a change in the problems solution is caused by a change in problem's input. Large condition numbers indicate that small perturbations and numerical errors are magnified greatly when solving the system. Examples -------- >>> import numpy as np >>> from pyamg.util.linalg import condest >>> c = condest(np.array([[1.0,0.],[0.,2.0]])) >>> print c 2.0
4.024737
4.148873
0.97008
r # convert to matrix type 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.rand(A.shape[0], 1) xAy = np.dot((A*x).conjugate().T, y) xAty = np.dot(x.conjugate().T, A*y) diff = float(np.abs(xAy - xAty) / np.sqrt(np.abs(xAy*xAty))) else: # compute the difference, A - A.H if sparse.isspmatrix(A): diff = np.ravel((A - A.H).data) else: diff = np.ravel(A - A.H) if np.max(diff.shape) == 0: diff = 0 else: diff = np.max(np.abs(diff)) if diff < tol: diff = 0 return True else: if verbose: print(diff) return False return diff
def ishermitian(A, fast_check=True, tol=1e-6, verbose=False)
r"""Return True if A is Hermitian to within tol. Parameters ---------- A : {dense or sparse matrix} e.g. array, matrix, csr_matrix, ... fast_check : {bool} If True, use the heuristic < Ax, y> = < x, Ay> for random vectors x and y to check for conjugate symmetry. If False, compute A - A.H. tol : {float} Symmetry tolerance verbose: {bool} prints max( \|A - A.H\| ) if nonhermitian and fast_check=False abs( <Ax, y> - <x, Ay> ) if nonhermitian and fast_check=False Returns ------- True if hermitian False if nonhermitian Notes ----- This function applies a simple test of conjugate symmetry Examples -------- >>> import numpy as np >>> from pyamg.util.linalg import ishermitian >>> ishermitian(np.array([[1,2],[1,1]])) False >>> from pyamg.gallery import poisson >>> ishermitian(poisson((10,10))) True
2.690752
2.734439
0.984024
n = a.shape[0] m = a.shape[1] if m == 1: # Pseudo-inverse of 1 x 1 matrices is trivial 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: # The block size is greater than 1 # Create necessary arrays and function pointers for calculating pinv gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), (np.ones((1,), dtype=a.dtype))) RHS = np.eye(m, dtype=a.dtype) lwork = _compute_lwork(gelss_lwork, m, m, m) # Choose tolerance for which singular values are zero in *gelss below if cond is None: t = a.dtype.char eps = np.finfo(np.float).eps feps = np.finfo(np.single).eps geps = np.finfo(np.longfloat).eps _array_precision = {'f': 0, 'd': 1, 'g': 2, 'F': 0, 'D': 1, 'G': 2} cond = {0: feps*1e3, 1: eps*1e6, 2: geps*1e6}[_array_precision[t]] # Invert each block of a for kk in range(n): gelssoutput = gelss(a[kk], RHS, cond=cond, lwork=lwork, overwrite_a=True, overwrite_b=False) a[kk] = gelssoutput[1]
def pinv_array(a, cond=None)
Calculate the Moore-Penrose pseudo inverse of each block of the three dimensional array a. Parameters ---------- a : {dense array} Is of size (n, m, m) cond : {float} Used by gelss to filter numerically zeros singular values. If None, a suitable value is chosen for you. Returns ------- Nothing, a is modified in place so that a[k] holds the pseudoinverse of that block. Notes ----- By using lapack wrappers, this can be much faster for large n, than directly calling pinv2 Examples -------- >>> import numpy as np >>> from pyamg.util.linalg import pinv_array >>> a = np.array([[[1.,2.],[1.,1.]], [[1.,1.],[3.,3.]]]) >>> ac = a.copy() >>> # each block of a is inverted in-place >>> pinv_array(a)
3.890322
3.669614
1.060145
# Amalgamate for the supernode case 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.isspmatrix_csr(A): warn("Implicit conversion of A to csr", sparse.SparseEfficiencyWarning) A = sparse.csr_matrix(A) dim = V.shape[1] # Create two arrays for differencing the different coordinates such # that C(i,j) = distance(point_i, point_j) cols = A.indices rows = np.repeat(np.arange(A.shape[0]), A.indptr[1:] - A.indptr[0:-1]) # Insert difference for each coordinate into C C = (V[rows, 0] - V[cols, 0])**2 for d in range(1, dim): C += (V[rows, d] - V[cols, d])**2 C = np.sqrt(C) C[C < 1e-6] = 1e-6 C = sparse.csr_matrix((C, A.indices.copy(), A.indptr.copy()), shape=A.shape) # Apply drop tolerance if relative_drop is True: if theta != np.inf: amg_core.apply_distance_filter(C.shape[0], theta, C.indptr, C.indices, C.data) else: amg_core.apply_absolute_distance_filter(C.shape[0], theta, C.indptr, C.indices, C.data) C.eliminate_zeros() C = C + sparse.eye(C.shape[0], C.shape[1], format='csr') # Standardized strength values require small values be weak and large # values be strong. So, we invert the distances. C.data = 1.0 / C.data # Scale C by the largest magnitude entry in each row C = scale_rows_by_largest_entry(C) return C
def distance_strength_of_connection(A, V, theta=2.0, relative_drop=True)
Distance based strength-of-connection. Parameters ---------- A : csr_matrix or bsr_matrix Square, sparse matrix in CSR or BSR format V : array Coordinates of the vertices of the graph of A relative_drop : bool If false, then a connection must be within a distance of theta from a point to be strongly connected. If true, then the closest connection is always strong, and other points must be within theta times the smallest distance to be strong Returns ------- C : csr_matrix C(i,j) = distance(point_i, point_j) Strength of connection matrix where strength values are distances, i.e. the smaller the value, the stronger the connection. Sparsity pattern of C is copied from A. Notes ----- - theta is a drop tolerance that is applied row-wise - If a BSR matrix given, then the return matrix is still CSR. The strength is given between super nodes based on the BSR block size. Examples -------- >>> from pyamg.gallery import load_example >>> from pyamg.strength import distance_strength_of_connection >>> data = load_example('airfoil') >>> A = data['A'].tocsr() >>> S = distance_strength_of_connection(data['A'], data['vertices'])
3.650932
3.344354
1.09167
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 < 0 or theta > 1): raise ValueError('expected theta in [0,1]') Sp = np.empty_like(A.indptr) Sj = np.empty_like(A.indices) Sx = np.empty_like(A.data) if norm == 'abs': amg_core.classical_strength_of_connection_abs( A.shape[0], theta, A.indptr, A.indices, A.data, Sp, Sj, Sx) elif norm == 'min': amg_core.classical_strength_of_connection_min( A.shape[0], theta, A.indptr, A.indices, A.data, Sp, Sj, Sx) else: raise ValueError('Unknown norm') S = sparse.csr_matrix((Sx, Sj, Sp), shape=A.shape) if blocksize > 1: S = amalgamate(S, blocksize) # Strength represents "distance", so take the magnitude S.data = np.abs(S.data) # Scale S by the largest magnitude entry in each row S = scale_rows_by_largest_entry(S) return S
def classical_strength_of_connection(A, theta=0.0, norm='abs')
Classical Strength Measure. Return a strength of connection matrix using the classical AMG measure An off-diagonal entry A[i,j] is a strong connection iff:: A[i,j] >= theta * max(|A[i,k]|), where k != i (norm='abs') -A[i,j] >= theta * max(-A[i,k]), where k != i (norm='min') Parameters ---------- A : csr_matrix or bsr_matrix Square, sparse matrix in CSR or BSR format theta : float Threshold parameter in [0,1]. norm: 'string' 'abs' : to use the absolute value, 'min' : to use the negative value (see above) Returns ------- S : csr_matrix Matrix graph defining strong connections. S[i,j]=1 if vertex i is strongly influenced by vertex j. See Also -------- symmetric_strength_of_connection : symmetric measure used in SA evolution_strength_of_connection : relaxation based strength measure Notes ----- - A symmetric A does not necessarily yield a symmetric strength matrix S - Calls C++ function classical_strength_of_connection - The version as implemented is designed form M-matrices. Trottenberg et al. use max A[i,k] over all negative entries, which is the same. A positive edge weight never indicates a strong connection. - See [2000BrHeMc]_ and [2001bTrOoSc]_ References ---------- .. [2000BrHeMc] Briggs, W. L., Henson, V. E., McCormick, S. F., "A multigrid tutorial", Second edition. Society for Industrial and Applied Mathematics (SIAM), Philadelphia, PA, 2000. xii+193 pp. .. [2001bTrOoSc] Trottenberg, U., Oosterlee, C. W., Schuller, A., "Multigrid", Academic Press, Inc., San Diego, CA, 2001. xvi+631 pp. Examples -------- >>> import numpy as np >>> from pyamg.gallery import stencil_grid >>> from pyamg.strength import classical_strength_of_connection >>> n=3 >>> stencil = np.array([[-1.0,-1.0,-1.0], ... [-1.0, 8.0,-1.0], ... [-1.0,-1.0,-1.0]]) >>> A = stencil_grid(stencil, (n,n), format='csr') >>> S = classical_strength_of_connection(A, 0.0)
2.548198
2.698991
0.94413
return evolution_strength_of_connection(A, B, epsilon, k, proj_type, block_flag, symmetrize_measure)
def ode_strength_of_connection(A, B=None, epsilon=4.0, k=2, proj_type="l2", block_flag=False, symmetrize_measure=True)
(deprecated) Use evolution_strength_of_connection instead.
2.506876
1.976577
1.268292
# random n x R block in column ordering n = A.shape[0] x = np.random.rand(n * R) - 0.5 x = np.reshape(x, (n, R), order='F') # for i in range(R): # x[:,i] = x[:,i] - np.mean(x[:,i]) b = np.zeros((n, 1)) for r in range(0, R): jacobi(A, x[:, r], b, iterations=k, omega=alpha) # x[:,r] = x[:,r]/norm(x[:,r]) return x
def relaxation_vectors(A, R, k, alpha)
Generate test vectors by relaxing on Ax=0 for some random vectors x. Parameters ---------- A : csr_matrix Sparse NxN matrix alpha : scalar Weight for Jacobi R : integer Number of random vectors k : integer Number of relaxation passes Returns ------- x : array Dense array N x k array of relaxation vectors
3.5903
3.551799
1.01084
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, int): raise ValueError('expected integer k>0') if epsilon < 1: raise ValueError('expected epsilon>1.0') def distance(x): (rows, cols) = A.nonzero() return 1 - np.sum(x[rows] * x[cols], axis=1)**2 / \ (np.sum(x[rows]**2, axis=1) * np.sum(x[cols]**2, axis=1)) return distance_measure_common(A, distance, alpha, R, k, epsilon)
def affinity_distance(A, alpha=0.5, R=5, k=20, epsilon=4.0)
Affinity Distance Strength Measure. Parameters ---------- A : csr_matrix Sparse NxN matrix alpha : scalar Weight for Jacobi R : integer Number of random vectors k : integer Number of relaxation passes epsilon : scalar Drop tolerance Returns ------- C : csr_matrix Sparse matrix of strength values References ---------- .. [LiBr] Oren E. Livne and Achi Brandt, "Lean Algebraic Multigrid (LAMG): Fast Graph Laplacian Linear Solver" Notes ----- No unit testing yet. Does not handle BSR matrices yet. See [LiBr]_ for more details.
2.368034
2.405611
0.98438
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, int): raise ValueError('expected integer k>0') if epsilon < 1: raise ValueError('expected epsilon>1.0') if p < 1: raise ValueError('expected p>1 or equal to numpy.inf') def distance(x): (rows, cols) = A.nonzero() if p != np.inf: avg = np.sum(np.abs(x[rows] - x[cols])**p, axis=1) / R return (avg)**(1.0 / p) else: return np.abs(x[rows] - x[cols]).max(axis=1) return distance_measure_common(A, distance, alpha, R, k, epsilon)
def algebraic_distance(A, alpha=0.5, R=5, k=20, epsilon=2.0, p=2)
Algebraic Distance Strength Measure. Parameters ---------- A : csr_matrix Sparse NxN matrix alpha : scalar Weight for Jacobi R : integer Number of random vectors k : integer Number of relaxation passes epsilon : scalar Drop tolerance p : scalar or inf p-norm of the measure Returns ------- C : csr_matrix Sparse matrix of strength values References ---------- .. [SaSaSc] Ilya Safro, Peter Sanders, and Christian Schulz, "Advanced Coarsening Schemes for Graph Partitioning" Notes ----- No unit testing yet. Does not handle BSR matrices yet. See [SaSaSc]_ for more details.
2.662921
2.676695
0.994854
# create test vectors x = relaxation_vectors(A, R, k, alpha) # apply distance measure function to vectors d = func(x) # drop distances to self (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() # remove weak connections # removes entry e from a row if e > theta * min of all entries in the row amg_core.apply_distance_filter(C.shape[0], epsilon, C.indptr, C.indices, C.data) C.eliminate_zeros() # Standardized strength values require small values be weak and large # values be strong. So, we invert the distances. C.data = 1.0 / C.data # Put an identity on the diagonal C = C + sparse.eye(C.shape[0], C.shape[1], format='csr') # Scale C by the largest magnitude entry in each row C = scale_rows_by_largest_entry(C) return C
def distance_measure_common(A, func, alpha, R, k, epsilon)
Create strength of connection matrixfrom a function applied to relaxation vectors.
6.012361
5.574771
1.078495
RowsPerBlock = U.blocksize[0] ColsPerBlock = U.blocksize[1] num_block_rows = int(U.shape[0]/RowsPerBlock) UB = np.ravel(U*B) # Apply constraints, noting that we need the conjugate of B # for use as Bi.H in local projection pyamg.amg_core.satisfy_constraints_helper(RowsPerBlock, ColsPerBlock, num_block_rows, B.shape[1], np.conjugate(np.ravel(B)), UB, np.ravel(BtBinv), U.indptr, U.indices, np.ravel(U.data)) return U
def Satisfy_Constraints(U, B, BtBinv)
U is the prolongator update. Project out components of U such that U*B = 0. Parameters ---------- U : bsr_matrix m x n sparse bsr matrix Update to the prolongator B : array n x k array of the coarse grid near nullspace vectors BtBinv : array Local inv(B_i.H*B_i) matrices for each supernode, i B_i is B restricted to the sparsity pattern of supernode i in U Returns ------- Updated U, so that U*B = 0. Update is computed by orthogonally (in 2-norm) projecting out the components of span(B) in U in a row-wise fashion. See Also -------- The principal calling routine, pyamg.aggregation.smooth.energy_prolongation_smoother
4.774827
4.82776
0.989036
weight = omega/approximate_spectral_radius(S) P = T for i in range(degree): P = P - weight*(S*P) return P
def richardson_prolongation_smoother(S, T, omega=4.0/3.0, degree=1)
Richardson prolongation smoother. Parameters ---------- S : csr_matrix, bsr_matrix Sparse NxN matrix used for smoothing. Typically, A or the "filtered matrix" obtained from A by lumping weak connections onto the diagonal of A. T : csr_matrix, bsr_matrix Tentative prolongator omega : scalar Damping parameter Returns ------- P : csr_matrix, bsr_matrix Smoothed (final) prolongator defined by P = (I - omega/rho(S) S) * T where rho(S) is an approximation to the spectral radius of S. Notes ----- Results using Richardson prolongation smoother are not precisely reproducible due to a random initial guess used for the spectral radius approximation. For precise reproducibility, set numpy.random.seed(..) to the same value before each test. Examples -------- >>> from pyamg.aggregation import richardson_prolongation_smoother >>> from pyamg.gallery import poisson >>> from scipy.sparse import coo_matrix >>> import numpy as np >>> data = np.ones((6,)) >>> row = np.arange(0,6) >>> col = np.kron([0,1],np.ones((3,))) >>> T = coo_matrix((data,(row,col)),shape=(6,2)).tocsr() >>> T.todense() matrix([[ 1., 0.], [ 1., 0.], [ 1., 0.], [ 0., 1.], [ 0., 1.], [ 0., 1.]]) >>> A = poisson((6,),format='csr') >>> P = richardson_prolongation_smoother(A,T) >>> P.todense() matrix([[ 0.64930164, 0. ], [ 1. , 0. ], [ 0.64930164, 0.35069836], [ 0.35069836, 0.64930164], [ 0. , 1. ], [ 0. , 0.64930164]])
7.645287
13.589252
0.562598
if not hasattr(A, 'rho_D_inv'): D_inv = get_diagonal(A, inv=True) D_inv_A = scale_rows(A, D_inv, copy=True) A.rho_D_inv = approximate_spectral_radius(D_inv_A) return A.rho_D_inv
def rho_D_inv_A(A)
Return the (approx.) spectral radius of D^-1 * A. Parameters ---------- A : sparse-matrix Returns ------- approximate spectral radius of diag(A)^{-1} A Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.relaxation.smoothing import rho_D_inv_A >>> from scipy.sparse import csr_matrix >>> import numpy as np >>> A = csr_matrix(np.array([[1.0,0,0],[0,2.0,0],[0,0,3.0]])) >>> print rho_D_inv_A(A) 1.0
3.541804
4.331345
0.817715
if not hasattr(A, 'rho_block_D_inv'): from scipy.sparse.linalg import LinearOperator blocksize = Dinv.shape[1] if Dinv.shape[1] != Dinv.shape[2]: raise ValueError('Dinv has incorrect dimensions') elif Dinv.shape[0] != int(A.shape[0]/blocksize): raise ValueError('Dinv and A have incompatible dimensions') Dinv = sp.sparse.bsr_matrix((Dinv, sp.arange(Dinv.shape[0]), sp.arange(Dinv.shape[0]+1)), shape=A.shape) # Don't explicitly form Dinv*A def matvec(x): return Dinv*(A*x) D_inv_A = LinearOperator(A.shape, matvec, dtype=A.dtype) A.rho_block_D_inv = approximate_spectral_radius(D_inv_A) return A.rho_block_D_inv
def rho_block_D_inv_A(A, Dinv)
Return the (approx.) spectral radius of block D^-1 * A. Parameters ---------- A : sparse-matrix size NxN Dinv : array Inverse of diagonal blocks of A size (N/blocksize, blocksize, blocksize) Returns ------- approximate spectral radius of (Dinv A) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.relaxation.smoothing import rho_block_D_inv_A >>> from pyamg.util.utils import get_block_diag >>> A = poisson((10,10), format='csr') >>> Dinv = get_block_diag(A, blocksize=4, inv_flag=True)
2.921152
2.928001
0.997661
desired_matrix = name + format M = getattr(lvl, name) if format == 'bsr': desired_matrix += str(blocksize[0])+str(blocksize[1]) if hasattr(lvl, desired_matrix): # if lvl already contains lvl.name+format pass elif M.format == format and format != 'bsr': # is base_matrix already in the correct format? setattr(lvl, desired_matrix, M) elif M.format == format and format == 'bsr': # convert to bsr with the right blocksize # tobsr() will not do anything extra if this is uneeded setattr(lvl, desired_matrix, M.tobsr(blocksize=blocksize)) else: # convert newM = getattr(M, 'to' + format)() setattr(lvl, desired_matrix, newM) return getattr(lvl, desired_matrix)
def matrix_asformat(lvl, name, format, blocksize=None)
Set a matrix to a specific format. This routine looks for the matrix "name" in the specified format as a member of the level instance, lvl. For example, if name='A', format='bsr' and blocksize=(4,4), and if lvl.Absr44 exists with the correct blocksize, then lvl.Absr is returned. If the matrix doesn't already exist, lvl.name is converted to the desired format, and made a member of lvl. Only create such persistent copies of a matrix for routines such as presmoothing and postsmoothing, where the matrix conversion is done every cycle. Calling this function can _dramatically_ increase your memory costs. Be careful with it's usage.
4.264899
4.222281
1.010094
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.arange(0, nx-1), ny - 1) +\ np.repeat(np.arange(0, nx * (ny - 1), nx), nx - 1) + nx Vert2 = Vert3 + 1 Vert4 = Vert1 + 1 Verttmp = np.meshgrid(np.arange(0, nx, dtype='float'), np.arange(0, ny, dtype='float')) Verttmp = (Verttmp[0].ravel(), Verttmp[1].ravel()) Vert = np.vstack(Verttmp).transpose() Vert[:, 0] = (1.0 / (nx - 1)) * Vert[:, 0] Vert[:, 1] = (1.0 / (ny - 1)) * Vert[:, 1] E2V1 = np.vstack((Vert1, Vert2, Vert3)).transpose() E2V2 = np.vstack((Vert1, Vert4, Vert2)).transpose() E2V = np.vstack((E2V1, E2V2)) return Vert, E2V
def regular_triangle_mesh(nx, ny)
Construct a regular triangular mesh in the unit square. Parameters ---------- nx : int Number of nodes in the x-direction ny : int Number of nodes in the y-direction Returns ------- Vert : array nx*ny x 2 vertex list E2V : array Nex x 3 element list Examples -------- >>> from pyamg.gallery import regular_triangle_mesh >>> E2V,Vert = regular_triangle_mesh(3, 2)
2.138209
2.184828
0.978663
check_input(Verts, splitting) N = Verts.shape[0] Ndof = int(len(splitting) / N) E2V = np.arange(0, N, dtype=int) # adjust name in case of multiple variables a = fname.split('.') if len(a) < 2: fname1 = a[0] fname2 = '.vtu' elif len(a) >= 2: fname1 = "".join(a[:-1]) fname2 = a[-1] else: raise ValueError('problem with fname') new_fname = fname for d in range(0, Ndof): # for each variables, write a file or open a figure if Ndof > 1: new_fname = fname1 + '_%d.' % (d+1) + fname2 cdata = splitting[(d*N):((d+1)*N)] if output == 'vtk': write_basic_mesh(Verts=Verts, E2V=E2V, mesh_type='vertex', cdata=cdata, fname=new_fname) elif output == 'matplotlib': from pylab import figure, show, plot, xlabel, ylabel, title, axis cdataF = np.where(cdata == 0)[0] cdataC = np.where(cdata == 1)[0] xC = Verts[cdataC, 0] yC = Verts[cdataC, 1] xF = Verts[cdataF, 0] yF = Verts[cdataF, 1] figure() plot(xC, yC, 'r.', xF, yF, 'b.', clip_on=True) title('C/F splitting (red=coarse, blue=fine)') xlabel('x') ylabel('y') axis('off') show() else: raise ValueError('problem with outputtype')
def vis_splitting(Verts, splitting, output='vtk', fname='output.vtu')
Coarse grid visualization for C/F splittings. Parameters ---------- Verts : {array} coordinate array (N x D) splitting : {array} coarse(1)/fine(0) flags fname : {string, file object} file to be written, e.g. 'output.vtu' output : {string} 'vtk' or 'matplotlib' Returns ------- - Displays in screen or writes data to .vtu file for use in paraview (xml 0.1 format) Notes ----- D : dimension of coordinate space N : # of vertices in the mesh represented in Verts Ndof : # of dof (= ldof * N) - simply color different points with different colors. This works best with classical AMG. - writes a file (or opens a window) for each dof - for Ndof>1, they are assumed orderd [...dof1..., ...dof2..., etc] Examples -------- >>> import numpy as np >>> from pyamg.vis.vis_coarse import vis_splitting >>> Verts = np.array([[0.0,0.0], ... [1.0,0.0], ... [0.0,1.0], ... [1.0,1.0]]) >>> splitting = np.array([0,1,0,1,1,0,1,0]) # two variables >>> vis_splitting(Verts,splitting,output='vtk',fname='output.vtu') >>> from pyamg.classical import RS >>> from pyamg.vis.vis_coarse import vis_splitting >>> from pyamg.gallery import load_example >>> data = load_example('unit_square') >>> A = data['A'].tocsr() >>> V = data['vertices'] >>> E2V = data['elements'] >>> splitting = RS(A) >>> vis_splitting(Verts=V,splitting=splitting,output='vtk', fname='output.vtu')
3.201116
2.960748
1.081185
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): raise ValueError('E2V should be of type integer') if E2V.min() != 0: warnings.warn('element indices begin at %d' % E2V.min()) if Agg is not None: if Agg.shape[1] > Agg.shape[0]: raise ValueError('Agg should be of size Npts x Nagg') if A is not None: if Agg is not None: if (A.shape[0] != A.shape[1]) or (A.shape[0] != Agg.shape[0]): raise ValueError('expected square matrix A\ and compatible with Agg') else: raise ValueError('problem with check_input') if splitting is not None: splitting = splitting.ravel() if Verts is not None: if (len(splitting) % Verts.shape[0]) != 0: raise ValueError('splitting must be a multiple of N') else: raise ValueError('problem with check_input') if mesh_type is not None: valid_mesh_types = ('vertex', 'tri', 'quad', 'tet', 'hex') if mesh_type not in valid_mesh_types: raise ValueError('mesh_type should be %s' % ' or '.join(valid_mesh_types))
def check_input(Verts=None, E2V=None, Agg=None, A=None, splitting=None, mesh_type=None)
Check input for local functions.
2.24921
2.255279
0.997309
if not isspmatrix_csr(S): raise TypeError('expected csr_matrix') S = remove_diagonal(S) T = S.T.tocsr() # transpose S for efficient column access splitting = np.empty(S.shape[0], dtype='intc') influence = np.zeros((S.shape[0],), dtype='intc') amg_core.rs_cf_splitting(S.shape[0], S.indptr, S.indices, T.indptr, T.indices, influence, splitting) if second_pass: amg_core.rs_cf_splitting_pass2(S.shape[0], S.indptr, S.indices, splitting) return splitting
def RS(S, second_pass=False)
Compute a C/F splitting using Ruge-Stuben coarsening Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) second_pass : bool, default False Perform second pass of classical AMG coarsening. Can be important for classical AMG interpolation. Typically not done in parallel (e.g. Hypre). Returns ------- splitting : ndarray Array of length of S of ones (coarse) and zeros (fine) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import RS >>> S = poisson((7,), format='csr') # 1D mesh with 7 vertices >>> splitting = RS(S) See Also -------- amg_core.rs_cf_splitting References ---------- .. [1] Ruge JW, Stuben K. "Algebraic multigrid (AMG)" In Multigrid Methods, McCormick SF (ed.), Frontiers in Applied Mathematics, vol. 3. SIAM: Philadelphia, PA, 1987; 73-130.
3.688604
3.248005
1.135652
S = remove_diagonal(S) weights, G, S, T = preprocess(S) return MIS(G, weights)
def PMIS(S)
C/F splitting using the Parallel Modified Independent Set method. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) Returns ------- splitting : ndarray Array of length of S of ones (coarse) and zeros (fine) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import PMIS >>> S = poisson((7,), format='csr') # 1D mesh with 7 vertices >>> splitting = PMIS(S) See Also -------- MIS References ---------- .. [6] Hans De Sterck, Ulrike M Yang, and Jeffrey J Heys "Reducing complexity in parallel algebraic multigrid preconditioners" SIAM Journal on Matrix Analysis and Applications 2006; 27:1019-1039.
14.150414
16.440048
0.860728
S = remove_diagonal(S) weights, G, S, T = preprocess(S, coloring_method=method) return MIS(G, weights)
def PMISc(S, method='JP')
C/F splitting using Parallel Modified Independent Set (in color). PMIS-c, or PMIS in color, improves PMIS by perturbing the initial random weights with weights determined by a vertex coloring. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) method : string Algorithm used to compute the initial vertex coloring: * 'MIS' - Maximal Independent Set * 'JP' - Jones-Plassmann (parallel) * 'LDF' - Largest-Degree-First (parallel) Returns ------- splitting : array Array of length of S of ones (coarse) and zeros (fine) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import PMISc >>> S = poisson((7,), format='csr') # 1D mesh with 7 vertices >>> splitting = PMISc(S) See Also -------- MIS References ---------- .. [7] David M. Alber and Luke N. Olson "Parallel coarse-grid selection" Numerical Linear Algebra with Applications 2007; 14:611-643.
14.563068
16.4884
0.883231
if not isspmatrix_csr(S): raise TypeError('expected csr_matrix') S = remove_diagonal(S) colorid = 0 if color: colorid = 1 T = S.T.tocsr() # transpose S for efficient column access splitting = np.empty(S.shape[0], dtype='intc') amg_core.cljp_naive_splitting(S.shape[0], S.indptr, S.indices, T.indptr, T.indices, splitting, colorid) return splitting
def CLJP(S, color=False)
Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------- splitting : array Array of length of S of ones (coarse) and zeros (fine) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical.split import CLJP >>> S = poisson((7,), format='csr') # 1D mesh with 7 vertices >>> splitting = CLJP(S) See Also -------- MIS, PMIS, CLJPc References ---------- .. [8] David M. Alber and Luke N. Olson "Parallel coarse-grid selection" Numerical Linear Algebra with Applications 2007; 14:611-643.
4.421044
4.415728
1.001204
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.indices, -1, 1, 0, mis, weights, -1) else: if maxiter < 0: raise ValueError('maxiter must be >= 0') fn(G.shape[0], G.indptr, G.indices, -1, 1, 0, mis, weights, maxiter) return mis
def MIS(G, weights, maxiter=None)
Compute a maximal independent set of a graph in parallel. Parameters ---------- G : csr_matrix Matrix graph, G[i,j] != 0 indicates an edge weights : ndarray Array of weights for each vertex in the graph G maxiter : int Maximum number of iterations (default: None) Returns ------- mis : array Array of length of G of zeros/ones indicating the independent set Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import MIS >>> import numpy as np >>> G = poisson((7,), format='csr') # 1D mesh with 7 vertices >>> w = np.ones((G.shape[0],1)).ravel() >>> mis = MIS(G,w) See Also -------- fn = amg_core.maximal_independent_set_parallel
2.850228
2.886451
0.987451
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.indices, S.indptr), shape=(N, N)) T = S.T.tocsr() # transpose S for efficient column access G = S + T # form graph (must be symmetric) G.data[:] = 1 weights = np.ravel(T.sum(axis=1)) # initial weights # weights -= T.diagonal() # discount self loops if coloring_method is None: weights = weights + sp.rand(len(weights)) else: coloring = vertex_coloring(G, coloring_method) num_colors = coloring.max() + 1 weights = weights + (sp.rand(len(weights)) + coloring)/num_colors return (weights, G, S, T)
def preprocess(S, coloring_method=None)
Preprocess splitting functions. Parameters ---------- S : csr_matrix Strength of connection matrix method : string Algorithm used to compute the vertex coloring: * 'MIS' - Maximal Independent Set * 'JP' - Jones-Plassmann (parallel) * 'LDF' - Largest-Degree-First (parallel) Returns ------- weights: ndarray Weights from a graph coloring of G S : csr_matrix Strength matrix with ones T : csr_matrix transpose of S G : csr_matrix union of S and T Notes ----- Performs the following operations: - Checks input strength of connection matrix S - Replaces S.data with ones - Creates T = S.T in CSR format - Creates G = S union T in CSR format - Creates random weights - Augments weights with graph coloring (if use_color == True)
3.693399
3.633974
1.016353
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)
def load_example(name)
Load an example problem by name. Parameters ---------- name : string (e.g. 'airfoil') Name of the example to load Notes ----- Each example is stored in a dictionary with the following keys: - 'A' : sparse matrix - 'B' : near-nullspace candidates - 'vertices' : dense array of nodal coordinates - 'elements' : dense array of element indices Current example names are:%s Examples -------- >>> from pyamg.gallery import load_example >>> ex = load_example('knot')
3.823026
5.098467
0.749838
n = A.shape[0] # problem size 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 method == 'concurrent': gauss_seidel_indexed(A, e, z, indices=Findex, iterations=1) else: raise NotImplementedError('method not recognized: need habituated ' 'or concurrent') enorm_old = enorm enorm = norm(e) rhok_old = rhok rhok = enorm / enorm_old it += 1 # criteria 1 -- fast convergence if rhok < 0.1 * thetacr: break # criteria 2 -- at least nu iters, small relative change in CF (<0.1) elif ((abs(rhok - rhok_old) / rhok) < 0.1) and (it >= nu): break return rhok, e
def _CRsweep(A, B, Findex, Cindex, nu, thetacr, method)
Perform CR sweeps on a target vector. Internal function called by CR. Performs habituated or concurrent relaxation sweeps on target vector. Stops when either (i) very fast convergence, CF < 0.1*thetacr, are observed, or at least a given number of sweeps have been performed and the relative change in CF < 0.1. Parameters ---------- A : csr_matrix B : array like Target near null space mode Findex : array like List of F indices in current splitting Cindex : array like List of C indices in current splitting nu : int minimum number of relaxation sweeps to do thetacr Desired convergence factor Returns ------- rho : float Convergence factor of last iteration e : array like Smoothed error vector
4.720831
3.781673
1.248345
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() # 1. B = A.multiply(A).tocsc() # power(A,2) inconsistent in numpy, scipy.sparse d = B.diagonal().ravel() # 2. beta = B * x betabar = (1.0/n) * np.dot(x, beta) stdev = rowsum_stdev(x, beta) # 3 while stdev > tol and it < maxiter: for i in range(0, n): # solve equation x_i, keeping x_j's fixed # see equation (12) c2 = (n-1)*d[i] c1 = (n-2)*(beta[i] - d[i]*x[i]) c0 = -d[i]*x[i]*x[i] + 2*beta[i]*x[i] - n*betabar if (-c0 < 1e-14): print('warning: A nearly un-binormalizable...') return A else: # see equation (12) xnew = (2*c0)/(-c1 - np.sqrt(c1*c1 - 4*c0*c2)) dx = xnew - x[i] # here we assume input matrix is symmetric since we grab a row of B # instead of a column ii = B.indptr[i] iii = B.indptr[i+1] dot_Bcol = np.dot(x[B.indices[ii:iii]], B.data[ii:iii]) betabar = betabar + (1.0/n)*dx*(dot_Bcol + beta[i] + d[i]*dx) beta[B.indices[ii:iii]] += dx*B.data[ii:iii] x[i] = xnew stdev = rowsum_stdev(x, beta) it += 1 # rescale for unit 2-norm d = np.sqrt(x) D = spdiags(d.ravel(), [0], n, n) C = D * A * D C = C.tocsr() beta = C.multiply(C).sum(axis=1) scale = np.sqrt((1.0/n) * np.sum(beta)) return (1/scale)*C
def binormalize(A, tol=1e-5, maxiter=10)
Binormalize matrix A. Attempt to create unit l_1 norm rows. Parameters ---------- A : csr_matrix sparse matrix (n x n) tol : float tolerance x : array guess at the diagonal maxiter : int maximum number of iterations to try Returns ------- C : csr_matrix diagonally scaled A, C=DAD Notes ----- - Goal: Scale A so that l_1 norm of the rows are equal to 1: - B = DAD - want row sum of B = 1 - easily done with tol=0 if B=DA, but this is not symmetric - algorithm is O(N log (1.0/tol)) Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import binormalize >>> A = poisson((10,),format='csr') >>> C = binormalize(A) References ---------- .. [1] Livne, Golub, "Scaling by Binormalization" Tech Report SCCM-03-12, SCCM, Stanford, 2003 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.3.1679
4.095068
4.218492
0.970742
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
def rowsum_stdev(x, beta)
r"""Compute row sum standard deviation. Compute for approximation x, the std dev of the row sums s(x) = ( 1/n \sum_k (x_k beta_k - betabar)^2 )^(1/2) with betabar = 1/n dot(beta,x) Parameters ---------- x : array beta : array Returns ------- s(x)/betabar : float Notes ----- equation (7) in Livne/Golub
4.006404
3.424191
1.170029
if a >= b or a <= 0: raise ValueError('invalid interval [%s,%s]' % (a, b)) # Chebyshev roots for the interval [-1,1] std_roots = np.cos(np.pi * (np.arange(degree) + 0.5) / degree) # Chebyshev roots for the interval [a,b] scaled_roots = 0.5 * (b-a) * (1 + std_roots) + a # Compute monic polynomial coefficients of polynomial with scaled roots scaled_poly = np.poly(scaled_roots) # Scale coefficients to enforce C(0) = 1.0 scaled_poly /= np.polyval(scaled_poly, 0) return scaled_poly
def chebyshev_polynomial_coefficients(a, b, degree)
Chebyshev polynomial coefficients for the interval [a,b]. Parameters ---------- a,b : float The left and right endpoints of the interval. degree : int Degree of desired Chebyshev polynomial Returns ------- Coefficients of the Chebyshev polynomial C(t) with minimum magnitude on the interval [a,b] such that C(0) = 1.0. The coefficients are returned in descending order. Notes ----- a,b typically represent the interval of the spectrum for some matrix that you wish to damp with a Chebyshev smoother. Examples -------- >>> from pyamg.relaxation.chebyshev import chebyshev_polynomial_coefficients >>> print chebyshev_polynomial_coefficients(1.0,2.0, 3) [-0.32323232 1.45454545 -2.12121212 1. ]
3.70764
4.238808
0.874689
# std_roots = np.cos(np.pi * (np.arange(degree) + 0.5)/ degree) # print std_roots roots = rho/2.0 * \ (1.0 - np.cos(2*np.pi*(np.arange(degree, dtype='float64') + 1)/(2.0*degree+1.0))) # print roots roots = 1.0/roots # S_coeffs = list(-np.poly(roots)[1:][::-1]) S = np.poly(roots)[::-1] # monomial coefficients of S error propagator SSA_max = rho/((2.0*degree+1.0)**2) # upper bound spectral radius of S^2A S_hat = np.polymul(S, S) # monomial coefficients of \hat{S} propagator S_hat = np.hstack(((-1.0/SSA_max)*S_hat, [1])) # coeff for combined error propagator \hat{S}S coeffs = np.polymul(S_hat, S) coeffs = -coeffs[:-1] # coeff for smoother return (coeffs, roots)
def mls_polynomial_coefficients(rho, degree)
Determine the coefficients for a MLS polynomial smoother. Parameters ---------- rho : float Spectral radius of the matrix in question degree : int Degree of polynomial coefficients to generate Returns ------- Tuple of arrays (coeffs,roots) containing the coefficients for the (symmetric) polynomial smoother and the roots of polynomial prolongation smoother. The coefficients of the polynomial are in descending order References ---------- .. [1] Parallel multigrid smoothing: polynomial versus Gauss--Seidel M. F. Adams, M. Brezina, J. J. Hu, and R. S. Tuminaro J. Comp. Phys., 188 (2003), pp. 593--610 Examples -------- >>> from pyamg.relaxation.chebyshev import mls_polynomial_coefficients >>> mls = mls_polynomial_coefficients(2.0, 2) >>> print mls[0] # coefficients [ 6.4 -48. 144. -220. 180. -75.8 14.5] >>> print mls[1] # roots [ 1.4472136 0.5527864]
5.72869
6.253689
0.91605
levels = [multilevel_solver.level()] # convert A to csr if not isspmatrix_csr(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 be convertible to csr_matrix') # preprocess A A = A.asfptype() if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix') levels[-1].A = A while len(levels) < max_levels and levels[-1].A.shape[0] > max_coarse: extend_hierarchy(levels, strength, CF, keep) ml = multilevel_solver(levels, **kwargs) change_smoothers(ml, presmoother, postsmoother) return ml
def ruge_stuben_solver(A, strength=('classical', {'theta': 0.25}), CF='RS', presmoother=('gauss_seidel', {'sweep': 'symmetric'}), postsmoother=('gauss_seidel', {'sweep': 'symmetric'}), max_levels=10, max_coarse=10, keep=False, **kwargs)
Create a multilevel solver using Classical AMG (Ruge-Stuben AMG). Parameters ---------- A : csr_matrix Square matrix in CSR format strength : ['symmetric', 'classical', 'evolution', 'distance', 'algebraic_distance','affinity', 'energy_based', 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. CF : string Method used for coarse grid selection (C/F splitting) Supported methods are RS, PMIS, PMISc, CLJP, CLJPc, and CR. presmoother : string or dict Method used for presmoothing at each level. Method-specific parameters may be passed in using a tuple, e.g. presmoother=('gauss_seidel',{'sweep':'symmetric}), the default. postsmoother : string or dict Postsmoothing method with the same usage as presmoother 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. keep: bool Flag to indicate keeping extra operators in the hierarchy for diagnostics. For example, if True, then strength of connection (C) and tentative prolongation (T) are kept. Returns ------- ml : multilevel_solver Multigrid hierarchy of matrices and prolongation operators Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg import ruge_stuben_solver >>> A = poisson((10,),format='csr') >>> ml = ruge_stuben_solver(A,max_coarse=3) Notes ----- "coarse_solver" is an optional argument and is the solver used at the coarsest grid. The default is a pseudo-inverse. Most simply, coarse_solver can be one of ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ]. Additionally, coarse_solver 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. See [2001TrOoSc]_ for additional details. References ---------- .. [2001TrOoSc] Trottenberg, U., Oosterlee, C. W., and Schuller, A., "Multigrid" San Diego: Academic Press, 2001. Appendix A See Also -------- aggregation.smoothed_aggregation_solver, multilevel_solver, aggregation.rootnode_solver
3.739098
4.024446
0.929096
def unpack_arg(v): if isinstance(v, tuple): return v[0], v[1] else: return v, {} A = levels[-1].A # Compute the strength-of-connection matrix C, where larger # C[i,j] denote stronger couplings between i and j. fn, kwargs = unpack_arg(strength) if fn == 'symmetric': C = symmetric_strength_of_connection(A, **kwargs) elif fn == 'classical': C = classical_strength_of_connection(A, **kwargs) elif fn == 'distance': C = distance_strength_of_connection(A, **kwargs) elif (fn == 'ode') or (fn == 'evolution'): C = evolution_strength_of_connection(A, **kwargs) elif fn == 'energy_based': C = energy_based_strength_of_connection(A, **kwargs) elif fn == 'algebraic_distance': C = algebraic_distance(A, **kwargs) elif fn == 'affinity': C = affinity_distance(A, **kwargs) elif fn is None: C = A else: raise ValueError('unrecognized strength of connection method: %s' % str(fn)) # Generate the C/F splitting fn, kwargs = unpack_arg(CF) if fn == 'RS': splitting = split.RS(C, **kwargs) elif fn == 'PMIS': splitting = split.PMIS(C, **kwargs) elif fn == 'PMISc': splitting = split.PMISc(C, **kwargs) elif fn == 'CLJP': splitting = split.CLJP(C, **kwargs) elif fn == 'CLJPc': splitting = split.CLJPc(C, **kwargs) elif fn == 'CR': splitting = CR(C, **kwargs) else: raise ValueError('unknown C/F splitting method (%s)' % CF) # Generate the interpolation matrix that maps from the coarse-grid to the # fine-grid P = direct_interpolation(A, C, splitting) # Generate the restriction matrix that maps from the fine-grid to the # coarse-grid R = P.T.tocsr() # Store relevant information for this level if keep: levels[-1].C = C # strength of connection matrix levels[-1].splitting = splitting # C/F splitting levels[-1].P = P # prolongation operator levels[-1].R = R # restriction operator levels.append(multilevel_solver.level()) # Form next level through Galerkin product A = R * A * P levels[-1].A = A
def extend_hierarchy(levels, strength, CF, keep)
Extend the multigrid hierarchy.
3.22032
3.156437
1.020239
A = poisson((100, 100), format='csr') # 2D FD Poisson problem B = None # no near-null spaces guesses for SA b = sp.rand(A.shape[0], 1) # a random right-hand side # use AMG based on Smoothed Aggregation (SA) and display info mls = smoothed_aggregation_solver(A, B=B) print(mls) # Solve Ax=b with no acceleration ('standalone' solver) standalone_residuals = [] x = mls.solve(b, tol=1e-10, accel=None, residuals=standalone_residuals) # Solve Ax=b with Conjugate Gradient (AMG as a preconditioner to CG) accelerated_residuals = [] x = mls.solve(b, tol=1e-10, accel='cg', residuals=accelerated_residuals) del x # Compute relative residuals standalone_residuals = \ np.array(standalone_residuals) / standalone_residuals[0] accelerated_residuals = \ np.array(accelerated_residuals) / accelerated_residuals[0] # Compute (geometric) convergence factors factor1 = standalone_residuals[-1]**(1.0/len(standalone_residuals)) factor2 = accelerated_residuals[-1]**(1.0/len(accelerated_residuals)) print(" MG convergence factor: %g" % (factor1)) print("MG with CG acceleration convergence factor: %g" % (factor2)) # Plot convergence history try: import matplotlib.pyplot as plt plt.figure() plt.title('Convergence History') plt.xlabel('Iteration') plt.ylabel('Relative Residual') plt.semilogy(standalone_residuals, label='Standalone', linestyle='-', marker='o') plt.semilogy(accelerated_residuals, label='Accelerated', linestyle='-', marker='s') plt.legend() plt.show() except ImportError: print("\n\nNote: pylab not available on your system.")
def demo()
Outline basic demo.
3.599984
3.535178
1.018332
dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
def ensure_dirs(filename)
Make sure the directories exist for `filename`.
1.761134
1.912103
0.921045
if not isspmatrix_csr(C): raise TypeError('expected csr_matrix') if C.shape[0] != C.shape[1]: raise ValueError('expected square matrix') index_type = C.indptr.dtype num_rows = C.shape[0] Tj = np.empty(num_rows, dtype=index_type) # stores the aggregate #s Cpts = np.empty(num_rows, dtype=index_type) # stores the Cpts fn = amg_core.standard_aggregation num_aggregates = fn(num_rows, C.indptr, C.indices, Tj, Cpts) Cpts = Cpts[:num_aggregates] if num_aggregates == 0: # return all zero matrix and no Cpts return csr_matrix((num_rows, 1), dtype='int8'),\ np.array([], dtype=index_type) else: shape = (num_rows, num_aggregates) if Tj.min() == -1: # some nodes not aggregated mask = Tj != -1 row = np.arange(num_rows, dtype=index_type)[mask] col = Tj[mask] data = np.ones(len(col), dtype='int8') return coo_matrix((data, (row, col)), shape=shape).tocsr(), Cpts else: # all nodes aggregated Tp = np.arange(num_rows+1, dtype=index_type) Tx = np.ones(len(Tj), dtype='int8') return csr_matrix((Tx, Tj, Tp), shape=shape), Cpts
def standard_aggregation(C)
Compute the sparsity pattern of the tentative prolongator. Parameters ---------- C : csr_matrix strength of connection matrix Returns ------- AggOp : csr_matrix aggregation operator which determines the sparsity pattern of the tentative prolongator Cpts : array array of Cpts, i.e., Cpts[i] = root node of aggregate i Examples -------- >>> from scipy.sparse import csr_matrix >>> from pyamg.gallery import poisson >>> from pyamg.aggregation.aggregate import standard_aggregation >>> A = poisson((4,), format='csr') # 1D mesh with 4 vertices >>> A.todense() matrix([[ 2., -1., 0., 0.], [-1., 2., -1., 0.], [ 0., -1., 2., -1.], [ 0., 0., -1., 2.]]) >>> standard_aggregation(A)[0].todense() # two aggregates matrix([[1, 0], [1, 0], [0, 1], [0, 1]], dtype=int8) >>> A = csr_matrix([[1,0,0],[0,1,1],[0,1,1]]) >>> A.todense() # first vertex is isolated matrix([[1, 0, 0], [0, 1, 1], [0, 1, 1]]) >>> standard_aggregation(A)[0].todense() # one aggregate matrix([[0], [1], [1]], dtype=int8) See Also -------- amg_core.standard_aggregation
2.897086
2.796749
1.035876
if not isspmatrix_csr(C): raise TypeError('expected csr_matrix') if C.shape[0] != C.shape[1]: raise ValueError('expected square matrix') index_type = C.indptr.dtype num_rows = C.shape[0] Tj = np.empty(num_rows, dtype=index_type) # stores the aggregate #s Cpts = np.empty(num_rows, dtype=index_type) # stores the Cpts fn = amg_core.naive_aggregation num_aggregates = fn(num_rows, C.indptr, C.indices, Tj, Cpts) Cpts = Cpts[:num_aggregates] Tj = Tj - 1 if num_aggregates == 0: # all zero matrix return csr_matrix((num_rows, 1), dtype='int8'), Cpts else: shape = (num_rows, num_aggregates) # all nodes aggregated Tp = np.arange(num_rows+1, dtype=index_type) Tx = np.ones(len(Tj), dtype='int8') return csr_matrix((Tx, Tj, Tp), shape=shape), Cpts
def naive_aggregation(C)
Compute the sparsity pattern of the tentative prolongator. Parameters ---------- C : csr_matrix strength of connection matrix Returns ------- AggOp : csr_matrix aggregation operator which determines the sparsity pattern of the tentative prolongator Cpts : array array of Cpts, i.e., Cpts[i] = root node of aggregate i Examples -------- >>> from scipy.sparse import csr_matrix >>> from pyamg.gallery import poisson >>> from pyamg.aggregation.aggregate import naive_aggregation >>> A = poisson((4,), format='csr') # 1D mesh with 4 vertices >>> A.todense() matrix([[ 2., -1., 0., 0.], [-1., 2., -1., 0.], [ 0., -1., 2., -1.], [ 0., 0., -1., 2.]]) >>> naive_aggregation(A)[0].todense() # two aggregates matrix([[1, 0], [1, 0], [0, 1], [0, 1]], dtype=int8) >>> A = csr_matrix([[1,0,0],[0,1,1],[0,1,1]]) >>> A.todense() # first vertex is isolated matrix([[1, 0, 0], [0, 1, 1], [0, 1, 1]]) >>> naive_aggregation(A)[0].todense() # two aggregates matrix([[1, 0], [0, 1], [0, 1]], dtype=int8) See Also -------- amg_core.naive_aggregation Notes ----- Differs from standard aggregation. Each dof is considered. If it has been aggregated, skip over. Otherwise, put dof and any unaggregated neighbors in an aggregate. Results in possibly much higher complexities than standard aggregation.
3.230784
2.956922
1.092617
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_like(C.data).astype(float) elif distance == 'abs': data = abs(C.data) elif distance == 'inv': data = 1.0/abs(C.data) elif distance is 'same': data = C.data elif distance is 'min': data = C.data - C.data.min() else: raise ValueError('unrecognized value distance=%s' % distance) if C.dtype == complex: data = np.real(data) assert(data.min() >= 0) G = C.__class__((data, C.indices, C.indptr), shape=C.shape) num_seeds = int(min(max(ratio * G.shape[0], 1), G.shape[0])) distances, clusters, seeds = lloyd_cluster(G, num_seeds, maxiter=maxiter) row = (clusters >= 0).nonzero()[0] col = clusters[row] data = np.ones(len(row), dtype='int8') AggOp = coo_matrix((data, (row, col)), shape=(G.shape[0], num_seeds)).tocsr() return AggOp, seeds
def lloyd_aggregation(C, ratio=0.03, distance='unit', maxiter=10)
Aggregate nodes using Lloyd Clustering. Parameters ---------- C : csr_matrix strength of connection matrix ratio : scalar Fraction of the nodes which will be seeds. distance : ['unit','abs','inv',None] Distance assigned to each edge of the graph G used in Lloyd clustering For each nonzero value C[i,j]: ======= =========================== 'unit' G[i,j] = 1 'abs' G[i,j] = abs(C[i,j]) 'inv' G[i,j] = 1.0/abs(C[i,j]) 'same' G[i,j] = C[i,j] 'sub' G[i,j] = C[i,j] - min(C) ======= =========================== maxiter : int Maximum number of iterations to perform Returns ------- AggOp : csr_matrix aggregation operator which determines the sparsity pattern of the tentative prolongator seeds : array array of Cpts, i.e., Cpts[i] = root node of aggregate i See Also -------- amg_core.standard_aggregation Examples -------- >>> from scipy.sparse import csr_matrix >>> from pyamg.gallery import poisson >>> from pyamg.aggregation.aggregate import lloyd_aggregation >>> A = poisson((4,), format='csr') # 1D mesh with 4 vertices >>> A.todense() matrix([[ 2., -1., 0., 0.], [-1., 2., -1., 0.], [ 0., -1., 2., -1.], [ 0., 0., -1., 2.]]) >>> lloyd_aggregation(A)[0].todense() # one aggregate matrix([[1], [1], [1], [1]], dtype=int8) >>> # more seeding for two aggregates >>> Agg = lloyd_aggregation(A,ratio=0.5)[0].todense()
2.678319
2.572109
1.041293
blocksize = A.blocksize[0] BlockIndx = int(i/blocksize) rowstart = A.indptr[BlockIndx] rowend = A.indptr[BlockIndx+1] localRowIndx = i % blocksize # Get z indys = A.data[rowstart:rowend, localRowIndx, :].nonzero() z = A.data[rowstart:rowend, localRowIndx, :][indys[0], indys[1]] colindx = np.zeros((1, z.__len__()), dtype=np.int32) counter = 0 for j in range(rowstart, rowend): coloffset = blocksize*A.indices[j] indys = A.data[j, localRowIndx, :].nonzero()[0] increment = indys.shape[0] colindx[0, counter:(counter+increment)] = coloffset + indys counter += increment return np.mat(z).T, colindx[0, :]
def BSR_Get_Row(A, i)
Return row i in BSR matrix A. Only nonzero entries are returned Parameters ---------- A : bsr_matrix Input matrix i : int Row number Returns ------- z : array Actual nonzero values for row i colindx Array of column indices for the nonzeros of row i Examples -------- >>> from numpy import array >>> from scipy.sparse import bsr_matrix >>> from pyamg.util.BSR_utils import BSR_Get_Row >>> indptr = array([0,2,3,6]) >>> indices = array([0,2,2,0,1,2]) >>> data = array([1,2,3,4,5,6]).repeat(4).reshape(6,2,2) >>> B = bsr_matrix( (data,indices,indptr), shape=(6,6) ) >>> Brow = BSR_Get_Row(B,2) >>> print Brow[1] [4 5]
3.251575
3.892223
0.835403
blocksize = A.blocksize[0] BlockIndx = int(i/blocksize) rowstart = A.indptr[BlockIndx] rowend = A.indptr[BlockIndx+1] localRowIndx = i % blocksize # for j in range(rowstart, rowend): # indys = A.data[j,localRowIndx,:].nonzero()[0] # increment = indys.shape[0] # A.data[j,localRowIndx,indys] = x indys = A.data[rowstart:rowend, localRowIndx, :].nonzero() A.data[rowstart:rowend, localRowIndx, :][indys[0], indys[1]] = x
def BSR_Row_WriteScalar(A, i, x)
Write a scalar at each nonzero location in row i of BSR matrix A. Parameters ---------- A : bsr_matrix Input matrix i : int Row number x : float Scalar to overwrite nonzeros of row i in A Returns ------- A : bsr_matrix All nonzeros in row i of A have been overwritten with x. If x is a vector, the first length(x) nonzeros in row i of A have been overwritten with entries from x Examples -------- >>> from numpy import array >>> from scipy.sparse import bsr_matrix >>> from pyamg.util.BSR_utils import BSR_Row_WriteScalar >>> indptr = array([0,2,3,6]) >>> indices = array([0,2,2,0,1,2]) >>> data = array([1,2,3,4,5,6]).repeat(4).reshape(6,2,2) >>> B = bsr_matrix( (data,indices,indptr), shape=(6,6) ) >>> BSR_Row_WriteScalar(B,5,22)
2.90578
3.550706
0.818367
blocksize = A.blocksize[0] BlockIndx = int(i/blocksize) rowstart = A.indptr[BlockIndx] rowend = A.indptr[BlockIndx+1] localRowIndx = i % blocksize # like matlab slicing: x = x.__array__().reshape((max(x.shape),)) # counter = 0 # for j in range(rowstart, rowend): # indys = A.data[j,localRowIndx,:].nonzero()[0] # increment = min(indys.shape[0], blocksize) # A.data[j,localRowIndx,indys] = x[counter:(counter+increment), 0] # counter += increment indys = A.data[rowstart:rowend, localRowIndx, :].nonzero() A.data[rowstart:rowend, localRowIndx, :][indys[0], indys[1]] = x
def BSR_Row_WriteVect(A, i, x)
Overwrite the nonzeros in row i of BSR matrix A with the vector x. length(x) and nnz(A[i,:]) must be equivalent Parameters ---------- A : bsr_matrix Matrix assumed to be in BSR format i : int Row number x : array Array of values to overwrite nonzeros in row i of A Returns ------- A : bsr_matrix The nonzeros in row i of A have been overwritten with entries from x. x must be same length as nonzeros of row i. This is guaranteed when this routine is used with vectors derived form Get_BSR_Row Examples -------- >>> from numpy import array >>> from scipy.sparse import bsr_matrix >>> from pyamg.util.BSR_utils import BSR_Row_WriteVect >>> indptr = array([0,2,3,6]) >>> indices = array([0,2,2,0,1,2]) >>> data = array([1,2,3,4,5,6]).repeat(4).reshape(6,2,2) >>> B = bsr_matrix( (data,indices,indptr), shape=(6,6) ) >>> BSR_Row_WriteVect(B,5,array([11,22,33,44,55,66]))
3.249366
4.017578
0.808787
if not isspmatrix_csr(A): raise TypeError('expected csr_matrix for A') if not isspmatrix_csr(C): raise TypeError('expected csr_matrix for C') # Interpolation weights are computed based on entries in A, but subject to # the sparsity pattern of C. So, copy the entries of A into the # sparsity pattern of C. C = C.copy() C.data[:] = 1.0 C = C.multiply(A) Pp = np.empty_like(A.indptr) amg_core.rs_direct_interpolation_pass1(A.shape[0], C.indptr, C.indices, splitting, Pp) nnz = Pp[-1] Pj = np.empty(nnz, dtype=Pp.dtype) Px = np.empty(nnz, dtype=A.dtype) amg_core.rs_direct_interpolation_pass2(A.shape[0], A.indptr, A.indices, A.data, C.indptr, C.indices, C.data, splitting, Pp, Pj, Px) return csr_matrix((Px, Pj, Pp))
def direct_interpolation(A, C, splitting)
Create prolongator using direct interpolation. Parameters ---------- A : csr_matrix NxN matrix in CSR format C : csr_matrix Strength-of-Connection matrix Must have zero diagonal splitting : array C/F splitting stored in an array of length N Returns ------- P : csr_matrix Prolongator using direct interpolation Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.classical import direct_interpolation >>> import numpy as np >>> A = poisson((5,),format='csr') >>> splitting = np.array([1,0,1,0,1], dtype='intc') >>> P = direct_interpolation(A, A, splitting) >>> print P.todense() [[ 1. 0. 0. ] [ 0.5 0.5 0. ] [ 0. 1. 0. ] [ 0. 0.5 0.5] [ 0. 0. 1. ]]
3.247758
3.591913
0.904186
for j in range(k): Qloc = Q[j] v[j:j+2] = np.dot(Qloc, v[j:j+2])
def apply_givens(Q, v, k)
Apply the first k Givens rotations in Q to v. Parameters ---------- Q : list list of consecutive 2x2 Givens rotations v : array vector to apply the rotations to k : int number of rotations to apply. Returns ------- v is changed in place Notes ----- This routine is specialized for GMRES. It assumes that the first Givens rotation is for dofs 0 and 1, the second Givens rotation is for dofs 1 and 2, and so on.
3.891933
4.021652
0.967745
eps = float(epsilon) # for brevity 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)*CC + (-4*eps + 2)*SS c = (-1*eps - 1)*CC + (-1*eps - 1)*SS + (-3*eps + 3)*CS d = (-4*eps + 2)*CC + (2*eps - 4)*SS e = (8*eps + 8)*CC + (8*eps + 8)*SS stencil = np.array([[a, b, c], [d, e, d], [c, b, a]]) / 6.0 elif type == 'FD': a = 0.5*(eps - 1)*CS b = -(eps*SS + CC) c = -a d = -(eps*CC + SS) e = 2.0*(eps + 1) stencil = np.array([[a, b, c], [d, e, d], [c, b, a]]) return stencil
def diffusion_stencil_2d(epsilon=1.0, theta=0.0, type='FE')
Rotated Anisotropic diffusion in 2d of the form. -div Q A Q^T grad u Q = [cos(theta) -sin(theta)] [sin(theta) cos(theta)] A = [1 0 ] [0 eps ] Parameters ---------- epsilon : float, optional Anisotropic diffusion coefficient: -div A grad u, where A = [1 0; 0 epsilon]. The default is isotropic, epsilon=1.0 theta : float, optional Rotation angle `theta` in radians defines -div Q A Q^T grad, where Q = [cos(`theta`) -sin(`theta`); sin(`theta`) cos(`theta`)]. type : {'FE','FD'} Specifies the discretization as Q1 finite element (FE) or 2nd order finite difference (FD) The default is `theta` = 0.0 Returns ------- stencil : numpy array A 3x3 diffusion stencil See Also -------- stencil_grid, poisson Notes ----- Not all combinations are supported. Examples -------- >>> import scipy as sp >>> from pyamg.gallery.diffusion import diffusion_stencil_2d >>> sten = diffusion_stencil_2d(epsilon=0.0001,theta=sp.pi/6,type='FD') >>> print sten [[-0.2164847 -0.750025 0.2164847] [-0.250075 2.0002 -0.250075 ] [ 0.2164847 -0.750025 -0.2164847]]
2.480978
2.671026
0.928848
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], [0, -sth, cth]]) Rphi = Matrix([[cphi, sphi, 0], [-sphi, cphi, 0], [0, 0, 1]]) Q = Rpsi * Rth * Rphi epsy, epsz = symbols('epsy, epsz') A = Matrix([[1, 0, 0], [0, epsy, 0], [0, 0, epsz]]) D = Q * A * Q.T for i in range(3): for j in range(3): print('D[%d, %d] = %s' % (i, j, D[i, j]))
def _symbolic_rotation_helper()
Use SymPy to generate the 3D rotation matrix and products for diffusion_stencil_3d.
1.936584
1.855794
1.043534
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 = grad.T a = div * D * grad print(a[0])
def _symbolic_product_helper()
Use SymPy to generate the 3D products for diffusion_stencil_3d.
2.217844
2.030291
1.092378
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 sparse.isspmatrix(A) and A.format in formats: pass else: A = sparse.csr_matrix(A).asformat(formats[0]) if not isinstance(x, np.ndarray): raise ValueError('expected numpy array for argument x') if not isinstance(b, np.ndarray): raise ValueError('expected numpy array for argument b') M, N = A.shape if M != N: raise ValueError('expected square matrix') if x.shape not in [(M,), (M, 1)]: raise ValueError('x has invalid dimensions') if b.shape not in [(M,), (M, 1)]: raise ValueError('b has invalid dimensions') if A.dtype != x.dtype or A.dtype != b.dtype: raise TypeError('arguments A, x, and b must have the same dtype') if not x.flags.carray: raise ValueError('x must be contiguous in memory') x = np.ravel(x) b = np.ravel(b) return A, x, b
def make_system(A, x, b, formats=None)
Return A,x,b suitable for relaxation or raise an exception. Parameters ---------- A : sparse-matrix n x n system x : array n-vector, initial guess b : array n-vector, right-hand side formats: {'csr', 'csc', 'bsr', 'lil', 'dok',...} desired sparse matrix format default is no change to A's format Returns ------- (A,x,b), where A is in the desired sparse-matrix format and x and b are "raveled", i.e. (n,) vectors. Notes ----- Does some rudimentary error checking on the system, such as checking for compatible dimensions and checking for compatible type, i.e. float or complex. Examples -------- >>> from pyamg.relaxation.relaxation import make_system >>> from pyamg.gallery import poisson >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> (A,x,b) = make_system(A,x,b,formats=['csc']) >>> print str(x.shape) (100,) >>> print str(b.shape) (100,) >>> print A.format csc
2.170778
2.313719
0.93822
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
def sor(A, x, b, omega, iterations=1, sweep='forward')
Perform SOR iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) omega : scalar Damping parameter iterations : int Number of iterations to perform sweep : {'forward','backward','symmetric'} Direction of sweep Returns ------- Nothing, x will be modified in place. Notes ----- When omega=1.0, SOR is equivalent to Gauss-Seidel. Examples -------- >>> # Use SOR as stand-along solver >>> from pyamg.relaxation.relaxation import sor >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x0 = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> sor(A, x0, b, 1.33, iterations=10) >>> print norm(b-A*x0) 3.03888724811 >>> # >>> # Use SOR as the multigrid smoother >>> from pyamg import smoothed_aggregation_solver >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('sor', {'sweep':'symmetric', 'omega' : 1.33}), ... postsmoother=('sor', {'sweep':'symmetric', 'omega' : 1.33})) >>> x0 = np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
3.584352
4.579064
0.782769
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_start, row_stop, row_step = 0, int(len(x)/blocksize), 1 elif sweep == 'backward': row_start, row_stop, row_step = int(len(x)/blocksize)-1, -1, -1 elif sweep == 'symmetric': for iter in range(iterations): gauss_seidel(A, x, b, iterations=1, sweep='forward') gauss_seidel(A, x, b, iterations=1, sweep='backward') return else: raise ValueError("valid sweep directions are 'forward',\ 'backward', and 'symmetric'") if sparse.isspmatrix_csr(A): for iter in range(iterations): amg_core.gauss_seidel(A.indptr, A.indices, A.data, x, b, row_start, row_stop, row_step) else: for iter in range(iterations): amg_core.bsr_gauss_seidel(A.indptr, A.indices, np.ravel(A.data), x, b, row_start, row_stop, row_step, R)
def gauss_seidel(A, x, b, iterations=1, sweep='forward')
Perform Gauss-Seidel iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) iterations : int Number of iterations to perform sweep : {'forward','backward','symmetric'} Direction of sweep Returns ------- Nothing, x will be modified in place. Examples -------- >>> # Use Gauss-Seidel as a Stand-Alone Solver >>> from pyamg.relaxation.relaxation import gauss_seidel >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x0 = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> gauss_seidel(A, x0, b, iterations=10) >>> print norm(b-A*x0) 4.00733716236 >>> # >>> # Use Gauss-Seidel as the Multigrid Smoother >>> from pyamg import smoothed_aggregation_solver >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('gauss_seidel', {'sweep':'symmetric'}), ... postsmoother=('gauss_seidel', {'sweep':'symmetric'})) >>> x0=np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
2.311157
2.457472
0.940461
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: # no work to do return temp = np.empty_like(x) # Create uniform type, convert possibly complex scalars to length 1 arrays [omega] = type_prep(A.dtype, [omega]) if sparse.isspmatrix_csr(A): for iter in range(iterations): amg_core.jacobi(A.indptr, A.indices, A.data, x, b, temp, row_start, row_stop, row_step, omega) else: R, C = A.blocksize if R != C: raise ValueError('BSR blocks must be square') row_start = int(row_start / R) row_stop = int(row_stop / R) for iter in range(iterations): amg_core.bsr_jacobi(A.indptr, A.indices, np.ravel(A.data), x, b, temp, row_start, row_stop, row_step, R, omega)
def jacobi(A, x, b, iterations=1, omega=1.0)
Perform Jacobi iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) iterations : int Number of iterations to perform omega : scalar Damping parameter Returns ------- Nothing, x will be modified in place. Examples -------- >>> # Use Jacobi as a Stand-Alone Solver >>> from pyamg.relaxation.relaxation.relaxation import jacobi >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x0 = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> jacobi(A, x0, b, iterations=10, omega=1.0) >>> print norm(b-A*x0) 5.83475132751 >>> # >>> # Use Jacobi as the Multigrid Smoother >>> from pyamg import smoothed_aggregation_solver >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('jacobi', {'omega': 4.0/3.0, 'iterations' : 2}), ... postsmoother=('jacobi', {'omega': 4.0/3.0, 'iterations' : 2})) >>> x0=np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
3.797892
4.101868
0.925893
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.shape[0] != int(A.shape[0]/blocksize): raise ValueError('Dinv and A have incompatible dimensions') elif (Dinv.shape[1] != blocksize) or (Dinv.shape[2] != blocksize): raise ValueError('Dinv and blocksize are incompatible') sweep = slice(None) (row_start, row_stop, row_step) = sweep.indices(int(A.shape[0]/blocksize)) if (row_stop - row_start) * row_step <= 0: # no work to do return temp = np.empty_like(x) # Create uniform type, convert possibly complex scalars to length 1 arrays [omega] = type_prep(A.dtype, [omega]) for iter in range(iterations): amg_core.block_jacobi(A.indptr, A.indices, np.ravel(A.data), x, b, np.ravel(Dinv), temp, row_start, row_stop, row_step, omega, blocksize)
def block_jacobi(A, x, b, Dinv=None, blocksize=1, iterations=1, omega=1.0)
Perform block Jacobi iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix or bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) Dinv : array Array holding block diagonal inverses of A size (N/blocksize, blocksize, blocksize) blocksize : int Desired dimension of blocks iterations : int Number of iterations to perform omega : scalar Damping parameter Returns ------- Nothing, x will be modified in place. Examples -------- >>> # Use block Jacobi as a Stand-Alone Solver >>> from pyamg.relaxation.relaxation import block_jacobi >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x0 = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> block_jacobi(A, x0, b, blocksize=4, iterations=10, omega=1.0) >>> print norm(b-A*x0) 4.66474230129 >>> # >>> # Use block Jacobi as the Multigrid Smoother >>> from pyamg import smoothed_aggregation_solver >>> opts = {'omega': 4.0/3.0, 'iterations' : 2, 'blocksize' : 4} >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('block_jacobi', opts), ... postsmoother=('block_jacobi', opts)) >>> x0=np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
3.711512
3.911048
0.948981
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.shape[0] != int(A.shape[0]/blocksize): raise ValueError('Dinv and A have incompatible dimensions') elif (Dinv.shape[1] != blocksize) or (Dinv.shape[2] != blocksize): raise ValueError('Dinv and blocksize are incompatible') if sweep == 'forward': row_start, row_stop, row_step = 0, int(len(x)/blocksize), 1 elif sweep == 'backward': row_start, row_stop, row_step = int(len(x)/blocksize)-1, -1, -1 elif sweep == 'symmetric': for iter in range(iterations): block_gauss_seidel(A, x, b, iterations=1, sweep='forward', blocksize=blocksize, Dinv=Dinv) block_gauss_seidel(A, x, b, iterations=1, sweep='backward', blocksize=blocksize, Dinv=Dinv) return else: raise ValueError("valid sweep directions are 'forward',\ 'backward', and 'symmetric'") for iter in range(iterations): amg_core.block_gauss_seidel(A.indptr, A.indices, np.ravel(A.data), x, b, np.ravel(Dinv), row_start, row_stop, row_step, blocksize)
def block_gauss_seidel(A, x, b, iterations=1, sweep='forward', blocksize=1, Dinv=None)
Perform block Gauss-Seidel iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) iterations : int Number of iterations to perform sweep : {'forward','backward','symmetric'} Direction of sweep Dinv : array Array holding block diagonal inverses of A size (N/blocksize, blocksize, blocksize) blocksize : int Desired dimension of blocks Returns ------- Nothing, x will be modified in place. Examples -------- >>> # Use Gauss-Seidel as a Stand-Alone Solver >>> from pyamg.relaxation.relaxation import block_gauss_seidel >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> A = poisson((10,10), format='csr') >>> x0 = np.zeros((A.shape[0],1)) >>> b = np.ones((A.shape[0],1)) >>> block_gauss_seidel(A, x0, b, iterations=10, blocksize=4, sweep='symmetric') >>> print norm(b-A*x0) 0.958333817624 >>> # >>> # Use Gauss-Seidel as the Multigrid Smoother >>> from pyamg import smoothed_aggregation_solver >>> opts = {'sweep':'symmetric', 'blocksize' : 4} >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('block_gauss_seidel', opts), ... postsmoother=('block_gauss_seidel', opts)) >>> x0=np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
2.138325
2.187023
0.977733
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:]: h = c*residual + A*h x += h
def polynomial(A, x, b, coefficients, iterations=1)
Apply a polynomial smoother to the system Ax=b. Parameters ---------- A : sparse matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) coefficients : array_like Coefficients of the polynomial. See Notes section for details. iterations : int Number of iterations to perform Returns ------- Nothing, x will be modified in place. Notes ----- The smoother has the form x[:] = x + p(A) (b - A*x) where p(A) is a polynomial in A whose scalar coefficients are specified (in descending order) by argument 'coefficients'. - Richardson iteration p(A) = c_0: polynomial_smoother(A, x, b, [c_0]) - Linear smoother p(A) = c_1*A + c_0: polynomial_smoother(A, x, b, [c_1, c_0]) - Quadratic smoother p(A) = c_2*A^2 + c_1*A + c_0: polynomial_smoother(A, x, b, [c_2, c_1, c_0]) Here, Horner's Rule is applied to avoid computing A^k directly. For efficience, the method detects the case x = 0 one matrix-vector product is avoided (since (b - A*x) is b). Examples -------- >>> # The polynomial smoother is not currently used directly >>> # in PyAMG. It is only used by the chebyshev smoothing option, >>> # which automatically calculates the correct coefficients. >>> from pyamg.gallery import poisson >>> from pyamg.util.linalg import norm >>> import numpy as np >>> from pyamg.aggregation import smoothed_aggregation_solver >>> A = poisson((10,10), format='csr') >>> b = np.ones((A.shape[0],1)) >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)), ... coarse_solver='pinv2', max_coarse=50, ... presmoother=('chebyshev', {'degree':3, 'iterations':1}), ... postsmoother=('chebyshev', {'degree':3, 'iterations':1})) >>> x0=np.zeros((A.shape[0],1)) >>> residuals=[] >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
4.601454
5.544214
0.829956
A, x, b = make_system(A, x, b, formats=['csr']) indices = np.asarray(indices, dtype='intc') # if indices.min() < 0: # raise ValueError('row index (%d) is invalid' % indices.min()) # if indices.max() >= A.shape[0] # raise ValueError('row index (%d) is invalid' % indices.max()) if sweep == 'forward': row_start, row_stop, row_step = 0, len(indices), 1 elif sweep == 'backward': row_start, row_stop, row_step = len(indices)-1, -1, -1 elif sweep == 'symmetric': for iter in range(iterations): gauss_seidel_indexed(A, x, b, indices, iterations=1, sweep='forward') gauss_seidel_indexed(A, x, b, indices, iterations=1, sweep='backward') return else: raise ValueError("valid sweep directions are 'forward',\ 'backward', and 'symmetric'") for iter in range(iterations): amg_core.gauss_seidel_indexed(A.indptr, A.indices, A.data, x, b, indices, row_start, row_stop, row_step)
def gauss_seidel_indexed(A, x, b, indices, iterations=1, sweep='forward')
Perform indexed Gauss-Seidel iteration on the linear system Ax=b. In indexed Gauss-Seidel, the sequence in which unknowns are relaxed is specified explicitly. In contrast, the standard Gauss-Seidel method always performs complete sweeps of all variables in increasing or decreasing order. The indexed method may be used to implement specialized smoothers, like F-smoothing in Classical AMG. Parameters ---------- A : csr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) indices : ndarray Row indices to relax. iterations : int Number of iterations to perform sweep : {'forward','backward','symmetric'} Direction of sweep Returns ------- Nothing, x will be modified in place. Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.relaxation.relaxation import gauss_seidel_indexed >>> import numpy as np >>> A = poisson((4,), format='csr') >>> x = np.array([0.0, 0.0, 0.0, 0.0]) >>> b = np.array([0.0, 1.0, 2.0, 3.0]) >>> gauss_seidel_indexed(A, x, b, [0,1,2,3]) # relax all rows in order >>> gauss_seidel_indexed(A, x, b, [0,1]) # relax first two rows >>> gauss_seidel_indexed(A, x, b, [2,0]) # relax row 2, then row 0 >>> gauss_seidel_indexed(A, x, b, [2,3], sweep='backward') # 3, then 2 >>> gauss_seidel_indexed(A, x, b, [2,0,2]) # relax row 2, 0, 2
2.209481
2.356014
0.937804