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... | 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 p... | 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"] =... | 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
... | 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 + time... | 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... | 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... | 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... | 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 m... | 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.datetim... | 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 ... | 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),... | 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... | 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 ... | 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:
... | 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
... | 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'],
... | 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 smoothe... | 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
... | 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-
... | 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
#... | 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
... | 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 += ind... | 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
... | 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 : flo... | 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 ... | 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],
... | 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::
... | 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]]) +\
... | 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 =... | 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,... | 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 = n... | 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... | 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):
stenci... | 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 dim... | 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 ... | 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):
... | 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 radi... | 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
-... | 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}
... | 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.
Not... | 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)
... | 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 Fal... | 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
... | 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.
R... | 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"... | 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
... | 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('expe... | 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')
... | 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=alph... | 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
-------
... | 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')... | 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
-... | 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')... | 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... | 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.... | 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, ColsPe... | 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) mat... | 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 prolon... | 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 s... | 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 Val... | 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
-... | 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 bas... | 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... | 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.ar... | 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
E... | 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 = "".joi... | 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'
... | 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:
... | 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],
... | 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
... | 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 ... | 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 betwee... | 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]... | 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
A... | 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)
... | 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)
Return... | 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... | 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-... | 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
- ... | 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 ==... | 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... | 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... | 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_ma... | 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
... | 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 ... | 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
magni... | 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(roo... | 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 fo... | 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 typ... | 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_c... | 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 ... | 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... | 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_sol... | 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(... | 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
... | 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(... | 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
... | 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':
... | 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
... | 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]]
... | 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
... | 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,l... | 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 bee... | 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 ... | 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
... | 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... | 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
-------
... | 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
-----
... | 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... | 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... | 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], ... | 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... | 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)
... | 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
... | 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
Nu... | 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_ste... | 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
sw... | 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 scala... | 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
... | 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 dimensi... | 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... | 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 dimensi... | 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
... | 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*... | 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 secti... | 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())
... | 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 ... | 2.209481 | 2.356014 | 0.937804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.