tmana#
- cryocat.analysis.tmana.compute_gaussian_threshold(input_map)#
Compute an average Gaussian-based threshold from 1D profiles of a 3D map.
This function extracts 1D profiles along three principal axes passing through the peak of a 3D input map, fits a Gaussian model to each profile, and returns the average peak height as a threshold value.
- Parameters:
- input_maparray_like
A 3D array representing the input map or volume from which 1D profiles are extracted.
- Returns:
- thresholdfloat
The average Gaussian peak height computed from the three orthogonal 1D profiles.
Notes
Internally, the function uses
create_starting_parameters_1Dto determine the peak location and extract 1D intensity profiles.Gaussian fitting is performed using
lmfit.models.GaussianModel.The peak center along each axis is constrained to ±1 voxel around the detected peak.
The returned threshold represents a robust estimate of the map’s peak intensity suitable for downstream processing such as masking or segmentation.
- cryocat.analysis.tmana.compute_scores_map_threshold_triangle(scores_map)#
Compute a threshold value from a scores map using the triangle method.
This function applies the triangle thresholding algorithm to a 1D or flattened array of scores, which is often used for image histogram thresholding. The algorithm finds a threshold by maximizing the distance from a line drawn between the peak and the lowest level of the histogram.
- Parameters:
- scores_maparray_like
Input array containing scores or intensity values. The data will be flattened and sorted internally.
- Returns:
- float
The threshold value determined by the triangle method.
Notes
The method sorts the input data, identifies the histogram peak, and calculates a threshold that maximizes the distance to the line between the peak and the lowest non-zero level.
If the left tail of the histogram is shorter, the data is flipped before calculation to ensure robustness.
This implementation omits an additional constant factor used in some ImageJ implementations as it does not affect threshold location.
- cryocat.analysis.tmana.create_angular_distance_maps(angles_map, angles_list, output_file_base=None, write_out_maps=True, c_symmetry=1, angles_order='zxz')#
Generate angular distance maps from an orientation map and a list of reference angles.
This function computes three types of angular distance maps for a given orientation map: total angular distance, distance of the rotation axis (normals), and in-plane rotation distance. The distances are calculated relative to a zero rotation reference and can optionally be written to disk.
- Parameters:
- angles_mapstr or ndarray
Path to the orientation map file (if str) or a preloaded orientation map array. Values are assumed to be 1-based indices corresponding to rows in
angles_list.- angles_liststr or ndarray
Path to a file containing the reference rotation angles or a preloaded array of Euler angles (shape: [num_angles, 3]). The rotation order is specified by
angles_order.- output_file_basestr, optional
Base path for writing output maps. If None and
angles_mapis a file path, the base name of the file is used. Required ifwrite_out_mapsis True andangles_mapis an array.- write_out_mapsbool, default=True
Whether to write the generated maps to disk as
.emfiles.- c_symmetryint, default=1
C symmetry used to account for equivalent rotations.
- angles_orderstr, default=’zxz’
The Euler angles convention used in
angles_list.
- Returns:
- ang_dist_mapndarray
3D array of total angular distances for each voxel relative to zero rotation.
- dist_normals_mapndarray
3D array of angular distances corresponding to the rotation axes (normals).
- dist_inplane_mapndarray
3D array of angular distances corresponding to in-plane rotations.
Notes
The function assumes that the orientation map contains integer indices referring to rows of the angles list.
Distances are computed using the
geom.compare_rotationsfunction, which handles the symmetry specified byc_symmetry.Output maps are written in single precision (
np.single) whenwrite_out_mapsis True.
- cryocat.analysis.tmana.create_starting_parameters_1D(input_map, peak_tolerance=20)#
Identify peak values in central part of a map and extract 1D line profiles along each axis for all peaks.
This function applies a spherical mask to restrict the peak search to a central region of the input map, identifies the coordinates of the highest value within that region, determines the global peak value, and extracts the intensity profiles along the x, y, and z axes passing through the peak.
- Parameters:
- input_mapndarray
A 3D NumPy array representing the map (e.g., a correlation or density map).
- peak_toleranceint, optional
Radius of the spherical mask, in voxels, used to limit the peak search to the central region of the map. Default is 20.
- Returns:
- peak_centertuple of int
The (x, y, z) voxel coordinates of the detected peak center, found within the masked region.
- peak_heightfloat
The maximum value in the entire
input_map(global peak value).- profilesndarray of shape (N, 3)
The 1D intensity profiles along x, y, and z through the peak center. Each column corresponds to one axis: column 0 = x-axis profile, column 1 = y-axis profile, column 2 = z-axis profile.
Notes
The peak location is determined within the masked region, but the peak height is taken from the global maximum of the unmasked
input_map.The spherical mask is centered on the map center, not the detected peak.
This method is useful for analyzing the sharpness and anisotropy of a central peak.
- cryocat.analysis.tmana.create_starting_parameters_2D(input_map, peak_tolerance=20, peak_center=None)#
Generate 2D cross-sectional slices and peak parameters from a 3D input map.
This function extracts three orthogonal 2D slices (XY, YZ, XZ) through the specified or automatically determined peak of a 3D volume. It optionally restricts the search for the peak to a spherical region defined by
peak_tolerance.- Parameters:
- input_maparray_like
A 3D array representing the input map or volume from which to extract slices.
- peak_toleranceint, optional
Radius of the spherical mask (in voxels) used to restrict the search for the peak when
peak_centeris not provided. Default is 20.- peak_centertuple of int, optional
Coordinates (x, y, z) of the peak in the 3D volume. If None, the peak is automatically determined as the maximum value within the spherical mask.
- Returns:
- peak_centertuple of int
Coordinates (x, y, z) of the identified peak in the input volume.
- peak_heightfloat
Intensity value at the peak location.
- slicesndarray
A 3D array containing three orthogonal 2D slices stacked along the third axis. The slices correspond to the XY, YZ, and XZ planes passing through the peak.
Notes
The function assumes that
input_mapis a 3D array.The returned slices are aligned such that the first two dimensions correspond to the plane axes, and the third dimension indexes the three planes (XY, YZ, XZ).
- cryocat.analysis.tmana.evaluate_scores_map(input_map, label_type='plane', threshold_type='gauss')#
Evaluate a 3D scores map and extract labeled regions based on thresholding.
This function computes a threshold for the input 3D map, generates a binary mask, and extracts labeled regions according to the specified label type. It supports Gaussian, triangle, or hard thresholding methods.
- Parameters:
- input_maparray_like
A 3D array representing the volumetric score map to evaluate.
- label_typestr, optional
Type of region labeling to perform. Options are: - “ellipsoid” : fits an ellipsoid to the central region - “plane” : extracts central planes through the peak - others : extracts the central connected region Default is “plane”.
- threshold_typestr, optional
Method for thresholding the input map. Options are: - “gauss” : uses a Gaussian-based threshold - “triangle” : uses a triangle-based threshold - “hard” : sets threshold as half the peak height Default is “gauss”.
- Returns:
- labeled_mapndarray
The input map multiplied by the labeled mask, isolating the selected region.
- sizestuple of float
The estimated extents of the labeled region along each axis.
- peak_heightfloat
The peak value in the input map, computed using
create_starting_parameters_2D.- thresholded_mapndarray
The input map after applying the threshold, with values outside the region set to zero.
- surfacendarray or list
For ellipsoid labeling, a 3D array representing the fitted ellipsoid surface. For plane or other labeling, returns an empty list.
- Raises:
- ValueError
If
threshold_typeis not one of “gauss”, “triangle”, or “hard”.
- cryocat.analysis.tmana.filter_dist_maps(dist_maps, th_mask, min_angles_voxel_count)#
Filter 3D distance maps by applying a threshold mask and removing small connected regions.
This function iterates over each 3D distance map in a 4D array, applies a threshold mask, labels connected regions, and removes regions smaller than a specified minimum voxel count. The resulting maps are updated to retain only sufficiently large connected regions.
- Parameters:
- dist_mapsndarray
A 4D array of shape (X, Y, Z, N), where each 3D volume along the last axis represents a distance map to filter.
- th_maskndarray
A 3D binary mask applied to each distance map. Regions with zero values in this mask are ignored.
- min_angles_voxel_countint
Minimum number of voxels required for a connected region to be kept. Regions smaller than this threshold are removed.
- Returns:
- dist_mapsndarray
The filtered 4D distance maps with small regions removed and threshold mask applied.
- th_maskndarray
The updated 3D mask after removing small regions. This mask can be used for further processing or filtering.
Notes
Connectivity is set to 1 when labeling regions, meaning only direct neighbors along each axis are considered connected.
The function multiplies each distance map by the updated mask twice, first to remove small regions in each map individually, and again to ensure consistency across all maps.
- cryocat.analysis.tmana.get_central_label(map, peak_coordinates)#
Extract the central labeled region in a 3D map and compute its dimensions.
This function thresholds the input 3D map, labels connected components, identifies the component containing the specified peak coordinates, and calculates the extents of this central component along each axis.
- Parameters:
- maparray_like
A 3D array representing the volumetric data to process.
- peak_coordinatestuple of int
Coordinates (z, y, x) specifying a voxel within the central region.
- Returns:
- labeled_maskndarray
A 3D array of the same shape as
map, where voxels belonging to the central region are labeled as 1, and all others as 0.- size_xyztuple of int
Extent of the central region along each axis in the order (size_x, size_y, size_z).
Notes
Uses
skimage.measure.labelto label connected components in 3D.The central region is determined by the component containing the voxel at
peak_coordinates.The size along each axis is computed from the first and last non-zero voxel positions in that axis.
- cryocat.analysis.tmana.get_central_plane_labels(input_map, peak_coordinates, map_threshold=0.0)#
Generate central plane labels and approximate ellipsoid dimensions from a 3D map.
This function thresholds a 3D input map, extracts central XY, YZ, and XZ planes at the provided peak coordinates, labels connected components in each plane, fits ellipses to the central components, and combines the results into a 3D label mask. It also computes approximate half-lengths of the ellipsoid axes based on the fitted ellipses.
- Parameters:
- input_maparray_like
A 3D array representing the volumetric data to process. Works best for cubic volumes.
- peak_coordinatestuple of int
Coordinates (z, y, x) specifying the peak around which central planes are extracted.
- map_thresholdfloat, optional
Intensity value used to threshold the input map. Voxels equal to this value are shifted to avoid labeling conflicts. Default is 0.0.
- Returns:
- label_maskndarray
A 3D array of the same shape as
input_map, where voxels corresponding to the central-plane ellipses are labeled as 1 and others as 0.- ellipsoid_half_lengthstuple of float
Approximate half-lengths (along x, y, z) of the ellipsoid derived from the major and minor axes of the ellipses fitted in the central planes.
Notes
Uses
skimage.measure.labelto label connected components in 2D planes.Ellipses are fitted to the central labeled component in each plane using
skimage.draw.ellipse.The function accumulates ellipse masks from all three central planes to form a 3D label mask.
The returned
ellipsoid_half_lengthsare calculated as half the sum of major and minor axes contributions across the three planes.
- cryocat.analysis.tmana.get_ellipsoid_label(input_map, peak_coordinates, map_threshold=0.0)#
Generate a labeled ellipsoid around a peak in a 3D map.
This function thresholds a 3D map, identifies the connected component containing a specified peak, fits an ellipsoid to its surface, and returns a labeled volume corresponding to the fitted ellipsoid along with geometric properties.
- Parameters:
- input_maparray_like
A 3D array representing the input volumetric map.
- peak_coordinatestuple of int
Coordinates (z, y, x) of the peak around which the ellipsoid is fitted.
- map_thresholdfloat, optional
Intensity threshold for initial map segmentation. Voxels equal to this value are temporarily shifted to avoid labeling conflicts. Default is 0.0.
- Returns:
- fitted_labelndarray
A 3D array of the same shape as
input_mapwhere voxels inside the fitted ellipsoid are labeled as 1 and others as 0.- radii_sortedndarray
Array of the lengths of the principal axes of the fitted ellipsoid, sorted by magnitude.
- surface_fitndarray
A 3D binary array representing the ellipsoid surface obtained via marching cubes.
- th_mapndarray
Thresholded map where only the connected component containing the peak is labeled.
Notes
Uses
skimage.measure.labelfor connected component labeling.Uses
skimage.measure.marching_cubesto extract the ellipsoid surface.Ellipsoid fitting and voxel filling are performed with functions from
geom.Radii are doubled to represent full axis lengths.
- cryocat.analysis.tmana.scores_extract_particles(scores_map, angles_map, angles_list, tomo_id, particle_diameter, object_id=None, scores_threshold=None, sigma_threshold=None, cluster_size=None, n_particles=None, output_path=None, output_type='emmotl', angles_order='zxz', symmetry='c1', angles_numbering=0, tomo_mask=None)#
- Extracts particles from scores maps produced by template matching
with GAPSTOP(TM) or STOPGAP.
- Parameters:
- scores_mapstr or array-like
Path to the scores map file or the scores map array.
- angles_mapstr or array-like
Path to the angles map file or the angles map array.
- angles_liststr or array-like
Path to the angles list file or the angles list array.
- tomo_idint
Identifier for the tomogram from which particles are being extracted.
- particle_diameterfloat
Diameter of the particle to be used for extraction and clustering.
- object_idint, optional
Identifier for the object within the tomogram. Defaults to None.
- scores_thresholdfloat, optional
“Direct” threshold for the scores map. If set, all values below this threshold will be removed from the scores map. This parameter is useful if one knows exact threshold for the scores map. Defaults to None.
- sigma_thresholdfloat, optional
Number of standard deviations above the mean to consider as threshold for particle extraction. This parameter is prefered over the scores threshold for “batch” processing since the exact scores threshold might differ between different scores maps, while the sigma confidence is relatively stable. If None, the threshold is computed using
cryocat.tmana.compute_scores_map_threshold_triangle()function. Defaults to None.- cluster_sizeint, optional
Minimum number of particles required to form a cluster. Defaults to None.
- n_particlesint, optional
Maximum number of particles to extract. Defaults to None.
- output_pathstr, optional
Path to save the output file. If the output_path is not specified no file will be written out. Defaults to None.
- output_typestr, {“emmotl”, “stopgap”, “relion”}
Type of the file to be written out. The options are “emmotl”, “stopgap”, “relion”. This parameter is used only if output_path is not None. Defaults to “emmotl”.
- angles_orderstr, {“zxz”, “zzx”}
Order of rotation angles in the angles list. For lists generated by STOPGAP use “zzx”. For GAPSTOP(TM) use the same angle_order that was used in the list generation (default is “zxz”). Defaults to “zxz”.
- symmetrystr, default=”c1”
Symmetry to be applied. The function currently supports only cyclic (C) symmetries. If a non-C symmetry is provided, it raises warning and defaults to “c1”. Defaults to “c1”.
- angles_numberingint, default=0
Adjusts the indexing of angles from the angles map. Angle maps from STOPGAP start numbering from 1 and thus angles_numbering should be set to 1 to fetch correct angles from the angle lists. GAPSTOP(TM) numbers from 0. Defaults to 0.
- tomo_mask: str or array-like, optional
Path to a binary tomogram mask file or an array containing the mask. If provided the scores maps are multiplied with the mask prior any further processing.
- Returns:
- motlMotl object
Motl object containing the extracted particle coordinates, scores, and orientations.
- Raises:
- Warning
If a non-supported symmetry is provided, a warning is issued and the symmetry is set to “c1”.
Notes
The function supports only cyclic (C) symmetries. If a non-C symmetry is provided, it defaults to “c1”.
- cryocat.analysis.tmana.select_peaks(scores_map, angles_map, angles_file, peak_number=None, create_dist_maps=False, dist_maps_list=['_dist_all', '_dist_normals', '_dist_inplane'], dist_maps_name_base=None, write_dist_maps=False, min_peak_voxel_count=7, min_angles_voxel_count=7, template_mask=None, template_radius=2, edge_masking=None, tomo_mask=None, output_motl_name=None, tomo_number=None, angles_order='zxz')#
Automatic peak selection.
- Parameters:
- scores_mapndarray or str
Map with CCC scores (either path to it or loaded as ndarray)
- angles_mapndarray or str
Map with angle indices (either path to it or loaded as ndarray)
- angles_filendarray or str
Angle list used in TM (either path to it or loaded as ndarray). If ndarray is provided it has to be in correct order - phi, theta, psi
- peak_numberint
Number of peaks to return. Defaults to None.
- create_dist_mapsbool
Whether to create distance maps. They have to be provided for the computation. Defaults to False.
- dist_maps_listlist
What distance map(s) to use for the analysis. At least one has to be specified. Defaults to all of them: [‘_dist_all’,’_dist_normals’,’_dist_inplane’].
- dist_maps_name_basestr
Path and base name of the distance maps. Defaults to None.
- write_dist_mapsbool
Whether to write the created distance maps or not. Used only if create_dist_maps is True. Defaults to False.
- min_peak_voxel_countint
Size of the minimum volume each peak should have (in voxels). Defaults to 7.
- min_angles_voxel_countint
Size of the minimum volume each distance map should have around each peak (in voxels). Defaults to 7.
- template_maskndarray or str
Mask for masking out the volume around the seleceted peak (either path to it or loaded as ndarray). Ideally a tight mask with hard edges, that is NOT hollow (even for hollow structures). Defaults to None.
- template_radiusint
The radius of a sphere to use for masking out the volume around the selected peak. Used only if the template mask is not specified. Defaults to 2.
- edge_maskingint or ndarray of shape (3
Dimensions of edges to mask out (). Defaults to None.
- tomo_maskndarray
Mask to exclude regions from the analysis. It has to be the same size as the scores map. Defaults to None.
- output_motl_namestr
Name of the output motl. Defaults to None which results in no motl to be written out.
- tomo_numberint
Number of tomogram to be stored in motl. Defaults to None.
- “_dist_normals”
- “_dist_inplane”]
- Returns:
- output_motlcryomotl.Motl
Motl with the selected peaks.
- empty_labelndarray
Map with the selected peaks (same size as scores map).
- Raises:
- ValueError
If the edge_masking is not specified as one number nor ndsarray of shape (3,)
- ValueError
If the dist_maps_list contains unknown dist map specifier
- ValueError
If the create_dist_maps is False and the dist_maps_name_base is not specified