Skip to content

Analysis

leopard_em.analysis

Submodule for analyzing results during the template matching pipeline.

InspectionResult

Self-describing container for a saved peak-inspection run.

Attributes:

  • output_mode (str) –

    Either "cross_correlation" or "frc".

  • scores (ndarray) –

    The main score tensor. Shape is (N, n_px, n_defocus, n_orient, H, W) for cross-correlation mode and (N, n_px, n_defocus, n_orient, n_freq) for FRC mode. See :attr:axes for per-dimension labels.

  • axes (tuple[str, ...]) –

    Label for each dimension of :attr:scores.

  • euler_angle_offsets (ndarray) –

    ZYZ orientation offsets searched per particle, shape (n_orient, 3). Indexes the orientation axis of :attr:scores.

  • defocus_offsets (ndarray) –

    Relative defocus offsets (Angstroms), shape (n_defocus,). Indexes the defocus axis.

  • pixel_size_offsets (ndarray) –

    Relative pixel-size offsets, shape (n_px,). Indexes the pixel_size axis.

  • base_euler_angles (ndarray) –

    Per-particle base ZYZ angles the offsets are relative to, shape (N, 3).

  • base_defocus (ndarray) –

    Per-particle base astigmatic defocus the defocus_offsets are relative to, shape (N, 3) as (defocus_u, defocus_v, defocus_angle).

  • particle_index (ndarray | None) –

    Global particle index for each row of the particle axis, shape (N,), or None if the source dataframe had no particle_index column. Maps tensor rows back to the particle stack dataframe.

  • frequency_bins (ndarray | None) –

    FRC frequency bins, shape (n_freq,), in FRC mode; None otherwise.

  • frame_index (ndarray | None) –

    Movie frame index for each entry of the frame axis, shape (T,), when the result was produced by per-frame inspection; None otherwise.

  • metadata (dict[str, Any]) –

    Free-form metadata stored alongside the arrays (includes the format version and any caller-supplied extra_metadata).

MatchTemplatePeaks

Bases: NamedTuple

Helper class for return value of extract_peaks_and_statistics.

load_inspection_result

load_inspection_result(path: str | Path) -> InspectionResult

Load a .npz written by :func:save_inspection_result.

Parameters:

  • path (str | Path) –

    Path to the .npz file.

Returns:

  • InspectionResult

    Self-describing container with the score tensor and its axis metadata.

save_inspection_result

save_inspection_result(output_path: str | Path, *, result: Tensor | tuple[Tensor, Tensor], output_mode: Literal['cross_correlation', 'frc'], euler_angle_offsets: Tensor, defocus_offsets: Tensor, pixel_size_offsets: Tensor, base_euler_angles: Tensor, base_defocus: Tensor, particle_index: Tensor | ndarray | None = None, frame_index: Tensor | ndarray | None = None, per_frame: bool = False, extra_metadata: dict[str, Any] | None = None) -> Path

Write a peak-inspection result to a self-describing .npz file.

Parameters:

  • output_path (str | Path) –

    Destination path. A .npz suffix is appended if not present.

  • result (Tensor | tuple[Tensor, Tensor]) –

    Output of the inspect backend. A tensor in "cross_correlation" mode, or (frc_tensor, frequency_bins) in "frc" mode. When per_frame is True the score tensor carries an extra frame axis after particle.

  • output_mode (Literal['cross_correlation', 'frc']) –

    Score mode used to produce result.

  • euler_angle_offsets (Tensor) –

    Orientation offsets searched, shape (n_orient, 3).

  • defocus_offsets (Tensor) –

    Relative defocus offsets searched, shape (n_defocus,).

  • pixel_size_offsets (Tensor) –

    Relative pixel-size offsets searched, shape (n_px,).

  • base_euler_angles (Tensor) –

    Per-particle base ZYZ angles the offsets are relative to, shape (N, 3).

  • base_defocus (Tensor) –

    Per-particle base astigmatic defocus the offsets are relative to, shape (N, 3) as (defocus_u, defocus_v, defocus_angle).

  • particle_index (Tensor | ndarray | None, default: None ) –

    Global particle index for each tensor row, shape (N,).

  • frame_index (Tensor | ndarray | None, default: None ) –

    Movie frame index for each entry of the frame axis, shape (T,). Only meaningful when per_frame is True.

  • per_frame (bool, default: False ) –

    If True, the score tensor carries a frame axis after particle and the stored axis labels use the per-frame variants.

  • extra_metadata (dict[str, Any] | None, default: None ) –

    Additional JSON-serializable metadata to store alongside the arrays.

Returns:

  • Path

    The path the result was written to (with .npz suffix).

match_template_peaks_to_dataframe

match_template_peaks_to_dataframe(peaks: MatchTemplatePeaks) -> pd.DataFrame

Convert MatchTemplatePeaks object to a pandas DataFrame.

match_template_peaks_to_dict

match_template_peaks_to_dict(peaks: MatchTemplatePeaks) -> dict

Convert MatchTemplatePeaks object to a dictionary.

extract_peaks_and_statistics_p_value

extract_peaks_and_statistics_p_value(mip: Tensor, scaled_mip: Tensor, best_psi: Tensor, best_theta: Tensor, best_phi: Tensor, best_defocus: Tensor, correlation_average: Tensor, correlation_variance: Tensor, total_correlation_positions: int, p_value_cutoff: float = 8.0, mask_radius: float = 5.0, quadrant: int = 1) -> MatchTemplatePeaks

Extract peak locations and associated statistics using the p-value metric.

Parameters:

  • mip (Tensor) –

    Maximum intensity projection of the match template results.

  • scaled_mip (Tensor) –

    Z-score scaled maximum intensity projection.

  • best_psi (Tensor) –

    Best psi angles per pixel.

  • best_theta (Tensor) –

    Best theta angles per pixel.

  • best_phi (Tensor) –

    Best phi angles per pixel.

  • best_defocus (Tensor) –

    Best relative defocus values per pixel.

  • correlation_average (Tensor) –

    Mean correlation values per pixel.

  • correlation_variance (Tensor) –

    Variance of correlation values per pixel.

  • total_correlation_positions (int) –

    Total number of correlation positions evaluated.

  • p_value_cutoff (float, default: 8.0 ) –

    Minimum -ln(p) for peak detection; same scale as 2DTM postprocess pval / metric_cutoff (default 8.0, ballpark comparable to a z-score cutoff of 8).

  • mask_radius (float, default: 5.0 ) –

    Radius for peak masking.

  • quadrant (int, default: 1 ) –

    Quadrant constraint used in p-value calculation. - 1: First quadrant only (x1 > 0 and x2 > 0) - 3: Three quadrants (x1 > 0 or x2 > 0) Default is 1.

Returns:

extract_peaks_and_statistics_zscore

extract_peaks_and_statistics_zscore(mip: Tensor, scaled_mip: Tensor, best_psi: Tensor, best_theta: Tensor, best_phi: Tensor, best_defocus: Tensor, correlation_average: Tensor, correlation_variance: Tensor, total_correlation_positions: int, false_positives: float = 1.0, z_score_cutoff: float | None = None, mask_radius: float = 5.0) -> MatchTemplatePeaks

Returns peak locations, heights, and pose stats from match template results.

Parameters:

  • mip (Tensor) –

    Maximum intensity projection of the match template results.

  • scaled_mip (Tensor) –

    Scaled maximum intensity projection of the match template results.

  • best_psi (Tensor) –

    Best psi angles for each pixel.

  • best_theta (Tensor) –

    Best theta angles for each pixel.

  • best_phi (Tensor) –

    Best phi angles for each pixel.

  • best_defocus (Tensor) –

    Best relative defocus values for each pixel.

  • correlation_average (Tensor) –

    Average correlation value for each pixel.

  • correlation_variance (Tensor) –

    Variance of the correlation values for each pixel.

  • total_correlation_positions (int) –

    Total number of correlation positions calculated during template matching. Must be provided if z_score_cutoff is not provided (needed for the noise model).

  • false_positives (float, default: 1.0 ) –

    Number of false positives to allow in the image (over all pixels). Default is 1.0 which corresponds to a single false-positive.

  • z_score_cutoff (float, default: None ) –

    Z-score cutoff value for peak detection. If not provided, it is calculated using the Gaussian noise model. Default is None.

  • mask_radius (float, default: 5.0 ) –

    Radius of the mask to apply around the peak, in units of pixels. Default is 5.0.

Returns:

  • MatchTemplatePeaks

    Named tuple containing the peak locations, heights, and pose statistics.

gaussian_noise_zscore_cutoff

gaussian_noise_zscore_cutoff(num_ccg: int, false_positives: float = 1.0) -> float

Determines the z-score cutoff based on Gaussian noise model and number of pixels.

NOTE: This procedure assumes that the z-scores (normalized maximum intensity projections) are distributed according to a standard normal distribution. Here, this model is used to find the cutoff value such that there is at most 'false_positives' number of false positives in all of the pixels.

Parameters:

  • num_ccg (int) –

    Total number of cross-correlograms calculated during template matching. Product of the number of pixels, number of defocus values, and number of orientations.

  • false_positives (float, default: 1.0 ) –

    Number of false positives to allow in the image (over all pixels). Default is 1.0 which corresponds to a single false-positive.

Returns:

  • float

    Z-score cutoff.