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 set_data(
self,
top_left: tuple[float, float],
bot_right: tuple[float, float],
handles: bool = True,
selected: int | None = None,
rotation: bool = True,
) -> None:
"""Update the visualized interaction box with new data.
Parameters
--------... | Update the visualized interaction box with new data.
Parameters
----------
top_left : tuple[float, float]
The top left corner of the interaction box.
bot_right : tuple[float, float]
The bottom right corner of the interaction box.
handles : bool
... | set_data | python | napari/napari | src/napari/_vispy/visuals/interaction_box.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/visuals/interaction_box.py | BSD-3-Clause |
def _build_color_transform(self) -> FunctionChain:
"""Build the color transform function chain."""
funcs = [
Function(self._func_templates['red_to_luminance']),
Function(self.cmap.glsl_map),
]
return FunctionChain(
funcs=funcs,
) | Build the color transform function chain. | _build_color_transform | python | napari/napari | src/napari/_vispy/visuals/labels.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/visuals/labels.py | BSD-3-Clause |
def test_visibility_consistency(qapp, make_napari_viewer):
"""Make sure toggling visibility maintains image contrast.
see #1622 for details.
"""
viewer = make_napari_viewer(show=True)
layer = viewer.add_image(
np.random.random((200, 200)), contrast_limits=[0, 10]
)
qapp.processEven... | Make sure toggling visibility maintains image contrast.
see #1622 for details.
| test_visibility_consistency | python | napari/napari | src/napari/_vispy/_tests/test_image_rendering.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_image_rendering.py | BSD-3-Clause |
def test_clipping_planes_dims():
"""
Ensure that dims are correctly set on clipping planes
(vispy uses xyz, napary zyx)
"""
clipping_planes = {
'position': (1, 2, 3),
'normal': (1, 2, 3),
}
image_layer = Image(
np.zeros((2, 2, 2)), experimental_clipping_planes=clippin... |
Ensure that dims are correctly set on clipping planes
(vispy uses xyz, napary zyx)
| test_clipping_planes_dims | python | napari/napari | src/napari/_vispy/_tests/test_image_rendering.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_image_rendering.py | BSD-3-Clause |
def test_quaternion2euler_degrees(angles):
"""Test quaternion to euler angle conversion."""
# Test for degrees
q = Quaternion.create_from_euler_angles(*angles, degrees=True)
ea = quaternion2euler_degrees(q)
q_p = Quaternion.create_from_euler_angles(*ea, degrees=True)
# We now compare the corre... | Test quaternion to euler angle conversion. | test_quaternion2euler_degrees | python | napari/napari | src/napari/_vispy/_tests/test_utils.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_utils.py | BSD-3-Clause |
def test_big_2D_image(make_napari_viewer):
"""Test big 2D image with axis exceeding max texture size."""
viewer = make_napari_viewer()
shape = (20_000, 10)
data = np.random.random(shape)
layer = viewer.add_image(data, multiscale=False)
visual = viewer.window._qt_viewer.canvas.layer_to_visual[la... | Test big 2D image with axis exceeding max texture size. | test_big_2D_image | python | napari/napari | src/napari/_vispy/_tests/test_vispy_big_images.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_big_images.py | BSD-3-Clause |
def test_big_3D_image(make_napari_viewer):
"""Test big 3D image with axis exceeding max texture size."""
viewer = make_napari_viewer(ndisplay=3)
shape = (5, 10, 3_000)
data = np.random.random(shape)
layer = viewer.add_image(data, multiscale=False)
visual = viewer.window._qt_viewer.canvas.layer_... | Test big 3D image with axis exceeding max texture size. | test_big_3D_image | python | napari/napari | src/napari/_vispy/_tests/test_vispy_big_images.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_big_images.py | BSD-3-Clause |
def test_downsample_value(make_napari_viewer, shape):
"""Test getting correct value for downsampled data."""
viewer = make_napari_viewer()
data = np.zeros(shape)
data[shape[0] // 2 :, shape[1] // 2 :] = 1
layer = viewer.add_image(data, multiscale=False)
test_points = [
(int(shape[0] * ... | Test getting correct value for downsampled data. | test_downsample_value | python | napari/napari | src/napari/_vispy/_tests/test_vispy_big_images.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_big_images.py | BSD-3-Clause |
def test_data_change_ndisplay_image(make_napari_viewer):
"""Test change data calls for image layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
data = np.random.random((10, 15, 8))
layer = viewer.add_image(data)
visual = viewer.window._qt_viewer.canvas.layer_to_visua... | Test change data calls for image layer with ndisplay change. | test_data_change_ndisplay_image | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_data_change_ndisplay_labels(make_napari_viewer):
"""Test change data calls for labels layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
data = np.random.randint(20, size=(10, 15, 8))
layer = viewer.add_labels(data)
visual = viewer.window._qt_viewer.canvas.... | Test change data calls for labels layer with ndisplay change. | test_data_change_ndisplay_labels | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_data_change_ndisplay_points(make_napari_viewer):
"""Test change data calls for points layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
data = 20 * np.random.random((10, 3))
layer = viewer.add_points(data)
visual = viewer.window._qt_viewer.canvas.layer_to_v... | Test change data calls for points layer with ndisplay change. | test_data_change_ndisplay_points | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_data_change_ndisplay_vectors(make_napari_viewer):
"""Test change data calls for vectors layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
data = 20 * np.random.random((10, 2, 3))
layer = viewer.add_vectors(data)
visual = viewer.window._qt_viewer.canvas.laye... | Test change data calls for vectors layer with ndisplay change. | test_data_change_ndisplay_vectors | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_data_change_ndisplay_shapes(make_napari_viewer):
"""Test change data calls for shapes layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
data = 20 * np.random.random((10, 4, 3))
layer = viewer.add_shapes(data)
visual = viewer.window._qt_viewer.canvas.layer_... | Test change data calls for shapes layer with ndisplay change. | test_data_change_ndisplay_shapes | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_data_change_ndisplay_surface(make_napari_viewer):
"""Test change data calls for surface layer with ndisplay change."""
viewer = make_napari_viewer()
np.random.seed(0)
vertices = np.random.random((10, 3))
faces = np.random.randint(10, size=(6, 3))
values = np.random.random(10)
data ... | Test change data calls for surface layer with ndisplay change. | test_data_change_ndisplay_surface | python | napari/napari | src/napari/_vispy/_tests/test_vispy_calls.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_calls.py | BSD-3-Clause |
def test_vispy_camera_update_from_model(make_napari_viewer):
"""Test vispy camera update from model in 2D."""
viewer = make_napari_viewer()
vispy_camera = viewer.window._qt_viewer.canvas.camera
np.random.seed(0)
data = np.random.random((11, 11, 11))
viewer.add_image(data)
# Test default va... | Test vispy camera update from model in 2D. | test_vispy_camera_update_from_model | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_camera_model_update_from_vispy(make_napari_viewer):
"""Test camera model updates from vispy in 2D."""
viewer = make_napari_viewer()
vispy_camera = viewer.window._qt_viewer.canvas.camera
np.random.seed(0)
data = np.random.random((11, 11, 11))
viewer.add_image(data)
# Test default v... | Test camera model updates from vispy in 2D. | test_camera_model_update_from_vispy | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_vispy_camera_update_from_model_3D(make_napari_viewer):
"""Test vispy camera update from model in 3D."""
viewer = make_napari_viewer()
vispy_camera = viewer.window._qt_viewer.canvas.camera
np.random.seed(0)
data = np.random.random((11, 11, 11))
viewer.add_image(data)
viewer.dims.nd... | Test vispy camera update from model in 3D. | test_vispy_camera_update_from_model_3D | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_camera_model_update_from_vispy_3D(make_napari_viewer):
"""Test camera model updates from vispy in 3D."""
viewer = make_napari_viewer()
vispy_camera = viewer.window._qt_viewer.canvas.camera
np.random.seed(0)
data = np.random.random((11, 11, 11))
viewer.add_image(data)
viewer.dims.n... | Test camera model updates from vispy in 3D. | test_camera_model_update_from_vispy_3D | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_switching_ndisplay_maintains_3D_angles(make_napari_viewer):
"""Test that switching dims.ndisplay maintains 3D angles."""
viewer = make_napari_viewer()
vispy_camera = viewer.window._qt_viewer.canvas.camera
np.random.seed(0)
data = np.random.random((11, 11, 11))
viewer.add_image(data)
... | Test that switching dims.ndisplay maintains 3D angles. | test_switching_ndisplay_maintains_3D_angles | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_camera_orientation_2d(make_napari_viewer, qtbot):
"""Test that flipping orientation of the camera flips displayed image."""
viewer = make_napari_viewer(show=True)
data = np.arange(16).reshape((4, 4))
_ = viewer.add_image(data, interpolation2d='linear')
# in the default axis orientation of ... | Test that flipping orientation of the camera flips displayed image. | test_camera_orientation_2d | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_camera_orientation_3d(make_napari_viewer, qtbot):
"""Test that flipping camera orientation in 3D flips volume as expected."""
viewer = make_napari_viewer(show=True)
viewer.dims.ndisplay = 3
gradient_z = np.arange(16).reshape((16, 1, 1))
image = np.ones((16, 16))
image_3d = gradient_z * ... | Test that flipping camera orientation in 3D flips volume as expected. | test_camera_orientation_3d | python | napari/napari | src/napari/_vispy/_tests/test_vispy_camera.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_camera.py | BSD-3-Clause |
def test_3d_slice_of_2d_image_with_order(order):
"""See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small square when displayed in 3D.
"""
image = Image(np.zeros((4, 2)), scale=(1, 2))
vispy_image = V... | See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small square when displayed in 3D.
| test_3d_slice_of_2d_image_with_order | python | napari/napari | src/napari/_vispy/_tests/test_vispy_image_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_image_layer.py | BSD-3-Clause |
def test_2d_slice_of_3d_image_with_order(order):
"""See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small square when displayed in 2D.
"""
image = Image(np.zeros((8, 4, 2)), scale=(1, 2, 4))
vispy_ima... | See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small square when displayed in 2D.
| test_2d_slice_of_3d_image_with_order | python | napari/napari | src/napari/_vispy/_tests/test_vispy_image_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_image_layer.py | BSD-3-Clause |
def test_3d_slice_of_3d_image_with_order(order):
"""See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small cube when displayed in 3D.
"""
image = Image(np.zeros((8, 4, 2)), scale=(1, 2, 4))
vispy_image... | See https://github.com/napari/napari/issues/4926
We define a non-isotropic shape and scale that combined properly
with any order should make a small cube when displayed in 3D.
| test_3d_slice_of_3d_image_with_order | python | napari/napari | src/napari/_vispy/_tests/test_vispy_image_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_image_layer.py | BSD-3-Clause |
def test_no_float32_texture_support(monkeypatch):
"""Ensure Image node can be created if OpenGL driver lacks float textures.
See #3988, #3990, #6652.
"""
monkeypatch.setattr(
'napari._vispy.layers.image.get_gl_extensions', lambda: ''
)
image = Image(np.zeros((16, 8, 4, 2), dtype='uint8'... | Ensure Image node can be created if OpenGL driver lacks float textures.
See #3988, #3990, #6652.
| test_no_float32_texture_support | python | napari/napari | src/napari/_vispy/_tests/test_vispy_image_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_image_layer.py | BSD-3-Clause |
def test_node_origin_is_consistent_with_multiscale(
scale: int, ndim: int, ndisplay: int
):
"""See https://github.com/napari/napari/issues/6320"""
scales = (scale,) * ndim
# Define multi-scale image data with two levels where the
# higher resolution is twice as high as the lower resolution.
ima... | See https://github.com/napari/napari/issues/6320 | test_node_origin_is_consistent_with_multiscale | python | napari/napari | src/napari/_vispy/_tests/test_vispy_image_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_image_layer.py | BSD-3-Clause |
def make_labels_layer(array_type, shape):
"""Make a labels layer, either NumPy, zarr, or tensorstore."""
chunks = tuple(s // 2 for s in shape)
if array_type == 'numpy':
labels = np.zeros(shape, dtype=np.uint32)
elif array_type == 'zarr':
labels = zarr.zeros(shape=shape, dtype=np.uint32, ... | Make a labels layer, either NumPy, zarr, or tensorstore. | make_labels_layer | python | napari/napari | src/napari/_vispy/_tests/test_vispy_labels_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_labels_layer.py | BSD-3-Clause |
def test_labels_painting(qtbot, array_type, qt_viewer):
"""Check that painting labels paints on the canvas.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
"""
viewer = qt_viewer.viewer
labels = make_labels_layer(array_type, shape=(20, 20))
layer... | Check that painting labels paints on the canvas.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
| test_labels_painting | python | napari/napari | src/napari/_vispy/_tests/test_vispy_labels_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_labels_layer.py | BSD-3-Clause |
def test_labels_fill_slice(qtbot, array_type, qt_viewer):
"""Check that painting labels paints only on current slice.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
"""
labels = make_labels_layer(array_type, shape=(3, 20, 20))
labels[0, :, :] = 1
... | Check that painting labels paints only on current slice.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
| test_labels_fill_slice | python | napari/napari | src/napari/_vispy/_tests/test_vispy_labels_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_labels_layer.py | BSD-3-Clause |
def test_labels_painting_with_mouse(MouseEvent, qtbot, array_type, qt_viewer):
"""Check that painting labels paints on the canvas when using mouse.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
"""
labels = make_labels_layer(array_type, shape=(20, 20))... | Check that painting labels paints on the canvas when using mouse.
This should work regardless of array type. See:
https://github.com/napari/napari/issues/6079
| test_labels_painting_with_mouse | python | napari/napari | src/napari/_vispy/_tests/test_vispy_labels_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_labels_layer.py | BSD-3-Clause |
def test_labels_iso_gradient_modes(qtbot, qt_viewer):
"""Check that we can set `iso_gradient_mode` with `iso_categorical` rendering (test shader)."""
# NOTE: this test currently segfaults on Windows CI, but confirmed working locally
# because it's a segfault, we have to skip instead of xfail
qt_viewer.s... | Check that we can set `iso_gradient_mode` with `iso_categorical` rendering (test shader). | test_labels_iso_gradient_modes | python | napari/napari | src/napari/_vispy/_tests/test_vispy_labels_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_labels_layer.py | BSD-3-Clause |
def test_3D_multiscale_image(make_napari_viewer):
"""Test rendering of 3D multiscale image uses lowest resolution."""
viewer = make_napari_viewer()
data = [np.random.random((128,) * 3), np.random.random((64,) * 3)]
viewer.add_image(data)
# Check that this doesn't crash.
viewer.dims.ndisplay = ... | Test rendering of 3D multiscale image uses lowest resolution. | test_3D_multiscale_image | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_multiscale_screenshot(make_napari_viewer):
"""Test rendering of multiscale data with screenshot."""
viewer = make_napari_viewer(show=True)
shapes = [(4000, 3000), (2000, 1500), (1000, 750), (500, 375)]
data = [np.ones(s) for s in shapes]
_ = viewer.add_image(data, multiscale=True, contrast... | Test rendering of multiscale data with screenshot. | test_multiscale_screenshot | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_multiscale_screenshot_zoomed(make_napari_viewer):
"""Test rendering of multiscale data with screenshot after zoom."""
viewer = make_napari_viewer(show=True)
view = viewer.window._qt_viewer
shapes = [(4000, 3000), (2000, 1500), (1000, 750), (500, 375)]
data = [np.ones(s) for s in shapes]
... | Test rendering of multiscale data with screenshot after zoom. | test_multiscale_screenshot_zoomed | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_image_screenshot_zoomed(make_napari_viewer):
"""Test rendering of image data with screenshot after zoom."""
viewer = make_napari_viewer(show=True)
view = viewer.window._qt_viewer
data = np.ones((4000, 3000))
_ = viewer.add_image(data, multiscale=False, contrast_limits=[0, 1])
# Set ca... | Test rendering of image data with screenshot after zoom. | test_image_screenshot_zoomed | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_multiscale_zoomed_out(make_napari_viewer):
"""See https://github.com/napari/napari/issues/4781"""
# Need to show viewer to ensure that pixel_scale and physical_size
# get set appropriately.
viewer = make_napari_viewer(show=True)
shapes = [(3200, 3200), (1600, 1600), (800, 800)]
data = [... | See https://github.com/napari/napari/issues/4781 | test_multiscale_zoomed_out | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_multiscale_flipped_axes(make_napari_viewer):
"""Check rendering of multiscale images with negative scale values.
See https://github.com/napari/napari/issues/3057
"""
viewer = make_napari_viewer(show=True)
shapes = [(4000, 3000), (2000, 1500), (1000, 750), (500, 375)]
data = [np.ones(s... | Check rendering of multiscale images with negative scale values.
See https://github.com/napari/napari/issues/3057
| test_multiscale_flipped_axes | python | napari/napari | src/napari/_vispy/_tests/test_vispy_multiscale.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_multiscale.py | BSD-3-Clause |
def test_remove_selected_with_derived_text():
"""See https://github.com/napari/napari/issues/3504"""
points = np.random.rand(3, 2)
properties = {'class': np.array(['A', 'B', 'C'])}
layer = Points(points, text='class', properties=properties)
vispy_layer = VispyPointsLayer(layer)
text_node = vispy... | See https://github.com/napari/napari/issues/3504 | test_remove_selected_with_derived_text | python | napari/napari | src/napari/_vispy/_tests/test_vispy_points_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_points_layer.py | BSD-3-Clause |
def test_change_antialiasing():
"""Changing antialiasing on the layer should change it on the vispy node."""
points = np.random.rand(3, 2)
layer = Points(points)
vispy_layer = VispyPointsLayer(layer)
layer.antialiasing = 5
assert vispy_layer.node.antialias == layer.antialiasing | Changing antialiasing on the layer should change it on the vispy node. | test_change_antialiasing | python | napari/napari | src/napari/_vispy/_tests/test_vispy_points_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_points_layer.py | BSD-3-Clause |
def test_tracks_graph_cleanup():
"""
Test if graph data can be cleaned up without any issue.
There was problems with the shader buffer once, see issue #4155.
"""
tracks_data = [
[1, 0, 236, 0],
[1, 1, 236, 100],
[1, 2, 236, 200],
[2, 3, 436, 500],
[2, 4, 436, ... |
Test if graph data can be cleaned up without any issue.
There was problems with the shader buffer once, see issue #4155.
| test_tracks_graph_cleanup | python | napari/napari | src/napari/_vispy/_tests/test_vispy_tracks_layer.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/test_vispy_tracks_layer.py | BSD-3-Clause |
def vispy_image_scene_size(vispy_image: VispyImageLayer) -> np.ndarray:
"""Calculates the size of a vispy image/volume in 3D space.
The size is the shape of the node's data multiplied by the
node's transform scale factors.
Returns
-------
np.ndarray
The size of the node as a 3-vector o... | Calculates the size of a vispy image/volume in 3D space.
The size is the shape of the node's data multiplied by the
node's transform scale factors.
Returns
-------
np.ndarray
The size of the node as a 3-vector of the form (x, y, z).
| vispy_image_scene_size | python | napari/napari | src/napari/_vispy/_tests/utils.py | https://github.com/napari/napari/blob/master/src/napari/_vispy/_tests/utils.py | BSD-3-Clause |
def imread(filename: str) -> np.ndarray:
"""Dispatch reading images to imageio.v3 imread.
Parameters
----------
filename : string
The path or URI from which to read the image.
Returns
-------
data : np.ndarray
The image data.
"""
filename = abspath_or_url(filename)
... | Dispatch reading images to imageio.v3 imread.
Parameters
----------
filename : string
The path or URI from which to read the image.
Returns
-------
data : np.ndarray
The image data.
| imread | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def read_zarr_dataset(path: str):
"""Read a zarr dataset, including an array or a group of arrays.
Parameters
----------
path : str
Path to directory ending in '.zarr'. Path can contain either an array
or a group of arrays in the case of multiscale data.
Returns
-------
ima... | Read a zarr dataset, including an array or a group of arrays.
Parameters
----------
path : str
Path to directory ending in '.zarr'. Path can contain either an array
or a group of arrays in the case of multiscale data.
Returns
-------
image : array-like
Array or list of ... | read_zarr_dataset | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def magic_imread(
filenames: PathOrStr | list[PathOrStr], *, use_dask=None, stack=True
):
"""Dispatch the appropriate reader given some files.
The files are assumed to all have the same shape.
Parameters
----------
filenames : list
List of filenames or directories to be opened.
... | Dispatch the appropriate reader given some files.
The files are assumed to all have the same shape.
Parameters
----------
filenames : list
List of filenames or directories to be opened.
A list of `pathlib.Path` objects and a single filename or `Path` object
are also accepted.
... | magic_imread | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def _points_csv_to_layerdata(
table: np.ndarray, column_names: list[str]
) -> 'FullLayerData':
"""Convert table data and column names from a csv file to Points LayerData.
Parameters
----------
table : np.ndarray
CSV data.
column_names : list of str
The column names of the csv fi... | Convert table data and column names from a csv file to Points LayerData.
Parameters
----------
table : np.ndarray
CSV data.
column_names : list of str
The column names of the csv file
Returns
-------
layer_data : tuple
3-tuple ``(array, dict, str)`` (points data, me... | _points_csv_to_layerdata | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def _shapes_csv_to_layerdata(
table: np.ndarray, column_names: list[str]
) -> 'FullLayerData':
"""Convert table data and column names from a csv file to Shapes LayerData.
Parameters
----------
table : np.ndarray
CSV data.
column_names : list of str
The column names of the csv fi... | Convert table data and column names from a csv file to Shapes LayerData.
Parameters
----------
table : np.ndarray
CSV data.
column_names : list of str
The column names of the csv file
Returns
-------
layer_data : tuple
3-tuple ``(array, dict, str)`` (points data, me... | _shapes_csv_to_layerdata | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def _guess_layer_type_from_column_names(
column_names: list[str],
) -> str | None:
"""Guess layer type based on column names from a csv file.
Parameters
----------
column_names : list of str
List of the column names from the csv.
Returns
-------
str or None
Layer type i... | Guess layer type based on column names from a csv file.
Parameters
----------
column_names : list of str
List of the column names from the csv.
Returns
-------
str or None
Layer type if recognized, otherwise None.
| _guess_layer_type_from_column_names | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def read_csv(
filename: str, require_type: str | None = None
) -> tuple[np.ndarray, list[str], str | None]:
"""Return CSV data only if column names match format for ``require_type``.
Reads only the first line of the CSV at first, then optionally raises an
exception if the column names are not consisten... | Return CSV data only if column names match format for ``require_type``.
Reads only the first line of the CSV at first, then optionally raises an
exception if the column names are not consistent with a known format, as
determined by the ``require_type`` argument and
:func:`_guess_layer_type_from_column_... | read_csv | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def csv_to_layer_data(
path: str, require_type: str | None = None
) -> Optional['FullLayerData']:
"""Return layer data from a CSV file if detected as a valid type.
Parameters
----------
path : str
Path of file to open
require_type : str, optional
The desired layer type. If provi... | Return layer data from a CSV file if detected as a valid type.
Parameters
----------
path : str
Path of file to open
require_type : str, optional
The desired layer type. If provided, should be one of the keys in
``csv_reader_functions`` or the string "any". If ``None``,
... | csv_to_layer_data | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def napari_get_reader(
path: str | list[str],
) -> 'ReaderFunction':
"""Our internal fallback file reader at the end of the reader plugin chain.
This will assume that the filepath is an image, and will pass all of the
necessary information to viewer.add_image().
Parameters
----------
path ... | Our internal fallback file reader at the end of the reader plugin chain.
This will assume that the filepath is an image, and will pass all of the
necessary information to viewer.add_image().
Parameters
----------
path : str
path to file/directory
Returns
-------
callable
... | napari_get_reader | python | napari/napari | src/napari_builtins/io/_read.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_read.py | BSD-3-Clause |
def write_csv(
filename: str,
data: list | np.ndarray,
column_names: list[str] | None = None,
):
"""Write a csv file.
Parameters
----------
filename : str
Filename for saving csv.
data : list or ndarray
Table values, contained in a list of lists or an ndarray.
column... | Write a csv file.
Parameters
----------
filename : str
Filename for saving csv.
data : list or ndarray
Table values, contained in a list of lists or an ndarray.
column_names : list, optional
List of column names for table data.
| write_csv | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def imsave_extensions() -> tuple[str, ...]:
"""Valid extensions of files that imsave can write to.
Returns
-------
tuple
Valid extensions of files that imsave can write to.
"""
# import imageio
# return tuple(set(x for f in imageio.formats for x in f.extensions))
# The above me... | Valid extensions of files that imsave can write to.
Returns
-------
tuple
Valid extensions of files that imsave can write to.
| imsave_extensions | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def napari_write_image(path: str, data: Any, meta: dict) -> str | None:
"""Our internal fallback image writer at the end of the plugin chain.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : array or list of array
Image data. Can be N dimens... | Our internal fallback image writer at the end of the plugin chain.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : array or list of array
Image data. Can be N dimensional. If meta['rgb'] is ``True`` then the
data should be interpreted a... | napari_write_image | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def napari_write_labels(path: str, data: Any, meta: dict) -> str | None:
"""Our internal fallback labels writer at the end of the plugin chain.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : array or list of array
Image data. Can be N dime... | Our internal fallback labels writer at the end of the plugin chain.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : array or list of array
Image data. Can be N dimensional. If meta['rgb'] is ``True`` then the
data should be interpreted ... | napari_write_labels | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def napari_write_points(path: str, data: Any, meta: dict) -> str | None:
"""Our internal fallback points writer at the end of the plugin chain.
Append ``.csv`` extension to the filename if it is not already there.
Parameters
----------
path : str
Path to file, directory, or resource (like ... | Our internal fallback points writer at the end of the plugin chain.
Append ``.csv`` extension to the filename if it is not already there.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : array (N, D)
Coordinates for N points in D dimensions... | napari_write_points | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def napari_write_shapes(path: str, data: Any, meta: dict) -> str | None:
"""Our internal fallback points writer at the end of the plugin chain.
Append ``.csv`` extension to the filename if it is not already there.
Parameters
----------
path : str
Path to file, directory, or resource (like ... | Our internal fallback points writer at the end of the plugin chain.
Append ``.csv`` extension to the filename if it is not already there.
Parameters
----------
path : str
Path to file, directory, or resource (like a URL).
data : list of array (N, D)
List of coordinates for shapes, ... | napari_write_shapes | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def write_layer_data_with_plugins(
path: str, layer_data: list['FullLayerData']
) -> list[str]:
"""Write layer data out into a folder one layer at a time.
Call ``napari_write_<layer>`` for each layer using the ``layer.name``
variable to modify the path such that the layers are written to unique
fil... | Write layer data out into a folder one layer at a time.
Call ``napari_write_<layer>`` for each layer using the ``layer.name``
variable to modify the path such that the layers are written to unique
files in the folder.
Parameters
----------
path : str
path to file/directory
layer_da... | write_layer_data_with_plugins | python | napari/napari | src/napari_builtins/io/_write.py | https://github.com/napari/napari/blob/master/src/napari_builtins/io/_write.py | BSD-3-Clause |
def mock_npe2_pm():
"""Mock plugin manager with no registered plugins."""
with patch.object(PluginManager, 'discover'):
_pm = PluginManager()
with patch('npe2.PluginManager.instance', return_value=_pm):
yield _pm | Mock plugin manager with no registered plugins. | mock_npe2_pm | python | napari/napari | src/napari_builtins/_tests/conftest.py | https://github.com/napari/napari/blob/master/src/napari_builtins/_tests/conftest.py | BSD-3-Clause |
def test_read_csv_raises(tmp_path):
"""Test various exception raising circumstances with read_csv."""
temp = tmp_path / 'points.csv'
# test that points data is detected with require_type = None, any, points
# but raises for other shape types.
data = [['index', 'axis-0', 'axis-1']]
data.extend(n... | Test various exception raising circumstances with read_csv. | test_read_csv_raises | python | napari/napari | src/napari_builtins/_tests/test_io.py | https://github.com/napari/napari/blob/master/src/napari_builtins/_tests/test_io.py | BSD-3-Clause |
def test_csv_to_layer_data_raises(tmp_path):
"""Test various exception raising circumstances with csv_to_layer_data."""
temp = tmp_path / 'points.csv'
# test that points data is detected with require_type == points, any, None
# but raises for other shape types.
data = [['index', 'axis-0', 'axis-1']... | Test various exception raising circumstances with csv_to_layer_data. | test_csv_to_layer_data_raises | python | napari/napari | src/napari_builtins/_tests/test_io.py | https://github.com/napari/napari/blob/master/src/napari_builtins/_tests/test_io.py | BSD-3-Clause |
def test_reader_plugin_tif(save_image: Callable[..., Path], ext, stack):
"""Test the builtin reader plugin reads a temporary file."""
files = [
str(save_image(f'test_{i}{ext}')) for i in range(5 if stack else 1)
]
layer_data = npe2.read(files, stack=stack)
assert isinstance(layer_data, list)... | Test the builtin reader plugin reads a temporary file. | test_reader_plugin_tif | python | napari/napari | src/napari_builtins/_tests/test_reader.py | https://github.com/napari/napari/blob/master/src/napari_builtins/_tests/test_reader.py | BSD-3-Clause |
def test_no_write_layer_bad_extension(some_layer: 'layers.Layer'):
"""Test not writing layer data with a bad extension."""
with pytest.warns(UserWarning, match='No data written!'):
assert not some_layer.save('layer.bad_extension') | Test not writing layer data with a bad extension. | test_no_write_layer_bad_extension | python | napari/napari | src/napari_builtins/_tests/test_writer.py | https://github.com/napari/napari/blob/master/src/napari_builtins/_tests/test_writer.py | BSD-3-Clause |
def parse_min_python_version(requires_python: str):
"""
Extracts the minimal Python version from a requires-python string (e.g. ">=3.10").
Assumes a specifier like ">=X.Y" is present.
"""
m = re.search(r'>=\s*([\d\.]+)', requires_python)
if m:
ver_str = m.group(1)
try:
... |
Extracts the minimal Python version from a requires-python string (e.g. ">=3.10").
Assumes a specifier like ">=X.Y" is present.
| parse_min_python_version | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def get_specified_min_version(specifier: SpecifierSet) -> Version:
"""
Returns the effective minimal version from a dependency's specifier set.
This is the maximum among all lower-bound constraints (">=" or "==").
"""
lower_bounds = []
for spec in specifier:
if spec.operator in ('>=', '=... |
Returns the effective minimal version from a dependency's specifier set.
This is the maximum among all lower-bound constraints (">=" or "==").
| get_specified_min_version | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def has_compatible_wheel(files, required_py_ver: Version) -> bool:
"""
Returns True if any wheel file in the given list is compatible with the required Python version.
"""
for file_info in files:
if file_info.get('packagetype') == 'bdist_wheel':
fname = file_info.get('filename')
... |
Returns True if any wheel file in the given list is compatible with the required Python version.
| has_compatible_wheel | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def check_version_for_compatible_wheel(
pkg_name: str, version: Version, required_py_ver: Version
) -> bool:
"""
Checks whether the given version of a package provides a wheel compatible with the required Python version.
"""
url = f'https://pypi.org/pypi/{pkg_name}/{version}/json'
resp = request... |
Checks whether the given version of a package provides a wheel compatible with the required Python version.
| check_version_for_compatible_wheel | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def find_lowest_version_with_compatible_wheel(
pkg_name: str,
spec: SpecifierSet,
pypi_data: dict,
required_py_ver: Version,
current_min: Version,
):
"""
Among all candidate versions (satisfying the specifier and greater than current_min),
returns the lowest version that provides a compa... |
Among all candidate versions (satisfying the specifier and greater than current_min),
returns the lowest version that provides a compatible wheel for the required Python version.
Returns None if none found.
| find_lowest_version_with_compatible_wheel | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def process_dependency(dep_str: str, required_py_ver: Version, origin: str):
"""
Processes a single dependency string (from main dependencies or extras):
- Determines the specified minimal version.
- Checks if that version provides a compatible wheel for the required Python version.
- If not, ... |
Processes a single dependency string (from main dependencies or extras):
- Determines the specified minimal version.
- Checks if that version provides a compatible wheel for the required Python version.
- If not, searches for the lowest version above the specified minimal version that does.
R... | process_dependency | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def process_all_dependencies(
dependencies, required_py_ver: Version, origin: str
):
"""
Processes a list of dependency strings (from either main dependencies or extras)
and returns a list of issue reports.
"""
issues = []
for dep in dependencies:
result = process_dependency(dep, req... |
Processes a list of dependency strings (from either main dependencies or extras)
and returns a list of issue reports.
| process_all_dependencies | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def process_extras(extras: dict, required_py_ver: Version):
"""
Processes extra dependencies (grouped by extra name) and returns a list of issues.
"""
issues = []
for extra_name, dep_list in extras.items():
print(f'\n--- Processing extra: {extra_name} ---')
issues.extend(
... |
Processes extra dependencies (grouped by extra name) and returns a list of issues.
| process_extras | python | napari/napari | tools/check_deps_version.py | https://github.com/napari/napari/blob/master/tools/check_deps_version.py | BSD-3-Clause |
def get_branches() -> list[str]:
"""
Get all branches from the repository.
"""
out = subprocess.run( # nosec
['git', 'branch', '--list', '--format', '%(refname:short)', '-a'],
capture_output=True,
check=True,
)
return out.stdout.decode().split('\n') |
Get all branches from the repository.
| get_branches | python | napari/napari | tools/check_updated_packages.py | https://github.com/napari/napari/blob/master/tools/check_updated_packages.py | BSD-3-Clause |
def calc_changed_packages(
base_branch: str, src_dir: Path, python_version: str
) -> list[str]:
"""
Calculate a list of changed packages based on python_version
Parameters
----------
base_branch: str
branch against which to compare
src_dir: Path
path to the root of the repos... |
Calculate a list of changed packages based on python_version
Parameters
----------
base_branch: str
branch against which to compare
src_dir: Path
path to the root of the repository
python_version: str
python version to use
Returns
-------
list[str]
... | calc_changed_packages | python | napari/napari | tools/check_updated_packages.py | https://github.com/napari/napari/blob/master/tools/check_updated_packages.py | BSD-3-Clause |
def get_ref_name() -> str:
"""
Get the name of the current branch.
"""
ref_name = os.environ.get('GITHUB_REF_NAME')
if ref_name:
return ref_name
out = subprocess.run( # nosec
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
capture_output=True,
check=True,
)
... |
Get the name of the current branch.
| get_ref_name | python | napari/napari | tools/check_updated_packages.py | https://github.com/napari/napari/blob/master/tools/check_updated_packages.py | BSD-3-Clause |
def get_changed_dependencies(
base_branch: str,
all_packages=False,
python_version='3.10',
src_dir: Path | None = None,
):
"""
Get the changed dependencies.
all_packages: bool
If True, return all packages, not just the direct dependencies.
"""
if src_dir is None:
src... |
Get the changed dependencies.
all_packages: bool
If True, return all packages, not just the direct dependencies.
| get_changed_dependencies | python | napari/napari | tools/check_updated_packages.py | https://github.com/napari/napari/blob/master/tools/check_updated_packages.py | BSD-3-Clause |
def check_vendored_module(org: str, reponame: str, tag: str) -> str:
"""
Check if the vendored module is up to date.
Parameters
----------
org : str
The github organization name.
reponame : str
The github repository name.
tag : str
The github tag.
Returns
--... |
Check if the vendored module is up to date.
Parameters
----------
org : str
The github organization name.
reponame : str
The github repository name.
tag : str
The github tag.
Returns
-------
str
Returns the diff if the module is not up to date or an... | check_vendored_module | python | napari/napari | tools/check_vendored_modules.py | https://github.com/napari/napari/blob/master/tools/check_vendored_modules.py | BSD-3-Clause |
def cd(path: Path):
"""
Change directory to the given path and return to the previous one afterwards.
"""
current_dir = getcwd()
try:
chdir(path)
yield
finally:
chdir(current_dir) |
Change directory to the given path and return to the previous one afterwards.
| cd | python | napari/napari | tools/create_pr_or_update_existing_one.py | https://github.com/napari/napari/blob/master/tools/create_pr_or_update_existing_one.py | BSD-3-Clause |
def push(branch_name: str, update: bool = False):
"""
Push the current branch to the remote.
"""
try:
with cd(REPO_DIR):
logging.info('go to dir %s', REPO_DIR)
if update:
logging.info('Pushing to %s', branch_name)
subprocess.run(
... |
Push the current branch to the remote.
| push | python | napari/napari | tools/create_pr_or_update_existing_one.py | https://github.com/napari/napari/blob/master/tools/create_pr_or_update_existing_one.py | BSD-3-Clause |
def list_pr_for_branch(branch_name: str, access_token: str, repo=''):
"""
check if PR for branch exists
"""
org_name = repo.split('/')[0]
url = f'{BASE_URL}/repos/{repo}/pulls?state=open&head={org_name}:{branch_name}'
response = requests.get(url)
response.raise_for_status()
if response.j... |
check if PR for branch exists
| list_pr_for_branch | python | napari/napari | tools/create_pr_or_update_existing_one.py | https://github.com/napari/napari/blob/master/tools/create_pr_or_update_existing_one.py | BSD-3-Clause |
def add_comment_to_pr(
pull_request_number: int,
message: str,
repo='napari/napari',
):
"""
Add a comment to an existing PR.
"""
# Prepare the headers with the access token
headers = {'Authorization': f'token {os.environ.get("GITHUB_TOKEN")}'}
# publish the comment
payload = {'b... |
Add a comment to an existing PR.
| add_comment_to_pr | python | napari/napari | tools/create_pr_or_update_existing_one.py | https://github.com/napari/napari/blob/master/tools/create_pr_or_update_existing_one.py | BSD-3-Clause |
def get_pr_number() -> int:
"""
Get the PR number from the environment based on the PR_NUMBER variable.
Returns
-------
pr number: int
"""
pr_number = environ.get('PR_NUMBER')
logging.info('PR_NUMBER: %s', pr_number)
return int(pr_number) |
Get the PR number from the environment based on the PR_NUMBER variable.
Returns
-------
pr number: int
| get_pr_number | python | napari/napari | tools/create_pr_or_update_existing_one.py | https://github.com/napari/napari/blob/master/tools/create_pr_or_update_existing_one.py | BSD-3-Clause |
def _check_vars(self, method_name, args, kwargs):
"""Find interpolation variables inside a translation string.
This helps find any variables that need to be interpolated inside
a string so we can check against the `kwargs` for both singular
and plural strings (if present) inside `args`.... | Find interpolation variables inside a translation string.
This helps find any variables that need to be interpolated inside
a string so we can check against the `kwargs` for both singular
and plural strings (if present) inside `args`.
Parameters
----------
method_name :... | _check_vars | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def reset(self):
"""Reset variables storing found strings and translation errors."""
self._found = set()
self._trans_errors = [] | Reset variables storing found strings and translation errors. | reset | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def _find_func_definitions(
node: ast.AST, defs: list[ast.FunctionDef] | None = None
) -> list[ast.FunctionDef]:
"""Find all functions definition recrusively.
This also find functions nested inside other functions.
Parameters
----------
node : ast.Node
The initial node of the ast.
... | Find all functions definition recrusively.
This also find functions nested inside other functions.
Parameters
----------
node : ast.Node
The initial node of the ast.
defs : list of ast.FunctionDef
A list of function definitions to accumulate.
Returns
-------
list of as... | _find_func_definitions | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def find_files(
path: str,
skip_folders: tuple,
skip_files: tuple,
extensions: tuple = ('.py',),
) -> list[str]:
"""Find recursively all files in path.
Parameters
----------
path : str
Path to a folder to find files in.
skip_folders : tuple
Skip folders containing fo... | Find recursively all files in path.
Parameters
----------
path : str
Path to a folder to find files in.
skip_folders : tuple
Skip folders containing folder to skip
skip_files : tuple
Skip files.
extensions : tuple, optional
Extensions to filter by. Default is (".... | find_files | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def find_docstrings(fpath: str) -> dict[str, str]:
"""Find all docstrings in file path.
Parameters
----------
fpath : str
File path.
Returns
-------
dict
Simplified string as keys and the value is the original docstring
found.
"""
with open(fpath) as fh:
... | Find all docstrings in file path.
Parameters
----------
fpath : str
File path.
Returns
-------
dict
Simplified string as keys and the value is the original docstring
found.
| find_docstrings | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def compress_str(gen):
"""
This function takes a stream of token and tries to join
consecutive strings.
This is usefull for long translation string to be broken across
many lines.
This should support both joined strings without backslashes:
trans._(
"this"
"wil... |
This function takes a stream of token and tries to join
consecutive strings.
This is usefull for long translation string to be broken across
many lines.
This should support both joined strings without backslashes:
trans._(
"this"
"will"
"work"
... | compress_str | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def find_strings(fpath: str) -> dict[tuple[int, str], tuple[int, str]]:
"""Find all strings (and f-strings) for the given file.
Parameters
----------
fpath : str
File path.
Returns
-------
dict
A dict with a tuple for key and a tuple for value. The tuple contains
th... | Find all strings (and f-strings) for the given file.
Parameters
----------
fpath : str
File path.
Returns
-------
dict
A dict with a tuple for key and a tuple for value. The tuple contains
the line number and the stripped string. The value containes the line
num... | find_strings | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def find_trans_strings(
fpath: str,
) -> tuple[dict[str, str], list[tuple[str, set[str]]]]:
"""Find all translation strings for the given file.
Parameters
----------
fpath : str
File path.
Returns
-------
tuple
The first item is a dict with a stripped string as key and ... | Find all translation strings for the given file.
Parameters
----------
fpath : str
File path.
Returns
-------
tuple
The first item is a dict with a stripped string as key and the
orginal string for value. The second item is a list of tuples that
includes errors ... | find_trans_strings | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def import_module_by_path(fpath: str) -> ModuleType | None:
"""Import a module given py a path.
Parameters
----------
fpath : str
The path to the file to import as module.
Returns
-------
ModuleType or None
The imported module or `None`.
"""
import importlib.util
... | Import a module given py a path.
Parameters
----------
fpath : str
The path to the file to import as module.
Returns
-------
ModuleType or None
The imported module or `None`.
| import_module_by_path | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def find_issues(
paths: list[str], skip_words: list[str]
) -> tuple[StringIssuesDict, OutdatedStringsDict, TranslationErrorsDict]:
"""Find strings that have not been translated, and errors in translations.
This will not raise errors but return a list with found issues wo they
can be fixed at once.
... | Find strings that have not been translated, and errors in translations.
This will not raise errors but return a list with found issues wo they
can be fixed at once.
Parameters
----------
paths : list of str
List of paths to files to check.
skip_words : list of str
List of words... | find_issues | python | napari/napari | tools/validate_strings.py | https://github.com/napari/napari/blob/master/tools/validate_strings.py | BSD-3-Clause |
def run(
seed: int = 543,
data_path: str = "/tmp/cifar10",
output_path: str = "/tmp/output-cifar10/",
model: str = "resnet18",
batch_size: int = 512,
momentum: float = 0.9,
weight_decay: float = 1e-4,
num_workers: int = 12,
num_epochs: int = 24,
learning_rate: float = 0.4,
nu... | Main entry to train an model on CIFAR10 dataset.
Args:
seed (int): random state seed to set. Default, 543.
data_path (str): input dataset path. Default, "/tmp/cifar10".
output_path (str): output path. Default, "/tmp/output-cifar10".
model (str): model name (from torchvision) to setu... | run | python | pytorch/ignite | examples/cifar10/main.py | https://github.com/pytorch/ignite/blob/master/examples/cifar10/main.py | BSD-3-Clause |
def get_train_eval_loaders(path, batch_size=256):
"""Setup the dataflow:
- load CIFAR100 train and test datasets
- setup train/test image transforms
- horizontally flipped randomly and augmented using cutout.
- each mini-batch contained 256 examples
- setup train/test... | Setup the dataflow:
- load CIFAR100 train and test datasets
- setup train/test image transforms
- horizontally flipped randomly and augmented using cutout.
- each mini-batch contained 256 examples
- setup train/test data loaders
Returns:
train_loader, test_lo... | get_train_eval_loaders | python | pytorch/ignite | examples/cifar100_amp_benchmark/utils.py | https://github.com/pytorch/ignite/blob/master/examples/cifar100_amp_benchmark/utils.py | BSD-3-Clause |
def run(
seed=543,
data_path="/tmp/cifar10",
output_path="/tmp/output-cifar10/",
model="resnet18_QAT_8b",
batch_size=512,
momentum=0.9,
weight_decay=1e-4,
num_workers=12,
num_epochs=24,
learning_rate=0.4,
num_warmup_epochs=4,
validate_every=3,
checkpoint_every=1000,
... | Main entry to train an model on CIFAR10 dataset.
Args:
seed (int): random state seed to set. Default, 543.
data_path (str): input dataset path. Default, "/tmp/cifar10".
output_path (str): output path. Default, "/tmp/output-cifar10".
model (str): model name (from torchvision) to setu... | run | python | pytorch/ignite | examples/cifar10_qat/main.py | https://github.com/pytorch/ignite/blob/master/examples/cifar10_qat/main.py | BSD-3-Clause |
def check_manual_seed(seed):
"""If manual seed is not specified, choose a random one and communicate it to the user."""
seed = seed or random.randint(1, 10000)
random.seed(seed)
torch.manual_seed(seed)
print(f"Using manual seed: {seed}") | If manual seed is not specified, choose a random one and communicate it to the user. | check_manual_seed | python | pytorch/ignite | examples/gan/dcgan.py | https://github.com/pytorch/ignite/blob/master/examples/gan/dcgan.py | BSD-3-Clause |
def check_dataset(dataset, dataroot):
"""
Args:
dataset (str): Name of the dataset to use. See CLI help for details
dataroot (str): root directory where the dataset will be stored.
Returns:
dataset (data.Dataset): torchvision Dataset object
"""
resize = transforms.Resize(6... |
Args:
dataset (str): Name of the dataset to use. See CLI help for details
dataroot (str): root directory where the dataset will be stored.
Returns:
dataset (data.Dataset): torchvision Dataset object
| check_dataset | python | pytorch/ignite | examples/gan/dcgan.py | https://github.com/pytorch/ignite/blob/master/examples/gan/dcgan.py | BSD-3-Clause |
def get_data_loaders(train_batch_size, val_batch_size):
"""Method to setup data loaders: train_loader and val_loader"""
data_transform = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))])
train_loader = DataLoader(
MNIST(download=True, root=".", transform=data_transform, train=True),
ba... | Method to setup data loaders: train_loader and val_loader | get_data_loaders | python | pytorch/ignite | examples/mnist/mnist_save_resume_engine.py | https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist_save_resume_engine.py | BSD-3-Clause |
def log_model_weights(engine, model=None, fp=None, **kwargs):
"""Helper method to log norms of model weights: print and dump into a file"""
assert model and fp
output = {"total": 0.0}
max_counter = 5
for name, p in model.named_parameters():
name = name.replace(".", "/")
n = torch.nor... | Helper method to log norms of model weights: print and dump into a file | log_model_weights | python | pytorch/ignite | examples/mnist/mnist_save_resume_engine.py | https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist_save_resume_engine.py | BSD-3-Clause |
def log_model_grads(engine, model=None, fp=None, **kwargs):
"""Helper method to log norms of model gradients: print and dump into a file"""
assert model and fp
output = {"grads/total": 0.0}
max_counter = 5
for name, p in model.named_parameters():
if p.grad is None:
continue
... | Helper method to log norms of model gradients: print and dump into a file | log_model_grads | python | pytorch/ignite | examples/mnist/mnist_save_resume_engine.py | https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist_save_resume_engine.py | BSD-3-Clause |
def log_data_stats(engine, fp=None, **kwargs):
"""Helper method to log mean/std of input batch of images and median of batch of targets."""
assert fp
x, y = engine.state.batch
output = {
"batch xmean": x.mean().item(),
"batch xstd": x.std().item(),
"batch ymedian": y.median().ite... | Helper method to log mean/std of input batch of images and median of batch of targets. | log_data_stats | python | pytorch/ignite | examples/mnist/mnist_save_resume_engine.py | https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist_save_resume_engine.py | BSD-3-Clause |
def run_training(config_filepath, backend="nccl", with_clearml=True):
"""Main entry to run training experiment
Args:
config_filepath (str): training configuration .py file
backend (str): distributed backend: nccl, gloo or None to run without distributed config
with_clearml (bool): if Tr... | Main entry to run training experiment
Args:
config_filepath (str): training configuration .py file
backend (str): distributed backend: nccl, gloo or None to run without distributed config
with_clearml (bool): if True, uses ClearML as experiment tracking system
| run_training | python | pytorch/ignite | examples/references/classification/imagenet/main.py | https://github.com/pytorch/ignite/blob/master/examples/references/classification/imagenet/main.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.