Refine3D Policy¶
This document records the current policy for the base refine3D command. It
does not describe the staged solve3D controller, the class-average
solve3D_cavgs initializer, or the automated wrapper refine3D_auto. The one
exception is the per-state M-estimation of refine3D_auto state=X (section 8),
because its weighted reconstruction runs in the base matcher and assembly, with
the state sweep that runs it once per state (section 8).
Related workflow policies:
- solve3D_policy.md
- solve3D_cavgs_policy.md
- class-average rejection policy
- refine3D_auto_policy.md
- refine3D states policy
- classify3D_refs_policy.md
- automasking_policy.md
- nonuniform filtering policy
- reconstruct3D_pcg_policy.md
- particle cache policy
- separate_alignment_and_reconstruction_for_multistate_peak_mem_reduction.md
1. Scope¶
refine3D is an iterative projection-matching workflow over an existing
project and one or more starting 3D references. Its durable contract is:
- initialize project state and execution mode
- materialize the iteration reprojection model from current Cartesian volumes
- run particle-domain search and hard assignment: under
refine=prob*the matcher's batch pipeline (each batch's probability-table rows filled, each particle's pose drawn from its own row, refined continuously, its residual, its commit), under the classic modes the search strategies - write partition-local Cartesian reconstruction inputs
- run volume assembly when volume reconstruction is enabled
- persist project state for the next iteration or caller
The supported reconstruction path is Cartesian. Cartesian matching still uses
polar Fourier central sections internally, but those sections are generated
from the current Cartesian volumes. refine3D does not own a separate
non-Cartesian reconstruction branch.
Particle-domain work stays in the matcher: its preparation, the probabilistic
fills and draws, the search strategies, pose/state/shift updates, sigma updates
during Euclidean matching, and partial reconstruction writing. Volume-domain work stays in
volassemble and the volume postprocessing helpers it calls.
Shared-memory and distributed refine3D must preserve the same scientific
workflow and artifact contracts. Only toolbox lifetime, process launch, and
scheduling differ. Three rules belong to one strategy: only the distributed
strategy accepts convergence from the third iteration of the call on
(which_iter >= startit + 2) and schedules the final combine_eo iteration
(section 10); only the shared-memory run finalizer removes the os_out
entries of empty states (section 11.2).
2. Entry Points and Execution Mode¶
The public command is refine3D, registered in simple_ui_refine3D.f90 and
routed by simple_exec_refine3D.f90.
simple_commanders_refine3D.f90 performs the thin command-level setup:
- validate multi-volume input against
nstates - set local defaults such as
mkdir,cenlp,oritype, andprg - select a strategy through
create_refine3D_strategy - run the iteration loop
- delegate finalization and cleanup to the selected strategy
Strategy selection is command-line shaped:
npartswithoutpartselects the distributed master strategy- otherwise the shared-memory strategy is used
- distributed workers run the partition command path with
partandoutfile - the distributed master splits the rows into contiguous partitions that
balance the particles with state > 0 (
qsys_env%new(..., l_active),split_nobjs_active); with every row active this is the even split. The master merges the partition documents by their own ranges (merge_algndocs), so no consumer assumes a particular split - a worker whose partition samples nothing (fewer active particles than
partitions, or none of a class-balanced or probabilistic sample drawn over
the whole project) completes an empty transaction: its samplers accept an
empty sample only when
partis set (allow_empty), and it writes its unchanged sigma2 slice, its range's orientations, zero PCG accumulators andJOB_FINISHED
maxits is the number of iterations to run in the current invocation.
which_iter starts at startit, and extr_iter follows the same per-call
counter unless supplied by a caller.
Shared-memory refine3D currently rejects continue=yes. Distributed
continue=yes resumes from project-carried output volumes, FSC files, the
trailing chains and the sigma mode. It does not depend on the previous
partitioning: the partial reconstructions of the previous run are transient
(removed before every round) and are never read on continuation, so no
partial-file count is checked; a state without particles in a part writes no
partial, which is a zero contribution.
3. Ownership¶
simple_commanders_refine3D.f90 owns the base command entry point and the
shared iteration loop. It should stay thin. The module also hosts the commanders
of refine3D_auto, refine3D_states, refine3D_states_cavgs,
classify3D_refs and bootstrap_rec3D.
simple_refine3D_strategy.f90 owns:
- shared-memory versus distributed orchestration
- scheduler interaction
- iteration counters and convergence checks
- the iteration's sample draw (keyed on the run's seed, the pass, the iteration and the particle) under the probabilistic and the sampled modes
- matcher dispatch
- volume assembly dispatch
- per-iteration reprojection-model materialization
- run finalization
It must not absorb numerical volume postprocessing or assembled-reference construction.
simple_strategy3D_matcher.f90 owns refine3D_exec: consuming the
driver-generated reprojection model, selecting and running the search strategy,
updating orientations/states/shifts, updating Euclidean sigma estimates during
search, and writing partition-local Cartesian partial reconstructions. Under
refine=prob* it owns the batch pipeline (since 2026-11-04, the same body in
shared memory and in a distributed part): per batch the probability-table rows
filled, each particle's pose and state drawn from its own row, the extras of
the weighted insertion, then the continuous refinement, residual and commit; a distributed
part publishes a readout record (prob_readout_part<NN>.txt) that the master
merges in part order and prints.
simple_eul_prob_tab*.f90 own the fills and the selection rules on the
matcher's batches: the rows, the draws, the extras and cones, the temperatures,
the n_eff readout. No table, assignment or insertion file exists: the master
table, the table workers, the prob_align step and their files were retired on
2026-11-05.
simple_volassemble_strategy.f90 owns volume assembly (volassemble_exec):
reducing partials, restoring even/odd volumes, calculating FSCs, running
volume postprocessing, writing state volumes, and updating the particles'
resolution fields. It returns the names of the volumes each state ends with
and leaves params%vols alone.
simple_strategy_sigma2.f90 owns the canonical sigma2 commit
(commit_sigma2_exec).
These are strategy routines on a caller's (params, build) with explicit
arguments for what differs from the caller's own settings (the thread count,
which_iter, a write flag). The commanders volassemble and commit_sigma2
are thin wrappers: their execute(cline) builds parameters and a builder from
the command line and calls the routine. Both refine3D execution modes call
volassemble_exec and commit_sigma2_exec on their own project. Standalone
reconstruction and command-line callers retain the run_* wrappers. A routine that runs on the caller's parameters does
not run params%new: it sets the thread count it needs and the caller restores
its own afterwards, and it draws from the random generator without a reseed
(ruling of 2026-10-20); the probabilistic routes draw through the keyed,
stateless generator, which no reseed moves.
simple_vol_pproc_policy.f90 owns one check: whether a state's density-mask
file exists and matches the box and sampling of the volumes it would mask
(state_mask_is_compatible, shared by volume assembly, postprocessing and the
solve3D final reconstruction). The NU setup API owns its spherical mskdiam
support invariant.
4. Project and Builder State¶
The project is durable workflow state. The builder owns derived execution
state for one parsed command line and must not be treated as durable policy
state.
Shared-memory refine3D owns one parsed command, project and general toolbox
for its whole run. Each iteration refreshes the volumes, search toolbox, band
and prepared model; it retains symmetry, direction geometry and masks. The
matcher releases all-state alignment data before reconstruction. The Cartesian
follow-up consumes the same in-memory project and sample, with its own parameters
constructed once and its iteration/sampling settings refreshed explicitly.
Gridding assembly updates the owner's project without publishing it, and sigma2
consolidation uses that same project. The completed particle field is written
at iteration finalization; no project-file handoff is needed between phases.
The PCG master retains its additional particle-field write below. Startup
mutations needed by sigma2 bootstrap are still published before bootstrap.
Shared-memory strategies explicitly reset the intrinsic random stream at their alignment, follow-up, gridding-assembly and sigma-commit phase boundaries, preserving the reseed sequence of their command-based execution. Owner routines never reseed. The probabilistic generator and its key version are unchanged.
The shared-memory strategy retains the requested shift window and restores it before each alignment pass. Convergence may propose a wider window, but the former per-iteration parameter construction reset it to the command's request; keeping the parameters resident preserves that behavior explicitly.
Distributed refine3D keeps prototype command lines for the workers, the start
reconstruction, postprocessing and the thread count of the sigma commit; the
assembly command line is made each iteration from the master's own. These command lines are execution templates, not independent
workflow policies.
The distributed master is the one owner of its project. It materialises the
reprojection model on its own builder
(materialize_reprojection_model_master): the general toolbox once, at the
first iteration, which also reads the segments the model uses (the
non-data segments, out, optics and the particle field, then
update_projinfo, so that writes go to the run's own project and not to a
project the run was copied from), because the start reconstruction may
have written them; on later iterations the builder's volumes again
(new_vols), the search toolbox, the band and the model. The iteration's
sample draw (sample_ptcls4prob3D, keyed), volume assembly (gridding) and the
sigma commit run on the master's (params, build); the PCG master already did. The particle
field therefore holds this iteration's resolution fields (cfar,
lp_est) in memory, and the matching low-pass refresh reads the master's
own project.
The master writes the particle field once before the workers start (with
the iteration's sample, drawn by the master, or as the model left it), once
more after the merge only when a follow-up pass comes next (its workers read the
merged field), and once at the end of the iteration; the parts of a
probabilistic iteration reproduce the master's sample over their ranges
(sample4update_reprod) and publish their readout records, which the master
merges in part order after the schedule; merge_algndocs(..., write=.false.)
merges the workers' documents in memory, and gridding assembly does not write
the project on this path. The PCG master (rec_backend=pcg) writes the
particle field once, at the end of its call. The out segment is written once,
before postprocessing, which reads it from the file. The final full write
is unchanged. Workers read only the file; the master reads only what the
workers write.
Fresh-start checks that decide whether to consume project-carried matching
metadata must use the stage interval: which_iter <= startit with
continue != yes is fresh, even when startit is greater than one. A fresh
start still consumes the project's matching low-pass when the _nu_filt
references it was derived from are on disk (the refine3D_auto startup).
Before a matcher iteration writes partition-local Cartesian partials, stale partial reconstruction files for the active states and partitions must be removed.
5. Startup and State Initialization¶
If multiple starting volumes are supplied, nstates must be defined and
greater than one. Multi-state startup requires either all vol1..volN inputs
or none.
When orientations are absent, refine3D randomizes 3D orientations. When
projection indices are absent, distributed initialization sets them from the
Euler sampling.
For multi-state startup (the distributed master always, shared memory when the field holds at most one state bin):
- existing state assignments must match the requested
nstates - fresh state labels are randomized uniformly, whether complete starting volumes are supplied or the project references are used
- probabilistic multi-state startup requires each state to exceed the minimum population guard
Even/odd partitioning is required for consistent half-map reconstruction. The
partition belongs to the project, not to a field
(ensure_field_halves, src/main/project/simple_eo_partition.f90). The
master makes it once, before any worker runs, and workers stop rather than make
one. The same labels go to ptcl2D and ptcl3D, and existing labels never
change. A stack row that maps to a micrograph is a group: all its particles
share one half, so overlapping neighbouring picks never sit in opposite halves
and a reconstruction opens a stack once per state rather than once per half.
Groups go, largest first, to the half with fewer active particles. Their order
comes from the partition's own random stream, which leaves the particle sample
unchanged. A field with stack rows but no micrograph rows takes the per-index
route (partition_eo), as do class-average fields. The stack rows record which
route labelled them, so a missing, partial or inconsistent partition is told
apart, and an inconsistent one stops the run.
The offline select_particles eo_rebalance=yes export is an
exception to label preservation and micrograph grouping. It pairs selected
particles with adjacent scores within each symmetry-aware viewing bin into
opposite halves, balances odd leftovers, updates both particle fields and
replaces affected eo_group markers with eo_byindex. This is the selector's
default; eo_rebalance=no preserves the original labels.
The exported project no longer preserves the original gold-standard
independence: it mixes previously refined halves and may split correlated
neighbouring picks. Original half-maps/FSC must not validate the new split;
subsequent reconstruction uses the newly recorded labels without reassigning them.
5.1 Sigma2 bootstrap contract¶
Euclidean particle matching can opt into sigma2_anneal=yes (default yes in
solve3D, refine3D_auto, refine3D_local and refine3D_states; no in refine3D, where
the key is internal). The refinement owner saves or verifies the smoothed anchor,
interpolates sigma2_weight_start to sigma2_weight_end, and passes the current
sigma2_weight to workers. Negative weights blend the white ceiling into the
anchor; nonnegative weights blend the anchor into current residual spectra. The
last iteration of a ramp reaches its endpoint exactly, including a one-iteration
run.
- A solve3D stage gets its bounds from the controller, ramps over its budget and exits on convergence like any stage (see the solve3D policy).
- A standalone ramp (no
sigma2_weight_endon the command line) starts at -1 unless given and reaches 1 atminits(the budget's end withoutminits); convergence cannot end it before then. - refine3D_auto and refine3D_local smooth the committed spectra the run starts
from into the anchor (the fresh bootstrap of auto; the staged model noise of
local, or the bootstrap when none is staged) and run a standalone ramp from
0: model noise by
minits(3, ormaxitswhen given). The registration pass scores with measured noise. - refine3D_states makes the anchor the same way before its frequency march, scores at the anchor (weight 0), and ramps to 1 over the march's last three planned iterations, which reach into the block before a short last block. A block in the ramp gets its bounds and runs its whole budget. The missing-update pass scores with measured noise.
The anchor of a fresh run is the log-Savitzky–Golay smoothed bootstrap; only a
refinement controller's start smooths spectra of another provenance
(prepare_start_sigma_anchor). Each iteration logs the weight and the mean log
ratio of measured to anchor noise over the matching band. Polar and Cartesian
scoring (refine=cont, the pose_cont follow-up) see the blend; reconstruction
and residual estimation use measured spectra throughout, and residual-only and
assembly child commands discard scoring-annealing arguments.
Work that has alignments, or nothing at all, but no noise-power estimate is
one problem: a fresh solve3D start, the ini3D routes, external starting
volumes, the refine3D_auto startup, a refine3D started at a later iteration in
an empty directory, and every final reconstruction at a new sampling. Since
2026-09-06 all of them follow one rule, owned by simple_sigma2_bootstrap:
- Seed canonical state from the particle image power spectra (
calc_pspec), and let the first euclid pass replace the seed with residual sigmas. Image power needs neither alignment nor volume, and it is the basis every refinement already starts from. Half-map power (the formerbootstrap_rec3Destimator) sat on a different basis than the residual sigmas a refinement then computes and conditioned the euclid system markedly worse; it is retired. ensure_sigma2_for_iterationis a no-op when the project already owns a compatible committed state and seeds otherwise. The consuming refine3D reads that state directly; the external-reference pose initialization uses the same transaction path after its CC residual pass.- Refine3D is self-healing: a missing, invalid, wrong-grid, wrong-layout, or wrong-grouping state is rebuilt from particle power before workers launch.
- Where no refinement iteration follows (final reconstructions at original
sampling in solve3D and refine3D_auto), the seed is upgraded by one
residual pass:
refine=sigmaagainst the seeded map at the final sampling (no search, no volume assembly, no orientation output, alignment docs are not merged, no state labels seeded or written, so a multi-state project collapsed into one state keeps it (labels_may_change, as forrefine=eval; until 13 October 2026 the distributed start relabelled such a project at random and wrote it), and the particle field left exactly as it was: shared-memory initialisation does not resetupdatecnt/sampledfor it, the run finalizers do not write the field, and the distributed master refreshes it from disk before its whole-project write), committed as the next canonical generation, then the shipped euclid ML reconstruction runs on the residual sigmas. Since 2026-09-07bootstrap_rec3D(modulesimple_commanders_refine3D) owns this whole sequence: seed, bootstrap map, residual pass, commit, final map; the shared endingcalc_final_rec(modulesimple_final_rec, 2026-09-12), which closes solve3D, refine3D_auto, refine3D_states, refine3D_states_cavgs and classify3D_refs, calls it and carries no copy of the sequence. It runs standalone on any project with 3D orientations and is the test entry point for the final-reconstruction stage. The bootstrap map only serves as the residual reference, so it is always a gridding assembly with ML regularization (one particle pass, no postprocessing) that keeps the workflow'sfilt_modeandautomsk: the residual sigmas depend on the regularization of the reference they are scored against, so that reference is regularized exactly as the refinement's matching references were; the shipped map keeps the caller's backend andautomsk(so on PCG it is estimated on the same density-envelope support as the refinement, 2026-09-09;filt_mode=nonekeeps it classical) and, on PCG, starts from nothing at the native box and therefore gets the cold-solve budget of at leastFINAL_PCG_MAXITS_FLOOR(5) iterations whoever the caller is (2026-09-07). The base plus ML solve pair of that final PCG reconstruction is inherent to ML regularization: the prior is built from the base pair's independent-half FSC, which is also the reported FSC and the unfiltered pair postprocessing uses. - The residual pass is not an update (2026-09-27). Before this, the
shared-memory run finalizer wrote the particle field with the pass's
sampling bookkeeping: every active particle came back with
updatecnt+ 1, a newsampledround and cleared search statistics (poses untouched). So particles never updated by the refinement entered the shipped map, unlike the bootstrap map (sample4rectakesupdatecnt > 0rows), and counted as updated forupdate_missingand for the frozen membership ofsolve3D_addon; a standalonebootstrap_rec3Datwhich_iter=1(startit=1) even resetupdatecnt/sampledfor every particle first. Nothing reads the bump: the pass only closes final reconstructions, and a later refinement starts its own sampling round. - The unfiltered pair belongs to the assembly that wrote the map it
accompanies (2026-09-12): every gridding
volassemblewrites the_unfilhalves, the unregularized pair under ML regularization and copies of the halves otherwise, sopostprocess_nualways finds a current pair; and postprocessing ignores a pair whose box differs from the map. A final reconstruction at native sampling therefore never reads the cropped pair left behind by the last refinement block. - The registration-box rule is the same for both stores (2026-09-07): a final reconstruction whose registration (crop) box differs from the native box refreshes the sigmas at native sampling (image-power seed, bootstrap map, residual pass) before the shipped map. Before this the canonical store reused its committed state whenever it was structurally consumable, which is always true at the native box, and so skipped the refresh legacy performs; the two stores could not produce the same final map.
6. Reference Preparation¶
The strategy materializes the iteration reprojection model before matcher work starts. Reference preparation:
- reads the current Cartesian reference volumes
- applies reference masking/filtering/centering policy
- determines the active high-pass/low-pass shell range
- writes even/odd PFTC reference sections for the matcher
mirr_proj=yes is an advanced, opt-in reference-preparation setting (default
no). The optimized polar projector interpolates half the directions and
fills their mirror partners using the orientation frame correction. Reference
frames with general angles use angular Fourier rotation; zero/180-degree
corrections use exact reversal/conjugation. Reference
memoisation applies the same pairing separately within every state's
nspace bank, including the additional real-half banks used by
prob_post_diag=yes. Even/odd references remain independent. Mirroring requires
an even nspace; its projection differences are bounded by interpolation
error. Cartesian-only local refinement does not expose this setting.
With automsk=density or nu, the matching references carry the selected envelope
after filtering (automasking_policy.md, "Reconstruction and reference use").
NU assembly multiplies the _nu_filt references by it: the density envelope
under yes; under nu the NU-evidence envelope when valid, otherwise the
density envelope. Outside it the NU filter field takes the coarsest bank
candidate. The matcher multiplies references that are not NU products by the
density envelope under yes, and under nu while no _nu_filt references
exist by the lagged NU envelope with density fallback. automsk=density also
implies envfsc=yes (policy 2026-09-09), so FSC evaluation follows the density
envelope (post hoc with solvent correction on gridding; inside the estimator on
PCG, reported as >>> FSC MODE). Particles and matching-bandwidth selection
are unchanged.
automsk=nu requires filt_mode=nonuniform|nonuniform_lpset; automsk=density is
accepted with any filt_mode. automsk=tight is rejected together with NU
filtering because the NU-evidence envelope has no Otsu tightness mode.
The lifecycle is lag-by-one: volume assembly from iteration N writes the NU envelope used when iteration N+1 materializes its reprojection model. A missing mask at the initial bootstrap is therefore expected.
volassemble must not generate or promote matcher reprojections. The next
iteration's reprojection model is generated by the strategy from the current
Cartesian outputs.
The model file header is the authority for the matching shell range consumed by the matcher workers.
Reference preparation must project only the active matching shell range. It must not silently project to the crop interpolation limit unless matching policy explicitly asks for that range.
The 3D low-pass range comes from one of these sources:
- explicit LP-set
lp - project-carried NU-selected handoff in a continuing nonuniform refinement
- current FSC files
- an existing project
lpfield
lpstop caps the selected matching bandwidth. The crop Nyquist limit caps the
final Fourier index after the matching policy has selected a candidate range.
7. Matching Topology¶
Gold-standard matching keeps even and odd references independent.
If low-resolution even/odd docking is needed for registration, it is applied only after reference read/mask/filter and immediately before PFTC generation. Those blended references are not written as half-map outputs and do not feed FSC, automasking, NU filtering, or ordinary half-map handoff.
LP-set matching uses a merged registration reference. State count alone must
not force merged-reference matching; topology is controlled by LP-set policy.
filt_mode=uniform is disabled for multi-state search until it has a
state-specific low-pass contract.
In nonuniform mode, reference loading follows the NU policy:
- plain
nonuniformprefers independent_nu_filteven/odd references and falls back to regular even/odd references before using a merged map nonuniform_lpsetwith active LP-set matching uses the merged reference and prefers the merged_nu_filtproduct when present. In both modes the matching band is the finest member of the NU bank, the finest rung of the ladder cut atfsc/1.5or the regularized pair once it is at or beyond the ladder's finest rung (nonuniform_filtering_policy.mdsections 8 and 12, 2026-09-19)
The ordinary reference low-pass filter is not applied on top of a NU reference path. NU and ML-regularized references are treated as already filtered during volume assembly.
3D ICM regularization is retired: the icm key, icm3D program and volume
filter=icm path are removed. Nano refinement consumes images denoised by
the FLEX trajectory workflow or outside SIMPLE and uses the ordinary
reference-filtering path. The paired-stack icm2D command is also retired.
The single-image ICM filter used by micrograph preprocessing, and the ICM
algorithms for embedding rank selection and NU envelope labels, remain
separate operations.
8. Probabilistic and Matcher Work¶
The current workflow is a probabilistic alignment followed by hard particle
assignment, both inside the matcher's batch pipeline. It is not a monolithic
soft-assignment volume-integrated EM implementation. Every particle gets one pose and one state label, and
reconstruction follows the labels. The one exception is the per-state
M-estimation below: there reconstruction weighs each particle by a frozen
weight that flex_pca computed before the run. The refinement never computes
these weights from its own scores, and alignment never reads them.
Use the terms "probabilistic alignment" and "hard-assignment particle update" unless the ownership, artifacts, and update model actually change.
refine=prob* modes run the batch pipeline inside refine3D_exec
(prob_align_batch_pipeline.md, 2026-11-04): a batch's particles are
prepared once, their probability-table rows filled (fill_tab_range, the dense
table; prob_neigh the neighbourhood table's), each particle's pose and state
drawn from its own row (assign_batch), the extras of the weighted insertion
laid out, then the existing continuous refinement, residual and commit. The same body runs in
shared memory and in every distributed part; there is no pre-step, no master
table and no assignment artifact.
The matcher's search loop (3D and 2D) runs under a dynamic OpenMP schedule: a
particle is searched whole by one thread. Every draw of the probabilistic
routes is keyed on the run's seed, the pass, the iteration, the particle and
the draw (rnd_keyed, section 4 of the note), so the thread count, the batch
size and the partitioning change no draw; what a thread count still changes is
the floating-point order of the preparations and of the accumulators, which
the note's phase 3 measured and leaves as it is.
prob_neigh_mode controls how prob_neigh chooses candidate neighborhoods
before evaluating candidates:
state: score coarse subspace representatives independently per state, pool the selected neighborhoods across states, and evaluate the same pooled projection search space for every active state. The representatives are scored for a block of particles at once by the block kernel (below); the members of the pooled neighbourhoods per pair.geom: score every projection direction withinathres_cont(refine=cont's bound, default 10 degrees) of the particle's current orientation, under the point group, for every active state, with no coarse scoring or pooled peaks; a particle with a pose-student cone takes that cone and its mirror view instead. The subspaces only prefilter: a subspace whose representative lies farther than the cone plus the subspace's radius holds no direction in the cone (2026-11-09; before,geomsearched the one subspace containing the current projection, which a particle could never leave).shc: use the direct stochastic candidate path. When shifts are enabled, it first estimates a shift seed before candidate scoring.snhc: use the same direct stochastic candidate path without the initial shift seed. It is consequently also the zero-shift default for this mode.
The probabilistic tables score with the calibrated likelihood path: the
stored distances are noise-normalized negative log-likelihoods for the
Euclidean objective (objfun=euclid; the tables' constructors refuse the
CC objective, since the posterior they draw from is defined by the
Euclidean loss). The implementation uses a per-particle minimum shift
before exponentiation for numerical stability; this does not change
normalized weights.
Probability-table modes may still profile or MAP-refine shifts, and sometimes in-plane rotation, after stochastic candidate selection. The stored assignment distance is then the refined/profiled objective value. This is intended current behavior, not a full soft-assignment EM update.
Dense-table assignment (assign_rows)¶
Under prob the matcher assigns each batch's particles from their rows
(simple_eul_prob_tab.f90, assign_batch) by one draw per particle from its
tempered row posterior (since 2026-10-23; the only assignment since
2026-10-24, when the reference-balanced frontier was deleted from every
table). Particles are assigned to references; no reference is forced to be
populated. The particle's state and direction are one draw over its whole row,
every active state's block, with p proportional to exp(-T_i (L - L_min)), T_i
the particle's own temperature pi wsqsum_i / (2 pftsz) (the Euclidean loss's
noise scale), which the fill computes and keeps with the row; the state is the
drawn reference's (assign_rows, since 2026-11-05,
doc/implementation_notes/completed/multistate_posterior_state_draw.md). The
draw uses the keyed variate the selection already draws, so with one active
state, where the row is the block, the call, the variate and every output are
those of the rule before. That rule took the state of the closest reference
over all states (an exact tie to the lowest reference index) and drew the
direction within its block. The drawn reference's dense candidate is committed
(its in-plane, its refined shift when refined, the seed shift recorded, frac
100); the draw is keyed on the particle, so shared-memory and distributed runs
draw alike. A particle without a valid distance takes reference 1. The row's
values are the fill's (the top set refined), so the draw is a pose sampler on
that row. The in-plane rotation of every row
entry is drawn by the same rule: the posterior over all grid rotations of
the reference against the seeded particle at the particle's temperature
(gen_posterior_val, its bank form; score_ref, score_ref_bank), no
angular threshold. The top set the fill shift-refines is a search budget,
projs_ns = min(prob_athres, mean pose change) x nspace / 180
(calc_num2sample; the neighbourhood fills refine the npeaks_inpl lowest
per state): sizing it by the unrefined row's posterior mass instead broke
PorF (2026-10-25, the note, section 19, item 10), since that row is
conditional on the seed shift and the previous band and the shift
refinement is what re-ranks it; raising the cap (20, 40 degrees) did not
help either, since refining more candidates hands more particles to a
wrong reference whose shift search found a noise optimum (the bench
histogram refined argmin by decile of the cap, item 11). With more than one
active state the budget is split over the states' blocks (2026-11-05):
ceil(projs_ns / n_active) refined entries per block, at most n_active - 1
more in all. The window search refines each block's best. The polar shift map
keeps its screen's pool size (up to rounding), takes each block's share of it at
the origin, tracks the screen's width cutoff per block and refines each block's
share of its own screen. So every block gets the same number of screen and
refinement attempts, and no block is left with stored-shift losses only because
another state leads. With one state the split is the identity. The polar shift map records a
refinement only where it beats the stored shift's distance (a rule kept for the
single-state results), so a block can end without a recorded refinement for a
particle; the fill harness checks each block's share and the budget
(test=polar_matching_bench suite=fills). With
shift_prior=yes (the default since 2026-10-29; no turns it off) the tables' shift searches
and seed estimates carry a Gaussian on the shift's distance from the
search's start, width the previous iteration's shift variance per axis
(shift_prior_sigma2, from the sampled particles' shincarg, floored at
a pixel or a quarter of the matching wavelength, both in the original
sampling's pixels, lp / smpd, the unit of every search shift whatever the
crop; the multi-state table's quadratic grid step re-scores its fitted
shift with the same factor) and the particle's
untempered temperature converting it
to loss units; the search minimises and the row holds the MAP loss
(pftc_shsrch_grad%set_shift_prior), and the inpl_cont refinement of the
committed pose carries the same term on its joint loss, centred at the
committed shift (prep4prob arms it, prep_strategy3D measures the width).
The distance is that of the stored shift (2026-10-28): the optimizer's shift
at rotation irot is the stored shift rotated into the reference's frame,
x = R(irot) u, so the centre is kept as the stored shift u0 (the start
converted back at the rotation the caller expressed it at, irot on entry
to minimize, irot_in to minimize_joint: set_prior_centre) and the
penalty at any rotation is |x - R(irot) u0|^2 = |u - u0|^2, per rotation in
the all-rotation objective and the coarse grids, at the continuous angle
(with its gradient term) on the joint route, and on the stored shift
directly for the particle-frame lattice. Until then the centre was the
start x itself, which held only at the start's rotation: with a nonzero
seed a rotation change moved the stored shift without the penalty, and a
rotation that kept it paid (test_shift_prior_frame).
shift_sigma (the polar shift map, doc/implementation_notes/completed/polar_shift_search.md
and polar_shift_search_dynamic_centring.md) makes the tables' shift search
coarse-to-fine and centres each particle as it needs (ruling 19, 2026-11-02: the
centring is a per-particle state, not a stage, since the sampling strategies inject
particles no stage would otherwise centre). In every table fill with a shift search,
dense (process_particle_with_map) and neighbourhood (refine_best_neighbors) alike:
- a sampled particle takes the disk when its prior width
shsigis the sentinel (below zero: not yet centred in this workflow) or when three of its widths exceed the stage's windowtrs(shift_needs_disk), and the window otherwise; - the disk: the fill scores the references at the stored shift (the neighbourhood
table its candidates: in the state mode the subspace's coarse search comes first,
so an injected particle gets a direction as well as a shift; the geom mode keeps
its geometric neighbourhood), screens the references holding 99 % of the
particle's posterior at the origin (at least twice the refined count,
screen_pool_size) with the coarse map over the disk of 3 sigma (disk_radius_px, bounded by the box;SHIFTMAP_SCREEN) under the prior on the increment from the stored shift (it moves with the particle, ruling 22: in 3D the 2D shift is the origin, not the pick) at the particle's first centring and without it after (a re-centring is the data's alone; under the draw's tempering the untempered prior at the pick pulled centred particles back), keeps each one's coarse optimum, and refines the best at full resolution in a box of one map step about that optimum in the disk's own search object (pftc_shsrch_grad%minimize_in_cell: the L-BFGS from the cell in the box, the shift prior, when set, centred at the stored shift; the better of the refinement and the cell at its best rotation is the pose when it beats the origin's row, else that row stands; the 5 x 5 lattice that ran in the box until 2026-11-03 cost half to three quarters of the fill's refinement at the same accuracy). The rows are the refined losses, as the window path's; - the window: the same screen and refinement over the coarse window map
(
SHIFTMAP_WINDOW, radiustrs, no prior), the stage's search object, so the previous reference's seed, its shifted-particle bank and the 5 x 5 lattice at every rotation retire wherever the key runs (Phase 4);shift_sigma=0keeps them; - a disk particle is prepared under the box's mask (
ptcl_on_disk,prepimg4align), the others under the stage's; the preparation records the choice per particle (builder%note_obs_mask) and both reconstruction backends read it when they read the particle again instead of taking its record (prep_rec_observation_ptcl,obs_on_box), so the observation does not depend on the record buffer's budget (the review's M2, 2026-11-03); - the width: every coarse map's draw measures the standard deviation of the shift
under its posterior at the physical temperature (
shiftmap_draw); it travels with the refined entry (prob_refined_entry%sdev) through the assignment (ptcl_ref%sdev) tostrategy3D_prob, which writes the move (shincr) and the next prior width (shsig,record_shift_state): the assigned pose's width, at least the radius searched when the move reached its bound, within a tenth of it or half a map step where the map is finer (next_shift_width). The width chooses the next box and never enters the likelihood; the map's prior stays the only prior in the draw and in the weighted insertion's loss (insert_pose_loss, both 3D tables: the refined loss with the prior on the pose's increment at the physical temperature); - the sentinel is set by both refine3D masters at a run's first iteration
(
start_shift_state), except in a search about the stored poses (prob_neigh_mode=geom:refine3D_local refine=prob_neigh,refine3D_states pose_policy=local, the pose student's cones) or underkeep_centring=yes(refine3D_autoon a native project, 2026-11-16), which keeps the state the workflow before left (2026-11-11). Its never-centred particles keep the sentinel and take the disk, its widths choose by the rule, and a record that never held a width (zero, as in projects from before the map) takes the window about its stored shift. A solve3D stage continues the global iteration count, so only its first refine3D run resets, and the fill-in iterations' never-sampled particles are the ones that take the disk there. The master prints the disk set by cause and the widths' median and 90th percentile after its sample draw (print_disk_set; a part prints none). No stage ends on the centring.
Every table increment is native whatever the path (the refinement's
minimize(sh_rot=.true.) rotates the optimizer's shift into the particle's axes at
its rotation), and the consumer adds it to the stored shift unconverted
(strategy3D_prob, candidate_pose; test_table_increment_axes;
test_map_initialised_refinement pins the map-initialised optimum against the
lattice-initialised one). The parameter's default is 10 A (2026-11-02, across the
board): l_shift_map is the key's presence under objfun=euclid (an explicit key
under cc is refused), which a workflow's master passes to its stages, and
l_centring a run that centres, the key in a polar mode with a shift search
(prob, prob_neigh, and since ruling 20 the classic shc, neigh, greedy,
greedy_inpl), which the searches, the preparation and the consumers read;
refine=cont carries the key silently.
The classic modes (ruling 20, 2026-11-03) take the table's structure, not a seed:
under the key no shift search at the previous reference (inpl_srch_first) in any
state count (a previous-reference seed is optimal for one state only; the states
are not docked and nothing records each state's optimal projection), the
references scored at the stored shift as the mode has it, then the screen and
refinement of the tables (simple_shiftmap_srch) over every scored reference across
states and the previous one, which competes at its stored-shift score: one
refined for the committed pose, the peaks for neigh, the best cells refined
with minimize_in_cell. Under shc a particle that needs the disk is searched
greedily. extract_peak_ori records the shift state (record_shift).
The continuous in-plane route's joint domain contains the particle's box (the
disk under the key, shift_box_radius) and the incoming shift, so the solve
starts at, and is judged against, the pose it refines (the review's T1,
2026-11-03; test_continuous_seed_beyond_window). Before, a disk shift beyond
the window was projected into it and kept with the projected pose's score.
The disk remains circular through both refinement stages: minimize_in_cell
rejects an escaping result and re-scores the valid coarse cell at its best grid
rotation; minimize_joint rejects an escaping result so the consumer retains
the coupled incoming pose and score. Dense and neighbourhood tables, classic
searches, extra poses and joint view refinement use the same rule. The radius
is disk_radius_px before any rectangular-limit expansion, with only
floating-point rotation roundoff allowed. It bounds the native-pixel increment
from the stored shift, not the accumulated shift. Local-window searches keep
their rectangular refinement bounds.
Every posterior draw of the tables, the fills' in-plane draws
(pftc%ptcl_posterior_temp) and the assignments' direction, class and
neighbourhood draws alike, runs at one tempering factor times the particle
temperature: PROB_BETA (0.3, simple_defs; for small membrane proteins,
section 19 of the note; below one hotter), so below one the draws are from
the tempered posterior, p^beta, and from the posterior proper only at 1: the
search's annealing knob, section 4.4, run-time since 2026-10-23 after the run
at the physical temperature froze. The workflows carry the iteration's value
as prob_beta (its default is the constant) and the annealing tail moves it,
so the tail cools the in-plane draws with the direction draws (2026-10-29;
between 2026-10-28 and then the in-plane factor was pinned at a separate
constant while the n_eff control, since retired, moved the direction factor).
A refine3D run anneals when prob_beta_end is given: it searches flat at prob_beta
until neither FSC 0.5 nor FSC 0.143 gained on the previous iteration
(check_conv3D, the same gain test as the resolution exit, on the previous
iteration's STATS_FILE record), then ramps geometrically from prob_beta to
prob_beta_end over the next PROB_BETA_TAIL (5) iterations
(prob_beta_at; exec_refine3D puts the iteration's factor on the master's
parameters and the workers' command line, and the settings box of the
convergence report shows it, POSTERIOR DRAW BETA, with the tail's progress)
and ends when the tail is complete. In a single-state run, a cumulative
orientation-overlap gain of 0.02 above the last accepted high also postpones
the trigger for the same one-check window (two with weighted insertion).
The progress record is stage-local; small gains accumulate, while a fall and
rebound below that high is not progress. This guards flat FSC shells during
pose consolidation without an absolute overlap threshold. A budget too short for a stall
anneals over its last five iterations regardless. With more than one state the
stall is every populated state's (2026-11-05, states_stalled): the
convergence object keeps each state's last two resolutions, and the tail starts
when no populated state gained. A state counts as not gaining when both its
crossings are in this check and in the previous iteration's record and neither
improved; a state lacking a value is skipped; when every state is skipped, the
best state's test decides. The weighted insertion's two-iteration margin
applies per state, and the resolution exit stays on the best state.
prob_beta_end=0 (the default) is a flat run. solve3D sets prob_beta_end=1 on its last stage
unless the user set it, so the stages search hot and the final map is
weighted at the physical posterior; the other stages run flat at
prob_beta. Neither prob_beta nor prob_beta_end is a UI input
(2026-10-29): the workflows set them (the solve controllers on their stage
commands, the refine commanders per iteration for the workers); the keys stay
command-line keys for that internal passing only. The tail replaced a
ramp spread over the stage's whole budget
on 2026-10-24: on streptavidin the last stage ran its 25 iterations with the
resolution reached at the second (section 19 of the note). A refine=prob
or prob_neigh stage ends once the orientation overlap passes its overlap
(multi-state: the lowest state's mean mi_proj * mi_state over the current
observations), whatever the visited fraction, or on the resolution exit
(lpexit), its annealing tail or its
iteration budget; under an annealing tail the overlap starts the tail. A
populated state without current observations holds the overlap exit; empty
states are ignored. Overlap and resolution stalls respect minits before
starting a tail; its budget fallback can start earlier to finish on time. The
hill-climbing neighbourhood modes (prob_neigh_mode=shc|snhc, solve3D's first
two stages) never end on the overlap. The limit is OVERLAP_3D (0.99) unless
the workflow sets overlap: solve3D emits OVERLAP_3D_STAGE (0.95) from
stage 3 to the next-to-last stage, except its full-budget symmetry-search and
post-class-average particle-entry stages (minits=maxits, overlap 0.99).
Before 2026-11-11, check_conv3D bypassed the overlap for these modes and a stage ran to
an exit or its budget.
The n_eff readout (2026-10-29; section 20.2 of the note). Every
iteration logs, on the POSE ASSIGNMENT line (CLASS ASSIGNMENT in 2D), the
mean effective number of candidates a particle draws among, exp(entropy) of
its tempered row posterior, at the draw's factor (prob_beta, or the tail's);
the readout record also sums it at beta 1 (the physical posterior). The rows
are a subsample of those the draws are from: up to
PROB_NEFF_ROWS (1000) rows at a fixed stride through the iteration's global
sample (the rows are chosen by rank in that sample, so they are the same rows
whatever the partitioning; a part publishes its sums and counts in its readout
record and the master sums the parts in part order, never means of means),
each with at least PROB_NEFF_NMIN (6) valid candidates (a row of two lands
on one of its best two at any factor and would pull the level of the rows
where the choice is open), nothing below PROB_NEFF_MIN_ROWS (50) rows
(prob_neff_readout in simple_eul_prob_tab_utils, dense 3D,
neighbourhood, dense and sparse 2D). It is a readout, not a control: from
2026-10-27 to 2026-10-29 the same object solved the factor every iteration
so that the mean n_eff met a target (prob_neff, N* = 3), and on the
controlled comparison of 2026-10-28 (in-plane draws fixed, the prior's
frame fixed, shift_prior=yes) that failed PorF 7 of 10 and exp_gate 2 of
10 against 10 of 10 and the best exp_gate maps to date at prob_beta=0.3
flat with the tail. The width of the physical posterior at a stage entry is
the model's own estimate of how far the poses should be re-searched
against the current map (the first dense stage enters at a row-mode
fraction of 0.14-0.23 and cools to 0.7 by its end; the NU entry at 0.46),
and pinning n_eff cancelled exactly that; the flat factor keeps it. The
schedule is therefore prob_beta flat with the tail to 1, and the readout
is how it is watched. Unit-tested on synthetic rows against a numpy
emulation (test_neff_readout).
The state readout (STATE N_EFF, STATE MODE, STATE MASS ON UNREFINED,
2026-11-05). With more than one active state both 3D tables log, after
POSE ASSIGNMENT:
- over the rows the n_eff readout subsamples: the effective number of states,
exp(entropy) of the row's state marginal, at the draw's factor and at 1, the
mean largest state posterior, and per state the share of the block's tempered
mass on entries the fill did not refine;
- over every row: the share of draws in the row mode's state.
The values are carried in the parts' readout records as sums and counts and
summed by the master in part order (prob_state_readout in
simple_eul_prob_tab_utils). The refine3D strategy stores them on the
convergence object, which writes STATE_NEFF_DRAW, STATE_NEFF_PHYS,
STATE_MODE_FRAC and STATE_MASS_UNREFINEDnn to the statistics file once per
readout. It is a readout, not a control. A state n_eff near the number of
states with the labels at chance says the state draw is too hot, unless the
n_eff at 1 is broad too, when maps that cannot yet tell the states apart give
the same picture. Near 1 from the first iterations is the lock-on signature of
the retired closest-state rule. A large unrefined share says the marginal rests
on stored-shift losses.
Terminal diagnostics read >>> LABEL (qualifiers): values: the greppable
label first, the state or topk in parentheses, then unpadded numbers with
leading zeros, comma-separated with units. The insertion cone line gives the
rim-displacement limit (the finer of FSC=0.5 and the matching LP) as degrees of
rotation or pixels of shift; these are alternatives, not independent allowances.
The conical score is the cFAR of the FSC (STATE N) line. Stored
FSC-mode provenance and diagnostic files are unchanged.
The weighted insertion (topk, 2026-10-29, revised 2026-10-30; sections
20.8 and 20.12 of the note). In the probabilistic modes a particle may
enter the iteration's reconstruction at more than its committed pose: with
topk above 1 (default 3 since 2026-11-01, Hans's 3D sweep; 1 is the
single-draw run bit for bit) the assignment adds, beside the committed pose,
up to topk - 1 extra entries of the particle's row: the refined entries
(the ones whose shift is their own; an unrefined entry's shift is the
seed's, section 19.10 of the note) whose pose lies within the insertion cone
of the committed one (prob_insert_cone), the topk - 1 of them of highest
posterior at the particle's own temperature, each with its share of that
posterior renormalised over the committed entry and the extras, an extra
under PROB_INSERT_WMIN (0.01) of the particle dropped
(top_posterior_extras); the distance weighed is the refined pose's own loss,
carried beside the row (prob_refined_entry%loss), which under the polar
shift map is the drawn cell's posterior loss (the data term with the absolute
prior at the physical temperature), not the reference's evidence the row holds
(review R3, S2). The selection is deterministic (the top entries,
not a sample: within the cone the extras exist to reduce the variance of
the one-pose insertion, and the hypothesis is the committed draw's), so
topk touches no random stream, and it is made only when the committed
entry is itself refined, so that every distance weighed is a refined one
(an unrefined committed entry's distance is at the seed shift and would be
weighed low against its shift-refined neighbours for a reason the data do
not give; such a particle enters at its committed pose alone, as under the
single draw). The cone: a pose is within it when the angle of the rotation
between the two poses, the smallest over the point group's equivalents of
the candidate (the geodesic angle of R_c^T R_r R_g), times the mask's
radius, plus the distance between the two stored-frame shifts, is at most
the finer of the state map's FSC=0.5 resolution and the matching low-pass
limit: a rotation by alpha moves a point of the rim by at most r alpha,
a shift moves every point by its length, so the particle averaged over such
poses is displaced by no more than the map resolves (a heuristic scale, not
a no-blur guarantee: at the cone's edge the displacement is a full period
of the resolution's frequency, and the blur within the cone is whatever the
weights at the particle's own temperature put there, which is the data's
pose uncertainty when the temperature is calibrated). The low-pass bound
holds the cone at a stage's entry, where the FSC on disk is the previous
band's and coarse (PorF enters stage 3 at 22 A for a 12 A search; a cone
that wide admitted most of the refined set and the first iterations of the
stage inserted the top of the row's posterior rather than the hot draw,
three of seven restarts ending the stage a shell behind, 2026-10-30): the
search cannot leave poses undecided at a scale coarser than its own
matching limit. Each part reads each state's FSC on disk before its batches
(insert_cone_from_fsc; no FSC, no cone, the committed pose alone), the
distributed master reports the cone from the same files after its sample draw
(INSERTION CONE; the owner reports it in shared memory), and the table
sets the cone's geometry at the assignment from the direction space, the point
group and its rotation grid as rotation matrices (set_space). The extras are
selected per batch after the batch's draws (select_extras in both tables),
each thread on its own eligibility mask, and enter the part's insertion table
in particle order. The two builds
before the cone (2026-10-29) failed in opposite directions: extras over the
whole row at the search's factor 0.3 blurred the map and capped the
resolution (PfCRT 5/10); over the whole row at the particle's own
temperature they made the map the posterior expectation under the current
model from a stage's first iteration, colder than the search and without
the draws' randomness, so stage 3 could not re-derive the poses (every
stage-3 map bad, PorF and PfCRT unsatisfactory) while the late stages
gained (exp_gate, streptavidin finals). The committed pose is the single
draw as before and keeps the search, its seeds, the shift prior and the
convergence statistics unchanged; topk=1 is bit for bit the single-draw
run. The part keeps the extras in its insertion table (prob_insert_table:
per particle the committed weight and the extras as reference, in-plane
index, refined shift and weight), publishes their counts in its readout
record, and the master logs POSES INSERTED from the merged counts with the
insertions per particle, the mean committed weight and the fraction of
particles with more eligible entries than topk - 1: near zero the insertion is
the full average within the cone, above it topk is binding (the record also
holds the eligible entries per particle, the cone's occupancy). The batch's extras are laid out
from the part's table for the search (prob_insert_poses%setup_range, one
slot per extra, handed through strategy3D_spec), and the probabilistic
strategy resolves a
particle's extras in its srch just before it commits the draw
(strategy3D_prob%resolve_extra_poses), through the same conversion rule
as the committed pose (candidate_pose: the reference's Euler pair, the
in-plane index's angle, the stored shift as the particle's plus the
increment), so the extras and the committed pose can never disagree on the
axes. Where the committed pose takes the continuous in-plane route
(inpl_cont, the window path) each extra takes it too, before it, from its
own cell and shift through the same local joint solve and guards
(refine_extra_pose_continuously; an invalid or non-improving solve retains
the table's pose), so every inserted pose is at its local optimum in angle
and shift and the direction is the only variable the insertion averages
over; the weights stay the table's (the solve is local and bounded, so the
losses move little and alike; Hans, 2026-11-01), and the particle's route
status is the committed pose's. calc_3Drec then inserts the committed plane with its weight and
each extra pose from the committed plane re-shifted by the pose difference
(fplane_shift: a phase ramp over the stored lattice, no second read or
transform; the CTF^2 plane is shift-free), so the cost of an extra pose is
one gridding insertion. The PCG worker takes the same poses (2026-11-03):
each extra pose is one more weighted entry of the operator from the same
observation, laid out after the committed ones (pcg_extra_entries,
accumulate_pcg_extras; test_pcg_extra_entries pins the layout). The
weights of a particle sum to 1, so the trailing reconstruction's population
accounting is unchanged. The final and bootstrap reconstructions use the
committed poses, so the last iteration's map and a reconstruct3D from the
project differ under topk > 1. The shc and snhc neighbourhood modes of solve3D's stages 1-2
insert the committed pose alone, their candidates being the hill climb's
unrefined proposals; the 2D route has its own in-plane insertion (INPL_POSTERIOR_BUDGET = 64,
solve2D policy, "In-plane posterior insertion"), which the 3D route does not
have (below, "In-plane posterior insertion: removed from 3D"). No file carries the
assignment or the extras: the rows, the draws and the insertion table live in
the part's memory for the batch. State assignment stays hard: the
extras are drawn from the committed state's block alone (the dense table's
block, the neighbourhood table's state row) and enter that state's
half-map, and a particle never enters another state's map through the
insertion; soft state membership is m_estimator=flex's, whose state
weight multiplies the pose weights as it multiplies the committed pose's.
The resolution exits read differently under the insertion: the half-maps
agree a shell earlier, since the draw's noise is averaged out of each half
while, in solve3D's stages (lp set), both halves are matched against the
same reference, so with topk > 1 the stage resolution exit wants the
FSC=0.5 resolution a shell past the next stage's limit and no gain over two
iterations rather than one, and the annealing tail's stall test likewise
two iterations without gain (check_conv3D, the object's history of its
last two checks; topk=1 keeps the single draw's rules). Unit tests: the
selection (test_top_posterior_extras: topk=1 keeps the committed entry
alone and no random number is drawn at any topk, the extras are the
eligible entries of highest weight in descending order, never the committed
entry, the weights are the shares over the kept set, the mass rule, the
occupancy count), the cone (test_insert_cone: the half-angle, the joint
rotation-and-shift bound, a near and a far direction on a C1 spiral, the
half-turn and the one-step in-plane, the polar pair that the direction and
psi angles alone misjudge, the C4 seam), the table's round trip with its
occupancy counters, the two-state assignment, the plane re-shift against a
plane generated at the new shift (test_fplane_shift, with the insertion),
and the exits' margin (test_posterior_exits_weighted_insertion). The
readout: the four sets at topk=10, stage-3 maps and finals against the
control, with the cone's occupancy line read beside them.
In-plane posterior insertion: removed from 3D (decision, 2026-11-17). From 2026-11-14 to 2026-11-17
refine3D inserted every pose of a table pass (refine=prob, prob_neigh in state|geom, objfun=euclid,
volrec=yes) at a K = INPL_POSTERIOR_BUDGET point quadrature of its in-plane posterior instead of at its one
angle: first over the full circle with the views reweighted by their in-plane marginals, from 2026-11-16 confined
to the insertion cone with the table's view weights standing
(the plan and its record). On 2026-11-17
the maintainer removed it from 3D: "Remove the in-plane posterior weighting that we put in as default. It causes
more failures than pose weighting alone. In-plane posterior weighting doesn't work in 3D but works well in 2D."
refine3D and solve3D (gridding and PCG) insert each pose at its own angle with the table's pose weights: the
committed pose with its weight and, under topk > 1, the extras with theirs (above); the insertion cone opens
only under topk > 1, the resolution exits take the margin only under topk > 1 (l_margin), and the log
reports POSES INSERTED. 2D keeps its in-plane insertion (strategy2D_prob%insert_inplane;
solve2D policy, "In-plane posterior insertion"), and the class student's teacher still
forms the in-plane marginal (simple_eul_prob_marginal).
Neighbourhood-table assignment (assign_rows_neigh)¶
The neighbourhood tables (refine=prob_neigh, solve3D's stages 1-2 and
6-8; section 4.5 of the note, built 2026-10-23) follow the same rule on
their candidate store, whatever the neighbourhood (prob_neigh_mode). A
particle without a valid candidate is first re-seeded at its previous
orientation (its state's reference at its closest direction, scored at the
seed shift; seed_fallback_if_empty). Then the particle's state and
candidate are one draw from exp(-beta T_i (L - L_min)) over its valid
candidates of every state together (an active reference with an in-plane
index; the pooled row of assign_rows_neigh, since 2026-11-05), the drawn
candidate committed with its shift, frac the evaluated fraction. A particle
whose valid candidates all carry a non-finite distance, or whose state emptied
mid-run, keeps its orientation. The weighted insertion's extras gather the
committed state's candidates alone, and the committed candidate is found among
them by its position in the candidate store, so the cone and the
renormalisation are the committed state's and the committed entry is never an
extra. In prob_neigh_mode=state the pooled neighbourhood is the same for every
state and in geom one cone serves every state, so the candidate sets are
comparable. In shc|snhc the candidates are hill-climb proposals with unequal
counts per state, so the draw acts as an acceptance step over the proposals and
the incumbent, and it chooses the state as well. Until 2026-11-05 the state was that of the
closest valid candidate over all states and the draw ran within it, and the
extras' gathering chose that state again on its own. The in-plane rotation of every candidate is the
posterior draw over all grid rotations (score_seeded_ref,
gen_posterior_val and its bank form), as in the dense and 2D tables; the
re-seeding draws its in-plane the same way. T_i stays with the candidate row
(both fills write it).
The pose-overlap rule covers prob_neigh as it covers prob. Particles
are assigned to references and no reference is forced to be populated: the
reference-balanced frontier (every active reference drawing its closest free
particle, the greedy state labels, the leftover rule) was deleted on
2026-10-24 with the dense and 2D frontiers, and the particle never takes an
argmin.
On the direct stochastic neighbourhoods (shc|snhc, solve3D's stages
1-2, from random orientations) ten streptavidin restarts at prob_beta=0.3
had stages 1-2 do nothing (poses moving 85-90 degrees per iteration) and
stage 3 solve the structure from scratch (the note, section 19). The shc
fill scores references in random order and stops at the first that beats
the previous pose, so its store held references worse than the current pose
plus the one that beat it, and a draw over it was a forced move. The fill
now scores the previous reference too when the stop rule left it out
(evaluate_direct_stochastic_refs), so the draw is an acceptance step over
the proposals and the incumbent. Whether that alone revives the early
stages, or their small temperature (T about 33 at stage 1, where it is
hundreds from stage 3 on) also needs a colder draw than prob_beta gives,
is the open measurement. The stages run at prob_beta like the others
(prob_beta_ini, a solve3D-only override of stages 1-2, was removed on
2026-10-29 with the other tempering inputs).
The posterior sampling is the probability tables' (refine=prob|prob_neigh,
and the 2D tables, solve2D_policy.md): the search strategies of the other
modes (shc, neigh, greedy, and the 2D SHC strategies) keep their own
samplers; a day's migration of those onto the posterior primitive
(2026-10-23) was taken back on 2026-10-24, the posterior being the rule for
the table modes of the later stages. Design, measurements and the acceptance
test (PfCRT, 10 of 10 restarts at 3.6 A or better):
doc/implementation_notes/completed/pose_marginalization.md sections 4, 10,
16-19.
Probability-table rows¶
A part's rows live in its memory for one batch and are released after the
batch's selection: the dense table keeps the batch's rows and refined entries
(batch_rows, batch_refined, moved in by the fill, keep_batch_rows), the
neighbourhood table and the 2D tables keep the fill's candidates in the thread
buffers and turn them into the batch's candidate store or dense rows at the
assignment (batch_store_from_buffers, batch_rows_from_buffers). No part
file and no master table exist: the dense (format word -4), neighbourhood and
2D (-6, -7) part files, the parallel part reads, the assignment and
insertion-pose files and their deleter were retired on 2026-11-05 with the
prob_align step and the table workers (prob_align_batch_pipeline.md).
Before allocating a probabilistic matcher's particle slots, simple_matcher_memory
estimates dominant fixed and per-particle storage from geometry, the interpolation
and scoring bands, references, team size and candidate staging. Its byte counts
are 64-bit. The preferred thread-based batch capacity is reduced when necessary,
but never below one particle per thread (within the part's sample and the
preferred batch): the batch's parallel loops give each thread a particle, and
the fixed storage dominates, so a one-particle batch saves a few slots and runs
the fill and search on one thread (PorF refine3D_local, 2026-11-17: fixed storage
1.4-1.5x the budget, fill load balance 0.10-0.12 at eight threads).
The retained 3D observation buffer receives only the remaining alignment budget.
These are planning estimates, not a bound on library plans or total process RSS.
Fixed storage that already exceeds the budget retains the existing warning and
the one-particle-per-thread batch, with no retained observation buffer.
The shift search of the tables keeps a double-precision copy of the
reference for one minimisation (load_ref_aln_8, which records the
reference index and half per thread; the _aln evaluators take the index and
stop on a mismatch), and reuses the
all-rotation objective it computed at a shift when the same shift (bit for
bit) comes back, as L-BFGS-B's last accepted point does. Its Euclidean kernels
stay double: with float32 terms (2026-11-29, float32_kernels_and_pcg_precond.md)
L-BFGS-B's strict line search and its factr stop, which assume a double cost
and gradient, took 9 % more evaluations per search, and a rotation change by the
discrete-angle callback inside a run ended a search early. The likelihood
scores, and the power and bounded samplers of the 2D and greedy searches,
work in per-thread buffers over arrays of distances (no internal procedures,
so no heap trampolines).
The continuous in-plane route's 'lm' solve of the committed pose (euclid)
stops at the draw's resolution instead of factr's default (2026-11-21): both
relative stops at SHSRCH_JOINT_LOGP_TOL (0.01) over the particle's
prob_beta x T, at most a tenth of the material gain JOINT_IMPROVE_REL_TOL
(a fixture's unphysical T cannot stop it before a material step).
Gauss-Newton converges linearly here, and the default stop (a relative gain of
2e-9) took 5-6 more accepted steps that gained below the draw's resolution: in
a bgal solve3D a solve took 9-10 evaluations (3.0-3.5 with the stop), and the
steps after the first accepted one moved the pose by 0.02-0.03 px and
0.03-0.06 deg (medians). cc and the view mode keep the default stops. The
tables' L-BFGS-B shift searches keep theirs. Their first iteration (a gradient
step, capped at unit length on the bounded problem) gains almost nothing, but
scaling the cost so that it is a Newton step saved at most 0.8-1.5 evaluations
and 0.24-0.34 all-rotation scans per search on bgal, with the exact Hessian
free of charge: a few per cent of the search once a curvature is paid for,
within the run-to-run spread of its time.
Scoring in blocks (the block kernel)¶
The dense table's fill (fill_tab_range, every reference) and the
neighbourhood table's state mode (fill_tab_subspace_range, every active
state's subspace representatives) score in blocks of particles of one even/odd
half with the polar calculator's block kernel (score_block_posterior,
simple_polarft_block.f90; prob_table_matrix_scoring.md, 2026-11-21). A
batch's particles are ordered by half (the state mode then by the subspace
cell of the particle's previous direction, so that a block's particles share
pooled cells) and each half is cut into blocks of
min(16, max(4, n_half / (2 x team))) particles. One parallel region per batch
runs dynamically over the blocks, and a block is processed whole by one
thread: each particle's shift seed and seed bank (in the block's slot of the
thread's banks), then the block's scores at once, then each particle's
remaining steps in its path's order (dense: the shift refinement of the row's
best references, or under the polar shift map its screen and refinement, then
the temperature and the posterior diagnostic where the path has them; state:
the representatives' entries and peaks, the pool, the members per pair, the
shift refinement). A particle's shift prior
is set on the thread's search object again before its refinement, since the
block's later seeds set theirs.
The kernel computes, for every angular frequency bin 1..pftsz+1 (the Nyquist
bin included), the two Euclidean sums of every pair as one single-precision
complex matrix product (cgemm) of the block's weighted particle terms
against a tile of 32 references, transposes the products so that each pair's
bins are contiguous, runs one batched inverse FFT of 32 transforms per
particle, and converts and draws each pair with the per-pair kernels' own
procedures (euclid_dists_from_crvec, draw_posterior_rvec) and the pair's
keyed variate. It gives the entries gen_posterior_val (zero shift) or
gen_posterior_val_bank (the seed bank) give, but for the last bits of the
sums (their order, the weighting of the terms, the batched transform): the
kernel's tester in the fast gate (unit_pftc_align2D3D) holds the drawn losses
within 1e-6 relative of the per-pair routine's and the drawn rotation equal
but in max(1, 2e-5 of the pairs). The product always has the
same shape, 16 particles by 32 references (an absent particle is a zero row, a
missing reference a zero column), with each reference in the column of its
place in the list: the bundled OpenBLAS gives an element other last bits in
another column or in a call of another shape, but not in another row of a full
call, so a pair's entry depends on neither its block-mates nor the team, and
the fills are identical at one thread, any team, any batch size and any part
count (polar_matching_bench suite=fills). Another BLAS must keep that row
invariance or the identity is lost. The polar shift maps' shell sums are BLAS
products too (since 2026-11-23: one sgemm per order over the magnitudes that
keep it): their shapes follow the map's geometry alone, and each is cut into row
blocks of m·n·k below SGEMM_ONE_THREAD_MNK (simple_linalg), the bound under
which the bundled OpenBLAS stays on the calling thread outside a team as well, so
a pair's map is the same on any thread, in any team and from a serial caller.
The references are memoised once, in one layout every kernel reads:
ft_ref_terms (2·nk, pftsz+1, nrefs, half) holds, per reference and angular
bin, the shells' conj(FT(REF2)) on rows 1..nk and FT(REF) on rows nk+1..2nk.
The particles' terms have the same order (2·nk, pftsz+1, particles):
ft_ptcl_terms holds FT(CTF2) and FT(X·CTF) for the cc kernels,
ft_ptcl_wterms the same under the sigma2 weights of the particle's half,
w_k FT(CTF2) and -2 w_k FT(X·CTF), for the Euclidean ones. Both are made by
memoize_ptcls, the weighted ones again by memoize_sigma2_weights when the
weights change, so the objective may change on a live calculator. A
shifted-particle bank (memoize_shifted_ptcl) is a particle's terms of the
calculator's objective with the shifted cross term, shaped (2·nk, pftsz+1): a
caller allocates it in that shape and scores it under the objective it was
made for.
With the shells of a bin contiguous, a pair's two sums are one dot product per
bin of the reference terms and the particle terms (term_sums, the BLAS's
cdotc through its C entry): the unshifted and bank kernels of both
objectives, and the reference-power term of the kernels that transform a
shifted reference or a section on the fly (their cross term stays a shell
loop over ft_ptcl_ctf, bins by shells, which the particle memo keeps beside
the terms). The block kernel takes its products from the same memo: a full
tile of consecutive references is read in place, the columns of a bin one
reference apart (the product's leading dimension), any other tile gathered
bin by bin; the block's particle terms are gathered from ft_ptcl_terms or
the banks. No kernel keeps a second copy of the references. The block
kernel's entries are those of the earlier bin-major copy bit for bit; the
per-pair kernels' sums differ from the earlier shell loops in the last bits
(measured: at most 6e-7 relative on every memo-reading kernel, bundled
OpenBLAS on arm64). The per-thread work of the block kernel
(matcher_block_kernel_bytes) is counted by the matcher when the dense table
or the state mode runs. A persistent bin-major copy of every reference
beside ft_ref/ft_ref2 (2026-11-21 to 2026-11-25) cost 32 bytes per shell,
bin and reference in every part: 6.6 GiB at refine3D_auto's 20,000
directions.
The per-pair kernels keep every other caller: gen_posterior_val the members
of the state mode's pooled cells, the geom cones and the shc/snhc
search, and the other pair kernels the 2D tables, the shift refinement, the
posterior diagnostic's cross-half scoring and the cc objective. The members and the cones were measured on the block kernel and
left per pair: at the matcher's batch a cell is pooled by two to four
particles of a block, and the fixed product then uses a tenth to a fifth of
its pairs. On beta-galactosidase (four parts of six threads) the dense score
loop costs 0.38-0.40 of the per-pair routine's and the state mode's 0.53.
The tail of every pair is single precision where only last bits move, double
where a result is decided (2026-11-29, float32_kernels_and_pcg_precond.md).
The distance conversion (euclid_dists_from_crvec) takes the inverse
transform's row in single precision with the norm's reciprocal and the bound
rounded once from double, one fused multiply-add per rotation, and marks an
invalid distance by a select. The draw's and the quadrature's weights
(posterior_weights, used by draw_posterior_row and inpl_quadrature) are
single-precision arguments, clamped at 80/temp, through the array exponential
exp_neg_array (simple_math.f90: within two units in the last place of
float32, exactly 0 from exp(-80) on); the weights' sum, the cumulative sum and
the target stay double. The shift map's cell scoring (shiftmap_draw, reached
in production through shiftmap_mode) forms each cell's tempered log mass in
single precision and finds the maximum in a second pass. On the benchmark's
5 million pairs 0.016 % of the drawn rotations differ from the double tail's;
the fills stay identical across threads, batches and parts; the testers hold
each piece to its double formula (test_dists_single_precision,
test_draw_single_precision, test_cell_scoring_single_precision,
unit_numerics suite math).
Continuous in-plane policy¶
inpl_cont is internal since release 4 (2026-10-03), not a command-line key.
It is yes everywhere except under refine=cont, which sets it to no (the
Cartesian pass solves the in-plane angle itself); no is the historical
alternating search: continuous shift optimization with the discrete in-plane
angle callback. The convergence output keeps reporting the continuous in-plane
runs. yes follows the refine-only
principle: continuous refinement changes pose precision, never search
behavior. Selection sees exactly what the legacy route sees -- candidate
scoring, probability-table profiling, shift-seed estimation, and multi-peak
shift refinement all use the legacy discrete machinery unchanged -- and the
joint raw-Euclidean (sx,sy,rotind_frac) optimizer runs exactly once per
particle per iteration, after selection, to refine the committed assignment.
This makes the search trajectory identical to the validated legacy trajectory
by construction; the continuous route is a strict refinement of it and cannot
alter exploration dynamics on any sample. Objective type is a capability
check and must never activate continuous-angle behavior by itself.
Raw objfun=euclid and objfun=cc provide the analytic joint
(sx,sy,rotind_frac) gradient. The cc route minimizes -cc with a
quotient-rule angular derivative and maps scores as the clamped correlation
rather than exp(-loss). Parameter validation does not couple inpl_cont to
objfun or a specific program. Objective capability
is owned by the PFTC/search implementation. The opt-in is not restricted to refine=shc:
deterministic, neighborhood, evaluation, and probabilistic matcher routes use
the same policy wherever they commit a pose. A mode with no pose search,
such as sigma-only setup, naturally invokes neither optimizer. Unsupported
capability combinations fail validation rather than silently reverting to the
callback. The joint cc route is validated on nanoparticle data as well, so
the nano 2D/3D workflows follow the inpl_cont=yes default.
The continuous in-plane sub-suite of the fast gate
(simple_test_exec test=unit_pftc_align2D3D, simple_pftc_inplane_tester; it
replaced simple_test_continuous_inplane_hybrid_grad in September 2026) guards
the hybrid route with an integer-grid score identity, finite-difference checks
of the derivative components, and construction of the production joint
optimizer.
Probability tables are pure legacy under both inpl_cont values: candidate
scoring, shift-seed estimation, and per-candidate shift refinement use the
legacy discrete optimizer, and the table schema remains discrete (rounded
inpl, score, shift in the rounded-index frame). The joint optimizer never
touches table construction; refining candidates would sharpen the score
contrast the stochastic sampler sees and collapse exploration on difficult
samples (statistics parity below addresses the same failure through the
convergence side).
After hard state/projection/in-plane assignment, the matcher runs the joint
three-parameter optimizer locally for the selected pose -- the single joint
solve of the iteration. The assignment index is authoritative: it converts
the stored shift back to the native particle frame and seeds a solve bounded
to plus or minus two in-plane cells, without another global all-angle
selection. An accepted result persists one coupled pose: fractional Euler
e3, nearest integer inpl, shift, and score. A finite non-improving
evaluation retains the incoming discrete pose with its re-scored objective
value. A numerically invalid evaluation leaves the incoming assignment
untouched. No inpl_cont=yes path falls back to the legacy callback. State
and projection identity remain fixed during the final solve. A persisted
fractional e3 is rounded to the canonical integer cell before the next
search.
Statistics parity. Every statistic that steers search control --
dist_inpl, angular distances, class/projection overlap, and anything the
convergence checker reads -- is computed from the DISCRETE cells on both
sides of the comparison, never from fractional poses. Sub-grid pose precision
would otherwise read as premature convergence and truncate the annealing
schedule that difficult samples require. The fractional e3 and refined
shift are carried for reconstruction and persistence only.
Joint acceptance is guarded twice, in the shared optimizer. An improvement must be material -- it must beat the seed cost by a relative tolerance far above solver roundoff -- otherwise the solve counts as non-improving and the seed pose stands; this keeps the improved fraction an honest diagnostic and prevents noise-level "improvements" from committing fractional poses. A solution pinned to any joint search bound (the shift box or the plus-or-minus two-cell angular window) is likewise demoted to non-improving: an angular-bound-pinned solution contradicts the exhaustive seed selection, and a shift-corner solution is the signature of descent into truncated-series artifacts rather than signal.
Convergence dist_inpl reporting is symmetry-aware. When multiple symmetry
operations have the same Euler distance within numerical tolerance, including
projection-preserving operations in dihedral groups, the reported in-plane
distance uses the equivalent operation with the smallest in-plane change. A
symmetry-equivalent branch switch must not appear as a spurious 180-degree
in-plane move.
Reconstruction, sigma, assembly, and postprocessing children must not receive
matcher-only search policy (pose_cont); inpl_cont never appears on a
command line.
For multi-state alignment (nstates > 1), shift-first candidate scoring is
disabled. The matcher and probability-table paths may still refine shifts after
candidate/state selection, but they must not use a shift seed estimated from a
particle's previous state to score candidates in other states.
A matcher pass reads each selected particle from the stacks once
(doc/policies/particle_read_path_policy.md, "The particle buffer"). The
reconstruction after the search-phase teardown takes its images from the
pass's particle buffer: the raw images, or, when it reconstructs at a cropped
box from a polar search, the cropped observations the search kept as records.
Only when the buffer does not fit its memory budget does the reconstruction
read the stacks again, once per particle. Do not add further reads unless the
performance contract is explicitly changed.
The downscaled particle cache is a 2D-only feature: refine3D rejects
cache=yes and always reads the original full-size stacks (see
doc/policies/2D/particle_cache_policy.md).
Continuous view refinement on polar sections (cont_view)¶
cont_view=no|lbfgsb|lm (default no; doc/implementation_notes/planned/polar_continuous_view.md) refines
projection directions continuously in refine3D_local refine=prob_neigh (one state, objfun=euclid).
prob_neigh_mode chooses how the solver is seeded; topk bounds the hypotheses, without another seed-budget key:
- Geometric seeding (
prob_neigh_mode=geom, local default). Select at mosttopknearest bank directions inside the incoming pose's geometric cone, by symmetry-aware direction distance and stable bank-index ties. A positive particleconeretains its mirror-view contract; otherwiseathres_contbounds eligibility. Re-express the stored in-plane pose about each selected direction, keeping its fractional angle, and run the bounded view solver from zero residual shift (the batch particle already carries its stored shift). No all-angle bank score, shift map, or exhaustive fallback runs. Merge the evaluated solutions into resolution basins before the keyed draw atprob_beta * temperature; insert their best representatives with summed physical-temperature basin masses. An empty cone or no valid evaluated seed retains the incoming pose. A valid seed survives a non-improving or invalid solver result at its own B-spline score. - Image-posterior seeding (
prob_neigh_mode=state). The existing fill, keyed draw and temperatures are those ofprob_neigh; the draw sees the KB bank's scores before the committed pose and extras take the view solve. This route retains image-based in-plane recovery. Withoutcont_view, localgeomretains its image-scored cone search unchanged. - The extras (topk > 1). On the coarse bank no other cell lies within the insertion cone, so the extras are
not the cone's occupants but, in the image-posterior route, the row's
topk - 1entries of highest posterior (the tables skip the cone test under the key). After the committed pose, each takes the view solve from its own cell and shift (refine_extra_pose_continuously); the committed pose and the valid refined extras are merged into basins within the cone of one another (merge_view_basins: single linkage on the refined poses,within_poses), each basin enters the reconstruction at its best pose with its members' posterior weights at the particle's temperature added, a basin belowPROB_INSERT_WMINis dropped, and the committed pose becomes its basin's best when a refined extra beats it (strategy3D_prob%resolve_extra_poses_view, image-posterior route). The effective topk is the number of basins. The readout'sview_*fields and the part's bench report the outcome. - Bank = coarse grid. With the key on,
nspace_sub = nspace(1,000 unless given); the commander refuses an explicit differentnspace_suband the parameters refusenspace_sub /= nspace. The bank holdsnspacereprojections and nothing finer: the view solve takes the place of the fine neighbourhood step. - The solve.
pftc_shsrch_grad's view mode (new_joint_view) minimises the raw Euclidean loss with the joint mode's shift prior over (shift x, shift y, rotation index, tilt x, tilt y), from the drawn cell, its shift and the reference's own view; tilts are the components ofexp([wx,wy,0]x)about the drawn reference's in-plane axes, bounded by2 sqrt(4 pi/nspace)rad. Sections and their exact tilt derivatives are cut bypolarft_cont_calc(build%pcont) fromcartft_calc's B-spline references (gather_ref), which the master writes beside the polar model (cart_refs_needed) and a view pass reads into a calculator of its own (read_cart_refvols_view): references inbuild%cftcwould make each batch prepare Cartesian particle slots (build_batch_particles3D);polarft_calccorrelates the supplied section (gen_sect_euclid_grad_at_angle) and gives the Gauss-Newton matrix thelmsolver uses. The solve commits only on improvement over its own B-spline re-score of the drawn pose. - The committed pose. The prob strategy applies
strategy3D_srch%commit_viewafterassign_ori: the pose isRz(psi) T(w) R_refcomposed from matrices (view_pose; never a new e3 paired with the cell's e1, e2) andprojis the grid direction nearest to it. A stored off-grid pose is read back about its nearest cell byeuler_about_cell(prep4prob, the tables' shift seeds,assign_ori's distances, the sigma2 residual): the cell's direction with the in-plane angle closest to the pose, exact near the poles; on the cell the stored e3 as it is, so the no-change case is untouched. - Sigma2. A valid view solve's residual is taken at its point on its own section (the B-spline section at its
tilts, its shift, the rotation rounded to its grid index; the seed when the solve did not improve, so the stored
corrand the residual come from one model:polarft_cont_calc%sigma_contribthrougheuclid_sigma2%calc_sigma2); an invalid solve's and every other particle's is the bank section's.calc_sigma2_pftctakes the pose's shift as stored (the particle frame) and converts it to the shift of the reference at the evaluated rotation (shift_ptcl2ref), the evaluators' frame, so both residuals are the cost's (2D and 3D alike). - Off-route. The key is refused on
refine=cont, more than one state,objfun=cc,refine3D_autoand the other programs' parameter construction ignores it (the master's reconstruction children inherit its command line).refine3Ditself accepts it onrefine=prob_neighwith the same checks: it is the stage programrefine3D_localruns, and its workers carry the key. - Counts. The part's BENCH reports the view solves, sections cut, cost evaluations and their per-solve
ratios (
match3D view ...).
Continuous Cartesian pose policy¶
refine=cont is a refinement mode of refine3D (contract of the pose_cont
refactoring, doc/refactoring_notes/completed/pose_cont_refactoring.md). It
refines the five pose parameters of every sampled particle (three rotation
components, two shifts) continuously against Cartesian central sections of
the reference, from the poses stored in ptcl3D. It runs none of the polar
machinery: no projection grid, no polar reprojection model, no probability
table, no in-plane table. It is a continuation mode: every active particle must hold
a pose from a discrete workflow (positive state, half-set, projection
direction, finite angles and shifts); check_cont_seeds stops the run at
entry otherwise, before the random-orientation fallback of an unsearched
field. It searches no state: each pose is refined against its own state's
reference, and a multi-state start seeds and writes no labels for it
(labels_may_change, as for refine=sigma and eval), so a state left
empty, or a project in one state, is kept as it is (since 14 October 2026;
stream p07's local refinement relies on it).
Ownership:
src/main/cftc:cartft_calc(reference slots per state and half, particle slots of the batch, objective, gradient, normal terms, residual) andcartft_pose_opt(one bounded Levenberg-Marquardt transaction per particle: the joint five-parameter stage,lm_solveof the library's enginesrc/utils/math/simple_lm_solver.f90on acartft_pose_problem; a shift-only solve at a fixed rotation,refine_shift, is public for other callers and is not part of the transaction).simple_strategy3D_cont:strategy3D_cont, the matcher's only continuous-pose search object; it extendsstrategy3Dbeside the polar parentstrategy3D_pftc. The matcher also sumscartft_pose_work, the work record of the solves, per thread for its bench report (section 11.1).- The iteration strategy materializes the prepared real-space reference
volumes once per iteration (
cart_refvols_{even,odd}.bin, section 6 of this policy applies unchanged up to the polar projection). Every matcher reads them, pads them by 2 and keeps the packed padded transform per state and half, scaled bypadf**3and weighted per axis by the KB stencil's response over the B-spline stencil's (ref_weight). - Central sections are gathered on the fly with the separable quadratic B-spline on three taps per axis, continuous in value and derivative. On grid it reproduces the polar branch's KB model (KB interpolation policy, section 6a).
- Particle preparation follows
prepimg4alignup to the soft mask (centred on the stored shift, phase-flipped forCTFFLAG_YES) and multiplies by the KB stencil's taper (prepimg4align_cart), so the two representations share one sigma2.build_batch_particles3Dfills the Cartesian slots of the batch from the same read.
Evaluation: one pass (pose_normal_terms) returns the objective, the
five-vector gradient and the 5x5 Gauss-Newton matrix, and under euclid the
whitened |r|^2 per shell. It runs over the Friedel half plane of the
particle's band: for a real image every summand is Hermitian between (h,k)
and (-h,-k), so the half-plane sums are doubled and DC is added once. The
shift phase comes from two 1-D tables per pass. The full-disk kernels are
kept (*_full_disk) as the tests' reference.
Precision (2026-11-29, float32_kernels_and_pcg_precond.md): under euclid
the pass is single precision (pose_normal_terms_sp). A prepared Euclidean
slot carries a pixel table, its band's half-plane pixels with their frequency
factors, shell, observation and transfer in the kernel's order (fill_ptcl);
the pass gathers the reference for 64 pixels at a time through the array form
of the B-spline gather (gather_packed_bspline3_window_grad_n) and forms the
23 sums as float32 partials per block of 64 pixels, added in double; the DC
pixel, the finaliser and every decision of the LM transaction stay double. It
agrees with the double kernel within 1.4e-7 of the objective, 9e-7 of the
largest gradient component, 2.1e-7 of the Gauss-Newton matrix's diagonal and
4.4e-6 of each shell's residual (test_euclid_kernel_single_precision), gives the same solves on
cont_refine3D_bench, and is 18-24 % cheaper per pixel-evaluation at 24
threads. cc keeps the double kernel (pose_normal_terms_dp, also the float32
kernel's reference): 1 - cc is formed from large sums and cancels near the
optimum, so float32 terms would blur the pose there; its results are unchanged
bit for bit.
Objectives follow objfun: cc is 1 - cc with uniform per-pixel weight and
no sigma2 (a Cartesian cc pass reads, requires and writes none); euclid is
the polar loss normalized by the particle's whitened power, stored as
exp(-L). Its sigma2 contribution is the per-shell residual of the evaluation
that chose the committed pose (the seed, or the last accepted step), which the
transaction keeps (get_shell_residual) and the sigma owner unwhitens
(calc_sigma2); it costs no pass of its own.
The bounds are trs (total shift from the stored shift) and athres_cont
(default 10 degrees: the halfwidth of the total rotation from the stored pose,
the capture range for wrongly assigned orientations); athres and
prob_athres, which size the polar searches, do not apply. The solve is the
joint five-parameter Levenberg-Marquardt stage alone, about a third faster than
a shift-only stage before it (the former shift_then_joint route, retired in
lm_optimizer.md); repeated passes supply what one joint pass misses.
inpl_cont is overridden to no (the in-plane angle is part of the solve).
Steps and stopping (cartft_pose_opt on simple_lm_solver). The engine owns
the step control: the system scaled by (rotation_scale x3, 1, 1) and masked to
the active coordinates, the damped matrix C + mu*diag(d) with
d_i = max(C_ii, sqrt(eps)*max|C|, eps**2) solved by spd_solve_rel
(simple_linalg), mu from 1e-3, multiplied on a rejection by a factor that
starts at 4 and doubles, halved when the actual over predicted reduction
exceeds 0.75, and a step accepted at a positive reduction of at least 0.25 of
the predicted one; an unreliable damped solve counts as a rejection. The
transaction's problem owns the rest: the data-only observability veto (the
prior is added after it, so a prior never rescues an unobservable
pose: CARTFT_NO_RELIABLE_UPDATE), the rotation and shift step caps, the right
increment and the cumulative guard, the prior terms, and the shell residual.
- Curvature scale. Both objectives' Gauss-Newton matrices are multiplied
by the regression slope of the data on the model, weighted by
|f|^2as the matrices are and clamped to [0.05, 20] (curvature_scale). Forccthe slope stands in for the correlation, by which the plainJ^T Jof a normalized objective overstates the curvature. Foreuclidit corrects the over-step of a model brighter than the data. - Stopping. A stage stops:
- when an accepted step reduces the objective by less than
1e-6of it, or moves neither the rotation nor the shift by1e-8(radians, pixels); - when a proposal predicts less than that (it is not evaluated);
- when the scaled, masked gradient falls below
1e-8; - after 8 consecutive rejections;
- at 40 iterations.
- Passes per solve. The joint stage reuses the seed's evaluation and returns the objective at its endpoint, so a solve with N trial evaluations makes N+1 passes.
The rationale and the measured gains are in
doc/implementation_notes/completed/cont_lm_acceleration.md. The work
counters are the CONTINUOUS POSE WORK section of the bench report (section
11.1); test=cont_refine3D_bench times the solves on simulated 1JYX particles
(test environment policy).
Scores: a Cartesian pass writes corr_cart (slot 51 of the particle record),
the improved flag (slot 52) and the transaction status (pose_cont_status,
slot 42, a CARTFT_* code) for every particle it processes and never writes
corr, which keeps the value of the last polar pass. The two are not
comparable (C9). The convergence report of a Cartesian pass shows the mean
corr_cart, the attempts (the sampled particles) and the improved fraction.
Convergence under refine=cont (check_cont_conv in simple_convergence,
constants in simple_defs_conv): a sampled particle is stable when its
transaction ended accepted or with a finite no-improvement and it moved by at
most 0.5 degrees (dist + dist_inpl, an upper bound on the rotation angle)
and 1 A (shincarg * smpd). An iteration passes when 90% of the sampled
particles of every populated state are stable. The run converges when
consecutive passing iterations have together sampled 90% of the active
particles (sampled at or above the generation the streak began with); a
failing iteration resets the streak, and minits and maxits apply as for
every mode. A rejected transaction keeps the seed, so a zero pose update alone never
counts as convergence. The three thresholds are parameters with these values as defaults:
cont_conv_rot (degrees), cont_conv_shift (A) and cont_conv_frac (the
stable fraction and the streak coverage).
Continuous followup: pose_cont=yes in a discrete mode makes the iteration strategy follow
every discrete pass with a refine=cont pass over the same particle sample
(sample4update_reprod), in shared memory and distributed. The discrete pass
then writes no partial reconstructions; the continuous pass writes them, so the
iteration reconstructs once, from the refined poses. The continuous pass writes pose,
corr_cart, the improved flag and, under euclid, sigma2 into the sigma2
transaction the discrete pass opened: it starts from the discrete pass's
residual rows and replaces those of the particles it evaluates, so a particle
whose Cartesian slot is invalid keeps the residual of its discrete pose. It
leaves corr and the convergence fields of the discrete search (dist,
dist_inpl, shincarg, mi_proj, mi_state, frac, frac_greedy), so
convergence keeps measuring the discrete search. refine=cont with pose_cont=yes is the
internal name of the continuous followup pass and is refused on the command line.
Tests: unit_cart_align3D (cart calculator, pose optimizer,
pose strategy, pose statistics), lib_cart_align3D (1 000 simulated 1JYX
particles through strategy3D_cont), and the high-level gate
cont_refine3D_1jxy (shared memory, distributed, refine3D_local, auto and the continuous pass),
all gated on the simulation's ground-truth orientations.
refine3D_local is the single-state continuous continuation command. It uses
this refine=cont engine; see refine3D_local_policy.md.
Per-state M-estimation¶
refine3D_auto state=X refines state X of a multi-state project alone, as a
single-state refinement. m_estimator=no|flex {no} selects how particles enter
its reconstructions. With m_estimator=flex the run is a per-state
M-estimation: state X's members are aligned, and X's map is estimated from them,
each contributing with its weight for X in the project's state weight set. The
state weight set holds one weight per particle and state; flex_pca publishes
it (refine3D states policy). The weights are frozen: nothing in the run
recomputes them. With m_estimator=no the run refines the particles labelled X
from their hard labels, the hard comparison.
Members. The state weight set decides, once and for every consumer, which
states a particle is a member of (simple_state_weight_set). A particle's
energy is the sum of its squared weights over the states. Its largest weights
are taken in decreasing order until they carry 95% of that energy
(STATE_WEIGHT_ENERGY); the states they belong to are its member states, and a
state tied with the last one taken is a member too. No weight at or below 0.01
(STATE_WEIGHT_FLOOR) makes a member: PCG divides a member's noise spectrum by
its weight. A particle split between two states is a member of the second when
its weight there is above about 23% of its larger weight. Alignment and both
reconstruction backends use these members and nothing else, so a particle that
no reconstruction would insert is never aligned. The set's mass and effective
sample size of a state are those of its members.
Without state=, a project with more than one state to refine is refined state
by state, each as above, and the results are merged (the state sweep, below).
With one state to refine, m_estimator=flex without state= is refused, and
so is m_estimator=flex on a multi-state refine3D or on refine3D_states: a
search over states moves the labels the frozen weights were computed for.
nstates=N with m_estimator=flex and no state= makes the weight set in the
same run: flex_pca first divides a single-state project into at most N states
with soft weights (the flex-initialized sweep, below).
Work project. prepare_state_work_project
(simple_commanders_refine3D.f90) builds it right after the parameters are
built. state= requires mkdir=yes, so the work project and its weight set
live in the run's own directory.
- The project is copied to
refine3D_auto_stateXX.simple, and the selection program runs on the copy with pruning. The selected rows are the members of X (m_estimator=flex) or the particles labelled X (m_estimator=no); they reach the selection program as its per-row selection file. The copy holds them alone, as state 1. Each work row is checked against its parent row by stack and index in the stack. - State X's map and FSC, read from the parent, become state 1's in the copy,
where
refine3D_autofinds them as its project volume. Every other state's map and FSC entries are removed, as are the parent's weight-set entry and its canonical sigma2 registration. The copy's sigmas are seeded in this run, as for any project. - With
m_estimator=flexthe copy gets its own single-state weight set (publish_work_stateinsimple_state_weight_set): X's column at the work rows, the parent's hard-label flags for X, and the parent's producer and kind. Its manifest records the parent set's generation, layout digest and state as provenance. Publishing it over the parent's manifest is refused. - The run continues on the copy as an ordinary single-state
refine3D_auto.state=leaves the command line;m_estimatorstays. The run directory's copy of the parent is deleted, so the work project is the directory's only project. The project given on the command line is never written.
Reconstruction. With m_estimator=flex, every reconstruction of the run
reads the work project's weight set, from the startup reconstruction to the
final native one. In each iteration the matcher's write_partial_recs
(simple_strategy3D_matcher) passes the set to calc_3Drec on gridding, or to
the PCG (preconditioned conjugate gradients) worker. Every row of the work
project is a member, and each backend inserts it with its weight. Volume
assembly, update fractions and trailing
reconstruction count applied mass (the sum of the weights as the backend
applies them) instead of rows; see the
importance-sampling and fractional-update policy.
Alignment and sampling work on the members. Every row of the work project, that is every member of X, is aligned against state 1's reference and gets one pose, as in a hard run. The sampler does not read the weights; it chooses among the work project's rows by its usual rule.
Population gates use the effective sample size (ESS: the squared sum of a
state's weights divided by the sum of their squares), not row counts. The
probability table treats a state as present when the ESS of its weights exceeds
the table's minimum population (simple_eul_prob_tab). The per-iteration
registration and carry-forward decision (get_state_pops in
simple_refine3D_strategy) treats a weighted state as populated when its
weights carry applied mass, which is exactly when it has partial
reconstructions.
Final native reconstruction. calc_final_rec (simple_final_rec) puts
m_estimator, and state when the refinement command line has one, on the
child command line it builds. That line drives both of its routes, the direct
reconstruct3D and bootstrap_rec3D. It records the weight set's identity
(generation and layout digest) before reconstructing, and stops if the identity
has changed when it registers. The vol entry of each weighted map carries
three separate numbers: the hard population pop (the parent's label count of
X, for reporting), the applied mass mass and the ESS ess. Mass and ESS are
computed over the reconstructed rows, from the weights as the backend applied
them.
The refined map of X, its FSC and the refined poses live in the work project. A state sweep folds them back into a copy of the parent (below).
State sweep¶
refine3D_auto and refine3D_local without state= refine a project with more
than one state to refine one state at a time, and merge the results into one
project (run_refine3D_state_sweep, simple_commanders_refine3D.f90). The
sweep adds no scientific behaviour: each state is the ordinary state=X run
above, with the full nthr and nparts, and states run one after another.
Trigger. The commanders decide before the workflow touches the command
(refine3D_sweep_states). With state= given they take the existing path
without reading anything. Otherwise the states to refine are every positive
ptcl3D label with particles, or under m_estimator=flex every state of the
weight set that has members, ascending. With fewer
than two, the existing path runs, refusals included. vol1 (one state's map)
and mkdir=no are refused for a sweep.
Flex-initialized sweep. nstates=N asks for a sweep whose states flex_pca
makes first. It requires m_estimator=flex, no state=, N of at least 3
(FLEX_INIT_MIN_NSTATES), and a project with state=0/1 labels and no state weight
set: a set an earlier flex_pca made is refined as it is, never replaced, so with
one the command is refused and nstates must be left out. nstates > 1 without
m_estimator=flex is refused. The sweep makes its directory and copy first, then
runs flex_pca in place on the copy (mkdir=no) through
run_refine3D_flex_init (simple_refine3D_flex_init.f90), the routine
refine3D_states initializes with: npreimages=N, the run's rec_backend for
the basis M-step and the state maps, and the consensus map of the project's out
segment. Unlike refine3D_states it keeps the weight set and runs without the
population floor: the floor's placement (min_state_frac > 0) assigns hard
states, whose one-hot weights would make the M-estimation a hard-label
refinement, so min_state_frac > 0 is refused. N is therefore a ceiling: flex
places N states with its kernel weights and drops those below min_neff. The states to refine are then the weight
set's states with members, read from the copy, and the sweep continues as below
on the copy instead of the input; the children do not see nstates.
Before anything is made (after flex_pca, for a flex-initialized sweep),
the sweep records, from the input project (or the labelled copy), the rows each
state selects. It runs the halves' one maker, eo_transaction, on a
copy in memory and refuses when that would change the half of a row to refine:
each child would otherwise make its own halves. Projects whose halves an
earlier release made without stack records pass, as they do for a direct run.
Children. The sweep builds its parameters once, from the program, the
project and the directory keys, which makes its numbered directory and its copy
of the parent. The command line's projfile then names that copy, where the
command-line interface appends its job entry. For each state the sweep restores
the generator state a direct run's process starts from:
- with SIMPLE_SEED given, seed_rnd_fixed sets the reseed count to zero and
exports the run seed;
- without it, unset_run_seed unsets the variable and drops the cached run seed,
because the previous child's refine3D exported a seed of its own.
The child starts in the entry directory, where a direct run starts, so relative
input files resolve as for a direct run. It runs as exec_refine3D_workflow
with the command as given plus state=X and outdir naming its directory
inside the sweep's.
Merge. After the last child, every work project is folded into the copy:
- merge_state_rows (simple_sp_project_ptcl.f90) checks the work rows against
the parent rows by stack file and index in the stack (ptcl_rows_match). It
then checks the row identity: half, index in the stack, particle index, optics
and group, CTF observation, coordinates and frame. Each row labelled X then
takes the child's record, keeping the parent's label and stack number; rows
labelled with another state keep the parent's record. A mismatch stops the
sweep with the parent unchanged.
- import_state_artifacts (simple_sp_project_out.f90) registers the child's
map and FSC as state X's, with pop, and mass and ess when weighted. The
single vol_msk entry is the last child's; the weight-set entry is the
parent's.
- rebind_reference_set (simple_refine3D_provenance.f90) binds each child's
reference record to the merged parent and to state X. It keeps the record's
constituents, settings digest, geometry and matching low-pass, recomputes the
particle identity on the merged parent and sets the producer state to X. It
copies the recorded state-01 masks (automask, NU envelope, order mask) to their
state-X names beside the map. Every record is checked before any is changed;
a pending or invalid one stops the sweep, and a child without one keeps the
legacy route.
The copy's project information is updated to name itself, and the copy is
written once, through a temporary file and a rename. The table
refine3D_state_sweep.txt (state, child directory, work project) is written
beside it.
What the sweep does not do. The children's sigma2 stores and trailing chains
are not copied into the parent; a later local run validates as it does today.
The project given on the command line is never written. An interrupted sweep
leaves its copy (labelled by flex_pca in a flex-initialized sweep) and the child
directories, and is rerun from the input, flex_pca included; there is no resume. A rebound child work project is no longer a
continuation source: continuation is from the merged parent.
Continuation. The merged parent is a valid source for refine3D_local,
with state=X or as a sweep. With default settings a local run rebuilds its
derived products from the half maps rather than staging them. The final
reconstruction records its map with filt_mode=none unless automsk=nu, so its
settings digest differs from a nonuniform local refinement's. When the settings
match, local staging copies the recorded masks of the producer state, the order
mask included.
The fill's benchmark counters and particle-frame shifts¶
The fill's cost record (prob_fill_profile) is printed in each part's
REFINE3D_BENCH_PARTppp.txt record, the match3D fill ... lines (the files
are in BENCH/, section 11.1): the counts (the particles filled, the
references scored and refined, the shift searches, their alternations, the
coarse-grid evaluations, the objective and gradient evaluations, the coarse
maps, the shifted particle memos) and the thread-seconds of the fill's regions
(seed estimation, score loop, refinement, their sum, the fill region's wall
time and the load balance), beside the wall time of the table fill and of the
assignment. Thread-seconds are never part of % accounted for. The strategy
record times the master's sample draw where it timed the pre-step. The
PROB_TAB* and PROB_ALIGN* families were retired on 2026-11-05.
Every table fill with a shift search (the single-state and multi-state prob
tables and all prob_neigh fills) runs its loop with dynamic OpenMP
scheduling: the particles' costs differ (the shift searches, the stopping rule
of prob_neigh), and static blocks left threads idle at the tail. The dense
table and the state mode take blocks of particles (above), the other fills
single particles; a block or a particle is processed whole by one thread with
that thread's search object, and every draw is keyed on the particle and the
reference, so the schedule changes no draw. The score loop's thread-seconds of
a fill in blocks include the block kernel's call.
Every probabilistic table holds its shifts in the particle frame (the only
path since 2026-10-15; a developer key used to switch it on). The kernels shift the reference in its own polar frame and correlate
over every in-plane rotation, so a reference-frame shift s is the
particle-frame shift s * R(angle of the rotation) at that rotation (what
sh_rot already converts). A particle-frame shift is the same at every
rotation, so the particle can be shifted once, transformed over rotation like
ft_ptcl_ctf (memoize_shifted_ptcl), and scored against the unshifted
memoised references. The kernels that score such an entry
(gen_objfun_vals_bank, gen_posterior_val_bank, gen_euclid_dists_bank) sum the angular Nyquist
bin too, so a score is exact against the true shifted loss; the
shifted-reference kernels drop that bin and differ from it slightly.
- Particle-frame seed, single-state
probtable and everyprob_neightable that seeds (shcmode, and thegeomandstatemodes in single-state runs) with a shift search: the seed ofestimate_shift_seedis converted once at the rotation where its search ended and held as one particle-frame shift. Every scored reference, in the coarse and in the fine pass, is scored from one shifted particle (a seed belowSHERRSQuses the plain memo), a refined reference starts from the seed converted at its own rotation and clamped into the box, and an assigned candidate that was not refined records the seed as it is (record_seed_shift). - Particle-frame grid, multi-state
probtable: the 5 x 5 lattice of the coarse shift grid is a lattice of particle-frame shifts, one entry per lattice point built once per particle and shared by its refined references. The grid minimum starts the shift search at the reference-frame shift it corresponds to at its rotation, clamped into the box. - Quadratic step, multi-state
probtable: the L-BFGS-B alternations of a refined reference are replaced by a quadratic fit to the lattice, where the grid minimum has a full 3 x 3 stencil, the fitted curvature is positive definite and well conditioned, the step stays inside the centre cell and the search box, and one exact evaluation at the fitted shift (one more lattice entry) beats the grid minimum. Otherwise the alternations run from the grid minimum.
All three are approximations of shifting each reference by the seed: away from the seed rotation, and on the lattice, the scores, starts and recorded shifts differ from it. The parts' bench records (the fill lines) record the shifted particle memos built and (multi-state) the fits kept and the fallbacks per reason.
9. Volume Assembly¶
When volrec=yes, matcher workers write partition-local Cartesian partials and
the strategy dispatches volassemble.
volassemble:
- reduces partition-local partial reconstructions
- restores dense even/odd half-volumes, deapodizes them and applies the soft
spherical support at
msk_crop(identical to the PCG solve support) before writing; the merged volume gets the same support; the support is recorded in the<vol>_pcg_support.txtsidecar so downstream consumers never mask again (2026-09-09) - calculates FSC curves and state resolutions on the halves as shipped
- calculates conical FSC and cFAR from copies of the shipped halves; with
envfsc=yesthe copies are additionally masked by the on-the-fly density envelope low-pass filtered atenvmsklp, and the phase-randomized radial FSC uses the shipped half-volumes to determine its 0.8 randomization onset. No second spherical mask is applied anywhere in the FSC evaluation.envmsklpdefaults toENVMSKLP_DEFAULT(20 A) and is separate from theamsklpNU-evidence smoothing scale - writes
automask3D_stateNN.mrcwhenenvfsc=yes; the same density envelope is available to compatible non-PCG final postprocessing - restores merged state volumes
- derives the NU-evidence envelope from the completed accepted NU bank before unary storage is released
- writes derived NU reference products (
_nu_filt,_nu_locres) on both backends through the sharedsimple_nu_state_filtercompetition - records diagnostics and NU matching metadata in the project: per-particle
res(state FSC=0.143 resolution),res05(state FSC=0.5 resolution), andcfar(state conical FSC area ratio), the raw NU matching handoff inlp(clipped againstlpstopby the matcher before use) and, when NU filtering is active, the same NU-estimated limit inlp_est. The convergence readout reportsRESOLUTION @ FSC=0.143,RESOLUTION @ FSC=0.5, the band this iteration actually matched at (MATCHING LOW-PASS LIMIT (THIS ITERATION), fromparams%lp/kfromto(2)as fixed byset_bp_range3Dbefore the search -- an explicitlpor the previous handoff) and the handoff for the next iteration (NU HANDOFF LP (NEXT), the projectlpfield assembly writes after the search; 2026-09-14, after an explicitlp=3.6run reported the handoff as the matching band), per state whennstates > 1, and persists them asRESOLUTION,RESOLUTION_FSC05,LP_MATCHING(the matched band),LP_NU_HANDOFF,LP_ESTIMATED(plus_STATEnnvariants) in the iteration stats. Both backends write the same fields.cfaroccupies particle-record slot 53; older, narrower binary records zero-fill appended diagnostic slots when read
Volume assembly does not refresh matcher PFTC references. It only produces Cartesian volumes and metadata for the next iteration.
The shared helper restore_state_from_parts owns the restoration sequence.
Changes to ML ordering, sampling-density correction, FSC handling, trailing
reconstruction, low-resolution even/odd insertion, or LP-set behavior must go
through that shared helper rather than duplicated assembly branches.
FSCs and FSC-derived diagnostics are calculated from dense Cartesian half-volumes, not from sparse, intermediate, or low-resolution-blended registration-reference representations.
The nonuniform filter's source halves are the restored halves kept in memory as they are written (the box only, as a read of the file gives them). The trailing counts use the particle field in memory. Assembly back-fills missing projection labels before it; the labels do not enter the counts and are kept in the field it writes (since 2026-10-18; before, the counts reread the field and so dropped the labels on trailing runs).
9.1 PCG reconstruction backend¶
rec_backend=gridding|pcg selects the reconstruction backend; gridding is
the unchanged default and protects all existing workflows. The PCG solver
contract, output convention, ML two-map behavior, warm starts, and
diagnostics are owned by
reconstruct3D_pcg_policy.md; this section
records only the refine3D-side integration contract:
- Solver controls are distinct from refinement controls.
maxitscounts refinement iterations; the PCG solve budget ismaxits_pcg(default 2; more than 8 warns, more than 100 is refused) andrtolis PCG-specific (rtol <= 0demands exactlymaxits_pcgiterations). - The backend seam is dense even/odd half maps.
volassembledispatches to a backend-specific state restorer: gridding reduces(cmat,rho)and sampling-density-corrects; PCG reduces raw(B,D), finalizes the kernel and solves. FSC/cFAR diagnostics, filenames, and project updates share policy helpers, and both backends synthesize_nu_filtreferences through the same assembly-owned NU competition (base pair = the unregularized_unfilhalves, auxiliary member = theP_tau-regularized halves). PCG maps never receive gridding correction, a second sampling-density correction, or a post-hoc mask. - Raw statistics boundary. Workers accumulate and atomically publish raw,
unregularized
(B,D)per(state,half,part); only the master folds, finalizes, regularizes, and solves, reducing parts in ascending order. - Sigma ordering. For
objfun=euclid, iterationnscores and reconstructs with the sigma model committed before the iteration began. It writes new residual estimates into a pending transaction, completes assembly, and only then publishes them for iterationn+1. A stage-owned reconstruction such as solve3D symmetry consumes the same lagged model before the final transaction is published.objfun=ccis unweighted. - Weights versus priors. Particle/data weights (including
1/sigma2) multiply bothBandD. The zero-mean ML prior adds precision to the normal operator and preconditioner only; it never weightsB, and nothing prior-related is persisted in raw statistics. - FSC ownership. The FSC comes from the unregularized
_unfilbase pair and remains the resolution authority. The regularized pair is the closed-formP_tauoptimum of the base pair on the replayed operator (voxelwise,shrink_by_ml_prior, 2026-09-14; the replay solve is retired); NU filtering is applied afterwards by the shared competition, never inside the solve (policy 2026-09-06). - Solve support.
automsk=densityuses the conservative density envelope;automsk=nuprefers the lagged NU-evidence envelope and falls back to density; an explicitpcg_mskfileremains an override. The selected mask constrains both base and replay andenvfsc=yesis implied. PCG reports FSC on the constrained pair without post-hoc masking or phase randomization, logged as>>> FSC MODE. Before either mask source exists, the base bootstraps on the sphere and its current pair supplies replay density. - Current exclusions (hard-errored, not approximated): matrix-free workflow execution. Fractional/trailing reconstruction is implemented in the distributed master path.
- New regularization is research, tracked in
doc/implementation_notes/completed/pcg_priors_history.md; it cannot be used to close integration gates.
10. Trailing and Combined Even/Odd¶
Trailing reconstruction blends the even accumulators (sums and sampling density) with the previous even chain and the odd with the previous odd chain, in the accumulator domain (importance-sampling policy, section 7); finished half maps are never blended. It runs before restoration, NU-evidence envelope generation and derived reference filtering.
In LP-set mode, if trailing is active, assembly blends the even and odd accumulators first and restores the merged volume from the blended sums. Assembly must not use low-resolution even/odd docking insertion for LP-set outputs.
When combine_eo=yes, distributed refine3D schedules one additional final
iteration after convergence or run-length termination. That final iteration:
- disables fractional update
- forces full update
- sets
combine_eo=yes - tightens the low-pass criterion to at most 0.143
The combined even/odd iteration is part of base refine3D, not a terminal
refine3D_auto or solve3D reconstruction step.
11. Finalization and Artifacts¶
11.1 Benchmark reports¶
Benchmarking (L_BENCH_GLOB, on in every build) writes its reports into one
subdirectory of the run directory, BENCH/, never into the run directory
itself. Each benchmark family has one file there, and a family that every
partition reports has one file per partition. A report is appended to its
file as one record, so a run of any length writes a fixed number of files: for
a distributed solve3D run with 10 partitions, about 25 instead of one file per
iteration and partition (3,104 for a solve3D run of 94 refine3D iterations).
| file | written by | records |
|---|---|---|
REFINE3D_STRATEGY_BENCH.txt |
the refine3D strategy | one per iteration |
REFINE3D_BENCH_PARTppp.txt |
each 3D search partition | one per iteration |
REC3D_BENCH_PARTppp.txt |
each partition's reconstruction (gridding or PCG) | one per pass |
VOLASSEMBLE_BENCH.txt |
volume assembly | one per iteration |
PCG_ASSEMBLE_BENCH.txt |
the distributed PCG master (rec_backend=pcg) |
one per iteration |
SIGMA2_COMMIT_BENCH.txt |
the sigma2 commit | one per commit |
SOLVE3D_BENCH.txt |
solve3D, solve3D_addon |
one per run |
REFINE2D_STRATEGY_BENCH.txt, REFINE2D_BENCH_PARTppp.txt |
the refine2D strategy; each 2D search partition | one per iteration |
SOLVE2D_BENCH.txt |
solve2D |
one per report |
CAVGASSEMBLE_BENCH.txt, CAVGASSEMBLE_SUMS_BENCH.txt |
class-average assembly; its sum of the parts' contributions | one per assembly |
CAVGSUMS_BENCH_PARTppp.txt |
each partition's offline class sums | one per call |
A record starts with a *** BENCHMARK RECORD *** header that names the family
and, where they apply, the iteration (which_iter) and the partition. The
writer's own sections follow, as before: BENCHMARK CONTEXT and TIMINGS (s),
plus THREAD-SECONDS for the 2D and 3D searches (with the fill's regions under the probabilistic modes) and the class sums
(busy time summed over the team, the region's wall time, the team size and
the load balance), and RELATIVE TIMINGS (%) where a
writer reports them. A Cartesian pass (refine=cont, the Cartesian followup) adds
CONTINUOUS POSE WORK to its REFINE3D record: the solves by CARTFT_*
status, LM iterations, trial evaluations, accepted steps, bound hits,
calculator passes (the sigma2 residual is the committed evaluation's, with no
pass of its own), pixel-evaluations (passes
times the pixels of the particle's shells in the full disk), the solves that
reached the iteration cap, a histogram of actual over predicted reduction at
accepted steps, and the search
thread-seconds per pixel-evaluation. Its context gives the bytes of the
Cartesian references, and their read and transform count as reference
preparation. Each partition appends only to its own file, so
concurrent workers never write to the same file. The shared helper is
open_bench_report in src/fileio/simple_bench_io.f90; a new benchmark
writer uses it rather than opening a file of its own. SIMPLE never truncates
these files, and a record does not identify its run: clear BENCH/ before a
second run in the same directory.
scripts/plot_refine3d_bench.py reads a BENCH/ directory, or a directory of
the per-iteration files of earlier builds, and writes the per-iteration
summary table, a long table of every record, a text report and the figure;
for refine2D iterations also their critical path (bench_iterations2D.csv,
bench_profile2D.svg).
VOLASSEMBLE_BENCH.txt has, after its % accounted for line, a section
SPLIT TIMINGS (s): the nonuniform filter split into candidate filtering,
objective, label optimisation and composition, and per state the restore and
the filter. These are parts of the timings above and are not added to the
accounted total. The summary script adds the filter split as columns of
bench_iterations.csv.
PCG_ASSEMBLE_BENCH.txt is the PCG backend's counterpart, written by
assemble_refine3D_pcg around execute_rec3D_pcg_distributed_master and the
NU low-pass handoff. Its TIMINGS (s) are disjoint wall-clock phases summed
over states and halves: init, solve support, operator setup, raw read (I/O,
headers and validation of the partitions' accumulators, or of a carried
chain), raw summation, trailing chain (scaling, reading and blending the
previous chain, writing the new one and its manifest), operator finalize
(for the ml pair only P_tau and the preconditioner, since it reuses the base
pair's operator and reads nothing), the base, prior and ml solves (wall time
of the concurrent pair), solve finish (validation and the diagnostics files),
FSC and cFAR, map output, the nonuniform filter, project write, cleanup, the
handoff, total and % accounted for. Its context gives the raw files and
bytes read and the solve iterations per half; its SPLIT TIMINGS (s) give
the operator finalize per solve kind, each half's solve time and the NU
filter split. The summary script
splits the strategy's assembly into volassemble, four PCG master groups (raw
reduction; operator and solves; FSC, maps and NU filter; other) and the rest,
and reports the PCG phases over the run and by stage.
On each iteration, the strategy report should stay simple: context plus one
TIMINGS (s) section. Labels should include the coarse operation buckets
setup, the sample draw, matcher/scheduler, assembly/postprocess, and
total time, together with separately timed reprojection-model materialization
and the sigma2 transaction (the candidate preparation and the commit). These
measurements keep a per-iteration sigma update distinguishable from reference
preparation.
11.2 Run artifacts¶
Base objfun=cc refinement still does not bootstrap or consume sigma2. The
external-reference wrappers are the explicit exception: their shared service
runs calc_pspec before the fixed-reference CC pass, preserves that native-grid
partition state outside the initialized cohort, and replaces active cohort
shells with residual sigma2 after committed assignments.
Distributed matching writes partition alignment documents and merges them into the project after worker completion. Shared-memory matching writes the project directly after each iteration.
After the current iteration's committed orientations are available, both
strategies attempt to write orientations_distribution_stateNN.jpg for each
nonempty state. This projection-direction distribution is a secondary,
latest-view visualization, generated and overwritten at every iteration. It is not
authoritative scientific state, is not registered in os_out, and is not a
restart or workflow-handoff artifact. An empty state may produce no
new image. Failure to write this JPEG warns but does not invalidate the
refinement iteration.
After assembly, both strategies write one per-state
fsc_stateNN_iterNNN.pdf plot. Gridding with envfsc=yes uses a complete set
of diagnostic binaries (fscu_stateNN.bin, fsct_stateNN.bin,
fscn_stateNN.bin) with matching shell counts to show the corrected,
pre-envelope, envelope-masked and phase-randomized FSCs, identified by a legend.
PCG, envfsc=no, or missing/incompatible diagnostics use the ordinary FSC
curve under the same filename. No separate _phrand plot is written.
On finalization:
enditis written to the command linestartitis removed from the command line- active state volumes and FSCs are registered in
os_out - empty states are removed from
os_outby the shared-memory finalizer; the distributed run leaves the entries of such a state as its iterations registered them. Under per-state M-estimation a state is empty when its weights carry no applied mass cls3Ddistributed runs map class-orientation output back to particlesJOB_FINISHEDis touched by the shared-memory path
The original-sampling final reconstruction is distinct from an ordinary
refinement iteration. On the PCG backend, every calc_final_rec caller
applies the shared minimum five-iteration budget to this cold solve. An explicit
positive residual tolerance may still stop convergence earlier. Final
automatic sharpening follows the isotropic postprocess protocol
(2026-09-21, the postprocess_nu v2 recipe with one cutoff): the cutoff is
the FSC=0.143 of the reconstruction's FSC file (the base pair's curve,
envfsc-corrected where that applies), or of the _even_unfil/_odd_unfil
pair beside the map computed by postprocess when no file is given, one
Guinier B-factor of the density-windowed unfiltered pair average
(windowing restored 2026-10-16; see the PCG policy's final-sharpening
section for why a support-wide fit under-estimates |B|) between HPLIM_GUINIER
(10 A since 2026-09-26, RELION's --autob_lowres default and Rosenthal &
Henderson's lower limit; 20 A before, which put the steep envelope/micelle
region into the fit) and that cutoff (never of the shipped regularized
map: its prior's amplitude suppression steepens the slope, -150 on
streptavidin against -77 to -83 from unregularized maps), sharpen, the
FSC weighting exactly once, then the Butterworth low-pass at the cutoff.
The terminal summary reports the actual B-factor in A^2 (including zero),
whether FSC weighting is applied or already carried by the prior, and the
Butterworth cutoff. The FSC-source line retains 0.5/0.143 at <res05>/<res143> A.
Exactly once (2026-09-26): an ML-regularized map (support-provenance
solve_kind=regularized, or gridding_regularized from a gridding
reconstruction with ml_reg=yes) already carries it -- its prior shrank
every Fourier component by rho/(rho + <rho>/(tau SSNR_half)), about FSC
per shell -- and is only B-sharpened and Butterworth-filtered; every
other map (the imgkind=unfil|solvent pair averages, base or mixed PCG
solves, unregularized gridding maps, foreign maps) gets RELION's
weighting sqrt(2FSC/(1+FSC)) (Rosenthal & Henderson's C_ref,
postprocessing.cpp applyFscWeighting, zero from the first shell with
FSC < 1e-4). The 2026-09-22 recipe applied the Wiener 2FSC/(1+FSC) on
top of the regularized map's own shrinkage, leaving 0.036 of the
amplitude at FSC=0.143 (0.33 at 0.5): every map over-smoothed. Its
trigger -- exp_gate a cloud of structured noise under the Butterworth
alone at an automatic B of -108 while -50 looked right -- was a defect in
the closing filter (2026-09-27): the Butterworth array was sized to the
box, so apply_filter reached the corners of the Fourier cube (out to
sqrt(3) x Nyquist), where apply_bfac's exp(-B s^2/4) is largest, with
only the Butterworth's k^-8 tail against it. At exp_gate's 0.822 A/pixel
the corner gain is ~1e8 at B -108, ~1e5 at -80, ~4e2 at -60 (msp1 at
1.073 A: ~4e4 at -115); the noise sits outside the molecule because
there is no density there to hide it. Any filter sized to the FSC zeroes
the corners, which is why the FSC weighting and the NU sharpening never
showed it. The Butterworth now covers the Fourier shells up to Nyquist
only, and the sharpening is capped at the cutoff shell (2026-09-28): every
shell beyond the cutoff keeps the cutoff's gain exp(-B s_c^2/4) and the
Butterworth alone rolls it off (bfac_cap_filter), since there is no
signal beyond the cutoff to restore and at fine pixels exp(-B s^2/4)
otherwise outgrows the order-8 Butterworth from ~1.5 x the cutoff on
(exp_gate's Nyquist shell: x45 at B -108 uncapped). RELION differs in two
places kept on purpose: it fits B on the FSC-weighted map out to where
the FSC reaches zero (steeper) and applies no low-pass by default; SIMPLE
fits the unweighted unfiltered pair up to the FSC=0.143 cutoff (a
conservative B) and closes with the Butterworth there. No
density-windowed pair estimate. imgkind=unfil postprocesses the base pair
average with the same cutoff.
The transaction files of the sigma2 store (the candidate and the workers' range
files) are run-local. They are written and consumed inside a running
refinement and are not registered as os_out handoff artifacts; only the
committed store is registered, in projinfo.
12. Refactor Rules¶
- Preserve the particle-domain versus volume-domain boundary.
- Keep shared-memory and distributed workflows behaviorally aligned.
- Keep volume assembly as the owner of assembled-reference work.
- Do not move assembled-volume postprocessing into
refine3D_strategy. - Do not merge probabilistic particle-update logic with volume postprocessing.
- Do not introduce a second ambiguous source of matching references.
- Preserve the single image-stack read per matcher batch.
- Treat the parts' readout records, partition-local partials, state volumes, even/odd volumes, FSC files, automasks, and NU outputs as explicit workflow contracts.
- Preserve the two-mode in-plane boundary: only
new_alternatingmay attach the callback, and noinpl_cont=yespath may invoke it. - Initialize candidate-profiling joint solves with one callback-equivalent all-angle selection at the supplied shift; do not run the 5-by-5 coarse shift initializer.
- Treat the final 3D hard assignment as authoritative: refine locally around its rounded in-plane cell and never perform a second global angle selection.
- Keep probabilistic in-plane artifacts rounded and run durable fractional refinement only after final hard assignment.
- Keep
inpl_continternal: no UI input, no command-line key,noonly underrefine=cont. - Keep state weights out of alignment and sampling: they enter only reconstruction, its mass bookkeeping and its population gates, and no refinement step recomputes or changes them.