### Quick Start MOFA Model Training Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Create a MOFA model with default settings and immediately prepare and train it. This is suitable for initial exploration or when default parameters are sufficient. ```r model <- create_mofa(data) model <- prepare_mofa(model) # Uses all defaults model <- run_mofa(model, use_basilisk = TRUE) ``` -------------------------------- ### MOFA2 Workflow Example Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Demonstrates a typical workflow for MOFA2, including loading data, creating a MOFA object, checking dimensions, customizing factor names, preparing, training, and evaluating the model using ELBO. ```r # Load example data file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) # Create MOFA object model <- create_mofa(dt) # Check dimensions dims <- get_dimensions(model) print(dims) # Customize factor names factors_names(model) <- paste0("LF_", 1:dims$K) # Prepare model for training model <- prepare_mofa(model) # Train model model <- run_mofa(model, use_basilisk = TRUE) # Check model quality elbo <- get_elbo(model) cat("ELBO:", elbo, "\n") ``` -------------------------------- ### Prepare MOFA Model with Default Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Initializes a MOFA object and then prepares it for training using default data, model, and training options. This is a common starting point for model training. ```r # Create MOFA object model <- create_mofa(data) # Prepare with default options model <- prepare_mofa(model) ``` -------------------------------- ### Minimal MOFA2 Workflow Source: https://github.com/biofam/mofa2/blob/master/_autodocs/INDEX.md This snippet demonstrates the essential steps for using MOFA2: loading data, creating a MOFA object, preparing the model, running the training, and visualizing the results. It's suitable for a quick start and basic analysis. ```r library(MOFA2) # Load example data file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) # Create → Prepare → Train model <- create_mofa(dt) model <- prepare_mofa(model) model <- run_mofa(model, use_basilisk = TRUE) # Analyze results plot_variance_explained(model, x = "view", y = "factor") plot_factors(model, factors = c(1, 2), color_by = "group") ``` -------------------------------- ### Create Simulated MOFA Example Data Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-analysis.md Generate synthetic multi-omics data for testing and demonstration purposes. Allows customization of views, samples, features, and factors. ```r make_example_data(n_views = 3, n_samples = 200, n_features = list(1000, 500, 800), n_factors = 5, n_groups = 1) ``` ```r # Create example data data <- make_example_data(n_views = 2, n_samples = 100, n_factors = 5) # Use for quick testing model <- create_mofa(data$data) model <- prepare_mofa(model) ``` -------------------------------- ### Configure Model Options for MOFA2 Training Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Set the number of latent factors and ARD options for MOFA2. This example configures for 15 factors and enables sparsity on weights while disabling factor-level sparsity. ```r model_opts <- get_default_model_options(model) # Configure for 15 factors model_opts$num_factors <- 15 # Enable sparsity on weights model_opts$ard_weights <- TRUE # Disable factor-level sparsity model_opts$ard_factors <- FALSE model <- prepare_mofa(model, model_options = model_opts) ``` -------------------------------- ### MOFA2 Training Workflow Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md A step-by-step example demonstrating the complete MOFA2 training process, from loading data to saving and later loading the trained model. This workflow covers data preparation, option customization, model training, and persistence. ```r # Step 1: Load data file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) # Step 2: Create MOFA object model <- create_mofa(dt) print(model) # Shows untrained model info # Step 3: Get and customize options data_opts <- get_default_data_options(model) model_opts <- get_default_model_options(model) train_opts <- get_default_training_options(model) # Customize options data_opts$scale_views <- TRUE model_opts$num_factors <- 10 model_opts$ard_weights <- TRUE train_opts$maxiter <- 1000 train_opts$convergence_mode <- "fast" # Step 4: Prepare model model <- prepare_mofa(model, data_options = data_opts, model_options = model_opts, training_options = train_opts ) # Step 5: Train model model <- run_mofa(model, use_basilisk = TRUE) print(model) # Shows trained model info # Step 6: Save model saveRDS(model, file = "trained_model.rds") # Later: Load model model <- readRDS("trained_model.rds") # or from HDF5: model <- load_model("model.hdf5") ``` -------------------------------- ### samples_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set sample names per group for a MOFA object. ```APIDOC ## samples_names ### Description Get or set sample names per group. ### Method `samples_names(object)` `samples_names(object) <- value` ### Return List of character vectors (one per group) with sample names. ``` -------------------------------- ### Get and Set Sample Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of samples for each group within the MOFA object. ```r samples_names(object) ``` ```r samples_names(object) <- value ``` -------------------------------- ### Get Default Training Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves a list of default hyperparameters for MOFA model training. These include settings for maximum iterations, convergence criteria, and output file paths. ```r get_default_training_options(object) ``` -------------------------------- ### Get and Set Sample Metadata Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the sample metadata data frame. This data frame must include 'sample' and 'group' columns, along with any other relevant metadata. ```r samples_metadata(object) ``` ```r samples_metadata(object) <- value ``` -------------------------------- ### samples_metadata Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set the sample metadata data frame for a MOFA object. The data frame must include 'sample' and 'group' columns. ```APIDOC ## samples_metadata ### Description Get or set sample metadata data frame. ### Method `samples_metadata(object)` `samples_metadata(object) <- value` ### Return Data frame with samples as rows. Must contain columns: "sample", "group", plus any additional metadata columns. ``` -------------------------------- ### Get Default Stochastic Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves default options for stochastic variational inference. This is applicable when `training_options$stochastic` is set to TRUE and is recommended for very large datasets. ```r get_default_stochastic_options(object) ``` -------------------------------- ### Get Default MEFISTO Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves default options for MEFISTO, which extends MOFA to incorporate sample covariates. These options control the modeling of group-group covariance, covariates, and interactions. ```r get_default_mefisto_options(object) ``` -------------------------------- ### Get Default Model Options for MOFA Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves the default list of model configuration options for a MOFA object. This includes settings for the number of factors, likelihoods per view, and automatic relevance determination (ARD). ```r get_default_model_options(object) ``` -------------------------------- ### Get Default Data Options for MOFA Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves the default list of data preprocessing options for a MOFA object. These options control aspects like view and group scaling, centering, and memory usage. ```r get_default_data_options(object) ``` -------------------------------- ### Get Variance Explained Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-data.md Extracts the variance explained by the MOFA model across views and factors. Provides R-squared values per factor and total R-squared per view. ```r r2 <- get_variance_explained(model) r2$r2_per_factor # Variance explained per factor r2$r2_total # Total variance explained per view ``` -------------------------------- ### groups_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set group names for a MOFA object. ```APIDOC ## groups_names ### Description Get or set group names. ### Method `groups_names(object)` `groups_names(object) <- value` ### Return Character vector of group names. ``` -------------------------------- ### features_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set feature names per view for a MOFA object. ```APIDOC ## features_names ### Description Get or set feature names per view. ### Method `features_names(object)` `features_names(object) <- value` ### Return List of character vectors (one per view) with feature names. ``` -------------------------------- ### Get and Set Group Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of the groups in the MOFA object. ```r groups_names(object) ``` ```r groups_names(object) <- value ``` -------------------------------- ### Get and Set Feature Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of features for each view within the MOFA object. ```r features_names(object) ``` ```r features_names(object) <- value ``` -------------------------------- ### Prepare MOFA Model with Custom Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Prepares a MOFA object for training using custom-defined data, model, and training options. This allows fine-tuning of parameters like the number of factors, scaling, and training convergence. ```r # Create MOFA object model <- create_mofa(data) # Prepare with custom options model_opts <- get_default_model_options(model) model_opts$num_factors <- 10 model_opts$ard_weights <- TRUE data_opts <- get_default_data_options(model) data_opts$scale_views <- TRUE train_opts <- get_default_training_options(model) train_opts$maxiter <- 500 train_opts$convergence_mode <- "fast" model <- prepare_mofa(model, data_options = data_opts, model_options = model_opts, training_options = train_opts ) ``` -------------------------------- ### views_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set view names for a MOFA object. The number of names must match the number of views (M). ```APIDOC ## views_names ### Description Get or set view names. ### Method `views_names(object)` `views_names(object) <- value` ### Parameters #### Setter Parameters - `value` (character) - Required - New view names (length must equal M) ### Return Character vector of view names. ``` -------------------------------- ### factors_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set factor names for a MOFA object. The number of names must match the number of factors (K). ```APIDOC ## factors_names ### Description Get or set factor names. ### Method `factors_names(object)` `factors_names(object) <- value` ### Parameters #### Path Parameters - `object` (MOFA) - Required - A MOFA object #### Setter Parameters - `value` (character) - Required - New factor names (length must equal K) ### Return Character vector of factor names. ``` -------------------------------- ### make_example_data Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-analysis.md Creates simulated multi-omics data for testing and learning purposes. This function allows users to generate synthetic datasets with specified characteristics. ```APIDOC ## make_example_data ### Description Create simulated multi-omics data for testing and learning. ### Method ```r make_example_data(n_views = 3, n_samples = 200, n_features = list(1000, 500, 800), n_factors = 5, n_groups = 1) ``` ### Parameters #### Parameters - **n_views** (integer) - Optional - Number of views (omics modalities) (default: 3) - **n_samples** (integer) - Optional - Number of samples (default: 200) - **n_features** (list/integer) - Optional - Number of features per view (default: c(1000, 500, 800)) - **n_factors** (integer) - Optional - Number of latent factors (default: 5) - **n_groups** (integer) - Optional - Number of groups (default: 1) ### Return List containing: - `data`: List of data matrices (views) - `factors`: True factor values - `weights`: True weights - `covariance`: Covariance matrix ### Examples ```r # Create example data data <- make_example_data(n_views = 2, n_samples = 100, n_factors = 5) # Use for quick testing model <- create_mofa(data$data) model <- prepare_mofa(model) ``` ``` -------------------------------- ### prepare_mofa Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Prepares a MOFA object for training by setting various options related to data preprocessing, model configuration, and training hyperparameters. It validates these options against predefined rules and provides warnings for potential issues. ```APIDOC ## prepare_mofa ### Description Prepare a MOFA object for training by setting all necessary options. ### Method `prepare_mofa(object, data_options = NULL, model_options = NULL, training_options = NULL, stochastic_options = NULL, mefisto_options = NULL)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (MOFA) - Required - An untrained MOFA object (created via `create_mofa()`) - **data_options** (list) - Optional - Data preprocessing options. If NULL, uses defaults from `get_default_data_options()` - **model_options** (list) - Optional - Model configuration options. If NULL, uses defaults from `get_default_model_options()` - **training_options** (list) - Optional - Training hyperparameters. If NULL, uses defaults from `get_default_training_options()` - **stochastic_options** (list) - Optional - Stochastic inference options (only used if `training_options$stochastic = TRUE`) - **mefisto_options** (list) - Optional - MEFISTO-specific options (only needed for covariates) ### Request Example ```r # Create MOFA object model <- create_mofa(data) # Prepare with default options model <- prepare_mofa(model) # Prepare with custom options model_opts <- get_default_model_options(model) model_opts$num_factors <- 10 model_opts$ard_weights <- TRUE data_opts <- get_default_data_options(model) data_opts$scale_views <- TRUE train_opts <- get_default_training_options(model) train_opts$maxiter <- 500 train_opts$convergence_mode <- "fast" model <- prepare_mofa(model, data_options = data_opts, model_options = model_opts, training_options = train_opts ) ``` ### Response #### Success Response (200) An untrained MOFA object with options populated in the corresponding slots. #### Response Example None provided in source. ``` -------------------------------- ### covariates_names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set covariate names for MEFISTO models in a MOFA object. The number of names must match the number of covariates (C). ```APIDOC ## covariates_names ### Description Get or set covariate names (for MEFISTO models). ### Method `covariates_names(object)` `covariates_names(object) <- value` ### Parameters #### Setter Parameters - `value` (character) - Required - New covariate names (length must equal C) ### Return Character vector of covariate names. ### Throws - Error if no covariates present in object ``` -------------------------------- ### MOFA2 Quick Reference Cheat Sheet Source: https://github.com/biofam/mofa2/blob/master/_autodocs/README.md A collection of essential R commands for creating, configuring, training, accessing results, visualizing, analyzing, and saving MOFA2 models. Useful for quick lookups during development. ```r # Create model model <- create_mofa(data, groups = groups) # Configure & train model <- prepare_mofa(model) model <- run_mofa(model, use_basilisk = TRUE) # Access results Z <- get_factors(model) W <- get_weights(model) r2 <- calculate_variance_explained(model) # Visualize plot_factors(model, factors = 1:2, color_by = "group") plot_variance_explained(model) plot_weights_heatmap(model, view = 1) # Analyze model <- run_umap(model) plot_dimred(model, method = "UMAP") # Save save(model, file = "model.RData") ``` -------------------------------- ### features_metadata Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Get or set the feature metadata data frame for a MOFA object. The data frame must include 'feature' and 'view' columns. ```APIDOC ## features_metadata ### Description Get or set feature metadata data frame. ### Method `features_metadata(object)` `features_metadata(object) <- value` ### Return Data frame with features as rows. Must contain columns: "feature", "view", plus any additional metadata columns. ``` -------------------------------- ### Run MOFA Model Training Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Trains the MOFA model using the mofapy2 Python backend. It can automatically set up the Python environment using basilisk or use a manually configured environment. ```r run_mofa(object, outfile = NULL, save_data = TRUE, use_basilisk = FALSE) ``` ```r reticulate::use_python("/path/to/python", force = TRUE) reticulate::use_condaenv("mofa_env", force = TRUE) ``` ```r # Standard workflow file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) model <- create_mofa(dt) model <- prepare_mofa(model) # Option 1: Train with automatic environment setup (recommended) model <- run_mofa(model, use_basilisk = TRUE) # Option 2: Train with manual Python setup # reticulate::use_condaenv("mofa_env", force = TRUE) # model <- run_mofa(model, use_basilisk = FALSE) # Save model to specific location model <- run_mofa(model, outfile = "my_model.hdf5", use_basilisk = TRUE) ``` -------------------------------- ### Get and Set View Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of the views in the MOFA object. The length of the new names must match the number of views (M). ```r views_names(object) ``` ```r views_names(object) <- value ``` -------------------------------- ### Create MOFA object from MultiAssayExperiment Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Construct a MOFA object from a MultiAssayExperiment, where each experiment in the MAE becomes a view. Metadata can be extracted from colData. ```r # Assuming mae is a MultiAssayExperiment with RNA, CNV, and Methylation data model <- create_mofa_from_MultiAssayExperiment(mae, groups = "disease_status") ``` -------------------------------- ### Get Group Kernel Covariance Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-data.md Extracts the inferred group-group covariance matrix for each factor from a trained MOFA model. This is useful when model_groups is set to TRUE. ```r Kg <- get_group_kernel(model) # Kg[[1]] is the group covariance matrix for factor 1 ``` -------------------------------- ### Standard MOFA Model Configuration and Training Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Customize data scaling, model factor count, and training convergence criteria. Prepare and train the MOFA model with these specific options. ```r model <- create_mofa(data) # Customize options data_opts <- get_default_data_options(model) data_opts$scale_views <- TRUE model_opts <- get_default_model_options(model) model_opts$num_factors <- 15 train_opts <- get_default_training_options(model) train_opts$convergence_mode <- "medium" train_opts$maxiter <- 1500 # Prepare and train model <- prepare_mofa(model, data_options = data_opts, model_options = model_opts, training_options = train_opts ) model <- run_mofa(model, use_basilisk = TRUE) ``` -------------------------------- ### Get Factor Scales Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-data.md Extracts inferred scales for Gaussian Process factors from a trained MOFA model. Use this to understand the magnitude of variation for each factor. ```r get_scales(object) ``` -------------------------------- ### Complete MOFA2 Workflow Source: https://github.com/biofam/mofa2/blob/master/_autodocs/INDEX.md This comprehensive workflow covers the entire MOFA2 process from object creation and configuration to training, quality control, visualization, downstream analysis, and saving the model. It is useful for users who need to perform in-depth multi-omics factor analysis. ```r # 1. Create MOFA object from various input formats model <- create_mofa(data, groups = groups) # data.frame, list of matrices, Seurat, etc. # 2. Configure options model_opts <- get_default_model_options(model) model_opts$num_factors <- 15 train_opts <- get_default_training_options(model) train_opts$convergence_mode <- "slow" # 3. Prepare model model <- prepare_mofa(model, data_options = get_default_data_options(model), model_options = model_opts, training_options = train_opts ) # 4. Train model <- run_mofa(model, use_basilisk = TRUE) # 5. Quality control r2 <- calculate_variance_explained(model) dims <- get_dimensions(model) # 6. Visualization plot_variance_explained(model, x = "view", y = "factor") plot_factor(model, factors = 1:3, color_by = "metadata_column") # 7. Downstream analysis model <- run_umap(model) model <- cluster_samples(model, k = 5) enr <- run_enrichment(model, view = "RNA", feature.sets = gene_sets) # 8. Save model save(model, file = "trained_model.RData") ``` -------------------------------- ### Get and Set Factor Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of the factors in a MOFA object. The length of the new names must match the number of factors (K). ```r names <- factors_names(model) factors_names(model) <- paste0("Factor_", 1:length(names)) ``` -------------------------------- ### Configure Data Options for MOFA2 Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Set data preprocessing options such as scaling and centering for views and groups. Use float32 for memory efficiency on large datasets. ```r data_opts <- get_default_data_options(model) # Scale views to unit variance data_opts$scale_views <- TRUE # Don't scale groups data_opts$scale_groups <- FALSE # Don't center groups data_opts$center_groups <- FALSE # Use float32 for memory efficiency data_opts$use_float32 <- TRUE model <- prepare_mofa(model, data_options = data_opts) ``` -------------------------------- ### Configure General Training Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Adjusts general training parameters such as maximum iterations, ELBO computation frequency, and convergence mode. Use this to fine-tune the training process for desired convergence speed and accuracy. ```r train_opts <- get_default_training_options(model) # Use more iterations for slow convergence train_opts$maxiter <- 2000 # Start computing ELBO early train_opts$startELBO <- 1 # Compute ELBO frequently to monitor convergence train_opts$freqELBO <- 5 # Use strict convergence for final model train_opts$convergence_mode <- "slow" model <- prepare_mofa(model, training_options = train_opts) ``` -------------------------------- ### Get Factor Lengthscales Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-data.md Extracts inferred lengthscales for Gaussian Process factors from a trained MOFA model. Use this to understand the smoothness of variation along covariates for each factor. ```r ls <- get_lengthscales(model) plot(ls, main = "Factor Lengthscales") ``` -------------------------------- ### Create MOFA object from list of matrices Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Initialize a MOFA object using a named list of matrices, where each matrix represents a view. Matrices should have features as rows and samples as columns. Supports dense or sparse matrices. ```r data <- list( RNA = matrix(rnorm(1000*100), 1000, 100), CNA = matrix(rnorm(500*100), 500, 100), Methylation = matrix(rnorm(2000*100), 2000, 100) ) model <- create_mofa_from_matrix(data) ``` ```r groups <- rep(c("Group_A", "Group_B"), each=50) model <- create_mofa_from_matrix(data, groups=groups) ``` -------------------------------- ### Get and Set Feature Metadata Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the feature metadata data frame. This data frame must include 'feature' and 'view' columns, along with any other relevant metadata. ```r features_metadata(object) ``` ```r features_metadata(object) <- value ``` -------------------------------- ### Configure MEFISTO for Spatial Data Analysis Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Set up spatial coordinates and covariates, then configure MEFISTO options for spatial smoothing and a fine interpolation grid. Prepare the model with these spatial configurations. ```r # Set up spatial coordinates (2D) spatial_coords <- matrix(rnorm(2 * n_samples), nrow = 2) rownames(spatial_coords) <- c("x", "y") # Create covariates covariates <- list(group1 = spatial_coords[, 1:50]) # Configure for spatial analysis model <- set_covariates(model, covariates = covariates) mefisto_opts <- get_default_mefisto_options(model) mefisto_opts$GP_factors <- TRUE # Use GP for spatial smoothing mefisto_opts$n_grid <- 200 # Fine interpolation grid model <- prepare_mofa(model, mefisto_options = mefisto_opts) ``` -------------------------------- ### MOFA Model Configuration Options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/types.md Outlines the five slots that store configuration options for the MOFA model: data_options, model_options, training_options, stochastic_options, and mefisto_options. All are named lists. ```r # Data options model@data_options$scale_views model@data_options$scale_groups # Model options model@model_options$num_factors model@model_options$likelihoods # Training options model@training_options$maxiter model@training_options$convergence_mode # Stochastic options (if applicable) model@stochastic_options$batch_size model@stochastic_options$learning_rate # MEFISTO options (if applicable) model@mefisto_options$GP_factors model@mefisto_options$model_groups ``` -------------------------------- ### create_mofa_from_MultiAssayExperiment Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Creates a MOFA object from a MultiAssayExperiment object, where each experiment becomes a view. Metadata can also be extracted. ```APIDOC ## create_mofa_from_MultiAssayExperiment ### Description Create MOFA object from a MultiAssayExperiment object. ### Method create_mofa_from_MultiAssayExperiment(mae, groups = NULL, extract_metadata = FALSE) ### Parameters #### MultiAssayExperiment Input - **mae** (MultiAssayExperiment) - Required - A MultiAssayExperiment object where experiments become views. - **groups** (character) - Optional - Column name in colData or vector of group assignments. - **extract_metadata** (logical) - Optional - Whether to extract sample metadata from colData. ### Return An untrained `MOFA` object with one view per experiment in the MultiAssayExperiment. ### Examples ```r # Assuming mae is a MultiAssayExperiment with RNA, CNV, and Methylation data model <- create_mofa_from_MultiAssayExperiment(mae, groups = "disease_status") ``` ``` -------------------------------- ### Get MOFA Model Dimensions Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Extracts dimensionalities of the MOFA model, including the number of views, groups, samples per group, features per view, factors, and covariates. ```r file <- system.file("extdata", "model.hdf5", package = "MOFA2") model <- load_model(file) dims <- get_dimensions(model) dims$K # number of factors dims$M # number of views ``` -------------------------------- ### create_mofa Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Generic constructor that creates an untrained MOFA object from various input data formats. It handles data, groups, and metadata extraction, passing additional arguments to format-specific creation functions. ```APIDOC ## create_mofa ### Description Generic constructor that creates a MOFA object from various input formats. ### Method create_mofa ### Parameters #### Arguments - **data** (various) - Required - Input data in one of multiple formats: data.frame (long format), list of matrices, Seurat object, SingleCellExperiment, or MultiAssayExperiment - **groups** (character/numeric/vector) - Optional - Group assignment for samples. Can be a column name (for data.frame inputs), a vector of group labels, or NULL for single group - **extract_metadata** (logical) - Optional - Whether to extract sample/feature metadata from input object - **...** (—) - Optional - Additional arguments passed to format-specific creation functions ### Return An untrained `MOFA` object with data and metadata populated. ### Throws - Error if data format is not recognized - Error if groups are specified but don't match sample count ### Examples ```r # From long-format data.frame file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) model <- create_mofa(dt) # From list of matrices (features × samples) data_matrices <- list( view1 = matrix(rnorm(100*50), 100, 50), view2 = matrix(rnorm(80*50), 80, 50) ) model <- create_mofa(data_matrices) # From Seurat object model <- create_mofa(seurat_obj, extract_metadata = TRUE) ``` ``` -------------------------------- ### create_mofa_from_matrix Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Creates a MOFA object from a list of matrices. Each matrix in the list represents a view, with features as rows and samples as columns. ```APIDOC ## create_mofa_from_matrix ### Description Create MOFA object from a list of matrices. ### Method create_mofa_from_matrix(data, groups = NULL) ### Parameters #### Matrix Input - **data** (list) - Required - Named list of matrices where names are view names. Each matrix must have features as rows and samples as columns. Can be dense (matrix) or sparse (dgCMatrix, dgTMatrix). - **groups** (character/numeric) - Optional - Group assignment vector with length equal to number of columns (samples). ### Return An untrained `MOFA` object. ### Examples ```r # Create from list of matrices data <- list( RNA = matrix(rnorm(1000*100), 1000, 100), CNA = matrix(rnorm(500*100), 500, 100), Methylation = matrix(rnorm(2000*100), 2000, 100) ) model <- create_mofa_from_matrix(data) # With group structure groups <- rep(c("Group_A", "Group_B"), each=50) model <- create_mofa_from_matrix(data, groups=groups) ``` ``` -------------------------------- ### Load MOFA2 Model from HDF5 File Source: https://github.com/biofam/mofa2/blob/master/_autodocs/INDEX.md Load a trained MOFA2 model from an HDF5 file. This is the standard format for saving and sharing MOFA2 models. ```r model <- load_model("path/to/model.hdf5") ``` -------------------------------- ### Get and Set Covariate Names Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Retrieves or sets the names of covariates for MEFISTO models. The length of the new names must match the number of covariates (C). An error is thrown if no covariates are present. ```r covariates_names(object) ``` ```r covariates_names(object) <- value ``` -------------------------------- ### Configure MEFISTO Options for Time Series Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Set MEFISTO options to enable time-series smoothing for factors and group-specific smoothing. Prepare the model with these custom options. ```r mefisto_opts <- get_default_mefisto_options(model) mefisto_opts$GP_factors <- TRUE # Smooth factors over time mefisto_opts$model_groups <- TRUE # Different smoothing per group # Prepare model model <- prepare_mofa(model, mefisto_options = mefisto_opts) # Train and interpolate model <- run_mofa(model, use_basilisk = TRUE) # Interpolate to fine grid new_time <- matrix(seq(0, 10, 0.1), nrow = 1) model <- interpolate_factors(model, new_covariates = list(new_time, new_time)) ``` -------------------------------- ### Create MOFA object from SingleCellExperiment object Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Initialize a MOFA object from a SingleCellExperiment object. You can specify which assays and features to use for creating views. ```r create_mofa_from_SingleCellExperiment(object, groups = NULL, extract_metadata = TRUE, assay = NULL, features = NULL) ``` -------------------------------- ### Create MOFA Object from Seurat Object Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Initializes a MOFA object from a Seurat object, optionally extracting metadata. Ensure the Seurat object is properly formatted. ```r model <- create_mofa(seurat_obj, extract_metadata = TRUE) ``` -------------------------------- ### Enable and Configure Stochastic Variational Inference Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Enables stochastic variational inference and configures its hyperparameters like batch size and learning rate. Recommended for large datasets (N > 10,000) and when GPU acceleration is available. ```r train_opts <- get_default_training_options(model) # Enable stochastic inference train_opts$stochastic <- TRUE train_opts$maxiter <- 200 # Stochastic often converges faster stoch_opts <- get_default_stochastic_options(model) # Use larger batches for stability stoch_opts$batch_size <- 0.20 # Tune learning rate for stability stoch_opts$learning_rate <- 0.01 # Delayed start for stochastic mode stoch_opts$start_stochastic <- 50 model <- prepare_mofa(model, training_options = train_opts, stochastic_options = stoch_opts) ``` -------------------------------- ### run_mofa Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Trains the MOFA model using the mofapy2 Python backend. This function takes a prepared MOFA object and trains it, returning a trained MOFA object. ```APIDOC ## run_mofa ### Description Train the MOFA model using the mofapy2 Python backend. ### Method POST ### Endpoint `/run_mofa` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `object` (MOFA): Yes - A prepared MOFA object (must have run `prepare_mofa()` first) - `outfile` (character): No - NULL - Path for output HDF5 file. If NULL, uses temporary file specified in training_options or creates one with timestamp - `save_data` (logical): No - TRUE - Whether to save training data in HDF5 file (useful for downstream analysis but increases file size) - `use_basilisk` (logical): No - FALSE - Whether to use basilisk to automatically create a conda environment with mofapy2. If FALSE, requires manual Python configuration via reticulate ### Return A trained MOFA object (status = "trained") with populated expectations, training_stats, and other results. ### Details The function interfaces with the mofapy2 Python package through reticulate. There are two ways to specify Python: 1. **Manual (use_basilisk = FALSE, default)**: ```r reticulate::use_python("/path/to/python", force = TRUE) reticulate::use_condaenv("mofa_env", force = TRUE) ``` 2. **Automatic (use_basilisk = TRUE)**: The function uses basilisk to create and manage a conda environment automatically. ### Throws - Error if object is already trained - Error if object has not been prepared (no model_options or training_options) - Error if mofapy2 is not installed - Error if mofapy2 version doesn't match required version ### Warnings - Warning if mofapy2 version doesn't match R package version (may have compatibility issues) ### Examples ```r # Standard workflow file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) model <- create_mofa(dt) model <- prepare_mofa(model) # Option 1: Train with automatic environment setup (recommended) model <- run_mofa(model, use_basilisk = TRUE) # Option 2: Train with manual Python setup # reticulate::use_condaenv("mofa_env", force = TRUE) # model <- run_mofa(model, use_basilisk = FALSE) # Save model to specific location model <- run_mofa(model, outfile = "my_model.hdf5", use_basilisk = TRUE) ``` ``` -------------------------------- ### Get ELBO from Trained MOFA Model Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Extracts the final Evidence Lower Bound (ELBO) value from a trained MOFA model. Higher ELBO values indicate a better model fit and are useful for model selection. ```r elbo <- get_elbo(model) # Higher ELBO values indicate better model fit ``` -------------------------------- ### MOFA Sample Metadata Structure Source: https://github.com/biofam/mofa2/blob/master/_autodocs/types.md Describes the structure and required columns for the 'samples_metadata' slot, which is a data frame containing annotations for each sample. ```r # Required columns model@samples_metadata # data.frame # Column structure: # sample: character, sample identifiers # group: character, group assignment # Custom columns: metadata added during creation # Example head(model@samples_metadata) # sample group disease_status age # 1 sample_1 group1 control 45 # 2 sample_2 group1 diseased 52 # ... # Access model@samples_metadata$sample model@samples_metadata$disease_status ``` -------------------------------- ### Create MOFA Object from List of Matrices Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Constructs a MOFA object from a list where each element is a matrix representing a data view. Matrices should have features as rows and samples as columns. ```r data_matrices <- list( view1 = matrix(rnorm(100*50), 100, 50), view2 = matrix(rnorm(80*50), 80, 50) ) model <- create_mofa(data_matrices) ``` -------------------------------- ### Plot Enrichment Heatmap Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-analysis.md Generates a heatmap to visualize pathway-factor associations from enrichment results. Use this to get a high-level overview of significant enrichments across factors and pathways. Requires a trained MOFA object and feature set definitions. ```r plot_enrichment(object, view, feature.sets, factors = "all", threshold = 0.05, ...) ``` -------------------------------- ### get_default_model_options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves the default model configuration options for MOFA model preparation. These options include the number of factors, likelihoods, and automatic relevance determination settings. ```APIDOC ## get_default_model_options ### Description Get default model configuration options. ### Method `get_default_model_options(object)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (MOFA) - Required - An untrained MOFA object (created via `create_mofa()`) ### Request Example ```r # Get default model options model_opts <- get_default_model_options(model) ``` ### Response #### Success Response (200) A list with elements: - `num_factors`: integer, number of latent factors to learn (default: estimated from data) - `likelihoods`: named character vector of likelihoods per view, automatically inferred from data types (gaussian, bernoulli, poisson) - `ard_weights`: logical, use automatic relevance determination on weights (default: TRUE) - `ard_factors`: logical, use automatic relevance determination on factors (default: FALSE) #### Response Example None provided in source. ``` -------------------------------- ### Complex MOFA Workflow for Large Data and Multiple Groups Source: https://github.com/biofam/mofa2/blob/master/_autodocs/configuration.md Configure MOFA for large datasets and multiple groups, including group-specific scaling and centering, advanced model options like ARD weights, and stochastic training. Prepare and run the model with these comprehensive settings. ```r model <- create_mofa(data, groups = groups) # Data preprocessing data_opts <- get_default_data_options(model) data_opts$scale_views <- TRUE data_opts$scale_groups <- TRUE # Account for group differences data_opts$center_groups <- TRUE # Model configuration model_opts <- get_default_model_options(model) model_opts$num_factors <- 20 model_opts$ard_weights <- TRUE # Training train_opts <- get_default_training_options(model) train_opts$convergence_mode <- "slow" # Strict convergence train_opts$maxiter <- 2000 train_opts$save_data <- TRUE # Stochastic for large data if (sum(model@dimensions$N) > 10000) { train_opts$stochastic <- TRUE stoch_opts <- get_default_stochastic_options(model) stoch_opts$batch_size <- 0.20 } model <- prepare_mofa(model, data_options = data_opts, model_options = model_opts, training_options = train_opts, stochastic_options = if (train_opts$stochastic) stoch_opts else NULL ) model <- run_mofa(model, use_basilisk = TRUE) ``` -------------------------------- ### Accessing MOFA Class Slots Source: https://github.com/biofam/mofa2/blob/master/_autodocs/types.md Demonstrates how to read from and write to the slots of a MOFA object. Use the '@' operator for slot access. ```r # Read slot model@data model@expectations model@dimensions # Write slot model@status <- "trained" model@cache <- list() ``` -------------------------------- ### Cache Structure and Manual Clearing Source: https://github.com/biofam/mofa2/blob/master/_autodocs/types.md Inspect the cache slot for computationally expensive results like R-squared values per factor or total. Manually clear the cache if necessary by reinitializing the slot. ```r # Structure cache$variance_explained$r2_per_factor # List of matrices per group cache$variance_explained$r2_total # List of vectors per group # Automatically populated by calculate_variance_explained() # Clear cache manually if needed: model@cache <- list() ``` -------------------------------- ### get_default_mefisto_options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves the default options for MEFISTO, which extends MOFA to incorporate sample covariates for spatio-temporal integration. These options control the modeling of group-group covariance, covariates, and interactions. ```APIDOC ## get_default_mefisto_options ### Description Get default MEFISTO options for models with covariates. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Return A list with elements: - `model_groups`: logical, model group-group covariance structure (default: FALSE) - `model_covariates`: logical, model covariate effects (default: TRUE) - `model_interactions`: logical, model covariate-group interactions (default: TRUE) - `n_grid`: integer, number of points for interpolation grid (default: 100) - `grid_type`: character, type of interpolation grid: "regular" or "user-defined" (default: "regular") - `GP_factors`: logical, use Gaussian processes for temporal/spatial modeling (default: FALSE) ### Details MEFISTO (Multi-Omics Factor Analysis for Spatio-Temporal integration) extends MOFA to incorporate sample covariates (e.g., time, space, or other continuous variables). ``` -------------------------------- ### get_default_training_options Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Retrieves the default hyperparameters for MOFA model training. This includes settings for maximum iterations, ELBO computation, convergence modes, stochastic inference, output file paths, verbosity, and data saving. ```APIDOC ## get_default_training_options ### Description Get default training hyperparameters. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Return A list with elements: - `maxiter`: integer, maximum number of training iterations (default: 1000) - `startELBO`: integer, iteration at which to start computing ELBO (default: 1) - `freqELBO`: integer, frequency of ELBO computation (default: 10) - `convergence_mode`: character, one of "fast", "medium", "slow" (default: "fast") - `stochastic`: logical, whether to use stochastic variational inference (default: FALSE) - `outfile`: character, path for output HDF5 file (default: temporary file) - `verbose`: logical, print progress messages (default: FALSE) - `save_data`: logical, save training data in HDF5 (default: TRUE) ### Details Convergence modes affect ELBO convergence criteria: - "fast": Uses loose tolerance - "medium": Uses medium tolerance - "slow": Uses strict tolerance ``` -------------------------------- ### Inspect MOFA2 Model Structure Source: https://github.com/biofam/mofa2/blob/master/_autodocs/INDEX.md Use the `model` object directly to inspect its structure. This is useful for a quick overview of the trained model. ```r # Inspect model structure model ``` -------------------------------- ### Create MOFA Object from Long-Format Data Frame Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-core.md Initializes an untrained MOFA object using a data frame in long format. Ensure the data frame contains all necessary columns for sample and feature information. ```r file <- system.file("extdata", "test_data.RData", package = "MOFA2") load(file) model <- create_mofa(dt) ``` -------------------------------- ### Specifying Factors by Name, Index, or 'all' Source: https://github.com/biofam/mofa2/blob/master/_autodocs/types.md Functions accepting factor selection parameters can take a character vector of factor names, a numeric vector of 1-indexed factor positions, or the string 'all' to select all factors. ```r # All three specifications are equivalent: # By name (character vector) get_factors(model, factors = c("Factor1", "Factor3")) # By index (numeric vector, 1-indexed) get_factors(model, factors = c(1, 3)) # String "all" get_factors(model, factors = "all") ``` -------------------------------- ### Plot Data Overview Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-plotting.md Provides an overview of the data structure, showing sample counts per view and group, as well as feature counts. Helps in understanding the dataset's composition. ```r plot_data_overview(object) ``` -------------------------------- ### Load MOFA Model Source: https://github.com/biofam/mofa2/blob/master/_autodocs/api-reference-training.md Loads a trained MOFA model from an HDF5 file. Various parameters allow for customization of how the model and its data are loaded, including options for memory efficiency and outlier removal. ```r load_model(file, sort_factors = TRUE, on_disk = FALSE, load_data = TRUE, remove_outliers = FALSE, remove_inactive_factors = TRUE, verbose = FALSE, load_interpol_Z = FALSE) ``` ```r model <- load_model("model.hdf5") ``` ```r model <- load_model("model.hdf5", load_data = FALSE) ``` ```r model <- load_model("model.hdf5", on_disk = TRUE) ``` ```r model <- load_model("model.hdf5", remove_inactive_factors = TRUE) ``` ```r model <- load_model("model.hdf5", remove_outliers = TRUE) ```