:orphan: .. _ahelp_3dMVPA: ****** 3dMVPA ****** .. contents:: :local: | Usage: 3dMVPA [options] ============================================================ .. code-block:: none Cross-validated classification, continuous decoding, and encoding in ROIs or volume/surface neighborhoods. Preprocessing, intercepts, and model coefficients are fitted separately inside every training fold. Analysis modes and inputs: =========================================================== .. code-block:: none -mode classify Brain response patterns -> categorical labels. -mode decode Brain response patterns -> numeric targets. -mode encode Numeric stimulus/task features -> brain responses. -dataTable @TABLE -dataTableFile TABLE -dataTable Subj Run Condition InputFile ... One row per sample; a table can include many subjects. Subj identifies the subject for each row. Choose CV to match within-subject or held-out-subject prediction. InputFile must select one sub-brick when its dataset has more than one, except with -time_resolved. A subject-level table with Xmat and whole-bucket InputFile columns is expanded to the same sample representation before analysis. -testTable @TABLE Optional independent test table. When supplied, -testTableFile TABLE -dataTable/-dataTableFile contains training rows only. -testTable also accepts an inline table, with InputFile last, just like -dataTable. Both tables must have the same column names (order/case may differ), including test targets for scoring. Both may use Xmat expansion. Dataset paths retain the usual working-directory basis. Explicit sample IDs must be unique across both tables; omitted IDs are generated over the combined rows. The same dataset/brick on both sides is an error (including symlink aliases). Separate files alone do not establish scientific independence. Cannot accompany -trial_manifest, -partition_column, -train_value, -test_value, or outer CV options. All fixed-split tuning/inference restrictions below apply. Prediction audits append Partition, SourceTable, and SourceRow (one-based input data row, before expansion). -show_samples also prints this provenance. Internal MVPA_Partition/MVPA_SourceTable/MVPA_SourceRow columns are reserved in two-table input. -trial_manifest FILE Alternative to -dataTable: one row per trial beta. InputFile names a whole LSS or LSA beta bucket; Volume is its zero-based sub-brick index. Supply trial, run and target metadata explicitly. Optional Xmat and XColumn must occur together; XColumn is the zero-based original design-matrix column. These indices are checked; metadata is retained unchanged. No beta-label matching or Xmat expansion is applied. Cannot accompany -dataTable, -dataTableFile, or -xmat_stims. -time_resolved Classify independently at each latency of whole trial datasets (GIFTI/NIML surfaces or volumes). One table row = one trial, InputFile = whole epoch, no selectors. All trials must share the same spatial domain and time axis. Reuses fixed trial folds and neighborhoods; all learned transforms and tuning refit at each latency. Requires direct tables and -mode classify. No model, coefficient/pattern export or -nperm in this version. Temporal generalization/windows are not performed. With no timing options, process every data column; TimeIndex is zero-based and TimeSeconds is NA. No physical times are inferred from dataset metadata. -time_start SECONDS Together with -time_step, label ALL input columns -time_step SECONDS using start + TimeIndex * step. Start must be finite; step must be finite and positive. Infer the count from the first trial; every other trial must match. Both options require -time_resolved, must be supplied together, and cannot accompany -time_axis. -time_axis SPEC Optional explicit axis: a text FILE with finite, strictly increasing SECONDS, one per line (comments #), or a quoted AFNI inline vector, e.g. '1D: 601%-0.100%0.001' (N%start%step). N is the number of samples: 601 values from -0.100 to +0.500 seconds. Explicit lists such as '1D: -0.1 0 0.075' also work. Inline values use AFNI's float-vector precision. Endpoint-only '..' ranges are not supported. Negative pre-event times and irregular spacing allowed. Count must match every trial's sub-brick count; this explicit shared axis defines event-relative timing. Output: PREFIX is a score bucket, one brick per latency in axis order; PREFIX.temporal.1D contains ROI/center scores, NFeat and NFold with TimeIndex (zero-based) and TimeSeconds. Requested prediction/fold/tuning/selection and PCA audits also prepend these two time columns. No temporal significance or between-latency test is implied by these descriptive held-out score curves. -target_column NAME Categorical classification or numeric decoding target. -target_columns A,B Multiple numeric decoding targets. -design_columns A,B Numeric predictors for encoding neural responses. -score voxel|pattern Encoding output: voxel [default] predicts each masked voxel; pattern averages per-response metrics within each ROI/searchlight, excluding undefined values. -cv_column NAME Leave one level of NAME out at a time. Choose this (or -cv), -partition_column, OR a separate -testTable. -mask DSET Without -searchlight, positive values define ROIs and a binary mask is one ROI. With -searchlight, nonzero voxels define eligible centers and neighborhood voxels. The mask and every sample must share a grid or exact surface node-row domain. A surface searchlight may omit this option to search every represented sample node. Cross-validation: ========================================================== .. code-block:: none -cv run|subject|item Shorthand for -cv_column Run, Subj, or Item. -cv_k K Assign whole -cv_column groups to K balanced folds instead of leave-one-group-out. -within_column NAME Build independent folds inside each NAME level. For within-subject run CV, use Subj here. -partition_column NAME One prespecified train/test split, for all modes. Every row must have exactly one of the two values below; both sets must be nonempty. Values are case- sensitive. Cannot accompany -cv, -cv_column, -cv_k, or -within_column. No automatic subject/run splitting. -train_value LABEL Training value [train]; requires -partition_column. -test_value LABEL Testing value [test]; requires -partition_column. Only training rows fit preprocessing and the model; only test rows contribute to scores. Prediction audits retain training rows with NA predictions/folds. All test classes must be represented in training; class order comes from first appearance in training. Tuned ridge/SVM require -inner_cv_column, with at least two groups among training rows. Inner CV never uses the reserved test rows. Permutation blocks must lie entirely in one partition; use a composite partition/block column if needed. Full-data -save_coefficients is incompatible with a reserved test set. Add -save_model for supported reuse. Cross-condition/task/session transfer: =========================================================== .. code-block:: none -transfer_column NAME Directional source -> destination analysis, for all modes/estimators and ROI/volume/surface analyses. Replaces outer CV/partition options. Every row must belong to one of the two domains; no silent subsetting. -train_domain LABEL Required source-domain value (case-sensitive). -test_domain LABEL Required, distinct destination-domain value. -transfer_subjects within|disjoint Required study design: within: each subject has both domains; fit that subject's source rows and test only their destination rows. Other subjects never enter that fit or tuning. disjoint: one pooled source fit; every destination subject must be absent from source training. -transfer_items disjoint|allow Default disjoint: no shared item identities across domains, including across subjects. Use allow for deliberate transfer on repeated stimuli/items. Item IDs must identify the same stimulus globally; unique row IDs alone cannot establish item novelty. -session_column NAME Session identity column [Session], required for transfer. -transfer_sessions disjoint|allow Default disjoint: no shared (Subj,Session) keys across domains. Use allow for task/condition transfer within the same session. Local session names may repeat across different subjects. Transfer needs explicit subject and item roles (Subj, Item/Trial, or role options) plus session metadata. Sample IDs remain unique. Repeated dataset/ brick selections, including symlink aliases, are rejected even within a domain. Overlap checks use supplied exact identities, not image-content comparisons. One table may contain both domains; alternatively, -dataTable/-testTable must contain only source/destination rows respectively, with the same columns. Classification requires the same complete class-label set in each fit's two domains. Numeric response/design columns retain their shared names and order; values must be finite. Recode labels/align numeric units explicitly beforehand: no automatic category mapping, response matching, registration or alignment. Volume dimensions/view/space and real affine must match (1e-5 tolerance per entry); surface node IDs/order must match. One shared mask defines features. Only source rows fit nuisance adjustment, scaling, selection, PCA and models. Tuning requires -inner_cv_column with multiple source groups per fit. Test rows alone are scored. Permutation blocks must stay within domain AND subject for within-subject transfer; use composite keys such as Subj_Task_Run. Existing null/metric rules apply; transfer scores are not population inference. -save_coefficients is incompatible. -save_model retains #27's ridge/volume limits and requires ONE fit: save subjects separately for within-subject reuse. -apply_model does not repeat these study-design/overlap checks on new samples. PREFIX.transfer.1D records direction, policies, overlap counts, target/class mapping and each sample's domain/role/fold/subject/item/session. Standard prediction/fold audits remain available; training predictions are NA. -validate_only prints the transfer design without fitting or writing files. Sample roles: =========================================================== .. code-block:: none -subject_column NAME Subject role [auto-detect Subj]. -run_column NAME Run role [auto-detect Run]. -item_column NAME Item/trial role [auto-detect Trial or Item]. Item labels may repeat: equal labels mean the same item identity, not a run-local trial counter. Run is not automatically prepended. For distinct trials use run-qualified IDs, e.g. s01_r01_t001, s01_r02_t001. -fold_column NAME Fold role [auto-detect Fold]. -sample_column NAME Unique sample labels [auto-detect Sample; otherwise row000001, ...]. Explicit Sample IDs must be unique across all rows, including both train/test tables. -xmat_stims LIST Comma-separated X-matrix stimuli to expand [all]. Model options: =========================================================== .. code-block:: none -method METHOD Classify: centroid [default], ridge, svm, logistic, lda_diag, lda_shrinkage. Decode: ridge [default], elastic_net, pls, svr. Encode: ridge [default], elastic_net, pls, banded_ridge. See continuous estimator options below. Ridge classification fits one 0/1 response per class with argmax decisions; exact ties choose the first encoded class. Decisions are not probabilities. -logistic_lambda L|auto L2 softmax classification; positive penalty [1]. Binary and multiclass use one joint K-class model: mean natural-log loss + L/2 * sum(weights squared). Intercepts are unpenalized; no class weighting. Every training split must contain every class. Decisions are logits; probabilities sum to one. Exact argmax ties use the first encoded class. -logistic_lambda_grid L1,L2,... Enables grouped nested penalty selection [auto: 0.01,0.1,1,10,100]; cannot accompany numeric L. Default inner objective: log_loss; also accepts brier, ACC and BACC. Exact ties prefer larger lambda. Uses -inner_cv_column/-inner_cv_k; composes with nuisance adjustment, feature selection and PCA. -logistic_tol T Maximum absolute objective gradient [1e-6], range [1e-12,1e-2]. Verified on every fit. -logistic_max_iter N L-BFGS iteration limit [1000]; nonconvergence fails. Scale features for numerical stability. Solver storage is about 152*K*(NFeature+1) bytes per worker, plus data. -save_predictions adds ProbabilityClass0,... in the printed class-label order; training-only rows are NA. -save_fold_scores adds lambda, inner loss, convergence diagnostics, held-out LogLoss and Brier. Main score/permutation maps still use ACC/BACC. Model-file, coefficient and pattern export remain ridge-only. -svm_c C|auto Native linear SVM only: positive cost [1]. Each one-vs-rest model minimizes .5*(||w||^2+b^2) + C*sum(max(0,1-y*(Xw+b))^2). The intercept b IS penalized (constant feature = 1); no class weights. Larger C penalizes margin violations more strongly. Raw class margins are not probabilities; argmax wins, exact ties choose the first encoded class. -svm_c_grid C1,C2,... Positive distinct candidates; enables grouped nested selection [auto default: 0.01,0.1,1,10,100]. Cannot accompany numeric -svm_c. Uses -inner_cv_column and -inner_cv_k; by default minimize 1-ACC/BACC (-metric) over pooled inner held-out rows. Ties choose SMALLER C. Every inner training set needs every class. Scaling, selection and fitting repeat per permutation. PREFIX.tuning.1D records all candidate losses. -svm_tol T Absolute projected-dual-gradient tolerance [1e-6], range [1e-12,1e-2]. Deterministic cyclic coordinate descent verifies final KKT residual for every class. -svm_max_iter N Maximum sweeps per class [10000]. Nonconvergence is an error; increase this limit, rescale, or reduce C. Fold audits append C, InnerNFold, InnerLoss, maximum class SolverIterations and SolverResidual. SVM is classification-only; descriptive coefficient export currently remains ridge-only. -shrinkage A lda_shrinkage only: fixed covariance shrinkage in (0,1] [0.1]. Use (1-A)*S + max(A,F)*T*I, where S is pooled within-class covariance, T its mean variance, and F the relative variance floor. No CV tuning. -variance_floor F LDA only: relative variance floor [1e-6], allowed range [1e-12,1]. lda_diag floors each variance at F*T. If all within-class variances are zero, T uses overall training variance, then 1 for constant data. -class_prior P LDA only: equal [default] or empirical (training class proportions). LDA needs more training rows than classes in every outer fold. Slopes, means, covariances and priors use training rows only. DecisionClass scores are centered linear discriminants, not probabilities; exact ties choose the first class. Fold audits append Shrinkage, CovarianceScale, VarianceFloor (absolute), and CovarianceForm. -lambda L Positive ridge penalty [1]. Slopes are penalized; the training-fitted intercept is unpenalized. Use -lambda auto for nested grouped selection. -lambda_grid L1,L2,... Positive distinct candidates; enables nested tuning [auto default: 0.01,0.1,1,10,100]. Cannot accompany a numeric -lambda. One penalty per outer fold/unit is shared across responses. Default: mean response SSE / training-mean-baseline SSE on inner held-out rows; exclude constant responses. Exact ties or no informative responses select the largest penalty. For classification, responses are class indicators: default tuning uses normalized class-wise squared error. Override with -tune_metric ACC/BACC. Inner training sets contain every class, including under permutations. -lambda_per_response Continuous decode/encode only: select a separate lambda for each response using grouped inner CV. Enables the auto grid unless -lambda_grid is supplied; incompatible with numeric -lambda. Shared lambda remains the default. Each response minimizes its pooled inner -tune_metric loss (default normalized_mse); ties/all-undefined losses choose the largest lambda. Feature/PCA configurations remain shared: their objective is the mean of response- wise minimum losses, excluding undefined normalized-MSE responses. Configuration ties choose smaller requested feature count, then smaller requested PCA count. PREFIX.tuning.1D and optional candidate/count audits gain response-level losses, local lambda selections, configuration losses and final selections. Fold/pattern audits report each response's actual selected lambda. Preprocessing, tuning and fitting repeat under nulls; score aggregation/correction families do not change. Pattern encoding gains independent voxel/node penalties within each joint fit; singleton voxel encoding already tunes one response. Coefficient export remains a separate full-data shared-penalty fit requiring -coef_lambda. Inner candidate fits still share factors across responses; outer fits use up to min(NResponse,NLambda) factors. Extra audit storage grows as outer folds * feature/PCA configurations * lambdas * responses, per worker. -inner_cv_column NAME Inner grouping column [outer -cv_column]. Required explicitly with tuned fixed partitions. -inner_cv_k K Balance whole inner groups into K folds [default: leave one group out]. Every outer training set must contain at least two inner groups (or K if given). Shared by all candidate searches. Preprocessing is refitted within every inner split. PREFIX.tuning.1D records all candidate losses; fold audits append selected penalties and losses. -distance D Centroid only: euclidean [default], correlation, cosine. -tune_metric NAME Inner-CV selection objective, independent of -metric. Requires a lambda/C or feature-count search. default: normalized_mse for ridge (including classify); logistic uses log_loss; others use ACC/BACC from -metric. Classification accepts ACC, BACC, and (ridge only) normalized_mse. Decode/encode accepts normalized_mse, MSE, RMSE, MAE. Logistic also accepts log_loss and brier, pooled over inner held-out rows; see conventions below. ACC/BACC minimize 1-score on pooled inner held-out rows. Continuous errors pool rows within each response, then average responses equally; RMSE takes each response's square root before averaging. These errors retain target units, so differently scaled targets affect selection. normalized_mse divides each response's SSE by SSE of the inner-training-mean baseline, excluding zero-baseline responses. All excluded: NaN loss and deterministic tie fallback. Other losses must be finite; failed fits abort. BACC averages recalls over classes present in pooled inner tests, not equally over folds. Exact ties prefer fewer requested features, then larger lambda/smaller C. Outer scores, permutation tails and feature ranking rules do not change when the tuning objective changes. -save_tuning FILE Optional common candidate audit for any nested search. Includes objective, candidate ID, count, penalty, pooled test size, valid components, loss and selected flag. Existing PREFIX.tuning.1D and feature_tuning.1D remain. -pca_components K Fit centered, unwhitened PCA in every training split. -pca_components_grid K1,K2,... Tune distinct positive component counts jointly with feature counts and lambda/C in inner CV. Order: nuisance -> scale all inputs -> select -> PCA -> estimator. PCA always centers using training means, including with -scale none. In encode mode it projects design predictors, never response voxels. Defaults off. Counts clip to numerical rank and NTrain-1, separately in each split. Rank threshold is 64*DBL_EPSILON* max(NTrain,NFeat)*largest eigenvalue. Rank zero gives one zero model input and reports zero components. Ties: smaller feature count, smaller requested PCA count, then larger lambda / smaller C. Refit PCA in every permutation. PREFIX.pca.1D reports observed fold ranks and sample variances; PREFIX.pca_tuning.1D reports all nested candidates and inner count ranges. -save_pca_loadings FILE Optional observed fold component loadings and means, with original feature IDs. Coordinates are AFTER nuisance/scaling/selection, not raw input weights. Largest absolute loading is positive; tied eigenspaces have no unique basis. Memory scales as folds * input width * maximum retained count, per worker. PCA cannot yet accompany -save_coefficients. Correlation-distance centroid with one retained PC is degenerate; Euclidean is the default distance. -select_features K Retain the top K predictors per training split. -select_features_grid K1,K2,... Tune distinct positive counts in grouped inner CV, jointly with lambda/C when tuned. These options are mutually exclusive; default is all features. Counts are capped at each unit's available width. Every training split needs at least two samples. Classification: rank between-class / total variance (eta squared). Decode/encode: mean squared Pearson correlation over nonconstant response columns. Constant features score zero; exact ties use the lower original input-column index. Zero-score features can fill the requested count; scores are not significance. Order: nuisance OLS, scaling of ALL original columns, supervised selection, optional PCA, model fit. sample_center acts before selection and PCA. Selection is refitted in every inner/outer split and permutation. Never select once before cross-validation. Default: ridge tunes normalized squared loss; logistic tunes log_loss; other classifiers use 1-ACC/BACC from -metric. -tune_metric overrides the objective. Ties prefer smaller counts, then smaller PCA counts (if enabled), then largest lambda / smallest C. With constant ridge responses, normalized_mse uses that rule (loss is NaN). Encoding selects design columns, shared across the current unit's responses; it does not select output voxels. Writes PREFIX.features.1D with observed outer-fold original voxel/node IDs or design names, ranks, scores, requested/effective counts. With inner CV, also writes PREFIX.feature_tuning.1D with all count/penalty losses. With PCA these losses condition on its selected count. Existing penalty audits condition on both counts. NFeat in existing maps/tables remains the input width. Fixed partitions need explicit -inner_cv_column for a count grid. Incompatible with -save_coefficients. -nuisance_columns C1,C2,... Numeric covariates for predictor-side OLS. Fits intercept and slopes using training rows only, subtracts their prediction, then applies -scale. Repeats inside every inner/outer split and null fit. Adjusts neural predictors in classify/decode; design predictors in encode. Targets and scores retain their original units; this is not target residualization, incremental R2, or a causal/conditional effect test. Covariates must be known for training AND test rows. Supply numeric dummy columns for factors, omit one level and do not add an intercept column. Each training design must have full rank and ntrain > ncovariates+1. Cannot reuse target/design columns as nuisances. With -nperm, all covariate values must be identical within each -permute_within block. Exchangeability within those blocks remains the user's assumption. General residual permutations are not implemented. -save_coefficients is unavailable with this option because that export lacks nuisance-fit parameters. -scale S feature_zscore [default], sample_center, run_center, or none. All learned values are training-fold only. run_center requires a run role and cannot be applied to a run absent from that fold's training data. -metric M balanced_accuracy [default] or accuracy. This selects the SCORE map; the ROI table reports both. Continuous modes default to cross_validated_r2 and also accept pearson, spearman, MAE, RMSE. R2 uses each fold's training response mean as its baseline. All five metrics are saved per target; encoding pattern summaries weight responses equally. Undefined scores are NaN in tables and zero in maps; NVALID reports the primary metric's defined response count. Continuous estimator options: =========================================================== .. code-block:: none -method elastic_net Independent response fits for decoding/encoding. -enet_alpha A Positive penalty strength [1]. -enet_alpha_grid A,... Nested candidates (at least two distinct values). -enet_l1_ratio R L1 fraction in [0,1] [0.5]; 0=ridge, 1=lasso. -enet_l1_ratio_grid R,... Nested mixing-ratio candidates. Objective per response: SSE/(2*NTrain) + A*R*L1 + A*(1-R)*L2/2; intercept unpenalized. No target scaling. Alpha differs from ridge's unnormalized lambda: at R=0, equivalent ridge lambda=NTrain*A. Grids form the Cartesian product in supplied order, alpha first, mixing ratio second. No multitask penalty. Original-feature sparsity requires no PCA. Nuisance adjustment/scaling/feature selection remain fold-local. Sparse weights are predictive selections, not voxel activations, significance, or stable causal effects. -method banded_ridge Encoding only; shared group-penalty vector over responses. -feature_groups FILE Two-column table with exact header: Group Column One row per -design_columns entry, in that order. Every design column belongs to exactly one named group. These are predictor groups, not sample/CV groups. -banded_penalties FILE Table header lists group names in first-appearance order. Each row is one positive penalty vector. One row fixes penalties; multiple rows enable nested selection. Duplicate vectors/incorrect group order fail. Objective: SSE + sum_g lambda_g*||beta_g||^2; intercept unpenalized; no group-size normalization. -scale applies within training folds before penalties; default z-scoring is per column, not per group. Selection/PCA are excluded to preserve group identity. Group score variance/covariance audits are descriptive: correlated groups do not have unique causal contributions. -method pls Supervised NIPALS PLS1/PLS2 regression (decode/encode). -pls_components K Requested components [2]. -pls_components_grid K,... Nested component-count candidates. Training-center X/Y after predictor preprocessing; responses are NOT scaled. Use regression deflation of both X and Y by each X score, unit X weights. Initial score is the largest-variance residual Y column; exact ties use its original column order. Counts clip to min(NTrain-1,NFeat) and exhausted rank/ covariance; constants give a mean-only fit. NIPALS weight-iterate change must converge, or the fit fails. Multiple responses are joint within one fit unit: decoding targets, or the ROI/searchlight neural pattern. Voxel/node encoding instead fits each response alone; these response domains need not give the same prediction. Nested losses average response-wise losses equally; component fitting itself uses unscaled response covariance. -method svr Linear squared epsilon-insensitive SVR, decoding only. -svr_c C Positive loss weight [1]. -svr_c_grid C,... Nested C candidates. -svr_epsilon E Nonnegative tolerance in original target units [0.1]. -svr_epsilon_grid E,... Nested epsilon candidates; Cartesian C/epsilon grid. Objective per response: (||beta||^2+intercept^2)/2 + C*sum(max(0,abs(y-prediction)-E)^2). Intercept IS penalized (constant feature=1); loss is not divided by N. No target centering/scaling; separate response fits. Deterministic signed dual coordinate descent verifies the maximum absolute dual KKT residual. This differs from classification SVM and nonsquared epsilon loss. Voxelwise encoding is not exposed pending cost assessment. -reg_tol T Solver tolerance [1e-7], range 1e-12 through 1e-2. -reg_max_iter N Iteration limit [10000]. Failure to converge is an error. Elastic net checks max absolute KKT; SVR checks dual KKT; PLS checks weight-vector change. Banded ridge uses a direct solve and reports normal-equation residual. These residuals have different meanings/units. For these four estimators, parameters are selected jointly inside grouped inner CV using -inner_cv_column/-inner_cv_k and -tune_metric. The default is normalized MSE; MSE, RMSE and MAE are supported. Exact ties prefer smaller requested feature/PCA counts, then FIRST candidate in supplied order (also when all normalized losses are undefined). A fixed split with tuning needs explicit -inner_cv_column. Do not use ridge -lambda options for these estimators. Automatic observed audits (also restored after permutations): PREFIX.regression.1D Outer fit diagnostics and response metrics. PREFIX.regression_scores.1D Pooled held-out per-response scores. PREFIX.regression_candidates.1D All nested candidates and solver diagnostics. PREFIX.sparse_features.1D Elastic net: original IDs, weights, zero flags. PREFIX.group_contributions.1D Banded ridge: training group-score variance and covariance with total predicted score. Candidate parameters are recorded in audit headers. Candidate is one-based; generic pipeline Penalty fields contain that candidate ID for these methods. For elastic net, coefficients use fold-preprocessed predictor units. Selected means a nonzero coefficient; selected-out predictors are explicitly zero. PLS diagnostics distinguish requested/effective components. Saved fitted-model, coefficient-refit, and activation-pattern exports remain ridge-only. Inference uses the existing exchangeable-row null: decoding shuffles complete response rows; encoding shuffles complete design rows within the declared blocks. Every preprocessing stage, candidate search and fit is repeated. MAE/ RMSE use the lower tail; correlations/CV-R2 use the upper tail. Blocking is not an autocorrelation model; nuisance values must be constant within each block. Permutation inference: ========================================================= .. code-block:: none -nperm N Run N synchronized label/row relabelings [0: off]. The identity is included. If the allowed group has at most N distinct relabelings, it is enumerated exactly. -permute_within COL Relabel only among rows sharing COL. Required with -nperm; use 'none' only for an explicitly unrestricted null. -block_column is an alias. Choose a column that fully identifies the exchangeability unit, such as Run, Subj, Fold, or a composite block column. -seed S Monte-Carlo relabeling seed [1234567]. Exact tests do not depend on this value. Classification must leave every CV training fold with all target classes. Continuous modes shuffle whole target rows (decode) or design rows (encode), holding neural rows fixed. All attribute columns move together; blocks and CV metadata stay fixed. Rows must be exchangeable under this null; serial time-series dependencies require an appropriate design, not unrestricted row shuffling. Preprocessing, tuning, and fitting repeat per null. Each decoding target has a separate spatial family; encoding tests its voxel or mean-pattern score. MAE/RMSE use the lower tail; other metrics the upper. PREFIX.inference.1D reports all continuous results. Buckets add NULL_MEAN, ABOVE_NULL, PVAL/ZSCR/QVAL, PFWE/ZFWE, and NNULL_VALID per target. ABOVE_NULL is positive for improvement, including lower errors. Undefined observations have neutral p=1 and z=0; undefined nulls count conservatively as exceedances. Classification uses the selected metric's upper-tail label-permutation null. The same relabeling slot drives every ROI/searchlight center. Output adds the empirical score above null-chance, PVAL/ZSCR, BH QVAL, and max-statistic PFWE/ZFWE bricks. ZSCR and ZFWE carry AFNI FIZT statistical codes. Spatial and output options: ========================================================== .. code-block:: none -roi_sel LIST Restrict positive mask values with an AFNI int-list. This option cannot be combined with -searchlight. -searchlight NBHD Classify a moving volumetric neighborhood at every nonzero mask voxel. NBHD is a radius in mm or one of SPHERE(r), RECT(a,b,c), RHDD(r), or TOHD(r). OpenMP builds use one workspace per worker; set OMP_NUM_THREADS to control the worker count. -surf SURFACE Make -searchlight a geodesic surface searchlight on this mesh (.gii/.asc/.ply/...). With -surf, NBHD must be one positive radius in mm. Inputs and an optional mask must be NIML/GIFTI datasets with identical dense or sparse node-row domains. The output preserves sparse node indexes. Requires a build with SUMA support. -prefix PREFIX Output dataset prefix [MVPA]. Without inference the dataset contains SCORE, NFEAT, and NFOLD. -nperm adds ABOVE_CHANCE, PVAL, ZSCR, QVAL, PFWE, and ZFWE before NFEAT and NFOLD. ROI analysis also writes PREFIX.roi.1D with SCORE, ACC, BACC, NFEAT, and NFOLD for every ROI. -save_patterns PPREFIX Ridge decode/classify: descriptive activation patterns from each OUTER TRAINING fit, using that fold's selected lambda/features/PCA. No full-data refit or held-out covariance. Supports fixed/two-table partitions. A=Cov(X,S)*pinv(Cov(S,S)), where S is fitted training scores (not targets), X is all neural inputs after nuisance/scaling, before selection/PCA. Covariances are centered sample covariances (NTrain-1). Patterns use transformed feature units per score unit; discarded features can have nonzero patterns through correlation. Class scores use 0/1 ridge coding and are not probabilities. Normalization is JOINT over outputs; binary class patterns are opposite half-contrasts. Pseudoinverse cutoff: 64*DBL_EPSILON*max(NTrain,NOutput) *largest score eigenvalue. Rank zero yields zero maps with ScoreRank=0 (no defined score direction). Writes PPREFIX.patterns.1D, .pattern_covariance.1D and PPREFIX.unit_ID.fold_N maps (N is one-based), one brick per target/class, at the original voxel/node IDs. Folds and overlapping units stay separate; many maps can be produced. No pattern p-values, causal claims, or automatic fold averaging. With -nperm only restored observed patterns are exported. Other estimators and encode mode are not supported by this option. These patterns differ from raw predictive weights. -save_coefficients CPREFIX Ridge only: separate descriptive full-data refit. Writes CPREFIX.coefficients.1D and .preprocessing.1D. Encoding without searchlights writes CPREFIX maps: one brick per design column plus REFIT_INTERCEPT. Other analyses write CPREFIX.unit_ID per ROI/searchlight: one brick per decoding target/class (encoding: per design column plus intercept). Weights occupy neural feature/ response voxels/nodes, preserving sparse node IDs. Overlapping neighborhoods retain separate models; this can create many datasets and large audit files. TSV identifies unit, feature, response, map and brick; intercepts and all fitted preprocessing are retained. y = intercept + sum(preprocessed_X * coefficient). Weights use the requested -scale predictor units; responses are unscaled (class responses: 0/1). feature_zscore uses full-data population SD; sample_ center subtracts each row mean; run_center subtracts full-data subject/run means recorded in preprocessing. These are descriptive predictive weights, NOT held-out scores, activation/Haufe maps, or significance tests. Correlated features and scaling affect weight values. -coef_lambda L Positive full-data refit penalty [fixed -lambda]. Required with tuned CV; never changes CV penalties, scores, predictions or permutation inference. -save_predictions FILE Write one held-out prediction row per sample and spatial unit, including sample metadata, test fold, observed/predicted class labels, and every class decision value. Rows never tested are retained as NA. -save_fold_scores FILE Write ACC and BACC for every fold and spatial unit, with stratum and train/test sample counts. These two audit tables are opt-in because searchlight tables can be very large. -save_confusion FILE Classification only: truth-row confusion counts and per-class recall for each spatial unit, pooled and by CV fold, subject, and CV stratum. CountClassN columns follow the # Class label dictionary. Subjects use the resolved subject role; strata use -within_column (All when absent). CVFoldID is a zero-based fold index; CVStratum is separate so labels containing '/' remain unambiguous. -save_probability_scores FILE Logistic only: held-out LogLoss and Brier, pooled and by fold, subject and stratum. Means weight rows equally. LogLoss uses natural logs of true-class probabilities, evaluated stably from logits without clipping. Brier sums K squared probability errors before averaging rows: range [0,2], including binary (both classes summed). -save_calibration FILE Logistic only: one-vs-rest reliability bins per class, pooled across held-out rows. Ten equal-width bins: [lo,hi), last includes 1; counts, mean probability and observed class frequency; empty bins are NA. This assesses raw probabilities; no calibration transform is fitted. Pooling can hide subject/fold differences. Probability scores and bins are descriptive, with no probability-loss inference or population inference. -save_summary_scores FILE Classification only: ACC/BACC for the same groups, plus equal-subject and equal-stratum averages. Pooled ACC weights samples equally; pooled BACC weights present true classes equally. Equal-group rows average group scores, excluding empty groups. Missing true classes have NA recall and are omitted from that group's BACC. Summaries use original held- out predictions without refitting; they are descriptive and do not establish population inference. Both new audits are opt-in and can be large for searchlights. -show_table Print the canonical table after input conversion. -show_samples Print resolved datasets, bricks, and sample roles. -show_folds Print every training/test row in every fold. -validate_only Read and resolve the actual analysis inputs, print all three reports above plus class/fold counts and spatial coverage, then exit without fitting models or writing result/audit files. Redirect stdout to save this report. Errors return nonzero status. Checks include selected beta values (finite inside the selected ROIs/neighborhoods), numeric targets, grids/node domains, and outer/inner training folds. Values are checked after AFNI loading/conversion; readers may repair bad floats. This is not a raw file-integrity check. Repeated dataset/brick selections are warnings. Permutation block metadata is checked, but nulls are not generated or validated. Output paths and solver convergence are not tested. Supplied labels and XColumn provenance are not proof of correct event mapping, anatomical QC or run independence. -quiet Suppress informational and progress messages. -progress M auto, bar, line, or off [auto]. Auto uses an updating bar on a terminal and 10% milestone lines when stderr is redirected. Counts completed analysis locations (ROIs, searchlight centers, or encoding voxels/nodes), with throughput, elapsed time and approximate ETA. Each location includes all folds, tuning and requested permutations; a single large ROI can take a while before its first update. -quiet overrides this option. Saved models (ridge v1; logistic v2): =========================================================== .. code-block:: none -train_only Fit all labeled input rows and export -save_model. No test table, partition, outer CV or test labels. Supports ridge classify/decode and logistic classify. Tuning requires -inner_cv_column: fit preprocessing inside each inner split, select parameters, then fit all rows. Inner scores are model-selection results, not independent performance estimates. Run separately per subject unless pooling subjects is intentional. Writes PREFIX.training.1D (fit counts/penalties), plus requested tuning/selection/PCA audits. No score maps, held-out predictions, permutations or pattern export. -validate_only checks inputs without fitting/writing. -save_model FILE Export a ridge or logistic fitted model. Requires -train_only, -partition_column or -testTable, with volume ROIs/searchlights. With a fixed partition only training rows enter the model; no full-data refit. Stores ordered voxel features and image grid/space, target/class labels, nuisance column names/OLS fit, fitted scaling, feature selection, PCA and estimator state including response-specific penalties. Observed state is saved after permutation restoration. All units are kept in memory until the model is published atomically. Export excludes encoding, surface inputs, ordinary multi- fold CV exports, run_center and -save_coefficients. Supported scales: none, feature_zscore, sample_center. 3dMVPA -apply_model FILE -dataTableFile NEW_TABLE -prefix OUT Standalone: -apply_model must be first. Also accepts -dataTable @FILE, -sample_column and -subject_column. No other analysis/fitted-setting overrides are allowed. 3dMVPA -apply_model FILE -apply_dset DSET -prefix OUT Alternative to a table: predict every sub-brick of an AFNI HEAD/BRIK or NIfTI dataset. Optional selectors preserve order and original zero-based brick indices, e.g. 'cleaned+orig[10..$]' or 'cleaned.nii.gz[8,12,9]'. Cannot combine with table input or role overrides. Models requiring nuisance columns need table input. GIfTI/surface saved models are not yet supported. NEW_TABLE has InputFile (one volume/brick per row) and the saved nuisance columns, if any. Targets are optional. If supplied, observed classes must be known and numeric targets finite. Neither is used to make predictions. Inputs must match saved dimensions/view/space and real IJK-to-DICOM affine (absolute tolerance 1e-5 per entry). The saved voxel order is used; no mask is redefined. Writes OUT.applied.1D: unit/sample/response predictions, predicted class and optional observed target. Class scores (Prediction) are ridge 0/1 outputs, NOT probabilities, or logistic logits. Logistic adds a Probability column: softmax over all trained classes. Probabilities sum to one per ROI/sample but calibration on a new data domain is not guaranteed. Exact ties choose the first stored class. Never fits, tunes, computes held-out scores or performs inference. Using training rows here does not make predictions held-out. Output is long form: one row per ROI x class x sample (or ROI x continuous response x sample). A labeled mask trains one model per positive ROI value, using all its voxels; a binary mask trains one ROI model. -apply_dset appends SourceBrick, BrickLabel, TimeSeconds. TimeSeconds uses original dataset time metadata (NA without a recognized time axis), not stimulus timing. Whole-run baseline/nuisance cleanup is external; apply comparable cleanup to training and application data. All stage parameters and labels are versioned data; unsupported versions or malformed models are rejected. Grid checks cannot establish anatomical registration or acquisition compatibility; no registration is performed. Training block means and predicting an unlabeled run: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dTstat -mean -prefix block01.nii.gz 'cleaned.r01.nii.gz[8..11]' # blocks.1D: Subj Run Condition InputFile; one mean image per block. # rois.nii.gz: positive integers identify distinct, nonoverlapping ROIs. 3dMVPA -train_only -mode classify -dataTable @blocks.1D \ -target_column Condition -mask rois.nii.gz -method logistic \ -logistic_lambda 1 -save_model decoder.mvpa -prefix training 3dMVPA -apply_model decoder.mvpa -apply_dset cleaned.r03.nii.gz \ -prefix predictions # predictions.applied.1D: ROI x class x TR logits and probabilities. # For ridge scores instead, replace -method logistic -logistic_lambda 1 # with -method ridge -lambda 1 and use a different model/prefix. # Optional tuning: -logistic_lambda auto -inner_cv_column Run; # ridge uses -lambda auto -inner_cv_column Run. Each inner training # split must contain every class. Averaged-block tuning does not measure # single-TR prediction accuracy; independent labeled TRs are needed for that. Standalone paired model comparisons: ============================================================ .. code-block:: none 3dMVPA -compare_predictions A.pred.1D B.pred.1D -prefix CMP Compare two -save_predictions audits without refitting. Must be the first option; only -prefix may follow. Supports classification or continuous decode/encode; compare the same targets and spatial unit definitions. Matches complete unit/response/sample domains, including training-only rows, regardless of audit row order. Subject/run/item/input-fold, test fold/stratum, observed outcomes and tested status must agree. Continuous runs must have identical training-mean baselines for CV-R2. Available spatial metadata must also agree. Source table paths/row numbers are recorded, not identity keys. Use stable explicit -sample_column IDs if input tables are reordered. No silent intersection or missing pairs. Writes CMP.comparison.1D and CMP.paired_predictions.1D. Reports pooled, fold, subject and stratum scores: ACC/ BACC, or Pearson/Spearman/CV-R2/MAE/RMSE per response. DeltaBminusA is B-A; ImprovementB is positive when B improves (A-B for MAE/RMSE, B-A for other metrics). Undefined metrics/differences stay NA. Pooled scores use all held-out rows, not an average of fold scores. Only saved predictions are used; original fits, image registration and ROI definitions cannot be verified. Descriptive only: no p-values, confidence intervals, population inference, spatial maps or model selection. Preparing trial betas: =========================================================== .. code-block:: none Trial-beta fMRI analyses take response maps, not raw BOLD. A short LSS route: 1. afni_proc.py: preprocess all runs onto a common grid; inspect alignment, censoring and masks. Retain each run's full-length scaled EPI. 2. Build an IM design with 3dDeconvolve (directly or via afni_proc.py). For LSS, put ALL trials in one -stim_times_IM stimulus; keep category labels separately. In afni_proc.py, use -regress_stim_types IM and -regress_3dD_stop to write X.xmat.1D and X.nocensor.xmat.1D without fitting the full GLM. Choose timing/basis/nuisance options for your study. Alternative LSA route: fit the IM GLM with 3dDeconvolve/3dREMLfit and select each trial's actual _Coef brick; skip the LSS steps below. 3. 1dXmatTool: check and split the multi-run DESIGN before running 3dLSS. From the results directory (Bash syntax): mkdir -p split lss tables 1dXmatTool -infile X.xmat.1D -uncensored X.nocensor.xmat.1D \ -validate -for lss 1dXmatTool -infile X.xmat.1D -uncensored X.nocensor.xmat.1D \ -split_runs -prefix split/X Local censoring and trial-column mappings are preserved in the split matrices and .rows.1D/.columns.1D tables. Review failed checks first. 4. 3dLSS: fit each run separately. Adapt run list and EPI filenames: for run in 01 02 03 04; do 3dLSS -matrix split/X.r${run}.xmat.1D \ -input pb03.s01.r${run}.scale+orig \ -mask mask_epi_anat.s01+orig -prefix lss/LSS.r${run}.nii.gz done The scale-block number (pb03 here) depends on your afni_proc.py blocks. Use FULL-length per-run EPI; 3dLSS applies the local GoodList censoring. 5. 1dXmatTool -> 3dMVPA: map trials to estimates, then inspect the folds. Supply events.1D with Run Volume Condition [Item]: Run is one-based; Volume is the zero-based LSS volume within that run, in IM-column order. Category labels come from the trial log, not the single IM stimulus name. 1dXmatTool -infile X.xmat.1D -uncensored X.nocensor.xmat.1D \ -export_manifest -events events.1D -subject s01 \ -beta_pattern 'lss/LSS.r{run}.nii.gz' -prefix tables/lss 3dMVPA -mode classify -trial_manifest tables/lss.trials.1D \ -target_column Condition -cv_column Run \ -mask mask_epi_anat.s01+orig -validate_only To write InputFile[volume] rows for -dataTable instead, add -manifest_format selected to the export command. Add numeric targets or design predictors by matching trial identities for decode/encode. LSS can mix neighboring trials: keep separately estimated runs together in CV. Fold-local MVPA preprocessing cannot undo upstream dependence. Numbered examples: =========================================================== .. code-block:: none Run-CV examples (1, 2, 4, 5, 7-9) fit each subject independently with -cv_column Run -within_column Subj; provide at least four runs per subject. Each classification run contains every class. Run IDs include the subject (s01_r01, s02_r01), so permutation blocks never mix subjects. For held-out-subject prediction, replace those two options with -cv_column Subj; if tuning, also use -inner_cv_column Subj and enough training subjects. Replace filenames and column names with your data. Use -validate_only with an analysis command to inspect inputs before fitting. samples.1D has one row per trial; InputFile selects one beta brick. For example: Subj Run Item Condition Rating Arousal Motion Luminance Contrast Shape InputFile s01 s01_r01 s01_t001 face 4.2 2.1 0.1 0.8 0.3 1.2 s01/lss/LSS.r01.nii.gz[0] s01 s01_r01 s01_t002 house 2.3 1.4 0.2 0.4 0.7 0.5 s01/lss/LSS.r01.nii.gz[1] s02 s02_r01 s02_t001 face 3.8 2.5 0.2 0.8 0.3 1.2 s02/lss/LSS.r01.nii.gz[0] s02 s02_r01 s02_t002 house 2.7 1.6 0.1 0.4 0.7 0.5 s02/lss/LSS.r01.nii.gz[1] Include all trials/runs for each subject. Item denotes item identity; it need not be unique per row. If each trial is a distinct item, use IDs such as s01_r01_t001 and s01_r02_t001 (trial numbering can restart per run), or continue s01_t001, s01_t002, ... across runs. Reusing s01_t001 in two runs is accepted but identifies the same item for Item-based grouping or transfer overlap checks. Preserve that identity when a stimulus item truly repeats. Sample is different: it identifies an observation and must be unique even when Item repeats. If Sample is omitted, unique row IDs are generated. Condition is categorical; Rating/Arousal are numeric targets; Motion is a numeric nuisance covariate. Luminance/Contrast/Shape are numeric encoding predictors. Include only columns your command needs. All maps/masks must share the feature grid. rois.nii.gz is a labeled ROI mask (a binary mask is one ROI); brain.nii.gz is a binary search mask. Paths are relative to the current working directory. Pooled scores summarize held-out samples; they are not population inference. 1. Classification: ROI baseline and error audits. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode classify -dataTable @samples.1D \ -target_column Condition -cv_column Run -within_column Subj -mask rois.nii.gz \ -method centroid -scale feature_zscore -metric balanced_accuracy \ -save_predictions class_roi.pred.1D -save_confusion class_roi.confusion.1D \ -prefix class_roi Each subject/run is held out once. Read class_roi.roi.1D and the confusion table. 2. Classification: volume searchlight with permutation inference. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode classify -dataTable @samples.1D \ -target_column Condition -cv_column Run -within_column Subj -mask brain.nii.gz \ -searchlight 'SPHERE(5)' -method svm -svm_c 1 -scale feature_zscore \ -metric balanced_accuracy -nperm 5000 -permute_within Run -seed 314159 \ -prefix class_search The radius is 5 mm. Within-run shuffling must suit your experiment's null. Maps include BACC, PVAL and PFWE; use ZSCR/ZFWE for positive-only AFNI thresholds. Without -nperm, scores describe prediction performance without significance. 3. Classification: separate training/test tables and nested ridge tuning. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode classify -dataTable @training.1D -testTable @testing.1D \ -target_column Condition -mask rois.nii.gz -method ridge \ -lambda auto -inner_cv_column Run -tune_metric BACC \ -scale feature_zscore -save_predictions class_test.pred.1D \ -save_tuning class_test.candidates.1D -prefix class_test Tables have the same columns and distinct sample/brick identities. Reserve whole runs/sessions/subjects as appropriate; training needs multiple inner Run groups and every class. This fit pools training rows across subjects; only test rows are scored. For one table, use -partition_column Split with train/test values (example 6). 4. Decoding: predict two continuous attributes from ROI patterns. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode decode -dataTable @samples.1D \ -target_columns Rating,Arousal -cv_column Run -within_column Subj -mask rois.nii.gz \ -method ridge -lambda_per_response -inner_cv_column Run \ -scale feature_zscore -metric cross_validated_r2 \ -save_predictions decode_roi.pred.1D -prefix decode_roi Each target gets its own training-selected penalty. Inspect CVR2, correlation and errors in decode_roi.continuous.1D; negative CVR2 is possible. 5. Decoding: searchlight with nuisance adjustment, selection and PCA. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode decode -dataTable @samples.1D -target_column Rating \ -cv_column Run -within_column Subj -mask brain.nii.gz -searchlight 'SPHERE(5)' \ -method ridge -lambda auto -inner_cv_column Run \ -nuisance_columns Motion -scale feature_zscore \ -select_features 50 -pca_components 5 -prefix decode_search Training-only order: nuisance OLS -> scaling -> selection -> PCA -> ridge. Counts clip to available features/rank. Motion must be a valid, full-rank covariate in every training split. Nuisance adjustment acts on neural inputs. 6. Decoding: fixed holdout, save the fitted pipeline, apply to new samples. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode decode -dataTable @partitioned.1D -target_column Rating \ -partition_column Split -mask rois.nii.gz -method ridge \ -lambda auto -inner_cv_column Run -scale feature_zscore \ -save_model rating.mvpa -save_predictions decode_test.pred.1D \ -prefix decode_test 3dMVPA -apply_model rating.mvpa -dataTableFile new_samples.1D \ -prefix rating_new partitioned.1D adds Split=train/test to the sample table. Only training rows fit the saved pipeline, pooled across subjects. New samples need matching grids, but no Rating column. rating_new.applied.1D contains predictions; application never refits or scores. 7. Encoding: stimulus features predict each voxel's response. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode encode -dataTable @samples.1D \ -design_columns Luminance,Contrast,Shape -cv_column Run -within_column Subj \ -mask brain.nii.gz -score voxel -method ridge -lambda 1 \ -scale feature_zscore -metric cross_validated_r2 -prefix encode_voxel Scaling acts on design predictors. Output maps score each voxel's held-out prediction; use beta coefficients as InputFile responses, not t-statistics. 8. Encoding: ROI pattern scores with response-specific regularization. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode encode -dataTable @samples.1D \ -design_columns Luminance,Contrast,Shape -cv_column Run -within_column Subj \ -mask rois.nii.gz -score pattern -method ridge -lambda_per_response \ -inner_cv_column Run -scale feature_zscore \ -save_tuning encode_pattern.candidates.1D -prefix encode_pattern Each response voxel gets a penalty; pattern scores average defined voxel metrics within each ROI. This is not correlation between spatial patterns. 9. Encoding: test the feature-to-response association by permutation. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode encode -dataTable @samples.1D \ -design_columns Luminance,Contrast,Shape -cv_column Run -within_column Subj \ -mask brain.nii.gz -score voxel -method ridge -lambda 1 \ -scale feature_zscore -nperm 5000 -permute_within Run -seed 314159 \ -prefix encode_perm Whole design rows shuffle within Run; predictor columns move together. Use only when those rows are exchangeable. See encode_perm.inference.1D and PVAL/PFWE maps; this is not a population test across subjects. Output tables use .1D with # Columns: headers and mixed text/numeric fields; read them as tables. Explicit -save_* filenames are honored as given. 10. Cross-condition generalization: visual -> auditory within each subject. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode classify -dataTable @transfer.1D -target_column Condition \ -transfer_column Task -train_domain visual -test_domain auditory \ -transfer_subjects within -transfer_items allow \ -transfer_sessions allow -mask rois.nii.gz -method ridge \ -lambda auto -inner_cv_column Run -scale feature_zscore \ -save_predictions transfer.pred.1D -prefix transfer transfer.1D adds Task and Session, with canonical Item IDs. This example intentionally permits repeated items and same-session transfer. Each subject needs both tasks and multiple source Run groups. Inspect transfer.transfer.1D. For held-out-subject transfer use -transfer_subjects disjoint, with entirely different destination subjects. Reverse the domain values in a separate run with a new prefix to test the reverse direction; results need not be symmetric. 11. Classification: tune class probabilities and assess calibration. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: none 3dMVPA -mode classify -dataTable @samples.1D -target_column Condition \ -cv_column Run -within_column Subj -mask rois.nii.gz \ -method logistic -logistic_lambda auto -inner_cv_column Run \ -save_predictions logistic.pred.1D -save_fold_scores logistic.fold.1D \ -save_probability_scores logistic.scores.1D \ -save_calibration logistic.calibration.1D -prefix logistic Nested selection minimizes held-out log loss. Inspect probability scores and reliability bins alongside ACC/BACC; probabilities need not be well calibrated. Use -tune_metric brier to select lambda by squared probability error instead. 12. Sparse continuous decoding (elastic net): ============================================================ .. code-block:: none 3dMVPA -mode decode -dataTable @samples.1D -target_columns Rating,Arousal \ -cv_column Run -within_column Subj -mask rois.nii.gz \ -method elastic_net -enet_alpha_grid .01,.1,1 \ -enet_l1_ratio_grid .25,.75,1 -inner_cv_column Run \ -metric cross_validated_r2 -save_predictions sparse.pred.1D \ -prefix sparse Inspect sparse.sparse_features.1D alongside held-out response scores. Different folds may choose different voxels when features are correlated. 13. Named feature-space encoding (banded ridge): ============================================================ .. code-block:: none For -design_columns Visual1,Visual2,Semantic1,Semantic2, groups.1D contains: Group Column visual Visual1 visual Visual2 semantic Semantic1 semantic Semantic2 penalties.1D lists explicit candidate vectors, with the same group order: visual semantic 0.1 10 1 1 10 0.1 3dMVPA -mode encode -dataTable @samples.1D \ -design_columns Visual1,Visual2,Semantic1,Semantic2 \ -cv_column Run -mask brain.nii.gz -score voxel \ -method banded_ridge -feature_groups groups.1D \ -banded_penalties penalties.1D -inner_cv_column Run -prefix banded 14. Joint-target supervised components (PLS regression): ============================================================ .. code-block:: none 3dMVPA -mode decode -dataTable @samples.1D -target_columns Rating,Arousal \ -cv_column Run -within_column Subj -mask rois.nii.gz \ -method pls -pls_components_grid 1,2,4 -inner_cv_column Run \ -metric RMSE -save_predictions pls.pred.1D -prefix pls Response units affect the joint PLS components. Report those units and inspect retained counts in pls.regression.1D; PLS is distinct from unsupervised PCA. 15. Epsilon-insensitive behavioral prediction (linear SVR): ============================================================ .. code-block:: none 3dMVPA -mode decode -dataTable @samples.1D -target_column Rating \ -cv_column Run -within_column Subj -mask rois.nii.gz \ -method svr -svr_c_grid .1,1,10 -svr_epsilon_grid 0,.1,.5 \ -inner_cv_column Run -tune_metric MAE -metric MAE \ -save_predictions svr.pred.1D -prefix svr Epsilon has Rating's units. Compare aligned held-out predictions with the ridge baseline; changing the loss does not guarantee improved prediction. 16. Time-resolved MEG/EEG source classification: ============================================================= .. code-block:: none One row per individual trial (not an evoked condition average), with one scalar source map per GIFTI data column, all on the same node domain: Subj Run Sample Condition InputFile s01 r1 trial001 face trial001.lh.func.gii s01 r1 trial002 house trial002.lh.func.gii ... (all trials from all runs for this subject) latencies.1D contains one event-relative time in seconds per data column, e.g. -0.100, -0.099, ... on separate lines. Export matching scalar source orientations, vertex indexes/order, and event alignment for every trial. Process hemispheres separately unless explicitly constructing a shared domain. 3dMVPA -mode classify -dataTable @trials.1D \ -target_column Condition -cv_column Run -method ridge \ -mask lh.rois.niml.dset -time_resolved -time_axis latencies.1D \ -save_predictions lh.predictions.1D -save_fold_scores lh.folds.1D \ -prefix lh.decoding.niml.dset To process all latencies without specifying the number of samples, replace -time_axis latencies.1D above with: -time_start -0.100 -time_step 0.001 The count comes from the input columns; all trials must have the same count. Alternatively, omit -time_axis entirely and keep just -time_resolved to process every column with TimeIndex=0,1,2,... and TimeSeconds=NA. This does not infer event-relative timing from GIFTI or volume metadata. For regularly sampled trials, replace -time_axis latencies.1D above with: -time_axis '1D: 601%-0.100%0.001' This is AFNI's N%start%step syntax: 601 samples starting at -0.100 seconds, with a 0.001-second step, ending at +0.500 seconds (both endpoints included). For -0.100 through 0 seconds at the same spacing, use: -time_axis '1D: 101%-0.100%0.001' A range like '1D: -0.100..0' does not specify the step and is not accepted. The generated sample count must match every trial's number of data columns. For geodesic searchlights add -surf lh.white.gii -searchlight 10; the mask then defines eligible nodes (or omit it to use every represented node). Use a matching mesh with coordinates in mm and a SUMA-enabled build. The output bucket has one score map per latency; exact times and spatial-unit scores are in lh.decoding.niml.dset.temporal.1D. Trial folds are reused, but each latency gets independent training-only preprocessing, tuning and fits. Run subjects separately for individual curves/maps, or use explicit subject strata/held-out-subject CV to match the intended generalization question. Condition averages cannot substitute for trial-level cross-validation. No across-time inference is performed; significance at one time and not another does not establish a difference between those times. References: =========================================================== .. code-block:: none Selected methodological references; cite the papers relevant to your analysis. The options above specify 3dMVPA's objectives, scaling and inference contracts. * Cox (1996), Comput Biomed Res 29:162-173. [AFNI] AFNI: software for analysis and visualization of functional magnetic resonance neuroimages. https://doi.org/10.1006/cbmr.1996.0014 * Norman, Polyn, Detre & Haxby (2006), Trends Cogn Sci 10:424-430. [MVPA] Beyond mind-reading: multi-voxel pattern analysis of fMRI data. https://doi.org/10.1016/j.tics.2006.07.005 * Kriegeskorte, Goebel & Bandettini (2006), PNAS 103:3863-3868. [searchlights] Information-based functional brain mapping. https://doi.org/10.1073/pnas.0600244103 * Varma & Simon (2006), BMC Bioinformatics 7:91. [nested cross-validation] Bias in error estimation when using cross-validation for model selection. https://doi.org/10.1186/1471-2105-7-91 * Hoerl & Kennard (1970), Technometrics 12:55-67. [ridge regression] Ridge regression: biased estimation for nonorthogonal problems. https://doi.org/10.1080/00401706.1970.10488634 * Zou & Hastie (2005), J R Stat Soc B 67:301-320. [elastic net] Regularization and variable selection via the elastic net. https://doi.org/10.1111/j.1467-9868.2005.00503.x * Friedman, Hastie & Tibshirani (2010), J Stat Softw 33(1):1-22. Regularization paths for generalized linear models via coordinate descent. https://doi.org/10.18637/jss.v033.i01 [penalized regression/logistic models] * Hsieh et al. (2008), ICML:408-415. [linear SVM dual coordinate descent] A dual coordinate descent method for large-scale linear SVM. https://doi.org/10.1145/1390156.1390208 * Ho & Lin (2012), J Mach Learn Res 13:3323-3348. [linear SVR] Large-scale linear support vector regression. https://www.jmlr.org/papers/v13/ho12a.html * Dupre la Tour, Eickenberg, Nunez-Elizalde & Gallant (2022), NeuroImage 264:119728. [banded ridge encoding] Feature-space selection with banded ridge regression. https://doi.org/10.1016/j.neuroimage.2022.119728 * Wold, Sjostrom & Eriksson (2001), Chemom Intell Lab Syst 58:109-130. PLS-regression: a basic tool of chemometrics. [PLS regression] https://doi.org/10.1016/S0169-7439(01)00155-1 * Jolliffe & Cadima (2016), Philos Trans R Soc A 374:20150202. [PCA] Principal component analysis: a review and recent developments. https://doi.org/10.1098/rsta.2015.0202 * Haufe et al. (2014), NeuroImage 87:96-110. [activation patterns] On the interpretation of weight vectors of linear models in multivariate neuroimaging. https://doi.org/10.1016/j.neuroimage.2013.10.067 * Winkler et al. (2014), NeuroImage 92:381-397. Permutation inference for the general linear model. [permutation inference and exchangeability] https://doi.org/10.1016/j.neuroimage.2014.01.060 * Stelzer, Chen & Turner (2013), NeuroImage 65:69-82. Statistical inference and multiple testing correction in classification-based multi-voxel pattern analysis (MVPA): random permutations and cluster size control. [MVPA searchlight inference background] https://doi.org/10.1016/j.neuroimage.2012.09.063 * Phipson & Smyth (2010), Stat Appl Genet Mol Biol 9:39. Permutation P-values should never be zero: calculating exact P-values when permutations are randomly drawn. [nonzero permutation p-values] https://doi.org/10.2202/1544-6115.1585 * Nichols & Holmes (2002), Hum Brain Mapp 15:1-25. [permutation/max-FWE] Nonparametric permutation tests for functional neuroimaging: a primer with examples. https://doi.org/10.1002/hbm.1058 * Benjamini & Hochberg (1995), J R Stat Soc B 57:289-300. [FDR] Controlling the false discovery rate: a practical and powerful approach to multiple testing. https://doi.org/10.1111/j.2517-6161.1995.tb02031.x -- P Molfese, December 2026 * This binary version of 3dMVPA is compiled using OpenMP, a semi- automatic parallelizer software toolkit, which splits the work across multiple CPUs/cores on the same shared memory computer. * OpenMP is NOT like MPI -- it does not work with CPUs connected only by a network (e.g., OpenMP doesn't work across cluster nodes). * For some implementation and compilation details, please see https://afni.nimh.nih.gov/pub/dist/doc/misc/OpenMP.html * The number of CPU threads used will default to the maximum number on your system. You can control this value by setting environment variable OMP_NUM_THREADS to some smaller value (including 1). * Un-setting OMP_NUM_THREADS resets OpenMP back to its default state of using all CPUs available. ++ However, on some systems, it seems to be necessary to set variable OMP_NUM_THREADS explicitly, or you only get one CPU. ++ On other systems with many CPUS, you probably want to limit the CPU count, since using more than (say) 16 threads is probably useless. * You must set OMP_NUM_THREADS in the shell BEFORE running the program, since OpenMP queries this variable BEFORE the program actually starts. ++ You can't usefully set this variable in your ~/.afnirc file or on the command line with the '-D' option. * How many threads are useful? That varies with the program, and how well it was coded. You'll have to experiment on your own systems! * The number of CPUs on this particular computer system is ...... 1. * The maximum number of CPUs that will be used is now set to .... 1. ++ Compile date = Nov 17 2026 {AFNI_26.3.12:linux_ubuntu_24_64}