Skip to contents

This function creates an RSA model object by taking an MVPA (Multi-Variate Pattern Analysis) dataset and an RSA design.

Usage

rsa_model(
  dataset,
  design,
  distmethod = "spearman",
  regtype = "pearson",
  check_collinearity = TRUE,
  nneg = NULL,
  semipartial = FALSE,
  pattern_center = c("none", "stimulus_mean"),
  return_fingerprint = FALSE,
  fingerprint_method = c("pearson", "spearman"),
  fingerprint_basis = c("pca", "qr"),
  measure = c("distance", "similarity"),
  statistic = NULL,
  contrasts = NULL,
  condition_labels = NULL,
  crossval = NULL
)

Arguments

dataset

An instance of an mvpa_dataset.

design

An instance of an rsa_design created by rsa_design().

distmethod

Controls how the neural RDM is computed: the correlation distance 1 - r between each pair of observation patterns, with r Pearson ("pearson") or Spearman ("spearman", the default), or "crossvalidated_euclidean" (see below). It does not choose the comparison with the model RDMs; that is regtype.

regtype

Controls how the neural RDM is compared with each model RDM: "pearson" (Pearson correlation, the default), "spearman" (Spearman correlation, ranks of both vectors), "lm" or "rfit". With distmethod = "crossvalidated_euclidean", regtype also sets the model fit. Pearson and Spearman results differ when the relation between the two RDMs is not linear.

check_collinearity

Logical. When regtype = "lm", stop if two predictor RDMs correlate above 0.99 or the design matrix is rank deficient. When regtype is "lm" or "rfit", also warn if a model predictor has no usable variation or fewer than 10 effective items (see the section on effective support). Default is TRUE.

nneg

A named list of variables (predictors) for which non-negative regression coefficients should be enforced (only if regtype="lm"). Defaults to NULL (no constraints).

semipartial

Logical indicating whether to compute semi-partial correlations in the "lm" case (only if nneg is not used). Defaults to FALSE.

pattern_center

Optional pattern-centering method applied to the stimulus-by-voxel matrix before distances are computed. Use "stimulus_mean" to subtract the across-stimulus mean pattern (Hanson-style). Default is "none".

return_fingerprint

Logical; if TRUE, project the per-unit neural pair-dissimilarity vector onto an orthonormal basis of the signal model RDM subspace and return the standardized model-space score vector alongside the standard outputs. For pair_rsa_design objects, predictors supplied through nuisance are excluded from this fingerprint basis. The basis is cached on the model spec and reused across ROIs/searchlight units. Default FALSE.

fingerprint_method

Standardization method used when return_fingerprint = TRUE. One of "pearson" (centered/scaled) or "spearman" (rank-then-standardize). Default "pearson".

fingerprint_basis

Basis used to span the model RDM subspace when return_fingerprint = TRUE: "pca" (default) or "qr".

measure

Neural pair measurement: "distance" (default, correlation distance) or "similarity" (correlation). The choice applies after pattern centering and uses distmethod in either case.

statistic

NULL preserves the existing output selected by regtype/semipartial. Use "beta" with ordinary, unconstrained regtype = "lm" to return raw model coefficients. Nuisance coefficients remain internal. Fixed designs cache QR coefficient queries; missing neural cells rebuild the query for eligible pairs.

contrasts

Optional uniquely named list of named numeric coefficient weights, available with statistic = "beta". Coefficient names are those in design$model_mat, plus "(Intercept)". Outputs are named contrast_<name>.

condition_labels

Observation-aligned vector of condition IDs, required with distmethod = "crossvalidated_euclidean". Repeated observations of a condition are averaged within each partition. Its unique values must equal design$condition_ids; the RDM order comes from the design.

crossval

Independent-partition specification, for example blocked_cross_validation(run_ids). Required only for crossvalidated Euclidean RSA and stored as model$crossval. Partitions must be disjoint, nonempty, exhaustive and at least two in number. Every condition must be observed in every partition. Missing cells are rejected at construction; nonfinite neural values fail the affected ROI rather than becoming zeros.

Value

An object of class "rsa_model" (and "list"), containing:

  • dataset : the input dataset

  • design : the RSA design

  • distmethod : the distance method used

  • regtype : the regression type

  • nneg : a named list of constrained variables, if any

  • semipartial: whether to compute semi-partial correlations

  • design_diagnostics: an rsa_design_diagnostics object (see rsa_design_diagnostics)

Crossvalidated Euclidean distances

For each distinct condition pair, average the inner products of its difference patterns over all ordered pairs of independent partitions, then divide by the number of features. This estimates a squared Euclidean distance per feature, in squared input units, and retains negative estimates. No whitening is performed: this is not a Mahalanobis distance. All declared ROI features, including constant columns, are retained in the normalization; nonfinite columns fail the ROI instead of being removed by the shared ROI filter. Independent run IDs must be supplied separately from the unique condition IDs used by the feature RDMs. The caller is responsible for physical independence of partitions.

This mode supports ordinary rsa_design, measure = "distance", and the general searchlight dispatcher (engine = "auto" or "legacy"). Optimized engines, including "rsa_fast", are explicitly rejected. Correlation fits use regtype to select Pearson or Spearman association; historical correlation-distance behavior is unchanged. It does not change contrast_rsa_model's second-moment estimand. Item permutations relabel conditions jointly across all partitions and must preserve an explicit pair mask; specify suitable exchangeability blocks using block_var and keep_intra_run = TRUE when retaining within-block pairs. Pair masks alone do not establish exchangeability.

Relational coefficients

Combine pair_rsa_design(..., modulation = ...) with measure = "similarity", regtype = "lm", statistic = "beta" to estimate modulated relationships. For balanced one-to-one correspondence and retrieval-observation intercepts, these coefficients equal regression on matching-minus-nonmatching ERA scores. Unequal eligible candidate counts generally imply a weighted reduction. Coefficient queries are conditional on the specified measurement and fixed templates; they do not correct first-level measurement bias or error in estimated neural predictors. Pair cells are dependent. These outputs provide participant-level effects, not calibrated standard errors or population inference. Existing label permutations retain their joint-null restriction for multiple predictors; they do not test a modulation coefficient conditional on other terms.

Effective support of the design

RDM entries are not independent observations. Every item enters n_items - 1 pairs, so the n_pairs entries of a vectorised RDM carry on the order of n_items independent pieces of information, and a regression coefficient's variance is inflated further by the predictor's collinearity with the others (its VIF). The constructor computes n_items / VIF for every predictor and stores the result as design_diagnostics (see rsa_design_diagnostics). When regtype is "lm" or "rfit" and a model predictor falls below 10 effective items, it warns: that coefficient will vary across ROIs largely through noise. This is a heuristic screen, not a test.

For inference on RSA maps use run_permutation_searchlight, which permutes item labels and so carries the same dependence into the null. For regression with multiple design predictors (including nuisance predictors), this supports only an explicit joint no-association null via permutation_control(rsa_null = "joint"); it does not provide conditional inference on individual coefficients. The per-ROI t-values returned by regtype = "lm" use pair-based degrees of freedom and are anti-conservative.

See also

rsa_neural_rdm to compute the full neural correlation distance matrix from supplied observation-by-feature patterns.

Examples

# Create a random MVPA dataset (image data)
arr  <- array(rnorm(100 * 5), c(5, 5, 4, 5))   # 5 voxels x 5 voxels x 4 slices x 5 observations
sp   <- neuroim2::NeuroSpace(c(5, 5, 4, 5))
vec  <- neuroim2::NeuroVec(arr, sp)
mask <- neuroim2::LogicalNeuroVol(array(1, c(5, 5, 4)), neuroim2::NeuroSpace(c(5, 5, 4)))
mvpa_data <- mvpa_dataset(train_data = vec, mask = mask)

# Create two random RDMs (distance matrices) over the 5 observations
data_mat  <- matrix(rnorm(5 * 10), 5, 10)
dismat1   <- dist(data_mat)
dismat2   <- dist(matrix(rnorm(5 * 10), 5, 10))
rdes <- rsa_design(~ dismat1 + dismat2,
                   list(dismat1 = dismat1, dismat2 = dismat2))

# Create an RSA model with standard 'lm' (returns t-values):
rsa_mod <- rsa_model(mvpa_data, rdes, regtype = "lm")
#> Checking design matrix for collinearity...
#> Collinearity check passed.
#> Warning: RSA design has only 5 items, which is ~4.1 effective items for predictor 'dismat1' (VIF = 1.2). Its coefficient will be unstable across ROIs. Add items or pool runs. RDM entries share items, so the 10 pairs carry roughly 5 independent observations. Per-ROI t-values overstate the evidence. See run_permutation_searchlight() for the supported RSA null hypotheses; conditional coefficient inference with other predictors is not implemented.

# Create an RSA model enforcing non-negativity for dismat2 only:
# Requires the 'glmnet' package to be installed
# rsa_mod_nneg <- rsa_model(mvpa_data, rdes, regtype="lm",
#                          nneg = list(dismat2 = TRUE))

# Create an RSA model using 'lm' but returning semi-partial correlations:
rsa_mod_sp <- rsa_model(mvpa_data, rdes, regtype = "lm",
                        semipartial = TRUE)
#> Checking design matrix for collinearity...
#> Collinearity check passed.
#> Warning: RSA design has only 5 items, which is ~4.1 effective items for predictor 'dismat1' (VIF = 1.2). Its coefficient will be unstable across ROIs. Add items or pool runs. RDM entries share items, so the 10 pairs carry roughly 5 independent observations. Per-ROI t-values overstate the evidence. See run_permutation_searchlight() for the supported RSA null hypotheses; conditional coefficient inference with other predictors is not implemented.

# Train the model using a trial-by-feature matrix
fit_params <- train_model(rsa_mod_sp, data_mat, y = NULL, indices = NULL)
# 'fit_params' = named vector of semi-partial correlations for each predictor

# Condition-level feature RSA across three independent runs:
ids <- paste0("item", 1:6)
recording <- rep(1:2, each = 3)
pairs <- outer(recording, recording, `==`)
diag(pairs) <- FALSE
cv_design <- rsa_design(~ feature, list(feature = dist(1:6)),
                        condition_ids = ids, pair_mask = pairs)
cv_data <- gen_sample_dataset(c(2, 2, 2), 18, blocks = 3)$dataset
cv_model <- rsa_model(cv_data, cv_design,
  distmethod = "crossvalidated_euclidean",
  condition_labels = rep(ids, 3),
  crossval = blocked_cross_validation(rep(1:3, each = 6)))
# run_searchlight(cv_model, radius = 4, engine = "legacy")
# Six recordings with ten unique conditions each would retain 270 pairs.