cls_expansion: method and benchmarks¶
simple_exec prg=cls_expansion projfile=... ncls=<total subclasses> mskdiam=... nparts=10 nthr=8
The flex covariance model replaced the diffusion-map cls_split on 2026-10-05. Since 2026-10-12
ncls is the total number of subclasses (section 0); the benchmarks of section 2 were run with the
earlier fixed count per class (ncls=3 meant three per class). Since 2026-10-12 the sub-class averages
are the model's conditional averages (section 1, steps 4-5); the benchmarks of sections 2-4 were made
with the earlier soft-weighted member averages and the cross-fit. Since 2026-10-14 the kernel pre-images of as many
members as the budget, with a cross-validated latent rank and bandwidth, replace steps 3-5 of section 1
(cls_expansion_kernel_preimages.md): placement and the conditional averages were removed from the code, so
those steps describe history.
0. Subclass budget¶
Before any split, on the master (or the shared-memory run):
- Groups. The parent classes are clustered by their class averages exactly as for
balance=cavgsampling (cluster_cavgs_into_groups: average linkage on the in-plane, shift and mirror invariant correlation at 6 A,nclustgroups, default 20; every class its own group when there are no more classes thannclust, or when the project has no class averages orfrc2D). Classes of one view fall in one group, so classes that are essentially the same share a budget. - Capacity. A class of at least
max(2 minpop, 3 (neigs + 1))particles holds up tofloor(pop / minpop)subclasses (minpopdefault 25); any other class one, i.e. it is kept whole (its average is the class's CTF-corrected mean, with even/odd halves; nothing is dropped). - Group totals. Starting from one per class, the subclasses go one at a time to the open group
with the highest
P_g^0.5 / (T_g + 0.5)(Webster),P_gthe group population andT_gits current total, up to the group's capacity. The classes 2D already made of a view count against that view's share. - Within a group. The group's extra subclasses go one at a time to the class with the highest
pop / (n + 0.5), up to its capacity. nclsmust be at least the number of classes; when the capacities hold fewer, the run warns and delivers what they hold. The budget is written tocls_expansion_allocation.txt(class, group, pop, nsub) and read by the workers; the groups tocls_expansion_groupsNN_cavgsandcls_expansion_groups.txt.
1. Method¶
Per 2D class with two or more subclasses in the budget, with every member in the class frame by its own in-plane alignment:
- Model.
y_i = c_i (mu + U z_i + N nu_i) + noiseon the Fourier half-plane:c_ithe member's CTF,muthe class mean,Ua rank-16 basis (neigs=),Nfour nuisance columns (the pose tangents dx, dy, dtheta of the class mean and the mean itself for contrast),z_ithe latent. Noise weights from the sigma2 shell spectrum (else the class's residual spectrum). Fitted by an ALS probe (3 random starts) then PPCA EM, in sample. The members are masked in the class frame by the box's inscribed circle (soft edge): the box corners that the in-plane rotation moves would otherwise become directions of variation; nothing inside the box, beyondmskdiamincluded, is cut. - Bands. With
lp=the fit band islp. Otherwise it is derived per class: a first fit to half the class's resolution shell (the class mean's even/odd FRC at 0.143), at most 20 A; the even/odd FRC per shell of that basis, extended to every coefficient, sets the global band where it falls below 0.5, never finer than the first fit (a finer band let reproducible high-resolution variation, such as residual misalignment, crowd the coarse motion out of the latent). - Placement. Divisive bisection of
[z, log residual](the residual detrended against CTF power) into exactly the class's budgeted number of leaves: 2-means candidates on the full latent and on each coordinate, scored by Ashman's D along the cut axis, the leaf with the best cut split next; a tied-covariance GMM seeded by the leaves gives the labels: every member's most likely subclass (hard labels only; they are the project'sptcl2Dclass and the members of each subclass). - Conditional averages. Subclass
sgets the model's expected image at its latent centre,P + U_ext z_s:Pthe CTF-corrected class mean,z_sthe mean latent of its members moved off the prior ((I - S)^-1 (zbar_s - zbar),Sthe members' mean posterior covariance),U_extthe basis solved on every coefficient with the latents fixed and shrunk above the fit band, shell by shell, by2F/(1+F)of the even/odd basis FRC. Every subclass borrows the class's full signal and spends onlyneigsnumbers where it varies. - Halves and filter. Two independent half models, on the even and on the odd members (own mean,
basis and latents; the same bands and subclass membership), give the even and odd conditional
averages, written unfiltered. Each subclass's even/odd FRC (
cls_expansion_frcs.txt/.bin, registered asfrc2D) filters its full average by2F/(1+F)per shell. A class too small for half models uses the joint deviations in both halves; a class kept whole delivers its mean and half means, filtered the same way. - Readouts per subclass (
os_cls2D, class map):pop(hard members),neff(=pop; there are no soft weights),sep(Ashman's D of the parent's first cut, 0 for a whole class) andrepro, the correlation of the subclass's deviations from the two half models (0 for a whole class): a structural difference reproduces, a noise-driven split does not.
The poses of the sub-class averages are refined downstream (refine3D_states_cavgs) and the
particles' by particle-level refine3D_states; the earlier optional in-plane refine2D round and its
restoration from the split's soft weights are gone with the soft weights.
2. Benchmarks¶
Synthetic, planted truth, SNR 0.05, 2-way:
| test | flex | diffusion maps |
|---|---|---|
| EMD-8440/8445 50/50 mix, 60 classes: pure subclasses / purity / NMI | 143 of 180 / 0.90 / 0.24 | 35 of 120 / 0.68 / 0.01 |
| five-state ladder 40/30/15/10/5: purity / NMI | 0.62 / 0.18 | 0.42 / 0.01 |
Real data, label-free: best-pair cross-half reproducibility of the subclass differences per resolution band, 3-way, median over parents:
| > 60 A | 60-30 A | 30-15 A | |
|---|---|---|---|
| 10180 flex | 0.93 | 0.88 | 0.62 |
| 10180 diffusion maps | 0.90 | 0.27 | 0.07 |
| 10076 flex | 0.86 | 0.81 | 0.79 |
| 10076 diffusion maps | 0.99 | 0.43 | 0.24 |
Seven real sets, 3-way, same settings, the 12 most populated parents. Effect size = cross-half power of the best sibling difference over the parent's cross-half power at 60-30 A; largest share = the biggest subclass's fraction of the parent:
| dataset | particles | 60-30 A | 30-15 A | effect size | largest share | wall (80 cores) |
|---|---|---|---|---|---|---|
| ribosome 10076 | 132k | 0.81 | 0.79 | 2.87 | 0.64 | 6 min |
| spliceosome 10180 | 46k | 0.87 | 0.63 | 1.06 | 0.45 | 4 min |
| "not" (unpublished) | 805k | 0.88 | 0.82 | 0.57 | 0.81 | 56 min |
| trpm4 (sieved) | 576k | 0.78 | 0.70 | 0.40 | 0.81 | 13 min |
| EMPIAR-13553 | 1.34M | 0.98 | 0.93 | 0.33 | 0.53 | 4 h 30 |
| 10028 ribosome ref | 105k | 0.68 | 0.56 | 0.33 | 0.47 | 41 min |
| flipqr (sieved) | 504k | 0.73 | 0.57 | 0.26 | 0.72 | 9 min |
Reproducibility says whether a difference is real; the effect size says how big it is and ranks
the sets the way the montages read. Per 1000 particles the split costs about twice a refine2D
pass and the restoration 1.5 times; 13553 (one 550 GB stack) is 10 times slower in both because
members are fetched class by class, a random walk through the file.
3. Why it works, and why the diffusion-map split did not¶
- The comparison is made in the CTF-corrected, noise-whitened Fourier band where the structural signal is, with defocus, contrast and residual pose in the model rather than in the distance.
- Cross-fitting keeps the posterior honest; the kernel then pools members the data cannot tell apart and keeps apart those it can.
- Junk is not a cluster in a low-rank latent; the fit residual separates it.
- The diffusion-map split used Euclidean distances between raw masked pixels: at cryo-EM SNR the nearest-neighbour graph is a noise graph. Its subclass differences reproduce only above 60 A (density, background, blob size) and collapse in the structural band.
4. Limit¶
The per-particle state signal within a 2D view class: the cross-fitted latent scatter is 1.1-1.8 times the posterior width on real classes, enough to order members and to give reproducible sub-average differences, not to label individual particles. Pooling across views is the 3D path.
Appendix: the plan as written on 2026-09-30¶
Kept as written (the program was then called cls_split); the sections above record what was built and measured.
flex_pca-style class splitting (cls_expansion pca_mode=flex): plan¶
Status: plan, 2026-09-30 (revised the same day: no even/odd machinery; fixed ncls subclasses and
fixed neigs rank per parent class; EM fits the basis, the subclasses are placed once afterwards).
Target branch: master. Nothing implemented yet.
0. What cls_expansion does today, and the answer to "does it weight?"¶
cls_expansion (src/main/strategies/parallelization/simple_cls_expansion_strategy.f90, commander in
simple_commanders_denoise.f90) runs per parent 2D class:
transform_ptcls(simple_classaverager_restore.f90:780): reads the class members, optionally phase-flips, shifts and rotates each particle into the class frame by KB gridding, returns real-space images and their plain average.- automask from the parent average, noise normalisation, soft mask.
make_pcavecs-> diffusion-map or kPCA embedding (make_split_embedding), ICM rank selection.- Euclidean distance matrix in the embedding -> k-medoids, k chosen by silhouette over
nsubcls_min..nsubcls_max(or fixedncls). Every class is split into at least 2. - Hard labels written to
ptcl2D/class(global subclass) andptcl2D/cluster(parent);os_cls2Drebuilt withcluster/pop. - A trailing distributed
make_cavgsregeneratescls_expansion_cavgs.mrcfrom the hard labels.
It does not build weighted class averages. cavger_update_sums calls accumulate_fplane
without the optional weight argument (simple_classaverager_restore.f90:342,345), so every member
enters its subclass at unit weight. The embedding also has no noise or CTF model: phase-flipped,
masked real-space pixels with a Euclidean/kNN affinity. Sub-class membership is hard and
silhouette-driven, and a homogeneous class cannot answer "do not split".
1. Goal¶
A per-class projection-aware low-rank covariance fit (the flex_pca model, in 2D with the in-plane pose fixed) that yields, per parent class:
- a latent embedding
z_iwith posterior precision, from a CTF- and sigma2-weighted likelihood; - a fixed rank
neigs(existing cls_expansion key); no rank gate; - exactly
nclssubclasses per parent (existing cls_expansion key): k-means centres on the final embedding, soft weightsw_isfrom a tied-covariance GMM with thosenclscomponents (gmm_state_weights,nstates=ncls); no auto placement, pruning or merging; - weighted sub-class averages:
A_s = sum_i w_is C_i^* y_i / (sum_i w_is |C_i|^2 + eps); the 2D analogue ofreconstruct_flex_weighted_states. No even/odd halves: the classes are small and the halves only served the rank gate and a per-averageres; - hard labels (argmax) kept for the existing project contract, and the weight table delivered
through the
flex_weightsstore so downstream tools can use the soft assignment.
No new user-facing keys: ncls and neigs are the two inputs, both already on cls_expansion. Poses are not refined
(the low-rank family is a poor aligner; flex2D branch, proposal section 15.1).
2. Model (per parent class, Cartesian half-plane, pose fixed)¶
For member i in the class frame (rotated by -e3, shifted by -shift, as transform_ptcls
does, but without phase flipping and kept in Fourier space):
y_i(h,k) = C_i(h,k) [ mu(h,k) + sum_q U_q(h,k) z_iq ] + n_i(h,k), n_i ~ N(0, sigma2_i(|k|))
C_i is the particle's CTF evaluated on the rotated lattice: same defocus, astigmatism angle
rotated by e3 (sign to be pinned by a one-particle test against explicit rotation). Weights
W_i(h,k) = |C_i|^2 / sigma2_i(k).
E-step (flex_pca's MAP embedding, _em_embed): A_i = I + U^H W_i U, b_i = U^H W_i (y_i/C_i - mu)
(formally: b_i = U^H C_i^* (y_i - C_i mu)/sigma2), m_i = A_i^-1 b_i, S_i = A_i^-1.
M-step (flex2D branch, proposal section 6, transplanted from polar to Cartesian): for every
coefficient (h,k) a (K+1)x(K+1) weighted least-squares system
G(h,k) = sum_i W_i [1 m_i^T; m_i S_i + m_i m_i^T], rhs(h,k) = sum_i W_i (y_i/C_i) [1; m_i]
[mu; U] = G^-1 rhs (Tikhonov ridge on the basis block, relative to G(0,0))
over all members, K = neigs fixed.
The fit is expectation maximization (PPCA EM, flex_pca's probe loop): mu starts from the plain
weighted average and U from random projections; prior-free (ALS) probe iterations first, then the
PPCA E-step/M-step alternation with rescaling (flex2D findings: random-projection init is 1000x too small; ALS is
scale-invariant so U is rescaled by the latent second moment). Iteration count: flex_pca's
n_probe_iters upper bound with the convergence stop.
Fit band: coarse. State differences are low-resolution features and the fit degrades as the band
marches (flex2D 15.11: labels held at 20-30 A beat 8 A). Default lp_fit derived, not typed:
the coarser of flex_pca's derived band rule and the parent's own res from os_cls2D; the
restoration uses the full band. Fit at box_crop matched to lp_fit, restore at box.
Sigma2: the project's canonical sigma2 state (what make_cavgs ml_reg=yes reads via
cavger_read_euclid_sigma2); if absent, run the same ensure_canonical_sigma_state path flex_pca
uses (move it out of simple_commanders_flex_pca.f90 into a shared helper) rather than a silent
white fallback (memory: the white-noise fallback invalidated real-data runs).
3. States, weights, averages¶
- Placement, once, after the basis EM has converged:
kmeans_latent_targets(simple_flex_pca_targets.f90) withnclscentres on the MAP embedding, thengmm_state_weights(simple_flex_pca_gmm.f90) withnstates=nclsand those centres for the responsibilities. The subclasses are not part of the EM (no mixture prior onz);nsubcls_min/nsubcls_maxare ignored on this path andncls>=2is required. - Weighted averages: per state, numerator
sum_i w_is C_i^* y_i, denominatorsum_i w_is |C_i|^2(+ Wiener eps from sigma2 when ml_reg), on the full-box lattice, in the class frame (no re-gridding: the members were already rotated once).resinherits the parent'sos_cls2Dvalue. Members below the responsibility floor (RESP_FLOOR, as flex_pca) contribute nothing. - Delivery:
cls_expansion_cavgs.mrcin global subclass order, registered withadd_cavgs2os_outlike today;os_cls2Drows withcluster,pop(hard),neff(soft),res(parent's),state=1;ptcl2D/class= argmax subclass,ptcl2D/cluster= parent (unchanged contract). Weights: oneflex_weights_state_NNN.binper global subclass viaflex_weights_deliverwithos_ptcl2D(the store is keyed on box/smpd/layout digest, so a 2D field works; check thatflex_weights_consumabledoes not assume avol_flexsibling; if it does, add awhich_imgkindargument rather than a second store).
4. Architecture and ownership (master)¶
The flow is the repo's: ui -> exec -> commander -> strategy -> domain. Nothing new is added
above the strategy; the new code is one domain module plus one extension of the class subsystem.
| layer | file | owns | must not |
|---|---|---|---|
| ui | src/main/ui/simple/simple_ui_cluster2D.f90 (new_cls_expansion) |
pca_mode gains flex; help text says ncls and neigs are required on that path |
anything else |
| exec | src/main/exec/simple_exec_denoise.f90 |
unchanged: cls_expansion -> commander_cls_expansion |
|
| commander | src/main/commanders/simple/simple_commanders_denoise.f90 (exec_cls_expansion) |
cmdline normalisation and defaults before params%new; the canonical sigma2 state on the master only (workers consume it); the four lifecycle calls; skipping the trailing make_cavgs when pca_mode=flex |
reading part files, numerics |
| strategy | src/main/strategies/parallelization/simple_cls_expansion_strategy.f90 |
roles (shmem/master/worker), class partitions, the part-file protocol, the merge, all project writes (ptcl2D, os_cls2D, out-segment registrations of the cavg stack and the weight files). split_one_parent_class becomes a dispatcher: the existing body moves to split_class_diffmap, the new split_class_flex prepares the inputs (planes, CTFs, sigma2 rows via the class and sigma2 subsystems) and calls the domain |
the model, the EM, the averaging |
| domain | src/main/flex/simple_flex_cls_expansion.f90 (new) |
flex_cls_model and its EM (fit), embed, place_states (k-means + fixed-K GMM through simple_flex_pca_targets / simple_flex_pca_gmm), restore_states (weighted averages). Inputs are arrays: complex planes, CTF planes, sigma2 rows, ncls, neigs. Outputs: z, weights(ncls,N), labels(N), cavgs(ncls) as Fourier images |
importing parameters, builder, sp_project, qsys_env, or any part I/O (the 3D driver simple_flex_pca_model does; the 2D module stays pure so the unit test needs no project) |
| class | src/main/class/simple_classaverager_restore.f90 (transform_ptcls) |
the one gridding kernel that puts a member into the class frame; gains an optional Fourier-plane output (unflipped) and the rotated CTF parameters per member. The real-space path is unchanged | knowing about flex |
| sigma2 | src/main/sigma2/simple_sigma2_bootstrap.f90 |
ensure_canonical_sigma_state lifted here from the flex_pca commander. Today three private copies exist (flex_pca commander, rec3D strategy, cluster2D strategy prepare_canonical_sigma_update); cls_expansion calls the lifted one, the other copies can converge later, out of scope |
|
| weights store | src/main/flex/simple_flex_weights_state.f90 + sp_project%add_flex_weights2os_out |
reused as is with os_ptcl2D; if flex_weights_consumable turns out to assume a vol_flex sibling, the fix is a which_imgkind argument in the flex module, not a project change |
a second store |
| test | production/tests/simple_test_flex_cls_expansion.f90 (new) |
exercises the domain module alone on synthetic planes (auto-globbed, no CMake edit) | project fixtures |
| docs | src/main/flex/README.md, this note |
Reuse from the 3D flex code, exactly this and no more: kmeans_latent_targets
(simple_flex_pca_targets.f90), gmm_state_weights (simple_flex_pca_gmm.f90), the small
Hermitian solver solve_real_spd_complex (simple_flex_reconstructor_latent_ops.f90), and the
flex_weights store. Not reused: the EM driver, E-step, M-step and their submodules (all bound to
volume projection and the polar bank), simple_flex_pca_rec3D, simple_flex_pca_rounds and the
flex_pca strategy (its stage/round scheme and producer-owned part I/O are what this design avoids).
The per-coefficient EM in 2D is ~300 lines of new code; the flex2D branch's
simple_flex2D_model.f90 is the reference for it and is not imported.
Reused unchanged elsewhere: discrete_read_imgbatch/prepimgbatch, the KB gridding loop,
ctf%eval, load_sigma2_groups, add_cavgs2os_out, the cls_expansion master/worker scheduling and
merge.
5. Parts: the standard SIMPLE distribution, not flex_pca's rounds¶
The existing cls_expansion strategy already follows the usual pattern and is kept as is:
- The master (
nparts>1, nopart=) partitions the parent classes intonpartslists balanced by population (prepare_class_partitions), writescls_expansion_classes_partNN.txt, and submitssimple_exec prg=cls_expansion ... part=NN class_assignment=<list>throughqsys_env. - Every worker runs the same shared-memory code (
run_local_split) on its classes, in the master's directory, and writes only part files: todaycls_expansion_class_map_partNN.txtandcls_expansion_assignments_partNN.txt; the flex path addscls_expansion_frcs_partNN.txt(per-subclass even/odd FRCs) andcls_expansion_cavgs_partNN.mrc(local sub order). A worker never touches the project. - The master waits on the job-finished flags, merges the part files once
(
merge_worker_outputs: global subclass numbering, then labels, FRCs and the concatenated cavg stack in that order), writes the project, registers the stack and its FRCs, and cleans up. One submission, one merge, no rounds, no stages, no master-side numerics. nparts=1runs the samerun_local_splitin process and skips the part files.
The strategy owns every part file, read and write, as it does today. Cost per class per EM
iteration is N * ncoeff * (K+1)^2 (N = 1000, box_crop 128, K = 8: ~7e8 flops), negligible
against the particle read, so a class is never split across workers.
6. Validation (batch2, never the Mac)¶
- Unit test (item 7), no data.
- One-particle convention test: rotated-CTF sign, plane conventions against
transform_ptcls' real-space output (inverse FFT of the returned plane must equal the returned image). - 10028 8000-particle reference run (
/mnt/beegfs/elmlund/afan/10028/flex2D_tests/ref.simple):ncls=2 neigs=4on every class; do the two sub-averages differ visibly, and how do their weights split (a 50/50 split on a homogeneous class is the null result to expect). - Synthetic 50/50 mix (EMD-8440 vs 8445,
t4_mix5050): abinitio2D's 60 classes are all ~50/50; score per-subclass purity aftercls_expansion pca_mode=flexagainst the existingpca_mode=diffusion_mapson the same run. This is the decision test. - EMPIAR-10076 with the published per-particle labels (
labels/real_recall.py): purity/NMI per subclass vs the diffusion-map path.
7. Risks¶
- View vs state. Within a parent class the residual out-of-plane spread can be the first
dominant component, and a fixed
nclssplit will then partition on view. The current cls_expansion has the same confound. Mitigation: report the component's dominant resolution band and leave the split, note the confound in the manifest. - Small classes. With
nclsandneigsfixed, a 40-member class is fitted and split whatever its content; classes below3 x (neigs + 1)members are skipped (as cls_expansion skips pop <= 2). - Rotated-CTF sign and the gridding conventions: covered by validation step 2 before anything else is run.
- Weight store consumers were written for
vol_flexsiblings; verify item 3's delivery does not breakflex_weights_consumablefor 3D runs.
8. Open decisions¶
cls_expansion pca_mode=flex(recommended: reuses scheduling, merge, and the project contract) versus a separateflex_cls_expansionprogram (cleaner ownership, duplicated master/worker plumbing).- Whether the weighted averages should also be re-centred per subclass (cluster2D centres its averages every iteration; cls_expansion does not).
- Whether to expose the soft weights to
map2ptcls/selection downstream, or leave the hard labels as the only consumed output for now. (Settled 2026-10-12: hard labels only; the soft weights are gone.)