### Download example data with curl Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Downloads the example test data file from the cvanmf repository and saves it as sample.tsv. ```bash curl https://raw.githubusercontent.com/apduncan/cvanmf/main/resources/test_data.tsv > sample.tsv ``` -------------------------------- ### Install dependencies with poetry Source: https://github.com/apduncan/cvanmf/blob/main/CONTRIBUTING.md Use this command to install the project dependencies locally using poetry. ```console $ poetry install ``` -------------------------------- ### Test installation with rank_select command Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Run the rank_select command to verify installation. The expected output shows the usage message and an error indicating the missing -i/--input option. ```commandline rank_select Usage: rank_select [OPTIONS] Try 'rank_select --help' for help. Error: Missing option '-i' / '--input'. ``` -------------------------------- ### Reapply five_es model to example data Source: https://github.com/apduncan/cvanmf/blob/main/docs/reapply.ipynb Loads example abundance data and applies the five_es model using the `reapply` method. The input should be a pandas DataFrame with features on rows and samples on columns. The method applies appropriate transformations, so data does not need to be normalized beforehand. ```python from cvanmf import models, data import numpy as np # The example data is quite large, so we'll take a subset of samples result = models.five_es().reapply( # The input should be as a pandas DataFrame, with features on rows and # samples on columns. Data does not need to be normalised in this case, # the `reapply` method of the `five_es` object will apply the appropriate # transformations. y=data.example_abundance().iloc[:, :30] ) result.model_fit.describe() ``` -------------------------------- ### Example error output when conda is missing Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Example error output from slurm_script showing 'conda: command not found' and '/bin/activate: No such file or directory', which occurs when Nextflow cannot activate a micromamba environment. ```text [...] Command wrapper: /var/spool/slurmd/job1304257/slurm_script: line 325: conda: command not found /var/spool/slurmd/job1304257/slurm_script: line 325: /bin/activate: No such file or directory [...] ``` -------------------------------- ### Launch Jupyter Lab Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Starts Jupyter Lab with the cvanmf environment active. ```bash jupyter lab ``` -------------------------------- ### Install Jupyter Lab in cvanmf environment Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Installs Jupyter Lab into the specified conda environment. Replace {env_name} with the environment name. ```bash conda install --name {env_name} jupyterlab ``` -------------------------------- ### pip install cvanmf Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Installs cvanmf via pip. Requires Python version >=3.12. ```bash pip install cvanmf ``` -------------------------------- ### Generate decompositions with random initializations for rank selection Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Creates multiple decompositions for each rank in the given range using random starts. The 'top_n' parameter controls the number of signatures per rank, and 'random_starts' sets the number of random initializations. The seed ensures reproducibility. ```python rs_decomps = decompositions(x, ranks=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], top_n=10, random_starts=10, seed=4928, progress_bar=False) ``` -------------------------------- ### Install conda in micromamba environment Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md This command installs conda into the micromamba environment 'nfenv' to resolve Nextflow activation errors. Nextflow still uses micromamba for environment creation but needs conda for activation. ```commandline micromamba install -n nfenv conda ``` -------------------------------- ### Install gcc with mamba for cvanmf dependencies Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Installs gcc in the cvanmf conda environment to satisfy build dependencies. Alternative: use system package manager like 'sudo apt install gcc'. ```bash mamba install --name cvanmf gcc ``` -------------------------------- ### Run univariate tests with k3.univariate_tests Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Runs univariate tests on metadata fields (disease and tumor stage) using k3.univariate_tests. The metadata columns are renamed for readability. The result is a dataframe of test results, and the example shows the first few rows with .head(). ```python univar_results = k3.univariate_tests(sample_md[['disease', 'tumor_stage']].rename( # Rename our metadata fields to more readable form columns=dict(tumor_stage="Tumor Stage", disease="Disease") )) univar_results.head() ``` -------------------------------- ### Install cvanmf via Conda Source: https://github.com/apduncan/cvanmf/blob/main/README.md Use this command to install the package into a specific conda environment using the bioconda and conda-forge channels. ```bash conda install --name {envname} -c bioconda -c conda-forge cvanmf ``` -------------------------------- ### Plot metadata relationships with k3.plot_metadata Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates discrete and continuous metadata plots using k3.plot_metadata. The example renames metadata fields for readability, then customizes the discrete plot with plotnine: removes fill guides, sets figure size, rotates x-axis text, adds a title, adjusts y-axis expansion, and redefines facet rows/columns with a custom labeller. The plot is saved via figure_output(disc, "e_metadata", PUB) and displayed. Note that the plot is facetted by default and the underlying data is available in disc.data. ```python disc, cont = k3.plot_metadata(sample_md[['disease', 'tumor_stage', 'age']].rename( # Rename our metadata fields to more readable form columns=dict(tumor_stage="Tumor Stage", disease="Disease") )) disc = ( disc + pn.guides(fill="none") + pn.theme( figure_size=(3,4), axis_text_x=pn.element_text(rotation=60, hjust=1, vjust=1) ) + pn.ggtitle("Metadata Plots") # We're adding a little more room for the stars - the internal calculation doesn't always get the right space for custom size plots + pn.scale_y_continuous(expand=[0.1, 0, 0.2, 0]) # This plot is facetted by default, but we're redefining it so we can add linebreaks to row values # To see the data and columns which the plot is based on, your can look at disc.data + pn.facet_grid( rows='signature', cols='metadata_field', labeller=pn.labeller(rows=lambda x: x.replace("(", "\n(").replace('model', '\nmodel')), scales='free_x', space='free_x' ) ) figure_output(disc, "e_metadata", PUB) disc ``` -------------------------------- ### Create slurm.config for SLURM executor Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Creates a Nextflow config file to use the SLURM executor, micromamba for conda, and default resource settings. Override resource settings with the largemem label for memory-intensive tasks and use job arrays for reguBiCv and rankBiCv processes. Replace queue names with those for your HPC setup. ```nextflow profiles { slurm { // Say we want to use the slurm executor executor { name = 'slurm' } // Use micromamba to create environments conda.enabled = true conda.useMicromamba = true // Everything in the process block will apply to all processes run // by Nextflow process { conda = "${projectDir}/env.yaml" // By default, jobs will be submitted to the queue 'ei-short' queue = 'ei-short' // We'll request 1.5GB and 4 CPUs by default memory = '1.5GB' cpus = 4 // Some processes use more memory, and we've labelled these with // the 'largemem' label. Any settings in here will apply to // any of these more memory intensive tasks. withLabel: largemem { // Typically our processes requiring a lot of memory are // splitting and merging data, and not very computationally // demanding queue = 'ei-short' memory = '8GB' cpus = 2 } withName: "reguBiCv|rankBiCv" { // The pipeline generates a lot of these jobs with identical // requirements. It is better for the SLURM scheduler if these // are submitted as a job array. Nextflow can handle that for // us array = 1000 } } } } ``` -------------------------------- ### Load lung cancer cell composition data Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Loads the example NSCLC cell composition dataset using data.lung_cancer_cells(). The returned object is an ExampleData named tuple with properties for tables and metadata. ```python lung_data = data.lung_cancer_cells() lung_data ``` ```text Result: ExampleData[NSCLC, shape=(33, 224), rank=[]] ``` -------------------------------- ### conda install cvanmf in new environment Source: https://github.com/apduncan/cvanmf/blob/main/docs/install.md Installs cvanmf from bioconda into a new conda environment. Replace {env_name} with the desired environment name. Works with conda, mamba, or micromamba. ```bash conda install --name {env_name} -c bioconda -c conda-forge cvanmf ``` -------------------------------- ### Get scaled H matrix and verify sum Source: https://github.com/apduncan/cvanmf/blob/main/docs/reapply.ipynb Gets a scaled version of the H matrix so each sample sums to 1, and verifies that the sum of all scaled values equals 1.0 using `np.allclose`. ```python assert np.allclose(result.scaled('h').sum(), 1.0) result.scaled('h').iloc[:, :5] ``` -------------------------------- ### Configure conda path in Nextflow profile Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Example configuration snippet showing how to set the conda environment path in a Nextflow profile for a scheduler like slurm. ```nextflow profiles { slurm { ... process { conda = '/some/path/mambaforge/envs/cvapipe' ... ``` -------------------------------- ### Suggest alpha value Source: https://github.com/apduncan/cvanmf/blob/main/resources/cva_regu_analysis.ipynb Calls denovo.suggest_alpha to get a suggested alpha value from the regularization results. ```python denovo.suggest_alpha(rank_res) ``` -------------------------------- ### Plot stability rank selection with plotnine customization Source: https://github.com/apduncan/cvanmf/blob/main/resources/stab_rank_analysis.ipynb Creates a plot using denovo.plot_stability_rank_selection with the stability values, applies a figure size of 10 by 3 and removes the color guide. The dashed line indicates the automatically selected rank; higher values are better for all measures. ```python fig = ( denovo.plot_stability_rank_selection( series=[stability_values[c] for c in stability_values.columns] ) + pn.theme(figure_size=(10, 3)) + pn.guides(color="none") ) fig ``` -------------------------------- ### Run cvanmf with bind mounts Source: https://github.com/apduncan/cvanmf/blob/main/docs/docker.md Creates a local directory, downloads data, and runs the reapply command by mounting the host directory to the container. ```bash # Make directory mkdir example # Download some data wget https://github.com/apduncan/cvanmf/raw/refs/heads/main/src/cvanmf/data/NW_ABUNDANCE.tsv \ -O example/data.tsv # Run reapply on this data using the container docker run \ --mount type=bind,src="${PWD}/example/",dst=/mnt/data/ \ ghcr.io/apduncan/cvanmf:latest \ reapply \ -i /mnt/data/data.tsv \ -m 5es \ -o /mnt/data/results ``` -------------------------------- ### Import cvanmf and plotting libraries Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Initializes the environment by importing necessary libraries and configuring plotnine figure options. ```python from cvanmf import denovo import pandas as pd import plotnine as pn import matplotlib.pyplot as plt # Ignore plotnine's default size limits, as for big decompositions # we will want some big plots from plotnine.options import set_option set_option("figure_format", False) ``` -------------------------------- ### Run cvanmf with Singularity from command line Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Run the pipeline with Singularity by specifying the container image at the command line. The docker:// prefix lets Nextflow pull and convert the image to a Singularity image, cached according to singularity.libraryDir or NXF_SINGULARITY_LIBRARYDIR. ```bash nextflow run apduncan/cvanmf \ -with-singularity docker://ghcr.io/apduncan/cvanmf:latest-nf \ -r main -profile slurm -c custom.config \ -resume \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --seed 4298 \ --num_shuffles 3 ``` -------------------------------- ### Run cvanmf with execution report for memory estimation Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Run the pipeline with the -with-report option to generate an execution report for memory estimation. Use a single rank and small number of shuffles to gauge resource usage. ```bash nextflow run apduncan/cvanmf -r main -profile slurm -c custom.config \ -c slurm.config -resume -with-report report.html \ --matrix sample.tsv --ranks 2,3 --num_shuffles 10 \ --publish_dir output/sample_test --seed 4298 ``` -------------------------------- ### Create custom.config with rank and seed parameters Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Create a file named custom.config in the working directory. This overrides the default regu_rank list and seed value. Command line parameters take precedence over config values. ```nextflow params.regu_rank = [4,8] params.seed = 729108 ``` -------------------------------- ### Run cvanmf decompositions with selected parameters Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Runs denovo.decompositions with rank 3, alpha 2.23e-03, l1_ratio 1.0, seed 4298, and top_n 100. Retains the 100 best decompositions to compare signature similarity later. The output shows a progress bar completing 100/100 iterations. ```python decomps = denovo.decompositions( x=composition, ranks=[3], alpha=2.23e-03, l1_ratio=1.0, seed=4298, # We keep the 100 best decompositions so we can look at how similar signatures are across them later # You could chose to retain a lower number top_n=100 ) k3 = decomps[3][0] ``` ```text 100%|███████████████████████████████████| 100/100 [00:00<00:00, 142.97it/s] ``` -------------------------------- ### Verify Docker image execution Source: https://github.com/apduncan/cvanmf/blob/main/docs/docker.md Checks that the Docker image can be fetched and executed by running the reapply command to display its help message. ```bash docker run ghcr.io/apduncan/cvanmf:latest reapply ``` -------------------------------- ### Run pipeline with SLURM config Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Run the pipeline using the slurm profile and the custom SLURM config. Multiple config files can be provided; the slurm profile is selected with -profile slurm. ```bash nextflow run apduncan/cvanmf -r main -profile slurm -c custom.config \ -c slurm.config -resume \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --seed 4298 \ --num_shuffles 3 ``` -------------------------------- ### Run cvanmf with Docker from command line Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Run the pipeline with Docker by specifying the image at the command line. The image is pulled from the registry and used for all processes. ```bash nextflow run apduncan/cvanmf \ -with-docker ghcr.io/apduncan/cvanmf:latest-nf \ -r main -profile slurm -c custom.config \ -resume \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --seed 4298 \ --num_shuffles 3 ``` -------------------------------- ### Create conda environment with Mamba Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Downloads the environment file and creates a conda environment named cvapipe. The environment must be in a directory accessible from all compute nodes. ```bash curl https://raw.githubusercontent.com/apduncan/cvanmf/main/env.yaml > env.yaml mamba env create -n cvapipe -f env.yaml ``` -------------------------------- ### Run multiple decompositions for stability comparison Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Runs 101 decompositions for ranks 2 to 10 with alpha=0.0, l1_ratio=1.0, and a fixed seed. The top_n=101 retains all decompositions for comparison, and random_starts=101 provides 100 alternatives to the best. ```python decomps_multi = denovo.decompositions( x=composition, ranks=range(2, 11), # Suitable alpha hasn't been selected for all ranks, so set to 0 alpha=0.0, l1_ratio=1.0, seed=4298, # We want to retain all our decompositions so we can compare them top_n=101, # We choose 101 so we can take the best, and compare it to 100 others random_starts=101, progress_bar=False ) ``` -------------------------------- ### Create similar synthetic dataset Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Generates a synthetic dataset with the same properties as the original X (k=4, overlap=0.4) and displays it as a heatmap. This dataset should be well described by the existing model. ```python y_similar = data.synthetic_blocks( overlap=0.4, k=4, scale_lognormal_params=dict(sigma=0.75) ).data sns.heatmap(y_similar) ``` -------------------------------- ### Run pipeline with custom.config Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Run the pipeline with the custom config file using -c custom.config. Command line parameters like --seed override config values. The pipeline performs regularisation selection for ranks 4 and 8. ```bash nextflow run apduncan/cvanmf -r main -profile conda -c custom.config \ -resume \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --seed 4298 \ --num_shuffles 3 ``` -------------------------------- ### Plot regularisation selection results with plotnine Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates a plotnine figure from the regu_selection results, customising the theme, guides, title, and y-axis expansion. The figure is saved via figure_output and then displayed. The output shows FutureWarnings about pandas deprecations and plotnine warnings about saving the image. ```python plt_regusel = ( denovo.plot_regu_selection(regu_res, jitter=False) + pn.theme( figure_size=(2.66, 1.8), axis_text_x=pn.element_text(rotation=45, hjust=1.0) ) + pn.guides(fill = "none") + pn.ggtitle("Regularisation Selection") # We're adding a little more room for the stars + pn.scale_y_continuous(expand=[0.1, 0, 0.1, 0]) ) figure_output(plt_regusel, "a_regusel", PUB) plt_regusel ``` ```text Output: /home/kam24goz/repos/cvanmf/src/cvanmf/denovo.py:1194: FutureWarning: The previous implementation of stack is deprecated and will be removed in a future version of pandas. See the What's New notes for pandas 2.1.0 for details. Specify future_stack=True to adopt the new implementation and silence this warning. /home/kam24goz/repos/cvanmf/src/cvanmf/denovo.py:1298: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning. /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 2.66 x 1.8 in image. /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: cell_imgs/a_regusel.png /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 2.66 x 1.8 in image. /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: cell_imgs/a_regusel.pdf ``` -------------------------------- ### Run cvanmf pipeline with conda profile Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Executes the cvanmf pipeline on a sample matrix with ranks 2 and 3, 3 iterations, and 3 shuffles, using the conda profile to create an environment automatically. ```bash nextflow run apduncan/cvanmf -r main -profile conda \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --num_shuffles 3 ``` -------------------------------- ### Import required libraries for rank analysis Source: https://github.com/apduncan/cvanmf/blob/main/resources/cva_rank_analysis.ipynb Imports cvanmf, pickle, and plotnine needed for loading rank selection results and plotting. ```python from cvanmf import denovo import pickle import plotnine as p9 ``` -------------------------------- ### Plot bicrossvalidation rank selection and save with figure_output Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates a plotnine figure for bicrossvalidation rank selection using denovo.plot_rank_selection, customizes it with guides, theme, title, labels, and y-axis expansion, then passes it to figure_output to save as PNG, PDF, and TSV. The plot is displayed in the notebook by using it as the final line of the cell. The output shows FutureWarnings about pandas deprecations and PlotnineWarning messages about saving files. ```python plt_ranksel = ( denovo.plot_rank_selection(rank_res, jitter=False) + pn.guides(fill = "none") + pn.theme(figure_size=(2.66 * 2, 1.8)) + pn.ggtitle("Bicrossvalidation Rank Selection") + pn.xlab("Rank") + pn.ylab("") # We're adding a little more room for the stars - the internal calculation doesn't always get the right space for custom size plots + pn.scale_y_continuous(expand=[0.1, 0, 0.1, 0]) ) figure_output(plt_ranksel, "a_ranksel", PUB) # You can show the figure in the notebook by using it as the final line of the cell plt_ranksel ``` ```text Output: /home/kam24goz/repos/cvanmf/src/cvanmf/denovo.py:1194: FutureWarning: The previous implementation of stack is deprecated and will be removed in a future version of pandas. See the What's New notes for pandas 2.1.0 for details. Specify future_stack=True to adopt the new implementation and silence this warning. /home/kam24goz/repos/cvanmf/src/cvanmf/denovo.py:1298: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning. /home/kam24goz/repos/cvanmf/src/cvanmf/denovo.py:1303: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 5.32 x 1.8 in image. /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: cell_imgs/a_ranksel.png /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:606: PlotnineWarning: Saving 5.32 x 1.8 in image. /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/ggplot.py:607: PlotnineWarning: Filename: cell_imgs/a_ranksel.pdf ``` -------------------------------- ### Configure Docker in Nextflow profile Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Configure Docker in a Nextflow profile to avoid specifying the image each run. Set docker.enabled = true and provide the container image in the process scope; remove any conda-related settings. ```groovy profiles { slurm { (...) docker.enabled = true process { // Remove any conda related settings as well container = 'ghcr.io/apduncan/cvanmf:latest-nf' // You could specify a path to a .sif image as well, if // you do not want Nextflow to try to pull and convert // the image. (...) } } } } ``` -------------------------------- ### Find conda environment path Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Shows the command to list conda environments and the expected output format, which includes the environment path. ```bash > mamba env list | grep cvapipe cvapipe /some/path/mambaforge/envs/cvapipe ``` -------------------------------- ### Load the decomposition model Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Loads the decomposition model from the specified path. ```python # Load the model top_model = denovo.Decomposition.load(model) ``` -------------------------------- ### Generate decompositions with decompositions() Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Creates 100 decompositions for ranks 3, 4, and 5, keeping the top 5 for each rank. The result is a dictionary keyed by rank, with the first decomposition having the lowest reconstruction error. Regularisation can be enabled via l1_ratio and alpha, but note that the same alpha is applied to all ranks. ```python decomps = decompositions(x, ranks=[3, 4, 5], top_n=5, random_starts=5, seed=4928, progress_bar=False) # or to use regularisation # decomps = decompositions(x, ranks=[3, 4, 5], top_n=5, random_starts=5, seed=4928, l1_ratio=1.0, alpha=best_alpha) decomps ``` -------------------------------- ### Import required libraries for stability analysis Source: https://github.com/apduncan/cvanmf/blob/main/resources/stab_rank_analysis.ipynb Imports the denovo module from cvanmf, plotnine, and pandas for data handling and plotting. ```python from cvanmf import denovo import plotnine as pn import pandas as pd ``` -------------------------------- ### Load a single decomposition from disk Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Loads an individual decomposition from a specific subdirectory (e.g., test_save/5/0/). ```python one_decomp = Decomposition.load(in_dir=pathlib.Path("test_save/5/0/")) one_decomp ``` -------------------------------- ### Create a git branch Source: https://github.com/apduncan/cvanmf/blob/main/CONTRIBUTING.md Create a new branch for your bugfix or feature development. ```console $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Verify total-sum scaling of composition Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Checks that each sample sums to 1 using np.allclose, confirming the data is total-sum-scaled. ```python np.allclose(composition.sum(axis=0), 1.0) ``` ```text Result: True ``` -------------------------------- ### Load rank results and output as table Source: https://github.com/apduncan/cvanmf/blob/main/resources/cva_rank_analysis.ipynb Loads the rank selection results from 'rank_combined.pickle' and writes them to 'rank_analysis.tsv' as a tab-separated table. ```python # Output the results as a table as well with open("rank_combined.pickle", "rb") as f: rank_res = pickle.load(f) deno.BicvResult.results_to_table(rank_res).to_csv('rank_analysis.tsv', sep="\t") ``` -------------------------------- ### Run container as current user Source: https://github.com/apduncan/cvanmf/blob/main/docs/docker.md Executes the container while mapping host user IDs to prevent output files from being owned by root on Linux or MacOS. ```bash docker run \ --mount type=bind,src="${PWD}/example/",dst=/mnt/data/ \ --volume /etc/passwd:/etc/passwd:ro \ --volume /etc/group:/etc/group:ro \ --user $(id -u) \ ghcr.io/apduncan/cvanmf:latest \ reapply \ -i /mnt/data/data.tsv \ -m 5es \ -o /mnt/data/results ``` -------------------------------- ### Inspect composition matrix head Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Displays the first rows and columns of the composition data stored in the data property of the loaded dataset. ```python composition = lung_data.data composition.head().iloc[:,:3] ``` ```text Result: Adams_Kaminski_2020_001C \ cell_type B cell 0.019485 CD1c-positive myeloid dendritic cell 0.012571 CD4-positive, alpha-beta T cell 0.006285 CD8-positive, alpha-beta T cell 0.012571 alveolar macrophage 0.293526 Adams_Kaminski_2020_002C \ cell_type B cell 0.030466 CD1c-positive myeloid dendritic cell 0.007168 CD4-positive, alpha-beta T cell 0.021505 CD8-positive, alpha-beta T cell 0.014337 alveolar macrophage 0.367384 Adams_Kaminski_2020_003C cell_type B cell 0.038913 CD1c-positive myeloid dendritic cell 0.032539 CD4-positive, alpha-beta T cell 0.023482 CD8-positive, alpha-beta T cell 0.042603 alveolar macrophage 0.300906 ``` -------------------------------- ### Import cvanmf modules for de-novo analysis Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Imports seaborn, pathlib, and cvanmf modules needed for de-novo signature discovery, including rank selection, decompositions, and models. ```python import seaborn as sns import pathlib from cvanmf.denovo import rank_selection, plot_rank_selection, decompositions, Decomposition from cvanmf import models, data ``` -------------------------------- ### Run regu_selection for L1 regularisation Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Tests alpha values for rank 4 with l1_ratio=1.0 (pure L1). Uses 10 shuffles (default 100) for speed. Returns best_alpha and results. ```python best_alpha, regu_sel_res = regu_selection(x=x, rank=4, shuffles=10, seed=4298, l1_ratio=1.0, progress_bar=False) # shuffles sets the number iterations of bi-crossvalidation which are run. # The default is 100, it has been set lower here to make the documentation easier to compile, but 100 is a more # sensible value for real data ``` -------------------------------- ### Print model parameters Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Displays the model parameters excluding the input matrix. ```python # Print the parameters, except the input matrix {k:v for k,v in top_model.parameters._asdict().items() if k != 'x'} ``` -------------------------------- ### Create different synthetic dataset Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Generates a synthetic dataset with fewer features (m=75) and a different number of blocks (k=3) compared to the original, and displays it as a heatmap. This dataset should be handled poorly by the existing model. ```python y_different = data.synthetic_blocks( m=75, overlap=0.4, k=3, scale_lognormal_params=dict(sigma=0.75) ).data sns.heatmap(y_different) ``` -------------------------------- ### Import cvanmf and plotting libraries Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Imports the cvanmf modules (denovo, combine, data, stability) along with pandas, plotnine, numpy, matplotlib, and pathlib for the analysis. ```python from cvanmf import denovo, combine, data, stability import pandas as pd import plotnine as pn import numpy as np import matplotlib.pyplot as plt import pathlib ``` -------------------------------- ### Run rank_selection with bi-crossvalidation Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Runs bi-crossvalidation for ranks 2 to 6 with 20 shuffles. The default shuffles is 100, but it is set lower here for documentation speed. The seed is set for reproducibility. ```python rank_sel_res = rank_selection(x=x, ranks=range(2, 7), shuffles=20, seed=4298, progress_bar=False) # shuffles sets the number iterations of bi-crossvalidation which are run. # The default is 100, it has been set lower here to make the documentation easier to compile, but 100 is a more # sensible value for real data ``` -------------------------------- ### Pull Singularity image Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Creates a Singularity image from the Docker image on a system with internet access. The resulting image.sif file must be accessible to all compute nodes. ```bash singularity pull image.sif docker://ghcr.io/apduncan/cvanmf:0.3.1-nf ``` -------------------------------- ### Load all decompositions from disk Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Loads all decompositions previously saved in the given directory. The loaded_decomps object is then displayed. ```python loaded_decomps = Decomposition.load_decompositions(in_dir=pathlib.Path("test_save")) loaded_decomps ``` -------------------------------- ### Import regu_selection and plot_regu_selection Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Imports the functions needed for regularisation selection. ```python from cvanmf.denovo import regu_selection, plot_regu_selection ``` -------------------------------- ### List saved decomposition files Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Shell command to list the files created by the save operation, showing the directory structure under test_save. ```bash ! ls test_save/**/** ``` -------------------------------- ### Slice decomposition by samples and signatures Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Indexes a decomposition by sample, feature, and signature in that order. Supports slice syntax, lists of index names, or lists of index positions. Here, restricts to the first 50 samples and signatures S1, S3, S4, then renders the relative weight plot. ```python decomp_slcd = decomps[4][0][:50, :, ["S1", "S3", "S4"]] decomp_slcd.plot_relative_weight(heights=[0.3, 1, 0.2]).render() ``` -------------------------------- ### Plot feature weights with default settings Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates a feature weight plot using plot_feature_weight, showing all features above 4% of overall signature weights by default. Adds extra space left and right of the bubbles via scale_x_discrete. The output shows a PlotnineWarning about an existing x scale being replaced. ```python plt_weight = ( k3.plot_feature_weight() + pn.theme( figure_size=(4.2, 2.5) ) + pn.ggtitle("Feature Weight") + pn.scale_x_discrete(expand=(0.1, 0.0, 0.15, 0.0)) # This adds a little more room left and right of the bubbles ) plt_weight ``` ```text /home/kam24goz/miniforge3/envs/cvanmf/lib/python3.12/site-packages/plotnine/scales/scales.py:48: PlotnineWarning: Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale. ``` -------------------------------- ### Load regularization results from pickle Source: https://github.com/apduncan/cvanmf/blob/main/resources/cva_regu_analysis.ipynb Loads a pickle file containing regularization results into the variable rank_res. ```python with open("regu_combined.pickle", "rb") as f: rank_res = pickle.load(f) ``` -------------------------------- ### Run rank selection with denovo.rank_selection Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Searches ranks 2 to 10 using denovo.rank_selection with a fixed seed, 100 shuffles, and progress bar disabled. The result is used to identify an elbow point in the values. ```python rank_res = denovo.rank_selection( x=composition, ranks=list(range(2, 11)), seed=4298, shuffles=100, progress_bar=False ) ``` -------------------------------- ### Compare weight matrices after reapply Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Checks that the weight matrix of the reapplied decomposition matches the original decomposition's weight matrix for the features present in the new data. ```python decomps[4][0].w.loc[d_different.w.index] == d_different.w ``` -------------------------------- ### Plot model fit per sample Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Visualizes model fit for each sample as a dot plot, with custom sizing based on the number of samples. ```python # Make the plot wider when there are more samples modelfit_point_width = min((sliced_model.h.shape[1] / PLOT_MODELFIT_PPI) + 1, PLOT_MODELFIT_MAX_WIDTH) # Customise width and text ( sliced_model.plot_modelfit_point() + pn.theme( figure_size=(modelfit_point_width, 2), axis_text_x=pn.element_text(size=7) ) + pn.ggtitle("Model Fit") ) ``` -------------------------------- ### Define model path Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Sets the file path for the decomposition model to be loaded. ```python # Parameters for decomposition generation # All left None unless provided, so use cvanmf defaults model = "../output/4/model" ``` -------------------------------- ### Create PCoA plot on signature weights Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates a PCoA ordination plot using the plot_pcoa method on the 'h' (signature weights) data, colored by tumor stage and shaped by signature. Uses plotnine theme, custom color scale, and removes the point color legend. The plot is saved via figure_output and displayed. ```python plt_pcoa = ( k3.plot_pcoa(on="h", color=sample_md['tumor_stage'], shape="signature") + pn.theme(figure_size=(4.3, 4), legend_position="bottom") + pn.ggtitle("PCoA on Signature Weights") + pn.scale_color_manual( values=list(stage_color.values()), breaks=list(stage_color.keys()) ) # We're removing the point colour legend, as it will be indicated on another figure in the publication + pn.guides( color="none" ) ) figure_output(plt_pcoa, "c_pcoa", PUB) plt_pcoa ``` -------------------------------- ### Extract modelfit/stage posthoc results Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Filters univariate results to the modelfit signature and Tumor Stage metadata, then retrieves the posthoc string. The output shows only the advanced vs none comparison was significant below the default alpha of 0.05. ```python # To extract only the modelfit / stage tests univar_results[ (univar_results['signature'] == "modelfit") & (univar_results['md'] == 'Tumor Stage') ]['posthoc_str'] ``` -------------------------------- ### Reorder samples in a decomposition Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Shows how to reorder samples in a decomposition using the slicing syntax. Here, a random order is generated and applied, then the relative weight plot is rendered. ```python # Reorder samples - here we're just generating a random order import random new_order = list(range(decomps[4][0].h.shape[1])) random.shuffle(new_order) # Reorder the decomposition decomps[4][0][new_order].plot_relative_weight(heights=[0.3, 1, 0.2]).render() ``` -------------------------------- ### Resume failed cvanmf run with -resume flag Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Resumes a previously failed cvanmf pipeline run by adding the -resume flag, using the same parameters as the initial run. ```bash nextflow run apduncan/cvanmf -r main -profile conda -resume \ --matrix sample.tsv --ranks 2,3 --publish_dir output/sample --num_shuffles 3 ``` -------------------------------- ### Configure Singularity in Nextflow profile Source: https://github.com/apduncan/cvanmf/blob/main/docs/nextflow.md Configure Singularity in a Nextflow profile to avoid specifying the container each run. Set singularity.enabled = true and provide the container image (or a .sif path) in the process scope; remove any conda-related settings. ```groovy profiles { slurm { (...) singularity.enabled = true process { // Remove any conda related settings as well container = 'docker://ghcr.io/apduncan/cvanmf:latest-nf' // You could specify a path to a .sif image as well, if // you do not want Nextflow to try to pull and convert // the image. (...) } } } } ``` -------------------------------- ### Plot continuous metadata variables Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Displays a plot for continuous metadata variables using the 'cont' object and a custom theme with figure size 6 by 6. The source notes there is not much interesting to see. ```python cont + pn.theme(figure_size=(6, 6)) ``` -------------------------------- ### Reapply model to similar data Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Reapplies the best rank-4 decomposition to the similar dataset and renders the relative weight plot. The model describes the similar data reasonably well. ```python d_similar = decomps[4][0].reapply( y=y_similar ) d_similar.plot_relative_weight(heights=[0.3, 1, 0.2]).render() ``` -------------------------------- ### Export results to TSV Source: https://github.com/apduncan/cvanmf/blob/main/resources/cva_regu_analysis.ipynb Converts the regularization results to a table and saves it as a tab-separated file named 'regu_analysis.tsv'. ```python denovo.BicvResult.results_to_table(rank_res).to_csv('regu_analysis.tsv', sep="\t") ``` -------------------------------- ### Create relative weight plot Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Creates a relative weight plot using plot_relative_weight, showing stacked bars, a ribbon for tumor stage metadata, and a point plot of model fit. Includes a known bug where group colors are applied reversed, and uses Marsilea for rendering. ```python fig = k3.plot_relative_weight( # The metadata to show groups for. It will appear in the order and with the name we give it here in this series. group=( sample_md['tumor_stage'] .rename('Tumor Stage') .sort_values(ascending=False) ), # The colours should be provided as a series # There is currently a bug here, where the colours are applied reversed. group_colors=pd.Series( reversed(list(stage_color.values())), index=list(stage_color.keys()) ), model_fit=False, heights=[0.25, 1, 0], sample_label_size=False, legend_cols_grp=2, legend_cols_sig=2, width=4, point_size=0.1, threshold=None, legend_side="top" ) # The relative weight plot is produced by Marsilea, so unfortunately currently has a slightly different way to display and save fig.render() plt.show() ``` -------------------------------- ### Compute and plot signature stability for a single decomposition Source: https://github.com/apduncan/cvanmf/blob/main/docs/cell_example.ipynb Calculates signature stability for the best decomposition (decomps[3]) and plots it with custom styling. Signatures are mostly highly similar, but S3 has outliers with no similar signature in some decompositions. ```python sig_stability = stability.signature_stability( decomps[3], decomps[3][0] ) plt_stability = ( stability.plot_signature_stability( sig_stability, k3.colors ) + pn.ggtitle("Signature\nStability") + pn.theme(figure_size=(2.5, 3)) + pn.guides(fill="none") ) plt_stability ``` -------------------------------- ### Define utility constants Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Sets constants for plot sizing and sample limits to manage large datasets. ```python # Some utility constants for sizing plots etc. # for plot_modelfit_point # The number of samples that will be represent in one inch of horizontal space PLOT_MODELFIT_PPI = 20 # Maximum width allowed for plot PLOT_MODELFIT_MAX_WIDTH = 20 # Limit on number of samples to plot for large studies MAX_SAMPLES_PER_PLOT = 250 ``` -------------------------------- ### Inspect H matrix of reapply results Source: https://github.com/apduncan/cvanmf/blob/main/docs/reapply.ipynb Displays the first five rows and columns of the H matrix from the reapply result. The H matrix contains the Enterosignature weights for each sample. ```python result.h.head().iloc[:, :5] ``` -------------------------------- ### Render relative weight plot with model fit overlay Source: https://github.com/apduncan/cvanmf/blob/main/resources/rank_decomposition.ipynb Creates a relative weight plot showing signature weights per sample (scaled to sum to 1) with a model fit point plot appended on top. This plot is not a plotnine.ggplot object, so widths are set in the call. It can be expensive to produce with many signatures or samples. ```python legend_cols = (sliced_model.w.shape[1] // 6) + 1 sliced_model.plot_relative_weight( heights=[0.3, 0.7, 0.3], width=modelfit_point_width, point_size=.4, legend_cols_v=legend_cols, ).render() plt.show() ``` -------------------------------- ### Display best_alpha Source: https://github.com/apduncan/cvanmf/blob/main/docs/denovo.ipynb Prints the best alpha value selected by regu_selection. ```python best_alpha ```