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 _iter_indices(
self,
start: int = 0,
stop: int | None = None,
root: tuple[int, ...] = (),
) -> Generator[int | tuple[int]]:
"""Iter indices from start to stop.
Depth first traversal of the tree
"""
for i, item in enumerate(self[start:stop]):
... | Iter indices from start to stop.
Depth first traversal of the tree
| _iter_indices | 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 has_index(self, index: int | tuple[int, ...]) -> bool:
"""Return true if `index` is valid for this nestable list."""
if isinstance(index, int):
return -len(self) <= index < len(self)
if isinstance(index, tuple):
try:
self[index]
except Inde... | Return true if `index` is valid for this nestable list. | has_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 _preselect_hook(self, value: _T) -> _T:
"""Called before adding an item to the selection."""
if value not in self:
raise ValueError(
trans._(
'Cannot select item that is not in list: {value!r}',
deferred=True,
va... | Called before adding an item to the selection. | _preselect_hook | python | napari/napari | src/napari/utils/events/containers/_selectable_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_selectable_list.py | BSD-3-Clause |
def move_selected(self, index: int, insert: int) -> None:
"""Reorder list by moving the item at index and inserting it
at the insert index. If additional items are selected these will
get inserted at the insert index too. This allows for rearranging
the list based on dragging and droppin... | Reorder list by moving the item at index and inserting it
at the insert index. If additional items are selected these will
get inserted at the insert index too. This allows for rearranging
the list based on dragging and dropping a selection of items, where
index is the index of the prima... | move_selected | python | napari/napari | src/napari/utils/events/containers/_selectable_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_selectable_list.py | BSD-3-Clause |
def active(self, value: _T | None) -> None:
"""Set the active item.
This make `value` the only selected item, and make it current.
"""
if value == self._active:
return
self._active = value
self.clear() if value is None else self.select_only(value)
sel... | Set the active item.
This make `value` the only selected item, and make it current.
| active | python | napari/napari | src/napari/utils/events/containers/_selection.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_selection.py | BSD-3-Clause |
def _update_active(self) -> None:
"""On a selection event, update the active item based on selection.
(An active item is a single selected item).
"""
if len(self) == 1:
self.active = next(iter(self))
elif self._active is not None:
self._active = None
... | On a selection event, update the active item based on selection.
(An active item is a single selected item).
| _update_active | python | napari/napari | src/napari/utils/events/containers/_selection.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_selection.py | BSD-3-Clause |
def _json_encode(self) -> dict: # type: ignore[override]
"""Return an object that can be used by json.dumps."""
# we don't serialize active, as it's gleaned from the selection.
return {'selection': super()._json_encode(), '_current': self._current} | Return an object that can be used by json.dumps. | _json_encode | python | napari/napari | src/napari/utils/events/containers/_selection.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_selection.py | BSD-3-Clause |
def add(self, value: _T) -> None:
"""Add an element to the set, if not already present."""
if value not in self:
value = self._pre_add_hook(value)
self._set.add(value)
self._emit_change(added={value}, removed=set()) | Add an element to the set, if not already present. | add | python | napari/napari | src/napari/utils/events/containers/_set.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_set.py | BSD-3-Clause |
def update(self, others: Iterable[_T] = ()) -> None:
"""Update this set with the union of this set and others"""
to_add = set(others).difference(self._set)
if to_add:
to_add = {self._pre_add_hook(i) for i in to_add}
self._set.update(to_add)
self._emit_change(a... | Update this set with the union of this set and others | update | python | napari/napari | src/napari/utils/events/containers/_set.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_set.py | BSD-3-Clause |
def symmetric_difference_update(self, others: Iterable[_T]) -> None:
"""Update set to the symmetric difference of itself and another.
This will remove any items in this set that are also in `other`, and
add any items in others that are not present in this set.
"""
to_add = set(o... | Update set to the symmetric difference of itself and another.
This will remove any items in this set that are also in `other`, and
add any items in others that are not present in this set.
| symmetric_difference_update | python | napari/napari | src/napari/utils/events/containers/_set.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_set.py | BSD-3-Clause |
def __getitem__(self, key):
"""Get an item from the list
Parameters
----------
key : int, slice, or any type in self._lookup
The key to get.
Returns
-------
The value at `key`
Raises
------
IndexError:
If ``type(k... | Get an item from the list
Parameters
----------
key : int, slice, or any type in self._lookup
The key to get.
Returns
-------
The value at `key`
Raises
------
IndexError:
If ``type(key)`` is not in ``self._lookup`` (usual... | __getitem__ | python | napari/napari | src/napari/utils/events/containers/_typed.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_typed.py | BSD-3-Clause |
def __add__(self, other: Iterable[_T]) -> 'TypedMutableSequence[_T]':
"""Add other to self, return new object."""
copy = self.copy()
copy.extend(other)
return copy | Add other to self, return new object. | __add__ | python | napari/napari | src/napari/utils/events/containers/_typed.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_typed.py | BSD-3-Clause |
def index(self, value: _L, start: int = 0, stop: int | None = None) -> int:
"""Return first index of value.
Parameters
----------
value : Any
A value to lookup. If `type(value)` is in the lookups functions
provided for this class, then values in the list will be... | Return first index of value.
Parameters
----------
value : Any
A value to lookup. If `type(value)` is in the lookups functions
provided for this class, then values in the list will be searched
using the corresponding lookup converter function.
start ... | index | python | napari/napari | src/napari/utils/events/containers/_typed.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_typed.py | BSD-3-Clause |
def _iter_indices(
self, start: int = 0, stop: int | None = None
) -> Iterable[int]:
"""Iter indices from start to stop.
While this is trivial for this basic sequence type, this method lets
subclasses (like NestableEventedList modify how they are traversed).
"""
yiel... | Iter indices from start to stop.
While this is trivial for this basic sequence type, this method lets
subclasses (like NestableEventedList modify how they are traversed).
| _iter_indices | python | napari/napari | src/napari/utils/events/containers/_typed.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/containers/_typed.py | BSD-3-Clause |
def test_copy(test_dict, regular_dict):
"""Copying an evented dict should return a same-class evented dict."""
new_test = test_dict.copy()
assert len({type(k) for k in new_test}) >= 2, (
'We want at least non-string keys to test edge cases'
)
new_reg = regular_dict.copy()
assert id(new_... | Copying an evented dict should return a same-class evented dict. | test_copy | python | napari/napari | src/napari/utils/events/_tests/test_evented_dict.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_dict.py | BSD-3-Clause |
def test_child_events():
"""Test that evented dicts bubble child events."""
# create a random object that emits events
e_obj = E()
root = EventedDict()
observed = []
root.events.connect(lambda e: observed.append(e))
root['A'] = e_obj
e_obj.events.test(value='hi')
obs = [(e.type, e.ke... | Test that evented dicts bubble child events. | test_child_events | python | napari/napari | src/napari/utils/events/_tests/test_evented_dict.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_dict.py | BSD-3-Clause |
def test_evented_dict_subclass():
"""Test that multiple inheritance maintains events from superclass."""
class A:
events = EmitterGroup(boom=None)
class B(A, EventedDict):
pass
dct = B({'A': 1, 'B': 2})
assert hasattr(dct, 'events')
assert 'boom' in dct.events.emitters
ass... | Test that multiple inheritance maintains events from superclass. | test_evented_dict_subclass | python | napari/napari | src/napari/utils/events/_tests/test_evented_dict.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_dict.py | BSD-3-Clause |
def test_copy(test_list, regular_list):
"""Copying an evented list should return a same-class evented list."""
new_test = test_list.copy()
new_reg = regular_list.copy()
assert id(new_test) != id(test_list)
assert new_test == test_list
assert tuple(new_test) == tuple(test_list) == tuple(new_reg)
... | Copying an evented list should return a same-class evented list. | test_copy | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_move(test_list):
"""Test the that we can move objects with the move method"""
test_list.events = Mock(wraps=test_list.events)
def _fail():
raise AssertionError('unexpected event called')
test_list.events.removing.connect(_fail)
test_list.events.removed.connect(_fail)
test_list... | Test the that we can move objects with the move method | test_move | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_move_multiple_mimics_slice_reorder():
"""Test the that move_multiple provides the same result as slice insertion."""
data = list(range(8))
el = EventedList(data)
el.events = Mock(wraps=el.events)
assert el == data
new_order = [1, 5, 3, 4, 6, 7, 2, 0]
# this syntax
el.move_multip... | Test the that move_multiple provides the same result as slice insertion. | test_move_multiple_mimics_slice_reorder | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_slice(test_list, regular_list):
"""Slicing an evented list should return a same-class evented list."""
test_slice = test_list[1:3]
regular_slice = regular_list[1:3]
assert tuple(test_slice) == tuple(regular_slice)
assert isinstance(test_slice, test_list.__class__) | Slicing an evented list should return a same-class evented list. | test_slice | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def flatten(container):
"""Flatten arbitrarily nested list.
Examples
--------
>>> a = [1, [2, [3], 4], 5]
>>> list(flatten(a))
[1, 2, 3, 4, 5]
"""
for i in container:
if isinstance(i, MutableSequence):
yield from flatten(i)
else:
yield i | Flatten arbitrarily nested list.
Examples
--------
>>> a = [1, [2, [3], 4], 5]
>>> list(flatten(a))
[1, 2, 3, 4, 5]
| flatten | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_nested_indexing():
"""test that we can index a nested list with nl[1, 2, 3] syntax."""
ne_list = NestableEventedList(NEST)
# 110 -> '110' -> (1, 1, 0)
indices = [tuple(int(x) for x in str(n)) for n in flatten(NEST)]
for index in indices:
assert ne_list[index] == int(''.join(map(str,... | test that we can index a nested list with nl[1, 2, 3] syntax. | test_nested_indexing | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_child_events():
"""Test that evented lists bubble child events."""
# create a random object that emits events
e_obj = E()
# and two nestable evented lists
root = EventedList()
observed = []
root.events.connect(lambda e: observed.append(e))
root.append(e_obj)
e_obj.events.tes... | Test that evented lists bubble child events. | test_child_events | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_array_like_setitem():
"""Test that EventedList.__setitem__ works for array-like items"""
array = np.array((10, 10))
evented_list = EventedList([array])
evented_list[0] = array | Test that EventedList.__setitem__ works for array-like items | test_array_like_setitem | python | napari/napari | src/napari/utils/events/_tests/test_evented_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_list.py | BSD-3-Clause |
def test_creating_empty_evented_model():
"""Test creating an empty evented pydantic model."""
model = EventedModel()
assert model is not None
assert model.events is not None | Test creating an empty evented pydantic model. | test_creating_empty_evented_model | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model():
"""Test creating an evented pydantic model."""
class User(EventedModel):
"""Demo evented model.
Parameters
----------
id : int
User id.
name : str, optional
User name.
"""
id: int
name: str = 'Al... | Test creating an evented pydantic model. | test_evented_model | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_with_array():
"""Test creating an evented pydantic model with an array."""
def make_array():
return np.array([[4, 3]])
class Model(EventedModel):
"""Demo evented model."""
int_values: Array[int]
any_values: Array
shaped1_values: Array[float, ... | Test creating an evented pydantic model with an array. | test_evented_model_with_array | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_array_updates():
"""Test updating an evented pydantic model with an array."""
class Model(EventedModel):
"""Demo evented model."""
values: Array[int]
model = Model(values=[1, 2, 3])
# Mock events
model.events.values = Mock(model.events.values)
np.testi... | Test updating an evented pydantic model with an array. | test_evented_model_array_updates | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_array_equality():
"""Test checking equality with an evented model with custom array."""
class Model(EventedModel):
"""Demo evented model."""
values: Array[int]
model1 = Model(values=[1, 2, 3])
model2 = Model(values=[1, 5, 6])
assert model1 == model1
ass... | Test checking equality with an evented model with custom array. | test_evented_model_array_equality | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_np_array_equality():
"""Test checking equality with an evented model with direct numpy."""
class Model(EventedModel):
values: np.ndarray
model1 = Model(values=np.array([1, 2, 3]))
model2 = Model(values=np.array([1, 5, 6]))
assert model1 == model1
assert model1 !... | Test checking equality with an evented model with direct numpy. | test_evented_model_np_array_equality | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_da_array_equality():
"""Test checking equality with an evented model with direct dask."""
class Model(EventedModel):
values: da.Array
r = da.ones((64, 64))
model1 = Model(values=r)
model2 = Model(values=da.ones((64, 64)))
assert model1 == model1
# dask array... | Test checking equality with an evented model with direct dask. | test_evented_model_da_array_equality | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_nested_evented_model_serialization():
"""Test that encoders on nested sub-models can be used by top model."""
class NestedModel(EventedModel):
obj: MyObj
class Model(EventedModel):
nest: NestedModel
m = Model(nest={'obj': {'a': 1, 'b': 'hi'}})
raw = m.json()
assert ra... | Test that encoders on nested sub-models can be used by top model. | test_nested_evented_model_serialization | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_dask_delayed():
"""Test that evented models work with dask delayed objects"""
class MyObject(EventedModel):
attribute: Delayed
@delayed
def my_function():
pass
o1 = MyObject(attribute=my_function)
# check that equality checking works as expected
ass... | Test that evented models work with dask delayed objects | test_evented_model_dask_delayed | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_evented_model_with_property_setter_events(
mocked_object, attribute, value, expected_event_values
):
"""Test that setting connected fields and properties fires the right events.
For each field and property, set a new value and check that all the
dependent fields/properties fire events with the... | Test that setting connected fields and properties fires the right events.
For each field and property, set a new value and check that all the
dependent fields/properties fire events with the correct value,
and that non-connected properties fire no event.
| test_evented_model_with_property_setter_events | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_property_get_eq_operator():
"""Test if the __eq_operators__ for properties are properly recognized"""
class Tt(EventedModel):
a: int = 1
@property
def b(self) -> float: # pragma: no cover
return self.a * 2
@property
def c(self): # pragma: no cove... | Test if the __eq_operators__ for properties are properly recognized | test_property_get_eq_operator | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_property_str_annotation():
"""Test if the __str_annotations__ for properties are properly recognized"""
class Tt(EventedModel):
a: int = 1
@property
def b(self) -> 'np.ndarray': # pragma: no cover
return np.ndarray([self.a, self.a])
@property
def ... | Test if the __str_annotations__ for properties are properly recognized | test_property_str_annotation | python | napari/napari | src/napari/utils/events/_tests/test_evented_model.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_evented_model.py | BSD-3-Clause |
def test_weakref_event_emitter():
"""
We are testing that an event blocker does not keep hard reference to
the object we are blocking, especially if it's a bound method.
The reason it used to keep references is to get the count of how many time
a callback was blocked, but if the object does not exi... |
We are testing that an event blocker does not keep hard reference to
the object we are blocking, especially if it's a bound method.
The reason it used to keep references is to get the count of how many time
a callback was blocked, but if the object does not exists, then the bound method
does not a... | test_weakref_event_emitter | python | napari/napari | src/napari/utils/events/_tests/test_event_emitter.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_event_emitter.py | BSD-3-Clause |
def test_weakref_event_emitter_cb(disconnect_and_should_be_none):
"""
Note that as above but with pure callback, We keep a reference to it, the
reason is that unlike with bound method, the callback may be a closure and
may not stick around.
We thus expect the wekref to be None only if explicitely ... |
Note that as above but with pure callback, We keep a reference to it, the
reason is that unlike with bound method, the callback may be a closure and
may not stick around.
We thus expect the wekref to be None only if explicitely disconnected
| test_weakref_event_emitter_cb | python | napari/napari | src/napari/utils/events/_tests/test_event_emitter.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_event_emitter.py | BSD-3-Clause |
def test_error_on_connect():
"""Check that connections happen correctly even on decorated methods.
Some decorators will alter method.__name__, so that obj.method
will not be equal to getattr(obj, obj.method.__name__). We check here
that event binding will be correct even in these situations.
"""
... | Check that connections happen correctly even on decorated methods.
Some decorators will alter method.__name__, so that obj.method
will not be equal to getattr(obj, obj.method.__name__). We check here
that event binding will be correct even in these situations.
| test_error_on_connect | python | napari/napari | src/napari/utils/events/_tests/test_event_emitter.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_event_emitter.py | BSD-3-Clause |
def test_type_enforcement(dict_type):
"""Test that TypedDicts enforce type during mutation events."""
a = dict_type({'A': 1, 'B': 3, 'C': 5}, basetype=int)
assert tuple(a.values()) == (1, 3, 5)
with pytest.raises(TypeError):
a['D'] = 'string'
with pytest.raises(TypeError):
a.update({... | Test that TypedDicts enforce type during mutation events. | test_type_enforcement | python | napari/napari | src/napari/utils/events/_tests/test_typed_dict.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_typed_dict.py | BSD-3-Clause |
def test_multitype_enforcement(dict_type):
"""Test that basetype also accepts/enforces a sequence of types."""
a = dict_type({'A': 1, 'B': 3, 'C': 5.5}, basetype=(int, float))
assert tuple(a.values()) == (1, 3, 5.5)
with pytest.raises(TypeError):
a['D'] = 'string'
a['D'] = 2.4
a.update({... | Test that basetype also accepts/enforces a sequence of types. | test_multitype_enforcement | python | napari/napari | src/napari/utils/events/_tests/test_typed_dict.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_typed_dict.py | BSD-3-Clause |
def test_type_enforcement(list_type):
"""Test that TypedLists enforce type during mutation events."""
a = list_type([1, 2, 3, 4], basetype=int)
assert tuple(a) == (1, 2, 3, 4)
with pytest.raises(TypeError):
a.append('string')
with pytest.raises(TypeError):
a.insert(0, 'string')
w... | Test that TypedLists enforce type during mutation events. | test_type_enforcement | python | napari/napari | src/napari/utils/events/_tests/test_typed_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_typed_list.py | BSD-3-Clause |
def test_custom_lookup(list_type):
"""Test that we can get objects by non-integer index using custom lookups."""
class Custom:
def __init__(self, name='', data=()) -> None:
self.name = name
self.data = data
hi = Custom(name='hi')
dct = Custom(data={'some': 'data'})
... | Test that we can get objects by non-integer index using custom lookups. | test_custom_lookup | python | napari/napari | src/napari/utils/events/_tests/test_typed_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_typed_list.py | BSD-3-Clause |
def test_nested_type_enforcement():
"""Test that type enforcement also works with NestableLists."""
data = [1, 2, [3, 4, [5, 6]]]
a = NestableEventedList(data, basetype=int)
assert a[2, 2, 1] == 6
# first level
with pytest.raises(TypeError):
a.append('string')
with pytest.raises(Typ... | Test that type enforcement also works with NestableLists. | test_nested_type_enforcement | python | napari/napari | src/napari/utils/events/_tests/test_typed_list.py | https://github.com/napari/napari/blob/master/src/napari/utils/events/_tests/test_typed_list.py | BSD-3-Clause |
def _patch_perf_timer(
parent: ModuleType | type, callable_name: str, label: str
) -> None:
"""Patches the callable to run it inside a perf_timer.
Parameters
----------
parent
The module or class that contains the callable.
callable_name : str
The name of the callable (function ... | Patches the callable to run it inside a perf_timer.
Parameters
----------
parent
The module or class that contains the callable.
callable_name : str
The name of the callable (function or method).
label : str
The <function> or <class>.<method> we are patching.
| _patch_perf_timer | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def patch_callables(self) -> None:
"""Patch callables according to the config file.
Call once at startup but after main() has started running. Do not
call at module init or you will likely get circular dependencies.
This function potentially imports many modules.
"""
if ... | Patch callables according to the config file.
Call once at startup but after main() has started running. Do not
call at module init or you will likely get circular dependencies.
This function potentially imports many modules.
| patch_callables | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def _get_callables(self, list_name: str) -> list[str]:
"""Get the list of callables from the config file.
list_name : str
The name of the list to return.
"""
try:
return self.data['callable_lists'][list_name]
except KeyError as e:
raise Perfmo... | Get the list of callables from the config file.
list_name : str
The name of the list to return.
| _get_callables | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def _patch_callables(self) -> None:
"""Add a perf_timer to every callable.
Notes
-----
data["trace_callables"] should contain the names of one or more
lists of callables which are defined in data["callable_lists"].
"""
for list_name in self.data['trace_callables'... | Add a perf_timer to every callable.
Notes
-----
data["trace_callables"] should contain the names of one or more
lists of callables which are defined in data["callable_lists"].
| _patch_callables | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def trace_qt_events(self) -> bool:
"""Return True if we should time Qt events."""
if self.config_path is None:
return True # always trace qt events in legacy mode
try:
return self.data['trace_qt_events']
except KeyError:
return False | Return True if we should time Qt events. | trace_qt_events | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def trace_file_on_start(self) -> str | None:
"""Return path of trace file to write or None."""
if self.config_path is None:
return None # don't trace on start in legacy mode
try:
path = self.data['trace_file_on_start']
# Return None if it was empty string or... | Return path of trace file to write or None. | trace_file_on_start | python | napari/napari | src/napari/utils/perf/_config.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_config.py | BSD-3-Clause |
def _patch_attribute(
module: types.ModuleType, attribute_str: str, patch_func: PatchFunction
) -> None:
"""Patch the module's callable pointed to by the attribute string.
Parameters
----------
module : types.ModuleType
The module to patch.
attribute_str : str
An attribute in th... | Patch the module's callable pointed to by the attribute string.
Parameters
----------
module : types.ModuleType
The module to patch.
attribute_str : str
An attribute in the module like "function" or "class.method".
patch_func : PatchFunction
This function is called to perfor... | _patch_attribute | python | napari/napari | src/napari/utils/perf/_patcher.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_patcher.py | BSD-3-Clause |
def _import_module(
target_str: str,
) -> tuple[types.ModuleType, str] | tuple[None, None]:
"""Import the module portion of this target string.
Try importing successively longer segments of the target_str. For example:
napari.components.experimental.chunk._loader.ChunkLoader.load_chunk
will impo... | Import the module portion of this target string.
Try importing successively longer segments of the target_str. For example:
napari.components.experimental.chunk._loader.ChunkLoader.load_chunk
will import:
napari (success)
napari.components (success)
napari.components.experimental... | _import_module | python | napari/napari | src/napari/utils/perf/_patcher.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_patcher.py | BSD-3-Clause |
def patch_callables(callables: list[str], patch_func: PatchFunction) -> None:
"""Patch the given list of callables.
Parameters
----------
callables : List[str]
Patch all of these callables (functions or methods).
patch_func : PatchFunction
Called on every callable to patch it.
... | Patch the given list of callables.
Parameters
----------
callables : List[str]
Patch all of these callables (functions or methods).
patch_func : PatchFunction
Called on every callable to patch it.
Notes
-----
The callables list should look like:
[
"module.module... | patch_callables | python | napari/napari | src/napari/utils/perf/_patcher.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_patcher.py | BSD-3-Clause |
def __init__(self, value: int) -> None:
"""Create Stat with an initial value.
Parameters
----------
value : int
Initial value.
"""
self.min = value
self.max = value
self.sum = value
self.count = 1 | Create Stat with an initial value.
Parameters
----------
value : int
Initial value.
| __init__ | python | napari/napari | src/napari/utils/perf/_stat.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_stat.py | BSD-3-Clause |
def add(self, value: int) -> None:
"""Add a new value.
Parameters
----------
value : int
The new value.
"""
self.sum += value
self.count += 1
self.max = max(self.max, value)
self.min = min(self.min, value) | Add a new value.
Parameters
----------
value : int
The new value.
| add | python | napari/napari | src/napari/utils/perf/_stat.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_stat.py | BSD-3-Clause |
def average(self) -> int:
"""Average value.
Returns
-------
average value : int.
"""
if self.count > 0:
return self.sum // self.count
raise ValueError('no values') # impossible for us | Average value.
Returns
-------
average value : int.
| average | python | napari/napari | src/napari/utils/perf/_stat.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_stat.py | BSD-3-Clause |
def add_event(self, event: PerfEvent) -> None:
"""Save an event to performance trace file and
update the timers if the event has phase 'X'.
Parameters
----------
event : PerfEvent
Add this event.
"""
# Add event if tracing.
if self.trace_file ... | Save an event to performance trace file and
update the timers if the event has phase 'X'.
Parameters
----------
event : PerfEvent
Add this event.
| add_event | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def add_instant_event(
self,
name: str,
*,
category: str | None = None,
process_id: int | None = None,
thread_id: int | None = None,
**kwargs: float,
) -> None:
"""Build and add one event of length 0.
Parameters
----------
name... | Build and add one event of length 0.
Parameters
----------
name : str
Add this event.
category : str | None
Comma separated categories such as "render,update".
process_id : int | None
The process id that produced the event.
thread_id :... | add_instant_event | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def add_counter_event(self, name: str, **kwargs: float) -> None:
"""Add one counter event.
Parameters
----------
name : str
The name of this event like "draw".
**kwargs : float
The individual counters for this event.
Notes
-----
F... | Add one counter event.
Parameters
----------
name : str
The name of this event like "draw".
**kwargs : float
The individual counters for this event.
Notes
-----
For example add_counter_event("draw", triangles=5, squares=10).
| add_counter_event | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def block_timer(
name: str,
category: str | None = None,
print_time: bool = False,
*,
process_id: int | None = None,
thread_id: int | None = None,
phase: str = 'X',
**kwargs: float,
) -> Generator[PerfEvent, None, None]:
"""Time a block of code.
block_timer can be used when perf... | Time a block of code.
block_timer can be used when perfmon is disabled. Use perf_timer instead
if you want your timer to do nothing when perfmon is disabled.
Notes
-----
Most of the time you should use the perfmon config file to monkey-patch
perf_timer's into methods and functions. Then you do... | block_timer | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def add_instant_event(
self, name: str, **kwargs: str | float | None
) -> None:
"""empty timer to use when perfmon is disabled""" | empty timer to use when perfmon is disabled | add_instant_event | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def add_instant_event(
name: str,
*,
category: str | None = None,
process_id: int | None = None,
thread_id: int | None = None,
**kwargs: float,
) -> None:
"""Add one instant event.
Parameters
----------
name : str
Add this event.
category : str | None
Comma s... | Add one instant event.
Parameters
----------
name : str
Add this event.
category : str | None
Comma separated categories such as "render,update".
process_id : int | None
The process id that produced the event.
thread_id : int | None
The thread id that produced th... | add_instant_event | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def perf_timer( # type: ignore [misc]
name: str,
category: str | None = None,
print_time: bool = False,
*,
process_id: int | None = None,
thread_id: int | None = None,
phase: str = 'X',
**kwargs: float,
) -> Generator[None, None, None]:
"""Do ... | Do nothing when perfmon is disabled. | perf_timer | python | napari/napari | src/napari/utils/perf/_timers.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_timers.py | BSD-3-Clause |
def __init__(self, output_path: str) -> None:
"""Store events in memory and write to the file when done."""
self.output_path = output_path
# So the events we write start at t=0.
self.zero_ns = perf_counter_ns()
# Accumulate events in a list and only write at the end so the cost... | Store events in memory and write to the file when done. | __init__ | python | napari/napari | src/napari/utils/perf/_trace_file.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_trace_file.py | BSD-3-Clause |
def close(self) -> None:
"""Close the trace file, write all events to disk."""
event_data = [self._get_event_data(x) for x in self.events]
with open(self.output_path, 'w') as outf:
json.dump(event_data, outf) | Close the trace file, write all events to disk. | close | python | napari/napari | src/napari/utils/perf/_trace_file.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_trace_file.py | BSD-3-Clause |
def _get_event_data(self, event: 'PerfEvent') -> dict:
"""Return the data for one perf event.
Parameters
----------
event : PerfEvent
Event to write.
Returns
-------
dict
The data to be written to JSON.
"""
category = 'non... | Return the data for one perf event.
Parameters
----------
event : PerfEvent
Event to write.
Returns
-------
dict
The data to be written to JSON.
| _get_event_data | python | napari/napari | src/napari/utils/perf/_trace_file.py | https://github.com/napari/napari/blob/master/src/napari/utils/perf/_trace_file.py | BSD-3-Clause |
def set_slice(self, axes: Sequence[int]) -> 'Transform':
"""Return a transform subset to the visible dimensions.
Parameters
----------
axes : Sequence[int]
Axes to subset the current transform with.
Returns
-------
Transform
Resulting tra... | Return a transform subset to the visible dimensions.
Parameters
----------
axes : Sequence[int]
Axes to subset the current transform with.
Returns
-------
Transform
Resulting transform.
| set_slice | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def expand_dims(self, axes: Sequence[int]) -> 'Transform':
"""Return a transform with added axes for non-visible dimensions.
Parameters
----------
axes : Sequence[int]
Location of axes to expand the current transform with. Passing a
list allows expansion to occur... | Return a transform with added axes for non-visible dimensions.
Parameters
----------
axes : Sequence[int]
Location of axes to expand the current transform with. Passing a
list allows expansion to occur at specific locations and for
expand_dims to be like an i... | expand_dims | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def simplified(self) -> _T:
"""
Return the composite of the transforms inside the transform chain.
Raises
------
ValueError
If the transform chain is empty.
"""
if len(self) == 0:
raise ValueError(
trans._('Cannot simplify ... |
Return the composite of the transforms inside the transform chain.
Raises
------
ValueError
If the transform chain is empty.
| simplified | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def compose(self, transform: 'Transform') -> 'Transform':
"""Return the composite of this transform and the provided one."""
if not isinstance(transform, ScaleTranslate):
super().compose(transform)
scale = self.scale * transform.scale
translate = self.translate + self.scale *... | Return the composite of this transform and the provided one. | compose | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def scale(self) -> npt.NDArray:
"""Return the scale of the transform."""
if self._is_diagonal:
return np.diag(self._linear_matrix)
self._setup_decompose_linear_matrix_cache()
return self._cache_dict['decompose_linear_matrix'][1] | Return the scale of the transform. | scale | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def scale(self, scale):
"""Set the scale of the transform."""
if self._is_diagonal:
scale = scale_to_vector(scale, ndim=self.ndim)
for i in range(len(scale)):
self._linear_matrix[i, i] = scale[i]
else:
self._linear_matrix = compose_linear_matri... | Set the scale of the transform. | scale | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def rotate(self, rotate):
"""Set the rotation of the transform."""
self._linear_matrix = compose_linear_matrix(
rotate, self.scale, self._shear_cache
)
self._clean_cache() | Set the rotation of the transform. | rotate | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def shear(self) -> npt.NDArray:
"""Return the shear of the transform."""
if self._is_diagonal:
return np.zeros((self.ndim,))
self._setup_decompose_linear_matrix_cache()
return self._cache_dict['decompose_linear_matrix'][2] | Return the shear of the transform. | shear | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def shear(self, shear):
"""Set the shear of the transform."""
shear = np.asarray(shear)
if shear.ndim == 2:
if is_matrix_triangular(shear):
self._upper_triangular = is_matrix_upper_triangular(shear)
else:
raise ValueError(
... | Set the shear of the transform. | shear | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def linear_matrix(self, linear_matrix):
"""Set the linear matrix of the transform."""
self._linear_matrix = embed_in_identity_matrix(
linear_matrix, ndim=self.ndim
)
self._clean_cache() | Set the linear matrix of the transform. | linear_matrix | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def affine_matrix(self) -> npt.NDArray:
"""Return the affine matrix for the transform."""
matrix = np.eye(self.ndim + 1, self.ndim + 1)
matrix[:-1, :-1] = self._linear_matrix
matrix[:-1, -1] = self._translate
return matrix | Return the affine matrix for the transform. | affine_matrix | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def affine_matrix(self, affine_matrix):
"""Set the affine matrix for the transform."""
self._linear_matrix = affine_matrix[:-1, :-1]
self._translate = affine_matrix[:-1, -1]
self._clean_cache() | Set the affine matrix for the transform. | affine_matrix | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def set_slice(self, axes: Sequence[int]) -> 'Affine':
"""Return a transform subset to the visible dimensions.
Parameters
----------
axes : Sequence[int]
Axes to subset the current transform with.
Returns
-------
Affine
Resulting transform... | Return a transform subset to the visible dimensions.
Parameters
----------
axes : Sequence[int]
Axes to subset the current transform with.
Returns
-------
Affine
Resulting transform.
| set_slice | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def replace_slice(
self, axes: Sequence[int], transform: 'Affine'
) -> 'Affine':
"""Returns a transform where the transform at the indicated n dimensions is replaced with another n-dimensional transform
Parameters
----------
axes : Sequence[int]
Axes where the tr... | Returns a transform where the transform at the indicated n dimensions is replaced with another n-dimensional transform
Parameters
----------
axes : Sequence[int]
Axes where the transform will be replaced
transform : Affine
The transform that will be inserted. Mus... | replace_slice | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def _is_diagonal(self):
"""Determine whether linear_matrix is diagonal up to some tolerance.
Since only `self.linear_matrix` is checked, affines with a translation
component can still be considered diagonal.
"""
if '_is_diagonal' not in self._cache_dict:
self._cache_... | Determine whether linear_matrix is diagonal up to some tolerance.
Since only `self.linear_matrix` is checked, affines with a translation
component can still be considered diagonal.
| _is_diagonal | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def linear_matrix(self, linear_matrix):
"""Setting the linear matrix of a CompositeAffine transform is not supported."""
raise NotImplementedError(
trans._(
'linear_matrix cannot be set directly for a CompositeAffine transform',
deferred=True,
)
... | Setting the linear matrix of a CompositeAffine transform is not supported. | linear_matrix | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def affine_matrix(self, affine_matrix):
"""Setting the affine matrix of a CompositeAffine transform is not supported."""
raise NotImplementedError(
trans._(
'affine_matrix cannot be set directly for a CompositeAffine transform',
deferred=True,
)
... | Setting the affine matrix of a CompositeAffine transform is not supported. | affine_matrix | python | napari/napari | src/napari/utils/transforms/transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transforms.py | BSD-3-Clause |
def compose_linear_matrix(rotate, scale, shear) -> npt.NDArray:
"""Compose linear transform matrix from rotate, shear, scale.
Parameters
----------
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple conve... | Compose linear transform matrix from rotate, shear, scale.
Parameters
----------
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll conventi... | compose_linear_matrix | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def infer_ndim(
*, scale=None, translate=None, rotate=None, shear=None, linear_matrix=None
):
"""Infer the dimensionality of a transformation from its input components.
This is most useful when the dimensions of the inputs do not match, either
when broadcasting is desired or when an input represents a ... | Infer the dimensionality of a transformation from its input components.
This is most useful when the dimensions of the inputs do not match, either
when broadcasting is desired or when an input represents a parameterization
of a transform component (e.g. rotate as an angle of a 2D rotation).
Parameters... | infer_ndim | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def translate_to_vector(translate, *, ndim):
"""Convert a translate input into an n-dimensional transform component.
Parameters
----------
translate : 1-D array
A 1-D array of factors to shift each axis by. Translation is padded
with 0 in leading dimensions, so that, for example, a tran... | Convert a translate input into an n-dimensional transform component.
Parameters
----------
translate : 1-D array
A 1-D array of factors to shift each axis by. Translation is padded
with 0 in leading dimensions, so that, for example, a translation of
[4, 18, 34] in 3D can be used as ... | translate_to_vector | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def scale_to_vector(scale, *, ndim):
"""Convert a scale input into an n-dimensional transform component.
Parameters
----------
scale : 1-D array
A 1-D array of factors to scale each axis by. Scale is padded with 1
in leading dimensions, so that, for example, a scale of [4, 18, 34] in
... | Convert a scale input into an n-dimensional transform component.
Parameters
----------
scale : 1-D array
A 1-D array of factors to scale each axis by. Scale is padded with 1
in leading dimensions, so that, for example, a scale of [4, 18, 34] in
3D can be used as a scale of [1, 4, 18... | scale_to_vector | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def rotate_to_matrix(rotate, *, ndim):
"""Convert a rotate input into an n-dimensional transform component.
Parameters
----------
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotat... | Convert a rotate input into an n-dimensional transform component.
Parameters
----------
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll c... | rotate_to_matrix | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def _make_2d_rotation(theta_degrees):
"""Makes a 2D rotation matrix from an angle in degrees."""
cos_theta, sin_theta = _cos_sin_degrees(theta_degrees)
return np.array([[cos_theta, -sin_theta], [sin_theta, cos_theta]]) | Makes a 2D rotation matrix from an angle in degrees. | _make_2d_rotation | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def _make_3d_rotation(alpha_degrees, beta_degrees, gamma_degrees):
"""Makes a 3D rotation matrix from roll, pitch, and yaw in degrees.
For more details, see: https://en.wikipedia.org/wiki/Rotation_matrix#General_rotations
"""
cos_alpha, sin_alpha = _cos_sin_degrees(alpha_degrees)
R_alpha = np.array... | Makes a 3D rotation matrix from roll, pitch, and yaw in degrees.
For more details, see: https://en.wikipedia.org/wiki/Rotation_matrix#General_rotations
| _make_3d_rotation | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def shear_to_matrix(shear, *, ndim):
"""Convert a shear input into an n-dimensional transform component.
Parameters
----------
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
ndim : int
The d... | Convert a shear input into an n-dimensional transform component.
Parameters
----------
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
ndim : int
The desired dimensionality of the output transfor... | shear_to_matrix | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def expand_upper_triangular(vector):
"""Expand a vector into an upper triangular matrix.
Decomposition is based on code from https://github.com/matthew-brett/transforms3d.
In particular, the `striu2mat` function in the `shears` module.
https://github.com/matthew-brett/transforms3d/blob/0.3.1/transforms... | Expand a vector into an upper triangular matrix.
Decomposition is based on code from https://github.com/matthew-brett/transforms3d.
In particular, the `striu2mat` function in the `shears` module.
https://github.com/matthew-brett/transforms3d/blob/0.3.1/transforms3d/shears.py#L30-L77.
Parameters
--... | expand_upper_triangular | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def embed_in_identity_matrix(matrix, ndim):
"""Embed an MxM matrix bottom right of larger NxN identity matrix.
Parameters
----------
matrix : np.array
2D square matrix, MxM.
ndim : int
Integer with N >= M.
Returns
-------
full_matrix : np.array shape (N, N)
Larg... | Embed an MxM matrix bottom right of larger NxN identity matrix.
Parameters
----------
matrix : np.array
2D square matrix, MxM.
ndim : int
Integer with N >= M.
Returns
-------
full_matrix : np.array shape (N, N)
Larger matrix.
| embed_in_identity_matrix | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def decompose_linear_matrix(
matrix, upper_triangular=True
) -> tuple[npt.NDArray, npt.NDArray, npt.NDArray]:
"""Decompose linear transform matrix into rotate, scale, shear.
Decomposition is based on code from https://github.com/matthew-brett/transforms3d.
In particular, the `decompose` function in the... | Decompose linear transform matrix into rotate, scale, shear.
Decomposition is based on code from https://github.com/matthew-brett/transforms3d.
In particular, the `decompose` function in the `affines` module.
https://github.com/matthew-brett/transforms3d/blob/0.3.1/transforms3d/affines.py#L156-L246.
P... | decompose_linear_matrix | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def shear_matrix_from_angle(angle, ndim=3, axes=(-1, 0)):
"""Create a shear matrix from an angle.
Parameters
----------
angle : float
Angle in degrees.
ndim : int
Dimensionality of the shear matrix
axes : 2-tuple of int
Location of the angle in the shear matrix.
... | Create a shear matrix from an angle.
Parameters
----------
angle : float
Angle in degrees.
ndim : int
Dimensionality of the shear matrix
axes : 2-tuple of int
Location of the angle in the shear matrix.
Default is the lower left value.
Returns
-------
mat... | shear_matrix_from_angle | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def is_diagonal(matrix, tol=1e-8):
"""Determine whether a matrix is diagonal up to some tolerance.
Parameters
----------
matrix : 2-D array
The matrix to test.
tol : float, optional
Consider any entries with magnitude < `tol` as 0.
Returns
-------
is_diag : bool
... | Determine whether a matrix is diagonal up to some tolerance.
Parameters
----------
matrix : 2-D array
The matrix to test.
tol : float, optional
Consider any entries with magnitude < `tol` as 0.
Returns
-------
is_diag : bool
True if matrix is diagonal, False otherwi... | is_diagonal | python | napari/napari | src/napari/utils/transforms/transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/transform_utils.py | BSD-3-Clause |
def get_units_from_name(units: UnitsLike) -> UnitsInfo:
"""Convert a string or sequence of strings to pint units."""
try:
if isinstance(units, str):
return pint.get_application_registry()[units].units
if isinstance(units, Sequence):
return tuple(
pint.get_... | Convert a string or sequence of strings to pint units. | get_units_from_name | python | napari/napari | src/napari/utils/transforms/_units.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/_units.py | BSD-3-Clause |
def test_repeat_shear_setting():
"""Test repeatedly setting shear with a lower triangular matrix."""
# Note this test is needed to check lower triangular
# decomposition of shear is working
mat = np.eye(3)
mat[2, 0] = 0.5
transform = Affine(shear=mat.copy())
# Check shear decomposed into low... | Test repeatedly setting shear with a lower triangular matrix. | test_repeat_shear_setting | python | napari/napari | src/napari/utils/transforms/_tests/test_transforms.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/_tests/test_transforms.py | BSD-3-Clause |
def test_decompose_linear_matrix(upper_triangular):
"""Test composing and decomposing a linear matrix."""
np.random.seed(0)
# Decompose linear matrix
A = np.random.random((2, 2))
rotate, scale, shear = decompose_linear_matrix(
A, upper_triangular=upper_triangular
)
# Compose linear... | Test composing and decomposing a linear matrix. | test_decompose_linear_matrix | python | napari/napari | src/napari/utils/transforms/_tests/test_transform_utils.py | https://github.com/napari/napari/blob/master/src/napari/utils/transforms/_tests/test_transform_utils.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.