Custom Function Definitions#
Utilities for From Multi-Omics to Gene–Disease Discovery: Knowledge Graphs and LLM-Augmented Analysis tutorial (ECCB 2026, Geneva).
This module contains utility functions used in Session 2 (multi-omics / MOFA) and a small set of general evaluation helpers.
Exported functions#
load_omics
evaluate_predictions
plot_confusion_matrix
generate_diagnostic_plots
build_mofa_matrix_input
fit_mofa
select_active_factors
project_test_patients_to_mofa_factors
eta_squared_by_factor
fit_factor_classifier
plot_r2_heatmap
plot_factor_boxplots_by_subtype
- s2_helpers.build_mofa_matrix_input(X_by_omic)[source]#
Build MOFA input matrices from aligned omics tables.
mofapy2 expects a nested structure where each view (omics modality) contains one or more groups, and each entry is a numeric matrix of shape (n_samples, n_features).
This helper assumes: - all input DataFrames are already aligned on an identical patient index - a single group is used:
"TCGA-BRCA_train"- Parameters:
X_by_omic (dict[str, pandas.DataFrame]) – Mapping from view name (e.g.
"transcriptomics") to a 2D feature table indexed by patient/sample ID. Each DataFrame has shape (n_samples, n_features_view).- Returns:
data (list[list[numpy.ndarray]]) – MOFA data structure:
data[view][group] = Xwhere eachXis afloat32NumPy array of shape (n_samples, n_features_view).view_names (list[str]) – Names of the omics views in the same order as data.
feature_names (list[list[str]]) – Feature names per view in the same order as view_names.
sample_names (list[list[str]]) – Sample IDs per group. For a single group this is [sample_id_list].
group_names (list[str]) – Group names. For this tutorial this is [“TCGA-BRCA_train”].
- Raises:
AssertionError – If any view’s sample index does not match the first view’s sample index.
- s2_helpers.eta_squared_by_factor(factor_table, labels)[source]#
Compute one-way ANOVA eta-squared ($ \eta^2 $) for each factor.
Eta-squared here is interpreted as the fraction of factor variance explained by group (subtype) membership, computed without fitting a predictive model.
- Parameters:
factor_table (pandas.DataFrame) – Factor values (e.g. MOFA Z) with shape (n_samples, n_factors), indexed by sample ID.
labels (pandas.Series) – Group labels (e.g. subtype) indexed by the same sample IDs as factor_table.
- Returns:
Sorted table with columns: -
factor: factor column name -eta_squared: eta-squared value (float)- Return type:
pandas.DataFrame
Notes
If a factor has zero total variance, eta-squared is reported as
NaN.Labels are coerced to string to avoid mixed label types.
- s2_helpers.evaluate_predictions(y_true: ndarray, y_pred: ndarray, title: str) None[source]#
Compute and display common classification metrics.
The function prints: - a title header - accuracy - balanced accuracy - a confusion matrix (via
plot_confusion_matrix())- Parameters:
y_true (numpy.ndarray) – Ground-truth labels of shape (n_samples,).
y_pred (numpy.ndarray) – Predicted labels of shape (n_samples,).
title (str) – Title used in printed output and metric labelling.
- Returns:
Summary metrics with keys: -
model-accuracy-balanced_accuracy- Return type:
dict
Notes
classification_report is imported but not printed in the current implementation.
- s2_helpers.fit_factor_classifier(factors_df, y, train_ids, test_ids, model_name)[source]#
Train a logistic regression classifier on factor values and evaluate on a held-out set.
This is a lightweight diagnostic answering: do the learned latent factors preserve subtype information?
- Parameters:
factors_df (pandas.DataFrame) – Factor matrix (Z) indexed by sample ID, columns are factor names.
y (pandas.Series) – True labels indexed by sample ID.
train_ids (array-like) – Sample IDs to use for training.
test_ids (array-like) – Sample IDs to use for evaluation.
model_name (str) – Label used in metric output.
- Returns:
clf (sklearn.linear_model.LogisticRegression) – Fitted classifier.
pred (numpy.ndarray) – Predicted labels for test_ids.
metrics (dict) – Dictionary returned by
evaluate_predictions().
- s2_helpers.fit_mofa(data, view_names, feature_names, sample_names, group_names, max_factors, iterations, random_state, outfile)[source]#
Fit a MOFA model (mofapy2) and return the trained model object.
This function configures a compact MOFA model for continuous (Gaussian) multi-omics data, enabling ARD (automatic relevance determination) at both the factor and weight level to encourage sparsity/shrinkage of uninformative factors.
- Parameters:
data (list[list[numpy.ndarray]]) – Nested data structure as produced by
build_mofa_matrix_input().view_names (list[str]) – View names corresponding to entries in data.
feature_names (list[list[str]]) – Feature names per view.
sample_names (list[list[str]]) – Sample names per group.
group_names (list[str]) – Group names.
max_factors (int) – Maximum number of latent factors to learn.
iterations (int) – Number of training iterations.
random_state (int) – Random seed passed to MOFA training.
outfile (str | pathlib.Path) – Path for MOFA’s training output and/or saved model.
- Returns:
model – Trained MOFA entry point object.
- Return type:
mofapy2.run.entry_point.entry_point
Notes
The function calls
model.run()and then saves the model (if needed).
- s2_helpers.generate_diagnostic_plots(mofa_model_mfx, factors_df, factor_r2_summary, view_names, active_factor_cols, factor_subtype_assoc, train_ids, y_train, y_test, mofa_pred, output_dir, top_view_for_weights='transcriptomics')[source]#
Generate and save the core MOFA diagnostic plots used in the tutorial notebook.
This is a single entry point that produces several complementary diagnostics:
R2 heatmap: MOFA variance explained per (view, factor).
Factor boxplots: distributions of top subtype-associated factors by subtype (training patients only).
Confusion matrix: held-out subtype prediction errors from a classifier trained on factor values.
Ranked feature weights: strongest positive/negative feature loadings in a chosen view for the most subtype-associated factors.
- Parameters:
mofa_model_mfx (mofax.core.mofa_model.MofaModel | Any) – mofax model wrapper providing
get_r2()and plotting.factors_df (pandas.DataFrame) – Factor matrix (Z) for all samples, indexed by sample ID.
factor_r2_summary (pandas.DataFrame) – Factor-level R2 summary table (kept for notebook parity; not directly used).
view_names (list[str]) – View names (row order for R2 heatmap).
active_factor_cols (list[str]) – Selected active factor names (column order for R2 heatmap).
factor_subtype_assoc (pandas.DataFrame) – Table ranking factors by subtype association (e.g. output of
eta_squared_by_factor()) with afactorcolumn.train_ids (array-like) – Training sample IDs.
y_train (pandas.Series) – Training labels.
y_test (pandas.Series) – Test labels.
mofa_pred (array-like) – Predicted labels for the test set (for confusion matrix).
output_dir (str | pathlib.Path) – Directory where PNGs will be written.
top_view_for_weights (str, default="transcriptomics") – View to use when plotting ranked feature weights.
- Returns:
Side effect: saves PNG files under output_dir.
- Return type:
None
- s2_helpers.load_omics(data_dir: str | Path, omic_keys: Sequence[str]) tuple[dict[str, DataFrame], Series][source]#
Load TCGA-BRCA multi-omics views and subtype labels from a pickled bundle.
The function reads
omics.pklfrom data_dir. The pickle is expected to contain: - one DataFrame per requested omics view key - a label vector under the key"meta"The function also checks that all requested views share an identical patient index.
- Parameters:
data_dir (str | pathlib.Path) – Directory containing
omics.pkl.omic_keys (Sequence[str]) – Names of the omics views to load, e.g.
["transcriptomics", "proteomics", "methylation"].
- Returns:
X_views (dict[str, pandas.DataFrame]) – Mapping from each requested view name to a copy of its feature matrix.
y (pandas.Series) – Copy of the labels (subtype), indexed by patient/sample ID.
- Raises:
ValueError – If omic_keys is empty.
FileNotFoundError – If
omics.pkldoes not exist in data_dir.KeyError – If any requested omics key (or
"meta") is missing from the pickle.ValueError – If patient indices across views are not identical.
Notes
The function prints basic dataset diagnostics (view dimensions and label counts).
- s2_helpers.plot_confusion_matrix(y_test, y_pred)[source]#
Plot a confusion matrix for held-out subtype predictions.
- Parameters:
y_test (array-like) – True labels for the evaluation set.
y_pred (array-like) – Predicted labels for the evaluation set.
- Returns:
Displays the plot via Matplotlib.
- Return type:
None
- s2_helpers.plot_factor_boxplots_by_subtype(factors_df, train_ids, y_train, top_factors, output_path)[source]#
Plot boxplots of selected factors stratified by subtype and save to disk.
- Parameters:
factors_df (pandas.DataFrame) – Factor matrix indexed by sample ID.
train_ids (array-like) – Training sample IDs to include in the plot.
y_train (pandas.Series) – Training labels (subtypes).
top_factors (list[str]) – Factor column names to plot (one panel per factor).
output_path (str | pathlib.Path) – Output path for a PNG file.
- Returns:
Figure is saved and closed.
- Return type:
None
- s2_helpers.plot_r2_heatmap(r2_all, view_names, active_factor_cols, output_path)[source]#
Plot an annotated heatmap of MOFA variance explained (R2) and save to disk.
- Parameters:
r2_all (pandas.DataFrame) – Long-form R2 table with columns: -
factor-view-r2(numeric) Typically derived frommofa_model_mfx.get_r2()with column renaming.view_names (list[str]) – View order for plotting (rows).
active_factor_cols (list[str]) – Factor order for plotting (columns).
output_path (str | pathlib.Path) – Output path for a PNG file.
- Returns:
Figure is saved and closed.
- Return type:
None
- s2_helpers.project_test_patients_to_mofa_factors(model, X_train_by_view, X_test_by_view, train_factors, view_names)[source]#
Project held-out samples into a trained MOFA factor space.
MOFA is fitted on training samples only. For held-out samples, this function: - fixes learned weights (W) per view - computes a pseudo-inverse-based projection from scaled test features to factors - calibrates the raw projection to the trained factor scale using a linear map fitted on training samples only - averages projected factor values across views
Parameter#
- modelAny
Fitted MOFA model object providing
get_weights(views=..., df=True).- X_train_by_viewdict[str, pandas.DataFrame]
Training feature matrices per view, indexed by sample ID.
- X_test_by_viewdict[str, pandas.DataFrame]
Test feature matrices per view, indexed by sample ID.
- train_factorspandas.DataFrame
Training factor matrix (Z) indexed by sample ID with columns being factor names.
- view_nameslist[str]
Ordered list of view names to project with.
- returns:
Projected test factor values, indexed by test sample ID with the same factor columns as train_factors.
- rtype:
pandas.DataFrame
Notes
Scaling is done per view using training-set mean and standard deviation.
Features are intersected across MOFA weights, train data, and test data for safety.
- s2_helpers.select_active_factors(mofa_model_mfx, min_total_r2, max_factors)[source]#
Select “active” MOFA factors using variance explained (R2).
This function retrieves the variance-explained table from a fitted MOFA model, sums each factor’s R2 across all views, and keeps factors whose total R2 meets a minimum threshold. If none pass, it falls back to the single best factor.
- Parameters:
mofa_model_mfx (mofax.core.mofa_model.MofaModel | Any) – A mofax-wrapped MOFA model providing
get_r2().min_total_r2 (float) – Minimum total (summed across views) R2 required to keep a factor.
max_factors (int) – Maximum number of factors considered/trained (kept for API compatibility / notebook parity).
- Returns:
active_factor_cols (list[str]) – Selected factor names (e.g.
["Factor1", "Factor3"]).factor_r2_summary (pandas.DataFrame) – Table with columns: -
factor: factor name -total_r2: summed R2 across views Sorted descending bytotal_r2.
Notes
max_factors is not used directly in the current implementation but is kept to match the tutorial’s calling signature.