_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q35200
NewsApiClient.get_top_headlines
train
def get_top_headlines(self, q=None, sources=None, language='en', country=None, category=None, page_size=None, page=None): """ Returns live top and breaking headlines for a country, specific category in a country, single source, or multiple sources.. Optional pa...
python
{ "resource": "" }
q35201
NewsApiClient.get_sources
train
def get_sources(self, category=None, language=None, country=None): """ Returns the subset of news publishers that top headlines... Optional parameters: (str) category - The category you want to get headlines for! Valid values are: 'business','entertainment','general...
python
{ "resource": "" }
q35202
setup_logger
train
def setup_logger(name=None, logfile=None, level=logging.DEBUG, formatter=None, maxBytes=0, backupCount=0, fileLoglevel=None, disableStderrLogger=False): """ Configures and returns a fully configured logger instance, no hassles. If a logger with the specified name already exists, it returns the existing inst...
python
{ "resource": "" }
q35203
to_unicode
train
def to_unicode(value): """ Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value if not isins...
python
{ "resource": "" }
q35204
reset_default_logger
train
def reset_default_logger(): """ Resets the internal default logger to the initial configuration """ global logger global _loglevel global _logfile global _formatter _loglevel = logging.DEBUG _logfile = None _formatter = None logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, ...
python
{ "resource": "" }
q35205
slerp
train
def slerp(R1, R2, t1, t2, t_out): """Spherical linear interpolation of rotors This function uses a simpler interface than the more fundamental `slerp_evaluate` and `slerp_vectorized` functions. The latter are fast, being implemented at the C level, but take input `tau` instead of time. This funct...
python
{ "resource": "" }
q35206
squad
train
def squad(R_in, t_in, t_out): """Spherical "quadrangular" interpolation of rotors with a cubic spline This is the best way to interpolate rotations. It uses the analog of a cubic spline, except that the interpolant is confined to the rotor manifold in a natural way. Alternative methods involving ...
python
{ "resource": "" }
q35207
integrate_angular_velocity
train
def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12): """Compute frame with given angular velocity Parameters ========== Omega: tuple or callable Angular velocity from which to compute frame. Can be 1) a 2-tuple of float arrays (t, v) giving the angular velocity ve...
python
{ "resource": "" }
q35208
minimal_rotation
train
def minimal_rotation(R, t, iterations=2): """Adjust frame so that there is no rotation about z' axis The output of this function is a frame that rotates the z axis onto the same z' axis as the input frame, but with minimal rotation about that axis. This is done by pre-composing the input rotation with...
python
{ "resource": "" }
q35209
mean_rotor_in_chordal_metric
train
def mean_rotor_in_chordal_metric(R, t=None): """Return rotor that is closest to all R in the least-squares sense This can be done (quasi-)analytically because of the simplicity of the chordal metric function. The only approximation is the simple 2nd-order discrete formula for the definite integral of ...
python
{ "resource": "" }
q35210
as_float_array
train
def as_float_array(a): """View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the ...
python
{ "resource": "" }
q35211
as_quat_array
train
def as_quat_array(a): """View a float array as an array of quaternions The input array must have a final dimension whose size is divisible by four (or better yet *is* 4), because successive indices in that last dimension will be considered successive components of the output quaternion. This f...
python
{ "resource": "" }
q35212
as_spinor_array
train
def as_spinor_array(a): """View a quaternion array as spinors in two-complex representation This function is relatively slow and scales poorly, because memory copying is apparently involved -- I think it's due to the "advanced indexing" required to swap the columns. """ a = np.atleast_1d(a) ...
python
{ "resource": "" }
q35213
from_rotation_vector
train
def from_rotation_vector(rot): """Convert input 3-vector in axis-angle representation to unit quaternion Parameters ---------- rot: (Nx3) float array Each vector represents the axis of the rotation, with norm proportional to the angle of the rotation in radians. Returns -------...
python
{ "resource": "" }
q35214
as_euler_angles
train
def as_euler_angles(q): """Open Pandora's Box If somebody is trying to make you use Euler angles, tell them no, and walk away, and go and tell your mum. You don't want to use Euler angles. They are awful. Stay away. It's one thing to convert from Euler angles to quaternions; at least you're ...
python
{ "resource": "" }
q35215
from_euler_angles
train
def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None): """Improve your life drastically Assumes the Euler angles correspond to the quaternion R via R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2) The angles naturally must be in radians for this to make any sense. NOTE: Before op...
python
{ "resource": "" }
q35216
from_spherical_coords
train
def from_spherical_coords(theta_phi, phi=None): """Return the quaternion corresponding to these spherical coordinates Assumes the spherical coordinates correspond to the quaternion R via R = exp(phi*z/2) * exp(theta*y/2) The angles naturally must be in radians for this to make any sense. Not...
python
{ "resource": "" }
q35217
rotate_vectors
train
def rotate_vectors(R, v, axis=-1): """Rotate vectors by given quaternions For simplicity, this function simply converts the input quaternion(s) to a matrix, and rotates the input vector(s) by the usual matrix multiplication. However, it should be noted that if each input quaternion is only used to...
python
{ "resource": "" }
q35218
isclose
train
def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a tolerance. This function is essentially a copy of the `numpy.isclose` function, with different default tolerances and one minor changes necessary to...
python
{ "resource": "" }
q35219
allclose
train
def allclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False, verbose=False): """ Returns True if two arrays are element-wise equal within a tolerance. This function is essentially a wrapper for the `quaternion.isclose` function, but returns a single boolean value of True if all elements ...
python
{ "resource": "" }
q35220
derivative
train
def derivative(f, t): """Fourth-order finite-differencing with non-uniform time steps The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a ...
python
{ "resource": "" }
q35221
autodiscover
train
def autodiscover(): """ Auto-discover INSTALLED_APPS translation.py modules and fail silently when not present. This forces an import on them to register. Also import explicit modules. """ import os import sys import copy from django.utils.module_loading import module_has_submodule ...
python
{ "resource": "" }
q35222
build_css_class
train
def build_css_class(localized_fieldname, prefix=''): """ Returns a css class based on ``localized_fieldname`` which is easily splitable and capable of regionalized language codes. Takes an optional ``prefix`` which is prepended to the returned string. """ bits = localized_fieldname.split('_') ...
python
{ "resource": "" }
q35223
unique
train
def unique(seq): """ Returns a generator yielding unique sequence members in order A set by itself will return unique values without any regard for order. >>> list(unique([1, 2, 3, 2, 2, 4, 1])) [1, 2, 3, 4] """ seen = set() return (x for x in seq if x not in seen and not seen.add(x))
python
{ "resource": "" }
q35224
resolution_order
train
def resolution_order(lang, override=None): """ Return order of languages which should be checked for parameter language. First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES. """ if not settings.ENABLE_FALLBACKS: re...
python
{ "resource": "" }
q35225
fallbacks
train
def fallbacks(enable=True): """ Temporarily switch all language fallbacks on or off. Example: with fallbacks(False): lang_has_slug = bool(self.slug) May be used to enable fallbacks just when they're needed saving on some processing or check if there is a value for the current ...
python
{ "resource": "" }
q35226
parse_field
train
def parse_field(setting, field_name, default): """ Extract result from single-value or dict-type setting like fallback_values. """ if isinstance(setting, dict): return setting.get(field_name, default) else: return setting
python
{ "resource": "" }
q35227
append_translated
train
def append_translated(model, fields): "If translated field is encountered, add also all its translation fields." fields = set(fields) from modeltranslation.translator import translator opts = translator.get_options_for_model(model) for key, translated in opts.fields.items(): if key in fields...
python
{ "resource": "" }
q35228
MultilingualQuerySet._rewrite_col
train
def _rewrite_col(self, col): """Django >= 1.7 column name rewriting""" if isinstance(col, Col): new_name = rewrite_lookup_key(self.model, col.target.name) if col.target.name != new_name: new_field = self.model._meta.get_field(new_name) if col.targe...
python
{ "resource": "" }
q35229
MultilingualQuerySet._rewrite_where
train
def _rewrite_where(self, q): """ Rewrite field names inside WHERE tree. """ if isinstance(q, Lookup): self._rewrite_col(q.lhs) if isinstance(q, Node): for child in q.children: self._rewrite_where(child)
python
{ "resource": "" }
q35230
MultilingualQuerySet._rewrite_q
train
def _rewrite_q(self, q): """Rewrite field names inside Q call.""" if isinstance(q, tuple) and len(q) == 2: return rewrite_lookup_key(self.model, q[0]), q[1] if isinstance(q, Node): q.children = list(map(self._rewrite_q, q.children)) return q
python
{ "resource": "" }
q35231
MultilingualQuerySet._rewrite_f
train
def _rewrite_f(self, q): """ Rewrite field names inside F call. """ if isinstance(q, models.F): q.name = rewrite_lookup_key(self.model, q.name) return q if isinstance(q, Node): q.children = list(map(self._rewrite_f, q.children)) # Djang...
python
{ "resource": "" }
q35232
MultilingualQuerySet.order_by
train
def order_by(self, *field_names): """ Change translatable field names in an ``order_by`` argument to translation fields for the current language. """ if not self._rewrite: return super(MultilingualQuerySet, self).order_by(*field_names) new_args = [] fo...
python
{ "resource": "" }
q35233
add_translation_fields
train
def add_translation_fields(model, opts): """ Monkey patches the original model class to provide additional fields for every language. Adds newly created translation fields to the given translation options. """ model_empty_values = getattr(opts, 'empty_values', NONE) for field_name in opts.l...
python
{ "resource": "" }
q35234
patch_clean_fields
train
def patch_clean_fields(model): """ Patch clean_fields method to handle different form types submission. """ old_clean_fields = model.clean_fields def new_clean_fields(self, exclude=None): if hasattr(self, '_mt_form_pending_clear'): # Some form translation fields has been marked ...
python
{ "resource": "" }
q35235
patch_related_object_descriptor_caching
train
def patch_related_object_descriptor_caching(ro_descriptor): """ Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use language-aware caching. """ class NewSingleObjectDescriptor(LanguageCacheSingleObjectDescriptor, ro_descriptor.__class__): pass if django.VE...
python
{ "resource": "" }
q35236
TranslationOptions.validate
train
def validate(self): """ Perform options validation. """ # TODO: at the moment only required_languages is validated. # Maybe check other options as well? if self.required_languages: if isinstance(self.required_languages, (tuple, list)): self._ch...
python
{ "resource": "" }
q35237
TranslationOptions.update
train
def update(self, other): """ Update with options from a superclass. """ if other.model._meta.abstract: self.local_fields.update(other.local_fields) self.fields.update(other.fields)
python
{ "resource": "" }
q35238
TranslationOptions.add_translation_field
train
def add_translation_field(self, field, translation_field): """ Add a new translation field to both fields dicts. """ self.local_fields[field].add(translation_field) self.fields[field].add(translation_field)
python
{ "resource": "" }
q35239
Translator.get_registered_models
train
def get_registered_models(self, abstract=True): """ Returns a list of all registered models, or just concrete registered models. """ return [model for (model, opts) in self._registry.items() if opts.registered and (not model._meta.abstract or abstract)]
python
{ "resource": "" }
q35240
Translator._get_options_for_model
train
def _get_options_for_model(self, model, opts_class=None, **options): """ Returns an instance of translation options with translated fields defined for the ``model`` and inherited from superclasses. """ if model not in self._registry: # Create a new type for backwards ...
python
{ "resource": "" }
q35241
Translator.get_options_for_model
train
def get_options_for_model(self, model): """ Thin wrapper around ``_get_options_for_model`` to preserve the semantic of throwing exception for models not directly registered. """ opts = self._get_options_for_model(model) if not opts.registered and not opts.related: ...
python
{ "resource": "" }
q35242
Command.get_table_fields
train
def get_table_fields(self, db_table): """ Gets table fields from schema. """ db_table_desc = self.introspection.get_table_description(self.cursor, db_table) return [t[0] for t in db_table_desc]
python
{ "resource": "" }
q35243
Command.get_missing_languages
train
def get_missing_languages(self, field_name, db_table): """ Gets only missings fields. """ db_table_fields = self.get_table_fields(db_table) for lang_code in AVAILABLE_LANGUAGES: if build_localized_fieldname(field_name, lang_code) not in db_table_fields: ...
python
{ "resource": "" }
q35244
Command.get_sync_sql
train
def get_sync_sql(self, field_name, missing_langs, model): """ Returns SQL needed for sync schema for a new translatable field. """ qn = connection.ops.quote_name style = no_style() sql_output = [] db_table = model._meta.db_table for lang in missing_langs: ...
python
{ "resource": "" }
q35245
create_translation_field
train
def create_translation_field(model, field_name, lang, empty_value): """ Translation field factory. Returns a ``TranslationField`` based on a fieldname and a language. The list of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:: MOD...
python
{ "resource": "" }
q35246
TranslationFieldDescriptor.meaningful_value
train
def meaningful_value(self, val, undefined): """ Check if val is considered non-empty. """ if isinstance(val, fields.files.FieldFile): return val.name and not ( isinstance(undefined, fields.files.FieldFile) and val == undefined) return val is not None a...
python
{ "resource": "" }
q35247
LanguageCacheSingleObjectDescriptor.cache_name
train
def cache_name(self): """ Used in django 1.x """ lang = get_language() cache = build_localized_fieldname(self.accessor, lang) return "_%s_cache" % cache
python
{ "resource": "" }
q35248
TranslationBaseModelAdmin.replace_orig_field
train
def replace_orig_field(self, option): """ Replaces each original field in `option` that is registered for translation by its translation fields. Returns a new list with replaced fields. If `option` contains no registered fields, it is returned unmodified. >>> self = Tra...
python
{ "resource": "" }
q35249
TranslationBaseModelAdmin._get_form_or_formset
train
def _get_form_or_formset(self, request, obj, **kwargs): """ Generic code shared by get_form and get_formset. """ if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) ...
python
{ "resource": "" }
q35250
TranslationBaseModelAdmin._get_fieldsets_post_form_or_formset
train
def _get_fieldsets_post_form_or_formset(self, request, form, obj=None): """ Generic get_fieldsets code, shared by TranslationAdmin and TranslationInlineModelAdmin. """ base_fields = self.replace_orig_field(form.base_fields.keys()) fields = base_fields + list(self.get_read...
python
{ "resource": "" }
q35251
ClearableWidgetWrapper.media
train
def media(self): """ Combines media of both components and adds a small script that unchecks the clear box, when a value in any wrapped input is modified. """ return self.widget.media + self.checkbox.media + Media(self.Media)
python
{ "resource": "" }
q35252
ClearableWidgetWrapper.value_from_datadict
train
def value_from_datadict(self, data, files, name): """ If the clear checkbox is checked returns the configured empty value, completely ignoring the original input. """ clear = self.checkbox.value_from_datadict(data, files, self.clear_checkbox_name(name)) if clear: ...
python
{ "resource": "" }
q35253
setup_aiohttp_apispec
train
def setup_aiohttp_apispec( app: web.Application, *, title: str = "API documentation", version: str = "0.0.1", url: str = "/api/docs/swagger.json", request_data_name: str = "data", swagger_path: str = None, static_path: str = '/static/swagger', **kwargs ) -> None: """ aiohttp-...
python
{ "resource": "" }
q35254
docs
train
def docs(**kwargs): """ Annotate the decorated view function with the specified Swagger attributes. Usage: .. code-block:: python from aiohttp import web @docs(tags=['my_tag'], summary='Test method summary', description='Test method description', ...
python
{ "resource": "" }
q35255
response_schema
train
def response_schema(schema, code=200, required=False, description=None): """ Add response info into the swagger spec Usage: .. code-block:: python from aiohttp import web from marshmallow import Schema, fields class ResponseSchema(Schema): msg = fields.Str() ...
python
{ "resource": "" }
q35256
validation_middleware
train
async def validation_middleware(request: web.Request, handler) -> web.Response: """ Validation middleware for aiohttp web app Usage: .. code-block:: python app.middlewares.append(validation_middleware) """ orig_handler = request.match_info.handler if not hasattr(orig_handler, "_...
python
{ "resource": "" }
q35257
is_valid_input_array
train
def is_valid_input_array(x, ndim=None): """Test if ``x`` is a correctly shaped point array in R^d.""" x = np.asarray(x) if ndim is None or ndim == 1: return x.ndim == 1 and x.size > 1 or x.ndim == 2 and x.shape[0] == 1 else: return x.ndim == 2 and x.shape[0] == ndim
python
{ "resource": "" }
q35258
is_valid_input_meshgrid
train
def is_valid_input_meshgrid(x, ndim): """Test if ``x`` is a `meshgrid` sequence for points in R^d.""" # This case is triggered in FunctionSpaceElement.__call__ if the # domain does not have an 'ndim' attribute. We return False and # continue. if ndim is None: return False if not isinsta...
python
{ "resource": "" }
q35259
out_shape_from_meshgrid
train
def out_shape_from_meshgrid(mesh): """Get the broadcast output shape from a `meshgrid`.""" if len(mesh) == 1: return (len(mesh[0]),) else: return np.broadcast(*mesh).shape
python
{ "resource": "" }
q35260
out_shape_from_array
train
def out_shape_from_array(arr): """Get the output shape from an array.""" arr = np.asarray(arr) if arr.ndim == 1: return arr.shape else: return (arr.shape[1],)
python
{ "resource": "" }
q35261
vectorize._wrapper
train
def _wrapper(func, *vect_args, **vect_kwargs): """Return the vectorized wrapper function.""" if not hasattr(func, '__name__'): # Set name if not available. Happens if func is actually a function func.__name__ = '{}.__call__'.format(func.__class__.__name__) return wraps(f...
python
{ "resource": "" }
q35262
ProductSpaceOperator._convert_to_spmatrix
train
def _convert_to_spmatrix(operators): """Convert an array-like object of operators to a sparse matrix.""" # Lazy import to improve `import odl` time import scipy.sparse # Convert ops to sparse representation. This is not trivial because # operators can be indexable themselves and...
python
{ "resource": "" }
q35263
ProductSpaceOperator._call
train
def _call(self, x, out=None): """Call the operators on the parts of ``x``.""" # TODO: add optimization in case an operator appears repeatedly in a # row if out is None: out = self.range.zero() for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data): ...
python
{ "resource": "" }
q35264
ProductSpaceOperator.derivative
train
def derivative(self, x): """Derivative of the product space operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear`ProductSpaceOperator` The derivative Examples ...
python
{ "resource": "" }
q35265
ComponentProjection._call
train
def _call(self, x, out=None): """Project ``x`` onto the subspace.""" if out is None: out = x[self.index].copy() else: out.assign(x[self.index]) return out
python
{ "resource": "" }
q35266
ComponentProjectionAdjoint._call
train
def _call(self, x, out=None): """Extend ``x`` from the subspace.""" if out is None: out = self.range.zero() else: out.set_zero() out[self.index] = x return out
python
{ "resource": "" }
q35267
BroadcastOperator._call
train
def _call(self, x, out=None): """Evaluate all operators in ``x`` and broadcast.""" wrapped_x = self.prod_op.domain.element([x], cast=False) return self.prod_op(wrapped_x, out=out)
python
{ "resource": "" }
q35268
BroadcastOperator.derivative
train
def derivative(self, x): """Derivative of the broadcast operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear `BroadcastOperator` The derivative Examples ...
python
{ "resource": "" }
q35269
ReductionOperator._call
train
def _call(self, x, out=None): """Apply operators to ``x`` and sum.""" if out is None: return self.prod_op(x)[0] else: wrapped_out = self.prod_op.range.element([out], cast=False) pspace_result = self.prod_op(x, out=wrapped_out) return pspace_result[...
python
{ "resource": "" }
q35270
ReductionOperator.derivative
train
def derivative(self, x): """Derivative of the reduction operator. Parameters ---------- x : `domain` element The point to take the derivative in. Returns ------- derivative : linear `BroadcastOperator` Examples -------- >>> r...
python
{ "resource": "" }
q35271
load_julia_with_Shearlab
train
def load_julia_with_Shearlab(): """Function to load Shearlab.""" # Importing base j = julia.Julia() j.eval('using Shearlab') j.eval('using PyPlot') j.eval('using Images') return j
python
{ "resource": "" }
q35272
load_image
train
def load_image(name, n, m=None, gpu=None, square=None): """Function to load images with certain size.""" if m is None: m = n if gpu is None: gpu = 0 if square is None: square = 0 command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name, n, m, gpu, squ...
python
{ "resource": "" }
q35273
imageplot
train
def imageplot(f, str=None, sbpt=None): """Plot an image generated by the library.""" # Function to plot images if str is None: str = '' if sbpt is None: sbpt = [] if sbpt != []: plt.subplot(sbpt[0], sbpt[1], sbpt[2]) imgplot = plt.imshow(f, interpolation='nearest') im...
python
{ "resource": "" }
q35274
getshearletsystem2D
train
def getshearletsystem2D(rows, cols, nScales, shearLevels=None, full=None, directionalFilter=None, quadratureMirrorFilter=None): """Function to generate de 2D system.""" if shearLevels is None: shearLevels = [float(ceil(i / 2)) for i...
python
{ "resource": "" }
q35275
sheardec2D
train
def sheardec2D(X, shearletsystem): """Shearlet Decomposition function.""" coeffs = np.zeros(shearletsystem.shearlets.shape, dtype=complex) Xfreq = fftshift(fft2(ifftshift(X))) for i in range(shearletsystem.nShearlets): coeffs[:, :, i] = fftshift(ifft2(ifftshift(Xfreq * np.conj( ...
python
{ "resource": "" }
q35276
ShearlabOperator.adjoint
train
def adjoint(self): """The adjoint operator.""" op = self class ShearlabOperatorAdjoint(odl.Operator): """Adjoint of the shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): ...
python
{ "resource": "" }
q35277
ShearlabOperator.inverse
train
def inverse(self): """The inverse operator.""" op = self class ShearlabOperatorInverse(odl.Operator): """Inverse of the shearlet transform. See Also -------- odl.contrib.shearlab.ShearlabOperator """ def __init__(self): ...
python
{ "resource": "" }
q35278
submarine
train
def submarine(space, smooth=True, taper=20.0): """Return a 'submarine' phantom consisting in an ellipsoid and a box. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. smooth : bool, optional If ``True``, the boundaries are s...
python
{ "resource": "" }
q35279
_submarine_2d_smooth
train
def _submarine_2d_smooth(space, taper): """Return a 2d smooth 'submarine' phantom.""" def logistic(x, c): """Smoothed step function from 0 to 1, centered at 0.""" return 1. / (1 + np.exp(-c * x)) def blurred_ellipse(x): """Blurred characteristic function of an ellipse. If ...
python
{ "resource": "" }
q35280
_submarine_2d_nonsmooth
train
def _submarine_2d_nonsmooth(space): """Return a 2d nonsmooth 'submarine' phantom.""" def ellipse(x): """Characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. Fo...
python
{ "resource": "" }
q35281
text
train
def text(space, text, font=None, border=0.2, inverted=True): """Create phantom from text. The text is represented by a scalar image taking values in [0, 1]. Depending on the choice of font, the text may or may not be anti-aliased. anti-aliased text can take any value between 0 and 1, while non-anti...
python
{ "resource": "" }
q35282
Weighting.norm
train
def norm(self, x): """Calculate the norm of an element. This is the standard implementation using `inner`. Subclasses should override it for optimization purposes. Parameters ---------- x1 : `LinearSpaceElement` Element whose norm is calculated. Ret...
python
{ "resource": "" }
q35283
MatrixWeighting.is_valid
train
def is_valid(self): """Test if the matrix is positive definite Hermitian. If the matrix decomposition is available, this test checks if all eigenvalues are positive. Otherwise, the test tries to calculate a Cholesky decomposition, which can be very time-consuming for large matri...
python
{ "resource": "" }
q35284
MatrixWeighting.matrix_decomp
train
def matrix_decomp(self, cache=None): """Compute a Hermitian eigenbasis decomposition of the matrix. Parameters ---------- cache : bool or None, optional If ``True``, store the decomposition internally. For None, the ``cache_mat_decomp`` from class initialization ...
python
{ "resource": "" }
q35285
ArrayWeighting.equiv
train
def equiv(self, other): """Return True if other is an equivalent weighting. Returns ------- equivalent : bool ``True`` if ``other`` is a `Weighting` instance with the same `Weighting.impl`, which yields the same result as this weighting for any input,...
python
{ "resource": "" }
q35286
dca
train
def dca(x, f, g, niter, callback=None): r"""Subgradient DCA of Tao and An. This algorithm solves a problem of the form :: min_x f(x) - g(x), where ``f`` and ``g`` are proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpaceElement` Initial...
python
{ "resource": "" }
q35287
prox_dca
train
def prox_dca(x, f, g, niter, gamma, callback=None): r"""Proximal DCA of Sun, Sampaio and Candido. This algorithm solves a problem of the form :: min_x f(x) - g(x) where ``f`` and ``g`` are two proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpa...
python
{ "resource": "" }
q35288
doubleprox_dc
train
def doubleprox_dc(x, y, f, phi, g, K, niter, gamma, mu, callback=None): r"""Double-proxmial gradient d.c. algorithm of Banert and Bot. This algorithm solves a problem of the form :: min_x f(x) + phi(x) - g(Kx). Parameters ---------- x : `LinearSpaceElement` Initial primal guess, u...
python
{ "resource": "" }
q35289
doubleprox_dc_simple
train
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu): """Non-optimized version of ``doubleprox_dc``. This function is intended for debugging. It makes a lot of copies and performs no error checking. """ for _ in range(niter): f.proximal(gamma)(x + gamma * K.adjoint(y) - ...
python
{ "resource": "" }
q35290
matrix_representation
train
def matrix_representation(op): """Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- ...
python
{ "resource": "" }
q35291
power_method_opnorm
train
def power_method_opnorm(op, xstart=None, maxiter=100, rtol=1e-05, atol=1e-08, callback=None): r"""Estimate the operator norm with the power method. Parameters ---------- op : `Operator` Operator whose norm is to be estimated. If its `Operator.range` range does no...
python
{ "resource": "" }
q35292
as_scipy_operator
train
def as_scipy_operator(op): """Wrap ``op`` as a ``scipy.sparse.linalg.LinearOperator``. This is intended to be used with the scipy sparse linear solvers. Parameters ---------- op : `Operator` A linear operator that should be wrapped Returns ------- ``scipy.sparse.linalg.LinearO...
python
{ "resource": "" }
q35293
as_scipy_functional
train
def as_scipy_functional(func, return_gradient=False): """Wrap ``op`` as a function operating on linear arrays. This is intended to be used with the `scipy solvers <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_. Parameters ---------- func : `Functional`. A functional that ...
python
{ "resource": "" }
q35294
as_proximal_lang_operator
train
def as_proximal_lang_operator(op, norm_bound=None): """Wrap ``op`` as a ``proximal.BlackBox``. This is intended to be used with the `ProxImaL language solvers. <https://github.com/comp-imaging/proximal>`_ For documentation on the proximal language (ProxImaL) see [Hei+2016]. Parameters -------...
python
{ "resource": "" }
q35295
skimage_sinogram_space
train
def skimage_sinogram_space(geometry, volume_space, sinogram_space): """Create a range adapted to the skimage radon geometry.""" padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2))) det_width = volume_space.domain.extent[0] * np.sqrt(2) skimage_detector_part = uniform_partition(-det_width / 2.0...
python
{ "resource": "" }
q35296
clamped_interpolation
train
def clamped_interpolation(skimage_range, sinogram): """Interpolate in a possibly smaller space. Sets all points that would be outside the domain to match the boundary values. """ min_x = skimage_range.domain.min()[1] max_x = skimage_range.domain.max()[1] def interpolation_wrapper(x): ...
python
{ "resource": "" }
q35297
ScalingOperator._call
train
def _call(self, x, out=None): """Scale ``x`` and write to ``out`` if given.""" if out is None: out = self.scalar * x else: out.lincomb(self.scalar, x) return out
python
{ "resource": "" }
q35298
ScalingOperator.inverse
train
def inverse(self): """Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec Tru...
python
{ "resource": "" }
q35299
ScalingOperator.adjoint
train
def adjoint(self): """Adjoint, given as scaling with the conjugate of the scalar. Examples -------- In the real case, the adjoint is the same as the operator: >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2) >>> op(x) ...
python
{ "resource": "" }