def test_none_defaults(): """Make sure that an unannotated parameter with default=None is ok.""" assert widgets.create_widget(value=None).value is None def func(arg=None): return 1 assert magicgui(func)() == 1 assert str(magic_signature(func)) == str(magicgui(func).__signature__)
def test_positions(qtbot): """Test that providing position options puts widget in the right place.""" def func(a=1, b=2, c=3): pass def get_layout_items(layout): return [ layout.itemAt(i).widget().objectName() for i in range(layout.count()) ] gui = magicgui(func).Gui() assert get_layout_items(gui.layout()) == ["a", "b", "c"] gui = magicgui(func, a={"position": 2}, b={"position": 1}).Gui() assert get_layout_items(gui.layout()) == ["c", "b", "a"]
def magic_func(): """Test function decorated by magicgui.""" decorated = magicgui(func, call_button="my_button", auto_call=True, labels=False) return decorated
def test_trange_inside_of_indirectly_decorated_magicgui(): """Test that trange can find the magicgui within which it is called.""" indirectly_decorated = magicgui(_indirectly_decorated) indirectly_decorated.show() assert not indirectly_decorated._tqdm_pbars indirectly_decorated() assert len(indirectly_decorated._tqdm_pbars) == 1
def add_function_widget( self, function, *, magic_kwargs=None, name: str = '', area=None, allowed_areas=None, shortcut=None, ): """Turn a function into a dock widget via magicgui. Parameters ---------- function : callable Function that you want to add. magic_kwargs : dict, optional Keyword arguments to :func:`magicgui.magicgui` that can be used to specify widget. name : str, optional Name of dock widget to appear in window menu. area : str, optional Side of the main window to which the new dock widget will be added. Must be in {'left', 'right', 'top', 'bottom'}. If not provided the default will be determined by the widget.layout, with 'vertical' layouts appearing on the right, otherwise on the bottom. allowed_areas : list[str], optional Areas, relative to main window, that the widget is allowed dock. Each item in list must be in {'left', 'right', 'top', 'bottom'} By default, only provided areas is allowed. shortcut : str, optional Keyboard shortcut to appear in dropdown menu. Returns ------- dock_widget : QtViewerDockWidget `dock_widget` that can pass viewer events. """ from magicgui import magicgui widget = magicgui(function, **magic_kwargs or {}) if area is None: if str(widget.layout) == 'vertical': area = 'right' else: area = 'bottom' if allowed_areas is None: allowed_areas = [area] return self.add_dock_widget( widget, name=name or function.__name__.replace('_', ' '), area=area, allowed_areas=allowed_areas, shortcut=shortcut, )
def _evolve_gui(self): e = partial(evolve, self) e = partial(e, self.viewer) e = partial(e, self.timeit) e = magicgui(e, call_button='Evolve', layout='form') evolve_gui = e.Gui() self.viewer.window.add_dock_widget(evolve_gui) self.viewer.layers.events.changed.connect( lambda x: evolve_gui.refresh_choices())
def magic_projection(): return magicgui( _projection, auto_call=True, layout='vertical', input1={'label': 'Image'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['projection', 'in assistant']).keys() })
def test_multiple_gui_instance_independence(): """Test that multiple instance of the same decorated function are independent.""" def example(a=2): return a w1 = magicgui(example) w2 = magicgui(example) # they get their initial values from the function sigs assert w1.a.value == 2 assert w2.a.value == 2 # settings one doesn't affect the other w1.a.value = 10 assert w1.a.value == 10 assert w2.a.value == 2 # vice versa... w2.a.value = 4 assert w1.a.value == 10 assert w2.a.value == 4 # all instances are independent assert example() == 2 assert w1() == 10 assert w2() == 4
def magic_combine(): return magicgui(_combine, auto_call=True, layout='vertical', input1={'label': 'Image 1'}, input2={'label': 'Image 2'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['combine', 'in assistant'], must_not_have_categories=['map']).keys() })
def magic_label_measurements(): return magicgui( _label_measurements, auto_call=True, layout='vertical', input1={'label': 'Image'}, input2={'label': 'Labels'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['combine', 'map', 'in assistant' ]).keys() })
def magic_label(): return magicgui( _label, auto_call=True, layout='vertical', input1={'label': 'Image'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['label', 'in assistant']).keys() }, a=plus_minus_1k, b=plus_minus_1k)
def magic_label_processing(): return magicgui( _label_processing, auto_call=True, layout='vertical', input1={'label': 'Labels'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['label processing', 'in assistant' ]).keys() }, min=plus_minus_1k, max=plus_minus_1k)
def magic_binarize(): return magicgui(_binarize, auto_call=True, layout='vertical', input1={'label': 'Image'}, operation_name={ 'label': 'Operation', 'choices': cle.operations( must_have_categories=['binarize', 'in assistant'], must_not_have_categories=['combine']).keys() }, radius_x=plus_minus_1k, radius_y=plus_minus_1k, radius_z=plus_minus_1k)
def test_signature_repr(): """Test that the gui makes a proper signature.""" def func(a: str = "string", b: int = 3, c: float = 7.1): return locals() magic_func = magicgui(func) # the STRING signature representation should be the same as the original function assert str(inspect.signature(magic_func)) == str(inspect.signature(func)) # however, the magic_func signature is an enhance MagicSignature object: assert isinstance(inspect.signature(magic_func), MagicSignature) assert isinstance(inspect.signature(func), inspect.Signature) # make sure it is up to date magic_func.b.value = 0 assert (str(inspect.signature(magic_func)) == "(a: str = 'string', b: int = 0, c: float = 7.1)")
def add_function_widget( self, function, *, magic_kwargs=None, name: str = '', area: str = 'bottom', allowed_areas=None, shortcut=None, ): """Turn a function into a dock widget via magicgui. Parameters ---------- function : callable Function that you want to add. magic_kwargs : dict, optional Keyword arguments to :func:`magicgui.magicgui` that can be used to specify widget. name : str, optional Name of dock widget to appear in window menu. area : str Side of the main window to which the new dock widget will be added. Must be in {'left', 'right', 'top', 'bottom'} allowed_areas : list[str], optional Areas, relative to main window, that the widget is allowed dock. Each item in list must be in {'left', 'right', 'top', 'bottom'} By default, all areas are allowed. shortcut : str, optional Keyboard shortcut to appear in dropdown menu. Returns ------- dock_widget : QtViewerDockWidget `dock_widget` that can pass viewer events. """ from magicgui import magicgui return self.add_dock_widget( magicgui(function, **magic_kwargs or {}), name=name or function.__name__.replace('_', ' '), area=area, allowed_areas=allowed_areas, shortcut=shortcut, )
def magic_background_removal(): return magicgui(_background_removal, auto_call=True, layout='vertical', input1={'label': 'Image'}, operation_name={ 'label': 'Operation', 'choices': cle.operations(must_have_categories=[ 'filter', 'background removal', 'in assistant' ], must_not_have_categories=['combine' ]).keys() }, x=plus_minus_1k, y=plus_minus_1k, z=plus_minus_1k)
def magic_denoise(): return magicgui( _denoise, auto_call=True, layout='vertical', input1={'label': 'Image'}, operation_name={ 'label': 'Operation', 'choices': list( cle.operations( must_have_categories=['filter', 'denoise', 'in assistant'], must_not_have_categories=['combine']).keys()) }, x=plus_minus_1k, y=plus_minus_1k, z=plus_minus_1k)
def magic_map(): return magicgui(_map, auto_call=True, layout='vertical', input1={'label': 'Labels'}, operation_name={ 'label': 'Operation', 'choices': cle.operations(must_have_categories=[ 'label measurement', 'map', 'in assistant' ], must_not_have_categories=["combine" ]).keys() }, n={ 'min': 0, 'max': 1000 })
def test_add_at_position(labels): """Test that adding widghet with position option puts widget in the right place.""" def func(a=1, b=2, c=3): pass def get_layout_items(gui): lay = gui.native.layout() items = [ lay.itemAt(i).widget()._magic_widget.name for i in range(lay.count()) ] if labels: items = list(filter(None, items)) return items gui = magicgui(func, labels=labels) assert get_layout_items(gui) == ["a", "b", "c"] gui.insert(1, widgets.create_widget(name="new")) assert get_layout_items(gui) == ["a", "new", "b", "c"]
def test_add_at_position(labels, qtbot): """Test that adding widghet with position option puts widget in the right place.""" def func(a=1, b=2, c=3): pass def get_layout_items(layout): items = [ layout.itemAt(i).widget().objectName() for i in range(layout.count()) ] if labels: items = list(filter(None, items)) return items gui = magicgui(func, labels=labels).Gui() assert get_layout_items(gui.layout()) == ["a", "b", "c"] gui.set_widget("new", 1, position=1) assert get_layout_items(gui.layout()) == ["a", "new", "b", "c"] gui.set_widget("new2", 1, position=-2) assert get_layout_items(gui.layout()) == ["a", "new", "b", "new2", "c"] with pytest.raises(TypeError): gui.set_widget("hi", 1, position=1.5)
def test_widgets(function): magicgui(function)
from magicgui import magicgui def sliding_window_mean( arr: napari.types.ImageData, size: int = 1 ) -> napari.types.LayerDataTuple: window_shape = (size,) + (arr.shape[1:]) arr_windows = sliding_window_view(arr, window_shape=window_shape) # as before, use squeeze to remove singleton axes arr_windows_1d = np.squeeze( arr_windows, axis=tuple(range(1, arr.ndim)) ) arr_summed = np.sum(arr_windows_1d, axis=1) / size return ( arr_summed, { 'translate': (size // 2,) + (0,) * (arr.ndim - 1), 'name': 'mean-window', 'colormap': 'magenta', 'blending': 'additive', }, 'image', ) viewer = napari.view_image(blobs_dask, colormap='green') viewer.window.add_dock_widget(magicgui(sliding_window_mean, auto_call=True)) viewer.dims.current_step = (32, 0, 0) napari.run()
def magic_func_defaults(): decorated = magicgui(func) return decorated
def test_magicgui_type_error(): with pytest.raises(TypeError): magicgui("not a function") # type: ignore
def magic_func_autocall(): decorated = magicgui(func, auto_call=True) return decorated
def magic_measure(): return magicgui(_measure, layout='vertical', input1={'label': 'Image'}, labels={'label': 'Labels'}, call_button="Measure")
def magic_func_defaults(): return magicgui(func)
def magic_func_autocall(): return magicgui(func, auto_call=True)
def update(e): if len(example) > 2: del example[1] example.insert(1, magicgui(globals()[e.value]))
image_idx = get_parameter_position(wrapped, "image") if len(args) >= (image_idx + 1): args = list(args) if hasattr(args[image_idx], "data"): args[image_idx] = args[image_idx].data elif "image" in kwargs: if hasattr(kwargs["image"], "data"): kwargs["image"] = kwargs["image"].data return wrapped(*args, **kwargs) adapted_functions = [ image_as_napari_layer(f) for f in find_functions_with_arg_named(filters, "image") ] guis = {} for func in adapted_functions: opts: Dict[str, Any] = defaultdict(dict) opts.update({"ignore": ["output"], "auto_call": True}) annotations = guess_numpydoc_annotations(func) for pname, value in annotations.items(): if "choices" in value: opts[pname]["choices"] = value["choices"] # if "type" in value: # opts[pname]["dtype"] = value["type"] guis[func.__name__] = magicgui(func, **opts) app = QApplication([]) for func in guis.values(): func.Gui()