code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _zero_preserving_modulo_inner_loop( values: np.ndarray, n: int, to_zero: int, out: np.ndarray ) -> np.ndarray: """``(values - 1) % n + 1``, but with one specific value mapped to 0. This ensures (1) an output value in [0, n] (inclusive), and (2) that no nonzero values in the input are zero in the ou...
``(values - 1) % n + 1``, but with one specific value mapped to 0. This ensures (1) an output value in [0, n] (inclusive), and (2) that no nonzero values in the input are zero in the output, other than the ``to_zero`` value. Parameters ---------- values : np.ndarray The dividend of the...
_zero_preserving_modulo_inner_loop
python
napari/napari
src/napari/utils/colormaps/_accelerated_cmap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_accelerated_cmap.py
BSD-3-Clause
def clip(data: np.ndarray, min_val: int, max_val: int) -> np.ndarray: """ Clip data to the given range. """ dtype_info = np.iinfo(data.dtype) min_val = max(min_val, dtype_info.min) max_val = min(max_val, dtype_info.max) return np.clip(data, min_val, max_val)
Clip data to the given range.
clip
python
napari/napari
src/napari/utils/colormaps/_accelerated_cmap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_accelerated_cmap.py
BSD-3-Clause
def _labels_raw_to_texture_direct_numpy( data: np.ndarray, direct_colormap: 'DirectLabelColormap' ) -> np.ndarray: """Convert labels data to the data type used in the texture. This implementation uses numpy vectorized operations. See `_cast_labels_data_to_texture_dtype_direct` for more details. ""...
Convert labels data to the data type used in the texture. This implementation uses numpy vectorized operations. See `_cast_labels_data_to_texture_dtype_direct` for more details.
_labels_raw_to_texture_direct_numpy
python
napari/napari
src/napari/utils/colormaps/_accelerated_cmap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_accelerated_cmap.py
BSD-3-Clause
def _labels_raw_to_texture_direct_loop( data: np.ndarray, direct_colormap: 'DirectLabelColormap' ) -> np.ndarray: """ Cast direct labels to the minimum type. Parameters ---------- data : np.ndarray The input data array. direct_colormap : DirectLabelColormap The direct colorm...
Cast direct labels to the minimum type. Parameters ---------- data : np.ndarray The input data array. direct_colormap : DirectLabelColormap The direct colormap. Returns ------- np.ndarray The cast data array.
_labels_raw_to_texture_direct_loop
python
napari/napari
src/napari/utils/colormaps/_accelerated_cmap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_accelerated_cmap.py
BSD-3-Clause
def _labels_raw_to_texture_direct_inner_loop( data: np.ndarray, dkt: 'typed.Dict', out: np.ndarray ) -> np.ndarray: """ Relabel data using typed dict with mapping unknown labels to default value """ # The numba typed dict does not provide official Api for # determine key and value types for ...
Relabel data using typed dict with mapping unknown labels to default value
_labels_raw_to_texture_direct_inner_loop
python
napari/napari
src/napari/utils/colormaps/_accelerated_cmap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_accelerated_cmap.py
BSD-3-Clause
def revcmap(data): """Can only handle specification *data* in dictionary format.""" data_r = {} for key, val in data.items(): if callable(val): valnew = _reverser(val) # This doesn't work: lambda x: val(1-x) # The same "val" (the first one) is used # e...
Can only handle specification *data* in dictionary format.
revcmap
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def _reverse_cmap_spec(spec): """Reverses cmap specification *spec*, can handle both dict and tuple type specs.""" if 'listed' in spec: return {'listed': spec['listed'][::-1]} if 'red' in spec: return revcmap(spec) else: revspec = list(reversed(spec)) if len(revspec...
Reverses cmap specification *spec*, can handle both dict and tuple type specs.
_reverse_cmap_spec
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def _generate_cmap(name, lutsize): """Generates the requested cmap from its *name*. The lut size is *lutsize*.""" spec = datad[name] # Generate the colormap object. if 'red' in spec: return colors.LinearSegmentedColormap(name, spec, lutsize) elif 'listed' in spec: return color...
Generates the requested cmap from its *name*. The lut size is *lutsize*.
_generate_cmap
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def register_cmap(name=None, cmap=None, data=None, lut=None): """ Add a colormap to the set recognized by :func:`get_cmap`. It can be used in two ways:: register_cmap(name='swirly', cmap=swirly_cmap) register_cmap(name='choppy', data=choppydata, lut=128) In the first case, *cmap* mus...
Add a colormap to the set recognized by :func:`get_cmap`. It can be used in two ways:: register_cmap(name='swirly', cmap=swirly_cmap) register_cmap(name='choppy', data=choppydata, lut=128) In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap` instance. The *name* ...
register_cmap
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def get_cmap(name=None, lut=None): """ Get a colormap instance, defaulting to rc values if *name* is None. Colormaps added with :func:`register_cmap` take precedence over built-in colormaps. If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be returned. If *lut* is not ...
Get a colormap instance, defaulting to rc values if *name* is None. Colormaps added with :func:`register_cmap` take precedence over built-in colormaps. If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be returned. If *lut* is not None it must be an integer giving the numb...
get_cmap
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def __init__(self, norm=None, cmap=None): r""" Parameters ---------- norm : :class:`matplotlib.colors.Normalize` instance The normalizing object which scales data, typically into the interval ``[0, 1]``. If *None*, *norm* defaults to a *colors.Normaliz...
Parameters ---------- norm : :class:`matplotlib.colors.Normalize` instance The normalizing object which scales data, typically into the interval ``[0, 1]``. If *None*, *norm* defaults to a *colors.Normalize* object which initializes its scaling ba...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def to_rgba(self, x, alpha=None, bytes=False, norm=True): """ Return a normalized rgba array corresponding to *x*. In the normal case, *x* is a 1-D or 2-D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for t...
Return a normalized rgba array corresponding to *x*. In the normal case, *x* is a 1-D or 2-D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling ...
to_rgba
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def set_array(self, A): """Set the image array from numpy array *A*. Parameters ---------- A : ndarray """ self._A = A self.update_dict['array'] = True
Set the image array from numpy array *A*. Parameters ---------- A : ndarray
set_array
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def set_cmap(self, cmap): """ set the colormap for luminance data Parameters ---------- cmap : colormap or registered colormap name """ cmap = get_cmap(cmap) self.cmap = cmap self.changed()
set the colormap for luminance data Parameters ---------- cmap : colormap or registered colormap name
set_cmap
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def set_norm(self, norm): """Set the normalization instance. Parameters ---------- norm : `.Normalize` """ if norm is None: norm = colors.Normalize() self.norm = norm self.changed()
Set the normalization instance. Parameters ---------- norm : `.Normalize`
set_norm
python
napari/napari
src/napari/utils/colormaps/vendored/cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/cm.py
BSD-3-Clause
def is_color_like(c): """Return whether *c* can be interpreted as an RGB(A) color.""" try: to_rgba(c) except ValueError: return False else: return True
Return whether *c* can be interpreted as an RGB(A) color.
is_color_like
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def to_rgba(c, alpha=None): """ Convert *c* to an RGBA color. Parameters ---------- c : Matplotlib color alpha : scalar, optional If *alpha* is not ``None``, it forces the alpha value, except if *c* is ``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``. Re...
Convert *c* to an RGBA color. Parameters ---------- c : Matplotlib color alpha : scalar, optional If *alpha* is not ``None``, it forces the alpha value, except if *c* is ``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``. Returns ------- tuple ...
to_rgba
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def _to_rgba_no_colorcycle(c, alpha=None): """Convert *c* to an RGBA color, with no support for color-cycle syntax. If *alpha* is not ``None``, it forces the alpha value, except if *c* is ``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``. """ orig_c = c if isinstance(c, str):...
Convert *c* to an RGBA color, with no support for color-cycle syntax. If *alpha* is not ``None``, it forces the alpha value, except if *c* is ``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.
_to_rgba_no_colorcycle
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def to_rgba_array(c, alpha=None): """Convert *c* to a (n, 4) array of RGBA colors. If *alpha* is not ``None``, it forces the alpha value. If *c* is ``"none"`` (case-insensitive) or an empty list, an empty array is returned. """ # Special-case inputs that are already arrays, for performance. (If t...
Convert *c* to a (n, 4) array of RGBA colors. If *alpha* is not ``None``, it forces the alpha value. If *c* is ``"none"`` (case-insensitive) or an empty list, an empty array is returned.
to_rgba_array
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def to_hex(c, keep_alpha=False): """Convert *c* to a hex color. Uses the ``#rrggbb`` format if *keep_alpha* is False (the default), ``#rrggbbaa`` otherwise. """ c = to_rgba(c) if not keep_alpha: c = c[:3] return "#" + "".join(format(int(np.round(val * 255)), "02x") ...
Convert *c* to a hex color. Uses the ``#rrggbb`` format if *keep_alpha* is False (the default), ``#rrggbbaa`` otherwise.
to_hex
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def makeMappingArray(N, data, gamma=1.0): """Create an *N* -element 1-d lookup table *data* represented by a list of x,y0,y1 mapping correspondences. Each element in this list represents how a value between 0 and 1 (inclusive) represented by x is mapped to a corresponding value between 0 and 1 (inc...
Create an *N* -element 1-d lookup table *data* represented by a list of x,y0,y1 mapping correspondences. Each element in this list represents how a value between 0 and 1 (inclusive) represented by x is mapped to a corresponding value between 0 and 1 (inclusive). The two values of y are to allow for...
makeMappingArray
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, name, N=256): """ Parameters ---------- name : str The name of the colormap. N : int The number of rgb quantization levels. """ self.name = name self.N = int(N) # ensure that N is always int self._rgba_b...
Parameters ---------- name : str The name of the colormap. N : int The number of rgb quantization levels.
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __call__(self, X, alpha=None, bytes=False): """ Parameters ---------- X : scalar, ndarray The data value(s) to convert to RGBA. For floats, X should be in the interval ``[0.0, 1.0]`` to return the RGBA values ``X*100`` percent along the Colormap li...
Parameters ---------- X : scalar, ndarray The data value(s) to convert to RGBA. For floats, X should be in the interval ``[0.0, 1.0]`` to return the RGBA values ``X*100`` percent along the Colormap line. For integers, X should be in the interval `...
__call__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __copy__(self): """Create new object with the same class, update attributes """ cls = self.__class__ cmapobject = cls.__new__(cls) cmapobject.__dict__.update(self.__dict__) if self._isinit: cmapobject._lut = np.copy(self._lut) return cmapobject
Create new object with the same class, update attributes
__copy__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def set_under(self, color='k', alpha=None): """Set color to be used for low out-of-range values. Requires norm.clip = False """ self._rgba_under = to_rgba(color, alpha) if self._isinit: self._set_extremes()
Set color to be used for low out-of-range values. Requires norm.clip = False
set_under
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def set_over(self, color='k', alpha=None): """Set color to be used for high out-of-range values. Requires norm.clip = False """ self._rgba_over = to_rgba(color, alpha) if self._isinit: self._set_extremes()
Set color to be used for high out-of-range values. Requires norm.clip = False
set_over
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, name, segmentdata, N=256, gamma=1.0): """Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are option...
Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 o...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def from_list(name, colors, N=256, gamma=1.0): """ Make a linear segmented colormap with *name* from a sequence of *colors* which evenly transitions from colors[0] at val=0 to colors[-1] at val=1. *N* is the number of rgb quantization levels. Alternatively, a list of (va...
Make a linear segmented colormap with *name* from a sequence of *colors* which evenly transitions from colors[0] at val=0 to colors[-1] at val=1. *N* is the number of rgb quantization levels. Alternatively, a list of (value, color) tuples can be given to divide the rang...
from_list
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def reversed(self, name=None): """ Make a reversed instance of the Colormap. Parameters ---------- name : str, optional The name for the reversed colormap. If it's None the name will be the name of the parent colormap + "_r". Returns ----...
Make a reversed instance of the Colormap. Parameters ---------- name : str, optional The name for the reversed colormap. If it's None the name will be the name of the parent colormap + "_r". Returns ------- LinearSegmentedColormap ...
reversed
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, colors, name='from_list', N=None): """ Make a colormap from a list of colors. *colors* a list of matplotlib color specifications, or an equivalent Nx3 or Nx4 floating point array (*N* rgb or rgba values) *name* a string ...
Make a colormap from a list of colors. *colors* a list of matplotlib color specifications, or an equivalent Nx3 or Nx4 floating point array (*N* rgb or rgba values) *name* a string to identify the colormap *N* the number of en...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def _resample(self, lutsize): """ Return a new color map with *lutsize* entries. """ colors = self(np.linspace(0, 1, lutsize)) return ListedColormap(colors, name=self.name)
Return a new color map with *lutsize* entries.
_resample
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def reversed(self, name=None): """ Make a reversed instance of the Colormap. Parameters ---------- name : str, optional The name for the reversed colormap. If it's None the name will be the name of the parent colormap + "_r". Returns ----...
Make a reversed instance of the Colormap. Parameters ---------- name : str, optional The name for the reversed colormap. If it's None the name will be the name of the parent colormap + "_r". Returns ------- ListedColormap A r...
reversed
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, vmin=None, vmax=None, clip=False): """ If *vmin* or *vmax* is not given, they are initialized from the minimum and maximum value respectively of the first input processed. That is, *__call__(A)* calls *autoscale_None(A)*. If *clip* is *True* and the given valu...
If *vmin* or *vmax* is not given, they are initialized from the minimum and maximum value respectively of the first input processed. That is, *__call__(A)* calls *autoscale_None(A)*. If *clip* is *True* and the given value falls outside the range, the returned value will be 0 o...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def process_value(value): """ Homogenize the input *value* for easy and efficient normalization. *value* can be a scalar or sequence. Returns *result*, *is_scalar*, where *result* is a masked array matching *value*. Float dtypes are preserved; integer types with two by...
Homogenize the input *value* for easy and efficient normalization. *value* can be a scalar or sequence. Returns *result*, *is_scalar*, where *result* is a masked array matching *value*. Float dtypes are preserved; integer types with two bytes or smaller are converted to ...
process_value
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __call__(self, value, clip=None): """ Normalize *value* data in the ``[vmin, vmax]`` interval into the ``[0.0, 1.0]`` interval and return it. *clip* defaults to *self.clip* (which defaults to *False*). If not already initialized, *vmin* and *vmax* are initialized using ...
Normalize *value* data in the ``[vmin, vmax]`` interval into the ``[0.0, 1.0]`` interval and return it. *clip* defaults to *self.clip* (which defaults to *False*). If not already initialized, *vmin* and *vmax* are initialized using *autoscale_None(value)*.
__call__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def autoscale(self, A): """Set *vmin*, *vmax* to min, max of *A*.""" A = np.asanyarray(A) self.vmin = A.min() self.vmax = A.max()
Set *vmin*, *vmax* to min, max of *A*.
autoscale
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def autoscale_None(self, A): """Autoscale only None-valued vmin or vmax.""" A = np.asanyarray(A) if self.vmin is None and A.size: self.vmin = A.min() if self.vmax is None and A.size: self.vmax = A.max()
Autoscale only None-valued vmin or vmax.
autoscale_None
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, linthresh, linscale=1.0, vmin=None, vmax=None, clip=False): """ *linthresh*: The range within which the plot is linear (to avoid having the plot go to infinity around zero). *linscale*: This allows the linear range (-*linthresh* to *l...
*linthresh*: The range within which the plot is linear (to avoid having the plot go to infinity around zero). *linscale*: This allows the linear range (-*linthresh* to *linthresh*) to be stretched relative to the logarithmic range. Its value is the number of de...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def _transform_vmin_vmax(self): """Calculates vmin and vmax in the transformed system.""" vmin, vmax = self.vmin, self.vmax arr = np.array([vmax, vmin]).astype(float) self._upper, self._lower = self._transform(arr)
Calculates vmin and vmax in the transformed system.
_transform_vmin_vmax
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, boundaries, ncolors, clip=False): """ Parameters ---------- boundaries : array-like Monotonically increasing sequence of boundaries ncolors : int Number of colors in the colormap to be used clip : bool, optional If ...
Parameters ---------- boundaries : array-like Monotonically increasing sequence of boundaries ncolors : int Number of colors in the colormap to be used clip : bool, optional If clip is ``True``, out of range values are mapped to 0 if they ...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def rgb_to_hsv(arr): """ Convert float rgb values (in the range [0, 1]), in a numpy array to hsv values. Parameters ---------- arr : (..., 3) array-like All values must be in the range [0, 1] Returns ------- hsv : (..., 3) ndarray Colors converted to hsv values in r...
Convert float rgb values (in the range [0, 1]), in a numpy array to hsv values. Parameters ---------- arr : (..., 3) array-like All values must be in the range [0, 1] Returns ------- hsv : (..., 3) ndarray Colors converted to hsv values in range [0, 1]
rgb_to_hsv
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def hsv_to_rgb(hsv): """ Convert hsv values to rgb. Parameters ---------- hsv : (..., 3) array-like All values assumed to be in range [0, 1] Returns ------- rgb : (..., 3) ndarray Colors converted to RGB values in range [0, 1] """ hsv = np.asarray(hsv) # ch...
Convert hsv values to rgb. Parameters ---------- hsv : (..., 3) array-like All values assumed to be in range [0, 1] Returns ------- rgb : (..., 3) ndarray Colors converted to RGB values in range [0, 1]
hsv_to_rgb
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1, hsv_min_sat=1, hsv_max_sat=0): """ Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees. Parameters ...
Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees. Parameters ---------- azdeg : number, optional The azimuth (0-360, degrees clockwise from North) of the light ...
__init__
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def direction(self): """ The unit vector direction towards the light source """ # Azimuth is in degrees clockwise from North. Convert to radians # counterclockwise from East (mathematical notation). az = np.radians(90 - self.azdeg) alt = np.radians(self.altdeg) return n...
The unit vector direction towards the light source
direction
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.): """ Calculates the illumination intensity for a surface using the defined azimuth and elevation for the light source. This computes the normal vectors for the surface, and then passes them on to `shade_normals...
Calculates the illumination intensity for a surface using the defined azimuth and elevation for the light source. This computes the normal vectors for the surface, and then passes them on to `shade_normals` Parameters ---------- elevation : array-like ...
hillshade
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def shade_normals(self, normals, fraction=1.): """ Calculates the illumination intensity for the normal vectors of a surface using the defined azimuth and elevation for the light source. Imagine an artificial sun placed at infinity in some azimuth and elevation position illumina...
Calculates the illumination intensity for the normal vectors of a surface using the defined azimuth and elevation for the light source. Imagine an artificial sun placed at infinity in some azimuth and elevation position illuminating our surface. The parts of the surface that sl...
shade_normals
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None, vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs): """ Combine colormapped data values with an illumination intensity map (a.k.a. "hillshade") of the values. Parameters ---------- ...
Combine colormapped data values with an illumination intensity map (a.k.a. "hillshade") of the values. Parameters ---------- data : array-like A 2d array (or equivalent) of the height values used to generate a shaded map. cmap : `~matplotlib.col...
shade
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv', vert_exag=1, dx=1, dy=1, **kwargs): """ Use this light source to adjust the colors of the *rgb* input array to give the impression of a shaded relief map with the given `elevation`. Parameters -...
Use this light source to adjust the colors of the *rgb* input array to give the impression of a shaded relief map with the given `elevation`. Parameters ---------- rgb : array-like An (M, N, 3) RGB array, assumed to be in the range of 0 to 1. elevation : arr...
shade_rgb
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None, hsv_min_val=None, hsv_min_sat=None): """ Take the input data array, convert to HSV values in the given colormap, then adjust those color values to give the impression of a shaded relief map with a s...
Take the input data array, convert to HSV values in the given colormap, then adjust those color values to give the impression of a shaded relief map with a specified light source. RGBA values are returned, which can then be used to plot the shaded image with imshow. The color ...
blend_hsv
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def blend_overlay(self, rgb, intensity): """ Combines an rgb image with an intensity map using "overlay" blending. Parameters ---------- rgb : ndarray An MxNx3 RGB array of floats ranging from 0 to 1 (color image). intensity : ndarray An MxNx1 arr...
Combines an rgb image with an intensity map using "overlay" blending. Parameters ---------- rgb : ndarray An MxNx3 RGB array of floats ranging from 0 to 1 (color image). intensity : ndarray An MxNx1 array of floats ranging from 0 to 1 (grayscale image). ...
blend_overlay
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def from_levels_and_colors(levels, colors, extend='neither'): """ A helper routine to generate a cmap and a norm instance which behave similar to contourf's levels and colors arguments. Parameters ---------- levels : sequence of numbers The quantization levels used to construct the :cla...
A helper routine to generate a cmap and a norm instance which behave similar to contourf's levels and colors arguments. Parameters ---------- levels : sequence of numbers The quantization levels used to construct the :class:`BoundaryNorm`. Values ``v`` are quantizized to level ``i`...
from_levels_and_colors
python
napari/napari
src/napari/utils/colormaps/vendored/colors.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/colors.py
BSD-3-Clause
def _ch_helper(gamma, s, r, h, p0, p1, x): """Helper function for generating picklable cubehelix color maps.""" # Apply gamma factor to emphasise low or high intensity values xg = x ** gamma # Calculate amplitude and angle of deviation from the black to white # diagonal in the plane of constant perc...
Helper function for generating picklable cubehelix color maps.
_ch_helper
python
napari/napari
src/napari/utils/colormaps/vendored/_cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/_cm.py
BSD-3-Clause
def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0): """ Return custom data dictionary of (r,g,b) conversion functions, which can be used with :func:`register_cmap`, for the cubehelix color scheme. Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in ter...
Return custom data dictionary of (r,g,b) conversion functions, which can be used with :func:`register_cmap`, for the cubehelix color scheme. Unlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a...
cubehelix
python
napari/napari
src/napari/utils/colormaps/vendored/_cm.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/vendored/_cm.py
BSD-3-Clause
def test_categorical_colormap_direct(): """Test a categorical colormap with a provided mapping""" colormap = {'hi': np.array([1, 1, 1, 1]), 'hello': np.array([0, 0, 0, 0])} cmap = CategoricalColormap(colormap=colormap) color = cmap.map(['hi']) np.testing.assert_allclose(color, [[1, 1, 1, 1]]) c...
Test a categorical colormap with a provided mapping
test_categorical_colormap_direct
python
napari/napari
src/napari/utils/colormaps/_tests/test_categorical_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_categorical_colormap.py
BSD-3-Clause
def test_linear_colormap_with_control_points(): """Test a linear colormap with control points.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) cmap = Colormap(colors, name='testing', controls=[0, 0.75, 1]) assert cmap.name == 'testing' assert cmap.interpolation == 'linear' asse...
Test a linear colormap with control points.
test_linear_colormap_with_control_points
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_non_ascending_control_points(): """Test non ascending control points raises an error.""" colors = np.array( [[0, 0, 0, 1], [0, 0.5, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]] ) with pytest.raises( ValidationError, match='need to be sorted in ascending order' ): Colormap(colo...
Test non ascending control points raises an error.
test_non_ascending_control_points
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_wrong_number_control_points(): """Test wrong number of control points raises an error.""" colors = np.array( [[0, 0, 0, 1], [0, 0.5, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]] ) with pytest.raises( ValidationError, match='Wrong number of control points' ): Colormap(colors, n...
Test wrong number of control points raises an error.
test_wrong_number_control_points
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_wrong_start_control_point(): """Test wrong start of control points raises an error.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) with pytest.raises( ValidationError, match='must start with 0.0 and end with 1.0' ): Colormap(colors, name='testing', controls=[0....
Test wrong start of control points raises an error.
test_wrong_start_control_point
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_wrong_end_control_point(): """Test wrong end of control points raises an error.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) with pytest.raises( ValidationError, match='must start with 0.0 and end with 1.0' ): Colormap(colors, name='testing', controls=[0, 0.7...
Test wrong end of control points raises an error.
test_wrong_end_control_point
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_direct_colormap_with_values_outside_data_dtype(): """https://github.com/napari/napari/pull/6998#issuecomment-2176070672""" color_dict = { 1: np.array([1, 0, 1, 1]), 2: np.array([0, 1, 0, 1]), 257: np.array([1, 1, 1, 1]), None: np.array([0, 0, 0, 0]), } cmap = Dir...
https://github.com/napari/napari/pull/6998#issuecomment-2176070672
test_direct_colormap_with_values_outside_data_dtype
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormap.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormap.py
BSD-3-Clause
def test_can_accept_vispy_colormaps(): """Test that we can accept vispy colormaps.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) vispy_cmap = VispyColormap(colors) cmap = ensure_colormap(vispy_cmap) assert isinstance(cmap, Colormap) np.testing.assert_almost_equal(cmap.colors, ...
Test that we can accept vispy colormaps.
test_can_accept_vispy_colormaps
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_napari_colormaps(): """Test that we can accept napari colormaps.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) napari_cmap = Colormap(colors) cmap = ensure_colormap(napari_cmap) assert isinstance(cmap, Colormap) np.testing.assert_almost_equal(cmap.colors, c...
Test that we can accept napari colormaps.
test_can_accept_napari_colormaps
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_vispy_colormap_name_tuple(): """Test that we can accept vispy colormap named type.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) vispy_cmap = VispyColormap(colors) cmap = ensure_colormap(('special_name', vispy_cmap)) assert isinstance(cmap, Colormap) np.tes...
Test that we can accept vispy colormap named type.
test_can_accept_vispy_colormap_name_tuple
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_napari_colormap_name_tuple(): """Test that we can accept napari colormap named type.""" colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) napari_cmap = Colormap(colors) cmap = ensure_colormap(('special_name', napari_cmap)) assert isinstance(cmap, Colormap) np.test...
Test that we can accept napari colormap named type.
test_can_accept_napari_colormap_name_tuple
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_named_vispy_colormaps(): """Test that we can accept named vispy colormap.""" cmap = ensure_colormap('red') assert isinstance(cmap, Colormap) assert cmap.name == 'red'
Test that we can accept named vispy colormap.
test_can_accept_named_vispy_colormaps
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_named_mpl_colormap(): """Test we can accept named mpl colormap""" cmap_name = 'RdYlGn' cmap = ensure_colormap(cmap_name) assert isinstance(cmap, Colormap) assert cmap.name == cmap_name
Test we can accept named mpl colormap
test_can_accept_named_mpl_colormap
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_vispy_colormaps_in_dict(): """Test that we can accept vispy colormaps in a dictionary.""" colors_a = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) colors_b = np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1]]) vispy_cmap_a = VispyColormap(colors_a) vispy_cmap_b = VispyCol...
Test that we can accept vispy colormaps in a dictionary.
test_can_accept_vispy_colormaps_in_dict
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_accept_napari_colormaps_in_dict(): """Test that we can accept vispy colormaps in a dictionary""" colors_a = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]) colors_b = np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1]]) napari_cmap_a = Colormap(colors_a) napari_cmap_b = Colormap(co...
Test that we can accept vispy colormaps in a dictionary
test_can_accept_napari_colormaps_in_dict
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_can_degrade_gracefully(): """Test that we can degrade gracefully if given something not recognized.""" with pytest.warns(UserWarning): cmap = ensure_colormap(object) assert isinstance(cmap, Colormap) assert cmap.name == 'gray'
Test that we can degrade gracefully if given something not recognized.
test_can_degrade_gracefully
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_vispy_colormap_amount(): """ Test that the amount of localized vispy colormap names matches available colormaps. """ for name in _VISPY_COLORMAPS_ORIGINAL: assert name in _VISPY_COLORMAPS_TRANSLATIONS
Test that the amount of localized vispy colormap names matches available colormaps.
test_vispy_colormap_amount
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_mpl_colormap_exists(): """Test that all localized mpl colormap names exist.""" for name in _MATPLOTLIB_COLORMAP_NAMES: assert getattr(cm, name, None) is not None
Test that all localized mpl colormap names exist.
test_mpl_colormap_exists
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_colormap_error_suggestion(name, display_name): """ Test that vispy/mpl errors, when using `display_name`, suggest `name`. """ with pytest.raises( KeyError, match=rf'{display_name}.*you might want to use.*{name}' ): vispy_or_mpl_colormap(display_name)
Test that vispy/mpl errors, when using `display_name`, suggest `name`.
test_colormap_error_suggestion
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_colormap_error_from_inexistent_name(): """ Test that vispy/mpl errors when using a wrong name. """ name = 'foobar' with pytest.raises(KeyError, match=rf'{name}.*Recognized colormaps are'): vispy_or_mpl_colormap(name)
Test that vispy/mpl errors when using a wrong name.
test_colormap_error_from_inexistent_name
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_ensure_colormap_with_single_color(color): """See https://github.com/napari/napari/issues/3141""" colormap = ensure_colormap(color) np.testing.assert_array_equal(colormap.colors[0], [0, 0, 0, 1]) expected_color = transform_color(color)[0] np.testing.assert_array_equal(colormap.colors[-1], ex...
See https://github.com/napari/napari/issues/3141
test_ensure_colormap_with_single_color
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_ensure_colormap_with_hex_color_string(color): """ Test all the accepted hex color representations (single/double digit rgb with/without alpha) """ cmap = ensure_colormap(color) assert isinstance(cmap, Colormap) assert cmap.name == color.lower()
Test all the accepted hex color representations (single/double digit rgb with/without alpha)
test_ensure_colormap_with_hex_color_string
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_ensure_colormap_with_recognized_hex_color_string(color): """ Test that a hex color string for magenta is associated with the existing magenta colormap """ cmap = ensure_colormap(color) assert isinstance(cmap, Colormap) assert cmap.name == 'magenta'
Test that a hex color string for magenta is associated with the existing magenta colormap
test_ensure_colormap_with_recognized_hex_color_string
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_ensure_colormap_error_with_invalid_hex_color_string(): """ Test that ensure_colormap errors when using an invalid hex color string """ color = '#ff' with pytest.raises(KeyError, match=rf'{color}.*Recognized colormaps are'): ensure_colormap(color)
Test that ensure_colormap errors when using an invalid hex color string
test_ensure_colormap_error_with_invalid_hex_color_string
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_ensure_colormap_with_recognized_mpl_color_name(mpl_name): """ Test that the colormap name is identical to the the mpl color name passed to ensure_colormap """ cmap = ensure_colormap(mpl_name) assert isinstance(cmap, Colormap) assert cmap.name == mpl_name
Test that the colormap name is identical to the the mpl color name passed to ensure_colormap
test_ensure_colormap_with_recognized_mpl_color_name
python
napari/napari
src/napari/utils/colormaps/_tests/test_colormaps.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_colormaps.py
BSD-3-Clause
def test_warns_but_parses(): """Test collection of colors that raise a warning but do not return a default white color array. """ colors = ['', (43, 3, 3, 3), np.array([[3, 3, 3, 3], [0, 0, 0, 1]])] true_colors = [ np.zeros((1, 4), dtype=np.float32), np.array([[1, 3 / 43, 3 / 43, 3 ...
Test collection of colors that raise a warning but do not return a default white color array.
test_warns_but_parses
python
napari/napari
src/napari/utils/colormaps/_tests/test_color_to_array.py
https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/_tests/test_color_to_array.py
BSD-3-Clause
def conint( *, strict: bool = False, gt: int | None = None, ge: int | None = None, lt: int | None = None, le: int | None = None, multiple_of: int | None = None, ne: int | None = None, ) -> type[int]: """Extended version of `pydantic.types.conint` that includes not-equal.""" # use...
Extended version of `pydantic.types.conint` that includes not-equal.
conint
python
napari/napari
src/napari/utils/events/custom_types.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/custom_types.py
BSD-3-Clause
def confloat( *, strict: bool = False, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, multiple_of: float | None = None, step: float | None = None, ) -> type[float]: """Extended version of `pydantic.types.confloat` that includes ste...
Extended version of `pydantic.types.confloat` that includes step size.
confloat
python
napari/napari
src/napari/utils/events/custom_types.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/custom_types.py
BSD-3-Clause
def _is_core_callback(self, callback: CallbackRef | Callback, core: str): """ Check if the callback is a core callback Parameters ---------- callback : Union[CallbackRef, Callback] The callback to check. Callback could be function or weak reference to obj...
Check if the callback is a core callback Parameters ---------- callback : Union[CallbackRef, Callback] The callback to check. Callback could be function or weak reference to object method coded using weakreference to object and method name stored in ...
_is_core_callback
python
napari/napari
src/napari/utils/events/event.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/event.py
BSD-3-Clause
def _check_signature(fun: Callable) -> bool: """ Check if function will accept event parameter """ signature = inspect.signature(fun) parameters_list = list(signature.parameters.values()) if sum(map(_is_pos_arg, parameters_list)) > 1: raise RuntimeError( ...
Check if function will accept event parameter
_check_signature
python
napari/napari
src/napari/utils/events/event.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/event.py
BSD-3-Clause
def _is_pos_arg(param: inspect.Parameter): """ Check if param is positional or named and has no default parameter. """ return ( param.kind in [ inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, ] and param.default == inspe...
Check if param is positional or named and has no default parameter.
_is_pos_arg
python
napari/napari
src/napari/utils/events/event.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/event.py
BSD-3-Clause
def no_class_attributes(): """Context in which pydantic.main.ClassAttribute just passes value 2. Due to a very annoying decision by PySide2, all class ``__signature__`` attributes may only be assigned **once**. (This seems to be regardless of whether the class has anything to do with PySide2 or not). ...
Context in which pydantic.main.ClassAttribute just passes value 2. Due to a very annoying decision by PySide2, all class ``__signature__`` attributes may only be assigned **once**. (This seems to be regardless of whether the class has anything to do with PySide2 or not). Furthermore, the PySide2 ``__...
no_class_attributes
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def _update_dependents_from_property_code( cls, prop_name, prop, deps, visited=() ): """Recursively find all the dependents of a property by inspecting the code object. Update the given deps dictionary with the new findings. """ for name in prop.fget.__code__.co_names: if name in cls.__fiel...
Recursively find all the dependents of a property by inspecting the code object. Update the given deps dictionary with the new findings.
_update_dependents_from_property_code
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def _reset_event_source(self): """ set the event sources of self and all the children to the correct values """ # events are all messed up due to objects being probably # recreated arbitrarily during validation self.events.source = self for name in self.__fields__...
set the event sources of self and all the children to the correct values
_reset_event_source
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def reset(self): """Reset the state of the model to default values.""" for name, value in self._defaults.items(): if isinstance(value, EventedModel): getattr(self, name).reset() elif ( self.__config__.allow_mutation and self.__field...
Reset the state of the model to default values.
reset
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def update( self, values: Union['EventedModel', dict], recurse: bool = True ) -> None: """Update a model in place. Parameters ---------- values : dict, napari.utils.events.EventedModel Values to update the model with. If an EventedModel is passed it is ...
Update a model in place. Parameters ---------- values : dict, napari.utils.events.EventedModel Values to update the model with. If an EventedModel is passed it is first converted to a dictionary. The keys of this dictionary must be found as attributes on the ...
update
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def __eq__(self, other) -> bool: """Check equality with another object. We override the pydantic approach (which just checks ``self.dict() == other.dict()``) to accommodate more complicated types like arrays, whose truth value is often ambiguous. ``__eq_operators__`` is construc...
Check equality with another object. We override the pydantic approach (which just checks ``self.dict() == other.dict()``) to accommodate more complicated types like arrays, whose truth value is often ambiguous. ``__eq_operators__`` is constructed in ``EqualityMetaclass.__new__`` ...
__eq__
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def enums_as_values(self, as_values: bool = True): """Temporarily override how enums are retrieved. Parameters ---------- as_values : bool, optional Whether enums should be shown as values (or as enum objects), by default `True` """ null = object(...
Temporarily override how enums are retrieved. Parameters ---------- as_values : bool, optional Whether enums should be shown as values (or as enum objects), by default `True`
enums_as_values
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def get_defaults(obj: BaseModel): """Get possibly nested default values for a Model object.""" dflt = {} for k, v in obj.__fields__.items(): d = v.get_default() if d is None and isinstance(v.type_, main.ModelMetaclass): d = get_defaults(v.type_) dflt[k] = d return dfl...
Get possibly nested default values for a Model object.
get_defaults
python
napari/napari
src/napari/utils/events/evented_model.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/evented_model.py
BSD-3-Clause
def move(self, src_index: int, dest_index: int = 0) -> bool: """Insert object at ``src_index`` before ``dest_index``. Both indices refer to the list prior to any object removal (pre-move space). """ if dest_index < 0: dest_index += len(self) + 1 if dest_index...
Insert object at ``src_index`` before ``dest_index``. Both indices refer to the list prior to any object removal (pre-move space).
move
python
napari/napari
src/napari/utils/events/containers/_evented_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_evented_list.py
BSD-3-Clause
def move_multiple( self, sources: Iterable[Index], dest_index: int = 0 ) -> int: """Move a batch of `sources` indices, to a single destination. Note, if `dest_index` is higher than any of the `sources`, then the resulting position of the moved objects after the move operation ...
Move a batch of `sources` indices, to a single destination. Note, if `dest_index` is higher than any of the `sources`, then the resulting position of the moved objects after the move operation is complete will be lower than `dest_index`. Parameters ---------- sources : ...
move_multiple
python
napari/napari
src/napari/utils/events/containers/_evented_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_evented_list.py
BSD-3-Clause
def _move_plan( self, sources: Iterable[Index], dest_index: int ) -> Generator[tuple[int, int], None, None]: """Prepared indices for a multi-move. Given a set of ``sources`` from anywhere in the list, and a single ``dest_index``, this function computes and yields ``(from_ind...
Prepared indices for a multi-move. Given a set of ``sources`` from anywhere in the list, and a single ``dest_index``, this function computes and yields ``(from_index, to_index)`` tuples that can be used sequentially in single move operations. It keeps track of what has moved where and ...
_move_plan
python
napari/napari
src/napari/utils/events/containers/_evented_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_evented_list.py
BSD-3-Clause
def ensure_tuple_index(index: MaybeNestedIndex) -> NestedIndex: """Return index as a tuple of ints or slices. Parameters ---------- index : Tuple[Union[int, slice], ...] or int or slice An index as an int, tuple, or slice Returns ------- NestedIndex The index, guaranteed to...
Return index as a tuple of ints or slices. Parameters ---------- index : Tuple[Union[int, slice], ...] or int or slice An index as an int, tuple, or slice Returns ------- NestedIndex The index, guaranteed to be a tuple. Raises ------ TypeError If the input ...
ensure_tuple_index
python
napari/napari
src/napari/utils/events/containers/_nested_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_nested_list.py
BSD-3-Clause
def split_nested_index(index: MaybeNestedIndex) -> tuple[ParentIndex, Index]: """Given a nested index, return (nested_parent_index, row). Parameters ---------- index : MaybeNestedIndex An index as an int, tuple, or slice Returns ------- Tuple[NestedIndex, Index] A tuple of ...
Given a nested index, return (nested_parent_index, row). Parameters ---------- index : MaybeNestedIndex An index as an int, tuple, or slice Returns ------- Tuple[NestedIndex, Index] A tuple of ``parent_index``, ``row`` Raises ------ ValueError If any of the...
split_nested_index
python
napari/napari
src/napari/utils/events/containers/_nested_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_nested_list.py
BSD-3-Clause
def _non_negative_index( self, parent_index: ParentIndex, dest_index: Index ) -> Index: """Make sure dest_index is a positive index inside parent_index.""" destination_group = self[parent_index] # not handling slice indexes if isinstance(dest_index, int) and dest_index < 0: ...
Make sure dest_index is a positive index inside parent_index.
_non_negative_index
python
napari/napari
src/napari/utils/events/containers/_nested_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_nested_list.py
BSD-3-Clause
def _move_plan( self, sources: Iterable[MaybeNestedIndex], dest_index: NestedIndex ) -> Generator[tuple[NestedIndex, NestedIndex], None, None]: """Prepared indices for a complicated nested multi-move. Given a set of possibly-nested ``sources`` from anywhere in the tree, and a single...
Prepared indices for a complicated nested multi-move. Given a set of possibly-nested ``sources`` from anywhere in the tree, and a single ``dest_index``, this function computes and yields ``(from_index, to_index)`` tuples that can be used sequentially in single move operations. It keeps...
_move_plan
python
napari/napari
src/napari/utils/events/containers/_nested_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_nested_list.py
BSD-3-Clause
def move( self, src_index: int | NestedIndex, dest_index: int | NestedIndex = (0,), ) -> bool: """Move a single item from ``src_index`` to ``dest_index``. Parameters ---------- src_index : Union[int, NestedIndex] The index of the object to move ...
Move a single item from ``src_index`` to ``dest_index``. Parameters ---------- src_index : Union[int, NestedIndex] The index of the object to move dest_index : Union[int, NestedIndex], optional The destination. Object will be inserted before ``dest_index.``, ...
move
python
napari/napari
src/napari/utils/events/containers/_nested_list.py
https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_nested_list.py
BSD-3-Clause