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 get_theme(theme_id: str):
"""Get a copy of theme based on its id.
If you get a copy of the theme, changes to the theme model will not be
reflected in the UI unless you replace or add the modified theme to
the `_themes` container.
Parameters
----------
theme_id : str
ID of reque... | Get a copy of theme based on its id.
If you get a copy of the theme, changes to the theme model will not be
reflected in the UI unless you replace or add the modified theme to
the `_themes` container.
Parameters
----------
theme_id : str
ID of requested theme.
Returns
-------
... | get_theme | python | napari/napari | src/napari/utils/theme.py | https://github.com/napari/napari/blob/master/src/napari/utils/theme.py | BSD-3-Clause |
def register_theme(theme_id, theme, source):
"""Register a new or updated theme.
Parameters
----------
theme_id : str
id of requested theme.
theme : dict of str: str, Theme
Theme mapping elements to colors.
source : str
Source plugin of theme
"""
if isinstance(th... | Register a new or updated theme.
Parameters
----------
theme_id : str
id of requested theme.
theme : dict of str: str, Theme
Theme mapping elements to colors.
source : str
Source plugin of theme
| register_theme | python | napari/napari | src/napari/utils/theme.py | https://github.com/napari/napari/blob/master/src/napari/utils/theme.py | BSD-3-Clause |
def is_theme_available(theme_id):
"""Check if a theme is available.
Parameters
----------
theme_id : str
id of requested theme.
Returns
-------
bool
True if the theme is available, False otherwise.
"""
if theme_id == 'system':
return True
if theme_id not... | Check if a theme is available.
Parameters
----------
theme_id : str
id of requested theme.
Returns
-------
bool
True if the theme is available, False otherwise.
| is_theme_available | python | napari/napari | src/napari/utils/theme.py | https://github.com/napari/napari/blob/master/src/napari/utils/theme.py | BSD-3-Clause |
def rebuild_theme_settings():
"""update theme information in settings.
here we simply update the settings to reflect current list of available
themes.
"""
from napari.settings import get_settings
settings = get_settings()
settings.appearance.refresh_themes() | update theme information in settings.
here we simply update the settings to reflect current list of available
themes.
| rebuild_theme_settings | python | napari/napari | src/napari/utils/theme.py | https://github.com/napari/napari/blob/master/src/napari/utils/theme.py | BSD-3-Clause |
def _get_display_name(
locale: str, display_locale: str = _DEFAULT_LOCALE
) -> str:
"""
Return the language name to use with a `display_locale` for a given language locale.
This is used to generate the preferences dialog options.
Parameters
----------
locale : str
The language name... |
Return the language name to use with a `display_locale` for a given language locale.
This is used to generate the preferences dialog options.
Parameters
----------
locale : str
The language name to use.
display_locale : str, optional
The language to display the `locale`.
... | _get_display_name | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _is_valid_locale(locale: str) -> bool:
"""
Check if a `locale` value is valid.
Parameters
----------
locale : str
Language locale code.
Notes
-----
A valid locale is in the form language (See ISO-639 standard) and an
optional territory (See ISO-3166 standard).
Exam... |
Check if a `locale` value is valid.
Parameters
----------
locale : str
Language locale code.
Notes
-----
A valid locale is in the form language (See ISO-639 standard) and an
optional territory (See ISO-3166 standard).
Examples of valid locales:
- English: "en"
- A... | _is_valid_locale | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def value(self) -> str:
"""
Return the original string with interpolated kwargs, if provided.
"""
return self._original_value(
self._msgid,
self._msgid_plural,
self._n,
self._kwargs,
) |
Return the original string with interpolated kwargs, if provided.
| value | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def translation(self) -> str:
"""
Return the translated string with interpolated kwargs, if provided.
"""
if (
self._n is not None
and self._msgid_plural is not None
and self._msgctxt is not None
):
translation = gettext.dnpgettext(... |
Return the translated string with interpolated kwargs, if provided.
| translation | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _update_locale(self, locale: str):
"""
Update the locale environment variables.
Parameters
----------
locale : str
The language name to use.
"""
self._locale = locale
localedir = None
if locale.split('_')[0] != _DEFAULT_LOCALE:
... |
Update the locale environment variables.
Parameters
----------
locale : str
The language name to use.
| _update_locale | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _dnpgettext(
self,
*,
msgid: str,
msgctxt: str | None = None,
msgid_plural: str | None = None,
n: int | None = None,
**kwargs,
) -> str:
"""
Helper to handle all trans methods and delegate to corresponding
gettext methods.
... |
Helper to handle all trans methods and delegate to corresponding
gettext methods.
Must provide one of the following sets of arguments:
- msgid
- msgid, msgctxt
- msgid, msgid_plural, n
- msgid, msgid_plural, n, msgctxt
Parameters
----------
... | _dnpgettext | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _(
self, msgid: str, deferred: bool = False, **kwargs
) -> TranslationString | str:
"""
Shorthand for `gettext.gettext` with enhanced functionality.
Parameters
----------
msgid : str
The singular string to translate.
deferred : bool, optional
... |
Shorthand for `gettext.gettext` with enhanced functionality.
Parameters
----------
msgid : str
The singular string to translate.
deferred : bool, optional
Define if the string translation should be deferred or executed
in place. Default is Fa... | _ | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _n(
self,
msgid: str,
msgid_plural: str,
n: int,
deferred: bool | None = False,
**kwargs,
) -> TranslationString | str:
"""
Shorthand for `gettext.ngettext` with enhanced functionality.
Parameters
----------
msgid : str
... |
Shorthand for `gettext.ngettext` with enhanced functionality.
Parameters
----------
msgid : str
The singular string to translate.
msgid_plural : str
The plural string to translate.
n : int
The number for pluralization.
deferre... | _n | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _p(
self,
msgctxt: str,
msgid: str,
deferred: bool | None = False,
**kwargs,
) -> TranslationString | str:
"""
Shorthand for `gettext.pgettext` with enhanced functionality.
Parameters
----------
msgctxt : str
The messag... |
Shorthand for `gettext.pgettext` with enhanced functionality.
Parameters
----------
msgctxt : str
The message context.
msgid : str
The singular string to translate.
deferred : bool, optional
Define if the string translation should be ... | _p | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _np(
self,
msgctxt: str,
msgid: str,
msgid_plural: str,
n: int,
deferred: bool | None = False,
**kwargs,
) -> TranslationString | str:
"""
Shorthand for `gettext.npgettext` with enhanced functionality.
Parameters
----------... |
Shorthand for `gettext.npgettext` with enhanced functionality.
Parameters
----------
msgctxt : str
The message context.
msgid : str
The singular string to translate.
msgid_plural : str
The plural string to translate.
n : int
... | _np | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _update_env(locale: str):
"""
Update the locale environment variables based on the settings.
Parameters
----------
locale : str
The language name to use.
"""
for key in ['LANGUAGE', 'LANG']:
os.environ[key] = f'{locale}.UTF-8' |
Update the locale environment variables based on the settings.
Parameters
----------
locale : str
The language name to use.
| _update_env | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _set_locale(cls, locale: str):
"""
Set locale for the translation bundles based on the settings.
Parameters
----------
locale : str
The language name to use.
"""
if _is_valid_locale(locale):
cls._LOCALE = locale
if locale.... |
Set locale for the translation bundles based on the settings.
Parameters
----------
locale : str
The language name to use.
| _set_locale | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def load(cls, domain: str = 'napari') -> TranslationBundle:
"""
Load translation domain.
The domain is usually the normalized ``package_name``.
Parameters
----------
domain : str
The translations domain. The normalized python package name.
Returns
... |
Load translation domain.
The domain is usually the normalized ``package_name``.
Parameters
----------
domain : str
The translations domain. The normalized python package name.
Returns
-------
Translator
A translator instance bou... | load | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _load_language(
default_config_path: str = _DEFAULT_CONFIG_PATH,
locale: str = _DEFAULT_LOCALE,
) -> str:
"""
Load language from configuration file directly.
Parameters
----------
default_config_path : str or Path
The default configuration path, optional
locale : str
... |
Load language from configuration file directly.
Parameters
----------
default_config_path : str or Path
The default configuration path, optional
locale : str
The default locale used to display options, optional
Returns
-------
str
The language locale set by nap... | _load_language | python | napari/napari | src/napari/utils/translations.py | https://github.com/napari/napari/blob/master/src/napari/utils/translations.py | BSD-3-Clause |
def _missing_(cls, value: object) -> 'TriangulationBackend':
"""Handle missing values in the enum."""
# Handle the case where the value is not a valid enum member
if isinstance(value, str):
return cls[value.replace(' ', '_').lower()]
raise ValueError(f"'{value}' is not a vali... | Handle missing values in the enum. | _missing_ | python | napari/napari | src/napari/utils/triangulation_backend.py | https://github.com/napari/napari/blob/master/src/napari/utils/triangulation_backend.py | BSD-3-Clause |
def set_backend(backend: TriangulationBackend) -> TriangulationBackend:
"""Set the triangulation backend to use.
Parameters
----------
backend : TriangulationBackend
The triangulation backend to use.
Returns
-------
TriangulationBackend
The previous triangulation backend.
... | Set the triangulation backend to use.
Parameters
----------
backend : TriangulationBackend
The triangulation backend to use.
Returns
-------
TriangulationBackend
The previous triangulation backend.
| set_backend | python | napari/napari | src/napari/utils/triangulation_backend.py | https://github.com/napari/napari/blob/master/src/napari/utils/triangulation_backend.py | BSD-3-Clause |
def validate_n_seq(n: int, dtype=None):
"""Creates a function to validate a sequence of len == N and type == dtype.
Currently does **not** validate generators (will always validate true).
Parameters
----------
n : int
Desired length of the sequence
dtype : type, optional
If pro... | Creates a function to validate a sequence of len == N and type == dtype.
Currently does **not** validate generators (will always validate true).
Parameters
----------
n : int
Desired length of the sequence
dtype : type, optional
If provided each item in the sequence must match dtyp... | validate_n_seq | python | napari/napari | src/napari/utils/validators.py | https://github.com/napari/napari/blob/master/src/napari/utils/validators.py | BSD-3-Clause |
def func(obj):
"""Function that validates whether an object is a sequence of len `n`.
Parameters
----------
obj : any
the object to be validated
Raises
------
TypeError
If the object is not an indexable collection.
ValueError
... | Function that validates whether an object is a sequence of len `n`.
Parameters
----------
obj : any
the object to be validated
Raises
------
TypeError
If the object is not an indexable collection.
ValueError
If the object does... | func | python | napari/napari | src/napari/utils/validators.py | https://github.com/napari/napari/blob/master/src/napari/utils/validators.py | BSD-3-Clause |
def _pairwise(iterable: Iterable):
"""Convert iterable to a zip object containing tuples of pairs along the
sequence.
Examples
--------
>>> pairwise([1, 2, 3, 4])
<zip at 0x10606df80>
>>> list(pairwise([1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
"""
# duplicate the iterable
a, ... | Convert iterable to a zip object containing tuples of pairs along the
sequence.
Examples
--------
>>> pairwise([1, 2, 3, 4])
<zip at 0x10606df80>
>>> list(pairwise([1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
| _pairwise | python | napari/napari | src/napari/utils/validators.py | https://github.com/napari/napari/blob/master/src/napari/utils/validators.py | BSD-3-Clause |
def _validate_increasing(values: Iterable) -> None:
"""Ensure that values in an iterable are monotocially increasing.
Examples
--------
>>> _validate_increasing([1, 2, 3, 4])
None
>>> _validate_increasing([1, 4, 3, 4])
ValueError: Sequence [1, 4, 3, 4] must be monotonically increasing.
... | Ensure that values in an iterable are monotocially increasing.
Examples
--------
>>> _validate_increasing([1, 2, 3, 4])
None
>>> _validate_increasing([1, 4, 3, 4])
ValueError: Sequence [1, 4, 3, 4] must be monotonically increasing.
Raises
------
ValueError
If `values` is c... | _validate_increasing | python | napari/napari | src/napari/utils/validators.py | https://github.com/napari/napari/blob/master/src/napari/utils/validators.py | BSD-3-Clause |
def resize_dask_cache(
nbytes: int | None = None, mem_fraction: float | None = None
) -> Cache:
"""Create or resize the dask cache used for opportunistic caching.
The cache object is an instance of a :class:`Cache`, (which
wraps a :class:`cachey.Cache`).
See `Dask opportunistic caching
<https:... | Create or resize the dask cache used for opportunistic caching.
The cache object is an instance of a :class:`Cache`, (which
wraps a :class:`cachey.Cache`).
See `Dask opportunistic caching
<https://docs.dask.org/en/latest/caching.html>`_
Parameters
----------
nbytes : int, optional
... | resize_dask_cache | python | napari/napari | src/napari/utils/_dask_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_dask_utils.py | BSD-3-Clause |
def _is_dask_data(data: Any) -> bool:
"""Return True if data is a dask array or a list/tuple of dask arrays."""
return isinstance(data, da.Array) or (
isinstance(data, collections.abc.Sequence)
and any(isinstance(i, da.Array) for i in data)
) | Return True if data is a dask array or a list/tuple of dask arrays. | _is_dask_data | python | napari/napari | src/napari/utils/_dask_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_dask_utils.py | BSD-3-Clause |
def configure_dask(data: Any, cache: bool = True) -> DaskIndexer:
"""Spin up cache and return context manager that optimizes Dask indexing.
This function determines whether data is a dask array or list of dask
arrays and prepares some optimizations if so.
When a delayed dask array is given to napari, ... | Spin up cache and return context manager that optimizes Dask indexing.
This function determines whether data is a dask array or list of dask
arrays and prepares some optimizations if so.
When a delayed dask array is given to napari, there are couple things that
need to be done to optimize performance.... | configure_dask | python | napari/napari | src/napari/utils/_dask_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_dask_utils.py | BSD-3-Clause |
def normalize_dtype(dtype_spec: 'DTypeLike') -> np.dtype:
"""Return a proper NumPy type given ~any duck array dtype.
Parameters
----------
dtype_spec : numpy dtype, numpy type, torch dtype, tensorstore dtype, etc
A type that can be interpreted as a NumPy numeric data type, e.g.
'uint32'... | Return a proper NumPy type given ~any duck array dtype.
Parameters
----------
dtype_spec : numpy dtype, numpy type, torch dtype, tensorstore dtype, etc
A type that can be interpreted as a NumPy numeric data type, e.g.
'uint32', np.uint8, torch.float32, etc.
Returns
-------
dtyp... | normalize_dtype | python | napari/napari | src/napari/utils/_dtype.py | https://github.com/napari/napari/blob/master/src/napari/utils/_dtype.py | BSD-3-Clause |
def elements_in_slice(
index: tuple[npt.NDArray[np.int_], ...], position_in_axes: dict[int, int]
) -> npt.NDArray[np.bool_]:
"""Mask elements from a multi-dimensional index not in a given slice.
Some n-D operations may edit data that is not visible in the current slice.
Given slice position information... | Mask elements from a multi-dimensional index not in a given slice.
Some n-D operations may edit data that is not visible in the current slice.
Given slice position information (as a dictionary mapping axis to index on that
axis), this function returns a boolean mask for the possibly higher-dimensional
... | elements_in_slice | python | napari/napari | src/napari/utils/_indexing.py | https://github.com/napari/napari/blob/master/src/napari/utils/_indexing.py | BSD-3-Clause |
def index_in_slice(
index: tuple[npt.NDArray[np.int_], ...],
position_in_axes: dict[int, int],
indices_order: tuple[int, ...],
) -> tuple[npt.NDArray[np.int_], ...]:
"""Convert a NumPy fancy indexing expression from data to sliced space.
Parameters
----------
index : tuple of array of int
... | Convert a NumPy fancy indexing expression from data to sliced space.
Parameters
----------
index : tuple of array of int
A NumPy fancy indexing expression [1]_.
position_in_axes : dict[int, int]
A dictionary mapping sliced (non-displayed) axes to a slice position.
indices_order : tu... | index_in_slice | python | napari/napari | src/napari/utils/_indexing.py | https://github.com/napari/napari/blob/master/src/napari/utils/_indexing.py | BSD-3-Clause |
def register_logger_to_napari_handler(
module: str,
) -> Generator[None, None, None]:
"""
Register a specific module's logger to use our custom log handler.
"""
logger = logging.getLogger(module)
# ensure the default "last resort" logging to console remains
if not logger.handlers and logging... |
Register a specific module's logger to use our custom log handler.
| register_logger_to_napari_handler | python | napari/napari | src/napari/utils/_logging.py | https://github.com/napari/napari/blob/master/src/napari/utils/_logging.py | BSD-3-Clause |
def _html_tag_for_level(level_name: str, level_value: int) -> str:
"""
Generate html tag for the appropriate logging level.
"""
colors = {
logging.INFO: 'cyan',
logging.WARNING: 'orange',
logging.ERROR: 'red',
logging.CRITICAL: 'magenta',
}
color = 'blue'
for ... |
Generate html tag for the appropriate logging level.
| _html_tag_for_level | python | napari/napari | src/napari/utils/_logging.py | https://github.com/napari/napari/blob/master/src/napari/utils/_logging.py | BSD-3-Clause |
def _get_layer_from_widget(gui: ComboBox, viewer: Viewer) -> Optional[Layer]:
"""Retrieve layer used as input to function wrapped into magicgui .
Parameters
----------
gui : magicgui.widgets.ComboBox
The instantiated ComboBox widget.
Returns
-------
Layer
layer passed as in... | Retrieve layer used as input to function wrapped into magicgui .
Parameters
----------
gui : magicgui.widgets.ComboBox
The instantiated ComboBox widget.
Returns
-------
Layer
layer passed as input to the function wrapped into magicgui.
| _get_layer_from_widget | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def _get_layers_from_widget(gui: FunctionGui, viewer: Viewer) -> list[Layer]:
"""Retrieve layers used as input to function wrapped into magicgui .
Parameters
----------
gui : magicgui.widgets.FunctionGui
The instantiated FunctionGui widget.
Returns
-------
list
list of laye... | Retrieve layers used as input to function wrapped into magicgui .
Parameters
----------
gui : magicgui.widgets.FunctionGui
The instantiated FunctionGui widget.
Returns
-------
list
list of layers passed as input to the function wrapped into magicgui.
| _get_layers_from_widget | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def _calc_affine_from_source_layers(data_ndim, source_layers: list[Layer]):
"""Calculate affine information for provided data based on source layers.
Parameters
----------
data : array
Data to be added to the viewer.
source_layers : list
List of layers used to calculate affine infor... | Calculate affine information for provided data based on source layers.
Parameters
----------
data : array
Data to be added to the viewer.
source_layers : list
List of layers used to calculate affine information.
Returns
-------
dict
Dictionary with affine informatio... | _calc_affine_from_source_layers | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def add_layer_data_to_viewer(gui: FunctionGui, result: Any, return_type: type):
"""Show a magicgui result in the viewer.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to the c... | Show a magicgui result in the viewer.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to the current viewer as the corresponding
layer type.
Parameters
----------
g... | add_layer_data_to_viewer | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def add_layer_data_tuples_to_viewer(gui, result, return_type):
"""Show a magicgui result in the viewer.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to the current viewer as ... | Show a magicgui result in the viewer.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to the current viewer as the corresponding
layer type.
Parameters
----------
g... | add_layer_data_tuples_to_viewer | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def add_worker_data(
widget, worker: FunctionWorker, return_type, _from_tuple=True
):
"""Handle a thread_worker object returned from a magicgui widget.
This allows someone annotate their magicgui with a return type of
`FunctionWorker[...]`, create a napari thread worker (e.g. with the
``@thread_wor... | Handle a thread_worker object returned from a magicgui widget.
This allows someone annotate their magicgui with a return type of
`FunctionWorker[...]`, create a napari thread worker (e.g. with the
``@thread_worker`` decorator), then simply return the worker. We will hook up
the `returned` signal to th... | add_worker_data | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def add_future_data(gui, future: Future, return_type, _from_tuple=True):
"""Process a Future object from a magicgui widget.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to th... | Process a Future object from a magicgui widget.
This function will be called when a magicgui-decorated function has a
return annotation of one of the `napari.types.<layer_name>Data` ... and
will add the data in ``result`` to the current viewer as the corresponding
layer type.
Parameters
------... | add_future_data | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def find_viewer_ancestor(widget) -> Viewer | None:
"""Return the closest parent Viewer of ``widget``.
Priority is given to `Viewer` ancestors of ``widget``.
`napari.current_viewer()` is called for Widgets without a
Viewer ancestor.
Parameters
----------
widget : QWidget
A widget
... | Return the closest parent Viewer of ``widget``.
Priority is given to `Viewer` ancestors of ``widget``.
`napari.current_viewer()` is called for Widgets without a
Viewer ancestor.
Parameters
----------
widget : QWidget
A widget
Returns
-------
viewer : napari.Viewer or None
... | find_viewer_ancestor | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def get_layers(gui: CategoricalWidget) -> list[Layer]:
"""Retrieve layers matching gui.annotation, from the Viewer the gui is in.
Parameters
----------
gui : magicgui.widgets.Widget
The instantiated MagicGui widget. May or may not be docked in a
dock widget.
Returns
-------
... | Retrieve layers matching gui.annotation, from the Viewer the gui is in.
Parameters
----------
gui : magicgui.widgets.Widget
The instantiated MagicGui widget. May or may not be docked in a
dock widget.
Returns
-------
tuple
Tuple of layers of type ``gui.annotation``
... | get_layers | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def get_layers_data(gui: CategoricalWidget) -> list[tuple[str, Any]]:
"""Retrieve layers matching gui.annotation, from the Viewer the gui is in.
As opposed to `get_layers`, this function returns just `layer.data` rather
than the full layer object.
Parameters
----------
gui : magicgui.widgets.W... | Retrieve layers matching gui.annotation, from the Viewer the gui is in.
As opposed to `get_layers`, this function returns just `layer.data` rather
than the full layer object.
Parameters
----------
gui : magicgui.widgets.Widget
The instantiated MagicGui widget. May or may not be docked in ... | get_layers_data | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def _make_choice_data_setter(gui: CategoricalWidget, choice_name: str):
"""Return a function that sets the ``data`` for ``choice_name`` in ``gui``.
Note, using lru_cache here so that the **same** function object is returned
if you call this twice for the same widget/choice_name combination. This is
so ... | Return a function that sets the ``data`` for ``choice_name`` in ``gui``.
Note, using lru_cache here so that the **same** function object is returned
if you call this twice for the same widget/choice_name combination. This is
so that when we connect it above in `layer.events.data.connect()`, it will
onl... | _make_choice_data_setter | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def add_layers_to_viewer(
gui: FunctionGui[Any], result: Any, return_type: type[list[Layer]]
) -> None:
"""Show a magicgui result in the viewer.
Parameters
----------
gui : MagicGui or QWidget
The instantiated MagicGui widget. May or may not be docked in a
dock widget.
result :... | Show a magicgui result in the viewer.
Parameters
----------
gui : MagicGui or QWidget
The instantiated MagicGui widget. May or may not be docked in a
dock widget.
result : Any
The result of the function call.
return_type : type
The return annotation that was used in... | add_layers_to_viewer | python | napari/napari | src/napari/utils/_magicgui.py | https://github.com/napari/napari/blob/master/src/napari/utils/_magicgui.py | BSD-3-Clause |
def _is_called_from_napari() -> bool:
"""
Check if the getter or setter is called from inner napari.
"""
if hasattr(sys, '_getframe'):
frame = sys._getframe(2)
return frame.f_code.co_filename.startswith(misc.ROOT_DIR)
return False |
Check if the getter or setter is called from inner napari.
| _is_called_from_napari | python | napari/napari | src/napari/utils/_proxies.py | https://github.com/napari/napari/blob/master/src/napari/utils/_proxies.py | BSD-3-Clause |
def in_main_thread_py() -> bool:
"""
Check if caller is in main python thread.
Returns
-------
thread_flag : bool
True if we are in the main thread, False otherwise.
"""
import threading
return threading.current_thread() == threading.main_thread() |
Check if caller is in main python thread.
Returns
-------
thread_flag : bool
True if we are in the main thread, False otherwise.
| in_main_thread_py | python | napari/napari | src/napari/utils/_proxies.py | https://github.com/napari/napari/blob/master/src/napari/utils/_proxies.py | BSD-3-Clause |
def create_func(cls, name=None, doc=None):
"""
Creates a function (such as `add_<layer>`) to add a layer to the viewer
The functionality is inherited from the corresponding `<layer>` class.
"""
cls_name = cls.__name__
if name is None:
name = camel_to_snake(cls_name)
if 'layer' in ... |
Creates a function (such as `add_<layer>`) to add a layer to the viewer
The functionality is inherited from the corresponding `<layer>` class.
| create_func | python | napari/napari | src/napari/utils/_register.py | https://github.com/napari/napari/blob/master/src/napari/utils/_register.py | BSD-3-Clause |
def fail_obj_graph(Klass): # pragma: no cover
"""
Fail is a given class _instances weakset is non empty and print the object graph.
"""
try:
import objgraph
except ModuleNotFoundError:
return
if len(Klass._instances) != 0:
global COUNTER
COUNTER += 1
im... |
Fail is a given class _instances weakset is non empty and print the object graph.
| fail_obj_graph | python | napari/napari | src/napari/utils/_testsupport.py | https://github.com/napari/napari/blob/master/src/napari/utils/_testsupport.py | BSD-3-Clause |
def napari_plugin_manager(monkeypatch):
"""A napari plugin manager that blocks discovery by default.
Note you can still use `napari_plugin_manager.register()` to directly
register a plugin module, class or dict for testing.
Or, to re-enable global discovery, use:
`napari_plugin_manager.discovery_b... | A napari plugin manager that blocks discovery by default.
Note you can still use `napari_plugin_manager.register()` to directly
register a plugin module, class or dict for testing.
Or, to re-enable global discovery, use:
`napari_plugin_manager.discovery_blocker.stop()`
| napari_plugin_manager | python | napari/napari | src/napari/utils/_testsupport.py | https://github.com/napari/napari/blob/master/src/napari/utils/_testsupport.py | BSD-3-Clause |
def mock_app_model():
"""Mock clean 'test_app' `NapariApplication` instance.
This fixture must be used whenever `napari._app_model.get_app_model()` is called to
return a 'test_app' `NapariApplication` instead of the 'napari'
`NapariApplication`. The `make_napari_viewer` fixture is already equipped with... | Mock clean 'test_app' `NapariApplication` instance.
This fixture must be used whenever `napari._app_model.get_app_model()` is called to
return a 'test_app' `NapariApplication` instead of the 'napari'
`NapariApplication`. The `make_napari_viewer` fixture is already equipped with
a `mock_app_model`.
... | mock_app_model | python | napari/napari | src/napari/utils/_testsupport.py | https://github.com/napari/napari/blob/master/src/napari/utils/_testsupport.py | BSD-3-Clause |
def make_napari_viewer_proxy(make_napari_viewer, monkeypatch):
"""Fixture that returns a function for creating a napari viewer wrapped in proxy.
Use in the same way like `make_napari_viewer` fixture.
Parameters
----------
make_napari_viewer : fixture
The make_napari_viewer fixture.
Ret... | Fixture that returns a function for creating a napari viewer wrapped in proxy.
Use in the same way like `make_napari_viewer` fixture.
Parameters
----------
make_napari_viewer : fixture
The make_napari_viewer fixture.
Returns
-------
function
A function that creates a napari... | make_napari_viewer_proxy | python | napari/napari | src/napari/utils/_testsupport.py | https://github.com/napari/napari/blob/master/src/napari/utils/_testsupport.py | BSD-3-Clause |
def MouseEvent():
"""Create a subclass for simulating vispy mouse events.
Returns
-------
Event : Type
A new dataclass named Event that can be used to create an
object with fields "type" and "is_dragging".
"""
@dataclass
class Event:
type: str
position: tupl... | Create a subclass for simulating vispy mouse events.
Returns
-------
Event : Type
A new dataclass named Event that can be used to create an
object with fields "type" and "is_dragging".
| MouseEvent | python | napari/napari | src/napari/utils/_testsupport.py | https://github.com/napari/napari/blob/master/src/napari/utils/_testsupport.py | BSD-3-Clause |
def validate_all_params_in_docstring(func):
"""
Validate if all the parameters in the function signature are present in the docstring.
"""
assert func.__doc__ is not None, f'Function {func} has no docstring'
parsed = parse(func.__doc__)
params = [x for x in parsed.params if x.args[0] == 'param'... |
Validate if all the parameters in the function signature are present in the docstring.
| validate_all_params_in_docstring | python | napari/napari | src/napari/utils/_test_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_test_utils.py | BSD-3-Clause |
def validate_kwargs_sorted(func):
"""
Validate if the keyword arguments in the function signature are sorted alphabetically.
"""
signature = inspect.signature(func)
kwargs_list = [
x.name
for x in signature.parameters.values()
if x.kind == inspect.Parameter.KEYWORD_ONLY
]... |
Validate if the keyword arguments in the function signature are sorted alphabetically.
| validate_kwargs_sorted | python | napari/napari | src/napari/utils/_test_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_test_utils.py | BSD-3-Clause |
def validate_docstring_parent_class_consistency(klass, skip=('data', 'ndim')):
"""
Validate if the docstrings of the class parameters and type information
are consistent with the parent class.
Parameters
----------
klass : type
The class to validate.
skip : tuple or set, optional
... |
Validate if the docstrings of the class parameters and type information
are consistent with the parent class.
Parameters
----------
klass : type
The class to validate.
skip : tuple or set, optional
Name of parameters that we know are different from the parent class.
By ... | validate_docstring_parent_class_consistency | python | napari/napari | src/napari/utils/_test_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/_test_utils.py | BSD-3-Clause |
def get_tb_formatter() -> Callable[[ExcInfo, bool, str], str]:
"""Return a formatter callable that uses IPython VerboseTB if available.
Imports IPython lazily if available to take advantage of ultratb.VerboseTB.
If unavailable, cgitb is used instead, but this function overrides a lot of
the hardcoded c... | Return a formatter callable that uses IPython VerboseTB if available.
Imports IPython lazily if available to take advantage of ultratb.VerboseTB.
If unavailable, cgitb is used instead, but this function overrides a lot of
the hardcoded citgb styles and adds error chaining (for exceptions that
result fr... | get_tb_formatter | python | napari/napari | src/napari/utils/_tracebacks.py | https://github.com/napari/napari/blob/master/src/napari/utils/_tracebacks.py | BSD-3-Clause |
def cgitb_chain(exc: Exception) -> Generator[str, None, None]:
"""Recurse through exception stack and chain cgitb_html calls."""
if exc.__cause__:
yield from cgitb_chain(exc.__cause__)
yield (
'<br><br><font color="#51B432">... | Recurse through exception stack and chain cgitb_html calls. | cgitb_chain | python | napari/napari | src/napari/utils/_tracebacks.py | https://github.com/napari/napari/blob/master/src/napari/utils/_tracebacks.py | BSD-3-Clause |
def ansi2html(
ansi_string: str, styles: dict[int, dict[str, str]] = ANSI_STYLES
) -> Generator[str, None, None]:
"""Convert ansi string to colored HTML
Parameters
----------
ansi_string : str
text with ANSI color codes.
styles : dict, optional
A mapping from ANSI codes to a dic... | Convert ansi string to colored HTML
Parameters
----------
ansi_string : str
text with ANSI color codes.
styles : dict, optional
A mapping from ANSI codes to a dict of css kwargs:values,
by default ANSI_STYLES
Yields
------
str
HTML strings that can be joined... | ansi2html | python | napari/napari | src/napari/utils/_tracebacks.py | https://github.com/napari/napari/blob/master/src/napari/utils/_tracebacks.py | BSD-3-Clause |
def map(self, color_properties: list | np.ndarray) -> np.ndarray:
"""Map an array of values to an array of colors
Parameters
----------
color_properties : Union[list, np.ndarray]
The property values to be converted to colors.
Returns
-------
colors : n... | Map an array of values to an array of colors
Parameters
----------
color_properties : Union[list, np.ndarray]
The property values to be converted to colors.
Returns
-------
colors : np.ndarray
An Nx4 color array where N is the number of property va... | map | python | napari/napari | src/napari/utils/colormaps/categorical_colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/categorical_colormap.py | BSD-3-Clause |
def make_colorbar(
cmap: 'Colormap', size: tuple[int, int] = (18, 28), horizontal: bool = True
) -> npt.NDArray[np.uint8]:
"""Make a colorbar from a colormap.
Parameters
----------
cmap : vispy.color.Colormap
Colormap to create colorbar with.
size : 2-tuple
Shape of colorbar.
... | Make a colorbar from a colormap.
Parameters
----------
cmap : vispy.color.Colormap
Colormap to create colorbar with.
size : 2-tuple
Shape of colorbar.
horizontal : bool
If True colobar is oriented horizontal, otherwise it is oriented
vertical.
Returns
------... | make_colorbar | python | napari/napari | src/napari/utils/colormaps/colorbars.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colorbars.py | BSD-3-Clause |
def _data_to_texture(
self, values: np.ndarray | np.integer
) -> np.ndarray | np.integer:
"""Map input values to values for send to GPU."""
raise NotImplementedError | Map input values to values for send to GPU. | _data_to_texture | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _get_mapping_from_cache(
self, data_dtype: np.dtype
) -> np.ndarray | None:
"""For given dtype, return precomputed array mapping values to colors.
Returns None if the dtype itemsize is greater than 2.
"""
target_dtype = _texture_dtype(self._num_unique_colors, data_dtype)... | For given dtype, return precomputed array mapping values to colors.
Returns None if the dtype itemsize is greater than 2.
| _get_mapping_from_cache | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def map(self, values: np.ndarray | np.integer | int) -> np.ndarray:
"""Map values to colors.
Parameters
----------
values : np.ndarray or int
Values to be mapped.
Returns
-------
np.ndarray of the same shape as values,
but with the last d... | Map values to colors.
Parameters
----------
values : np.ndarray or int
Values to be mapped.
Returns
-------
np.ndarray of the same shape as values,
but with the last dimension of size 4
Mapped colors.
| map | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _validate_color_dict(cls, v, values):
"""Ensure colors are RGBA arrays, not strings.
Parameters
----------
cls : type
The class of the object being instantiated.
v : MutableMapping
A mapping from integers to colors. It *may* have None as a key,
... | Ensure colors are RGBA arrays, not strings.
Parameters
----------
cls : type
The class of the object being instantiated.
v : MutableMapping
A mapping from integers to colors. It *may* have None as a key,
which indicates the color to map items not in t... | _validate_color_dict | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def map(self, values: np.ndarray | np.integer | int) -> np.ndarray:
"""Map values to colors.
Parameters
----------
values : np.ndarray or int
Values to be mapped.
Returns
-------
np.ndarray of same shape as values, but with last dimension of size 4
... | Map values to colors.
Parameters
----------
values : np.ndarray or int
Values to be mapped.
Returns
-------
np.ndarray of same shape as values, but with last dimension of size 4
Mapped colors.
| map | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _map_precast(self, values, apply_selection) -> np.ndarray:
"""Map values to colors.
Parameters
----------
values : np.ndarray
Values to be mapped. It need to be already cast using
cast_labels_to_minimum_type_auto
Returns
-------
np.nd... | Map values to colors.
Parameters
----------
values : np.ndarray
Values to be mapped. It need to be already cast using
cast_labels_to_minimum_type_auto
Returns
-------
np.ndarray of shape (N, M, 4)
Mapped colors.
Notes
... | _map_precast | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _values_mapping_to_minimum_values_set(
self, apply_selection=True
) -> tuple[dict[int | None, int], dict[int, np.ndarray]]:
"""Create mapping from original values to minimum values set.
To use minimum possible dtype for labels.
Returns
-------
Dict[Optional[int],... | Create mapping from original values to minimum values set.
To use minimum possible dtype for labels.
Returns
-------
Dict[Optional[int], int]
Mapping from original values to minimum values set.
Dict[int, np.ndarray]
Mapping from new values to colors.
... | _values_mapping_to_minimum_values_set | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _get_typed_dict_mapping(self, data_dtype: np.dtype) -> 'typed.Dict':
"""Create mapping from label values to texture values of smaller dtype.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much slower than uint8 or uint16 textures. When
la... | Create mapping from label values to texture values of smaller dtype.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much slower than uint8 or uint16 textures. When
labels data is (u)int(8,16), we simply use the labels data directly.
But when ... | _get_typed_dict_mapping | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _array_map(self):
"""Create an array to map labels to texture values of smaller dtype."""
max_value = max(
(abs(x) for x in self.color_dict if x is not None), default=0
)
if any(x < 0 for x in self.color_dict if x is not None):
max_value *= 2
if max_v... | Create an array to map labels to texture values of smaller dtype. | _array_map | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _convert_small_ints_to_unsigned(
data: np.ndarray | np.integer,
) -> np.ndarray | np.integer:
"""Convert (u)int8 to uint8 and (u)int16 to uint16.
Otherwise, return the original array.
Parameters
----------
data : np.ndarray | np.integer
Data to be converted.
Returns
------... | Convert (u)int8 to uint8 and (u)int16 to uint16.
Otherwise, return the original array.
Parameters
----------
data : np.ndarray | np.integer
Data to be converted.
Returns
-------
np.ndarray | np.integer
Converted data.
| _convert_small_ints_to_unsigned | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _cast_labels_data_to_texture_dtype_auto(
data: np.ndarray | np.integer,
colormap: CyclicLabelColormap,
) -> np.ndarray | np.integer:
"""Convert labels data to the data type used in the texture.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much slow... | Convert labels data to the data type used in the texture.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much slower than uint8 or uint16 textures. Here we
convert the labels data to uint8 or uint16, based on the following rules:
- uint8 and uint16 labels d... | _cast_labels_data_to_texture_dtype_auto | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _cast_labels_data_to_texture_dtype_direct(
data: np.ndarray | np.integer, direct_colormap: DirectLabelColormap
) -> np.ndarray | np.integer:
"""Convert labels data to the data type used in the texture.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much ... | Convert labels data to the data type used in the texture.
In https://github.com/napari/napari/issues/6397, we noticed that using
float32 textures was much slower than uint8 or uint16 textures. Here we
convert the labels data to uint8 or uint16, based on the following rules:
- uint8 and uint16 labels d... | _cast_labels_data_to_texture_dtype_direct | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _texture_dtype(num_colors: int, dtype: np.dtype) -> np.dtype:
"""Compute VisPy texture dtype given number of colors and raw data dtype.
- for data of type int8 and uint8 we can use uint8 directly, with no copy.
- for int16 and uint16 we can use uint16 with no copy.
- for any other dtype, we fall ba... | Compute VisPy texture dtype given number of colors and raw data dtype.
- for data of type int8 and uint8 we can use uint8 directly, with no copy.
- for int16 and uint16 we can use uint16 with no copy.
- for any other dtype, we fall back on `minimum_dtype_for_labels`, which
will require on-CPU mapping... | _texture_dtype | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def _normalize_label_colormap(
any_colormap_like,
) -> CyclicLabelColormap | DirectLabelColormap:
"""Convenience function to convert color containers to LabelColormaps.
A list of colors or 2D nparray of colors is interpreted as a color cycle
(`CyclicLabelColormap`), and a mapping of colors is interpret... | Convenience function to convert color containers to LabelColormaps.
A list of colors or 2D nparray of colors is interpreted as a color cycle
(`CyclicLabelColormap`), and a mapping of colors is interpreted as a direct
color map (`DirectLabelColormap`).
Parameters
----------
any_colormap_like : ... | _normalize_label_colormap | python | napari/napari | src/napari/utils/colormaps/colormap.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap.py | BSD-3-Clause |
def convert_vispy_colormap(colormap, name='vispy'):
"""Convert a vispy colormap object to a napari colormap.
Parameters
----------
colormap : vispy.color.Colormap
Vispy colormap object that should be converted.
name : str
Name of colormap, optional.
Returns
-------
napa... | Convert a vispy colormap object to a napari colormap.
Parameters
----------
colormap : vispy.color.Colormap
Vispy colormap object that should be converted.
name : str
Name of colormap, optional.
Returns
-------
napari.utils.Colormap
| convert_vispy_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def _napari_cmap_to_vispy(colormap: Colormap) -> VispyColormap:
"""Convert a napari colormap to its equivalent vispy colormap."""
cmap_args = colormap.dict()
cmap_args.pop('name')
cmap_args['bad_color'] = cmap_args.pop('nan_color')
return VispyColormap(**cmap_args) | Convert a napari colormap to its equivalent vispy colormap. | _napari_cmap_to_vispy | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def _validate_rgb(colors, *, tolerance=0.0):
"""Return the subset of colors that is in [0, 1] for all channels.
Parameters
----------
colors : array of float, shape (N, 3)
Input colors in RGB space.
Returns
-------
filtered_colors : array of float, shape (M, 3), M <= N
The ... | Return the subset of colors that is in [0, 1] for all channels.
Parameters
----------
colors : array of float, shape (N, 3)
Input colors in RGB space.
Returns
-------
filtered_colors : array of float, shape (M, 3), M <= N
The subset of colors that are in valid RGB space.
O... | _validate_rgb | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def low_discrepancy_image(image, seed=0.5, margin=1 / 256) -> np.ndarray:
"""Generate a 1d low discrepancy sequence of coordinates.
Parameters
----------
image : array of int
A set of labels or label image.
seed : float
The seed from which to start the quasirandom sequence.
... | Generate a 1d low discrepancy sequence of coordinates.
Parameters
----------
image : array of int
A set of labels or label image.
seed : float
The seed from which to start the quasirandom sequence.
Effective range is [0,1.0), as only the decimals are used.
margin : float
... | low_discrepancy_image | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def color_dict_to_colormap(colors):
"""
Generate a color map based on the given color dictionary
Parameters
----------
colors : dict of int to array of float, shape (4)
Mapping between labels and color
Returns
-------
colormap : napari.utils.Colormap
Colormap constructe... |
Generate a color map based on the given color dictionary
Parameters
----------
colors : dict of int to array of float, shape (4)
Mapping between labels and color
Returns
-------
colormap : napari.utils.Colormap
Colormap constructed with provided control colors
label_co... | color_dict_to_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def _low_discrepancy(dim, n, seed=0.5):
"""Generate a 1d, 2d, or 3d low discrepancy sequence of coordinates.
Parameters
----------
dim : one of {1, 2, 3}
The dimensionality of the sequence.
n : int
How many points to generate.
seed : float or array of float, shape (dim,)
... | Generate a 1d, 2d, or 3d low discrepancy sequence of coordinates.
Parameters
----------
dim : one of {1, 2, 3}
The dimensionality of the sequence.
n : int
How many points to generate.
seed : float or array of float, shape (dim,)
The seed from which to start the quasirandom s... | _low_discrepancy | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def _color_random(n, *, colorspace='lab', tolerance=0.0, seed=0.5):
"""Generate n random RGB colors uniformly from LAB or LUV space.
Parameters
----------
n : int
Number of colors to generate.
colorspace : str, one of {'lab', 'luv', 'rgb'}
The colorspace from which to get random col... | Generate n random RGB colors uniformly from LAB or LUV space.
Parameters
----------
n : int
Number of colors to generate.
colorspace : str, one of {'lab', 'luv', 'rgb'}
The colorspace from which to get random colors.
tolerance : float
How much margin to allow for out-of-rang... | _color_random | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def label_colormap(
num_colors=256, seed=0.5, background_value=0
) -> CyclicLabelColormap:
"""Produce a colormap suitable for use with a given label set.
Parameters
----------
num_colors : int, optional
Number of unique colors to use. Default used if not given.
Colors are in additio... | Produce a colormap suitable for use with a given label set.
Parameters
----------
num_colors : int, optional
Number of unique colors to use. Default used if not given.
Colors are in addition to a transparent color 0.
seed : float, optional
The seed for the random color generator... | label_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def shuffle_and_extend_colormap(
colormap: CyclicLabelColormap, seed: int, min_random_choices: int = 5
) -> CyclicLabelColormap:
"""Shuffle the colormap colors and extend it to more colors.
The new number of colors will be a prime number that fits into the same
dtype as the current number of colors in ... | Shuffle the colormap colors and extend it to more colors.
The new number of colors will be a prime number that fits into the same
dtype as the current number of colors in the colormap.
Parameters
----------
colormap : napari.utils.CyclicLabelColormap
Colormap to shuffle and extend.
see... | shuffle_and_extend_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def direct_colormap(color_dict=None):
"""Make a direct colormap from a dictionary mapping labels to colors.
Parameters
----------
color_dict : dict, optional
A dictionary mapping labels to colors.
Returns
-------
d : DirectLabelColormap
A napari colormap whose map() functio... | Make a direct colormap from a dictionary mapping labels to colors.
Parameters
----------
color_dict : dict, optional
A dictionary mapping labels to colors.
Returns
-------
d : DirectLabelColormap
A napari colormap whose map() function applies the color dictionary
to an ... | direct_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def vispy_or_mpl_colormap(name) -> Colormap:
"""Try to get a colormap from vispy, or convert an mpl one to vispy format.
Parameters
----------
name : str
The name of the colormap.
Returns
-------
colormap : napari.utils.Colormap
The found colormap.
Raises
------
... | Try to get a colormap from vispy, or convert an mpl one to vispy format.
Parameters
----------
name : str
The name of the colormap.
Returns
-------
colormap : napari.utils.Colormap
The found colormap.
Raises
------
KeyError
If no colormap with that name is ... | vispy_or_mpl_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def _increment_unnamed_colormap(
existing: Iterable[str], name: str = '[unnamed colormap]'
) -> tuple[str, str]:
"""Increment name for unnamed colormap.
NOTE: this assumes colormaps are *never* deleted, and does not check
for name collision. If colormaps can ever be removed, please update.
P... | Increment name for unnamed colormap.
NOTE: this assumes colormaps are *never* deleted, and does not check
for name collision. If colormaps can ever be removed, please update.
Parameters
----------
existing : list of str
Names of existing colormaps.
name : str, optional
Na... | _increment_unnamed_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def ensure_colormap(colormap: ValidColormapArg) -> Colormap:
"""Accept any valid colormap argument, and return Colormap, or raise.
Adds any new colormaps to AVAILABLE_COLORMAPS in the process, except
for custom unnamed colormaps created from color values.
Parameters
----------
colormap : Valid... | Accept any valid colormap argument, and return Colormap, or raise.
Adds any new colormaps to AVAILABLE_COLORMAPS in the process, except
for custom unnamed colormaps created from color values.
Parameters
----------
colormap : ValidColormapArg
See ValidColormapArg for supported input types.
... | ensure_colormap | python | napari/napari | src/napari/utils/colormaps/colormap_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/colormap_utils.py | BSD-3-Clause |
def transform_color(colors: Any) -> np.ndarray:
"""Transforms provided color(s) to an Nx4 array of RGBA np.float32
values.
N is the number of given colors. The function is designed to parse all
valid color representations a user might have and convert them properly.
That being said, combinations of... | Transforms provided color(s) to an Nx4 array of RGBA np.float32
values.
N is the number of given colors. The function is designed to parse all
valid color representations a user might have and convert them properly.
That being said, combinations of different color representation in the
same list of... | transform_color | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _handle_str(color: str) -> np.ndarray:
"""Creates an array from a color of type string.
The function uses an LRU cache to enhance performance.
Parameters
----------
color : str
A single string as an input color. Can be a color name or a
hex representation of a color, with eithe... | Creates an array from a color of type string.
The function uses an LRU cache to enhance performance.
Parameters
----------
color : str
A single string as an input color. Can be a color name or a
hex representation of a color, with either 6 or 8 hex digits.
Returns
-------
... | _handle_str | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _handle_list_like(colors: Sequence) -> np.ndarray | None:
"""Parse a list-like container of colors into a numpy Nx4 array.
Handles all list-like containers of colors using recursion (if necessary).
The colors inside the container should all be represented in the same
manner. This means that a list ... | Parse a list-like container of colors into a numpy Nx4 array.
Handles all list-like containers of colors using recursion (if necessary).
The colors inside the container should all be represented in the same
manner. This means that a list containing ['r', (1., 1., 1.)] will raise
an error. Note that num... | _handle_list_like | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def handle_nested_colors(colors) -> ColorArray:
"""In case of an array-like container holding colors, unpack it."""
colors_as_rbga = np.ones((len(colors), 4), dtype=np.float32)
for idx, color in enumerate(colors):
colors_as_rbga[idx] = _color_switch[type(color)](color)
return ColorArray(colors_a... | In case of an array-like container holding colors, unpack it. | handle_nested_colors | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _handle_array(colors: np.ndarray) -> np.ndarray:
"""Converts the given array into an array in the right format."""
kind = colors.dtype.kind
# Object arrays aren't handled by napari
if kind == 'O':
warnings.warn(
trans._(
'An object array was passed as the color i... | Converts the given array into an array in the right format. | _handle_array | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _convert_array_to_correct_format(colors: np.ndarray) -> np.ndarray:
"""Asserts shape, dtype and normalization of given color array.
This function deals with arrays which are already 'well-behaved',
i.e. have (almost) the correct number of columns and are able to represent
colors correctly. It then ... | Asserts shape, dtype and normalization of given color array.
This function deals with arrays which are already 'well-behaved',
i.e. have (almost) the correct number of columns and are able to represent
colors correctly. It then it makes sure that the array indeed has exactly
four columns and that its v... | _convert_array_to_correct_format | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _handle_str_list_like(colors: Sequence | np.ndarray) -> np.ndarray:
"""Converts lists or arrays filled with strings to the proper color array
format.
Parameters
----------
colors : list-like
A sequence of string colors
Returns
-------
color_array : np.ndarray
Nx4, f... | Converts lists or arrays filled with strings to the proper color array
format.
Parameters
----------
colors : list-like
A sequence of string colors
Returns
-------
color_array : np.ndarray
Nx4, float32 color array
| _handle_str_list_like | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _normalize_color_array(colors: np.ndarray) -> np.ndarray:
"""Normalize all array values to the range [0, 1].
The added complexity here stems from the fact that if a row in the given
array contains four identical value a simple normalization might raise a
division by zero exception.
Parameters
... | Normalize all array values to the range [0, 1].
The added complexity here stems from the fact that if a row in the given
array contains four identical value a simple normalization might raise a
division by zero exception.
Parameters
----------
colors : np.ndarray
A numpy array with val... | _normalize_color_array | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _create_hex_to_name_dict():
"""Create a dictionary mapping hexadecimal RGB colors into their
'official' name.
Returns
-------
hex_to_rgb : dict
Mapping from hexadecimal RGB ('#ff0000') to name ('red').
"""
colordict = get_color_dict()
hex_to_name = {f'{v.lower()}ff': k for k... | Create a dictionary mapping hexadecimal RGB colors into their
'official' name.
Returns
-------
hex_to_rgb : dict
Mapping from hexadecimal RGB ('#ff0000') to name ('red').
| _create_hex_to_name_dict | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def _check_color_dim(val):
"""Ensures input is Nx4.
Parameters
----------
val : np.ndarray
A color array of possibly less than 4 columns
Returns
-------
val : np.ndarray
A four columns version of the input array. If the original array
was a missing the fourth channe... | Ensures input is Nx4.
Parameters
----------
val : np.ndarray
A color array of possibly less than 4 columns
Returns
-------
val : np.ndarray
A four columns version of the input array. If the original array
was a missing the fourth channel, it's added as 1.0 values.
| _check_color_dim | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def rgb_to_hex(rgbs: Sequence) -> np.ndarray:
"""Convert RGB to hex quadruplet.
Taken from vispy with slight modifications.
Parameters
----------
rgbs : Sequence
A list-like container of colors in RGBA format with values
between [0, 1]
Returns
-------
arr : np.ndarray
... | Convert RGB to hex quadruplet.
Taken from vispy with slight modifications.
Parameters
----------
rgbs : Sequence
A list-like container of colors in RGBA format with values
between [0, 1]
Returns
-------
arr : np.ndarray
An array of the hex representation of the inp... | rgb_to_hex | python | napari/napari | src/napari/utils/colormaps/standardize_color.py | https://github.com/napari/napari/blob/master/src/napari/utils/colormaps/standardize_color.py | BSD-3-Clause |
def minimum_dtype_for_labels(num_colors: int) -> np.dtype:
"""Return the minimum texture dtype that can hold given number of colors.
Parameters
----------
num_colors : int
Number of unique colors in the data.
Returns
-------
np.dtype
Minimum dtype that can hold the number o... | Return the minimum texture dtype that can hold given number of colors.
Parameters
----------
num_colors : int
Number of unique colors in the data.
Returns
-------
np.dtype
Minimum dtype that can hold the number of colors.
| minimum_dtype_for_labels | 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 zero_preserving_modulo_numpy(
values: np.ndarray, n: int, dtype: np.dtype, to_zero: int = 0
) -> 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 outp... | ``(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_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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.