model_cavgs_rejection¶
Scope¶
model_cavgs_rejection is the SIMPLE class-average rejection-model program. It evaluates cls2D class averages, applies hard validity rejects, extracts a fixed scalar feature bank, normalizes those features within the dataset, and applies a named model to partition class averages into accepted and rejected sets. The model can also abstain from additional soft rejection and report that the final decision was hard preselection only.
This is a learned feature-vector model. It replaced the streaming microchunk rejector, a cumulative rule engine that has been retired. The two shared several image-processing primitives but used them differently: microchunking applied fixed sequential criteria and rejected a class as soon as any criterion fired; model_cavgs_rejection uses hard rejects only for validity failures, then scores the remaining class averages with a learned probability model.
The implementation lives in src/main/cavg_quality. The command entry point is exec_model_cavgs_rejection in src/main/commanders/simple/simple_commanders_cavgs.f90.
Implementation Files¶
simple_cavg_quality_types.f90: shared constants and derived types.simple_cavg_quality_feats.f90: feature definitions, feature extraction, hard rejects, and robust normalization.simple_cavg_quality_stats.f90: binary metrics, AUC, and statistical helpers.simple_cavg_quality_model.f90: built-in presets, model file I/O, pairwise-logistic scoring, and promotion snippets.simple_cavg_quality_analysis.f90: evaluation, analysis reports, and feature tables.simple_cavg_quality_learn.f90: analysis-table reader, feature-policy search, model search, and learn reports.simple_cavg_quality_lattice.f90: the lattice bank of thenanocontext and its lattice gradesLAT_PEAK_MIN(denoised class averages) andLAT_PEAK_MIN_RAW(raw ones), and the model gate oftrajectory_solve3Dwith its constantK_MODEL(see The nano Context).
Comparison with the Retired Microchunk Rejector¶
The sieve and stream paths call this backend directly, not through the program (the callers are listed under Hard-Reject Comparison). The rule engine it replaced (the microchunk rejector and its caller, both removed) was deterministic and rule based. The comparison below is kept because its thresholds explain several of the hard gates the model retains.
| Aspect | Retired microchunk rejection | model_cavgs_rejection |
|---|---|---|
| Decision type | Cumulative rule engine. | Learned feature-vector model with hard validity gates. |
| Primary owner | The microchunk rejector and its caller (both removed). | src/main/cavg_quality, called by model_cavgs_rejection, particle sieving and the stream. |
| Unit of evidence | Individual scalar rules applied one after another. | Normalized feature vector scored by the pairwise-logistic model and its probability threshold. |
| Rejection semantics | A class rejected by any rule remains rejected. | Hard rejects are final; remaining classes are scored and partitioned by the model. |
| Threshold source | Fixed constants, with tier-specific population and local-variance overrides. | Built-in or learned model specification; learn mode chooses feature policy, weights, and threshold controls from analysis datasets. |
| Adaptation to dataset | Robust local-variance z-scores are dataset-relative, but thresholds are fixed. | Robust feature normalization is dataset-relative; the learned coefficients and probability threshold are fixed per model. |
| Training data | None. | Manual selections from quality_mode=analyze files. |
| Output role | Online stream cleanup and particle deselection. | Batch/chunk/pool class-average selection, analysis, training, and model promotion. |
Evidence Comparison¶
The model feature bank keeps the microchunk-style image-processing evidence, optional stored-score and signal evidence, and the local-variance/support evidence needed to detect fuzzy-ball overfitting in learned models. The overfit local-variance features are part of the learned model feature vector and are included in every learn-mode feature policy. Texture descriptors were removed after they failed to justify the extra feature and extraction complexity. The current chunk100mics preset uses the microchunk_plus_score_signal policy: microchunk plus stored-score, overfit-family, center/edge signal, presence, and fuzzy-ball signal evidence.
| Evidence | Retired microchunk rule engine | model_cavgs_rejection feature-vector model |
Current chunk role |
|---|---|---|---|
| Class population | Hard rule: reject below a tier-specific fraction of total population. | log_pop feature plus context-specific population hard gates. |
Active feature and hard gate. |
| Resolution | Hard rule: reject when res > 40.0. |
neg_log_res feature plus hard reject when res > 40.0. |
Active feature and hard gate. |
| Foreground centering | Otsu foreground connected components; reject if any centroid lies outside the mask radius. | centered feature is negative normalized centroid displacement; centroid outside the mask is a hard reject. |
Active feature and hard gate. |
| Foreground outside mask | Reject when the largest valid foreground component has more than 10 pixels outside the mask disc. | cc_area_frac measures largest component area relative to the mask disc; outside-mask excess is a hard reject. |
Active feature and hard gate. |
| Full-image component cleanup | Connected components spanning the full image are removed before mask tests. | Same concept is applied during feature extraction before geometry features and hard mask rejection. | Hard-gate preprocessing. |
| Foreground local variance | Robust-z rule on foreground/background local variance after 10 A low-pass and Otsu masking. | log_locvar_fg feature; a hard reject only when both variances are at most EPS (1e-6). |
Active feature. |
| Background local variance | Robust-z rule paired with foreground local variance. | log_locvar_bg feature; a hard reject only when both variances are at most EPS (1e-6). |
Active feature. |
| Stored score evidence | Not used by the rule engine. | corr_frc_proxy reads stored class correlation or FRC-like score when present. |
Inactive in the current chunk preset. |
| Center/edge signal | Not used by the rule engine. | log_center_edge_snr feature in the signal family. |
Active feature. |
| Presence | Not used by the rule engine. | presence feature in the signal family. |
Active feature. |
| Overfit local variance | Not used by the rule engine. | neg_log_locvar_fg, neg_log_locvar_bg, and log_locvar_fg_bg_ratio provide low/localized variance evidence. |
Active features in learned policies. |
| Overfit band-pass localization | Not used by the rule engine. | log_bp40_100_center_edge_var measures center/edge variance after 100 to 40 A band-pass; low raw values can be context-specific hard gates, while ordinary low values remain learned evidence. |
Active feature in learned policies plus context-specific hard floors. |
| Fuzzy-ball signal | Not used by the rule engine. | fuzzy_ball_signal combines foreground texture, central presence, and 100 to 40 A center/edge localization. Low values mark the fuzzy-ball pattern as continuous learned evidence, not as an apply-time hard gate. |
Active feature in learned policies. |
| Invalid pixels | Not a named microchunk rule. | Image values containing invalid pixels are hard rejected. | Hard gate. |
Hard-Reject Comparison¶
Hard rejects in model_cavgs_rejection are selected by the chunk, pool, sieve, or nano context (the nano gates are
described under The nano Context). Analyze mode requires an explicit quality_context; learned model artifacts store the consistent context inferred from their input tables, and application reads the context from the selected artifact.
The callers, with the preset and the context each applies:
| Caller | Preset | Context | Use |
|---|---|---|---|
model_cavgs_rejection program |
chunk100mics, or quality_model / infile |
the model artifact's | selection, annotation, analysis, learning, evaluation |
particle sieve (simple_ptcl_sieve): both tiers in stream p05, the coarse tier in p03 |
sieve |
sieve |
rejection of class averages with their particles; with use_model=no the sieve hard gates only |
stream initial analysis (p03, simple_stream_stage_initial_analysis) |
chunk100mics |
chunk |
class selection of both cycles |
multistate stream stage (p07), through score_cavgs_with_model (simple_state_assignment) |
pool |
pool |
the class selection of the route to the reference volumes (applied); each assignment's class averages are scored beside the fit's rejection, logged and not applied |
Every caller but the program scores through score_project_cavgs (simple_cavg_quality_selection),
which takes the class averages' pixel size so that the relational feature's mask radius is right.
Particle sieving applies the sieve preset and context in both its tiers: its fine tier merges
coarse-cleaned particles into chunks of 10,000 particles or more, but it is the sieve's second
pass, so it keeps the sieve's scoring (ptcl_sieve_policy.md §8). The chunk preset and context
belong to stream initial analysis and are the model_cavgs_rejection command's default.
Chunk and pool share non-negotiable validity gates. Chunk adds early-streaming cleanup gates for undersupported and fuzzy-ball-like class averages. Pool adds its own final pre-3D cleanup gates for low population, low band-pass localization, and poor nominal resolution. Sieve has its own pre-model gate policy and deliberately does not inherit the shared chunk/pool validity gates.
| Criterion | Retired microchunk rule engine | model_cavgs_rejection |
|---|---|---|
| Population | Rejects pop < ceiling(sum(pop) * fraction). Fractions are tier-specific. |
Shared: reject pop <= 0. Chunk/sieve: reject pop < ceiling(sum(pop) * 0.0035). Pool: reject pop < ceiling(sum(pop) * 5.0e-4). |
| Resolution | Rejects res > 40.0. |
Chunk/pool shared validity rejects res > 40.0; pool additionally rejects res > 25.0. |
| Empty or mismatched class-average stack | Stream chunk is marked REJECTION_FAILED and COMPLETE. |
Apply/analyze require a valid project, cls2D entries, matching class-average stack, and mskdiam; invalid inputs stop the command. |
| Invalid pixels | No separate named rule. | Hard rejected. |
| No valid foreground component | Rejected after full-image connected components are pruned. | Hard rejected after the same style of foreground-component pruning. |
| Foreground centroid outside mask | Rejected. | Hard rejected. |
| Largest foreground component outside mask | Rejected when outside pixels exceed 10. | Hard rejected when outside pixels exceed 10. |
| Local variance exactly degenerate | Rejected when both inside/outside scores are near zero. | Chunk/pool hard reject when both foreground/background local variances are at most EPS (1e-6). |
| Local variance low but not degenerate | Rejected by fixed robust-z thresholds. | Chunk only: reject an extreme absolute foreground local-variance floor; otherwise encoded as learned evidence. Pool does not apply this extra gate. |
| Band-pass center/edge variance extremely low | Not used by the rule engine. | Chunk hard rejects when raw bp_center_edge_var < 1.5; pool hard rejects when raw bp_center_edge_var < 10.0; sieve leaves this value as learned evidence. |
Retired microchunk tier thresholds:
| Tier | Population fraction | Local-variance strong threshold | Local-variance weak threshold |
|---|---|---|---|
| Pass 1 | 0.0050 |
-0.5 |
-0.1 |
| Pass 2 | 0.0035 |
-1.0 |
-1.0 |
| Reference chunk | 0.0025 |
-2.0 |
-2.0 |
| Match chunk | 0.0025 |
-2.0 |
-2.0 |
model_cavgs_rejection uses context-specific population hard-reject fractions: 0.0035 for chunk/sieve and 5.0e-4 for pool.
Learning Model¶
The rejection model is a low-dimensional, monotone feature-vector classifier with explicit hard constraints. In learning-theory terms, the hard rejects are prior validity constraints: they remove classes the model is not asked to rescue or fit. The remaining rows form a supervised training set from manual selections.
Linear score-and-cluster artifacts (a linear quality score whose per-dataset
boundary came from k-medoids clustering and Otsu thresholding) are not
supported: read_model accepts only model_version=11 pairwise-logistic files,
and the clustering apply path was removed for release 4.
Training fits a relational pairwise-logistic artifact. Its fitted parameters are an intercept, linear feature coefficients, pairwise base-feature interaction coefficients, the required relational coefficient, a probability threshold, and a regularization strength. The coefficients are fit from the canonical training files only. On two-class trainable datasets, the logistic loss gives manually selected classes moderately higher total weight than manually deselected classes so the probability surface learns rejection evidence without becoming an overly aggressive rejector. Manually deselected examples with the overfit/support-poor or band-pass-localization signature get an additional training-time loss multiplier, so fuzzy-ball examples influence the fit without becoming an apply-time hard reject. Learn reports also expose an internal overfit-focus loss scale for experiments; it is currently neutral.
All features are robustly normalized inside the current dataset. Relational logistic artifacts apply their learned probability surface and fixed probability threshold.
The learning objective is empirical risk minimization over manually annotated quality_mode=analyze runs. Feature-weight candidates are learned only from datasets where both manual states remain present after hard rejects, because those are the datasets with a learnable soft boundary. Candidate models are scored over all scoreable datasets using only non-hard-rejected rows. Two-class trainable datasets contribute specificity with a small false-negative-rate tolerance over the trainable manually good rows. Datasets where at least 20% of the trainable class averages are manually bad rows matching the fuzzy-ball signature get an additional hinge/quadratic objective penalty when the accepted fuzzy-ball-signature rate is above the tolerated rate. The signature is poor support plus either low local-variance evidence or low 100 to 40 A band-pass center/edge localization. This keeps selected-class protection global while making the objective care specifically about fuzzy-ball leakage in small-specimen chunks. The final macro score is a fixed robust score: half the mean dataset score and half the mean score over the lower tail of datasets. During pairwise-logistic fitting, manually bad rows with the same fuzzy-ball signature get extra loss weight. Datasets where only manually good rows remain after hard rejects contribute recall, so they teach the model not to reject good classes that passed the hard gates. Datasets where only manually bad rows remain contribute specificity only when no manually good classes were removed by hard rejects. If manually good classes were entirely removed by hard rejects, the dataset is reported as hard-gate blocked and skipped for soft-model scoring. Hard-rejected rows remain visible in diagnostics, including counts of manually good classes lost to hard gates, but they do not participate in fitting the learned boundary.
Feature-family policies act as a small structural model-selection layer. The relational logistic learner fits coefficients independently for each policy and selects the feature policy, regularization lambda, and probability threshold from the supplied training data.
Use filetab= to define the target workflow scenario being trained. For example, early streaming chunk models should be fit from chunk analyses, while late pooled-refinement models should be fit from pool analyses. To inspect cross-scenario behavior without influencing the model, train the target model and then run quality_mode=evaluate filetab=... infile=... on the other scenario.
| Policy | Active families | Purpose |
|---|---|---|
microchunk |
microchunk, overfit |
Tests whether scalar analogues of the stream rejector plus overfit local-variance evidence are sufficient. |
microchunk_plus_score |
microchunk, overfit, score |
Adds stored class correlation/FRC-like evidence. |
microchunk_plus_signal |
microchunk, overfit, signal |
Adds center/edge and presence evidence without stored score evidence. |
microchunk_plus_score_signal |
microchunk, overfit, score, signal |
Uses the full compact quality feature set. |
Learn mode reports feature signal, feature-drop diagnostics, and leave-one-dataset-out feature-policy diagnostics so that the selected model can be interpreted as a compact scientific statement about which evidence family and weight structure generalized on the supplied training set.
Command Modes¶
quality_mode=apply computes quality features, applies the selected model, writes cavgs_quality_features.txt, writes quality_selected_cavgs.mrc, quality_rejected_cavgs.mrc, hard_gate_rejections.mrc, quality_ranked_cavgs.mrc, and quality_ranked_cavgs.txt, maps the selected class averages into particle states, annotates cls2D with quality, quality_cluster, and accept, annotates cls3D when its class count matches cls2D, optionally prunes particles with prune=yes, and writes the project.
quality_mode=analyze requires quality_context, applies that context's hard gates, computes model output, and treats the existing cls2D state as the manual reference. It writes the single canonical learner input cavgs_quality_training.txt, including the gate context that produced its hard-reject mask, plus the selected/rejected stacks, hard_gate_rejections.mrc, and the score-ranked class-average stack and rank table. The project selection is left unchanged.
quality_mode=learn reads a training file table of cavgs_quality_training.txt files from filetab= and fits the relational logistic model from the neutral neutral_learn_base foundation. Every input must declare cavg_quality_training_version=1 and relational_feature_schema=corr_knn_signal_v1, contain the normalized CC-neighbour signal-statistics feature and every z_* feature column (including the overfit family), and record the same chunk, pool, or sieve context in quality_context. A missing training version or feature column, missing or mixed relational schemas, missing or mixed contexts, and a combined input set in which the hard gates rejected every class average are fatal before fitting. The shared input-table context becomes the learned version-11 model context. Learn mode does not accept quality_context, quality_model, or infile. It writes a learned model file controlled by fname= and writes cavgs_quality_learn_report.txt.
quality_mode=evaluate applies the selected fixed model without refitting. With filetab=, it evaluates one or more saved cavgs_quality_training.txt files and preserves the model artifact context because the saved hard gates are not recomputed. Without filetab=, it evaluates a single project directly using the existing cls2D state as the manual reference, like analyze mode. It writes cavgs_quality_evaluate_report.txt, or the report path controlled by fname=.
quality_mode=promote reads a model file from infile=, preserves its context, and writes a Fortran promotion snippet controlled by fname=.
score_states=yes is a default-off diagnostic path for project-backed runs. It requires the default
quality_mode=apply, projfile, mskdiam, matching cls2D and cls3D class counts, and a nonnegative
state assignment on every cls3D row with at least one positive state ID. It evaluates every built-in
quality model in the model's own hard-gate context and groups the surviving model scores by cls3D
state ID from zero through the maximum assigned state. The command writes
cavgs_quality_state_scores.txt with the total, scored, and hard-rejected class counts plus mean,
median, sample standard deviation, minimum, and maximum score for each model/state pair. Empty state
groups and groups for which no class average passes the model's hard gates are retained in the report
with NA score statistics. This path does not write class-average stacks, map selections into particles,
annotate or write the project, or prune particles. It rejects model overrides because its purpose is to
compare all built-in models on the same state assignment.
apply and analyze require projfile and mskdiam. learn requires filetab. evaluate requires either filetab or projfile plus mskdiam. promote requires infile. The commander sets oritype=cls2D, defaults mkdir=yes, and defaults prune=no.
For apply, analyze, and project-backed evaluate, the command uses chunk100mics unless quality_model or infile is supplied. infile is the external model input; fname is output-only and is rejected in apply or analyze mode. Apply and evaluate do not accept quality_context: the complete internal or external model artifact supplies its context, that context selects the hard gates, and surviving rows are scored by the same model. Analyze is the only mode that accepts an explicit context because it owns generation of a context-tagged training table. Runtime output reports the model name, built-in or external source, model context, effective hard-gate context, and context source. Saved-analysis evaluate filetab=... runs do not write image stacks because they do not load a project or class-average stack; they reuse the saved gate masks while preserving the evaluated model's artifact context.
Model Selection¶
quality_model selects a built-in preset outside learn mode. The promoted built-ins are:
chunk100mics: default chunk/stream-style version-11 pairwise logistic model trained from/Users/elmlundho/model_cavgs_rejection/chunk_training5; it includescorr_knn_signal_v1relational evidence.sieve: version-11 pairwise logistic model for small-chunk sieve class averages.pool: version-11 pairwise logistic model trained from/Users/elmlundho/model_cavgs_rejection/pool_training4for pooled class averages before 3D refinement.nano: the lattice gate for nanoparticle time series (contextnano, a threshold on the rawlattice_peak, no relational term); see the nano section below.
When infile is supplied, the model file is treated as a complete model and wins over the built-in preset.
Relational logistic model files use model_version=11 and explicit key-value fields:
namecontextfeature_policyfeature_weightsinterceptlinear_coefficientsinteraction_termsinteraction_coefficientsprob_thresholdregularization_lambdacalibration_temperaturerelational_feature_schemarelational_knnrelational_corr_hprelational_corr_lprelational_corr_trsrelational_coefficient
A model file may also name a built-in preset; its values are loaded first and the explicit keys override them. Files with any other model_version are refused, and unknown model-file keys are rejected. Version 11 dropped the unused cluster-threshold fields of version 10 (boundary_margin, min_score_separation, the Otsu offsets and switches, cluster rescue and the minimum-accept fraction).
Feature Bank¶
The feature bank is a property of the context. The chunk, pool and sieve contexts share the fourteen features
below; CAVG_QUALITY_NFEATS (14) is the largest bank, and every bank array is indexed by position in the
context's own list (cavg_quality_bank_size(context)). The nano context's six features are listed under The nano
Context. All features below are higher_is_better. The model consumes normalized z_* values; raw values are written for diagnostics.
| Index | Feature | Family | Source | Meaning |
|---|---|---|---|---|
| 1 | log_pop |
microchunk |
cls2D pop |
Log class population. |
| 2 | neg_log_res |
microchunk |
cls2D res |
Negative log class resolution estimate. |
| 3 | centered |
microchunk |
Otsu foreground connected components | Negative normalized centroid displacement of segmented signal. |
| 4 | log_locvar_fg |
microchunk |
Foreground-mask local variance | Log local variance in the foreground Otsu mask. |
| 5 | log_locvar_bg |
microchunk |
Background-mask local variance | Log local variance outside the foreground Otsu mask. |
| 6 | corr_frc_proxy |
score |
cls2D corr when present |
Stored class correlation or FRC-like quality proxy. |
| 7 | log_center_edge_snr |
signal |
Center/edge variance statistics | Log central variance relative to edge variance. |
| 8 | cc_area_frac |
microchunk |
Foreground connected-component area | Largest foreground component area divided by expected mask area. |
| 9 | presence |
signal |
Center/border statistics | Central signal excess relative to border background noise. |
| 10 | neg_log_locvar_fg |
overfit |
Foreground-mask local variance | Negative log local variance in the foreground Otsu mask; higher values indicate lower foreground variation. |
| 11 | neg_log_locvar_bg |
overfit |
Background-mask local variance | Negative log local variance outside the foreground Otsu mask; higher values indicate quieter background. |
| 12 | log_locvar_fg_bg_ratio |
overfit |
Foreground/background local variance | Log foreground/background local variance ratio; higher values indicate support-localized detail. |
| 13 | log_bp40_100_center_edge_var |
overfit |
Band-pass center/edge variance | Log center/edge variance ratio after 100 to 40 A band-pass; low raw values flag overfit fuzzy balls. |
| 14 | fuzzy_ball_signal |
overfit |
Combined overfit evidence | Sum of log_locvar_fg, presence, and log_bp40_100_center_edge_var; low values indicate fuzzy-ball overfit evidence. |
Feature families are used by learn mode. Every learned policy includes microchunk and overfit; the policy variants append optional evidence families:
microchunkmicrochunk_plus_scoremicrochunk_plus_signalmicrochunk_plus_score_signal
Resolution is intentionally not controlled by a separate training switch. If nominal resolution is unreliable for a particular scenario, the regularized linear or pairwise-logistic fit is expected to down-weight it or use it conditionally through interactions with other features.
Features outside the selected policy are encoded by zero weights.
Extraction Constants¶
FOREGROUND_SEG_LP = 30.0SIGNAL_METRIC_LP = 10.0OVERFIT_SIGNAL_BP_HP = 100.0OVERFIT_SIGNAL_BP_LP = 40.0CAVG_RES_HARD_REJECT_A = 40.0POP_FRACTION_HARD_REJECT = 0.0035BP_CENTER_EDGE_VAR_HARD_REJECT_MIN = 1.5CHUNK_LOCVAR_FG_HARD_REJECT_MAX = exp(-4.5)POOL_RES_HARD_REJECT_A = 25.0POOL_POP_FRACTION_HARD_REJECT = 5.0e-4POOL_BP_CENTER_EDGE_VAR_HARD_REJECT_MIN = 10.0LOCVAR_WINDOW = 10MASK_HARD_OUTSIDE_PIXELS = 10LOG_EPS = 1.0e-12EPS = 1.0e-6CLIP_Z = 4.0ANALYSIS_BOXSIZE = 128(the box a class average is resized to for the band-pass center/edge variance)
Hard Rejects¶
Hard rejects are context-sensitive gates. For chunk, pool, and sieve, they run before model fitting, model scoring, and training-score calculation.
A class average is hard rejected in chunk and pool when any shared validity condition holds:
pop <= 0;res > 40.0;- the image contains invalid pixels;
- foreground segmentation has no valid component after full-image connected components are pruned;
- a segmented foreground component centroid lies outside the mask radius;
- the largest foreground component has more than 10 pixels outside the mask disc;
- foreground and background local variance are both at most
EPS(1e-6).
For quality_context=chunk, these additional early-streaming gates also apply:
pop < ceiling(sum(pop) * 0.0035);- raw foreground local variance is below
exp(-4.5); - raw 100 to 40 A band-pass center/edge variance is below
1.5.
For quality_context=pool, the chunk local-variance floor is not applied. Pool instead adds stricter final pre-3D cleanup gates learned from the current pool training set:
res > 25.0;pop < ceiling(sum(pop) * 5.0e-4);- raw 100 to 40 A band-pass center/edge variance is below
10.0.
For quality_context=sieve, the route uses a separate pre-model gate policy. It does not inherit the shared chunk/pool validity gates. The sieve-specific gates are:
pop < ceiling(sum(pop) * 0.0035);- the image contains invalid pixels;
- foreground segmentation has no valid component after full-image connected components are pruned;
- a segmented foreground component centroid lies outside the mask radius;
- the largest foreground component has more than 10 pixels outside the mask disc.
Classes that survive these gates are scored by the selected logistic model.
Hard-rejected classes receive rejected state directly. Their normalized features are set to -CLIP_Z, their model scores are set to -CLIP_Z, and they remain visible in analysis and learning reports.
The band-pass center/edge floor is deliberately conservative. In the v4 chunk training tables, bp_center_edge_var < 1.5 preserved all manually selected classes while still removing additional manually rejected classes beyond population and resolution. More aggressive fuzzy-ball evidence should remain in the normalized feature vector and learned model, not in the default pre-training hard rejects.
Project-backed apply, analyze, and evaluate runs also write hard_gate_rejections.mrc. For every context, this is a bookkeeping stack containing classes removed before the model stage.
Normalization¶
normalize_cavg_quality_features computes per-feature robust statistics over non-hard-rejected rows only. Each feature is centered by the median and scaled by the Gaussian MAD. Values are clipped to [-CLIP_Z, CLIP_Z]. If a feature has no robust spread, its normalized value is set to zero for trainable rows.
Built-In Presets¶
chunk100mics uses feature policy microchunk_plus_score_signal and the relational logistic model. It was trained from /Users/elmlundho/model_cavgs_rejection/chunk_training5.
sieve uses feature policy microchunk_plus_score_signal, a 0.25 acceptance probability threshold, and the corr_knn_signal_v1 relational evidence schema.
pool uses feature policy microchunk_plus_signal, a 0.30 acceptance probability threshold, and the same corr_knn_signal_v1 relational evidence schema. It was trained from /Users/elmlundho/model_cavgs_rejection/pool_training4.
prob_threshold 3.500000E-01
regularization 1.000000E-03
feature_weights uniform over all 14 microchunk_plus_score_signal features
On the refreshed v4 chunk-training table, this promoted preset scored macro_evaluate_score=0.50847, improving over the previous built-in chunk preset (-0.80859). The main gain was selected-class protection: soft-classification totals moved from tp=297, fp=95, tn=151, fn=33 to tp=324, fp=83, tn=163, fn=6.
Classification¶
For each non-hard-rejected class average, the relational logistic model computes:
prob_accept = sigmoid(intercept + sum(linear_coefficients * features)
+ sum(interaction_coefficients * feature_i * feature_j)
+ relational_coefficient * relational_feature)
Every supported artifact declares the relational schema. Non-hard-rejected rows are accepted when prob_accept >= prob_threshold.
Standard hard gates still run before the logistic model.
The classifier reports its soft decision explicitly:
soft_decision=probability_threshold, withsoft_reason=pairwise_logistic_relational(orpairwise_logisticfor a model without relational evidence): the logistic model scored every non-hard-rejected class average againstprob_threshold.soft_decision=hard_only, withsoft_reason=standard_hard_gates_only: only the standard hard gates ran.
threshold and raw_threshold both report prob_threshold; threshold_offset is always zero.
Analysis Output¶
cavgs_quality_training.txt starts with
# cavg_quality_training_version=1. It includes:
- dataset and model identity;
- selected/rejected counts;
soft_decision,soft_reason, and the number of trainable rows rejected by the soft model;- confusion metrics against the manual
cls2Dstate; - relational schema and provider policy when supported by the model;
- model fields as comments;
- feature inventory;
- per-feature AUC, robust separation, current weight, and suggested weight;
- threshold scan;
- one row per class average containing state, hard-reject flag, quality score, manual state, raw/normalized base features, and raw/normalized promoted relational feature.
cavgs_quality_features.txt uses the same per-class row format without the analysis summary comments.
Learning¶
quality_mode=learn reads canonical files generated by the current analyze format. Required columns are:
dataset_idhard_rejectmanual_state- all required
z_*feature columns for the 14-feature bank
Every file must declare relational_feature_schema=corr_knn_signal_v1, contain
z_signal_stats_anchor_topk_mean, and agree on k, high-pass, low-pass, and
shift-range policy. Every file must also record the hard-gate context that
produced its mask, and all files in one learning run must record the same
context. That shared value becomes the learned model context. Analyze
guarantees this metadata even when its scoring model is an older base-only
artifact.
Hard-rejected rows are kept in reports but excluded from feature-weight estimation, candidate scoring, feature-signal diagnostics, feature-drop diagnostics, and feature-policy diagnostics. If every row across the combined input set is hard rejected, learn mode stops before fitting or writing a model.
Learn mode assigns each dataset an automatic role:
balanced: both manual good and manual bad rows remain after hard rejects; used for feature weights and scored by specificity with a small false-negative-rate tolerance.trainable_good_only: only manual good rows remain after hard rejects; not used for feature weights, scored by guarded recall.trainable_bad_only: only manual bad rows remain after hard rejects and no manually good rows were hard rejected; not used for feature weights, scored by specificity.skip_hard_gate_blocked: only manual bad rows remain because all manually good rows were hard rejected; reported but skipped for soft-model fitting and scoring.
Balanced datasets use specificity with a small false-negative-rate tolerance over trainable manually good rows. Overfit-focused datasets also subtract a hinge/quadratic penalty for the accepted manually bad fuzzy-ball-signature rate above the tolerated rate. The final macro score blends the mean dataset score with a fractional lower tail of the dataset scores. This makes threshold selection care about datasets where bad fuzzy-ball classes still leak through, while still penalizing candidates that reject too large a fraction of manually selected classes. Good-only datasets use a recall guard in the learn score. Raw recall is still reported in the dataset table, but the guarded learn score applies an additional shortfall penalty below the good-only recall floor. This prevents a candidate model from improving balanced datasets by rejecting a large fraction of classes from datasets that contain only trainable manual positives.
The learner fits an intercept, selected base-feature coefficients, all pairwise interactions among those selected base features, and one relational coefficient. The relational feature remains a standalone term; it is not expanded into another interaction bank. Learn mode searches:
- feature policies:
microchunk,microchunk_plus_score,microchunk_plus_signal,microchunk_plus_score_signal; - L2 regularization:
0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1; - probability thresholds from
0.02through0.90on the fixed grid reported by the learner.
The fit is ab initio with respect to the rejection model. Chunk, pool, and stage-specific behaviour is represented by the learned artifact context and coefficients, not by separate fitting procedures. A relational pool-context fit therefore produces a version-11 artifact with the same relational schema as the built-in pool preset.
Each candidate is evaluated on every scoreable training dataset using the role-specific learn score. Objective value breaks score ties.
The learn report includes the search grid, macro_learn_score, fitted base and
relational coefficients, dataset-role diagnostics, and per-dataset confusion
metrics.
quality_mode=evaluate uses the same trainable-row scoring semantics as learn mode, but it does not derive weights, search thresholds, or write a model file. This is intended for held-out validation. It can score saved analysis tables through filetab, or a single manually selected project directly through projfile and mskdiam. The evaluate report includes the fixed model settings, macro_evaluate_score, dataset-role diagnostics, and per-dataset confusion metrics.
Promotion¶
quality_mode=promote writes a Fortran snippet for adding a learned model as a built-in preset in simple_cavg_quality_model.f90. The snippet also lists the UI/help files that need the model name added when a new built-in is introduced.
Tests¶
simple_test_exec test=unit_numerics runs the backend's sub-suites "cavg quality relations"
(simple_cavg_quality_relations_tester), "cavg quality selection"
(simple_cavg_quality_selection_tester) and "cavg quality nano" (simple_cavg_quality_lattice_tester: the
lattice family on synthetic class averages, its normalization, the nano gates and preset, the model gate's cut in
closed form, the diameter calibration, the bank by context, model-file and table round trips, team against one-thread identity); one runs alone with
suite=.
The nano Context¶
quality_context=nano selects the class averages of nanoparticle time series (analysis2D_nano), where an
aligned average of about twenty frames shows atomic lattice fringes or does not. At 0.358 A per pixel in a box of
43 to 57 A, the cryo-EM gates reject every class (the 100 to 40 A band is empty, the foreground geometry is
constant), and the population gate rejects the good classes, which are the smaller ones.
Gates: a class is hard rejected when it is empty (pop <= 0), has invalid pixels, has both local variances at or
below EPS, or has no measurable spectrum. Nothing else is gated.
Bank (the order of simple_cavg_quality_lattice). Each class average has its mean removed and is soft-masked at
box/2 - 2. Its power spectrum is smoothed by a periodic 3 by 3 box, and each shell's smoothed power is divided by the
shell mean. The band runs from 3 A to Nyquist, without the graphene shells.
| Index | Feature | Direction | Meaning |
|---|---|---|---|
| 1 | lattice_peak |
higher | log10 of the largest smoothed band power over its ring mean |
| 2 | spot_count |
higher | local maxima of that ratio of lattice grade (at least LAT_PEAK_MIN) |
| 3 | spot_arc |
lower | log10 of the strongest spot's extent across over along its radius |
| 4 | spot_diam |
none | projected-sphere diameter (A) fitted to the strongest spot: the particle size of the class |
| 5 | spot_snr |
higher | log10 of the fitted spot amplitude over its background |
| 6 | band_presence |
higher | log10 of band-passed energy in the central disc over the annulus, unmasked |
Normalization. lattice_peak enters the bank raw: it is a log10 ratio of a peak to its own ring mean, already
normalized, and its threshold is absolute (LAT_PEAK_MIN, 0.65). The other five enter by the median and MAD of
the valid classes, as the cryo-EM bank does, clipped to CLIP_Z; hard-rejected rows sit at -CLIP_Z. The
training table's header records the lattice grade and the median spot_diam of the accepted classes
(lattice_peak_min, spot_diam_median_accepted). The project floor that the autonomous run fitted (a mixture over
the classes' lattice_peak, with a guard) was retired on 2026-10-28: a trajectory with few out-of-focus stretches
has no floor population, and on the labeled data the raw threshold is as good or better than the floor-relative one.
The relational feature uses a nano band (high-pass 15 A, low-pass 1.5 A, shift 3 pixels), because the model schema
requires the term. It carries no evidence on the labeled data. Learn mode has one feature policy, lattice.
apply with a nano model writes diam (the class's spot_diam) on every scored cls2D row. It writes the median
over the accepted classes as diam on the class-average entry of os_out, beside mskdiam.
Preset nano: the lattice gate. A class is accepted when its lattice_peak is at least LAT_PEAK_MIN (0.65: a
strongest smoothed Fourier peak 4.5 times its ring mean); the probability is sigmoid((lattice_peak - 0.65) / 0.1)
at threshold 1/2. thres=<log10 ratio> moves the threshold for one run (set_nano_threshold; it is refused with
any other model). There is no relational term (the only built-in allowed without one; its k-nearest-neighbour
alignment carries no evidence on nanoparticle class averages). The threshold is set for recall, by the
maintainer's ruling of 2026-10-28: for these time series losing useful frames costs more than carrying some junk
into 3D. On three labeled platinum trajectories 0.65 keeps 98 to 99% of the selected classes and lets 27 to 56% of
the rejected ones through; the balanced-accuracy optimum (0.90 to 0.95, 0.92 to 0.98) rejected faint-fringe
classes the maintainer keeps. A learned nano model ranked the classes exactly as lattice_peak alone does
(held-out AUC 0.973 to 0.991) and was not promoted; the gate is the preset. The evidence is in
doc/implementation_notes/completed/nano_cavgs_rejection_report.md.
The rejection of a nanoparticle time series, after analysis2D_nano:
simple_exec prg=model_cavgs_rejection quality_model=nano mskdiam=<particle diameter x 1.5, A> nthr=8 # prune=yes to drop the frames; thres= to move the gate
mskdiam sets the soft mask of the lattice spectrum; mskdiam=0 falls back to the box, which is acceptable for
the lattice features. apply writes the class diameter (diam, from the strongest Bragg spot) on every scored
cls2D row and its median over the accepted classes, beside the mask diameter, on the class-average entry of
os_out, for simulate_nanoparticle and autorefine3D_nano.
The two gates of trajectory_solve3D (raw class averages)¶
single_exec prg=trajectory_solve3D gates before it denoises, because the flex denoiser turns a frame without a
particle, or a latticeless blob, into a pooled particle image (measured twice in ../../implementation_notes/completed/trajectory_solve3D.md, phase 1).
The order is: the raw frames centred (center2D_nano); the diameter estimated on the centred chunk averages; the
start model; refine2D_nano on the raw frames; and then the two gates, coupled on its class averages. A class is
kept only if both keep it. Then the prune; only the kept frames are denoised before 3D.
- The lattice gate is this preset at a second grade,
LAT_PEAK_MIN_RAW = 0.52, which the program passes asthres. Class averages of raw graphene-subtracted frames have lower lattice peaks than denoised ones, and the same rule that set 0.65 (the strictest threshold keeping at least 98% of the maintainer's selected classes on each labelled trajectory) gives 0.52 on the labelled classes rebuilt on the raw frames. That keeps 0.995, 0.995 and 0.985 of the selected classes and removes 0.22, 0.20 and 0.37 of the rejected ones; 0.65 would keep only 0.984, 0.962 and 0.939. The lattice peak still ranks the raw averages (area under the curve 0.990, 0.971, 0.971; pooled 0.978). - The validity gates' flatness is measured on the unfiltered class average. Raw averages hold almost nothing below the cryo-EM low-pass of 10 Å and were hard-rejected there, including classes the maintainer selected.
- The model gate aligns the class averages the lattice gate kept to the start model, the face-centred cubic
particle
simulate_nanoparticlebuilds for the estimated diameter (refine3D_nano oritype=cls3D maxits=1 lp=1.0 trs=10, the passautorefine3D_nanoruns against its final map: a global search over directions, in-plane angles and shifts). The correlation iscorrofcls3D, the best correlation to a reprojection in the band 3 to 1 Å. A class is rejected when it lies belowmedian - K_MODEL x 1.4826 x MADof the lattice gate's survivors (median absolute deviation, MAD). - The rule is
model_gate_states, andK_MODEL = 3, both insimple_cavg_quality_lattice.f90.model_gate_nsd=<robust spreads>moves the cut for one run; the program checks it on its command line, as it checks its other keys (program-specific checks live in the commander, never in the parameter class).K_MODELcomes from ruling 2's rule (the smallest of 1.5, 2, 2.5, 3, 4 keeping at least 98% of the selected classes with the lattice gate in front), which gave 3 on denoised averages behind 0.65 (phase 0). On the raw tables behind 0.52 every value keeps the same recall, so the rule cannot choose. A gate set for recall breaks that tie toward the permissive end, so 3 stays (ruling 9). The strictest value, 1.5, removed two of 13 classes of a clean simulated trajectory, while any K above about 1.9 removes nothing there. - What the model gate does is little, and that is the result. The correlation ranks the lattice gate's survivors well (area under the curve 0.993, 0.966, 0.967 on the raw sets), but at 98% recall a cut relative to the survivors' median and spread has no room. Behind 0.52, at 3, it removes another 0.02, 0.00 and 0.00 of the rejected classes, and on 71-17/traj01 it removed nothing in the denoised-first order. The correlation level to the simulated particle differs between trajectories, so an absolute floor set on one would be wrong on another; a gate relative to the upper mode of the correlations is the form to try next.
- Products: the model-gate stage writes the class table
model_gate_classes.tsv(class, population, lattice peak, lattice-gate state, correlation, best orientation and shift, model-gate state) and class-average/ reprojection pairs of the rejected classes and of twenty kept ones.applywrites the raw lattice peak aslattice_peakon every scoredcls2Drow besidediam. - The workflow test (
single_workflow, suitefcc) runs the program on a simulated trajectory without planted junk and asserts that the gates lose at most 5% of its frames, beside the map's floors and the pose checks.
Example Commands¶
Analyze a manually selected project:
simple_exec prg=model_cavgs_rejection \
quality_mode=analyze \
quality_context=chunk \
projfile=my_project.simple \
mskdiam=180 \
mkdir=yes
Apply the default chunk model:
simple_exec prg=model_cavgs_rejection \
quality_mode=apply \
projfile=my_project.simple \
mskdiam=180 \
mkdir=yes
Train from a file table of canonical outputs:
simple_exec prg=model_cavgs_rejection \
quality_mode=learn \
filetab=cavgs_quality_training_filetab.txt \
fname=cavgs_quality_model_learned.txt \
mkdir=yes
Evaluate a fixed built-in model on independent canonical outputs:
simple_exec prg=model_cavgs_rejection \
quality_mode=evaluate \
quality_model=chunk100mics \
filetab=holdout_training_files.txt \
fname=cavgs_quality_evaluate_report.txt \
mkdir=yes
Evaluate a single manually selected project directly:
simple_exec prg=model_cavgs_rejection \
quality_mode=evaluate \
quality_model=chunk100mics \
projfile=my_project.simple \
mskdiam=180 \
fname=cavgs_quality_evaluate_report.txt \
mkdir=yes
Apply a learned model file:
simple_exec prg=model_cavgs_rejection \
quality_mode=apply \
infile=cavgs_quality_model_learned.txt \
projfile=my_project.simple \
mskdiam=180 \
mkdir=yes
Promote a learned model:
simple_exec prg=model_cavgs_rejection \
quality_mode=promote \
infile=cavgs_quality_model_learned.txt \
fname=cavgs_quality_model_learned_builtin_code.txt \
mkdir=yes