sta#

class cryocat.analysis.sta.Block(n_iterations, job, motl_name, search_mode=None, temperature=0.0, overrides=<factory>)#

Bases: object

One block in a STOPGAP / novaSTA run schedule.

Parameters:
n_iterationsint

Number of iterations this block contributes.

job{“avg”, “ali”}

Whether this block is an averaging or alignment step.

motl_namestr

Motl name pattern. Supports {base}, {run}, and {iter} placeholders, which are expanded by expand_motl_name().

search_mode{“hc”, “shc”} or None, default=None

Search mode. None is valid for averaging blocks.

temperaturefloat, default=0.0

Simulated annealing temperature. 0 = disabled.

overridesdict, default={}

Per-block overrides for any base_params field.

job#
motl_name#
n_iterations#
overrides#
search_mode = None#
temperature = 0.0#
class cryocat.analysis.sta.CoassignmentFactor(labels, particle_ids, run_labels, n_classes)#

Bases: object

Factored representation of a co-assignment matrix over several runs.

Attributes:
labelsnumpy.ndarray

(N, R) int32 array of global class indices; class blocks of different runs never overlap. -1 marks a particle absent from that run.

particle_idsnumpy.ndarray

(N,) sorted particle identifiers; row i of everything refers to particle_ids[i].

run_labelslist of str

Human-readable name per run, in column order of labels.

n_classesnumpy.ndarray

(R,) number of classes observed in each run.

agreement_histogram(method='auto', n_samples=1000000, max_exact_tuples=5000, seed=0, max_runs=None)#

Distribution of pairwise agreement counts.

Exact by tuple-based O(T² R) enumeration when the number of distinct label tuples T is at most max_exact_tuples; otherwise estimated from n_samples uniformly drawn particle pairs.

Parameters:
method{‘auto’, ‘exact’, ‘sampled’}, default ‘auto’

'auto' picks exact when T <= max_exact_tuples.

n_samplesint, default 1_000_000

Pairs drawn when method is 'sampled' or auto chooses sampled.

max_exact_tuplesint, default 5_000

T threshold for 'auto'.

seedint or None, default 0

RNG seed for the sampled path.

max_runsint or None, default None

Legacy parameter. When given, raises UserInputError if n_runs > max_runs (preserves pre-existing test contracts) and requires full_participation.

Returns:
pandas.DataFrame

Columns: n_runs_agreeing, n_pairs, fraction_of_pairs, fraction_at_least_k, exact.

Raises:
UserInputError

If max_runs is given and n_runs > max_runs, or if participation is incomplete.

consistency_groups()#

Group particles by their full label tuple across runs.

Returns:
pandas.DataFrame

One row per particle: particle_id, group (tuple id), and group_size.

property full_participation#

True when every particle is classified in every run.

indicator()#

Return the sparse indicator B with M = (1/R) B B^T.

Returns:
scipy.sparse.csr_matrix

Shape (n_particles, sum(n_classes)), one non-zero per particle per run in which that particle appears.

labels#
matrix(max_particles=5000, dtype='float32')#

Materialise the dense (N, N) co-assignment matrix.

Only for visualisation of modest particle counts – everything else in this class avoids it. Memory is N**2 * itemsize bytes.

Parameters:
max_particlesint, default=5000

Refuse above this, rather than attempting a multi-gigabyte allocation. Raise it deliberately if you mean it.

dtypestr, default=’float32’

Accumulator dtype.

Returns:
numpy.ndarray

(N, N) matrix; M[i, j] is the fraction of runs containing both particles in which they shared a class. Diagonal is 1.

Raises:
UserInputError

If n_particles exceeds max_particles.

n_classes#
property n_particles#

Number of distinct particles across all runs.

property n_runs#

Number of classification runs.

particle_ids#
pca(n_components=10)#

Principal coordinates of the co-assignment matrix.

Exact, not approximate: the eigenvectors of M = (1/R) B B^T are the left singular vectors of B, obtained here from the small (P, P) Gram matrix B^T B where P = sum(n_classes) is a few dozen. Cost is O(N P^2); no N x N array is formed.

Parameters:
n_componentsint, default=10

Number of components; silently capped at rank(M).

Returns:
scoresnumpy.ndarray

(N, n_components) particle coordinates, components ordered by decreasing eigenvalue.

eigenvaluesnumpy.ndarray

(n_components,) eigenvalues of M.

presence()#

Return the sparse presence indicator C; co-occurrence is C C^T.

run_agreement()#

Pairwise adjusted Rand index between every pair of runs.

Returns:
dict with keys:
- ``”summary”``DataFrame[run, n_classes, mean_ari, min_ari, max_ari]
- ``”matrix”``R×R DataFrame of pairwise ARI indexed by run label
run_labels#
class cryocat.analysis.sta.ConsensusResult(labels, particle_ids, group_sizes, min_agreement, linkage, method, n_assigned, n_junk, reliable, verdict, junk_class)#

Bases: object

Output of consensus_groups().

Attributes:
labelsnumpy.ndarray

(N,) int32 consensus class per particle; junk_class where unassigned.

particle_idsnumpy.ndarray

(N,) particle identifiers matching the input factor.

group_sizespandas.Series

Mapping class → particle count (including junk class if non-empty).

min_agreementfloat

The threshold actually used, after snapping to the nearest achievable k/R.

linkagestr

Linkage rule used.

methodstr

Which computation ladder row ran.

n_assignedint

Particles assigned to a non-junk class.

n_junkint

Particles collapsed to the junk class.

reliablebool

Whether the ensemble supports a stable grouping.

verdictstr

One human-readable sentence summarising the result.

junk_classint

The class value used for unassigned / small-group particles.

group_sizes#
junk_class#
labels#
linkage#
method#
min_agreement#
n_assigned#
n_junk#
particle_ids#
reliable#
verdict#
class cryocat.analysis.sta.NovaStaParams(df, df_extra=None, create_ref=False, ref_family='singleref', use_euler_search=False)#

Bases: StaParameters

novaSTA flat key-value parameter file representation.

All parameters are stored in df using canonical column names (e.g. "cone angle", "low pass", "wedge list"). Run-level keys (iter, startIndex, createRef) become object attributes, not columns. Unknown camelCase keys (not in the schema) are stored under their original camelCase name in df.

classmethod from_file(path)#

Load a novaSTA flat key-value parameter file.

Parameters:
pathPathOrStr

Path to the novaSTA flat parameter file (typically .txt / .params).

Returns:
NovaStaParams
Raises:
ValueError

If any parameter has a value count other than 1 or iter.

get_fsc_filename(iteration, working_dir=None)#

Return the novaSTA FSC curve path for a given iteration.

novaSTA writes its FSC curve as <refname>_<iteration>_fsc.txt (one correlation value per line). The path is constructed from the same ref column and the same optional working_dir override used by resolve_ref_base().

Parameters:
iterationint

Iteration number, embedded verbatim (not zero-padded).

working_dirPathOrStr or None, default=None

Directory override applied to the stored ref value (see _apply_working_dir()).

Returns:
str or None

Full FSC filename, or None if ref is not set.

get_half_map_paths(iteration, working_dir=None)#

Return the (even, odd) half-map paths for a given iteration.

novaSTA names half-maps as <refname>_even_<iteration>.em and <refname>_odd_<iteration>.em.

Parameters:
iterationint

Iteration number.

working_dirPathOrStr or None, default=None

Directory override (see resolve_ref_base()).

Returns:
tuple[str, str] or None

(even_path, odd_path), or None if ref is not set.

property motl_type#

Motl type string for this format (implemented by subclasses).

resolve_ccmask(working_dir=None)#

novaSTA CC mask path – self.df['cc mask'] with optional override.

Parameters:
working_dirPathOrStr or None, default=None

Directory override (see _apply_working_dir()).

Returns:
str or None
resolve_mask(working_dir=None)#

novaSTA particle mask path – self.df['mask'] with optional override.

Parameters:
working_dirPathOrStr or None, default=None

Directory override (see _apply_working_dir()).

Returns:
str or None
resolve_ref_base(working_dir=None, separator='_')#

novaSTA reference base – self.df['ref'] + separator with optional override.

novaSTA stores the reference column as a base name (downstream appends <iter>.em); this helper mirrors get_motl_base_name() for symmetry.

Parameters:
working_dirPathOrStr or None, default=None

Directory override (see _apply_working_dir()).

separatorstr, default=’_’

Appended after the resolved path.

Returns:
str or None
resolve_wedge_list(working_dir=None)#

novaSTA wedge list path – self.df['wedge list'] with optional override.

Parameters:
working_dirPathOrStr or None, default=None

Directory override. Applied via _apply_working_dir() (relative paths get prepended; absolute paths have their directory replaced).

Returns:
str or None
write_out(path, create_ref=None, param_set='basic', strict=False)#

Write a novaSTA flat key-value parameter file.

Parameters:
pathPathOrStr

Destination path for the flat key-value file.

create_refbool or None, default=None

If None, uses the flag stored on the object.

param_set{“basic”, “full”}, default=”basic”

Controls which columns are emitted.

strictbool, default=False

If True, raise on validation problems; otherwise warn.

class cryocat.analysis.sta.StaParamContext(create_ref, ref_family, n_iterations, is_avg_row, sta_type, use_euler_search, _row)#

Bases: object

Context passed to mandatory_if lambdas during validation and write.

Parameters:
create_refbool

Whether an averaging pre-step is materialised on write.

ref_familyStaRefFamily

Reference strategy ("singleref", "multiref", "multiclass").

n_iterationsint

Total number of alignment iterations.

is_avg_rowbool

True when building the optional averaging row (STOPGAP only).

sta_typestr

Target format — "stopgap" or "novasta". Used by format-aware mandatory_if lambdas (e.g. rootdir is mandatory for STOPGAP only; fsc mask and pixel size are mandatory for novaSTA only).

use_euler_searchbool

When True and sta_type == "stopgap", the Euler parameterisation replaces the cone search — the four canonical angle extents become optional and the seven Euler columns become required.

_rowdict

Snapshot of the current row’s canonical column values (for cross-parameter dependencies in mandatory_if).

create_ref#
get(name, default=None)#
is_avg_row#
n_iterations#
ref_family#
sta_type#
class cryocat.analysis.sta.StaParamSpec(canonical, stopgap, novasta, dtype, default, literals=None, per_iteration=False, group='core', mandatory_if=None, to_format=None, from_format=None, note='')#

Bases: object

Descriptor for a single STA parameter across formats.

Parameters:
canonicalstr or None

Canonical df column name. None means STOPGAP-derived-only (e.g. angincr), which has no df column of its own.

stopgapstr or None

STOPGAP STAR column name without leading _. None = novaSTA only.

novastastr or None

novaSTA camelCase key. None = STOPGAP only.

dtypetype

Expected Python type (int, float, str, bool).

defaultAny

Default value, or the sentinel MANDATORY / DERIVED. Use None for optional parameters that have no meaningful default.

literalsAny, optional

Literal type alias whose get_args gives allowed string values.

per_iterationbool, optional

True when the parameter may vary per alignment iteration.

groupstr, optional

Logical group: "core", "filters", "angles", "full", "euler", "spectral", "cleaning", "extraction".

mandatory_ifcallable or None, optional

(ctx: StaParamContext) -> bool; parameter is required when this returns True AND default is MANDATORY (or default is a fall-back value for conditional requirements).

to_formatcallable or None, optional

(value, sta_type: str) -> Any; converts the canonical value to the format-specific representation on write. Used for parameters whose on-disk encoding differs between formats (e.g. symmetry Schoenflies vs. integer, split into even odd vs. ignore_halfsets inversion).

from_formatcallable or None, optional

(value, sta_type: str) -> Any; converts a format-specific value read from disk to the canonical representation on load. Symmetric with to_format.

notestr, optional

Free-text remark (e.g. open questions marked # CONFIRM:).

canonical#
default#
dtype#
from_format = None#
group = 'core'#
literals = None#
mandatory_if = None#
note = ''#
novasta#
per_iteration = False#
stopgap#
to_format = None#
class cryocat.analysis.sta.StaParameters(df, df_extra=None, create_ref=False, ref_family='singleref', use_euler_search=False)#

Bases: object

Base class for STA parameter file representations.

Both StopgapParams and NovaStaParams store all parameters in canonical column names (e.g. "motl", "wedge list", "low pass"). Format-specific names are applied only on write.

Attributes:
dfpandas.DataFrame

Canonical columns, one row per alignment iteration.

df_extrapandas.DataFrame

Format-specific extra columns not in the schema (same index as df).

df_statspandas.DataFrame or None

Per-iteration RMSE statistics populated by attach_log().

fscpandas.DataFrame or None

FSC curve populated by attach_fsc().

create_refbool

Whether an averaging pre-step should be materialised on write.

ref_familyStaRefFamily

Reference strategy: "singleref", "multiref", or "multiclass".

attach_fsc(path, pixel_size=None, box_size=None)#

Read and attach an FSC curve.

Parameters:
pathPathOrStr

Path to the FSC curve file.

pixel_sizefloat or None, default=None

Pixel size in Å.

box_sizeint or None, default=None

Subtomogram box size. If None, falls back to subtomo_size in df.

Returns:
pandas.DataFrame
attach_log(log_path)#

Parse a novaSTA log and attach per-iteration RMSE stats.

Parameters:
log_pathPathOrStr

Path to the novaSTA log file.

Returns:
pandas.DataFrame
property end_iteration#

Last iteration index, or None if df is empty.

classmethod from_dict(params, sta_type='novasta')#

Construct an StaParameters from a parameter dictionary (GUI path).

Parameters:
paramsdict

Keyed by canonical column names, snake_case, or novaSTA camelCase key names. Values may be scalars, lists, or whitespace-separated strings.

Control keys (extracted and not stored in df):

  • start_index / start index (int, default 1)

  • create_ref / create ref (bool, default False)

  • ref_family / ref family (StaRefFamily, default "singleref")

sta_typestr, default=”novasta”

Target subclass: "stopgap" or "novasta".

Returns:
StopgapParams or NovaStaParams
Raises:
ValueError

If per-iteration sequence lengths disagree.

Warns:
UserWarning

When mandatory parameters are absent (object is still created; use validate() for a complete problem list).

get_motl_base_name(separator='_', working_dir=None)#

Return the motl base name (column value + separator), or None.

The default implementation matches the novaSTA layout: the motl column already carries the (relative or absolute) full path and is used verbatim. working_dir, when supplied, overrides the directory portion of that path – relative paths are joined onto working_dir, absolute paths have their directory replaced with working_dir while the basename is preserved. Subclasses (e.g. StopgapParams) override this to honour their own directory conventions.

Parameters:
separatorstr, default=’_’

Appended to the motl path stored in df. Downstream loaders then append <iter><extension> to build per-iteration paths.

working_dirPathOrStr or None, default=None

Directory override. When None, the value stored in the params file is used as-is (current working directory is assumed for relative paths). When provided, it replaces the directory portion of the stored motl path – see _apply_working_dir() for the exact rules.

Returns:
str or None
classmethod load(path, sta_type=None, **kwargs)#

Load a parameter file, dispatching on sta_type or file extension.

Parameters:
pathPathOrStr

Path to the parameter file.

sta_typestr or None, default=None

"stopgap" or "novasta". If None, .star → stopgap, otherwise → novasta.

**kwargs

Forwarded to the subclass from_file.

Returns:
StopgapParams or NovaStaParams
property motl_type#

Motl type string for this format (implemented by subclasses).

property num_iterations#

Number of alignment iterations stored in df.

property start_iteration#

First iteration index, or None if df is empty.

to_novasta()#

Return a NovaStaParams backed by the same canonical df.

Format-specific column conversions (symmetry Schoenflies→integer; split into even odd bool→inverted integer) are applied eagerly to the copied df so that the result is a self-consistent novaSTA object. write_out further passes values through to_format; for already- converted values this is idempotent.

to_stopgap()#

Return a StopgapParams backed by the same canonical df.

Format-specific column conversions are applied eagerly; write_out / _build_row further pass values through to_format, which is idempotent for already-converted values.

validate(param_set='basic')#

Return a list of human-readable problem strings (empty = OK).

Parameters:
param_set{“basic”, “full”}, default=”basic”

"basic" checks only the 34 core STOPGAP parameters; "full" also checks full/euler/spectral groups.

Returns:
list of str

Empty when no problems were found.

Notes

Checks performed (in order):

  1. Missing MANDATORY parameters (considering mandatory_if conditions).

  2. Literal value violations.

  3. Per-iteration length disagreements.

  4. euler_axes axis constraint (second must differ from first).

  5. Cone/Euler mutual exclusivity.

class cryocat.analysis.sta.StaRun(input_motl_id, run_mode, output_base, folder_name, subtomo_path, base_params, schedule, n_runs=1, references=<factory>)#

Bases: object

Serialisable descriptor for one STOPGAP / novaSTA STA run.

Parameters:
input_motl_idstr

Pool ID of the input motl.

run_mode{“singleref”, “multiref”, “multiclass”}

Run mode (property of the run, not the block).

output_basePath

Parent directory inside which run folder(s) are created.

folder_namestr

Base name for the run folder. When n_runs > 1 the per-run suffix _mr{i} is appended automatically.

subtomo_pathPath

Path to the subtomogram directory; symlinked into each run folder.

base_paramsdict

Run-wide parameters (masks, wedgelist, binning, filters, angular search, …).

schedulelist[Block]

Per-block parameters. At least one Block required.

n_runsint, default=1

Number of parallel runs (mr1..mrN). Single run when 1.

referenceslist[Path], default=[]

Existing reference files (when applicable; copied to ref/).

base_params#
folder_name#
input_motl_id#
n_runs = 1#
output_base#
references#
run_mode#
schedule#
subtomo_path#
class cryocat.analysis.sta.StopgapParams(df, df_extra=None, create_ref=False, ref_family='singleref', use_euler_search=False)#

Bases: StaParameters

STOPGAP STAR-file subtomogram-averaging parameter representation.

All parameters are stored in df using canonical column names (e.g. "motl", "wedge list", "low pass"). STOPGAP-specific column names (e.g. motl_name, wedgelist_name, lp_rad) are applied only when writing. Raw STOPGAP angle-iteration columns (angincr, angiter, phi_angincr, phi_angiter) are converted to the canonical angle-extent form ("cone angle", "cone sampling", "inplane angle", "inplane sampling") on from_file() and converted back on write_out().

classmethod from_file(path, load_completed_only=False)#

Load a STOPGAP subtomogram parameter STAR file.

Parameters:
pathPathOrStr

Path to the STOPGAP .star parameter file.

load_completed_onlybool, default=False

If True, keep only rows where completed_ali == 1.

Returns:
StopgapParams
Raises:
ValueError

If the file specifier is wrong, or if columns still carry a leading _ after Starfile.read() strips one (indicating a double-underscore in the file from a broken writer).

get_half_map_paths(iteration, working_dir=None)#

Return the (half_A, half_B) half-map paths for a given iteration.

STOPGAP names half-maps as <refbase>_A_<iteration>.<ext> and <refbase>_B_<iteration>.<ext>. The extension (.em or .mrc) is resolved by checking what exists on disk; .em is the default when neither (or both) exist.

Parameters:
iterationint

Iteration number.

working_dirPathOrStr or None, default=None

Directory override (see resolve_ref_base()).

Returns:
tuple[str, str] or None

(path_A, path_B), or None if ref is not set.

Warns:
UserWarning

When both the .em and .mrc forms exist for the same half.

get_motl_base_name(separator='_', working_dir=None)#

STOPGAP motl base name – rootdir/lists/<motl><separator>.

STOPGAP runs follow a fixed directory layout under a single rootdir (stored as the rootdir column of every row): motls live in lists/, masks in masks/, and references in refs/. When working_dir is supplied it overrides the rootdir column; the lists/ subdirectory + the motl name column + separator are still appended verbatim. Downstream loaders append <iter>.star to form the per-iteration path.

Parameters:
separatorstr, default=’_’

Appended to the motl name.

working_dirPathOrStr or None, default=None

Directory override. When None, the rootdir column is used; when both are absent, only the motl name + separator is returned (no leading directory).

Returns:
str or None
property motl_type#

Motl type string for this format (implemented by subclasses).

resolve_ccmask(working_dir=None)#

STOPGAP CC mask path – rootdir/masks/<cc mask>.

Parameters:
working_dirPathOrStr or None, default=None

Overrides the rootdir column when supplied.

Returns:
str or None
resolve_mask(working_dir=None)#

STOPGAP particle mask path – rootdir/masks/<mask>.

Parameters:
working_dirPathOrStr or None, default=None

Overrides the rootdir column when supplied.

Returns:
str or None
resolve_ref_base(working_dir=None, separator='_')#

STOPGAP reference base name – rootdir/refs/<ref><separator>.

Downstream code appends <iter>.em to form the per-iteration reference path, mirroring the motl-base-name convention.

Parameters:
working_dirPathOrStr or None, default=None

Overrides the rootdir column when supplied.

separatorstr, default=’_’

Appended to the reference name.

Returns:
str or None
resolve_wedge_list(working_dir=None)#

STOPGAP wedge list path – rootdir/lists/<wedge list>.

Parameters:
working_dirPathOrStr or None, default=None

Overrides the rootdir column when supplied.

Returns:
str or None
write_out(path, create_ref=None, ref_family=None, total_iterations=None, param_set='basic', strict=False)#

Write a STOPGAP subtomogram parameter STAR file.

Parameters:
pathPathOrStr

Destination path for the .star file.

create_refbool or None, default=None

If None, uses the value stored on the object.

ref_familyStaRefFamily or None, default=None

"singleref", "multiref", or "multiclass". If None, uses the value stored on the object.

total_iterationsint or None, default=None

If larger than the current alignment-iteration count, pad with extra rows (params copied from the last row, progress flags 0).

param_set{“basic”, “full”}, default=”basic”

"basic" writes the 34 standard STOPGAP columns. "full" additionally writes full/euler/spectral groups. Auto-promotes to "full" when any full-group columns are set in df.

strictbool, default=False

If True, raise ValueError on validation problems instead of emitting a warning.

cryocat.analysis.sta.build_coassignment_factor(dataframes, particle_column='subtomo_id', class_column='class', run_labels=None)#

Build the factored co-assignment representation from several runs.

Particles are matched across runs by particle_column, never by row order. Class labels need not be consistent between runs; co-assignment is permutation invariant.

Parameters:
dataframeslist of pandas.DataFrame

One per classification run; each must contain both columns.

particle_columnstr, default=’subtomo_id’

Column holding particle identifiers, unique within each run.

class_columnstr, default=’class’

Column holding the within-run class assignment.

run_labelslist of str, optional

Names for the runs, in order. Defaults to run_1 ... run_R.

Returns:
CoassignmentFactor
Raises:
UserInputError

If fewer than two runs are given, a required column is missing, a run is empty, or a run repeats a particle identifier.

cryocat.analysis.sta.build_ctx(*, sta_type='stopgap', create_ref=False, ref_family='singleref', n_iterations=1, is_avg_row=False, use_euler_search=False, row=None)#

Build a StaParamContext for use with is_mandatory().

Parameters:
sta_type{“stopgap”, “novasta”}, default=”stopgap”
create_refbool, default=False
ref_familyStaRefFamily, default=”singleref”
n_iterationsint, default=1
is_avg_rowbool, default=False
use_euler_searchbool, default=False
rowdict or None, default=None

Canonical column values for the current row (used by cross-parameter mandatory_if dependencies). None is treated as empty.

Returns:
StaParamContext
cryocat.analysis.sta.compose_subtomo_mode(job, run_mode)#

Compose a STOPGAP subtomo_mode string.

Parameters:
job{“avg”, “ali”}
run_mode{“singleref”, “multiref”, “multiclass”}
Returns:
str

One of the six StaSubtomoMode literals.

Examples

>>> compose_subtomo_mode("ali", "multiref")
'ali_multiref'
cryocat.analysis.sta.compute_alignment_statistics(motl_base_name, start_it, end_it, motl_type='stopgap', filter_rows=None, filter_column_name='subtomo_id', output_path=None, load_kwargs=None)#

Compute alignment statistics for specified motls and iterations. Pairs of (current motl, subsequent motl) are evaluated for differences in cone angles, in-plane angles, change in positions of particles and root mean square errors (RMSE) in x, y, and z directions. The output contains mean, median, std, and variance for cone and in-plane angles, the mean distance between the particles and the RMSE of movement in x, y, and z directions.

Parameters:
motl_base_namestr

Base name for a motl to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’stopgap’

Type of the input motl.

filter_rowsListLike or None, default=None

Rows to filter. Only rows that are within the filter_rows will be kept. None means no filtering.

filter_column_nameMotlColumn, default=’subtomo_id’

Column based on which the filtering is performed. Ignored when filter_rows is None.

output_pathPathOrStr or None, default=None

Output file for the statistics. If None no file will be written out.

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
pandas DataFrame

Comptuted statistics of the alignment for the specified iterations.

Examples

>>> # No filtering, motls motl_1.star to motl_17.star will be loaded for evaluation. Statistics
>>> # will be written into /path/to/the/motl_alignment_stats.csv file.
>>> stats_df = compute_alignment_statistics(
...    "/path/to/the/motl_", 1, 17,
...     motl_type="stopgap", output_path="/path/to/the/motl_alignment_stats.csv"
... )
>>> # Motls motl_1.star to motl_17.star will be loaded for evaluation, no file will be written out.
>>> # Filtering will be done based on column geom3 and only particles with values in filter_rows will be evaluated.
>>> stats_df = compute_alignment_statistics(
...     "/path/to/the/motl_", 1, 17,
...     filter_rows=values_to_keep_for_motl, filter_column_name="geom3",
...     motl_type="stopgap"
... )
cryocat.analysis.sta.compute_alignment_statistics_from_params(input_params, sta_type=None, motl_separator='_', working_dir=None, **kwargs)#

Run compute_alignment_statistics() driven by a parameter file, dict, or object.

Parameters:
input_paramsPathOrStr, dict, or StaParameters

Path to a parameter file, a canonical parameter dict, or an already- loaded StaParameters object.

sta_typestr or None, default=None

"stopgap" or "novasta". Auto-detected from extension if None.

motl_separatorstr, default=’_’

Appended to the stored motl path to form the base name.

working_dirPathOrStr or None, default=None

Optional directory override. See evaluate_alignment_from_params() for the per-format rules.

**kwargs

Forwarded to compute_alignment_statistics().

Returns:
pandas.DataFrame
cryocat.analysis.sta.compute_startidx_sequence(schedule, starting_iter=1)#

Return the startidx for every block in schedule.

The first block starts at starting_iter; each subsequent block starts immediately after the previous one finishes.

Parameters:
schedulelist[Block]

Ordered list of blocks.

starting_iterint, default=1

Absolute iteration index of the very first iteration.

Returns:
list[int]

One entry per block in the same order as schedule.

Examples

>>> blks = [Block(1, "avg", "{base}"), Block(10, "ali", "{base}"), Block(20, "ali", "{base}")]
>>> compute_startidx_sequence(blks, starting_iter=1)
[1, 2, 12]
cryocat.analysis.sta.consensus_groups(factor, min_agreement=1.0, linkage='complete', min_group_size=10, junk_class=0)#

Group particles that co-occur in at least min_agreement of the runs.

Parameters:
factorCoassignmentFactor

Built by build_coassignment_factor().

min_agreementfloat, default=1.0

Fraction of runs in which a pair must share a class to be grouped together. Snapped up to the nearest achievable k/R value.

linkage{‘complete’, ‘average’, ‘single’}, default=’complete’

Agglomerative linkage rule. Ignored at min_agreement=1.0. 'single' is warned against: a single weak link can chain two genuine classes.

min_group_sizeint, default=10

Groups smaller than this collapse to junk_class.

junk_classint, default=0

Class label written for unassigned / small-group particles.

Returns:
ConsensusResult
cryocat.analysis.sta.consensus_motl(result, source_motl, class_column='class', keep_junk=True)#

Geometry from source_motl, consensus classes written to class_column.

Parameters:
resultConsensusResult

Output of consensus_groups().

source_motlMotl

Provides the particle geometry; matched by subtomo_id.

class_columnstr, default=’class’

Column in the motl DataFrame to overwrite with consensus labels.

keep_junkbool, default=True

If False, drop particles absent from the factor or in the junk class.

Returns:
Motl

A copy of source_motl with class_column updated.

cryocat.analysis.sta.continue_run_prefill(last_row)#

Extract the starting-iteration and base-params for a continue run.

Parameters:
last_rowdict

Canonical column values from the last row of an existing parameter file (i.e. params.df.iloc[-1].to_dict()).

Returns:
dict

{"starting_iter": int, "base_params": dict}

Notes

The temperature field is forced to 0 in the returned base_params because simulated annealing is only meaningful at the start of a de-novo run — see spec §A5.

cryocat.analysis.sta.create_denovo_multiref_run(input_motl, number_of_classes, output_motl_base, input_motl_type='emmotl', class_occupancy=None, iteration_number=1, number_of_runs=1, output_motl_type='stopgap')#

Creates number_of_runs motls for reference averaging and one motl for alignment. The motls for reference averaging are created by random selection of N particles for each class from the input_motl, where N equals to class_occupancy. The particles within the classes of each motl can overlap, i.e. each class will have a unique set of particles, but some particles can be assigned in mutliple classes. The alignment motl is just input motl where the class was randomly assign to be from 1 to number_of_classes. The idea behind this is to run multi-reference alignment where different runs will have different starting references while due to simmulated annealing only one motl for alignment is needed afterwards.

Parameters:
input_motlMotlSource

Input motl (specified either as a path, DataFrame or Motl object).

number_of_classesint

Number of classes to create references for and to assign randomly to the alignment motl.

output_motl_basePathOrStr

Base path for the output motl files. The final name will be created as output_motl_base_ref_mr#runID_iterationNumber where runID is from 1 to number_of_runs and iterationNumber is iteration_number. The alignment motl will be named output_motl_base_iterationNumber. Extension is determined by output_motl_type.

input_motl_typeMotlType, default=’emmotl’

Type of the input motl file.

class_occupancyint or None, default=None

Number of particles per class for the reference averaging motls. If None, the number is determined as 1/10 of total number of particles in the input motl.

iteration_numberint, default=1

Iteration number to be used in the output name creation.

number_of_runsint, default=1

Number of motls to create.

output_motl_typestr, default=’stopgap’

Type of the output motl file (see write_out_motl() for accepted values).

Returns:
list[Path]

Paths of every motl file written: number_of_runs reference motls followed by the single shared alignment motl.

Examples

>>> # Will create two motls in stopgap format with names stopgap_dn_ref_mr1_4.star and stopgap_dn_ref_mr2_4.star for
>>> # reference averaging and one alignment motl stopgap_dn_4.star. In each motl, the particles will have 8 classes.
>>> # The alignment motl will have same number of particles as the input_motl, the reference motls will have
>>> # number_of_classes * class_occupancy (16 000) particles each.
>>> create_denovo_multiref_run(
... "/path/to/relion_1.star", number_of_classes=8, output_motl_base="stopgap_dn",
... input_motl_type="relion", class_occupancy = 2000, iteration_number=4, number_of_runs=2,
... output_motl_type="stopgap"
... )
cryocat.analysis.sta.create_multiref_run(input_motl, number_of_classes, output_motl_base, input_motl_type='emmotl', iteration_number=1, number_of_runs=1, output_motl_type='stopgap')#

Creates motls for multiple runs of a multi-reference alignment. In essence, it will randomly assign specified number of classes to each motl that will be created. New motls will be written out into files output_motl_base_mr#runID_iterationNumber either in stopgap, emmotl or relion format.

Parameters:
input_motlMotlSource

Input motl (specified either as a path, DataFrame or Motl object).

number_of_classesint

Number of classes to assign randomly.

output_motl_basePathOrStr

Base path for the output motl files. The final name will be created as output_motl_base_mr#runID_iterationNumber where runID is from 1 to number_of_runs and iterationNumber is iteration_number. The extension is determined by output_motl_type.

input_motl_typeMotlType, default=’emmotl’

Type of the input motl file.

iteration_numberint, default=1

Iteration number to be used in the output name creation.

number_of_runsint, default=1

Number of motls to create.

output_motl_typestr, default=’stopgap’

Type of the output motl file (see write_out_motl() for accepted values).

Returns:
list[Path]

Paths of every motl file written (one per run).

Examples

>>> # Will create two motls in stopgap format with names stopgap_classes_mr1_4.star and stopgap_classes_mr2_4.star
>>> create_multiref_run(
... "/path/to/relion_1.star", number_of_classes=8, output_motl_base="stopgap_classes",
... input_motl_type="relion", iteration_number=4, number_of_runs=2,
... output_motl_type="stopgap"
... )
cryocat.analysis.sta.create_run_folder(sta_run, motl_paths, starting_iter=1, overwrite=False)#

Create STOPGAP run folders according to the C1 layout spec.

Validates first (via preflight_run_folder()), then creates everything atomically (all or nothing per run).

Parameters:
sta_runStaRun

Run descriptor.

motl_pathslist[Path]

Paths of motl files to copy into lists/.

starting_iterint, default=1

First iteration index for the startidx sequence.

overwritebool, default=False

When True, remove existing run folders before creating. Never merges — partial overwrites are not permitted.

Returns:
dict

Manifest with keys "dirs_created", "files_copied", "symlinks_created" — each a list of str paths.

Raises:
FileExistsError

When a target folder already exists and overwrite is False.

ValueError

When overwrite is True but the folder cannot be removed.

cryocat.analysis.sta.denovo_template_blocks()#

Return the 3-block de-novo reference creation template.

Consists of 1 averaging block ({base}_ref_mr{run}) followed by 10 SHC-annealing alignment iterations and 20 SHC zero-temperature alignment iterations (30 total).

Returns:
list[Block]
cryocat.analysis.sta.evaluate_alignment(motl_base_names, start_it, end_it, motl_type='stopgap', write_out_stats=False, plot_values=True, filter_rows=None, filter_column_name='subtomo_id', labels=None, graph_title='Alignment stability', graph_output_file=None, load_kwargs=None)#

Evaluate alignment stability for specified motls and iterations.

Parameters:
motl_base_namesListLike of str

List of MOTL base names or a single motl base name to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’stopgap’

Type of the input motl.

write_out_statsbool, default=False

Whether to write out stats. If True, the stats will be written to the motl_base_name + _as_motlID.csv where the motlID is given by its position in the motl_base_names list. For example, for motl_shift_3.em the final will be motl_shift_as_1.em if the motl_shift_ is the first motl in the motl_base_names.

plot_valuesbool, default=True

Whether to plot values.

filter_rowsListLike or None, default=None

Rows to filter. Only rows that are within the filter_rows will be kept. None means no filtering.

filter_column_nameListLike of MotlColumn, default=’subtomo_id’

Column name(s) based on which the filtering is performed. Ignored when filter_rows is None.

labelsListLike of str or None, default=None

Labels for the plot. Should have the same length as the motl_base_names. In case of None, the labels will be automatically set as motl_base_names (paths are stripped). Used only if plot_values is True.

graph_titlestr, default=’Alignment stability’

Title of the graph. Used only if plot_values is True.

graph_output_filePathOrStr or None, default=None

Output file for the graph. Used only if plot_values is True. If None no file will be written out.

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
list of pandas DataFrames

List of computed alignment stability statistics dataframes.

Examples

>>> # Single motl, no filtering, motls motl_1.star to motl_17.star will be loaded for evaluation. Statistics
>>> # will be written into /path/to/the/motl_as_1.csv file.
>>> motl_base_name = "/path/to/the/motl_"
>>> stats_df = evaluate_alignment(motl_base_name, 1, 17, motl_type="stopgap", plot_values=True,write_out_stats=True)
>>> # Multiple motls, no filtering, motls motl1_1.star to motl1_17.star and motl3_1.star to motl3_17.star
>>> # will be loaded for evaluation. Statistics will be written into /path/to/the/motl1_as_1.csv and
>>> # /path/to/the/motl3_as_2.csv files.
>>> motl_base_names = ["/path/to/the/motl1_", "/path/to/the/motl3_"]
>>> stats_df = evaluate_alignment(motl_base_names, 1, 17, motl_type="stopgap", plot_values=True, write_out_stats=True)
>>> # Multiple motls, motls motl1_1.star to motl1_17.star and motl3_1.star to motl3_17.star will be loaded for
>>> # evaluation. Statistics will be written into /path/to/the/motl1_as_1.csv and /path/to/the/motl3_as_2.csv files.
>>> # Filtering will be done based on column geom3 and only particles with values in filter_rows will be evaluated.
>>> motl_base_names = ["/path/to/the/motl1_", "/path/to/the/motl3_"]
>>> filter_rows = [values_to_keep_for_motl1, values_to_keep_for_motl3]
>>> stats_df = evaluate_alignment(
...     motl_base_names, 1, 17,
...     filter_rows=filter_rows, filter_column_name="geom3",
...     motl_type="stopgap", plot_values=True, write_out_stats=True
... )
>>> # Multiple motls, motls motl1_1.star to motl1_17.star and motl3_1.star to motl3_17.star will be loaded for
>>> # evaluation. Statistics will be written into /path/to/the/motl1_as_1.csv and /path/to/the/motl3_as_2.csv files.
>>> # Filtering will be done based on column geom3 for motl1 and based on subtomo_id for motl3.
>>> # Only particles with values in filter_rows will be evaluated.
>>> motl_base_names = ["/path/to/the/motl1_", "/path/to/the/motl3_"]
>>> filter_rows = [values_to_keep_for_motl1, values_to_keep_for_motl3]
>>> filter_column_name = ["geom3", "subtomo_id"]
>>> stats_df = evaluate_alignment(
...     motl_base_names, 1, 17,
...     filter_rows=filter_rows, filter_column_name=filter_column_name,
...     motl_type="stopgap", plot_values=True, write_out_stats=True
... )
>>> # Multiple motls, motls motl1_1.star to motl1_17.star and motl3_1.star to motl3_17.star will be loaded for
>>> # evaluation. Statistics will be written into /path/to/the/motl1_as_1.csv and /path/to/the/motl3_as_2.csv files.
>>> # Filtering will be done based on column geom3 for motl1 and no filtering will be done for motl3.
>>> # Only particles with values in filter_rows will be evaluated.
>>> motl_base_names = ["/path/to/the/motl1_", "/path/to/the/motl3_"]
>>> filter_rows = [values_to_keep_for_motl1, None]
>>> filter_column_name = ["geom3", None]
>>> stats_df = evaluate_alignment(
...     motl_base_names, 1, 17,
...     filter_rows=filter_rows, filter_column_name=filter_column_name,
...     motl_type="stopgap", plot_values=True, write_out_stats=True
... )
cryocat.analysis.sta.evaluate_alignment_from_params(input_params, sta_type=None, motl_separator='_', working_dir=None, **kwargs)#

Run evaluate_alignment() driven by a parameter file, dict, or object.

Pulls motl_base_name, start_iteration, end_iteration, and motl_type directly off the resolved StaParameters instance and forwards everything else through to evaluate_alignment().

Parameters:
input_paramsPathOrStr, dict, or StaParameters

Path to a parameter file, a canonical parameter dict, or an already- loaded StaParameters object.

sta_typestr or None, default=None

"stopgap" or "novasta". Auto-detected from extension if None.

motl_separatorstr, default=’_’

Appended to the stored motl path to form the base name (e.g. "./allmotl_lt" → "./allmotl_lt_").

working_dirPathOrStr or None, default=None

Optional directory override. For STOPGAP it replaces the rootdir column (the lists/ subdirectory is still appended, so the motl prefix becomes working_dir/lists/<motl name>_). For novaSTA it overrides the directory portion of the stored motl path – relative paths get prepended, absolute paths have their directory replaced. Pass None to use the path embedded in the parameter file as-is.

**kwargs

Forwarded to evaluate_alignment(). motl_type defaults to the format-native type ("stopgap" or "emmotl") if not supplied.

Returns:
list of pandas.DataFrame
cryocat.analysis.sta.evaluate_classification(motl_base_name, start_it, end_it, motl_type='stopgap', output_file_stats=None, plot_results=False, output_file_graphs=None, load_kwargs=None)#

Get the occupancy of each class over the iterations and the class stability of subtomograms over iterations.

Parameters:
motl_base_namestr

Base name for a motl to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’stopgap’

Type of the input motl.

output_file_statsPathOrStr or None, default=None

Name of the file into which the results will be written out. If None, no results will be written out.

plot_resultsbool, default=False

Whether to plot the results.

output_file_graphsPathOrStr or None, default=None

Name of the file into which the plotted graphs will be written out. If None, the graphs will not be written out. Ignored when plot_results is False.

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
occupancydict

A dictionary containing the occupancy of each class over the iterations.

changing_subtomosdict

A dictionary containing the number of different subtomogram IDs for each class over iterations.

cryocat.analysis.sta.evaluate_multirun_stability(input_motls, input_motl_type='stopgap')#

Evaluate how many particles ended up within the same class among all the classification runs. It is meant to be used for multiruns with existing references (i.e. not de novo ones) where all runs uses the same references in the same order.

Parameters:
input_motlslist of MotlSource

List of input motls (paths, DataFrames, or Motl objects). At least two are required.

input_motl_typeMotlType, default=’stopgap’

Type of the input motl.

Returns:
common_occupanciesdict

A dictionary containing common subtomo_ids for each class of particles.

cryocat.analysis.sta.existing_refs_template_blocks()#

Return the 2-block classification-with-existing-references template.

Consists of 1 HC alignment iteration followed by 29 SHC iterations (30 total), temperature 0 throughout.

Returns:
list[Block]
cryocat.analysis.sta.expand_motl_name(pattern, *, base, run, iter_)#

Expand a motl name pattern with {base}, {run}, {iter} placeholders.

Parameters:
patternstr

Template string, e.g. "{base}_ref_mr{run}" or "{base}".

basestr

Value to substitute for {base}.

runint

Value to substitute for {run}.

iter_int

Value to substitute for {iter}.

Returns:
str

Examples

>>> expand_motl_name("{base}_ref_mr{run}", base="motl", run=2, iter_=1)
'motl_ref_mr2'
cryocat.analysis.sta.get_choices(spec)#

Return the allowed literal values for spec, or an empty tuple.

Parameters:
specStaParamSpec
Returns:
tuple of str
cryocat.analysis.sta.get_class_occupancy(motl_base_name, start_it, end_it, motl_type='stopgap', load_kwargs=None)#

Get the occupancy of each class over the iterations.

Parameters:
motl_base_namestr

Base name for a motl to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’stopgap’

Type of the input motl.

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
occupancydict

A dictionary containing the occupancy of each class over the iterations.

Notes

Loading of many motls can take some time. If you also want to compute stability of classes it is recommended to use cryocat.analysis.sta.evaluate_classification() which gives both occupancy and stability and reads in all the motls only once.

cryocat.analysis.sta.get_default(spec)#

Return the default value for spec, or None for MANDATORY/DERIVED.

Parameters:
specStaParamSpec
Returns:
Any
cryocat.analysis.sta.get_motl_extension(motl_type)#

Return the file extension for a given motl type.

Parameters:
motl_typeMotlType

The type of motl file ('emmotl', 'relion', 'relion5', 'relion5_1', or 'stopgap').

Returns:
str

The file extension corresponding to the motl type.

Raises:
ValueError

If the motl type is not supported.

cryocat.analysis.sta.get_motl_filename(motl_base_name, iteration, motl_type)#

Construct the full filename for a motl file given a base name, iteration, and type.

For Relion-type motls the iteration number is zero-padded to three digits and the suffix _data.star is appended. For all other types the extension is determined by get_motl_extension().

Parameters:
motl_base_namestr

Base name for the motl file, without the iteration number or extension. For example, for motl_shift_3.em the base name is motl_shift_.

iterationint

Iteration number to embed in the filename.

motl_typeMotlType

Type of the motl file (e.g. 'emmotl', 'stopgap', 'relion', 'relion5', 'relion5_1'). Any value containing 'relion' triggers zero-padded three-digit formatting.

Returns:
str

Full filename constructed from motl_base_name, iteration, and the appropriate extension or suffix for the given motl_type.

cryocat.analysis.sta.get_schema(sta_type, *, include_derived=False, groups=None)#

Return schema entries relevant to sta_type.

Parameters:
sta_type{“stopgap”, “novasta”}

Filter by format: STOPGAP-only entries have novasta=None; novaSTA-only entries have stopgap=None. Shared entries appear in both.

include_derivedbool, default=False

Include entries whose default is DERIVED (e.g. iteration counter columns that are computed on write, not stored in the canonical df).

groupsset of str or None, default=None

Restrict to entries in these logical groups. None returns all groups.

Returns:
list of StaParamSpec
cryocat.analysis.sta.get_shared_schema(*, include_derived=False, groups=None)#

Return schema entries that appear in both STOPGAP and novaSTA.

Parameters:
include_derivedbool, default=False
groupsset of str or None, default=None
Returns:
list of StaParamSpec
cryocat.analysis.sta.get_stable_particles(motl_base_name, start_it, end_it, motl_type='emmotl', load_kwargs=None)#

Load and analyze particle data across multiple iterations to identify stable particles, i.e. particles that do not change their class.

Parameters:
motl_base_namestr

Base name for a motl to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’emmotl’

Type of the input motl. One of the standard motl-format identifiers ('emmotl', 'stopgap', 'relion', 'relion5', 'relion5_1').

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
list

List of subtomo_ids that have the same class across the specified iterations.

Notes

This function loads motive list files from specified iterations, merges them, and identifies subtomo_ids (subtomogram identifiers) that have a consistent class across all iterations. The percentage of stable particles relative to the total number of particles in the first iteration is printed.

cryocat.analysis.sta.get_subtomos_class_stability(motl_base_name, start_it, end_it, motl_type='stopgap', load_kwargs=None)#

Calculate the class stability of subtomograms over iterations.

Parameters:
motl_base_namestr

Base name for a motl to perform the evaluation on. Base name means without the iteration number and extension. For example for name motl_shift_3.em the base name is motl_shift_.

start_itint

Starting iteration number.

end_itint

Ending iteration number.

motl_typeMotlType, default=’stopgap’

Type of the input motl.

load_kwargsdict or None, default=None

Dictionary of keyword arguments passed to the Motl.load method (and subsequently to the underlying Motl class constructors like ‘RelionMotl’ and RelionMotlv5). This is useful for providing necessary metadata like pixel_size, binning, optics_data, or custom formats (tomo_format, subtomo_format).

Returns:
different_sidsdict

A dictionary containing the number of different subtomogram IDs for each class over iterations.

Notes

Loading of many motls can take some time. If you also want to compute occupancy of classes it is recommended to use cryocat.analysis.sta.evaluate_classification() which gives both occupancy and stability and reads in all the motls only once.

cryocat.analysis.sta.is_mandatory(spec, ctx)#

Return whether spec is required under ctx.

Parameters:
specStaParamSpec
ctxStaParamContext

Built via build_ctx().

Returns:
bool
cryocat.analysis.sta.nova_to_stopgap_angles(cone_angle, cone_sampling, inplane_angle, inplane_sampling)#

Convert novaSTA angle extents to STOPGAP angle iteration counts.

Parameters:
cone_anglefloat
cone_samplingfloat
inplane_anglefloat
inplane_samplingfloat
Returns:
angiter, angincr, phi_angiter, phi_angincrint or float
cryocat.analysis.sta.preflight_run_folder(sta_run, motl_paths, starting_iter=1)#

Validate all inputs for a run-folder creation without touching the filesystem.

All problems are collected before returning (not stop-at-first).

Parameters:
sta_runStaRun

Run descriptor.

motl_pathslist[Path]

Paths returned by create_multiref_run() or create_denovo_multiref_run().

starting_iterint, default=1
Returns:
list[str]

Human-readable problem descriptions; empty list means OK to proceed.

cryocat.analysis.sta.process_warp_subtomos(input_motl, output_path, tomo_id=None, output_motl=None, motl_type='emmotl', flip_map=False, sort_by_tomo=True, base_folder=None, subtomo_prefix='subtomo_', file_format='mrc', relion_kwargs=None, output_kwargs=None)#

Multiply Warp2 subtomograms by their CTF and write them into one folder, sequentially numbered after sorting by tomogram.

Parameters:
input_motlMotlSource

Warp2 RELION star file (or any MotlSource accepted by load()). When loading from a file, the motl type is always "relion"; pass relion-specific options via relion_kwargs.

output_pathPathOrStr

Folder for the output subtomograms. Created if it does not exist. Each file is named {subtomo_prefix}{subtomo_id}.{file_format}.

tomo_idListLike or None, optional

Process only these tomogram IDs (for parallelisation). Particle numbering is computed on the full star file so IDs are identical across parallel jobs. Default: all tomograms.

output_motlPathOrStr or None, optional

If given, the full sorted motl (all tomograms) is written to this path using motl_type and output_kwargs.

motl_typeMotlType, default "emmotl"

Format used when writing output_motl.

flip_mapbool, default False

Mirror each subtomogram volume along z around the box centre (N/2 for even N). Applied during the per-subtomogram loop independently of flip_handedness.

sort_by_tomobool, default True

If True, sort particles by tomo_id (stable sort, preserving star-file order within each tomogram) before renumbering. If False, particles are renumbered in their current order without any reordering.

base_folderPathOrStr or None, optional

Folder the relative paths inside the star file are resolved against. Default: paths are used as-is.

subtomo_prefixstr, default "subtomo_"

Prefix prepended to the subtomogram ID in each output file name.

file_format{“mrc”, “em”}, default "mrc"

Output file format for each subtomogram.

relion_kwargsdict or None, optional

Keyword arguments forwarded to the RELION motl loader (RelionMotl). Recognised keys: version, pixel_size, binning, optics_data.

output_kwargsdict or None, optional

Keyword arguments forwarded to write_out() when writing output_motl (beyond motl_type).

Returns:
cryomotl.Motl

The sorted (and optionally flipped) motl with new 1-based subtomo_id values.

cryocat.analysis.sta.reliability_summary(factor)#

Agreement histogram plus a verdict on whether the ensemble supports a stable grouping.

Returns:
dict with keys:

histogram — pd.DataFrame | None eigenvalues — np.ndarray reliable — bool verdict — str n_runs — int n_particles — int

cryocat.analysis.sta.sta_log_read(log_path)#

Parse a novaSTA log file into a per-iteration RMSE statistics DataFrame.

Each iteration block is delimited by a line matching Starting iteration #N. Within each block the RMSE lines are harvested.

Parameters:
log_pathPathOrStr

Path to the novaSTA log file.

Returns:
pandas.DataFrame

Columns: iteration, rmse_x, rmse_y, rmse_z, rmse_rotation, rmse_angular_distance, rmse_inplane_rotation (only labels present in the file appear as columns). One row per iteration.

cryocat.analysis.sta.stopgap_to_nova_angles(angiter, angincr, phi_angiter, phi_angincr)#

Convert STOPGAP angle iteration counts to novaSTA angle extents.

Parameters:
angiterint

Cone angle step count (STOPGAP _angiter).

angincrfloat

Cone angle step size in degrees (STOPGAP _angincr).

phi_angiterint

In-plane angle step count (STOPGAP _phi_angiter).

phi_angincrfloat

In-plane angle step size in degrees (STOPGAP _phi_angincr).

Returns:
cone_angle, cone_sampling, inplane_angle, inplane_samplingfloat

Notes

cone_angle = 2 * ceil(angiter/2) * angincr loses the parity of an odd angiter. A STOPGAP→novaSTA→STOPGAP round-trip may therefore turn an odd angiter into angiter + 1 while leaving cone_angle unchanged. Treat the novaSTA (angle-extent) convention as canonical when both are available. cone_angle == 0 (i.e. angiter == 0) indicates an averaging-only step.

cryocat.analysis.sta.validate_ref_mapping(mapping)#

Validate a reference-renaming mapping table before applying it.

Each entry in mapping is {"src_run": int, "src_class": int, "src_iter": int, "dst_class": int, "src_ref_dir": str}.

Checks performed:

  • Target classes are contiguous starting from 1.

  • For every source entry, the main map plus A and B half maps exist.

Parameters:
mappinglist[dict]

Rows from the reference-renaming table in the GUI.

Returns:
list[str]

Validation errors; empty list means the mapping is valid.

cryocat.analysis.sta.write_out_motl(input_motl, output_file_base, output_motl_type)#

Writes out a given motl file to a specified output format.

Parameters:
input_motlMotlSource

Input motl to be written out (a Motl, a DataFrame, or a path). Only the .df attribute is read.

output_file_basePathOrStr

Base path for the output file (extension is appended automatically).

output_motl_typestr

Type of the output motl file – one of 'stopgap', 'relion', 'relion5', 'relion5_1', 'emfile'. 'emfile' is accepted here for historical reasons and maps to an EmMotl write; for new code prefer the standard MotlType enum value 'emmotl' via the cryocat.core.cryomotl.Motl API.

Returns:
None
Raises:
ValueError

If the output_motl_type is not one of the supported types.