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 build_gpt2_config( vocab_size: int = 10000, bos_token_id: int = 0, eos_token_id: int = 0, max_length: int = 1024, dropout: float = 0.0, **kwargs ): """ Builds a custom GPT-2 config based on a given Transformers config, with a few more user-friendly aliases. """ return GP...
Builds a custom GPT-2 config based on a given Transformers config, with a few more user-friendly aliases.
build_gpt2_config
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def GPT2ConfigCPU( vocab_size: int = 1000, bos_token_id: int = 0, eos_token_id: int = 0, **kwargs ): """ Returns a GPT-2 config more suitable for training on a regular consumer CPU. """ return GPT2Config( vocab_size=vocab_size, n_positions=64, n_ctx=64, n_embd=128, ...
Returns a GPT-2 config more suitable for training on a regular consumer CPU.
GPT2ConfigCPU
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def GPTNeoConfigCPU( vocab_size: int = 1000, bos_token_id: int = 0, eos_token_id: int = 0, **kwargs ): """ Returns a GPT Neo config more suitable for training on a regular consumer CPU. """ return GPTNeoConfig( vocab_size=vocab_size, max_position_embeddings=64, hidden_size=2...
Returns a GPT Neo config more suitable for training on a regular consumer CPU.
GPTNeoConfigCPU
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def find_index_of_subset(large_list, small_list): """ Returns the index after the small_list within the large list, Returns -1 if not present. Adapted from https://stackoverflow.com/a/45819222 which shows that it is performant for input lengths < 1000, which is the common case for this function. ...
Returns the index after the small_list within the large list, Returns -1 if not present. Adapted from https://stackoverflow.com/a/45819222 which shows that it is performant for input lengths < 1000, which is the common case for this function.
find_index_of_subset
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def skip_special_tokens(tensor, device, special_token_ids): """Filters out special tokens by ids in the given 1D tensor. Adapted from https://stackoverflow.com/a/62588955 Args: tensor (tensor): PyTorch Tensor device (str): Device, usually "cpu" or "cuda:0" token_ids (set): List of ...
Filters out special tokens by ids in the given 1D tensor. Adapted from https://stackoverflow.com/a/62588955 Args: tensor (tensor): PyTorch Tensor device (str): Device, usually "cpu" or "cuda:0" token_ids (set): List of Token IDs
skip_special_tokens
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def model_max_length(config): """Returns the maximum generation length for the given model.""" return getattr(config, "n_positions", None) or getattr( config, "max_position_embeddings", None )
Returns the maximum generation length for the given model.
model_max_length
python
minimaxir/aitextgen
aitextgen/utils.py
https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py
MIT
def IDR_fetch_image(image_id: int, progressbar: bool = True) -> np.ndarray: """ Download the image with id image_id from the IDR Will fetch all image planes corresponding to separate timepoints/channels/z-slices and return a numpy array with dimension order (t,z,y,x,c) Displaying download prog...
Download the image with id image_id from the IDR Will fetch all image planes corresponding to separate timepoints/channels/z-slices and return a numpy array with dimension order (t,z,y,x,c) Displaying download progress can be disabled by passing False to progressbar.
IDR_fetch_image
python
napari/napari
examples/3d_kymograph_.py
https://github.com/napari/napari/blob/master/examples/3d_kymograph_.py
BSD-3-Clause
def segment(image): """Segment an image using an intensity threshold determined via Otsu's method. Parameters ---------- image : np.ndarray The image to be segmented Returns ------- label_image : np.ndarray The resulting image where each detected object labeled with a u...
Segment an image using an intensity threshold determined via Otsu's method. Parameters ---------- image : np.ndarray The image to be segmented Returns ------- label_image : np.ndarray The resulting image where each detected object labeled with a unique integer.
segment
python
napari/napari
examples/annotate_segmentation_with_text.py
https://github.com/napari/napari/blob/master/examples/annotate_segmentation_with_text.py
BSD-3-Clause
def make_bbox(bbox_extents): """Get the coordinates of the corners of a bounding box from the extents Parameters ---------- bbox_extents : list (4xN) List of the extents of the bounding boxes for each of the N regions. Should be ordered: [min_row, min_column, max_row, max_column] ...
Get the coordinates of the corners of a bounding box from the extents Parameters ---------- bbox_extents : list (4xN) List of the extents of the bounding boxes for each of the N regions. Should be ordered: [min_row, min_column, max_row, max_column] Returns ------- bbox_rect...
make_bbox
python
napari/napari
examples/annotate_segmentation_with_text.py
https://github.com/napari/napari/blob/master/examples/annotate_segmentation_with_text.py
BSD-3-Clause
def create_label_menu(shapes_layer, label_feature, labels): """Create a label menu widget that can be added to the napari viewer dock Parameters ---------- shapes_layer : napari.layers.Shapes a napari shapes layer label_feature : str the name of the shapes feature to use the display...
Create a label menu widget that can be added to the napari viewer dock Parameters ---------- shapes_layer : napari.layers.Shapes a napari shapes layer label_feature : str the name of the shapes feature to use the displayed text labels : List[str] list of the possible text la...
create_label_menu
python
napari/napari
examples/bbox_annotator.py
https://github.com/napari/napari/blob/master/examples/bbox_annotator.py
BSD-3-Clause
def update_label_menu(): """This is a callback function that updates the label menu when the default features of the Shapes layer change """ new_label = str(shapes_layer.feature_defaults[label_feature][0]) if new_label != label_menu.value: label_menu.value = new_label
This is a callback function that updates the label menu when the default features of the Shapes layer change
update_label_menu
python
napari/napari
examples/bbox_annotator.py
https://github.com/napari/napari/blob/master/examples/bbox_annotator.py
BSD-3-Clause
def set_selected_features_to_default(): """This is a callback that updates the feature values of the currently selected shapes. This is a side-effect of the deprecated current_properties setter, but does not occur when modifying feature_defaults.""" indices = list(shapes_layer.selected_d...
This is a callback that updates the feature values of the currently selected shapes. This is a side-effect of the deprecated current_properties setter, but does not occur when modifying feature_defaults.
set_selected_features_to_default
python
napari/napari
examples/bbox_annotator.py
https://github.com/napari/napari/blob/master/examples/bbox_annotator.py
BSD-3-Clause
def shift_plane_along_normal(viewer, event): """Shift a plane along its normal vector on mouse drag. This callback will shift a plane along its normal vector when the plane is clicked and dragged. The general strategy is to 1) find both the plane normal vector and the mouse drag vector in canvas coo...
Shift a plane along its normal vector on mouse drag. This callback will shift a plane along its normal vector when the plane is clicked and dragged. The general strategy is to 1) find both the plane normal vector and the mouse drag vector in canvas coordinates 2) calculate how far to move the plane ...
shift_plane_along_normal
python
napari/napari
examples/clipping_planes_interactive_.py
https://github.com/napari/napari/blob/master/examples/clipping_planes_interactive_.py
BSD-3-Clause
def wait_for_layers(viewer, layer_names, *, interval=0.1): """Wait for any thread creating layers to finish. If we expect a different thread to be adding layers to `viewer`, we can wait for them to be added based on their expected names. """ for name in layer_names: while name not in vi...
Wait for any thread creating layers to finish. If we expect a different thread to be adding layers to `viewer`, we can wait for them to be added based on their expected names.
wait_for_layers
python
napari/napari
examples/fourier_transform_playground.py
https://github.com/napari/napari/blob/master/examples/fourier_transform_playground.py
BSD-3-Clause
def wave_2d(frequency, angle, phase_shift): """Generate a 2D sine wave based on angle, frequency and phase shift.""" angle = np.deg2rad(angle) phase_shift = np.deg2rad(phase_shift) wave = 2 * np.pi * (X * np.cos(angle) + Y * np.sin(angle)) * frequency return np.sin(wave + phase_shift)
Generate a 2D sine wave based on angle, frequency and phase shift.
wave_2d
python
napari/napari
examples/fourier_transform_playground.py
https://github.com/napari/napari/blob/master/examples/fourier_transform_playground.py
BSD-3-Clause
def update_layer(name, data, **kwargs): """Update a layer in the viewer with new data. If data is None, then the layer is removed. If the layer is not present, it's added to the viewer. """ if FINISHED: return # don't update the viewer after the example has finished if data is None: ...
Update a layer in the viewer with new data. If data is None, then the layer is removed. If the layer is not present, it's added to the viewer.
update_layer
python
napari/napari
examples/fourier_transform_playground.py
https://github.com/napari/napari/blob/master/examples/fourier_transform_playground.py
BSD-3-Clause
def combine_and_set_data(wave_args): """Merge 2D waves, calculate the FT and update the viewer. The wave phases are offset by the current time multiplied by an arbitrary speed value; this generates an animated wave if called repeatedly. """ if not wave_args: # this happens on yielding from ...
Merge 2D waves, calculate the FT and update the viewer. The wave phases are offset by the current time multiplied by an arbitrary speed value; this generates an animated wave if called repeatedly.
combine_and_set_data
python
napari/napari
examples/fourier_transform_playground.py
https://github.com/napari/napari/blob/master/examples/fourier_transform_playground.py
BSD-3-Clause
def moving_wave( wave_id: int = 0, frequency: float = 0.2, angle: int = 0, phase_shift: int = 0, speed: float = 1, run=True, ): """Send new parameters to the listening thread to update the 2D waves. The `run` checkbox can be disabled to stop sending values to the thread while changi...
Send new parameters to the listening thread to update the 2D waves. The `run` checkbox can be disabled to stop sending values to the thread while changing parameters.
moving_wave
python
napari/napari
examples/fourier_transform_playground.py
https://github.com/napari/napari/blob/master/examples/fourier_transform_playground.py
BSD-3-Clause
def append(delayed_image): """Appends the image to viewer. Parameters ---------- delayed_image : dask.delayed function object """ if delayed_image is None: return if viewer.layers: # layer is present, append to its data layer = viewer.layers[0] image_shape =...
Appends the image to viewer. Parameters ---------- delayed_image : dask.delayed function object
append
python
napari/napari
examples/live_tiffs_.py
https://github.com/napari/napari/blob/master/examples/live_tiffs_.py
BSD-3-Clause
def watch_path(path): """Watches the path for new files and yields it once file is ready. Notes ----- Currently, there is no proper way to know if the file has written entirely. So the workaround is we assume that files are generating serially (in most microscopes it common), and files are name...
Watches the path for new files and yields it once file is ready. Notes ----- Currently, there is no proper way to know if the file has written entirely. So the workaround is we assume that files are generating serially (in most microscopes it common), and files are name in alphanumeric sequence...
watch_path
python
napari/napari
examples/live_tiffs_.py
https://github.com/napari/napari/blob/master/examples/live_tiffs_.py
BSD-3-Clause
def image_arithmetic( layerA: 'napari.types.ImageData', operation: Operation, layerB: 'napari.types.ImageData', ) -> 'napari.types.ImageData': """Adds, subtracts, multiplies, or divides two same-shaped image layers.""" if layerA is not None and layerB is not None: return operation.value(laye...
Adds, subtracts, multiplies, or divides two same-shaped image layers.
image_arithmetic
python
napari/napari
examples/magic_image_arithmetic.py
https://github.com/napari/napari/blob/master/examples/magic_image_arithmetic.py
BSD-3-Clause
def center_cross_on_mouse( viewer_model: napari.components.viewer_model.ViewerModel, ): """move the cross to the mouse position""" if not getattr(viewer_model, 'mouse_over_canvas', True): # There is no way for napari 0.4.15 to check if mouse is over sending canvas. show_info( 'M...
move the cross to the mouse position
center_cross_on_mouse
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def _qt_open( self, filenames: list, stack: bool, plugin: str | None = None, layer_type: str | None = None, **kwargs, ): """for drag and drop open files""" self.main_viewer.window._qt_viewer._qt_open( filenames, stack, plugin, layer_type, *...
for drag and drop open files
_qt_open
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def _update_extent(self): """ Calculate the extent of the data. Ignores the layer with cross itself in calculating the extent. """ layers = [ layer for layer in self.viewer.layers if layer is not self.layer ] self._extent = sel...
Calculate the extent of the data. Ignores the layer with cross itself in calculating the extent.
_update_extent
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def _layer_added(self, event): """add layer to additional viewers and connect all required events""" self.viewer_model1.layers.insert( event.index, copy_layer(event.value, 'model1') ) self.viewer_model2.layers.insert( event.index, copy_layer(event.value, 'model2')...
add layer to additional viewers and connect all required events
_layer_added
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def _sync_data(self, event): """sync data modification from additional viewers""" if self._block: return for model in [self.viewer, self.viewer_model1, self.viewer_model2]: layer = model.layers[event.source.name] if layer is event.source: conti...
sync data modification from additional viewers
_sync_data
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def _property_sync(self, name, event): """Sync layers properties (except the name)""" if event.source not in self.viewer.layers: return try: self._block = True setattr( self.viewer_model1.layers[event.source.name], name, ...
Sync layers properties (except the name)
_property_sync
python
napari/napari
examples/multiple_viewer_widget.py
https://github.com/napari/napari/blob/master/examples/multiple_viewer_widget.py
BSD-3-Clause
def two_way_communication_with_args(start, end): """Both sends and receives values to & from the main thread. Accepts arguments, puts them on the worker object. Receives values from main thread with ``incoming = yield`` Optionally returns a value at the end """ # do computationally intensive w...
Both sends and receives values to & from the main thread. Accepts arguments, puts them on the worker object. Receives values from main thread with ``incoming = yield`` Optionally returns a value at the end
two_way_communication_with_args
python
napari/napari
examples/multithreading_two_way_.py
https://github.com/napari/napari/blob/master/examples/multithreading_two_way_.py
BSD-3-Clause
def create_connected_widget(): """Builds a widget that can control a function in another thread.""" w = Controller() steps = 40 # the decorated function now returns a GeneratorWorker object, and the # Qthread in which it's running. # (optionally pass start=False to prevent immediate running) ...
Builds a widget that can control a function in another thread.
create_connected_widget
python
napari/napari
examples/multithreading_two_way_.py
https://github.com/napari/napari/blob/master/examples/multithreading_two_way_.py
BSD-3-Clause
def iterable(): """using progress as a wrapper for iterables """ my_stacked_volume = np.random.random((5, 4, 500, 500)) # we can wrap any iterable object in `progress` and see a progress # bar in the viewer for im_slice in progress(my_stacked_volume): process(im_slice)
using progress as a wrapper for iterables
iterable
python
napari/napari
examples/progress_bar_minimal_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_minimal_.py
BSD-3-Clause
def indeterminate(): """By passing a total of 0, we can have an indeterminate progress bar """ # note progress(total=0) is equivalent to progress() with progress(total=0) as pbr: x = 0 while x != 42: pbr.set_description(f'Processing {x}') x = choice(range(100)) ...
By passing a total of 0, we can have an indeterminate progress bar
indeterminate
python
napari/napari
examples/progress_bar_minimal_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_minimal_.py
BSD-3-Clause
def arbitrary_steps(): """We can manually control updating the value of the progress bar. """ with progress(total=4) as pbr: sleep(3) pbr.set_description('Step 1 Complete') # manually updating the progress bar by 1 pbr.update(1) sleep(1) pbr.set_description('...
We can manually control updating the value of the progress bar.
arbitrary_steps
python
napari/napari
examples/progress_bar_minimal_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_minimal_.py
BSD-3-Clause
def cancelable_iterable(): """We can allow expensive computations to be cancelable """ # Note that if canceled, for loop will terminate prematurely # You can use cancel_callback to close files, clean up state, etc # if the user cancels the operation. def cancel_callback(): print('Operati...
We can allow expensive computations to be cancelable
cancelable_iterable
python
napari/napari
examples/progress_bar_minimal_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_minimal_.py
BSD-3-Clause
def try_thresholds(): """Tries each threshold, and adds result to viewer.""" if 'Binarised' in viewer.layers: del viewer.layers['Binarised'] thresholded_nuclei = [] # we wrap our iterable with `progress` # this will automatically add a progress bar to our activity dock for threshold_fu...
Tries each threshold, and adds result to viewer.
try_thresholds
python
napari/napari
examples/progress_bar_segmentation_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_segmentation_.py
BSD-3-Clause
def segment_binarised_ims(): """Segments each of the binarised ims. Uses `progress` within a context manager allowing us to manipulate the progress bar within the loop """ if 'Binarised' not in viewer.layers: raise TypeError('Cannot segment before thresholding') if 'Segmented' in viewer...
Segments each of the binarised ims. Uses `progress` within a context manager allowing us to manipulate the progress bar within the loop
segment_binarised_ims
python
napari/napari
examples/progress_bar_segmentation_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_segmentation_.py
BSD-3-Clause
def process_ims(): """ First performs thresholding, then segmentation on our image. Manually updates a `progress` object. """ if 'Binarised' in viewer.layers: del viewer.layers['Binarised'] if 'Segmented' in viewer.layers: del viewer.layers['Segmented'] # we instantiate a m...
First performs thresholding, then segmentation on our image. Manually updates a `progress` object.
process_ims
python
napari/napari
examples/progress_bar_segmentation_.py
https://github.com/napari/napari/blob/master/examples/progress_bar_segmentation_.py
BSD-3-Clause
def napari_get_reader(path): """A basic implementation of the napari_get_reader hook specification.""" # if we know we cannot read the file, we immediately return None. if not path.endswith(readable_extensions): return None # otherwise we return the *function* that can read ``path``. return ...
A basic implementation of the napari_get_reader hook specification.
napari_get_reader
python
napari/napari
examples/reader_plugin.py
https://github.com/napari/napari/blob/master/examples/reader_plugin.py
BSD-3-Clause
def reader_function(path): """Take a path and returns a list of LayerData tuples.""" data = imread(path) # Readers are expected to return data as a list of tuples, where each tuple # is (data, [meta_dict, [layer_type]]) return [(data,)]
Take a path and returns a list of LayerData tuples.
reader_function
python
napari/napari
examples/reader_plugin.py
https://github.com/napari/napari/blob/master/examples/reader_plugin.py
BSD-3-Clause
def tracks_3d_merge_split(): """Create tracks with splitting and merging.""" timestamps = np.arange(300) def _trajectory(t, r, track_id): theta = t * 0.1 x, y = _circle(r, theta) z = np.zeros(x.shape) tid = np.ones(x.shape) * track_id return np.stack([tid, t, z, y, ...
Create tracks with splitting and merging.
tracks_3d_merge_split
python
napari/napari
examples/tracks_3d_with_graph.py
https://github.com/napari/napari/blob/master/examples/tracks_3d_with_graph.py
BSD-3-Clause
def get_scale_translate(dataset, array_name): """Get the translate/offset and scale parameters for an xarray dataset. This code assumes that the dataset is regularly spaced. You should interpolate your data if it is sampled at irregular spaces. Parameters ---------- dataset : xr.Dataset ...
Get the translate/offset and scale parameters for an xarray dataset. This code assumes that the dataset is regularly spaced. You should interpolate your data if it is sampled at irregular spaces. Parameters ---------- dataset : xr.Dataset The dataset containing the array to be displayed. ...
get_scale_translate
python
napari/napari
examples/xarray-latlon-timeseries.py
https://github.com/napari/napari/blob/master/examples/xarray-latlon-timeseries.py
BSD-3-Clause
def resize_selection_box( layer: Image, event: 'NapariMouseEvent' ) -> 'Generator[None, None, None]': """Resize the selection box based on mouse movement. Parameters ---------- layer : DetectorLayer The layer to resize the selection box for. event : NapariMouseEvent The event tr...
Resize the selection box based on mouse movement. Parameters ---------- layer : DetectorLayer The layer to resize the selection box for. event : NapariMouseEvent The event triggered by mouse movement. Yields ------ None This is a generator function that handles mous...
resize_selection_box
python
napari/napari
examples/dev/controllable_overlay.py
https://github.com/napari/napari/blob/master/examples/dev/controllable_overlay.py
BSD-3-Clause
def highlight_roi_box_handles(layer: Image, event: NapariMouseEvent) -> None: """Highlight the hovered handle of a selection box. Parameters ---------- layer : Image The layer to highlight the selection box for. event : NapariMouseEvent The event triggered by mouse movement. """...
Highlight the hovered handle of a selection box. Parameters ---------- layer : Image The layer to highlight the selection box for. event : NapariMouseEvent The event triggered by mouse movement.
highlight_roi_box_handles
python
napari/napari
examples/dev/controllable_overlay.py
https://github.com/napari/napari/blob/master/examples/dev/controllable_overlay.py
BSD-3-Clause
def create_sample_coords(n_polys=3000, n_vertices=32): """random circular polygons with given number of vertices""" center = np.random.randint(0, 1000, (n_polys, 2)) radius = ( 1000 / np.sqrt(n_polys) * np.random.uniform(0.9, 1.1, (n_polys, n_vertices)) ) phi = np.linspace(0...
random circular polygons with given number of vertices
create_sample_coords
python
napari/napari
examples/dev/demo_shape_creation.py
https://github.com/napari/napari/blob/master/examples/dev/demo_shape_creation.py
BSD-3-Clause
def pltri(vertices, triangles, *, mask=None, ax=None): """Plot a triangulation in Matplotlib. Transposes x and y to match napari's row/columns coordinates. (We invert the y-axis in napari to match the expected lat/lon coordinate orientation of this dataset.) """ if ax is None: fig, ax =...
Plot a triangulation in Matplotlib. Transposes x and y to match napari's row/columns coordinates. (We invert the y-axis in napari to match the expected lat/lon coordinate orientation of this dataset.)
pltri
python
napari/napari
examples/dev/poly-hole.py
https://github.com/napari/napari/blob/master/examples/dev/poly-hole.py
BSD-3-Clause
def generate_regular_polygon(n, radius=1): """Generate vertices of a regular n-sided polygon centered at the origin. Parameters ---------- n : int The number of sides (vertices). radius : float, optional The radius of the circumscribed circle. Returns ------- np.ndarray...
Generate vertices of a regular n-sided polygon centered at the origin. Parameters ---------- n : int The number of sides (vertices). radius : float, optional The radius of the circumscribed circle. Returns ------- np.ndarray An array of shape (n, 2) containing the v...
generate_regular_polygon
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def generate_order_vectors(path_, closed) -> np.ndarray: """Generate the vectors tangent to the path. Parameters ---------- path_ : np.ndarray, shape (N, 2) A list of 2D path coordinates. closed : bool Whether the coordinates represent a closed polygon or an open line/path. ...
Generate the vectors tangent to the path. Parameters ---------- path_ : np.ndarray, shape (N, 2) A list of 2D path coordinates. closed : bool Whether the coordinates represent a closed polygon or an open line/path. Returns ------- vec : np.ndarray, shape (N, 2, 2) ...
generate_order_vectors
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def generate_orthogonal_vectors(direction_vectors: np.ndarray) -> np.ndarray: """Generate the orthogonal vectors to the direction vectors. The orthogonal vector starts at the middle of the direction vector and is orthogonal to it in the positive orientation. Its length is half of the direction vector, ...
Generate the orthogonal vectors to the direction vectors. The orthogonal vector starts at the middle of the direction vector and is orthogonal to it in the positive orientation. Its length is half of the direction vector, to align with the normalized edge width. Parameters ---------- direction...
generate_orthogonal_vectors
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def generate_edge_triangle_borders(centers, offsets, triangles) -> np.ndarray: """Generate 3 vectors that represent the borders of the triangle. These are vectors to show the *ordering* of the triangles in the data. Parameters ---------- centers, offsets, triangles : np.ndarray of float Th...
Generate 3 vectors that represent the borders of the triangle. These are vectors to show the *ordering* of the triangles in the data. Parameters ---------- centers, offsets, triangles : np.ndarray of float The mesh triangulation of the shape's edge path. Returns ------- borders : ...
generate_edge_triangle_borders
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def generate_face_triangle_borders(vertices, triangles) -> np.ndarray: """For each triangle in mesh generate 3 vectors that represent the borders of the triangle. """ borders = np.empty((len(triangles)*3, 2, 2), dtype=vertices.dtype) for i, triangle in enumerate(triangles): a, b, c = triangle ...
For each triangle in mesh generate 3 vectors that represent the borders of the triangle.
generate_face_triangle_borders
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def asdict(dataclass_instance): """Shallow copy version of `dataclasses.asdict`.""" return {f.name: getattr(dataclass_instance, f.name) for f in fields(dataclass_instance)}
Shallow copy version of `dataclasses.asdict`.
asdict
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def get_helper_data_from_shapes(shapes_layer: Shapes) -> Helpers: """Function to generate all auxiliary data for a shapes layer.""" shapes = shapes_layer._data_view.shapes mesh_list = [(s._edge_vertices, s._edge_offsets, s._edge_triangles) for s in shapes] path_list = [(s.data, s._close...
Function to generate all auxiliary data for a shapes layer.
get_helper_data_from_shapes
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def add_helper_layers(viewer: napari.Viewer, source_layer): """Add helper layers to the viewer that track with the source shapes.""" helpers = get_helper_data_from_shapes(source_layer) # sizes and colors are hardcoded based on vibes sizes = [0.2, 0.1, 0.1, 0.06, 0.04, 0.05, 0.04, 0.04] colors = ['ye...
Add helper layers to the viewer that track with the source shapes.
add_helper_layers
python
napari/napari
examples/dev/triangle_edge.py
https://github.com/napari/napari/blob/master/examples/dev/triangle_edge.py
BSD-3-Clause
def layer_data_and_types(): """Fixture that provides some layers and filenames Returns ------- tuple ``layers, layer_data, layer_types, filenames`` - layers: some image and points layers - layer_data: same as above but in LayerData form - layer_types: list of strings wi...
Fixture that provides some layers and filenames Returns ------- tuple ``layers, layer_data, layer_types, filenames`` - layers: some image and points layers - layer_data: same as above but in LayerData form - layer_types: list of strings with type of layer - filename...
layer_data_and_types
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def layer(request): """Parameterized fixture that supplies a layer for testing. Parameters ---------- request : _pytest.fixtures.SubRequest The pytest request object Returns ------- napari.layers.Layer The desired napari Layer. """ np.random.seed(0) if request.p...
Parameterized fixture that supplies a layer for testing. Parameters ---------- request : _pytest.fixtures.SubRequest The pytest request object Returns ------- napari.layers.Layer The desired napari Layer.
layer
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def layers(): """Fixture that supplies a layers list for testing. Returns ------- napari.components.LayerList The desired napari LayerList. """ np.random.seed(0) list_of_layers = [ Image(np.random.rand(20, 20)), Labels(np.random.randint(10, size=(20, 2))), Po...
Fixture that supplies a layers list for testing. Returns ------- napari.components.LayerList The desired napari LayerList.
layers
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _fresh_settings(monkeypatch): """This fixture ensures that default settings are used for every test. and ensures that changes to settings in a test are reverted, and never saved to disk. """ from napari import settings from napari.settings import NapariSettings from napari.settings._exp...
This fixture ensures that default settings are used for every test. and ensures that changes to settings in a test are reverted, and never saved to disk.
_fresh_settings
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _auto_shutdown_dask_threadworkers(): """ This automatically shutdown dask thread workers. We don't assert the number of threads in unchanged as other things modify the number of threads. """ assert dask.threaded.default_pool is None try: yield finally: if isinstance(...
This automatically shutdown dask thread workers. We don't assert the number of threads in unchanged as other things modify the number of threads.
_auto_shutdown_dask_threadworkers
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def napari_svg_name(): """the plugin name changes with npe2 to `napari-svg` from `svg`.""" from importlib.metadata import version if parse_version(version('napari-svg')) < parse_version('0.1.6'): return 'svg' return 'napari-svg'
the plugin name changes with npe2 to `napari-svg` from `svg`.
napari_svg_name
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def npe2pm_(npe2pm, monkeypatch): """Autouse npe2 & npe1 mock plugin managers with no registered plugins.""" from napari.plugins import NapariPluginManager monkeypatch.setattr(NapariPluginManager, 'discover', lambda *_, **__: None) return npe2pm
Autouse npe2 & npe1 mock plugin managers with no registered plugins.
npe2pm_
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _clear_cached_action_injection(): """Automatically clear cached property `Action.injected`. Allows action manager actions to be injected using current provider/processors and dependencies. See #7219 for details. To be removed after ActionManager deprecation. """ from napari.utils.action_man...
Automatically clear cached property `Action.injected`. Allows action manager actions to be injected using current provider/processors and dependencies. See #7219 for details. To be removed after ActionManager deprecation.
_clear_cached_action_injection
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def pytest_generate_tests(metafunc): """Generate separate test for each test toc check if all events are defined.""" if 'event_define_check' in metafunc.fixturenames: res = [] ids = [] for obj in metafunc.cls.get_objects(): for check, instance, name in _event_check(obj): ...
Generate separate test for each test toc check if all events are defined.
pytest_generate_tests
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _disable_notification_dismiss_timer(monkeypatch): """ This fixture disables starting timer for closing notification by setting the value of `NapariQtNotification.DISMISS_AFTER` to 0. As Qt timer is realised by thread and keep reference to the object, without increase of reference counter object...
This fixture disables starting timer for closing notification by setting the value of `NapariQtNotification.DISMISS_AFTER` to 0. As Qt timer is realised by thread and keep reference to the object, without increase of reference counter object could be garbage collected and cause segmentation fault ...
_disable_notification_dismiss_timer
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def run_with_trace(self): # pragma: no cover """ QThread.run but adding execution to sys.settrace when measuring coverage. See https://github.com/nedbat/coveragepy/issues/686#issuecomment-634932753 and `init_with_trace`. When running QThreads during testing, we monkeypatch the ...
QThread.run but adding execution to sys.settrace when measuring coverage. See https://github.com/nedbat/coveragepy/issues/686#issuecomment-634932753 and `init_with_trace`. When running QThreads during testing, we monkeypatch the QThread constructor and run methods with traceable equiva...
run_with_trace
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def init_with_trace(self, *args, **kwargs): """Constructor for QThread adding tracing for coverage measurements. Functions running in QThreads don't get measured by coverage.py, see https://github.com/nedbat/coveragepy/issues/686. Therefore, we will monkeypatch the constructor to add to...
Constructor for QThread adding tracing for coverage measurements. Functions running in QThreads don't get measured by coverage.py, see https://github.com/nedbat/coveragepy/issues/686. Therefore, we will monkeypatch the constructor to add to the thread to `sys.settrace` when we call `run...
init_with_trace
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _disable_throttling(monkeypatch): """Disable qthrottler from superqt. This is sometimes necessary to avoid flaky failures in tests due to dangling qt timers. """ # if this monkeypath fails then you should update path to GenericSignalThrottler monkeypatch.setattr( 'superqt.utils._thr...
Disable qthrottler from superqt. This is sometimes necessary to avoid flaky failures in tests due to dangling qt timers.
_disable_throttling
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def qapp_cls(): """The qapp fixture uses the qapp_cls fixture to select the class to use for create the QApplication instance. As qapp fixture is using more complex logic, we decided not to override it but overwrite the fixture used by it. We need to set attributte before the Q...
The qapp fixture uses the qapp_cls fixture to select the class to use for create the QApplication instance. As qapp fixture is using more complex logic, we decided not to override it but overwrite the fixture used by it. We need to set attributte before the QApplication is created. ...
qapp_cls
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def disable_get_log_level_value(monkeypatch): """Enforce to not set logging to logging.NOTSET, that crashes current tests """ import logging monkeypatch.setattr( 'napari._qt.widgets.qt_logger.get_log_level_value', lambda x: logging.WARNING, )
Enforce to not set logging to logging.NOTSET, that crashes current tests
disable_get_log_level_value
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def _fix_magic_name(monkeypatch, request): """Fix napari.utils.naming.magic_name to handle test as as internal napari module.""" from napari.utils import naming monkeypatch.setitem( naming.magic_name.__kwdefaults__, 'path_prefix', (naming.ROOT_DIR, str(request.fspath)), )
Fix napari.utils.naming.magic_name to handle test as as internal napari module.
_fix_magic_name
python
napari/napari
src/napari/conftest.py
https://github.com/napari/napari/blob/master/src/napari/conftest.py
BSD-3-Clause
def image_reader_to_layerdata_reader( func: Callable[[PathOrPaths], ArrayLike], ) -> ReaderFunction: """Convert a PathLike -> ArrayLike function to a PathLike -> LayerData. Parameters ---------- func : Callable[[PathLike], ArrayLike] A function that accepts a string or list of strings, and ...
Convert a PathLike -> ArrayLike function to a PathLike -> LayerData. Parameters ---------- func : Callable[[PathLike], ArrayLike] A function that accepts a string or list of strings, and returns an ArrayLike. Returns ------- reader_function : Callable[[PathLike], List[LayerData...
image_reader_to_layerdata_reader
python
napari/napari
src/napari/types.py
https://github.com/napari/napari/blob/master/src/napari/types.py
BSD-3-Clause
def _register_types_with_magicgui(): """Register ``napari.types`` objects with magicgui.""" from concurrent.futures import Future from magicgui import register_type from napari.utils import _magicgui as _mgui for type_ in (LayerDataTuple, list[LayerDataTuple]): register_type( ...
Register ``napari.types`` objects with magicgui.
_register_types_with_magicgui
python
napari/napari
src/napari/types.py
https://github.com/napari/napari/blob/master/src/napari/types.py
BSD-3-Clause
def update_console(self, variables): """Update console's namespace with desired variables. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the console's namespace. If a dict, a simple update is done. If a str, the s...
Update console's namespace with desired variables. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the console's namespace. If a dict, a simple update is done. If a str, the string is assumed to have variable na...
update_console
python
napari/napari
src/napari/viewer.py
https://github.com/napari/napari/blob/master/src/napari/viewer.py
BSD-3-Clause
def export_rois( self, rois: list[np.ndarray], paths: str | Path | list[str | Path] | None = None, scale: float | None = None, ): """Export the given rectangular rois to specified file paths. Iteratively take a screenshot of each given roi. Note that 3D rois ...
Export the given rectangular rois to specified file paths. Iteratively take a screenshot of each given roi. Note that 3D rois or taking rois when number of dimensions displayed in the viewer canvas is 3, is currently not supported. Parameters ---------- rois: numpy arra...
export_rois
python
napari/napari
src/napari/viewer.py
https://github.com/napari/napari/blob/master/src/napari/viewer.py
BSD-3-Clause
def screenshot( self, path: str | None = None, *, size: tuple[str, str] | None = None, scale: float | None = None, canvas_only: bool = True, flash: bool = False, ): """Take currently displayed screen and convert to an image array. Parameters ...
Take currently displayed screen and convert to an image array. Parameters ---------- path : str, optional Filename for saving screenshot image. size : tuple of two ints, optional Size (resolution height x width) of the screenshot. By default, the currently ...
screenshot
python
napari/napari
src/napari/viewer.py
https://github.com/napari/napari/blob/master/src/napari/viewer.py
BSD-3-Clause
def close_all(cls) -> int: """ Class method, Close all existing viewer instances. This is mostly exposed to avoid leaking of viewers when running tests. As having many non-closed viewer can adversely affect performances. It will return the number of viewer closed. Retu...
Class method, Close all existing viewer instances. This is mostly exposed to avoid leaking of viewers when running tests. As having many non-closed viewer can adversely affect performances. It will return the number of viewer closed. Returns ------- int ...
close_all
python
napari/napari
src/napari/viewer.py
https://github.com/napari/napari/blob/master/src/napari/viewer.py
BSD-3-Clause
def current_viewer() -> Viewer | None: """Return the currently active napari viewer.""" try: from napari._qt.qt_main_window import _QtMainWindow except ImportError: return None else: return _QtMainWindow.current_viewer()
Return the currently active napari viewer.
current_viewer
python
napari/napari
src/napari/viewer.py
https://github.com/napari/napari/blob/master/src/napari/viewer.py
BSD-3-Clause
def _merge_layer_viewer_sigs_docs(func): """Make combined signature, docstrings, and annotations for `func`. This is a decorator that combines information from `Viewer.__init__`, and one of the `viewer.add_*` methods. It updates the docstring, signature, and type annotations of the decorated function ...
Make combined signature, docstrings, and annotations for `func`. This is a decorator that combines information from `Viewer.__init__`, and one of the `viewer.add_*` methods. It updates the docstring, signature, and type annotations of the decorated function with the merged versions. Parameters ...
_merge_layer_viewer_sigs_docs
python
napari/napari
src/napari/view_layers.py
https://github.com/napari/napari/blob/master/src/napari/view_layers.py
BSD-3-Clause
def _make_viewer_then( add_method: str, /, *args, viewer: Viewer | None = None, **kwargs, ) -> tuple[Viewer, Any]: """Create a viewer, call given add_* method, then return viewer and layer. This function will be deprecated soon (See #4693) Parameters ---------- add_method : str...
Create a viewer, call given add_* method, then return viewer and layer. This function will be deprecated soon (See #4693) Parameters ---------- add_method : str Which ``add_`` method to call on the viewer, e.g. `add_image`, or `add_labels`. *args : list Positional arguments...
_make_viewer_then
python
napari/napari
src/napari/view_layers.py
https://github.com/napari/napari/blob/master/src/napari/view_layers.py
BSD-3-Clause
def limit_numpy1x_threads_on_macos_arm() -> ( None ): # pragma: no cover (macos only code) """Set openblas to use single thread on macOS arm64 to prevent numpy crash. On NumPy version<2 wheels on macOS ARM64 architectures, a BusError is raised, crashing Python, if NumPy is accessed from multiple threa...
Set openblas to use single thread on macOS arm64 to prevent numpy crash. On NumPy version<2 wheels on macOS ARM64 architectures, a BusError is raised, crashing Python, if NumPy is accessed from multiple threads. (See https://github.com/numpy/numpy/issues/21799.) This function uses the global check abov...
limit_numpy1x_threads_on_macos_arm
python
napari/napari
src/napari/_check_numpy_version.py
https://github.com/napari/napari/blob/master/src/napari/_check_numpy_version.py
BSD-3-Clause
def validate_unknown_args(unknown: list[str]) -> dict[str, Any]: """Convert a list of strings into a dict of valid kwargs for add_* methods. Will exit program if any of the arguments are unrecognized, or are malformed. Converts string to python type using literal_eval. Parameters ---------- u...
Convert a list of strings into a dict of valid kwargs for add_* methods. Will exit program if any of the arguments are unrecognized, or are malformed. Converts string to python type using literal_eval. Parameters ---------- unknown : List[str] a list of strings gathered as "unknown" argum...
validate_unknown_args
python
napari/napari
src/napari/__main__.py
https://github.com/napari/napari/blob/master/src/napari/__main__.py
BSD-3-Clause
def _run_plugin_module(mod, plugin_name): """Register `mod` as a plugin, find/create viewer, and run napari.""" from napari import Viewer, run from napari.plugins import plugin_manager plugin_manager.register(mod, name=plugin_name) # now, check if a viewer was created, and if not, create one. ...
Register `mod` as a plugin, find/create viewer, and run napari.
_run_plugin_module
python
napari/napari
src/napari/__main__.py
https://github.com/napari/napari/blob/master/src/napari/__main__.py
BSD-3-Clause
def _maybe_rerun_with_macos_fixes(): """ Apply some fixes needed in macOS, which might involve running this script again using a different sys.executable. 1) Quick fix for Big Sur Python 3.9 and Qt 5. No relaunch needed. 2) Using `pythonw` instead of `python`. This can be used to ensu...
Apply some fixes needed in macOS, which might involve running this script again using a different sys.executable. 1) Quick fix for Big Sur Python 3.9 and Qt 5. No relaunch needed. 2) Using `pythonw` instead of `python`. This can be used to ensure we're using a framework build of P...
_maybe_rerun_with_macos_fixes
python
napari/napari
src/napari/__main__.py
https://github.com/napari/napari/blob/master/src/napari/__main__.py
BSD-3-Clause
def time_zoom(self, n): """Time to zoom in and zoom out.""" if NAPARI_0_4_19: self.viewer.window._qt_viewer.view.camera.zoom( 0.5, center=(0.5, 0.5) ) self.viewer.window._qt_viewer.view.camera.zoom( 2.0, center=(0.5, 0.5) ) ...
Time to zoom in and zoom out.
time_zoom
python
napari/napari
src/napari/benchmarks/benchmark_qt_viewer_image.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_qt_viewer_image.py
BSD-3-Clause
def time_on_mouse_move(self): """Time to drag paint on mouse move.""" if NAPARI_0_4_19: self.viewer.window._qt_viewer.on_mouse_move(self.event) else: self.viewer.window._qt_viewer.canvas._on_mouse_move(self.event)
Time to drag paint on mouse move.
time_on_mouse_move
python
napari/napari
src/napari/benchmarks/benchmark_qt_viewer_labels.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_qt_viewer_labels.py
BSD-3-Clause
def time_load_3d(self, *_): """Time to first render of the layer in 3D.""" self.app.processEvents() self.viewer.dims.ndisplay = 3 self.app.processEvents() self.viewer.dims.ndisplay = 2 self.app.processEvents()
Time to first render of the layer in 3D.
time_load_3d
python
napari/napari
src/napari/benchmarks/benchmark_qt_viewer_labels.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_qt_viewer_labels.py
BSD-3-Clause
def _disable_numba(self): """Replace numba jit functions with pure python functions.""" try: from napari.layers.shapes import ( _accelerated_triangulate_dispatch as _triangle_dispatch, ) except ImportError: return if not hasattr(_trian...
Replace numba jit functions with pure python functions.
_disable_numba
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def warmup_numba() -> None: """Warmup numba cache to avoid the first call being slow.""" try: from napari.layers.shapes._accelerated_triangulate_dispatch import ( warmup_numba_cache, ) except ImportError: return warmup_numba_cache()
Warmup numba cache to avoid the first call being slow.
warmup_numba
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def revert_backend(self): """Restore changes made by select_backend function. Call in teardown step.""" if hasattr(get_settings().experimental, 'triangulation_backend'): get_settings().experimental.triangulation_backend = ( self.prev_settings_new ) else: ...
Restore changes made by select_backend function. Call in teardown step.
revert_backend
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def time_drag_shape(self, _n): """Time to process 5 shape drag events""" # initialize the position and select a shape position = tuple(np.mean(self.layer.data[0], axis=0)) # create events click_event = read_only_mouse_event( type='mouse_press', is_draggin...
Time to process 5 shape drag events
time_drag_shape
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def time_select_shape(self, _n): """Time to process shape selection events""" position = tuple(np.mean(self.layer.data[1], axis=0)) # create events click_event = read_only_mouse_event( type='mouse_press', is_dragging=False, modifiers=[], p...
Time to process shape selection events
time_select_shape
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def skip_triangle_backend( _n_shapes, _n_points, _shape_type, triangulation_backend ): """This is a helper function to skip triangle testing in polygon with holes case if the bugfix is not available. It may be removed after release on napari 0.6.0. """ from napari.layers.shapes import _shapes_u...
This is a helper function to skip triangle testing in polygon with holes case if the bugfix is not available. It may be removed after release on napari 0.6.0.
skip_triangle_backend
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def non_convex_no_self_intersection_polygons( n_shapes=5_000, n_points=32 ) -> list[np.ndarray]: """ Create a set of non-convex coordinates Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape """ rng = np.rand...
Create a set of non-convex coordinates Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape
non_convex_no_self_intersection_polygons
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def convex_polygons(n_shapes=5_000, n_points=32) -> list[np.ndarray]: """ Create a set of convex coordinates Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape """ rng = np.random.default_rng(0) radius = 500 ...
Create a set of convex coordinates Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape
convex_polygons
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def polygons_with_hole(n_shapes=5_000, n_points=32) -> list[np.ndarray]: """ Create a set of polygon with hole Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape """ rng = np.random.default_rng(0) assert n_po...
Create a set of polygon with hole Parameters ---------- n_shapes : int Number of shapes to create n_points : int Number of virtex of each shape
polygons_with_hole
python
napari/napari
src/napari/benchmarks/benchmark_shapes_layer.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/benchmark_shapes_layer.py
BSD-3-Clause
def _generate_ball(radius: int, ndim: int) -> np.ndarray: """Generate a ball of given radius and dimension. Parameters ---------- radius : int Radius of the ball. ndim : int Dimension of the ball. Returns ------- ball : ndarray of uint8 Binary array of the hyper...
Generate a ball of given radius and dimension. Parameters ---------- radius : int Radius of the ball. ndim : int Dimension of the ball. Returns ------- ball : ndarray of uint8 Binary array of the hyper ball.
_generate_ball
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def _generate_density(radius: int, ndim: int) -> np.ndarray: """Generate gaussian density of given radius and dimension.""" shape = (2 * radius + 1,) * ndim coords = np.indices(shape) - radius dist = np.sqrt(np.sum(coords**2 / ((radius / 4) ** 2), axis=0)) res = np.exp(-dist) res[res < 0.02] = 0...
Generate gaussian density of given radius and dimension.
_generate_density
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def _structure_at_coordinates( shape: tuple[int], coordinates: np.ndarray, structure: np.ndarray, *, multipliers: Sequence = itertools.repeat(1), dtype=None, reduce_fn: Callable[ [np.ndarray, np.ndarray, np.ndarray | None], np.ndarray ], ): """Update data with structure at gi...
Update data with structure at given coordinates. Parameters ---------- data : ndarray Array to update. coordinates : ndarray Coordinates of the points. The structures will be added at these points (center). structure : ndarray Array with encoded structure. For exampl...
_structure_at_coordinates
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def _update_data_with_mask(data, struct, out=None): """Update ``data`` with ``struct`` where ``struct`` is nonzero.""" # these branches are needed because np.where does not support # an out= keyword argument if out is None: return np.where(struct, struct, data) else: # noqa: RET505 ...
Update ``data`` with ``struct`` where ``struct`` is nonzero.
_update_data_with_mask
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def _smallest_dtype(n: int) -> np.dtype: """Find the smallest dtype that can hold n values.""" for dtype in [np.uint8, np.uint16, np.uint32, np.uint64]: if np.iinfo(dtype).max >= n: return dtype break else: raise ValueError(f'{n=} is too large for any dtype.')
Find the smallest dtype that can hold n values.
_smallest_dtype
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def labeled_particles( shape: Sequence[int], dtype: np.dtype | None = None, n: int = 144, seed: int | None = None, return_density: bool = False, ) -> np.ndarray | tuple[np.ndarray, np.ndarray, np.ndarray]: """Generate labeled blobs of given shape and dtype. Parameters ---------- sha...
Generate labeled blobs of given shape and dtype. Parameters ---------- shape : Sequence[int] Shape of the resulting array. dtype : Optional[np.dtype] Dtype of the resulting array. n : int Number of blobs to generate. seed : Optional[int] Seed for the random numbe...
labeled_particles
python
napari/napari
src/napari/benchmarks/utils.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/utils.py
BSD-3-Clause
def split_identifier(value: str) -> BenchmarkIdentifier: """Split a string into a module and class identifier.""" parts = value.split('.') if len(parts) != 3: raise argparse.ArgumentError( "Benchmark identifier should be in the form 'module.class.benchmark'" ) return Benchmar...
Split a string into a module and class identifier.
split_identifier
python
napari/napari
src/napari/benchmarks/__main__.py
https://github.com/napari/napari/blob/master/src/napari/benchmarks/__main__.py
BSD-3-Clause