gridgene.contours module#

gridgene.contours.timeit(func)[source]
class gridgene.contours.GetContour(array_to_contour, logger=None, contour_name=None, points_x_y=None)[source]

Bases: object

Parent class for contour handling and filtering from a 3D array.

This class handles extraction and filtering of contours from a 3D array where the first two dimensions represent spatial coordinates (x and y), and the third dimension contains gene-specific values.

array

The 3D array from which contours are to be extracted. The first two dimensions are x and y spatial positions; the third dimension corresponds to genes.

Type:

np.ndarray

local_sum_image

The 2D array representing the local sum of the input array.

Type:

np.ndarray

contours

List of contours extracted from the array.

Type:

list of np.ndarray

contour_name

Name of the contour for identification.

Type:

str

total_valid_contours

Total number of valid contours after filtering.

Type:

int

contours_filtered_area

Number of contours remaining after area filtering.

Type:

int

logger

Logger instance for logging information and errors.

Type:

logging.Logger

points_x_y

Optional 2D array of shape (N, 2) containing (x, y) points for plotting or further analysis.

Type:

np.ndarray, optional

__init__(array_to_contour, logger=None, contour_name=None, points_x_y=None)[source]

Initializes the GetContour object.

check_contours()[source]

Validates and closes contours.

filter_contours_area(min_area_threshold)[source]

Filters contours based on a minimum area threshold.

filter_contours_no_counts()[source]

Filters out contours with no transcript counts in the array.

filter_contours_by_gene_threshold(gene_array, threshold, gene_name='')[source]

Filters contours based on gene-specific thresholds.

filter_contours_by_gene_comparison(gene_array1, gene_array2, gene_name1='', gene_name2='')[source]

Filters contours where gene_array1 has higher signal than gene_array2.

plot_contours_scatter(...)[source]

Creates a scatter plot with overlaid contours.

plot_conv_sum(...)[source]

Plots the convolution sum image with contours.

check_contours()[source]

Validate and clean contour data.

Ensures each contour has at least 3 points, closes open contours, and converts them to integer format for OpenCV compatibility.

Return type:

None

filter_contours_area(min_area_threshold)[source]

Filter contours by minimum area.

Parameters:

min_area_threshold (float) – Contours with area below this threshold are discarded.

Return type:

None

filter_contours_no_counts()[source]

Remove contours that do not contain any non-zero values in the array.

Returns:

Contours that contain non-zero signal in the original array.

Return type:

List[np.ndarray]

filter_contours_no_counts_and_area(min_area_threshold)[source]

Filter contours based on both signal presence and minimum area.

Parameters:

min_area_threshold (float) – Minimum area a contour must have to be retained.

Returns:

Valid contours satisfying both count and area criteria.

Return type:

List[np.ndarray]

filter_contours_by_gene_threshold(gene_array, threshold, gene_name='')[source]

Retain contours where the gene signal meets a minimum threshold.

Parameters:
  • gene_array (np.ndarray) – 2D or 3D array of gene expression values.

  • threshold (float) – Minimum gene signal required inside the contour.

  • gene_name (str, optional) – Optional name of the gene, used for logging.

Return type:

None

filter_contours_by_gene_comparison(gene_array1, gene_array2, gene_name1='', gene_name2='')[source]

Filter contours by comparing signal from two gene arrays.

Only retain contours where the first gene has higher counts than the second.

Parameters:
  • gene_array1 (np.ndarray) – First gene array.

  • gene_array2 (np.ndarray) – Second gene array.

  • gene_name1 (str, optional) – Name for the first gene (used in logging).

  • gene_name2 (str, optional) – Name for the second gene (used in logging).

Return type:

None

plot_contours_scatter(path=None, show=False, s=0.1, alpha=0.5, linewidth=1, c_points='blue', c_contours='red', figsize=(10, 10), ax=None, **kwargs)[source]

Plot a scatter plot of spatial points overlaid with contours.

Parameters:
  • path (str, optional) – Directory where the plot will be saved (if specified).

  • show (bool) – Whether to display the plot interactively.

  • s (float) – Size of scatter points.

  • alpha (float) – Transparency of scatter points.

  • linewidth (float) – Width of contour lines.

  • c_points (str) – Color for scatter points.

  • c_contours (str) – Color for contour lines.

  • figsize (Tuple[int, int]) – Size of the figure.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot; if None, a new figure is created.

  • **kwargs (dict) – Additional keyword arguments for customizing scatter and line plots.

Returns:

The matplotlib Axes object used for plotting.

Return type:

Axes

plot_conv_sum(cmap='plasma', c_countour='white', path=None, show=False, figsize=(10, 10), ax=None)[source]

Plot the local sum (convolution) image with contour overlays.

Parameters:
  • cmap (str) – Colormap for the local sum image.

  • c_countour (str) – Color for overlaying contours.

  • path (str, optional) – Path to save the figure (if specified).

  • show (bool) – Whether to display the plot interactively.

  • figsize (Tuple[int, int]) – Size of the figure.

  • ax (matplotlib.axes.Axes, optional) – Axes on which to plot; if None, a new figure is created.

Returns:

The matplotlib Axes object used for plotting.

Return type:

Axes

class gridgene.contours.ConvolutionContours(array_to_contour, logger=None, contour_name=None)[source]

Bases: GetContour

A subclass of GetContour for generating contours based on a convolution of the input array. This class provides methods for computing a local density map and extracting contours based on intensity thresholds.

local_sum_image

2D array containing the result of convolution on the input data, used as a basis for contour detection.

Type:

np.ndarray or None

get_conv_sum(kernel_size, kernel_shape='square')[source]

Compute a 2D convolution sum across the 3D input array to create a density map.

Parameters:
  • kernel_size (int) – The size of the convolution kernel.

  • kernel_shape (str, optional) – Shape of the kernel: either ‘square’ or ‘circle’. Defaults to ‘square’.

Raises:

ValueError – If kernel_shape is not one of {‘square’, ‘circle’}.

Return type:

None

contours_from_sum(density_threshold, min_area_threshold, directionality='higher')[source]

Generate contours from the convolution sum using a threshold, and filter by area.

Parameters:
  • density_threshold (float) – The threshold applied to the convolution image to create a binary mask.

  • min_area_threshold (float) – Minimum area that a contour must have to be retained.

  • directionality (str, optional) – Direction of thresholding: - ‘higher’: select pixels greater than the threshold - ‘lower’: select pixels less than the threshold Default is ‘higher’.

Raises:
  • RuntimeError – If the convolution sum image (local_sum_image) has not been computed.

  • ValueError – If directionality is not ‘higher’ or ‘lower’.

Return type:

None

class gridgene.contours.KDTreeContours(kd_tree_data, logger=None, contour_name=None, height=None, width=None)[source]

Bases: GetContour

A subclass of GetContour for generating contours from spatial point data using KD-tree or BallTree-based neighbor counts, clustering, and geometric hulls.

This class supports estimating local point densities via neighbor search, extracting density-based arrays, applying clustering (e.g., DBSCAN), and generating contours from those clusters using circle or concave hulls.

kd_tree_data

Input coordinate data, with ‘X’ and ‘Y’ columns.

Type:

pd.DataFrame

points_x_y

Array of shape (n_samples, 2) containing the input (X, Y) coordinates.

Type:

np.ndarray

height

Height of the image space (used to define output array size).

Type:

int

width

Width of the image space.

Type:

int

image_size

Tuple of (height+1, width+1) defining the output array dimensions.

Type:

tuple

radius

Radius used for neighborhood calculations and clustering.

Type:

float

get_kdt_dist(radius)[source]

Compute the number of neighbors for each point using BallTree within a given radius.

The neighbor count is stored in a new column of kd_tree_data named ‘{contour_name}_neighbor_count’.

Parameters:

radius (int) – Search radius used to define neighborhood around each point.

Return type:

None

get_neighbour_array()[source]

Create a 2D array where each pixel value corresponds to the neighbor count at the rounded integer (X, Y) location of the points.

Returns:

2D array with shape (height+1, width+1) where each pixel represents the number of neighbors for that spatial location.

Return type:

np.ndarray

interpolate_array()[source]

Fill zero values in the neighbor count array using OpenCV inpainting.

This helps in smoothing sparse or missing regions in the data grid.

Returns:

Inpainted version of array_total_nei.

Return type:

np.ndarray

contours_from_neighbors(density_threshold, min_area_threshold, directionality='higher')[source]

Extract contours from a local sum image using a density threshold.

Parameters:
  • density_threshold (float) – Density threshold for extracting contours.

  • min_area_threshold (float) – Minimum area threshold to keep a contour.

  • directionality (str, optional) – Direction to threshold (‘higher’ or ‘lower’), by default ‘higher’.

Return type:

None

find_points_with_neighoors(radius, min_neighbours)[source]

Find points with neighbors within a given radius using KDTree.

Parameters:
  • radius (float) – Search radius to find neighbors around each point.

  • min_neighbours (int) – Minimum number of neighbors for a point to be considered valid.

Return type:

None

label_points_with_neigbors()[source]

Label clustered points with DBSCAN based on neighbor relationships.

Uses the radius and minimum number of neighbors to identify point clusters.

Return type:

None

contours_from_kd_tree_simple_circle()[source]

Create contours using circular masks centered on DBSCAN clusters.

A circle is drawn around each cluster, with a radius covering all points.

Return type:

None

contours_from_kd_tree_concave_hull(alpha=0.1)[source]

Create contours using concave hulls (alpha shapes) on DBSCAN clusters.

Parameters:

alpha (float) – Alpha parameter controlling the shape tightness. Smaller values yield tighter shapes.

Return type:

None

contours_from_kd_tree_complex_hull()[source]

Create contours using convex hulls from DBSCAN clusters.

Uses scipy.spatial.ConvexHull to wrap cluster points.

Return type:

None

get_contours_around_points_with_neighboors(type_contouring='simple_circle')[source]

Generate contours around points with neighbors using KDTree + DBSCAN.

Parameters:

type_contouring (str, default='simple_circle') – Method for generating contours: - ‘simple_circle’ : Circles around clusters. - ‘complex_hull’ : Convex hulls around clusters. - ‘concave_hull’ : Concave hulls (alpha shapes) around clusters.

Return type:

None

plot_point_clusters_with_contours(show=False, figsize=(10, 10))[source]

Plot DBSCAN clusters with overlayed contour boundaries.

Parameters:
  • show (bool, default=False) – Whether to call plt.show() immediately.

  • figsize (tuple, default=(10, 10)) – Size of the plot in inches.

Returns:

The figure object for the plot.

Return type:

matplotlib.figure.Figure

plot_dbscan_labels(show=True, figsize=(8, 8))[source]

Plot points colored by DBSCAN cluster labels.

Parameters:
  • show (bool, default=True) – Whether to call plt.show() immediately.

  • figsize (tuple of int, default=(8, 8)) – Size of the figure in inches.

Returns:

The figure object for the plot.

Return type:

matplotlib.figure.Figure