Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def innerprod(self, X):
N = len(self.shape)
R = len(self.lmbda)
res = 0
for r in range(R):
vecs = []
for n in range(N):
vecs.append(self.U[n][:, r])
res += self.lmbda[r] * X.ttv(tupl... | [
"\n Efficient computation of the inner product of a ktensor with another tensor\n\n Parameters\n ----------\n X : tensor_mixin\n Tensor to compute the inner product with.\n\n Returns\n -------\n p : float\n Inner product between ktensor and X.\n... |
Please provide a description of the function:def toarray(self):
A = dot(self.lmbda, khatrirao(tuple(self.U)).T)
return A.reshape(self.shape) | [
"\n Converts a ktensor into a dense multidimensional ndarray\n\n Returns\n -------\n arr : np.ndarray\n Fully computed multidimensional array whose shape matches\n the original ktensor.\n "
] |
Please provide a description of the function:def fromarray(A):
subs = np.nonzero(A)
vals = A[subs]
return sptensor(subs, vals, shape=A.shape, dtype=A.dtype) | [
"Create a sptensor from a dense numpy array"
] |
Please provide a description of the function:def _ttm_me_compute(self, V, edims, sdims, transp):
shapeY = np.copy(self.shape)
# Determine size of Y
for n in np.union1d(edims, sdims):
shapeY[n] = V[n].shape[1] if transp else V[n].shape[0]
# Allocate Y (final result)... | [
"\n Assume Y = T x_i V_i for i = 1...n can fit into memory\n "
] |
Please provide a description of the function:def transpose(self, axes=None):
if axes is None:
raise NotImplementedError(
'Sparse tensor transposition without axes argument is not supported'
)
nsubs = tuple([self.subs[idx] for idx in axes])
nshape ... | [
"\n Compute transpose of sparse tensors.\n\n Parameters\n ----------\n axes : array_like of ints, optional\n Permute the axes according to the values given.\n\n Returns\n -------\n d : dtensor\n dtensor with axes permuted.\n "
] |
Please provide a description of the function:def concatenate(self, tpl, axis=None):
if axis is None:
raise NotImplementedError(
'Sparse tensor concatenation without axis argument is not supported'
)
T = self
for i in range(1, len(tpl)):
... | [
"\n Concatenates sparse tensors.\n\n Parameters\n ----------\n tpl : tuple of sparse tensors\n Tensors to be concatenated.\n axis : int, optional\n Axis along which concatenation should take place\n "
] |
Please provide a description of the function:def fold(self):
nsubs = zeros((len(self.data), len(self.ten_shape)), dtype=np.int)
if len(self.rdims) > 0:
nidx = unravel_index(self.row, self.ten_shape[self.rdims])
for i in range(len(self.rdims)):
nsubs[:, se... | [
"\n Recreate original tensor by folding unfolded_sptensor according toc\n ``ten_shape``.\n\n Returns\n -------\n T : sptensor\n Sparse tensor that is created by refolding according to ``ten_shape``.\n "
] |
Please provide a description of the function:def als(X, rank, **kwargs):
# ------------ init options ----------------------------------------------
ainit = kwargs.pop('init', _DEF_INIT)
maxIter = kwargs.pop('maxIter', _DEF_MAXITER)
conv = kwargs.pop('conv', _DEF_CONV)
lmbdaA = kwargs.pop('lamb... | [
"\n RESCAL-ALS algorithm to compute the RESCAL tensor factorization.\n\n\n Parameters\n ----------\n X : list\n List of frontal slices X_k of the tensor X.\n The shape of each X_k is ('N', 'N').\n X_k's are expected to be instances of scipy.sparse.csr_matrix\n rank : int\n ... |
Please provide a description of the function:def _updateA(X, A, R, P, Z, lmbdaA, orthogonalize):
n, rank = A.shape
F = zeros((n, rank), dtype=A.dtype)
E = zeros((rank, rank), dtype=A.dtype)
AtA = dot(A.T, A)
for i in range(len(X)):
F += X[i].dot(dot(A, R[i].T)) + X[i].T.dot(dot(A, R[i... | [
"Update step for A"
] |
Please provide a description of the function:def _compute_fval(X, A, R, P, Z, lmbdaA, lmbdaR, lmbdaZ, normX):
f = lmbdaA * norm(A) ** 2
for i in range(len(X)):
ARAt = dot(A, dot(R[i], A.T))
f += (norm(X[i] - ARAt) ** 2) / normX[i] + lmbdaR * norm(R[i]) ** 2
return f | [
"Compute fit for full slices"
] |
Please provide a description of the function:def als(X, rank, **kwargs):
# init options
ainit = kwargs.pop('init', _DEF_INIT)
maxiter = kwargs.pop('max_iter', _DEF_MAXITER)
fit_method = kwargs.pop('fit_method', _DEF_FIT_METHOD)
conv = kwargs.pop('conv', _DEF_CONV)
dtype = kwargs.pop('dtype... | [
"\n Alternating least-sqaures algorithm to compute the CP decomposition.\n\n Parameters\n ----------\n X : tensor_mixin\n The tensor to be decomposed.\n rank : int\n Tensor rank of the decomposition.\n init : {'random', 'nvecs'}, optional\n The initialization method to use.\n ... |
Please provide a description of the function:def _init(init, X, N, rank, dtype):
Uinit = [None for _ in range(N)]
if isinstance(init, list):
Uinit = init
elif init == 'random':
for n in range(1, N):
Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype)
elif init == 'nvec... | [
"\n Initialization for CP models\n "
] |
Please provide a description of the function:def nvecs(X, n, rank, do_flipsign=True, dtype=np.float):
Xn = X.unfold(n)
if issparse_mat(Xn):
Xn = csr_matrix(Xn, dtype=dtype)
Y = Xn.dot(Xn.T)
_, U = eigsh(Y, rank, which='LM')
else:
Y = Xn.dot(Xn.T)
N = Y.shape[0]
... | [
"\n Eigendecomposition of mode-n unfolding of a tensor\n "
] |
Please provide a description of the function:def flipsign(U):
midx = abs(U).argmax(axis=0)
for i in range(U.shape[1]):
if U[midx[i], i] < 0:
U[:, i] = -U[:, i]
return U | [
"\n Flip sign of factor matrices such that largest magnitude\n element will be positive\n "
] |
Please provide a description of the function:def khatrirao(A, reverse=False):
if not isinstance(A, tuple):
raise ValueError('A must be a tuple of array likes')
N = A[0].shape[1]
M = 1
for i in range(len(A)):
if A[i].ndim != 2:
raise ValueError('A must be a tuple of matr... | [
"\n Compute the columnwise Khatri-Rao product.\n\n Parameters\n ----------\n A : tuple of ndarrays\n Matrices for which the columnwise Khatri-Rao product should be computed\n\n reverse : boolean\n Compute Khatri-Rao product in reverse order\n\n Examples\n --------\n >>> A = np.... |
Please provide a description of the function:def teneye(dim, order):
I = zeros(dim ** order)
for f in range(dim):
idd = f
for i in range(1, order):
idd = idd + dim ** (i - 1) * (f - 1)
I[idd] = 1
return I.reshape(ones(order) * dim) | [
"\n Create tensor with superdiagonal all one, rest zeros\n "
] |
Please provide a description of the function:def ttm(self, V, mode=None, transp=False, without=False):
if mode is None:
mode = range(self.ndim)
if isinstance(V, np.ndarray):
Y = self._ttm_compute(V, mode, transp)
elif is_sequence(V):
dims, vidx = chec... | [
"\n Tensor times matrix product\n\n Parameters\n ----------\n V : M x N array_like or list of M_i x N_i array_likes\n Matrix or list of matrices for which the tensor times matrix\n products should be performed\n mode : int or list of int's, optional\n ... |
Please provide a description of the function:def ttv(self, v, modes=[], without=False):
if not isinstance(v, tuple):
v = (v, )
dims, vidx = check_multiplication_dims(modes, self.ndim, len(v), vidx=True, without=without)
for i in range(len(dims)):
if not len(v[vid... | [
"\n Tensor times vector product\n\n Parameters\n ----------\n v : 1-d array or tuple of 1-d arrays\n Vector to be multiplied with tensor.\n modes : array_like of integers, optional\n Modes in which the vectors should be multiplied.\n without : boolean,... |
Please provide a description of the function:def handle(self, *args, **options):
from categories.migration import migrate_app
from categories.settings import MODEL_REGISTRY
if options['app_names']:
for app in options['app_names']:
migrate_app(None, app)
... | [
"\n Alter the tables\n "
] |
Please provide a description of the function:def _process_registry(registry, call_func):
from django.core.exceptions import ImproperlyConfigured
from django.apps import apps
for key, value in list(registry.items()):
model = apps.get_model(*key.split('.'))
if model is None:
... | [
"\n Given a dictionary, and a registration function, process the registry\n "
] |
Please provide a description of the function:def register_model(self, app, model_name, field_type, field_definitions):
from django.apps import apps
import collections
app_label = app
if isinstance(field_definitions, str):
field_definitions = [field_definitions]
... | [
"\n Process for Django 1.7 +\n app: app name/label\n model_name: name of the model\n field_definitions: a string, tuple or list of field configurations\n field_type: either 'ForeignKey' or 'ManyToManyField'\n "
] |
Please provide a description of the function:def field_exists(app_name, model_name, field_name):
model = apps.get_model(app_name, model_name)
table_name = model._meta.db_table
cursor = connection.cursor()
field_info = connection.introspection.get_table_description(cursor, table_name)
field_name... | [
"\n Does the FK or M2M table exist in the database already?\n "
] |
Please provide a description of the function:def drop_field(app_name, model_name, field_name):
app_config = apps.get_app_config(app_name)
model = app_config.get_model(model_name)
field = model._meta.get_field(field_name)
with connection.schema_editor() as schema_editor:
schema_editor.remove... | [
"\n Drop the given field from the app's model\n "
] |
Please provide a description of the function:def migrate_app(sender, *args, **kwargs):
from .registration import registry
if 'app_config' not in kwargs:
return
app_config = kwargs['app_config']
app_name = app_config.label
fields = [fld for fld in list(registry._field_registry.keys()) ... | [
"\n Migrate all models of this app registered\n "
] |
Please provide a description of the function:def items_for_tree_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = ''
try:
f, attr, value = lookup_field(field_name, result, cl.model_admin)
except (Attr... | [
"\n Generates the actual list of data.\n "
] |
Please provide a description of the function:def result_tree_list(cl):
import django
result = {
'cl': cl,
'result_headers': list(result_headers(cl)),
'results': list(tree_results(cl))
}
if django.VERSION[0] == 1 and django.VERSION[1] > 2:
from django.contrib.admin.te... | [
"\n Displays the headers and data list together\n "
] |
Please provide a description of the function:def get_absolute_url(self):
from django.urls import NoReverseMatch
if self.alternate_url:
return self.alternate_url
try:
prefix = reverse('categories_tree_list')
except NoReverseMatch:
prefix = '/'... | [
"Return a path"
] |
Please provide a description of the function:def get_content_type(self, content_type):
qs = self.get_queryset()
return qs.filter(content_type__name=content_type) | [
"\n Get all the items of the given content type related to this item.\n "
] |
Please provide a description of the function:def get_relation_type(self, relation_type):
qs = self.get_queryset()
return qs.filter(relation_type=relation_type) | [
"\n Get all the items of the given relationship type related to this item.\n "
] |
Please provide a description of the function:def handle_class_prepared(sender, **kwargs):
from .settings import M2M_REGISTRY, FK_REGISTRY
from .registration import registry
sender_app = sender._meta.app_label
sender_name = sender._meta.model_name
for key, val in list(FK_REGISTRY.items()):
... | [
"\n See if this class needs registering of fields\n "
] |
Please provide a description of the function:def get(self, *args, **kwargs):
return self.model._default_manager.get(*args, **kwargs) | [
"\n Quick and dirty hack to fix change_view and delete_view; they use\n self.queryset(request).get(...) to get the object they should work\n with. Our modifications to the queryset when INCLUDE_ANCESTORS is\n enabled make get() fail often with a MultipleObjectsReturned\n exception... |
Please provide a description of the function:def old_changelist_view(self, request, extra_context=None):
"The 'change list' admin view for this model."
from django.contrib.admin.views.main import ERROR_FLAG
from django.core.exceptions import PermissionDenied
from django.utils.encoding im... | [] |
Please provide a description of the function:def changelist_view(self, request, extra_context=None, *args, **kwargs):
extra_context = extra_context or {}
extra_context['EDITOR_MEDIA_PATH'] = settings.MEDIA_PATH
extra_context['EDITOR_TREE_INITIAL_STATE'] = settings.TREE_INITIAL_STATE
... | [
"\n Handle the changelist view, the django view for the model instances\n change list/actions page.\n "
] |
Please provide a description of the function:def get_queryset(self, request):
qs = self.model._default_manager.get_queryset()
qs.__class__ = TreeEditorQuerySet
return qs | [
"\n Returns a QuerySet of all model instances that can be edited by the\n admin site. This is used by changelist_view.\n "
] |
Please provide a description of the function:def handle(self, *args, **options):
from categories.migration import drop_field
if 'app_name' not in options or 'model_name' not in options or 'field_name' not in options:
raise CommandError("You must specify an Application name, a Model ... | [
"\n Alter the tables\n "
] |
Please provide a description of the function:def deactivate(self, request, queryset):
selected_cats = self.model.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
item.active = F... | [
"\n Set active to False for selected items\n "
] |
Please provide a description of the function:def get_indent(self, string):
indent_amt = 0
if string[0] == '\t':
return '\t'
for char in string:
if char == ' ':
indent_amt += 1
else:
return ' ' * indent_amt | [
"\n Look through the string and count the spaces\n "
] |
Please provide a description of the function:def make_category(self, string, parent=None, order=1):
cat = Category(
name=string.strip(),
slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49],
# arent=parent,
order=order
)
cat._tree_manage... | [
"\n Make and save a category object from a string\n "
] |
Please provide a description of the function:def parse_lines(self, lines):
indent = ''
level = 0
if lines[0][0] == ' ' or lines[0][0] == '\t':
raise CommandError("The first line in the file cannot start with a space or tab.")
# This keeps track of the current paren... | [
"\n Do the work of parsing each line\n "
] |
Please provide a description of the function:def handle(self, *file_paths, **options):
import os
for file_path in file_paths:
if not os.path.isfile(file_path):
print("File %s not found." % file_path)
continue
f = open(file_path, 'r')
... | [
"\n Handle the basic import\n "
] |
Please provide a description of the function:def label_from_instance(self, obj):
return '%s %s' % (self.level_indicator * getattr(obj, obj._mptt_meta.level_attr), obj) | [
"\n Creates labels which represent the tree level of each node when\n generating option labels.\n "
] |
Please provide a description of the function:def get_cat_model(model):
try:
if isinstance(model, string_types):
model_class = apps.get_model(*model.split("."))
elif issubclass(model, CategoryBase):
model_class = model
if model_class is None:
raise Typ... | [
"\n Return a class from a string or class\n "
] |
Please provide a description of the function:def get_category(category_string, model=Category):
model_class = get_cat_model(model)
category = str(category_string).strip("'\"")
category = category.strip('/')
cat_list = category.split('/')
if len(cat_list) == 0:
return None
try:
... | [
"\n Convert a string, including a path, and return the Category object\n "
] |
Please provide a description of the function:def get_category_drilldown(parser, token):
bits = token.split_contents()
error_str = '%(tagname)s tag should be in the format {%% %(tagname)s ' \
'"category name" [using "app.Model"] as varname %%} or ' \
'{%% %(tagname)s category... | [
"\n Retrieves the specified category, its ancestors and its immediate children\n as an iterable.\n\n Syntax::\n\n {% get_category_drilldown \"category name\" [using \"app.Model\"] as varname %}\n\n Example::\n\n {% get_category_drilldown \"/Grandparent/Parent\" [using \"app.Model\"] as fam... |
Please provide a description of the function:def breadcrumbs(category_string, separator=' > ', using='categories.category'):
cat = get_category(category_string, using)
return {'category': cat, 'separator': separator} | [
"\n {% breadcrumbs category separator=\"::\" using=\"categories.category\" %}\n\n Render breadcrumbs, using the ``categories/breadcrumbs.html`` template,\n using the optional ``separator`` argument.\n "
] |
Please provide a description of the function:def display_drilldown_as_ul(category, using='categories.Category'):
cat = get_category(category, using)
if cat is None:
return {'category': cat, 'path': []}
else:
return {'category': cat, 'path': drilldown_tree_for_node(cat)} | [
"\n Render the category with ancestors and children using the\n ``categories/ul_tree.html`` template.\n\n Example::\n\n {% display_drilldown_as_ul \"/Grandparent/Parent\" %}\n\n or ::\n\n {% display_drilldown_as_ul category_obj %}\n\n Returns::\n\n <ul>\n <li><a href=\"/... |
Please provide a description of the function:def display_path_as_ul(category, using='categories.Category'):
if isinstance(category, CategoryBase):
cat = category
else:
cat = get_category(category)
return {'category': cat, 'path': cat.get_ancestors() or []} | [
"\n Render the category with ancestors, but no children using the\n ``categories/ul_tree.html`` template.\n\n Example::\n\n {% display_path_as_ul \"/Grandparent/Parent\" %}\n\n or ::\n\n {% display_path_as_ul category_obj %}\n\n Returns::\n\n <ul>\n <li><a href=\"/cate... |
Please provide a description of the function:def get_top_level_categories(parser, token):
bits = token.split_contents()
usage = 'Usage: {%% %s [using "app.Model"] as <variable> %%}' % bits[0]
if len(bits) == 3:
if bits[1] != 'as':
raise template.TemplateSyntaxError(usage)
va... | [
"\n Retrieves an alphabetical list of all the categories that have no parents.\n\n Syntax::\n\n {% get_top_level_categories [using \"app.Model\"] as categories %}\n\n Returns an list of categories [<category>, <category>, <category, ...]\n "
] |
Please provide a description of the function:def tree_queryset(value):
from django.db.models.query import QuerySet
from copy import deepcopy
if not isinstance(value, QuerySet):
return value
qs = value
qs2 = deepcopy(qs)
# Reaching into the bowels of query sets to find out whether t... | [
"\n Converts a normal queryset from an MPTT model to include all the ancestors\n so a filtered subset of items can be formatted correctly\n "
] |
Please provide a description of the function:def recursetree(parser, token):
bits = token.contents.split()
if len(bits) != 2:
raise template.TemplateSyntaxError('%s tag requires a queryset' % bits[0])
queryset_var = FilterExpression(bits[1], parser)
template_nodes = parser.parse(('endrecur... | [
"\n Iterates over the nodes in the tree, and renders the contained block for each node.\n This tag will recursively render children into the template variable {{ children }}.\n Only one database query is required (children are cached for the whole tree)\n\n Usage:\n <ul>\n {% r... |
Please provide a description of the function:def gaussian_filter(data, sigma=4., truncate = 4., normalize=True, res_g=None):
if not len(data.shape) in [1, 2, 3]:
raise ValueError("dim = %s not supported" % (len(data.shape)))
if np.isscalar(sigma):
sigma = [sigma] * data.ndim
if any(t... | [
"\n blurs data with a gaussian kernel of given sigmas\n \n Parameters\n ----------\n data: ndarray\n 2 or 3 dimensional array \n sigma: scalar or tuple\n the sigma of the gaussian \n truncate: float \n truncate the kernel after truncate*sigma \n normalize: bool\n ... |
Please provide a description of the function:def convolve(data, h, res_g=None, sub_blocks=None):
if not len(data.shape) in [1, 2, 3]:
raise ValueError("dim = %s not supported" % (len(data.shape)))
if len(data.shape) != len(h.shape):
raise ValueError("dimemnsion of data (%s) and h (%s) are... | [
"\n convolves 1d-3d data with kernel h \n\n data and h can either be numpy arrays or gpu buffer objects (OCLArray, \n which must be float32 then)\n\n boundary conditions are clamping to zero at edge.\n \n "
] |
Please provide a description of the function:def _convolve_np(data, h):
data_g = OCLArray.from_array(np.require(data,np.float32,"C"))
h_g = OCLArray.from_array(np.require(h,np.float32,"C"))
return _convolve_buf(data_g, h_g).get() | [
"\n numpy variant\n "
] |
Please provide a description of the function:def _convolve_buf(data_g, h_g, res_g=None):
assert_bufs_type(np.float32, data_g, h_g)
prog = OCLProgram(abspath("kernels/convolve.cl"))
if res_g is None:
res_g = OCLArray.empty(data_g.shape, dtype=np.float32)
Nhs = [np.int32(n) for n in h_g.sh... | [
"\n buffer variant\n "
] |
Please provide a description of the function:def _convolve3_old(data, h, dev=None):
if dev is None:
dev = get_device()
if dev is None:
raise ValueError("no OpenCLDevice found...")
dtype = data.dtype.type
dtypes_options = {np.float32: "",
np.uint16: "-D SHOR... | [
"convolves 3d data with kernel h on the GPU Device dev\n boundary conditions are clamping to edge.\n h is converted to float32\n\n if dev == None the default one is used\n "
] |
Please provide a description of the function:def _scale_shape(dshape, scale = (1,1,1)):
nshape = np.round(np.array(dshape) * np.array(scale))
return tuple(nshape.astype(np.int)) | [
"returns the shape after scaling (should be the same as ndimage.zoom"
] |
Please provide a description of the function:def scale(data, scale = (1.,1.,1.), interpolation = "linear"):
if not (isinstance(data, np.ndarray) and data.ndim == 3):
raise ValueError("input data has to be a 3d array!")
interpolation_defines = {"linear": ["-D", "SAMPLER_FILTER=CLK_FILTER_LINEAR"]... | [
"\n returns a interpolated, scaled version of data\n \n the output shape is scaled too.\n \n Parameters\n ----------\n data: ndarray\n 3d input array\n scale: float, tuple\n scaling factor along each axis (x,y,z) \n interpolation: str\n either \"nearest\" or \"linear\... |
Please provide a description of the function:def abspath(myPath):
import sys, os
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
return os.path.join(base_path, os.path.basename(myPath))
except Exception:
base_path = os.path.a... | [
" Get absolute path to resource, works for dev and for PyInstaller "
] |
Please provide a description of the function:def perlin2(size, units=None, repeat=(10.,)*2, scale=None, shift=(0, 0)):
if scale:
if np.isscalar(scale):
scale = (scale,)*2
repeat = scale
units = (1.,)*2
wx, wy = repeat
dx, dy = units
offset_x, offset_y = shift
... | [
"\n 2d perlin noise\n either scale =(10.,10.) or units (5.,5.) have to be given....\n\n scale is the characteristic length in pixels\n Parameters\n ----------\n size:\n\n units\n repeat\n scale\n shift\n\n Returns\n -------\n\n "
] |
Please provide a description of the function:def perlin3(size, units=(1.,)*3, repeat=(10.,)*3, shift=0, scale=None, n_volumes=1):
if np.isscalar(shift):
shift = (shift,)*len(size)
if scale:
if np.isscalar(scale):
scale = (scale,)*3
repeat = scale
units = (1.,)*3... | [
"returns a 3d perlin noise array of given size (Nx,Ny,Nz)\n and units (dx,dy,dz) with given repeats (in units)\n by doing the noise calculations on the gpu\n\n The volume can be splitted into n_volumes pieces if gou memory is not enough\n\n either scale or units have to be given\n\n shift = (.1,.1,.2... |
Please provide a description of the function:def nlm2(data,sigma, size_filter = 2, size_search = 3):
prog = OCLProgram(abspath("kernels/nlm2.cl"),
build_options="-D FS=%i -D BS=%i"%(size_filter,size_search))
data = data.astype(np.float32)
img = OCLImage.from_array(data)
dis... | [
"for noise level of sigma_0, choose sigma = 1.5*sigma_0\n \n "
] |
Please provide a description of the function:def init_device(**kwargs):
new_device = OCLDevice(**kwargs)
# just change globals if new_device is different from old
if _ocl_globals.device.device != new_device.device:
_ocl_globals.device = new_device | [
"same arguments as OCLDevice.__init__\n e.g.\n id_platform = 0\n id_device = 1\n ....\n "
] |
Please provide a description of the function:def device_priority(cls, device_with_type_tuple):
device, device_type = device_with_type_tuple
return (device_type is pyopencl.device_type.GPU,
device.get_info(pyopencl.device_info.GLOBAL_MEM_SIZE),
) | [
"used to sort devices\n device_with_type_tuple = (device, device_type)\n "
] |
Please provide a description of the function:def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False):
if axes is None:
axes = list(range(arr_obj.ndim))
if isinstance(arr_obj, OCLArray):
if not arr_obj.dtype.type in DTYPE_KERNEL_NAMES:
raise NotImplementedError... | [
"\n gpu version of fftshift for numpy arrays or OCLArrays\n\n Parameters\n ----------\n arr_obj: numpy array or OCLArray (float32/complex64)\n the array to be fftshifted\n axes: list or None\n the axes over which to shift (like np.fft.fftshift)\n if None, all axes are taken\n ... |
Please provide a description of the function:def _fftshift_single(d_g, res_g, ax = 0):
dtype_kernel_name = {np.float32:"fftshift_1_f",
np.complex64:"fftshift_1_c"
}
N = d_g.shape[ax]
N1 = 1 if ax==0 else np.prod(d_g.shape[:ax])
N2 = 1 if ax == len(d_g.shape)-... | [
"\n basic fftshift of an OCLArray\n\n\n shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k]\n = [N1, N, N2]\n\n the we can address each element in the flat buffer by\n\n index = i + N2*j + N2*N*k\n\n where i = 1 .. N2\n j = 1 .. N\n k = 1 .. N1\n\n and the swap of elements... |
Please provide a description of the function:def convolve_sep2(data, hx, hy, res_g=None, sub_blocks=None):
if isinstance(data, np.ndarray):
data = np.ascontiguousarray(data)
if sub_blocks == (1, 1) or sub_blocks is None:
return _convolve_sep2_numpy(data, hx, hy)
else:
... | [
"convolves 2d data with kernel h = outer(hx,hy)\n boundary conditions are clamping to edge.\n\n data is either np array or a gpu buffer (OCLArray)\n\n "
] |
Please provide a description of the function:def convolve_sep3(data, hx, hy, hz, res_g=None, sub_blocks=(1, 1, 1), tmp_g = None):
if isinstance(data, np.ndarray):
data = np.ascontiguousarray(data)
if sub_blocks == (1, 1, 1) or sub_blocks is None:
return _convolve_sep3_numpy(data, h... | [
"convolves 3d data with kernel h = outer(hx,hy, hz)\n boundary conditions are clamping to edge.\n\n data, hx, hy.... are either np array or a gpu buffer (OCLArray)\n\n "
] |
Please provide a description of the function:def bilateral2(data, fSize, sigma_p, sigma_x = 10.):
dtype = data.dtype.type
dtypes_kernels = {np.float32:"bilat2_float",
np.uint16:"bilat2_short"}
if not dtype in dtypes_kernels:
logger.info("data type %s not supported ... | [
"bilateral filter "
] |
Please provide a description of the function:def deconv_rl(data, h, Niter = 10):
if isinstance(data,np.ndarray):
return _deconv_rl_np(data,h, Niter)
elif isinstance(data,OCLArray):
return _deconv_rl_gpu_conv(data,h, Niter)
else:
raise TypeError("array argument (1) has bad typ... | [
" richardson lucy deconvolution of data with psf h\n using spatial convolutions (h should be small then)\n "
] |
Please provide a description of the function:def bilateral3(data, size_filter, sigma_p, sigma_x = 10.):
dtype = data.dtype.type
dtypes_kernels = {np.float32:"bilat3_float",}
if not dtype in dtypes_kernels:
logger.info("data type %s not supported yet (%s), casting to float:"%(dtype,list(dtypes... | [
"bilateral filter "
] |
Please provide a description of the function:def ssim(x, y, data_range=None, scaled = False, verbose = False):
if not x.shape == y.shape:
raise ValueError('Input images must have the same dimensions.')
K1 = 0.01
K2 = 0.03
sigma = 1.5
win_size = 7
if scaled:
x = x.astype(n... | [
"compute ssim\n parameters are like the defaults for skimage.compare_ssim\n\n "
] |
Please provide a description of the function:def fft_convolve(data, h, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False,
kernel_is_fftshifted = False):
if isinstance(data,np.ndarray):
return _fft_convolve_numpy(data, h,
... | [
" convolves data with kernel h via FFTs\n\n \n data should be either a numpy array or a OCLArray (see doc for fft)\n both data and h should be same shape\n\n if data/h are OCLArrays, then:\n - type should be complex64\n - shape should be equal and power of two\n - h is assumed to be... |
Please provide a description of the function:def _fft_convolve_numpy(data, h, plan = None,
kernel_is_fft = False,
kernel_is_fftshifted = False):
if data.shape != h.shape:
raise ValueError("data and kernel must have same size! %s vs %s "%(str(data.shape),... | [
" convolving via opencl fft for numpy arrays\n\n data and h must have the same size\n "
] |
Please provide a description of the function:def _fft_convolve_gpu(data_g, h_g, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False):
assert_bufs_type(np.complex64,data_g,h_g)
if data_g.shape != h_g.shape:
raise ValueError("data and ker... | [
" fft convolve for gpu buffer\n "
] |
Please provide a description of the function:def convolve_spatial2(im, psfs,
mode = "constant",
grid_dim = None,
sub_blocks = None,
pad_factor = 2,
plan = None,
return_plan = False):
... | [
"\n GPU accelerated spatial varying convolution of an 2d image with a\n (Gy,Gx) grid of psfs assumed to be equally spaced within the image\n the input image im is subdivided into (Gy,Gx) blocks, each block is\n convolved with the corresponding psf and linearly interpolated to give the\n final result\... |
Please provide a description of the function:def _convolve_spatial2(im, hs,
mode = "constant",
grid_dim = None,
pad_factor = 2,
plan = None,
return_plan = False):
if grid_dim:
Gs = tuple(grid_... | [
"\n spatial varying convolution of an 2d image with a 2d grid of psfs\n\n shape(im_ = (Ny,Nx)\n shape(hs) = (Gy,Gx, Hy,Hx)\n\n the input image im is subdivided into (Gy,Gx) blocks\n hs[j,i] is the psf at the center of each block (i,j)\n\n as of now each image dimension has to be divisible by the g... |
Please provide a description of the function:def _tv2(data,weight,Niter=50):
if dev is None:
dev = imgtools.__DEFAULT_OPENCL_DEVICE__
if dev is None:
raise ValueError("no OpenCLDevice found...")
proc = OCLProcessor(dev,utils.absPath("kernels/tv_chambolle.cl"))
if Ncut ==1:
... | [
"\n chambolles tv regularized denoising\n\n weight should be around 2+1.5*noise_sigma\n "
] |
Please provide a description of the function:def tv2(data,weight,Niter=50):
prog = OCLProgram(abspath("kernels/tv2.cl"))
data_im = OCLImage.from_array(data.astype(np,float32,copy=False))
pImgs = [ dev.createImage(data.shape[::-1],
mem_flags = cl.mem_flags.READ_WRITE... | [
"\n chambolles tv regularized denoising\n\n weight should be around 2+1.5*noise_sigma\n "
] |
Please provide a description of the function:def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None):
if data.ndim == 2:
_filt = make_filter(_median_filter_gpu_2d())
elif data.ndim == 3:
_filt = make_filter(_median_filter_gpu_3d())
else:
raise ValueError("currentl... | [
"\n median filter of given size\n\n Parameters\n ----------\n data: 2 or 3 dimensional ndarray or OCLArray of type float32\n input data\n size: scalar, tuple\n the size of the patch to consider\n cval: scalar, \n the constant value for out of border access (cf mode = \"con... |
Please provide a description of the function:def affine(data, mat=np.identity(4), mode="constant", interpolation="linear"):
warnings.warn(
"gputools.transform.affine: API change as of gputools>= 0.2.8: the inverse of the matrix is now used as in scipy.ndimage.affine_transform")
if not (isinstance(... | [
"\n affine transform data with matrix mat, which is the inverse coordinate transform matrix \n (similar to ndimage.affine_transform)\n \n Parameters\n ----------\n data, ndarray\n 3d array to be transformed\n mat, ndarray \n 3x3 or 4x4 inverse coordinate transform matrix \n m... |
Please provide a description of the function:def shift(data, shift=(0, 0, 0), mode="constant", interpolation="linear"):
if np.isscalar(shift):
shift = (shift,) * 3
if len(shift) != 3:
raise ValueError("shift (%s) should be of length 3!")
shift = -np.array(shift)
return affine(data... | [
"\n translates 3d data by given amount\n \n \n Parameters\n ----------\n data: ndarray\n 3d array\n shift : float or sequence\n The shift along the axes. If a float, `shift` is the same for each axis. \n If a sequence, `shift` should contain one value for each axis. \n ... |
Please provide a description of the function:def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"):
if center is None:
center = tuple([s // 2 for s in data.shape])
cx, cy, cz = center
m = np.dot(mat4_translate(cx, cy, cz),
np.dot(mat4_... | [
"\n rotates data around axis by a given angle\n\n Parameters\n ----------\n data: ndarray\n 3d array\n axis: tuple\n axis to rotate by angle about\n axis = (x,y,z)\n angle: float\n center: tuple or None\n origin of rotation (cz,cy,cx) in pixels\n if None, cent... |
Please provide a description of the function:def map_coordinates(data, coordinates, interpolation="linear",
mode='constant'):
if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):
raise ValueError("input data has to be a 2d or 3d array!")
coordinates = np.asarray(coord... | [
"\n Map data to new coordinates by interpolation.\n The array of coordinates is used to find, for each point in the output,\n the corresponding coordinates in the input.\n\n should correspond to scipy.ndimage.map_coordinates\n \n Parameters\n ----------\n data\n coordinates\n output\n ... |
Please provide a description of the function:def geometric_transform(data, mapping = "c0,c1", output_shape=None,
mode='constant', interpolation="linear"):
if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):
raise ValueError("input data has to be a 2d or 3d array!")
... | [
"\n Apply an arbitrary geometric transform.\n The given mapping function is used to find, for each point in the\n output, the corresponding coordinates in the input. The value of the\n input at those coordinates is determined by spline interpolation of\n the requested order.\n Parameters\n ----... |
Please provide a description of the function:def convolve_spatial2(im, hs,
mode = "constant",
plan = None,
return_plan = False):
if im.ndim !=2 or hs.ndim !=4:
raise ValueError("wrong dimensions of input!")
if not np.all([n%g==0 fo... | [
"\n spatial varying convolution of an 2d image with a 2d grid of psfs\n\n shape(im_ = (Ny,Nx)\n shape(hs) = (Gy,Gx, Hy,Hx)\n\n the input image im is subdivided into (Gy,Gz) blocks\n hs[j,i] is the psf at the center of each block (i,j)\n\n as of now each image dimension has to be divisble by the gr... |
Please provide a description of the function:def _convert_axes_to_absolute(dshape, axes):
if axes is None:
return None
elif isinstance(axes, (tuple, list)):
return tuple(np.arange(len(dshape))[list(axes)])
else:
raise NotImplementedError("axes %s is of unsupported type %s "%(st... | [
"axes = (-2,-1) does not work in reikna, so we have to convetr that"
] |
Please provide a description of the function:def fft_plan(shape, dtype=np.complex64, axes=None, fast_math=True):
# if not axes is None and any([a<0 for a in axes]):
# raise NotImplementedError("indices of axes have to be non negative, but are: %s"%str(axes))
axes = _convert_axes_to_absolute(shape,... | [
"returns an reikna plan/FFT obj of shape dshape\n "
] |
Please provide a description of the function:def fft(arr_obj, res_g=None,
inplace=False,
inverse=False,
axes=None,
plan=None,
fast_math=True):
if plan is None:
plan = fft_plan(arr_obj.shape, arr_obj.dtype,
axes=axes,
... | [
" (inverse) fourier trafo of 1-3D arrays\n\n creates a new plan or uses the given plan\n \n the transformed arr_obj should be either a\n\n - numpy array:\n\n returns the fft as numpy array (inplace is ignored)\n \n - OCLArray of type complex64:\n\n writes transform into res_g if give... |
Please provide a description of the function:def _wrap_OCLArray(cls):
def prepare(arr):
return np.require(arr, None, "C")
@classmethod
def from_array(cls, arr, *args, **kwargs):
queue = get_device().queue
return cl_array.to_device(queue, prepare(arr), *args, **kwargs)
@cl... | [
"\n WRAPPER\n "
] |
Please provide a description of the function:def pad_to_shape(d, dshape, mode = "constant"):
if d.shape == dshape:
return d
diff = np.array(dshape)- np.array(d.shape)
#first shrink
slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff)
res = d[slices]
#then p... | [
"\n pad array d to shape dshape\n "
] |
Please provide a description of the function:def pad_to_power2(data, axis = None, mode="constant"):
if axis is None:
axis = list(range(data.ndim))
if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]):
return data
else:
return pad_to_shape(data,[(_next_power... | [
"\n pad data to a shape of power 2\n if axis == None all axis are padded\n "
] |
Please provide a description of the function:def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
if data.ndim == 2:
_filt = make_filter(_generic_filter_gpu_2d(FUNC = "(val>res?val:res)", DEFAULT = "-INFINITY"))
elif data.ndim == 3:
_filt = make_filter(_generic_filter_gpu_3d(FUNC... | [
"\n maximum filter of given size\n\n Parameters\n ----------\n data: 2 or 3 dimensional ndarray or OCLArray of type float32\n input data\n size: scalar, tuple\n the size of the patch to consider\n res_g: OCLArray\n store result in buffer if given\n sub_blocks:\n ... |
Please provide a description of the function:def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
if data.ndim == 2:
_filt = make_filter(_generic_filter_gpu_2d(FUNC="(val<res?val:res)", DEFAULT="INFINITY"))
elif data.ndim == 3:
_filt = make_filter(_generic_filter_gpu_3d(FUNC="(va... | [
"\n minimum filter of given size\n\n Parameters\n ----------\n data: 2 or 3 dimensional ndarray or OCLArray of type float32\n input data\n size: scalar, tuple\n the size of the patch to consider\n res_g: OCLArray\n store result in buffer if given\n sub_blocks:\n ... |
Please provide a description of the function:def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True):
if normalized:
if np.isscalar(size):
norm = size
else:
norm = np.int32(np.prod(size))**(1./len(size))
FUNC = "res+val/%s"%norm
... | [
"\n mean filter of given size\n\n Parameters\n ----------\n data: 2 or 3 dimensional ndarray or OCLArray of type float32\n input data\n size: scalar, tuple\n the size of the patch to consider\n res_g: OCLArray\n store result in buffer if given\n sub_blocks:\n per... |
Please provide a description of the function:def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)):
truncate = 4.
radius = tuple(int(truncate*s +0.5) for s in sigma)
size = tuple(2*r+1 for r in radius)
s = sigma[0]
if data.ndim == 2:
_filt = make_filter(_generic_filter_gp... | [
"\n gaussian filter of given size\n\n Parameters\n ----------\n data: 2 or 3 dimensional ndarray or OCLArray of type float32\n input data\n size: scalar, tuple\n the size of the patch to consider\n res_g: OCLArray\n store result in buffer if given\n sub_blocks:\n ... |
Please provide a description of the function:def deconv_rl(data, h, Niter=10, mode_conv="fft", log_iter=False):
if isinstance(data, np.ndarray):
mode_data = "np"
elif isinstance(data, OCLArray):
mode_data = "gpu"
else:
raise TypeError("array argument (1) has bad type: %s"%type(... | [
" richardson lucy deconvolution of data with psf h\n using spatial convolutions (h should be small then)\n\n mode_conv = \"fft\" or \"spatial\"\n "
] |
Please provide a description of the function:def _deconv_rl_gpu_conv(data_g, h_g, Niter=10):
# set up some gpu buffers
u_g = OCLArray.empty(data_g.shape, np.float32)
u_g.copy_buffer(data_g)
tmp_g = OCLArray.empty(data_g.shape, np.float32)
tmp2_g = OCLArray.empty(data_g.shape, np.float32)
... | [
"\n using convolve\n\n "
] |
Please provide a description of the function:def _deconv_rl_np_fft(data, h, Niter=10,
h_is_fftshifted=False):
if data.shape!=h.shape:
raise ValueError("data and h have to be same shape")
if not h_is_fftshifted:
h = np.fft.fftshift(h)
hflip = h[::-1, ::-1]
#... | [
" deconvolves data with given psf (kernel) h\n\n data and h have to be same shape\n\n\n via lucy richardson deconvolution\n "
] |
Please provide a description of the function:def _deconv_rl_gpu_fft(data_g, h_g, Niter=10):
if data_g.shape!=h_g.shape:
raise ValueError("data and h have to be same shape")
# set up some gpu buffers
u_g = OCLArray.empty(data_g.shape, np.complex64)
u_g.copy_buffer(data_g)
tmp_g = OCL... | [
"\n using fft_convolve\n\n "
] |
Please provide a description of the function:def _separable_series2(h, N=1):
if min(h.shape)<N:
raise ValueError("smallest dimension of h is smaller than approximation order! (%s < %s)"%(min(h.shape),N))
U, S, V = linalg.svd(h)
hx = [-U[:, n] * np.sqrt(S[n]) for n in range(N)]
hy = [-V[n,... | [
" finds separable approximations to the 2d function 2d h\n\n returns res = (hx, hy)[N]\n s.t. h \\approx sum_i outer(res[i,0],res[i,1])\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.