### Installing rMVPA from command line using Git Source: https://github.com/bbuchsbaum/rmvpa/blob/master/README.md This snippet shows how to clone the rMVPA repository using Git and then install the package locally from the command line using R CMD install. This provides an alternative installation method to using R's devtools. ```Bash git clone git@github.com:bbuchsbaum/rMVPA.git R CMD install rMVPA ``` -------------------------------- ### Example of Creating a MANOVA Model in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/manova_model.html This example illustrates the intended usage of `manova_model` by first attempting to create an `mvpa_dataset` and `manova_design` instances, and then passing them to `manova_model`. Note that the example as provided in the source text contains errors due to missing prerequisite objects and functions, indicating it's a conceptual example rather than a runnable one without further setup. ```R # Create a MANOVA model dataset <- create_mvpa_dataset(data_matrix, labels, subject_ids) #> Error in create_mvpa_dataset(data_matrix, labels, subject_ids): could not find function "create_mvpa_dataset" formula <- y ~ x1 + x2 data_list <- list(y = dissimilarity_matrix_y, x1 = dissimilarity_matrix_x1, x2 = dissimilarity_matrix_x2) #> Error: object 'dissimilarity_matrix_y' not found design <- manova_design(formula, data_list) #> Error: object 'data_list' not found manova_model_obj <- manova_model(dataset, design) #> Error: object 'dataset' not found ``` -------------------------------- ### Installing rMVPA from command line using Git and R CMD Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/index.html This snippet provides instructions for installing the 'rMVPA' package from the command line. It involves cloning the GitHub repository using Git and then installing the R package using the standard `R CMD install` command. ```Shell git clone git@github.com:bbuchsbaum/rMVPA.git R CMD install rMVPA ``` -------------------------------- ### Comprehensive MVPA Configuration File Example Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/CommandLineScripts.html This comprehensive YAML configuration file (`config.yaml`) defines all essential parameters for an MVPA searchlight analysis. It includes paths to data sources, analysis parameters like the model type ("rf"), data mode, core count, searchlight radius, label and block columns, output options, and advanced settings for feature selection and cross-validation, ensuring a complete and reproducible setup. ```YAML # Data Sources train_design: "train_design.txt" test_design: "test_design.txt" train_data: "train_data.nii" test_data: "test_data.nii" mask: "mask.nii" # Analysis Parameters model: "rf" # Random Forest classifier data_mode: "image" # or "surface" ncores: 4 radius: 6 label_column: "condition" block_column: "session" # Output Options output: "searchlight_results" normalize_samples: TRUE class_metrics: TRUE # Advanced Options feature_selector: method: "anova" cutoff_type: "percentile" cutoff_value: 0.1 cross_validation: name: "twofold" nreps: 10 # Optional Subsetting train_subset: "subject == 'S01'" test_subset: "subject == 'S02'" ``` -------------------------------- ### Installing rMVPA and neuroim2 using devtools in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/index.html This snippet demonstrates how to install the 'rMVPA' and 'neuroim2' R packages directly from GitHub using the `devtools::install_github` function. It requires the `devtools` package to be installed and loaded, and is intended for R users. ```R #library(devtools) install_github("bbuchsbaum/neuroim2") install_github("bbuchsbaum/rMVPA") ``` -------------------------------- ### Installing rMVPA and neuroim2 using devtools in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/README.md This snippet demonstrates how to install the rMVPA and neuroim2 R packages directly from GitHub using the devtools library. This method is crucial for obtaining the latest development versions of these packages. ```R #library(devtools) install_github("bbuchsbaum/neuroim2") install_github("bbuchsbaum/rMVPA") ``` -------------------------------- ### Example Usage of mvpa_model in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_model.html This example demonstrates how to set up and use the `mvpa_model` function within the `rMVPA` package. It includes loading a model, creating `NeuroVec` and `LogicalNeuroVol` objects, initializing `mvpa_dataset` and `mvpa_design`, defining a custom performance metric, and finally calling `mvpa_model` with these components. It also shows subsequent calls to `run_searchlight` and a `stopifnot` check, though these result in errors in the provided context. ```R mod <- load_model("sda") traindat <- neuroim2::NeuroVec(array(rnorm(6*6*6*100), c(6,6,6,100)), neuroim2::NeuroSpace(c(6,6,6,100))) mask <- neuroim2::LogicalNeuroVol(array(rnorm(6*6*6)>-.2, c(6,6,6)), neuroim2::NeuroSpace(c(6,6,6))) mvdset <- mvpa_dataset(traindat,mask=mask) design <- data.frame(fac=rep(letters[1:4], 25), block=rep(1:10, each=10)) cval <- blocked_cross_validation(design$block) mvdes <- mvpa_design(design, ~ fac, block_var=~block) #> Error in mvpa_design(design, ~fac, block_var = ~block): argument "y_train" is missing, with no default custom_perf <- function(result) { c(accuracy=sum(result$observed == result$predicted)/length(result$observed)) } mvpmod <- mvpa_model(mod, dataset=mvdset, design=mvdes, crossval=cval, performance=custom_perf) #> Error: object 'mvdes' not found ret <- run_searchlight(mvpmod) #> Error: object 'mvpmod' not found stopifnot("accuracy" %in% names(ret)) #> Error: object 'ret' not found ``` -------------------------------- ### Creating Random MVPA Dataset in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/rsa_model.html This example demonstrates how to generate a random matrix and labels to simulate an MVPA dataset. It then attempts to create an `mvpa_dataset` object, though the example notes an error indicating `train_data` does not inherit from `NeuroVec`. ```R data <- matrix(rnorm(100 * 100), 100, 100) labels <- factor(rep(1:2, each = 50)) mvpa_data <- mvpa_dataset(data, labels) ``` -------------------------------- ### Creating RSA Model with Default Parameters in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/rsa_model.html This example attempts to create an RSA model using the previously generated `mvpa_data` and `rdes` objects. It uses the default `distmethod` ('spearman') and `regtype` ('pearson'), though the example notes an error due to `mvpa_data` not being found. ```R rsa_mod <- rsa_model(mvpa_data, rdes) ``` -------------------------------- ### Example MVPA Design File Structure Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/CommandLineScripts.html This snippet shows an example `train_design.txt` file, which is crucial for defining experimental conditions and subject information for an MVPA analysis. It illustrates the structure with columns like `trial`, `condition` (the label column for classification/regression), `subject`, and `session` (a potential block column), used to specify the target variable and experimental design. ```Text trial condition subject session 1 Face S01 1 2 House S01 1 3 Face S01 1 4 House S01 1 5 Face S01 2 ``` -------------------------------- ### Example of Creating and Evaluating classification_result in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/classification_result.html This example demonstrates the end-to-end process of creating a `classification_result` object. It shows how to prepare observed and predicted data, generate probabilities, construct the result object, and then compute performance metrics like Accuracy and AUC using the `performance` function. ```R # A vector of observed values yobs <- factor(rep(letters[1:4], 5)) # Predicted probabilities probs <- data.frame(a = runif(1:20), b = runif(1:20), c = runif(1:20), d = runif(1:20)) probs <- sweep(probs, 1, rowSums(probs), "/") # Get the max probability per row and use this to determine the predicted class maxcol <- max.col(probs) predicted <- levels(yobs)[maxcol] # Construct a classification result cres <- classification_result(yobs, predicted, probs) # Compute default performance measures (Accuracy, AUC) performance(cres) #> Accuracy AUC #> 0.20000000 -0.02666667 ``` -------------------------------- ### Running MVPA Searchlight with Basic Parameters (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/CommandLineScripts.html This command-line example demonstrates how to execute the MVPA_Searchlight.R script for a basic searchlight MVPA. It specifies input data files (train_data.nii, train_design.txt), a brain mask (mask.nii), a searchlight radius, the sda_notune model, the label column for classification, the number of cores for parallel processing, and an output prefix. It requires a 4D fMRI file, a trial-by-trial design matrix, and a brain mask. ```Shell MVPA_Searchlight.R --radius=6 \ --train_design=train_design.txt \ --train_data=train_data.nii \ --mask=mask.nii \ --model=sda_notune \ --label_column=condition \ --ncores=4 \ --output=my_searchlight_output ``` -------------------------------- ### Creating contrast_rsa_model with Multiple Metrics (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/roxygen_todo.md This R code demonstrates how to call the `contrast_rsa_model` function, specifying multiple output metrics simultaneously using a character vector for the `output_metric` parameter. It shows an example of requesting 'beta_delta', 'recon_score', and 'beta_only' metrics from the model. ```R model_multi_metric <- contrast_rsa_model( dataset = mvpa_dat, design = msreve_des, output_metric = c("beta_delta", "recon_score", "beta_only") ) ``` -------------------------------- ### Example MVPA Regional Analysis in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/run_regional.html This comprehensive example demonstrates how to set up a sample dataset, create a region mask, define cross-validation, load a model, and execute a regional MVPA analysis using `run_regional`. It also shows how to access the performance metrics, predictions, and fitted models. ```R # \donttest{ # Generate sample dataset (3D volume with categorical response) dataset <- gen_sample_dataset( D = c(10,10,10), # Small 10x10x10 volume nobs = 100, # 100 observations nlevels = 3, # 3 classes response_type = "categorical", data_mode = "image", blocks = 3 # 3 blocks for cross-validation ) # Create region mask with 5 ROIs region_mask <- NeuroVol( sample(1:5, size=length(dataset$dataset$mask), replace=TRUE), space(dataset$dataset$mask) ) #> Error in NeuroVol(sample(1:5, size = length(dataset$dataset$mask), replace = TRUE), space(dataset$dataset$mask)): could not find function "NeuroVol" # Create cross-validation specification cval <- blocked_cross_validation(dataset$design$block_var) # Load SDA classifier (Shrinkage Discriminant Analysis) model <- load_model("sda_notune") # Create MVPA model mspec <- mvpa_model( model = model, dataset = dataset$dataset, design = dataset$design, model_type = "classification", crossval = cval, return_fits = TRUE # Return fitted models ) # Run regional analysis results <- run_regional(mspec, region_mask) #> Error: object 'region_mask' not found # Access results head(results$performance) # Performance metrics #> Error: object 'results' not found head(results$prediction_table) # Predictions #> Error: object 'results' not found first_roi_fit <- results$fits[[1]] # First ROI's fitted model #> Error: object 'results' not found # } ``` -------------------------------- ### Initializing RSA Model with Multiple Output Metrics (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/roxygen_docs_plan.md This R code demonstrates how to use the `contrast_rsa_model` function to create a Representational Similarity Analysis (RSA) model. It specifies `mvpa_dat` as the dataset and `msreve_des` as the design, requesting three different output metrics: `beta_delta`, `recon_score`, and `beta_only`. This example fulfills the requirement of showing multiple metrics. ```R model_multi_metric <- contrast_rsa_model( dataset = mvpa_dat, design = msreve_des, output_metric = c("beta_delta", "recon_score", "beta_only") ) ``` -------------------------------- ### Examples of creating feature selection specifications in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/feature_selector.html These examples demonstrate how to use the `feature_selector` function to create different feature selection specifications. The first line creates a specification using the 'FTest' method and selecting the top 1000 features. The second line uses 'FTest' to select the top 10% of features. The last line checks the class of the resulting object. ```R fsel <- feature_selector("FTest", "top_k", 1000) fsel <- feature_selector("FTest", "top_p", .1) class(fsel) == "FTest" #> [1] TRUE FALSE FALSE ``` -------------------------------- ### Creating RSA Model with Custom Parameters in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/rsa_model.html This snippet demonstrates creating an RSA model with specific `distmethod` ('pearson') and `regtype` ('lm') parameters. It highlights how to customize the analysis, despite the example noting an error due to `mvpa_data` not being found. ```R rsa_mod_custom <- rsa_model(mvpa_data, rdes, distmethod = "pearson", regtype = "lm") ``` -------------------------------- ### Example Usage of crossv_twofold for Data Preparation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/crossv_twofold.html This example demonstrates the practical application of `crossv_twofold`. It initializes a sample data frame `X`, a response vector `y`, and a `block_var` to simulate input data, then calls `crossv_twofold` with 10 repetitions to generate the cross-validation folds, showcasing typical usage. ```R X <- data.frame(x1 = rnorm(100), x2 = rnorm(100)) y <- rep(letters[1:4], 25) block_var <- rep(1:4, each = 25) cv <- crossv_twofold(X, y, block_var, nreps = 10) ``` -------------------------------- ### Example Usage of `crossv_block` for Data Partitioning in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/crossv_block.html This example demonstrates the practical application of `crossv_block`. It creates synthetic data `X`, a response `y`, and a `block_var` to simulate a dataset. The function is then called to partition `X` and `y` into cross-validation folds based on `block_var`, resulting in the `cv` object containing the prepared training and testing subsets. ```R X <- data.frame(x1 = rnorm(100), x2 = rnorm(100)) y <- rep(letters[1:4], 25) block_var <- rep(1:4, each = 25) cv <- crossv_block(X, y, block_var) ``` -------------------------------- ### Example: Using Sequential Blocked Cross-Validation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/cross_validation.html This example demonstrates how to set up `sequential_blocked_cross_validation`. It defines `block_var`, `nfolds`, and `nreps`, then creates the cross-validation object. It also shows how to prepare sample data and use `crossval_samples` with the sequential specification. ```R block_var <- rep(1:5, each=50) nfolds <- 2 nreps <- 4 cval <- sequential_blocked_cross_validation(block_var, nfolds, nreps) X <- matrix(rnorm(length(block_var) * 10), length(block_var), 10) y <- rep(letters[1:5], length.out=length(block_var)) sam <- crossval_samples(cval, as.data.frame(X), y) ``` -------------------------------- ### Loading and Inspecting MVPA and Caret Models in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/load_model.html These examples demonstrate how to load different types of models using `load_model`, including custom MVPA models like 'sda_notune' and 'corclass', as well as `caret` models such as 'rf' (random forest) and 'svmRadial' (SVM). The examples also show how to access and print the tunable parameters of the loaded models. ```R # Load custom MVPA model model <- load_model("sda_notune") # Load correlation classifier with parameter tuning options corr_model <- load_model("corclass") print(corr_model$parameters) # Load caret's random forest model rf_model <- load_model("rf") print(rf_model$parameters) # Load caret's SVM model svm_model <- load_model("svmRadial") ``` -------------------------------- ### Creating MVPA Dataset with Test Data in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_dataset.html This snippet illustrates how to construct an `mvpa_dataset` that includes both training and test data. It creates a separate `NeuroVec` for the test data and passes it along with the training data and mask to the `mvpa_dataset` function. Similar to the previous example, the errors in the original text indicate missing `NeuroVec` and `NeuroVol` function definitions in the example's execution context. ```R # Create dataset with test data test_vec <- NeuroVec(array(rnorm(1000*20), c(10,10,10,20))) dataset_with_test <- mvpa_dataset(train_vec, test_vec, mask=mask_vol) ``` -------------------------------- ### Creating MVPA Dataset from NeuroVec Objects in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_dataset.html This example demonstrates how to create an `mvpa_dataset` object using `NeuroVec` for training data and `NeuroVol` for the voxel mask. It initializes synthetic `NeuroVec` and `NeuroVol` instances, then passes them to the `mvpa_dataset` function. The errors shown in the original text indicate that `NeuroVec` and `NeuroVol` functions were not found in the example's environment, but the code structure is correct for their intended use. ```R # Create dataset from NeuroVec objects train_vec <- NeuroVec(array(rnorm(1000*100), c(10,10,10,100))) mask_vol <- NeuroVol(array(1, c(10,10,10))) dataset <- mvpa_dataset(train_vec, mask=mask_vol) ``` -------------------------------- ### Running Standard Searchlight Analysis in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/run_searchlight.html This example demonstrates how to perform a standard searchlight analysis using the `run_searchlight` function. It involves generating a sample dataset with categorical responses, setting up cross-validation using data blocks, loading a Shrinkage Discriminant Analysis (SDA) classifier, and creating an MVPA model. Finally, it executes the searchlight with an 8mm radius and 'standard' method, with the `results` object containing the performance metrics. ```R # Generate sample dataset with categorical response dataset <- gen_sample_dataset( D = c(8,8,8), # 8x8x8 volume nobs = 100, # 100 observations response_type = "categorical", data_mode = "image", blocks = 3, # 3 blocks for cross-validation nlevels = 2 # binary classification ) # Create cross-validation specification using blocks cval <- blocked_cross_validation(dataset$design$block_var) # Load the SDA classifier (Shrinkage Discriminant Analysis) model <- load_model("sda_notune") # Create MVPA model mspec <- mvpa_model( model = model, dataset = dataset$dataset, design = dataset$design, model_type = "classification", crossval = cval ) # Run searchlight analysis results <- run_searchlight( mspec, radius = 8, # 8mm radius method = "standard" # Use standard searchlight ) # Results contain performance metrics # Access them with results$performance ``` -------------------------------- ### Example Usage of `crossv_seq_block` for Data Preparation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/crossv_seq_block.html This example demonstrates how to use `crossv_seq_block` to prepare data for sequential block cross-validation. It initializes a data frame `X`, a response vector `y`, and a `block_var` for 100 observations, then calls `crossv_seq_block` with 2 folds to generate the cross-validation data structure. ```R X <- data.frame(x1=rnorm(100), x2=rnorm(100)) y <- rep(letters[1:4], 25) block_var <- rep(1:4, each=25) cv <- crossv_seq_block(X,y,2, block_var) ``` -------------------------------- ### Example: Using Bootstrap Blocked Cross-Validation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/cross_validation.html This example demonstrates how to create a `bootstrap_blocked_cross_validation` object. It initializes a `block_var` and `weights`, then calls the function to create the cross-validation specification. It also shows how to generate sample data and use `crossval_samples` with the created specification. ```R block_var <- rep(1:5, each=50) weights <- runif(length(block_var)) weights[1] = 0 cval <- bootstrap_blocked_cross_validation(block_var, weights=weights) X <- matrix(rnorm(length(block_var) * 10), length(block_var), 10) y <- rep(letters[1:5], length.out=length(block_var)) sam <- crossval_samples(cval, as.data.frame(X), y) ``` -------------------------------- ### Creating a MANOVA Design Object in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/manova_design.html This example demonstrates how to use the `manova_design` function to create a MANOVA design object in R. It defines a formula expression and a named list of placeholder dissimilarity matrices, then calls the function to construct the design object. Note that the example includes comments and shows expected errors because the placeholder matrices are not defined in this context. ```R # Create a MANOVA design formula <- y ~ x1 + x2 data_list <- list(y = dissimilarity_matrix_y, x1 = dissimilarity_matrix_x1, x2 = dissimilarity_matrix_x2) manova_design_obj <- manova_design(formula, data_list) ``` -------------------------------- ### Comparing RDMs with Different Methods in rMVPA (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/RSA.html This snippet demonstrates how to use the `rsa_model` function in the `rMVPA` library to compare neural and model RDMs using various statistical methods. It shows examples for Pearson correlation, linear regression (`lm`), and rank-based regression (`rfit`), highlighting the `distmethod` and `regtype` parameters for specifying the distance metric and regression type, respectively. ```R # Pearson correlation rsa_pearson <- rsa_model(dset, basic_design, distmethod = "pearson", regtype = "pearson") # Linear regression rsa_lm <- rsa_model(dset, basic_design, distmethod = "spearman", regtype = "lm") # Rank-based regression rsa_rfit <- rsa_model(dset, basic_design, distmethod = "spearman", regtype = "rfit") ``` -------------------------------- ### Creating Basic MVPA Design with Training Data (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_design.html This example demonstrates how to initialize a simple `mvpa_design` object using only a training data frame (`train_df`) and specifying the training response variable (`y_train`) as a formula. This is suitable for analyses that do not involve separate test sets or complex cross-validation schemes. ```R # Basic design with only training data train_df <- data.frame(condition = rep(c("A", "B"), each = 50), block = rep(1:5, each = 20), group = rep(c("Group1", "Group2"), 50)) design <- mvpa_design(train_df, y_train = ~ condition) ``` -------------------------------- ### Creating Surface Dataset with Automatic Mask in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_surface_dataset.html This example demonstrates how to create an `mvpa_surface_dataset` object using only training data. It shows the creation of a `NeuroSurfaceVector` for training and then initializes the dataset, allowing the mask to be automatically generated from the training data indices. ```R # Create surface dataset with automatic mask train_surf <- NeuroSurfaceVector(geometry, data) dataset <- mvpa_surface_dataset(train_surf, name="lh") ``` -------------------------------- ### Extracting Multiple Data Samples - rMVPA - R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/get_samples.html This snippet demonstrates the basic usage of the `get_samples` function. It requires an input dataset object (`obj`) and a list of vectors containing voxel indices (`vox_list`) to specify which data points to extract. The function returns a list of data samples, each corresponding to an entry in the provided voxel list, enabling targeted data retrieval for further processing. ```R get_samples(obj, vox_list) ``` -------------------------------- ### Creating Surface Dataset with Test Data and Custom Mask in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_surface_dataset.html This example illustrates creating an `mvpa_surface_dataset` with both optional test data and a custom vertex mask. It shows how to define a `NeuroSurfaceVector` for test data and construct a binary mask vector before initializing the dataset with all parameters. ```R # Create dataset with test data and custom mask test_surf <- NeuroSurfaceVector(geometry, test_data) mask <- numeric(length(nodes(geometry))) mask[roi_indices] <- 1 dataset <- mvpa_surface_dataset(train_surf, test_surf, mask, name="rh") ``` -------------------------------- ### Creating RSA Design - rsa_design Function - R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/rsa_design.html This example demonstrates how to create a simple RSA design using the `rsa_design` function. It first generates a random 100x100 dissimilarity matrix (`dismat`) using `dist` and `rnorm`. Then, it calls `rsa_design` with a formula referencing `dismat` and a list containing the dissimilarity matrix, resulting in an `rsa_design` object (`rdes`) ready for further analysis. ```R dismat <- dist(matrix(rnorm(100*100), 100, 100)) rdes <- rsa_design(~ dismat, list(dismat=dismat)) ``` -------------------------------- ### Combining Sample Model Fits with `weighted_model` in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/weighted_model.html This example demonstrates how to create and combine two sample model fits (`fit1`, `fit2`) using the `weighted_model` function. It shows how to pass a list of fits, assign custom names, and specify explicit weights (0.6 and 0.4) for each model to form a new `w_model` object. ```R # Create two sample model fits fit1 <- list(model = "model1", y = c(0, 1), fit = "fit1") fit2 <- list(model = "model2", y = c(1, 0), fit = "fit2") # Combine the model fits into a weighted consensus model w_model <- weighted_model(fits = list(fit1, fit2), names = c("model1", "model2"), weights = c(0.6, 0.4)) ``` -------------------------------- ### Creating MVPA Design with Test Data and Blocking (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_design.html This R example illustrates how to construct an `mvpa_design` object that includes both training and separate test data frames. It also demonstrates the use of `block_var` for defining a blocking factor, which is crucial for stratified cross-validation in MVPA analyses. ```R # Design with test data and blocking variable test_df <- data.frame(condition = rep(c("A", "B"), each = 25)) design_with_test <- mvpa_design( train_df, test_df, y_train = ~ condition, y_test = ~ condition, block_var = ~ block ) ``` -------------------------------- ### Demonstrating k-fold Cross-Validation Usage in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/kfold_cross_validation.html This example demonstrates how to use `kfold_cross_validation` to create a cross-validation object (`cval`) with 100 observations and 10 folds. It then uses `crossval_samples` to generate samples based on this specification and a sample dataset, finally asserting that the number of rows in the resulting samples is 10. ```R cval <- kfold_cross_validation(len=100, nfolds=10) samples <- crossval_samples(cval, data=as.data.frame(matrix(rnorm(100*10), 100, 10)), y=rep(letters[1:5],20)) stopifnot(nrow(samples) == 10) ``` -------------------------------- ### Performing Regional MVPA with Blocked Cross-Validation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/CrossValidation.html This snippet demonstrates the setup and execution of a regional MVPA analysis using blocked cross-validation. It involves generating a sample dataset, creating a region mask, preparing an MVPA dataset, loading a classification model, defining blocked cross-validation, and running the regional analysis. ```R # Generate a sample dataset data_out <- gen_sample_dataset(D = c(6,6,6), nobs = 80, blocks = 4, nlevels = 2) # Create a region mask mask <- data_out$dataset$mask nvox <- sum(mask) region_mask <- neuroim2::NeuroVol( sample(1:3, size = nvox, replace = TRUE), space(mask), indices = which(mask > 0) ) # Create MVPA dataset dset <- mvpa_dataset(data_out$dataset$train_data, mask = data_out$dataset$mask) # Load the classification model mod <- load_model("sda_notune") tune_grid <- data.frame(lambda = 0.01, diagonal = FALSE) # Example 1: Using Blocked Cross-Validation blocked_cv <- blocked_cross_validation(data_out$design$block_var) mvpa_mod_blocked <- mvpa_model( mod, dataset = dset, design = data_out$design, crossval = blocked_cv, tune_grid = tune_grid ) # Run regional analysis with blocked CV results_blocked <- run_regional(mvpa_mod_blocked, region_mask) ``` -------------------------------- ### Predicting Continuous Values with a Fitted Regression Model in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/predict.regression_model_fit.html This example demonstrates the practical application of the `predict` function with a `regression_model_fit` object. It illustrates the steps involved in preparing new data and then invoking `predict` with both the `fitted_model` and `new_data` to generate predictions. The included comments highlight potential errors if the required objects are not defined. ```R # Assuming `fitted_model` is a fitted model object of class `regression_model_fit` new_data <- iris_dataset$test_data #> Error in eval(expr, envir, enclos): object 'iris_dataset' not found predictions <- predict(fitted_model, new_data) #> Error in predict(fitted_model, new_data): object 'fitted_model' not found ``` -------------------------------- ### Defining MVPA Design Object Parameters (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/mvpa_design.html This R function signature outlines the parameters for creating an `mvpa_design` object. It specifies required arguments like `train_design` and `y_train`, and optional arguments such as `test_design`, `y_test`, `block_var`, and `split_by` for more complex analysis setups. ```R mvpa_design( train_design, test_design = NULL, y_train, y_test = NULL, block_var = NULL, split_by = NULL, ... ) ``` -------------------------------- ### Generating Dataset with External Test Set in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/gen_sample_dataset.html This example shows how to generate a synthetic dataset that includes a separate external test set using `gen_sample_dataset`. It configures the dataset for categorical responses with multiple levels and explicitly enables the `external_test` option, which is crucial for evaluating model generalization. ```R # Generate dataset with external test set test_dataset <- gen_sample_dataset( D = c(8,8,8), nobs = 80, response_type = "categorical", nlevels = 3, external_test = TRUE ) ``` -------------------------------- ### Generating Categorical Image Dataset in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/gen_sample_dataset.html This example demonstrates how to use `gen_sample_dataset` to create a synthetic categorical image dataset. It specifies dimensions, number of observations, response type, data mode, blocks, and number of levels, suitable for testing image-based MVPA with discrete categories. ```R # Generate categorical image dataset dataset <- gen_sample_dataset( D = c(10,10,10), nobs = 100, response_type = "categorical", data_mode = "image", blocks = 3, nlevels = 2 ) ``` -------------------------------- ### Visualizing Intra-Run Exclusions in RSA (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/RSA.html This R snippet illustrates the effect of excluding within-run comparisons in RSA by creating a small example dataset with two runs. It generates a distance matrix and a comparison matrix, showing which trial pairs are considered 'across-run' (TRUE) versus 'within-run' (FALSE) based on their run labels, helping to visualize the `keep_intra_run = FALSE` logic. ```R # Create a small example with 2 runs, 4 trials each mini_data <- matrix(1:8, ncol=1) # Trial numbers 1-8 run_labels <- c(1,1,1,1, 2,2,2,2) # Two runs with 4 trials each # Create distance matrix d <- dist(mini_data) d_mat <- as.matrix(d) # Show which comparisons are kept (TRUE) or excluded (FALSE) comparison_matrix <- outer(run_labels, run_labels, "!=") # Only show lower triangle to match distance matrix structure comparison_matrix[upper.tri(comparison_matrix)] <- NA # Display the matrices cat("Trial numbers:\n") print(matrix(1:8, nrow=8, ncol=8)[lower.tri(matrix(1:8, 8, 8))]) cat("\nRun comparisons (TRUE = across-run, FALSE = within-run):\n") print(comparison_matrix[lower.tri(comparison_matrix)]) ``` -------------------------------- ### Applying FTest Feature Selection with Top-p Cutoff to Data (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/FeatureSelection.html This example illustrates applying feature selection using the 'FTest' method with a 'top_p' cutoff to simulated data. A feature selector is configured to select the top 10% of features (cutoff_value = 0.1). The `select_features()` function is then used to apply this selection, and the resulting proportion of selected features is calculated and printed, confirming the 10% selection. ```R # Apply feature selection using the FTest method with top_p cutoff (select top 10% of features) fsel <- feature_selector(method = "FTest", cutoff_type = "top_p", cutoff_value = 0.1) selected_features <- select_features(fsel, X, Y) # Calculate the proportion of features selected the_proportion <- sum(selected_features) / ncol(X) cat("Proportion of features selected (top_p):", the_proportion, "\n") ``` -------------------------------- ### Example: Using Blocked Cross-Validation in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/reference/cross_validation.html This example illustrates the usage of `blocked_cross_validation`. It defines a `block_var` and then creates a cross-validation specification. It also includes sample data generation and the application of `crossval_samples` to the generated data. ```R block_var <- rep(1:5, each=50) cval <- blocked_cross_validation(block_var) X <- matrix(rnorm(length(block_var) * 10), length(block_var), 10) y <- rep(letters[1:5], length.out=length(block_var)) sam <- crossval_samples(cval, as.data.frame(X), y) ``` -------------------------------- ### Defining run_searchlight.contrast_rsa_model S3 Method in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/contrast_rsa_plan.md This S3 method orchestrates the execution of a searchlight analysis for the `contrast_rsa_model`. It internally calls `run_searchlight_base`, passing `msreve_iterate` as the `mvpa_fun` (iterator) and `combine_msreve_standard` as the `combiner`. This method serves as the high-level entry point for users to run the contrast RSA searchlight. ```R run_searchlight.contrast_rsa_model <- function(obj, ...) { # Define the method signature and handle method-specific arguments # For now, only supporting a "standard" method # Call run_searchlight_base internally searchlight_results <- run_searchlight_base( model_spec = obj, mvpa_fun = msreve_iterate, combiner = combine_msreve_standard, ... ) return(searchlight_results) } ``` -------------------------------- ### Downloading rMVPA command line scripts with wget Source: https://github.com/bbuchsbaum/rmvpa/blob/master/README.md This snippet provides commands to download optional 'coding-free' MVPA analysis scripts (MVPA_Searchlight.R and MVPA_Regional.R) directly from the rMVPA GitHub repository using wget. These scripts enable command-line execution of MVPA analyses. ```Bash wget https://raw.githubusercontent.com/bbuchsbaum/rMVPA/master/scripts/MVPA_Searchlight.R wget https://raw.githubusercontent.com/bbuchsbaum/rMVPA/master/scripts/MVPA_Regional.R ``` -------------------------------- ### Executing MVPA Script with Configuration File Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/CommandLineScripts.html This command-line snippet demonstrates how to run the `MVPA_Searchlight.R` script using a specified configuration file. The `--config=config.yaml` argument tells the R script to load all its analysis parameters from the `config.yaml` file, streamlining the execution process and ensuring consistency and reproducibility across runs. ```Bash Rscript MVPA_Searchlight.R --config=config.yaml ``` -------------------------------- ### Downloading rMVPA command-line analysis scripts with wget Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/index.html These commands download two R scripts, `MVPA_Searchlight.R` and `MVPA_Regional.R`, which are designed for 'coding-free' MVPA analysis. They are retrieved directly from the rMVPA GitHub repository using the `wget` utility. ```Shell wget https://raw.githubusercontent.com/bbuchsbaum/rMVPA/master/scripts/MVPA_Searchlight.R wget https://raw.githubusercontent.com/bbuchsbaum/rMVPA/master/scripts/MVPA_Regional.R ``` -------------------------------- ### Implementing train_model.contrast_rsa_model Method in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/contrast_rsa_plan.md This S3 method is the core of the `contrast_rsa_model`'s training process. It takes the model object, searchlight data, and searchlight info. The method orchestrates several steps: computing cross-validated means, calculating the G-matrix, preparing RSA regression inputs, running the regression, computing the Delta matrix, extracting the center voxel's projection, and finally calculating a Q-dimensional result vector based on the specified output metric. ```R train_model.contrast_rsa_model <- function(obj, sl_data, sl_info) { # Step 1: Call compute_crossvalidated_means_sl to get Û_sl Û_sl <- compute_crossvalidated_means_sl( sl_data = sl_data, mvpa_design_obj = obj$design$mvpa_design, cv_spec_obj = obj$design$cv_spec, # Assuming cv_spec is part of msreve_design estimation_method = obj$estimation_method ) # Step 2: Compute Ĝ_sl = Û_sl %*% t(Û_sl) Ĝ_sl <- Û_sl %*% t(Û_sl) # Step 3: Prepare RSA regression inputs dvec_sl <- as.vector(Ĝ_sl) # Vectorize Ĝ_sl # Create predictor matrix X_sl from obj$design$contrast_matrix # This would involve adapting or reusing rsa_model_mat logic X_sl <- rsa_model_mat(obj$design$contrast_matrix) # Conceptual call # Step 4: Run regression (using obj$regression_type) to get β_sl (Q-vector) # Reuse existing regression functions like run_lm, run_lm_constrained β_sl <- run_lm(dvec_sl, X_sl, type = obj$regression_type) # Conceptual call # Step 5: Compute Δ_sl = t(Û_sl) %*% C (V_sl x Q matrix) Δ_sl <- t(Û_sl) %*% obj$design$contrast_matrix # Step 6: Extract center voxel's projection Δ_{v_c,sl} (Q-vector) using sl_info center_voxel_id <- sl_info$center_voxel_id # Assuming sl_info provides this # Need to map center_voxel_id to its row index within sl_data/Δ_sl # This mapping depends on how sl_data is structured relative to original dataset center_voxel_row_idx <- which(sl_data$voxel_ids == center_voxel_id) # Conceptual mapping Δ_vc_sl <- Δ_sl[center_voxel_row_idx, , drop = FALSE] # Step 7: Calculate the final result_vector based on obj$output_metric result_vector <- switch( obj$output_metric, "beta_delta_product" = as.vector(β_sl * Δ_vc_sl), # Example metric # Add other output metrics as needed stop(paste("Unsupported output_metric:", obj$output_metric)) ) # Step 8: Return the named result_vector (Q-dimensional) # Names should correspond to the contrasts names(result_vector) <- colnames(obj$design$contrast_matrix) # Assuming contrast matrix has column names # Add robust error handling if (any(is.na(result_vector))) { warning("NA values in result_vector for searchlight.") } return(result_vector) } ``` -------------------------------- ### Creating contrast_rsa_model S3 Class Constructor in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/contrast_rsa_plan.md This snippet defines the constructor for the `contrast_rsa_model` S3 class, which inherits from `mvpa_model_spec`. The constructor takes an `mvpa_dataset`, an `msreve_design` object, and parameters like `estimation_method`, `regression_type`, and `output_metric`. It's crucial that it internally uses `create_model_spec` for proper instantiation. ```R contrast_rsa_model <- function(mvpa_dataset_obj, msreve_design_obj, estimation_method = "average_betas", regression_type = "ols", output_metric = "beta_delta_product") { # Input validation if (!inherits(mvpa_dataset_obj, "mvpa_dataset")) stop("mvpa_dataset_obj must be an mvpa_dataset object.") if (!inherits(msreve_design_obj, "msreve_design")) stop("msreve_design_obj must be an msreve_design object.") # Crucially, use create_model_spec internally model_spec <- create_model_spec( "contrast_rsa_model", dataset = mvpa_dataset_obj, design = msreve_design_obj, estimation_method = estimation_method, regression_type = regression_type, output_metric = output_metric ) # Additional validation or setup specific to contrast_rsa_model # For example, ensure contrast_matrix is valid if (is.null(msreve_design_obj$contrast_matrix)) { stop("msreve_design_obj must contain a 'contrast_matrix'.") } return(model_spec) } ``` -------------------------------- ### Creating and Running RSA Model with Searchlight Analysis (R) Source: https://github.com/bbuchsbaum/rmvpa/blob/master/docs/articles/RSA.html This snippet demonstrates the full process of setting up and running an RSA model, including creating an MVPA dataset, defining the RSA model with specified dissimilarity and regression methods (e.g., Spearman), and executing a searchlight analysis to map results across the brain volume. ```R dset <- mvpa_dataset(dataset$dataset$train_data, mask=dataset$dataset$mask) rsa_spearman <- rsa_model( dataset = dset, design = basic_design, distmethod = "spearman", regtype = "spearman" ) results <- run_searchlight( rsa_spearman, radius = 4, method = "standard" ) ``` -------------------------------- ### Making rMVPA command line scripts executable Source: https://github.com/bbuchsbaum/rmvpa/blob/master/README.md After downloading the MVPA analysis scripts, this snippet shows how to make them executable using the chmod command. This is a necessary step before moving them to your system's PATH for direct execution. ```Bash chmod +x MVPA_Searchlight.R chmod +x MVPA_Regional.R ``` -------------------------------- ### Defining msreve_design S3/S4 Class in R Source: https://github.com/bbuchsbaum/rmvpa/blob/master/contrast_rsa_plan.md This snippet outlines the conceptual structure for the `msreve_design` S3/S4 class, which serves as a container for an `mvpa_design` object and a user-defined `contrast_matrix`. It also suggests an optional helper function to orthogonalize contrasts, enhancing design flexibility. ```R # Conceptual S3 class definition for msreve_design msreve_design <- function(mvpa_design_obj, contrast_matrix_C) { obj <- list( mvpa_design = mvpa_design_obj, contrast_matrix = contrast_matrix_C # K x Q matrix ) class(obj) <- "msreve_design" return(obj) } # Optional helper function to orthogonalize contrasts orthogonalize_contrasts <- function(C) { # Implementation logic for orthogonalizing the contrast matrix C # This might involve QR decomposition or similar linear algebra operations. message("Orthogonalizing contrast matrix...") C_orthogonalized <- C # Placeholder return(C_orthogonalized) } ```