hong2p.roi module

hong2p.roi.autoroi_metadata_filename(ijroi_file)[source]
hong2p.roi.certain_roi_indices(df)[source]

Returns boolean mask of certain ROIs, for DataFrame with ‘roi’ column level

Return type

ndarray

hong2p.roi.check_no_roi_jumps(roi_xyd, max_cost)[source]
hong2p.roi.contour2mask(contour, shape)[source]

Returns a boolean mask True inside contour and False outside.

hong2p.roi.correspond_and_renumber_rois(roi_xyd_sequence, debug=False, checks=False, use_renumber_rois2=True, **kwargs)[source]
hong2p.roi.correspond_rois(left_centers_or_seq, *right_centers, cost_fn=None, max_cost=None, show=False, write_plots=True, left_name='Left', right_name='Right', name_prefix='', draw_on=None, title='', colors=None, connect_centers=True, pairwise_plots=True, pairwise_same_style=False, roi_numbers=False, jitter=True, progress=None, squeeze=True, verbose=False, debug_points=None)[source]

Args: left_centers_or_seq (list): (length n_timepoints) list of (n_rois x 2)

arrays of ROI center coordinates.

Returns: lr_matches: list of arrays matching ROIs in one timepoint to ROIs in the

next.

left_unmatched: list of arrays with ROI labels at time t,

without a match at time (t + 1)

right_unmatched: same as left_unmatched, but for (t + 1) with respect to t.

total_costs: array of sums of costs from matching.

fig: matplotlib figure handle to the figure with all ROIs on it,

for modification downstream.

hong2p.roi.crop_to_coord_bbox(matrix, coords, margin=0)[source]

Returns matrix cropped to bbox of coords and bounds.

hong2p.roi.crop_to_nonzero(matrix, margin=0)[source]

Returns a matrix just large enough to contain the non-zero elements of the input, and the bounding box coordinates to embed this matrix in a matrix with indices from (0,0) to the max coordinates in the input matrix.

hong2p.roi.db_footprints2array(df, shape)[source]

Returns footprints in an array of dims (shape + (n_footprints,)).

hong2p.roi.db_row2footprint(db_row, shape=None)[source]

Returns dense array w/ footprint from row in cells table.

hong2p.roi.extract_traces(movie, footprints, *, _sum=False, verbose=False)[source]

Averages the movie within each mask in footprints to make a matrix of traces (n_frames x n_footprints).

Parameters
  • movie – should be of shape (T, [Z,] Y, X).

  • footprints – should be of shape ([Z,] Y, X, #-ROIs)

hong2p.roi.extract_traces_bool_masks(movie, footprints, *, verbose=False)[source]

Averages the movie within each boolean mask in footprints to make a matrix of traces (n_frames x n_footprints).

Parameters
  • movie – should be of shape (T, [Z,] Y, X).

  • footprints – should be of shape ([Z,] Y, X, #-ROIs)

hong2p.roi.fit_circle_rois(tif, template_data=None, avg=None, movie=None, method_str='cv2.TM_CCOEFF_NORMED', thresholds=None, exclusion_radius_frac=0.8, min_neighbors=None, debug=False, _packing_debug=False, show_fit=None, write_ijrois=False, _force_write_to=None, overwrite=False, exclude_dark_regions=None, dark_fraction_beyond_dhist_min=0.6, max_n_rois=650, min_n_rois=150, per_scale_max_n_rois=None, per_scale_min_n_rois=None, threshold_update_factor=0.7, update_factor_shrink_factor=0.7, max_threshold_tries=4, _um_per_pixel_xy=None, multiscale=True, roi_diams_px=None, roi_diams_um=None, roi_diams_from_kmeans_k=None, multiscale_strategy='one_order', template_d2match_value_scale_fn=None, allow_duplicate_px_scales=False, _show_scaled_templates=False, verbose=False, **kwargs)[source]

Even if movie or avg is passed in, tif is used to find metadata and determine where to save ImageJ ROIs.

_um_per_pixel_xy only used for testing. Normally, XML is found from tif, and that is loaded to get this value.

Returns centers_px, radii_px (both w/ coordinates and conventions ijrois uses)

hong2p.roi.footprints_to_flat_cnmf_dims(footprints)[source]

Takes array of (x, y[, z], n_footprints) to (n_pixels, n_footprints).

There is more than one way this reshaping can be done, and this produces output as CNMF expects it.

hong2p.roi.get_circle_ijroi_input(center_px, radius_px)[source]

Returns appropriate first arg for my ijroi.write_roi

hong2p.roi.greedy_roi_packing(match_images, ds, radii_px, thresholds=None, ns=None, exclusion_radius_frac=0.7, min_dist2neighbor_px=15, min_neighbors=3, exclusion_mask=None, draw_on=None, debug=False, draw_bboxes=True, draw_circles=True, draw_nums=True, multiscale_strategy='one_order', match_value_weights=None, radii_px_ps=None, scale_order=None, subpixel=False, _src_img_shape=None, _show_match_images=False, _show_packing_constraints=False, _show_fit=True, _initial_single_threshold=None)[source]

Args: match_images (np.ndarray / iterable of same): 2-dimensional array of match value higher means better match of that point to template.

Shape is determined by the number of possible offsets of the template in the original image, so it is smaller than the original image in each dimension. As an example, for a 3x3 image and a 2x2 template, the template can occupy 4 possible positions in the 3x3 image, and the match image will be 2x2.

ds (int / iterable of same): integer width (and height) of square template.

related to radius, but differ by margin set outside.

radii_px (int / iterable of same): radius of cell in pixels.

exclusion_radius_frac (float): approximately 1 - the fraction of two ROI

radii that are allowed to overlap.

hong2p.roi.has_ijrois(ijroiset_dir_or_fname)[source]
Return type

bool

hong2p.roi.ijroi2cv_contour(roi)[source]
hong2p.roi.ijroi2mask(roi, shape, z=None)[source]

z: z-index ROI was drawn on

hong2p.roi.ijroi_comparable_via_name(n)[source]

Returns whether input refers to only a single ROI name (‘VM3?’ and ‘VM3’)

Return type

bool

hong2p.roi.ijroi_filename(ijroiset_dir_or_fname, must_exist=True)[source]
Return type

Path

hong2p.roi.ijroi_masks(ijroiset_dir_or_fname, thorimage_dir, as_xarray=True, drop_maximal_extent_rois=True, indices=None, **kwargs)[source]
Return type

Union[ndarray, DataArray]

hong2p.roi.ijroi_mtime(ijroiset_dir_or_fname)[source]

RoiSet.zip (/directory with one) path to Unix timestamp modification time

Return type

float

hong2p.roi.ijroi_name_as_if_certain(roi_name)[source]

Removes characters indicating uncertainty, to group ROIs by best guess at ID

‘VM3’ -> ‘VM3’ ‘VM3?’ -> ‘VM3’ ‘VM3+?’ -> ‘VM3’ ‘VM2|VM3?’ -> None ‘VM2+VM3?’ -> None

Any time ijroi_uncertainty_chars split remainder of name into more than one part, None is returned (ambiguous which name it should refer to).

Return type

Optional[str]

hong2p.roi.ijrois2masks(ijrois, shape, as_xarray=False)[source]

Transforms ROIs loaded from my ijroi fork to an array full of boolean masks, of dimensions (shape + (n_rois,)).

Return type

Union[ndarray, DataArray]

hong2p.roi.is_ijroi_certain(roi)[source]

Returns whether an ROI is named indicating it’s ID is certain.

False for names that are default, integers, or include one of ijroi_uncertainty_chars (e.g. ‘?’), and True otherwise.

Return type

bool

hong2p.roi.is_ijroi_name_default(roi)[source]
Return type

bool

hong2p.roi.is_ijroi_named(roi)[source]
Return type

bool

hong2p.roi.is_ijroi_plane_outline(roi)[source]

Returns ROI name indicates it’s an outline of a whole structure (e.g. the AL)

There will typically be exactly one of these per plane, when used. Sub-ROIs (e.g. glomeruli) should be contained within this larger region.

Return type

bool

hong2p.roi.load_template_data(err_if_missing=False)[source]
hong2p.roi.make_test_centers(initial_n=20, nt=100, frame_shape=(256, 256), sigma=3, exlusion_radius=None, p=0.05, max_n=None, round_=False, diam_px=20, add_diameters=True, verbose=False)[source]
hong2p.roi.merge_ijroi_masks(masks, **kwargs)[source]
Parameters
  • masks (xarray.DataArray) – must have at least dims ‘x’, ‘y’, and ‘roi’. ‘roi’ should be indexed by a MultiIndex and one of the levels should have the name of the on argument. Currently expect the dtype to be ‘bool’.

  • label_fn (callable) – function mapping the values of the on column to labels for the ROIs. Only ROIs created via merging will be given these labels, while unmerged ROIs will recieve unique number labels. Defaults to a function that takes strings, removes trailing/leading underscores, and parses an int from what remains.

hong2p.roi.merge_rois(rois, on='ijroi_prefix', merge_fn=None, label_fn=None, check_no_overlap=False)[source]
Parameters
  • rois (xarray.DataArray) – must have at least dims ‘x’, ‘y’, and ‘roi’. ‘roi’ should be indexed by a MultiIndex and one of the levels should have the name of the on argument. Currently expect the dtype to be ‘bool’.

  • on (str) – name of other ROI metadata dimension to merge on

  • label_fn (callable) – function mapping the values of the on column to labels for the ROIs. Only ROIs created via merging will be given these labels, while unmerged ROIs will recieve unique number labels. Defaults to the identity function.

  • check_no_overlap (bool) – (optional, default=False) If True, checks that no merged rois shared any pixels before being merged. If merged ROIs are all on different planes, this should be True because ImageJ ROIs are defined on single planes.

hong2p.roi.merge_single_plane_rois(rois, min_overlap_frac=0.3, n_dilations=1)[source]

For handling single plane ROIs that are on adjacent Z planes, and correspond to the same biological feature. This is to merge the single plane ROIs that suite2p outputs.

hong2p.roi.numpy2xarray_rois(rois, roi_indices=None)[source]

Takes numpy array of shape ([z,]y,x,roi) to labelled xarray.

Parameters

roi_indices (None | dict) – values must be iterables of length equal to number of ROIs. ‘roi_num’ will be included as an additional ROI index regardless.

Return type

DataArray

hong2p.roi.plot_circles(draw_on, centers, radii)[source]
hong2p.roi.point_idx(xys_to_check, pt_xy, swap_xy=False)[source]
hong2p.roi.py2imagej_coords(array)[source]

Since ijroi source seems to have Y as first coord and X as second.

hong2p.roi.renumber_rois(matches_list, centers_list, debug_points=None, max_cost=None)[source]

Each sequence of matched ROIs gets an increasing integer identifier (including length-1 sequences, i.e. unmatched stuff).

Returns lists of IDs in each element of input list and centers, re-indexed with new IDs.

hong2p.roi.renumber_rois2(matches_list, centers_list)[source]
hong2p.roi.roi_center(roi)[source]
hong2p.roi.roi_centers(rois)[source]
hong2p.roi.roi_jumps(roi_xyd, max_cost)[source]

Returns dict of first_frame -> list of (x, y, str(point idx)) for each time an ROI jumps by >= max_cost on consecutive frames.

correspond_rois should have not matched these points.

Output suitable for debug_points kwarg to correspond_rois

hong2p.roi.rois2best_planes_only(rois, roi_quality, verbose=True)[source]

Currently assumes input only has non-zero values in a single plane for a given unique combination of ROI identifier variables.

Return type

DataArray

hong2p.roi.scale_template(template_data, um_per_pixel_xy, target_cell_diam_um=None, target_cell_diam_px=None, target_template_d=None, debug=False)[source]
hong2p.roi.select_certain_rois(df)[source]

Returns input subset with certain ROI labels, for input with ‘roi’ column level

Return type

DataFrame

hong2p.roi.stable_rois(lr_matches, verbose=False)[source]

Takes a list of n_cells x 2 matrices, with each row taking an integer ROI label from one set of labels to the other.

Input is as first output of correspond_rois.

Returns: stable_cells: a n_stable_cells x (len(lr_matches) + 1) matrix, where rows

represent different labels for the same real cells. Columns have the set of stable cells IDs, labelled as the inputs are.

new_lost: a (len(lr_matches) - 1) length list of IDs lost when matching

lr_matches[i] to lr_matches[i + 1]. only considers IDs that had been stable across all previous pairs of matchings.

hong2p.roi.template_data_file()[source]
hong2p.roi.template_match(scene, template, method_str='cv2.TM_CCOEFF', hist=False, debug=False)[source]