### ROISelector Attributes and Initialization Example Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/roi_selector Demonstrates the key attributes of the ROISelector class, including `images`, `rois`, `categories`, and `multi`. It also shows how to enable multi-ROI selection and provides an example of accessing the defined ROIs. ```python >>> rs.multi = True >>> rs.rois [{'cat1': RectangleROI(top_left=(52.5, 27.8), bottom_right=(117.2, 68.8)), 'cat2': RectangleROI(top_left=(25.3, 35.7), bottom_right=(60.8, 67.2))}, {'cat1': PathROI(<48 vertices>), 'cat2': PathROI(<30 vertices>)}] ``` -------------------------------- ### SDT Library - Q Module Source: https://schuetzgroup.github.io/sdt-python/genindex Details components starting with 'Q' in the SDT library, specifically focusing on the query and query_particles methods of SmFRETAnalyzer. ```APIDOC ## SDT Library - Q Module ### Description This section covers components starting with 'Q' in the SDT library. ### Methods: - **query()** (sdt.fret.SmFRETAnalyzer method) - **query_particles()** (sdt.fret.SmFRETAnalyzer method) ``` -------------------------------- ### Global Configuration Dictionary (Python) Source: https://schuetzgroup.github.io/sdt-python/helper A global configuration dictionary used for various settings within the sdt library. The example shows a default list for 'channel_names'. ```python sdt.config.rc = { 'channel_names': ['channel1', 'channel2'] } ``` -------------------------------- ### Get Files Recursively with sdt.io.get_files() Source: https://schuetzgroup.github.io/sdt-python/io Shows how to recursively search for files matching a regular expression within a subdirectory using `get_files()`. It returns a list of matching file names and extracted IDs. ```python >>> names, ids = get_files(r"^image_.*_(\d{3}).tif$", "subdir") >>> names ['image_xxx_001.tif', 'image_xxx_002.tif', 'image_yyy_003.tif'] >>> ids [(1,), (2,), (3,)] ``` -------------------------------- ### Fit Affine Transformation to Point Pairs Source: https://schuetzgroup.github.io/sdt-python/optimize This example demonstrates how to fit an affine transformation between two sets of points using the `AffineModel`. Given corresponding point coordinates, the `fit` method of `AffineModel` can be used to find the best-fitting transformation, represented by a transformation matrix. ```python from sdt import optimize # Assuming xy and xy_t are numpy arrays of shape (n_points, n_dimensions) # where xy[i, :] is a point and xy_t[i, :] is its transformed counterpart. r = optimize.AffineModel().fit(xy_t, xy) print(r.transform) ``` -------------------------------- ### Get Settings - Python Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/locator Retrieves the current algorithm and options settings from the object. It returns a dictionary containing the 'algorithm' and 'options' attributes. This function has no input parameters. ```python def get_settings(self): """Get all settings (algorithm and options) Returns ------- dict :py:attr:`algorithm` and :py:attr:`options` attributes are accessible via the "algorithm" and "options" keys, respectively. """ return {"algorithm": self.algorithm, "options": self.options} ``` -------------------------------- ### Gaussian1DModel and Gaussian2DModel Fitting Source: https://schuetzgroup.github.io/sdt-python/optimize This section describes how to fit 1D and 2D Gaussian functions to data using the `Gaussian1DModel` and `Gaussian2DModel` classes from the `sdt-python` library. It includes examples of creating models, guessing initial parameters, fitting the models to data, and evaluating the fitted models. ```APIDOC ## Gaussian1DModel and Gaussian2DModel Fitting ### Description This documentation explains how to use `Gaussian1DModel` and `Gaussian2DModel` for fitting 1D and 2D Gaussian functions to data. It leverages the `lmfit` package for the actual fitting process. ### Method This is not an API endpoint, but a programmatic interface. ### Endpoint N/A ### Parameters #### Request Body N/A ### Request Example ```python # 1D Gaussian Fit Example import numpy from sdt import optimize x = numpy.arange(100) y = numpy.exp(-(x - 50)**2 / 8) m = optimize.Gaussian1DModel() p = m.guess(y, x) res = m.fit(y, params=p, x=x) print(res.best_values) print(res.eval(x=50.3)) # 2D Gaussian Fit Example coords = numpy.indices((50, 100)) x, y = coords center = numpy.array([[20, 40]]).T centered_flat = coords.reshape((2, -1)) - center cov = numpy.linalg.inv(numpy.array([[8, 0], [0, 18]])) z = 2 * numpy.exp(-numpy.sum(centered_flat * (cov @ centered_flat), axis=0)) z = z.reshape(x.shape) m = optimize.Gaussian2DModel() p = m.guess(z, x, y) res = m.fit(z, params=p, x=x, y=y) print(res.best_values) print(res.eval(x=20.5, y=40.5)) ``` ### Response #### Success Response (200) - **best_values** (dict) - A dictionary containing the fitted parameters of the Gaussian model. - **eval() output** (float) - The evaluated value of the fitted Gaussian function at the specified point. #### Response Example ```json # 1D Fit Example Output: {'offset': 4.4294473935549931e-136, 'sigma': 1.9999999999999996, 'center': 50.0, 'amplitude': 1.0} 0.98881304461123321 # 2D Fit Example Output: {'rotation': 0.0, 'offset': 2.6045547770814313e-55, 'sigmay': 3.0, 'centery': 40.0, 'sigmax': 1.9999999999999996, 'centerx': 20.0, 'amplitude': 2.0} 1.9117294272505907 ``` ``` -------------------------------- ### Graceful numba import and usage Source: https://schuetzgroup.github.io/sdt-python/helper Demonstrates how to use the `sdt.helper.numba` submodule to avoid a hard dependency on the numba library. This allows code using numba decorators like `jit` to be imported even if numba is not installed. The `numba_available` flag can be used to check for numba's presence. ```python >>> from sdt.helper import numba >>> @numba.jit(nopython=True) # This will not raise an error ... def f(x): ... return x ``` ```python >>> from sdt.helper import numba >>> if numba.numba_available: ... # numba is installed ... else: ... # numba is not installed ``` -------------------------------- ### Example: lmfit Model Fitting with exp_sum_lmfit (Python) Source: https://schuetzgroup.github.io/sdt-python/funcs Demonstrates how to use the exp_sum_lmfit function within the lmfit framework for curve fitting. It involves setting up parameter hints, creating parameters, and performing the fit using provided x and y data. ```python import numpy import lmfit # Assume funcs.exp_sum_lmfit is defined elsewhere and imported # from sdt import funcs # Example import num_exp = 2 # Example: sum of 2 exponentials + offset x = numpy.array(...) # x values y = numpy.array(...) # y values mant_names = ["mant{}".format(i) for i in range(num_exp)] exp_names = ["exp{}".format(i) for i in range(num_exp)] m = lmfit.Model(funcs.exp_sum_lmfit) # Use the actual imported function m.set_param_hint("offset", value=1.0) for m_name in mant_names: m.set_param_hint(m_name, value=0.1) for e_name in exp_names: m.set_param_hint(e_name, value=-0.5) p = m.make_params() f = m.fit(y, params=p, x=x) # Pass 'x' as the independent variable argument expected by exp_sum_lmfit ``` -------------------------------- ### Initialize and Use Thresholder for Image Thresholding Source: https://schuetzgroup.github.io/sdt-python/nbui Shows how to initialize the Thresholder UI for image thresholding. It includes setting image data, interacting with the UI to find parameters, and retrieving the thresholding algorithm and options. The result can be applied to an image using the provided function. ```python >>> %matplotlib widget >>> # Assume img_list is a list of 2D arrays containing image data >>> th = Thresholder(img_list) >>> th >>> th.algorithm "adaptive" >>> par = th.options >>> par {'block_size': 65, 'c': -5.0, 'smooth': 1.5, 'method': 'mean'} >>> mask = th.func(img_list[0], **par) # image.adaptive_thresh ``` -------------------------------- ### Get Changepoint Probabilities - Python Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/changepoint/bayes_online This method retrieves the calculated changepoint probabilities. It looks a specified number of data points into the past to enhance robustness. The implementation inherently assigns a 100% probability to the start of the signal, which might need filtering. ```python def get_probabilities(self, past): """Get changepoint probabilities To calculate the probabilities, look a number of data points (as given by the `past` parameter) into the past to increase robustness. There is always 100% probability that there was a changepoint at the start of the signal due to how the algorithm is implemented; one should filter that out if necessary or use :py:meth:`find_changepoints`, which does that for you. Parameters ---------- past : int How many datapoints into the past to look. Larger values will increase robustness, but also latency, meaning that if `past` equals some number `x`, a changepoint within the last `x` data points cannot be detected. Returns ------- numpy.ndarray Changepoint probabilities as a function of time. The length of the array equals the number of datapoints - `past`. """ return np.array([p[past] for p in self.probabilities[past:-1]]) ``` -------------------------------- ### Initialize and Use Locator for Molecule Localization Source: https://schuetzgroup.github.io/sdt-python/nbui Demonstrates initializing the Locator UI for single molecule localization. It covers setting image data, displaying the UI, and retrieving localization parameters. This class requires the ipympl backend and is experimental. The retrieved parameters can be passed to localization functions. ```python >>> %matplotlib widget >>> locator = nbui.Locator() >>> locator.input = img_array # assuming this is an array of pixels >>> locator >>> files = sorted(pathlib.Path().glob("*.tif")) >>> locator.images = files >>> locator.algorithm "3D-DAOSTORM" >>> par = locator.options >>> par {'radius': 1.0, 'model': '2d', 'threshold': 800.0, 'find_filter': 'Cg', 'find_filter_opts': {'feature_radius': 3}, 'min_distance': None, 'size_range': None} >>> data = locator.batch_func(img_files, **par) # loc.daostorm_3d.batch ``` -------------------------------- ### Pipeline Decorator Example: Color Channel Extraction Source: https://schuetzgroup.github.io/sdt-python/helper Illustrates applying the pipeline decorator to a function for image processing. The 'color_channel' function is made lazy, allowing it to operate on image data lazily. An example shows how to preserve the original docstring. ```python @pipeline def color_channel(image, channel): return image[channel, :, :] @pipeline(retain_doc=True) def color_channel_preserved_doc(image, channel): return image[channel, :, :] ``` -------------------------------- ### Locator Class Initialization and Methods Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/loc/daostorm_3d/api Outlines the constructor and core methods of the 'Locator' class, including initialization with model and pixel size, and methods for locating peaks, batch processing, ROI-restricted operations, and saving/loading settings. ```python def __init__(self, model="2d", pixel_size=None, engine="numba"): pass def locate(self, raw_image): pass def batch(self, frames): pass def locate_roi(self, raw_image, roi): pass def batch_roi(self, frames, roi): pass def save_settings(self, file): pass @classmethod def load_settings(cls, file): pass ``` -------------------------------- ### Multivariate Changepoint Detection Setup (Python) Source: https://schuetzgroup.github.io/sdt-python/changepoint Prepares multivariate time series data for changepoint detection. Data is structured as a 2D array where each column represents a different time series. This setup is compatible with all detection algorithms. ```python import numpy as np # changepoint at t = 5 data1 = numpy.concatenate([numpy.random.normal(0, 0.1, 5), numpy.random.normal(2.5, 0.1, 15)]) # Another dataset with a changepoint at t = 10 data2 = numpy.concatenate([numpy.random.normal(1.5, 0.1, 10), numpy.random.normal(0, 0.1, 10)]) # multivariate data, one set per column data_m = numpy.array([data1, data2]).T ``` -------------------------------- ### Open and Manipulate Image Sequences with sdt.io Source: https://schuetzgroup.github.io/sdt-python/io Demonstrates opening an image sequence, creating substacks without loading data, and accessing individual frames lazily. The `ImageSequence` class allows for efficient handling of large image data. ```python >>> seq = ImageSequence("images.SPE").open() >>> len(seq) 100 >>> seq2 = seq[::2] # No data is loaded here >>> len(seq2) 50 >>> frame = seq2[1] # Load frame 1 (i.e., frame 2 in the original `seq`) >>> frame.shape (100, 150) >>> seq.close() ``` -------------------------------- ### Get the area of the mask Source: https://schuetzgroup.github.io/sdt-python/roi Calculates and returns the total area covered by True pixels in the boolean mask. ```python from sdt.roi import MaskROI import numpy as np # Example boolean mask mask_array = np.array([[True, True, False], [True, False, False]]) # Create a MaskROI object mask_roi = MaskROI(mask_array) # Get the area of the mask mask_area = mask_roi.area ``` -------------------------------- ### Python ImageSelector and ThresholderModule Initialization Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/thresholder Illustrates the initialization of ImageSelector and ThresholderModule classes, which are fundamental for managing image inputs and applying thresholding algorithms. It sets up event observers for changes in image selection and mask generation, and links traits for algorithm and options. ```python algorithm: str = traitlets.Enum(values=[A.name for A in algorithms]) """Name of the algorithm""" options: Dict = traitlets.Dict() """Options to the thresholding function""" def __init__(self, images: Union[Sequence, Dict] = []): """Parameters --------- images List of image (sequences) to populate to pass to :py:class:`ImageSelector` instance. """ self.image_selector = ImageSelector(images) self.thresholder_module = ThresholderModule() fig, ax = plt.subplots() self.image_display = ImageDisplay(ax) super().__init__([self.image_selector, self.thresholder_module, self.image_display]) self.image_selector.observe(self._image_changed, "output") self.thresholder_module.observe(self._mask_changed, "output") traitlets.link((self.thresholder_module, "algorithm"), (self, "algorithm")) traitlets.link((self.thresholder_module, "options"), (self, "options")) self._artists = [] self._image_changed() ``` -------------------------------- ### Label Mobile Sections Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/motion/immobilization Assigns a unique (negative) number to each mobile section of a track, starting at -2. This function modifies the DataFrame in place and also returns it. ```APIDOC ## POST /label_mobile ### Description Assigns a unique (negative) number to each mobile section of a track, starting at -2. This function modifies the DataFrame in place and also returns it. ### Method POST ### Endpoint /label_mobile ### Parameters #### Request Body - **tracks** (DataFrame) - Required - Tracking data with an `immob` column where all mobile sections of tracks are assigned `-1`. - **engine** (string) - Optional - The engine to use for labeling. Options: "numba", "python". Defaults to "numba". - **columns** (Mapping) - Optional - Override default column names. Relevant name is `particle`. ### Request Example ```json { "tracks": "", "engine": "numba", "columns": { "particle": "particle_id" } } ``` ### Response #### Success Response (200) - **tracks** (DataFrame) - The input `tracks` DataFrame with the updated `immob` column. #### Response Example ```json { "tracks": "" } ``` ``` -------------------------------- ### Initialize ROI Widget with ipywidgets Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/channel_splitter Initializes a widget for managing image ROIs. It sets up tabbed interfaces for different channels, buttons for splitting and swapping, and a checkbox for uniform ROI sizing. Dependencies include ipywidgets, traitlets, threading, and numpy. ```python def __init__(self, n_channels=1): # Tabbed interface for different channels self._dimension_tabs = ipywidgets.Tabs() self._dimension_tabs.set_trait('selected_index', 0) # Checkbox to force same size on all channels self._same_size_box = ipywidgets.Checkbox( description="Same size", value=True) traitlets.link((self, "same_size"), (self._same_size_box, "value")) # Buttons for splitting horizontally and vertically self._split_hor_button = ipywidgets.Button( description="split horizontally") self._split_hor_button.on_click(self._split_hor) self._split_ver_button = ipywidgets.Button( description="split vertically") self._split_ver_button.on_click(self._split_ver) # Button for swapping channels (i.e., reversing their order) self._swap_button = ipywidgets.Button(description="swap channels") self._swap_button.on_click(self._swap_chan) super().__init__([self._dimension_tabs, ipywidgets.HBox([self._split_hor_button, self._split_ver_button, self._swap_button, self._same_size_box]), self.image_display]) self._n_channels = n_channels self.channel_names = ["channel {}".format(i) for i in range(n_channels)] self._update_extents_lock = threading.Lock() self._update_rois_lock = threading.Lock() self._active_channel_changed() ``` -------------------------------- ### Temporarily Change Directory with sdt.io.chdir() Source: https://schuetzgroup.github.io/sdt-python/io Explains the usage of `chdir()` as a context manager to temporarily change the current working directory. The directory is restored automatically upon exiting the `with` block. ```python >>> with chdir("subdir"): ... # here the working directory is "subdir" >>> # here we are back ``` -------------------------------- ### GET /sdt.loc.get_raw_features Source: https://schuetzgroup.github.io/sdt-python/loc Retrieves raw image data surrounding localized features. For each localization, it returns a square of pixels centered on the feature's position. ```APIDOC ## GET /sdt.loc.get_raw_features ### Description Get raw image data surrounding localizations. For each feature, return the raw image data in the proximity to the feature position. ### Method GET ### Endpoint /sdt.loc.get_raw_features ### Parameters #### Query Parameters - **loc_data** (pandas.DataFrame) - Required - Localization data. Index must be unique. - **img_data** (list-like of numpy.ndarray) - Required - Image sequence. - **size** (int) - Required - For each feature, return a square of `2 * size + 1` pixels. - **columns** (dict) - Optional - Override default column names. Expected keys are 'coords' (list of column names for coordinates) and 'time' (string for time column name). ### Request Example ```json { "loc_data": "[pandas.DataFrame]", "img_data": "[list-like of numpy.ndarray]", "size": 5, "columns": { "coords": ["x", "z"], "time": "alt_frame" } } ``` ### Response #### Success Response (200) - **OrderedDict** - Image data for features. Uses the localization data indices as keys and square numpy.ndarrays of `2 * size + 1` pixels as values. #### Response Example ```json { "feature_index_1": "[numpy.ndarray]", "feature_index_2": "[numpy.ndarray]" } ``` ``` -------------------------------- ### SDT Library - R Module Source: https://schuetzgroup.github.io/sdt-python/genindex Lists classes, attributes, and methods starting with 'R' in the SDT library, including RANSAC, RectangleROI, RectMask, Registrator, and various reset/restore functionalities. ```APIDOC ## SDT Library - R Module ### Description This section outlines components starting with 'R' in the SDT library. ### Classes, Attributes, and Methods: - **raise_in_thread()** (in module sdt.helper) - **random_state** (sdt.optimize.RANSAC attribute) - **RANSAC** (class in sdt.optimize) - **rc** (in module sdt.config) - **reader_args** (sdt.io.ImageSequence attribute) - **RectangleROI** (class in sdt.roi) - **RectMask** (class in sdt.image) - **register_yaml_class()** (in module sdt.io.yaml) - **Registrator** (class in sdt.multicolor) - **registrator** (sdt.fret.SmFRETTracker attribute) - **renumber_frames()** (sdt.multicolor.FrameSelector method) - **reset()** (sdt.changepoint.BayesOnline method) - (sdt.changepoint.StudentT method) - **reset_filters()** (sdt.fret.SmFRETAnalyzer method) - **reset_origin()** (sdt.roi.MaskROI method) - (sdt.roi.PathROI method) - (sdt.roi.ROI method) - **restore_frame_numbers()** (sdt.multicolor.FrameSelector method) - **ROI** (class in sdt.roi) - **rois** (sdt.nbui.ChannelSplitter attribute) - (sdt.nbui.ROISelector attribute) - **ROISelector** (class in sdt.nbui) ``` -------------------------------- ### sdt.io.chdir Source: https://schuetzgroup.github.io/sdt-python/io Provides a context manager to temporarily change the current working directory. Upon exiting the 'with' block, the original directory is restored. ```APIDOC ## sdt.io.chdir ### Description Context manager to temporarily change the working directory. ### Method Context Manager ### Endpoint N/A (Context Manager) ### Parameters #### Path Parameters * **path** (str) - Required - Path of the directory to change to. `os.path.expanduser()` is called on this. ### Request Example ```python with chdir("subdir"): # here the working directory is "subdir" # here we are back ``` ### Response N/A (Context Manager) ``` -------------------------------- ### Get Length of Image Sequence in Python Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/io/image_sequence The `__len__` method returns the number of frames currently represented by the `ImageSequence` object, based on the `_len` attribute. ```python def __len__(self): return self._len ``` -------------------------------- ### SDT Library - S Module Source: https://schuetzgroup.github.io/sdt-python/genindex Details components starting with 'S' in the SDT library, encompassing serialization utilities, various modules, and specific classes/methods like Singleton, Slicerator, SmFRETAnalyzer, and StudentT. ```APIDOC ## SDT Library - S Module ### Description This section lists components starting with 'S' in the SDT library. ### Utilities and Modules: - **safe_dump()** (in module sdt.io.yaml) - **safe_dump_all()** (in module sdt.io.yaml) - **safe_load()** (in module sdt.io.yaml) - **safe_load_all()** (in module sdt.io.yaml) - **SafeDumper** (class in sdt.io.yaml) - **SafeLoader** (class in sdt.io.yaml) - **same_size** (sdt.nbui.ChannelSplitter attribute) - **save()** (in module sdt.io) - (sdt.flatfield.Corrector method) - (sdt.loc.z_fit.Parameters method) - (sdt.multicolor.Registrator method) - **save_as_tiff()** (in module sdt.io) - **save_pt2d()** (in module sdt.io) - **save_trc()** (in module sdt.io) - **sdt** (module) - **sdt.brightness** (module) - **sdt.changepoint** (module) - **sdt.config** (module) - **sdt.flatfield** (module) - **sdt.fret** (module) - **sdt.funcs** (module) - **sdt.helper** (module) - **sdt.image** (module) - **sdt.io** (module) - **sdt.loc** (module) - **sdt.loc.cg** (module) - **sdt.loc.daostorm_3d** (module) - **sdt.loc.z_fit** (module) - **sdt.motion** (module) - **sdt.multicolor** (module) - **sdt.nbui** (module) - **sdt.optimize** (module) - **sdt.plot** (module) - **sdt.roi** (module) - **sdt.sim** (module) - **sdt.spatial** (module) - **segment_stats()** (in module sdt.changepoint) - **select()** (sdt.multicolor.FrameSelector method) - **selected** (sdt.nbui.FileDialog attribute) - **set_columns()** (in module sdt.config) - **set_data()** (sdt.changepoint.ConstPrior method) - (sdt.changepoint.CostL1 method) - (sdt.changepoint.CostL2 method) - (sdt.changepoint.FullCovObsLikelihood method) - (sdt.changepoint.GaussianObsLikelihood method) - (sdt.changepoint.GeometricPrior method) - (sdt.changepoint.IfmObsLikelihood method) - **set_rois()** (sdt.nbui.ROISelector method) - **set_settings()** (sdt.nbui.Locator method) - **show_file_buttons** (sdt.nbui.ImageSelector property) - **sigma_from_z()** (sdt.loc.z_fit.Parameters method) - **simulate_brownian()** (in module sdt.sim) - **simulate_gauss()** (in module sdt.sim) - **Singleton** (class in sdt.helper) - **Slicerator** (class in sdt.helper) - **smallest_enclosing_circle()** (in module sdt.spatial) - **smfret_hist()** (in module sdt.fret) - **smfret_scatter()** (in module sdt.fret) - **SmFRETAnalyzer** (class in sdt.fret) - **SmFRETTracker** (class in sdt.fret) - **split_dataframe()** (in module sdt.helper) - **std()** (sdt.brightness.Distribution method) - **StepFunction** (class in sdt.funcs) - **StudentT** (class in sdt.changepoint) ``` -------------------------------- ### Initialize ROI Selector with Images Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/roi_selector Demonstrates how to initialize the ROISelector with a dictionary of images. It requires matplotlib widget backend and involves loading image data. The selection is then displayed as a widget. ```python from glob import glob from pathlib import Path import sys import numpy as np import pytest import cv2 # Add project root to path project_root = Path(__file__).parent.parent.parent sys.path.insert(0, str(project_root)) from sdt.convenience import io from sdt.select_roi import ROISelector def test_roi_selector_init(): """Test ROISelector initialization and basic usage.""" # Mock image loading image_data = np.random.rand(100, 100, 3) * 255 image_data = image_data.astype(np.uint8) class MockImageSequence: def __init__(self, data): self._data = data def open(self): return [self._data] io.ImageSequence = MockImageSequence # Create dummy files for glob to find with open("dummy_image1.tif", "w") as f: f.write("dummy content") with open("dummy_image2.tif", "w") as f: f.write("dummy content") names = sorted(glob("*.tif")) imgs = {n: io.ImageSequence(n).open()[0] for n in names} rs = ROISelector(imgs) assert isinstance(rs, ROISelector) assert len(rs.roi_selectors) > 0 # Clean up dummy files Path("dummy_image1.tif").unlink() Path("dummy_image2.tif").unlink() # Restore original ImageSequence if necessary # (This depends on how io.ImageSequence is managed in the actual library) # Example of setting categories rs.categories = ["cell", "background"] assert rs.categories == ["cell", "background"] # Example of setting auto_category rs.auto_category = True assert rs.auto_category is True # Example of multi-roi selection rs.multi = True assert rs.multi is True # The rs object itself would be displayed in a notebook # For testing, we can just check it was created # To run this test: # 1. Ensure you have pytest installed (`pip install pytest`) # 2. Save the code as a Python file (e.g., `test_roi.py`) # 3. Run pytest from your terminal in the same directory: # pytest # Note: The original example uses %matplotlib widget, which is for interactive # notebook environments and might not be directly applicable in a script test. # The mocking of io.ImageSequence is done to make the example runnable # without actual image files. ``` -------------------------------- ### ROISelector Initialization and Linking Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/roi_selector Initializes the ROISelector with image display and ROI selection modules. It establishes traitlet links between the image selector, ROI selector, and the ROISelector instance itself. Dependencies include matplotlib, ipywidgets, and custom modules like ImageSelector, ROISelectorModule, and ImageDisplay. ```python def __init__(self, images: Union[Sequence, Dict] = [], **kwargs): """Parameters --------- images List of image (sequences) to populate :py:attr:`images`. **kwargs Passed to parent ``__init__``. """ fig, ax = plt.subplots() self.image_selector = ImageSelector() self.image_selector.show_file_buttons = True self.roi_selector_module = ROISelectorModule(ax) self.image_display = ImageDisplay(ax) super().__init__([self.image_selector, self.roi_selector_module, ipywidgets.HBox([self.image_display])]) self.image_selector.observe(self._cur_image_changed, "output") traitlets.link((self.image_selector, "images"), (self, "images")) self.roi_selector_module.observe(self._roi_drawn, "rois") traitlets.directional_link((self.roi_selector_module, "categories"), (self, "categories")) traitlets.link((self.roi_selector_module, "multi"), (self, "multi")) self.image_selector.images = images ``` -------------------------------- ### Get DataFrame mask for localizations Source: https://schuetzgroup.github.io/sdt-python/roi Generates a boolean array indicating which localizations from a pandas DataFrame fall within the defined mask. It allows overriding default column names for coordinates. ```python import pandas as pd # Assuming mask_roi is an initialized MaskROI object and df is a pandas DataFrame # with localization data (e.g., columns 'x', 'y') # Example DataFrame data = {'x': [11, 12, 15, 25], 'y': [21, 23, 30, 40]} df = pd.DataFrame(data) # Get the boolean mask for localizations localization_mask = mask_roi.dataframe_mask(df) # Example with custom column names custom_columns = {'coords': ['x', 'y']} localization_mask_custom = mask_roi.dataframe_mask(df, columns=custom_columns) ``` -------------------------------- ### Pipeline Example: Multiply Elements by Two Source: https://schuetzgroup.github.io/sdt-python/helper Demonstrates the creation and usage of the Pipeline class for lazy evaluation. An ancestor list is processed by a lambda function that multiplies each element by two, showing how indexing triggers evaluation. ```python ancestor = [0, 1, 2, 3, 4] times_two = Pipeline(lambda x: 2*x, ancestor) print(times_two[3]) ``` -------------------------------- ### Get Undefined ROIs Structure Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/roi_selector Generates a dictionary structure representing undefined ROIs for all categories. If no categories are defined, it returns `None`. Otherwise, it returns a dictionary where each category maps to a list containing `None`. ```python def get_undefined_rois(self) -> Union[None, List, Dict]: """Get an entry for :py:attr:`rois` specifying undefined ROIs If no categories have been defined, this is simply `None`. Else this is a dict mapping category names to `None`. """ return self._unnormalize_rois( {c: [None] for c in (self.categories or [None])}) ``` -------------------------------- ### Initialize and Use ROISelector for Drawing ROIs Source: https://schuetzgroup.github.io/sdt-python/nbui Illustrates the initialization and usage of the ROISelector UI for drawing regions of interest on images. It covers loading images, defining categories, and enabling/disabling features like automatic category selection and multi-ROI selection. ```python >>> %matplotlib widget >>> names = sorted(glob("*.tif")) >>> imgs = {n: io.ImageSequence(n).open()[0] ... for n in names} # 1st frame from each sequence >>> rs = ROISelector(imgs) >>> rs >>> rs.categories = ["cell", "background"] >>> rs.auto_category = True >>> # Via `multi`, selection of multiple ROIs per image and category can be enabled and disabled. ``` -------------------------------- ### Otsu Thresholding UI with ipywidgets Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/thresholder Provides a UI using ipywidgets.HBox for Otsu's thresholding method. It allows adjustment of a multiplication factor and a smoothing parameter. The UI updates an 'options' dictionary suitable for the sdt.image.otsu_thresh function. ```python class OtsuOptions(ipywidgets.HBox): """UI for setting options for :py:func:`sdt.image.otsu_thresh`""" name = "otsu" """Method name ("otsu")""" func = image.otsu_thresh """Function that does the processing (:py:func:`sdt.image.otsu_thresh`)""" def __init__(self, *args, **kwargs): """Parameters ---------- *args, **kwargs Passed to the :py:class:`HBox` constructor after the list of children """ self._factor_sel = ipywidgets.FloatText( value=1, step=0.1, description="mult.") self._smoothing_sel = ipywidgets.FloatText( value=1.5, description="smooth", step=0.1) super().__init__([self._factor_sel, self._smoothing_sel], *args, **kwargs) for w in (self._factor_sel, self._smoothing_sel): w.observe(self._options_from_ui, "value") self._options_from_ui() self.observe(self._options_to_ui, "options") options: Dict = traitlets.Dict() """Options which can be passed directly to :py:func:`sdt.image.otsu_thresh` """ def _options_from_ui(self, change=None): """Set :py:attr:`options` from UI elements""" o = {"factor": self._factor_sel.value, "smooth": self._smoothing_sel.value} self.options = o def _options_to_ui(self, change=None): """Set UI element values from :py:attr:`options`""" o = self.options self._factor_sel.value = o["factor"] self._smoothing_sel.value = o["smooth"] ``` -------------------------------- ### Get Frame Numbers by Excitation Type (Python) Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/multicolor/frame_selector Retrieves the frame numbers that correspond to a specified excitation type within an evaluated sequence. It utilizes an internal mask-finding function to filter the frame numbers. ```python @staticmethod def _find_numbers(eval_seq: np.ndarray, frame_nos: np.ndarray, which: Union[str, Iterable[str]]) -> np.ndarray: """Find frames of certain type in list of frames, return numbers Parameters ---------- eval_seq Evaluated excitation sequence (array of characters). See :py:meth:`eval_seq`. frame_nos Array of frame numbers from which frames should be selected which Excitation type(s), one or multiple characters out of :py:attr:`excitation_seq`. Returns ------- Elements of `frame_nos` that are of an excitation type given by `which`. """ return frame_nos[__class__._find_mask(eval_seq, frame_nos, which)] ``` -------------------------------- ### Load Registrator Parameters (Python) Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/multicolor/registrator Loads Registrator parameters from a file and constructs a Registrator instance. Supports NPZ, MAT, and WRP formats. WRP format requires specific structure and calculations for parameters. Depends on NumPy and SciPy. ```python @classmethod def load(cls, file: Union[BinaryIO, str, Path], fmt: str = "npz", key: Tuple[str, str] = ("chromatic_param1", "chromatic_param2") ) -> "Registrator": """Read paramaters from a file and construct a `Registrator` Parameters ---------- file File name or an open file-like object to load data from. fmt Format to save data. Either numpy ("npz") or MATLAB ("mat") or `determine_shiftstretch`'s wrp ("wrp"). Defaults to "npz". Returns ------- A class instance with the parameters read from the file. Other parameters ---------------- key Name of the variables in the saved file (does not apply to "wrp"). Defaults to ("chromatic_param1", "chromatic_param2"). """ corr = cls(None, None) if fmt == "npz": npz = np.load(file) corr.parameters1 = npz[key[0]] corr.parameters2 = npz[key[1]] elif fmt == "mat": mat = scipy.io.loadmat(file) corr.parameters1 = mat[key[0]] corr.parameters2 = mat[key[1]] elif fmt == "wrp": d = scipy.io.loadmat(file, squeeze_me=True, struct_as_record=False(("S")) corr.parameters2 = np.array([[d.k1, 0., d.d1], [0., d.k2, d.d2], [0., 0., 1.]]) corr.parameters1 = np.linalg.inv(corr.parameters2) else: raise ValueError("Unknown format: {}".format(fmt)) return corr ``` -------------------------------- ### Python: Update Displayed Localizations Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/nbui/locator Updates the displayed localizations on the image. If localizations are enabled, it calls the `locate_func` to get localization data and then uses `matplotlib.pyplot.scatter` to draw the localizations. The display is updated dynamically. ```python @traitlets.observe("input") def _update(self, change=None): """Update displayed localizations""" if self.input is None: return if self._scatter_artist is not None: self._scatter_artist.remove() self._scatter_artist = None if self._show_loc_check.value: loc = self.locate_func(self.input, **self.options) self._scatter_artist = self.image_display.ax.scatter( loc["x"], loc["y"], facecolor="none", edgecolor="y") self.image_display.ax.figure.canvas.draw_idle() ``` -------------------------------- ### Simulate Gaussian PSFs for Images (Python) Source: https://schuetzgroup.github.io/sdt-python/sim Simulates a fluorescent image from multiple Gaussian PSFs. It's a frontend to lower-level functions and supports different engines ('numba', 'python', 'python_full') for performance. Input includes image shape, PSF centers, amplitudes, and sigmas. ```python sdt.sim.simulate_gauss(_shape_ , _centers_ , _amplitudes_ , _sigmas_ , _cutoff =5.0_, _mass =False_, _engine ='numba'_) ``` -------------------------------- ### Image Masking API Source: https://schuetzgroup.github.io/sdt-python/_modules/sdt/fret/sm_analyzer Applies a 2D boolean mask to filter localization data. The mask can be applied to specific frames using 'start' and 'stop' parameters. Supports applying multiple masks sequentially. ```APIDOC ## POST /filter/image_mask ### Description Applies a 2D boolean mask to filter localization data. The mask can be applied to specific frames using 'start' and 'stop' parameters. Supports applying multiple masks sequentially. ### Method POST ### Endpoint /filter/image_mask ### Parameters #### Query Parameters - **mask** (numpy.ndarray or list of dicts) - Required - The 2D boolean mask or a list of dictionaries, where each dictionary contains 'mask', 'key', 'start', and 'stop' for advanced masking. - **channel** (string) - Required - The channel to use for filtering (e.g., 'donor', 'acceptor'). - **reason** (string) - Required - Filtering reason or column name to use for the applied mask. #### Request Body *Note: This endpoint primarily uses query parameters for mask definition. A request body is not explicitly defined in the documentation but could be used for complex mask definitions.* ### Request Example ```python # Example 1: Single mask for all frames mask = numpy.zeros((200, 200), dtype=bool) mask[50:100, 50:100] = True filt.image_mask(mask, "donor", reason="spatial_filter") # Example 2: Multiple masks with frame ranges masks = [] for i in range(1, 3): masks.append({"key": "file%i" % i, "mask": numpy.ones((10 * i, 10 * i), dtype=bool), "stop": 100}) masks.append({"key": "file%i" % i, "mask": numpy.ones((20 * i, 20 * i), dtype=bool), "start": 100}) filt.image_mask(masks, "donor", reason="multi_frame_filter") ``` ### Response #### Success Response (200) *The response indicates the successful application of the filter. The actual data is modified in place.* #### Response Example *No explicit JSON response body is detailed. Success is indicated by the absence of errors.* ```