### Environment Setup with LIANA and Scanpy Source: https://liana-py.readthedocs.io/en/latest/notebooks/bivariate.html Imports necessary libraries for spatial analysis and sets figure DPI for smaller notebook output. Ensure these libraries are installed. ```python import pandas as pd import scanpy as sc import decoupler as dc import liana as li from matplotlib import pyplot as plt # set dpi to 50, to make the notebook smaller plt.rcParams['figure.dpi'] = 50 from mudata import MuData ``` -------------------------------- ### Install LIANA with All Extras Source: https://liana-py.readthedocs.io/en/latest/installation.html Install LIANA along with all optional dependencies for extended functionality. ```bash pip install 'liana[extras]' ``` -------------------------------- ### Install LIANA from Source for Development Source: https://liana-py.readthedocs.io/en/latest/installation.html Clone the repository and install LIANA in editable mode with development dependencies. ```bash git clone https://github.com/saezlab/liana-py.git cd liana-py pip install -e '.[dev]' ``` -------------------------------- ### Install Required Python Packages Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Install necessary libraries for MOFA, LIANA, and data handling using pip. ```bash pip install "decoupler>=2.0.0" pip install mofax pip install muon pip install omnipath pip install marsilea ``` -------------------------------- ### Install LIANA with Pip Source: https://liana-py.readthedocs.io/en/latest/installation.html Use this command to install the core LIANA package using pip. ```bash pip install liana ``` -------------------------------- ### Load example dataset Source: https://liana-py.readthedocs.io/en/latest/notebooks/basic_usage.html Load a pre-processed example dataset using scanpy's built-in datasets. This data is suitable for demonstrating liana's functionality. ```python adata = sc.datasets.pbmc68k_reduced() ``` -------------------------------- ### Install Pre-commit Hooks Source: https://liana-py.readthedocs.io/en/latest/contributing.html Install pre-commit locally to automatically enforce code styles on every commit. Dependencies are downloaded on the first run. ```bash pre-commit install ``` -------------------------------- ### Load Example Dataset with LIANA Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Load the pre-processed 'kang_2018' dataset using LIANA's testing utility. ```python adata = li.testing.datasets.kang_2018() ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://liana-py.readthedocs.io/en/latest/contributing.html Manually install development and testing dependencies using pip within a virtual environment. ```bash cd liana python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev,test,doc,extras]" ``` -------------------------------- ### Build Documentation Locally with Hatch Source: https://liana-py.readthedocs.io/en/latest/contributing.html Use Hatch to build and open the documentation locally. Ensure you have Hatch installed and configured for the project. ```bash hatch run docs:build hatch run docs:open ``` -------------------------------- ### Install Required Packages Source: https://liana-py.readthedocs.io/en/latest/notebooks/liana_c2c.html Installs necessary Python packages for cell-cell communication analysis using pip. ```bash pip install liana cell2cell decoupler omnipath seaborn==0.11 ``` -------------------------------- ### Load example dataset Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Loads the kang_2018 dataset, which contains ~25k PBMCs from 8 pooled patient lupus samples, each before and after IFN-beta stimulation. ```python adata = li.testing.datasets.kang_2018() ``` -------------------------------- ### Install MOFAcellular and related packages Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Installs necessary packages including decoupler, mofax, muon, omnipath, and marsilea using pip. Ensure you have decoupler version 2.0.0 or higher. ```bash pip install "decoupler>=2.0.0" pip install mofax pip install muon pip install omnipath pip install marsilea ``` -------------------------------- ### Load Required Packages Source: https://liana-py.readthedocs.io/en/latest/notebooks/inflow_score.html Installs and imports necessary Python libraries for single-cell analysis, including scanpy, liana, muon, and squidpy. ```python import numpy as np import pandas as pd import scanpy as sc import liana as li import muon as mu import anndata as ad import seaborn as sns import matplotlib.pyplot as plt import plotnine as p9 import squidpy as sq import os ``` -------------------------------- ### Install LIANA with Conda Source: https://liana-py.readthedocs.io/en/latest/installation.html Use this command to install LIANA via the bioconda channel using conda. ```bash conda install bioconda::liana ``` -------------------------------- ### Load Example Dataset Source: https://liana-py.readthedocs.io/en/latest/notebooks/liana_c2c.html Loads a pre-processed Anndata object for ~25k PBMCs from 8 pooled patient lupus samples, each before and after IFN-beta stimulation, using LIANA's testing datasets. ```python # load data as from CCC chapter ada = li.testing.datasets.kang_2018() ``` -------------------------------- ### Get method description Source: https://liana-py.readthedocs.io/en/latest/notebooks/basic_usage.html Obtain a short summary for a specific liana inference method, such as 'rank_aggregate'. This provides insights into its implementation and scoring. ```python li.mt.rank_aggregate.describe() ``` -------------------------------- ### Get and Pivot Ligand-Receptor Loadings Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Extracts variable loadings for ligand-receptor interactions from the MOFA+ model and pivots the data to have views as columns. Missing values are replaced with 0. ```python lr_loadings = li.ut.get_variable_loadings(mdata, varm_key='LFs', view_sep=':', ) lr_loadings.set_index('variable', inplace=True) # pivot views to wide lr_loadings = lr_loadings.pivot(columns='view', values='Factor1') # replace NaN with 0 lr_loadings.replace(np.nan, 0, inplace=True) lr_loadings.head() ``` -------------------------------- ### Get and Process Variance Explained (R2) Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Retrieves the R-squared values (variance explained) from the MOFA+ model for each view and factor. It then filters for Factor 1 and separates the 'View' column into 'source' and 'target' for further analysis. ```python # get variance explained by view and factor rsq = model.get_r2() factor1_rsq = rsq[rsq['Factor']=='Factor1'] # separate view column factor1_rsq[['source', 'target']] = factor1_rsq['View'].str.split(pat='&', n=1, expand=True) ``` -------------------------------- ### Build Documentation Locally with Sphinx Source: https://liana-py.readthedocs.io/en/latest/contributing.html Manually build the documentation using Sphinx after activating the virtual environment and navigating to the docs directory. Open the generated HTML index file to view the documentation. ```bash source .venv/bin/activate cd docs sphinx-build -M html . _build -W (xdg-)open _build/html/index.html ``` -------------------------------- ### Create and Find Hatch Test Environments Source: https://liana-py.readthedocs.io/en/latest/contributing.html Create test environments for all supported Python versions or list their paths using hatch. ```bash hatch env create hatch-test hatch env find hatch-test ``` -------------------------------- ### Run Hatch Environments for Tests and Docs Source: https://liana-py.readthedocs.io/en/latest/contributing.html Use hatch to run tests or build documentation. These commands are defined in the pyproject.toml file. ```bash hatch test hatch run docs:build ``` -------------------------------- ### MistyData.mod_names Source: https://liana-py.readthedocs.io/en/latest/generated/liana.method.MistyData.html Gets the names of the modalities within the MuData object. ```APIDOC ## MistyData.mod_names ### Description Names of modalities (alias for `list(mdata.mod.keys())`) This property is read-only. ``` -------------------------------- ### rank_aggregate.__call__ Source: https://liana-py.readthedocs.io/en/latest/generated/liana.method.rank_aggregate.__call__.html Get an aggregate of ligand-receptor scores from multiple methods. ```APIDOC ## rank_aggregate.__call__ ### Description Get an aggregate of ligand-receptor scores from multiple methods. ### Method Signature `rank_aggregate.__call__(_groupby_ , _resource_name ='consensus'_, _expr_prop =0.1_, _min_cells =5_, _groupby_pairs =None_, _base =np.float64(2.718281828459045)_, _aggregate_method ='rra'_, _consensus_opts =None_, _return_all_lrs =False_, _key_added ='liana_res'_, _use_raw =True_, _layer =None_, _de_method ='t-test'_, _n_perms =1000_, _seed =1337_, _n_jobs =1_, _resource =None_, _interactions =None_, _mdata_kwargs =None_, _spatial_key =None_, _spatial_kwargs =None_, _inplace =True_, _verbose =False_) ### Parameters * **adata** (`AnnData` | `MuData`) – Annotated data object. * **groupby** (`str`) – Key to be used for grouping. * **resource_name** (`str` (default: `'consensus'`)) – Name of the resource to be used for ligand-receptor inference. See `li.rs.show_resources()` for available resources. * **expr_prop** (`float` (default: `0.1`)) – Minimum expression proportion for the ligands and receptors (+ their subunits) in the corresponding cell identities. Set to 0 to return unfiltered results. * **min_cells** (`int` (default: `5`)) – Minimum cells (per cell identity if grouped by `groupby`) to be considered for downstream analysis. * **groupby_pairs** (`DataFrame` | `None` (default: `None`)) – A DataFrame with columns `source` and `target` to be used to subset the possible combinations of interacting cell types. If None, all possible combinations are used. * **base** (`float` (default: `np.float64(2.718281828459045)`)) – Exponent base used to reverse the log-transformation of the matrix. Relevant only for the `logfc` method. * **aggregate_method** (`str` (default: `'rra'`)) – Method aggregation approach, one of [‘mean’, ‘rra’], where `mean` represents the mean rank, while ‘rra’ is the RobustRankAggregate (Kolde et al., 2014) of the interactions * **consensus_opts** (`list` | `None` (default: `None`)) – Strategies to aggregate interactions across methods. Default is None - i.e. [‘Specificity’, ‘Magnitude’] and both specificity and magnitude are aggregated. * **return_all_lrs** (`bool` (default: `False`)) – Bool whether to return all ligand-receptor pairs, or only those that surpass the `expr_prop` threshold. Ligand-receptor pairs that do not pass the `expr_prop` threshold will be assigned to the _worst_ score of the ones that do. `False` by default. * **key_added** (`str` (default: `'liana_res'`)) – Key under which the results will be stored in `adata.uns` if `inplace` is True. * **use_raw** (`bool` | `None` (default: `True`)) – Use raw attribute of adata if present. * **layer** (`str` | `None` (default: `None`)) – Layer in anndata.AnnData.layers to use. If None, use anndata.AnnData.X. * **de_method** (`str` (default: `'t-test'`)) – Differential expression method. `scanpy.tl.rank_genes_groups` is used to rank genes according to 1vsRest. The default method is ‘t-test’. * **verbose** (`bool` | `None` (default: `False`)) – Verbosity flag. * **n_perms** (`int` (default: `1000`)) – Number of permutations for the permutation test. Relevant only for permutation-based methods (e.g., `CellPhoneDB`). If `None` is passed, no permutation testing is performed. * **seed** (`int` (default: `1337`)) – Random seed for reproducibility. * **n_jobs** (`int` (default: `1`)) – Number of jobs to run in parallel. * **resource** (`DataFrame` | `None` (default: `None`)) – A pandas dataframe with [`ligand`, `receptor`] columns. If provided will overrule the resource requested via `resource_name` * **interactions** (`list` | `None` (default: `None`)) – List of tuples with ligand-receptor pairs `[(ligand, receptor), ...]` to be used for the analysis. If passed, it will overrule the resource requested via `resource` and `resource_name`. * **mdata_kwargs** (`dict` | `None` (default: `None`)) – Keyword arguments to be passed to `li.fun.mdata_to_anndata` if `adata` is an instance of `MuData`. If an AnnData object is passed, these arguments are ignored. * **spatial_key** (`str` | `None` (default: `None`)) – Key in `adata.obsm` that contains the spatial coordinates. Default is `'spatial'`. * **spatial_kwargs** (`dict` | `None` (default: `None`)) – Keyword arguments passed to `liana.utils.spatial_pair_proximity()` for computing spatial proximity weights. Default is None, which uses default values (bandwidth=250, kernel=’gaussian’, trim_fraction=0.1). * **inplace** (`bool` (default: `True`)) – Whether to store results in place, or else to return them. ### Returns If `inplace = False`, returns a `DataFrame` with ligand-receptor results Otherwise, modifies the `adata` object with the following key: > * `anndata.AnnData.uns` `['liana_res']` with the aforementioned DataFrame ``` -------------------------------- ### geometric_mean.__call__ Source: https://liana-py.readthedocs.io/en/latest/api.html Gets an aggregate of ligand-receptor scores from multiple methods using geometric mean. ```APIDOC ## geometric_mean.__call__ ### Description Gets an aggregate of ligand-receptor scores from multiple methods using geometric mean. ### Method callable ### Parameters #### Path Parameters - **groupby** (str) - Description of groupby parameter - **...** - Other parameters may be available ``` -------------------------------- ### Get Metalinks Values Source: https://liana-py.readthedocs.io/en/latest/api.html Fetches distinct values from a specified column in a specified table. ```python get_metalinks_values(table_name, column_name) ``` -------------------------------- ### Show Available Resources Source: https://liana-py.readthedocs.io/en/latest/api.html Show available resources for prior knowledge. ```python show_resources() ``` -------------------------------- ### Get Metalinks Source: https://liana-py.readthedocs.io/en/latest/api.html Fetches edges of metabolite-proteins with specified annotations, applying filters if they are not None. ```python get_metalinks([db_path, types, ...]) ``` -------------------------------- ### Get Unique Sources from Liana Results Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Extract the unique source identifiers from the Liana results DataFrame. ```python adata.uns["liana_res"]['source'].unique() ``` -------------------------------- ### Import Libraries and Initialize Settings Source: https://liana-py.readthedocs.io/en/latest/notebooks/liana_c2c.html Imports essential Python libraries for data analysis, plotting, and LIANA/cell2cell functionalities. Includes warning filters and sets up matplotlib for inline plotting. Also configures PyTorch and TensorLy for GPU acceleration if available. ```python import pandas as pd import scanpy as sc import plotnine as p9 import liana as li import cell2cell as c2c import decoupler as dc # needed for pathway enrichment import warnings warnings.filterwarnings('ignore') from collections import defaultdict %matplotlib inline ``` ```python # NOTE: to use CPU instead of GPU, set use_gpu = False use_gpu = True if use_gpu: import torch import tensorly as tl device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": tl.set_backend('pytorch') else: device = "cpu" device ``` -------------------------------- ### Display available inference methods Source: https://liana-py.readthedocs.io/en/latest/notebooks/basic_usage.html List all available ligand-receptor inference methods within the liana package. Each method has different statistical approaches and scoring mechanisms. ```python li.mt.show_methods() ``` -------------------------------- ### Run Ligand-Receptor Method Source: https://liana-py.readthedocs.io/en/latest/api.html Callable ligand-receptor method instances provide helper functions to describe and run each method instance. ```python cellchat.__call__(groupby[, resource_name, ...]) ``` ```python cellphonedb.__call__(groupby[, ...]) ``` ```python connectome.__call__(groupby[, ...]) ``` ```python logfc.__call__(groupby[, resource_name, ...]) ``` ```python natmi.__call__(groupby[, resource_name, ...]) ``` ```python singlecellsignalr.__call__(groupby[, ...]) ``` ```python geometric_mean.__call__(groupby[, ...]) ``` ```python rank_aggregate.__call__(groupby[, ...]) ``` -------------------------------- ### Get Ligand-Receptor Loadings Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Retrieves ligand-receptor loadings for a specified factor from the MuData object. Allows custom separators for complex names. ```python variable_loadings = li.ut.get_variable_loadings(mdata, varm_key='LFs', view_sep=':', pair_sep="&", variable_sep="^") # get loadings for factor 1 ``` -------------------------------- ### Run Hatch Tests Source: https://liana-py.readthedocs.io/en/latest/contributing.html Execute tests using hatch, either with the highest supported Python version or with all supported versions. ```bash hatch test # or hatch test --all ``` -------------------------------- ### Import Python Libraries for MOFA Analysis Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Import core libraries including numpy, pandas, scanpy, plotnine, liana, muon, mofax, and decoupler for data manipulation, analysis, and visualization. ```python import numpy as np import pandas as pd import scanpy as sc import plotnine as p9 import liana as li # load muon and mofax import muon as mu import mofax as mofa import decoupler as dc ``` -------------------------------- ### show_resources Source: https://liana-py.readthedocs.io/en/latest/api.html Show available resources in LIANA. ```APIDOC ## show_resources ### Description Show available resources in LIANA. ``` -------------------------------- ### Get Factor Scores as DataFrame Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Retrieves factor scores from the MuData object as a pandas DataFrame, including specified observation keys for context. ```python factor_scores = li.ut.get_factor_scores(mdata, obsm_key='X_mofa', obs_keys=['patient', 'condition']) ``` -------------------------------- ### Get and Sort Variable Loadings Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Retrieves variable loadings from a MOFA model and sorts them by the absolute value of 'Factor1'. Ensure 'mdata' and 'li.ut' are imported and the model is loaded. ```python variable_loadings = li.ut.get_variable_loadings(mdata, varm_key='LFs', view_sep=':') # get loadings # order features by absolute value for Factor 1 variable_loadings = variable_loadings.sort_values(by='Factor1', key=lambda x: abs(x), ascending=False) variable_loadings.head() ``` -------------------------------- ### Load and Inspect MOFA Model Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Loads a MOFA+ model from an .h5ad file and prints a summary of its components. Ensure the 'mofa' library is imported and the model path is correct. ```python model = mofa.mofa_model("models/mofacellx.h5ad") model ``` -------------------------------- ### Get Human-Mouse Ortholog Mappings Source: https://liana-py.readthedocs.io/en/latest/notebooks/inflow_score.html Retrieve ortholog mappings between human and mouse gene symbols from the HCOP database. This is useful for cross-species analysis and ensuring compatibility of gene annotations. ```python map_df = li.rs.get_hcop_orthologs(url='https://ftp.ebi.ac.uk/pub/databases/genenames/hcop/human_mouse_hcop_fifteen_column.txt.gz', columns=['human_symbol', 'mouse_symbol'], # NOTE: HCOP integrates multiple resource, so we can filter out mappings in at least 3 of them for confidence min_evidence=3 ) map_df = map_df.rename(columns={'human_symbol':'source', 'mouse_symbol':'target'}) ``` -------------------------------- ### Initialize MISTy with RandomForestModel Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Construct a MISTy object using RandomForestModel for fitting individual random forests per target. Set n_jobs to -1 for maximum parallelism and verbose to True for detailed output. ```python misty(model=RandomForestModel, n_jobs=-1, verbose = True) ``` -------------------------------- ### Select Prior Knowledge Resource Source: https://liana-py.readthedocs.io/en/latest/api.html Read a resource of choice from the pre-generated resources in LIANA. ```python select_resource([resource_name]) ``` -------------------------------- ### show_resources() Source: https://liana-py.readthedocs.io/en/latest/generated/liana.resource.show_resources.html This function displays a list of all available resources that can be selected using the select_resource function. ```APIDOC ## show_resources() ### Description Show available resources. ### Returns A list of resource names available via `liana.resource.select_resource` ``` -------------------------------- ### Run Pytest Tests Source: https://liana-py.readthedocs.io/en/latest/contributing.html Activate your virtual environment and run pytest from the repository root to execute all tests. ```bash source .venv/bin/activate pytest ``` -------------------------------- ### Get MOFA Factor Scores Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Retrieves MOFA factor scores from the MuData object. This function simplifies accessing the factor scores and associated metadata, making it easier to perform statistical tests or further analysis. ```python # obtain factor scores factor_scores = li.ut.get_factor_scores(mdata, obsm_key='X_mofa', obs_keys=['condition', 'patient']) ``` -------------------------------- ### logfc.__call__() Source: https://liana-py.readthedocs.io/en/latest/generated/liana.method.logfc.__call__.html Runs a ligand-receptor method for interaction analysis. It takes an AnnData or MuData object and various parameters to configure the analysis, such as grouping keys, resource names, expression thresholds, and differential expression methods. Results can be stored in-place or returned as a DataFrame. ```APIDOC ## logfc.__call__() ### Description Run a ligand-receptor method. ### Parameters * **adata** (`AnnData` | `MuData`) – Annotated data object. * **groupby** (`str`) – Key to be used for grouping. * **resource_name** (`str` (default: `'consensus'`)) – Name of the resource to be used for ligand-receptor inference. See `li.rs.show_resources()` for available resources. * **expr_prop** (`float` (default: `0.1`)) – Minimum expression proportion for the ligands and receptors (+ their subunits) in the corresponding cell identities. Set to 0 to return unfiltered results. * **min_cells** (`int` (default: `5`)) – Minimum cells (per cell identity if grouped by `groupby`) to be considered for downstream analysis. * **groupby_pairs** (`DataFrame` | `None` (default: `None`)) – A DataFrame with columns `source` and `target` to be used to subset the possible combinations of interacting cell types. If None, all possible combinations are used. * **base** (`float` (default: `np.float64(2.718281828459045)`)) – Exponent base used to reverse the log-transformation of the matrix. Relevant only for the `logfc` method. * **supp_columns** (`list` | `None` (default: `None`)) – Additional columns to be added from any of the methods implemented in liana, or any of the columns returned by `scanpy.tl.rank_genes_groups`, each starting with ligand_* or receptor_*. For example, `['ligand_pvals', 'receptor_pvals']`. None by default. * **return_all_lrs** (`bool` (default: `False`)) – Bool whether to return all ligand-receptor pairs, or only those that surpass the `expr_prop` threshold. Ligand-receptor pairs that do not pass the `expr_prop` threshold will be assigned to the _worst_ score of the ones that do. `False` by default. * **key_added** (`str` (default: `'liana_res'`)) – Key under which the results will be stored in `adata.uns` if `inplace` is True. * **use_raw** (`bool` | `None` (default: `True`)) – Use raw attribute of adata if present. * **layer** (`str` | `None` (default: `None`)) – Layer in anndata.AnnData.layers to use. If None, use anndata.AnnData.X. * **de_method** (`str` (default: `'t-test'`)) – Differential expression method. `scanpy.tl.rank_genes_groups` is used to rank genes according to 1vsRest. The default method is ‘t-test’. * **verbose** (`bool` | `None` (default: `False`)) – Verbosity flag. * **n_perms** (`int` (default: `1000`)) – Number of permutations for the permutation test. Relevant only for permutation-based methods (e.g., `CellPhoneDB`). If `None` is passed, no permutation testing is performed. * **seed** (`int` (default: `1337`)) – Random seed for reproducibility. * **n_jobs** (`int` (default: `1`)) – Number of jobs to run in parallel. * **resource** (`DataFrame` | `None` (default: `None`)) – A pandas dataframe with [`ligand`, `receptor`] columns. If provided will overrule the resource requested via `resource_name` * **interactions** (`list` | `None` (default: `None`)) – List of tuples with ligand-receptor pairs `[(ligand, receptor), ...]` to be used for the analysis. If passed, it will overrule the resource requested via `resource` and `resource_name`. * **spatial_key** (`str` (default: `'spatial'`)) – Key in `adata.obsm` that contains the spatial coordinates. Default is `'spatial'`. * **spatial_kwargs** (`dict` | `None` (default: `None`)) – Keyword arguments passed to `liana.utils.spatial_pair_proximity()` for computing spatial proximity weights. Default is None, which uses default values (bandwidth=250, kernel=’gaussian’, trim_fraction=0.1). * **mdata_kwargs** (`dict` | `None` (default: `None`)) – Keyword arguments to be passed to `li.fun.mdata_to_anndata` if `adata` is an instance of `MuData`. If an AnnData object is passed, these arguments are ignored. * **inplace** (`bool` (default: `True`)) – Whether to store results in place, or else to return them. ### Returns If `inplace = False`, returns a `DataFrame` with ligand-receptor results Otherwise, modifies the `adata` object with the following key: - `anndata.AnnData.uns` `[`key_added`]` with the aforementioned DataFrame ``` -------------------------------- ### Estimate Cosine Similarity with Bivariate Analysis Source: https://liana-py.readthedocs.io/en/latest/notebooks/bivariate.html Calculates cosine similarity between cell types and TFs. Use `x_transform` and `y_transform` to make distributions comparable, for example, by z-scaling. The `local_name` parameter specifies the metric, and `mask_negatives` can be set to `True` to ignore negative values. ```python bdata = li.mt.bivariate(mdata, x_mod="comps", y_mod="tf", x_transform=sc.pp.scale, y_transform=sc.pp.scale, local_name="cosine", interactions=interactions, mask_negatives=True, add_categories=True, x_use_raw=False, y_use_raw=False, xy_sep="<->", x_name='celltype', y_name='tf' ) ``` -------------------------------- ### Import necessary Python libraries Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html Imports core libraries for data analysis and visualization, including numpy, pandas, scanpy, plotnine, liana, muon, mofax, and decoupler. ```python import numpy as np import pandas as pd import scanpy as sc import plotnine as p9 import liana as li # load muon and mofax import muon as mu import mofax as mofa import decoupler as dc ``` -------------------------------- ### Import Generic Packages for LIANA Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Imports essential libraries for spatial data analysis, including scanpy, decoupler, plotnine, and liana. ```python import scanpy as sc import decoupler as dc import plotnine as p9 import liana as li ``` -------------------------------- ### MOFA Model Output and Configuration Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html This output shows the loaded views and model configuration details for a MOFA analysis. It includes information on the number of samples and features per view, as well as prior settings and likelihoods for each view. ```text ######################################################### ### __ __ ____ ______ ### ### | \/ |/ __ \| ____/\ _ ### ### | \ / | | | | |__ / \ _| |_ ### ### | |\/| | | | | __/ /\ \_ _| ### ### | | | | |__| | | / ____ \|_| ### ### |_| |_|\____/|_|/_/ \_\ ### ### ### ######################################################### Loaded view='FGR3&CD14' group='group1' with N=16 samples and D=75 features... Loaded view='FGR3&DCs' group='group1' with N=16 samples and D=87 features... Loaded view='CD14&CD14' group='group1' with N=16 samples and D=81 features... Loaded view='FGR3&NK' group='group1' with N=16 samples and D=39 features... Loaded view='DCs&NK' group='group1' with N=16 samples and D=43 features... Loaded view='FGR3&FGR3' group='group1' with N=16 samples and D=79 features... Loaded view='DCs&CD14' group='group1' with N=16 samples and D=79 features... Loaded view='CD14&NK' group='group1' with N=16 samples and D=41 features... Loaded view='NK&CD8T' group='group1' with N=16 samples and D=33 features... Loaded view='CD14&DCs' group='group1' with N=16 samples and D=86 features... Loaded view='FGR3&CD8T' group='group1' with N=16 samples and D=46 features... Loaded view='CD8T&CD8T' group='group1' with N=16 samples and D=29 features... Loaded view='DCs&DCs' group='group1' with N=16 samples and D=89 features... Loaded view='CD14&FGR3' group='group1' with N=16 samples and D=79 features... Loaded view='DCs&FGR3' group='group1' with N=16 samples and D=82 features... Loaded view='B&CD8T' group='group1' with N=16 samples and D=36 features... Loaded view='DCs&CD8T' group='group1' with N=16 samples and D=51 features... Loaded view='CD4T&CD8T' group='group1' with N=16 samples and D=27 features... Loaded view='CD14&CD8T' group='group1' with N=16 samples and D=50 features... Loaded view='FGR3&CD4T' group='group1' with N=16 samples and D=33 features... Loaded view='DCs&CD4T' group='group1' with N=16 samples and D=37 features... Loaded view='CD14&CD4T' group='group1' with N=16 samples and D=31 features... Loaded view='CD8T&CD14' group='group1' with N=16 samples and D=33 features... Loaded view='NK&CD14' group='group1' with N=16 samples and D=45 features... Loaded view='B&CD14' group='group1' with N=16 samples and D=40 features... Loaded view='NK&FGR3' group='group1' with N=16 samples and D=43 features... Loaded view='CD8T&FGR3' group='group1' with N=16 samples and D=35 features... Loaded view='CD4T&CD14' group='group1' with N=16 samples and D=32 features... Loaded view='B&FGR3' group='group1' with N=16 samples and D=36 features... Loaded view='CD4T&FGR3' group='group1' with N=16 samples and D=37 features... Loaded view='NK&DCs' group='group1' with N=16 samples and D=46 features... Loaded view='B&DCs' group='group1' with N=16 samples and D=50 features... Loaded view='CD4T&DCs' group='group1' with N=16 samples and D=35 features... Loaded view='CD8T&DCs' group='group1' with N=16 samples and D=38 features... Loaded view='NK&NK' group='group1' with N=16 samples and D=26 features... Loaded view='B&NK' group='group1' with N=16 samples and D=26 features... Model options: - Automatic Relevance Determination prior on the factors: True - Automatic Relevance Determination prior on the weights: True - Spike-and-slab prior on the factors: False - Spike-and-slab prior on the weights: True Likelihoods: - View 0 (FGR3&CD14): gaussian - View 1 (FGR3&DCs): gaussian - View 2 (CD14&CD14): gaussian - View 3 (FGR3&NK): gaussian - View 4 (DCs&NK): gaussian - View 5 (FGR3&FGR3): gaussian - View 6 (DCs&CD14): gaussian - View 7 (CD14&NK): gaussian - View 8 (NK&CD8T): gaussian - View 9 (CD14&DCs): gaussian - View 10 (FGR3&CD8T): gaussian - View 11 (CD8T&CD8T): gaussian - View 12 (DCs&DCs): gaussian - View 13 (CD14&FGR3): gaussian - View 14 (DCs&FGR3): gaussian - View 15 (B&CD8T): gaussian - View 16 (DCs&CD8T): gaussian - View 17 (CD4T&CD8T): gaussian - View 18 (CD14&CD8T): gaussian - View 19 (FGR3&CD4T): gaussian - View 20 (DCs&CD4T): gaussian - View 21 (CD14&CD4T): gaussian - View 22 (CD8T&CD14): gaussian - View 23 (NK&CD14): gaussian ``` -------------------------------- ### Generate Ligand-Receptor Geneset Source: https://liana-py.readthedocs.io/en/latest/notebooks/liana_c2c.html Create a ligand-receptor geneset by combining ligand-receptor pairs with pathway information from PROGENy. This prepares the data for enrichment analysis. ```python # generate ligand-receptor geneset lr_progeny = li.rs.generate_lr_geneset(lr_pairs, net, lr_sep="^").rename(columns = {"interaction": "target"}) lr_progeny.head() ``` -------------------------------- ### Dotplot Interactions by Sample Source: https://liana-py.readthedocs.io/en/latest/api.html Generates a dotplot visualizing interactions aggregated by sample. ```python dotplot_by_sample([adata, uns_key, ...]) ``` -------------------------------- ### Visualize Ligand-Receptor Interactions by Sample Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Generate a dot plot to visualize ligand-receptor interactions across samples using `li.pl.dotplot_by_sample`. Customize the plot by specifying `colour` and `size` aesthetics, filtering interactions by `source_labels`, `target_labels`, `ligand_complex`, and `receptor_complex`. Adjust `size_range` for marker size. The plot can be further customized with `p9.theme` for facet label rotation. ```python (li.pl.dotplot_by_sample(adata, sample_key=sample_key, colour="magnitude_rank", size="specificity_rank", source_labels=["CD4T", "B", "FGR3"], target_labels=["CD8T", 'DCs', 'CD14'], ligand_complex=["B2M"], inverse_colour=True, inverse_size=True, receptor_complex=["KLRD1", "LILRB2", "CD3D"], figure_size=(12, 8), size_range=(0.5, 5), ) + # rotate facet labels p9.theme(strip_text=p9.element_text(size=10, colour="black", angle=90)) ) ``` -------------------------------- ### Import LIANA Library Source: https://liana-py.readthedocs.io/en/latest/api.html Import the LIANA library for use in your Python scripts. ```python import liana as li ``` -------------------------------- ### Load MOFA+ Model Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Loads a MOFA+ model from a specified H5AD file. This is the initial step to explore the model's structure and components. ```python model = mofa.mofa_model("models/mofatalk.h5ad") model ``` -------------------------------- ### List Available Bivariate Functions Source: https://liana-py.readthedocs.io/en/latest/notebooks/bivariate.html Prints a table of all available spatially-informed bivariate functions within the LIANA library, including their names and brief descriptions. ```python li.mt.bivariate.show_functions() ``` -------------------------------- ### Generate Ligand-Receptor Gene Set Source: https://liana-py.readthedocs.io/en/latest/api.html Generate a ligand-receptor gene set from a resource and a network. ```python generate_lr_geneset(resource, net[, ...]) ``` -------------------------------- ### logfc.__call__ Source: https://liana-py.readthedocs.io/en/latest/api.html Runs a ligand-receptor method for logFC analysis. ```APIDOC ## logfc.__call__ ### Description Runs a ligand-receptor method for logFC analysis. ### Method callable ### Parameters #### Path Parameters - **groupby** (str) - Description of groupby parameter - **resource_name** (str) - Optional - Description of resource_name parameter - **...** - Other parameters may be available ``` -------------------------------- ### select_resource() Source: https://liana-py.readthedocs.io/en/latest/generated/liana.resource.select_resource.html Reads a specified resource from the pre-generated resources in LIANA. This resource is used for ligand-receptor inference. ```APIDOC ## select_resource() ### Description Reads a specified resource from the pre-generated resources in LIANA. This resource is used for ligand-receptor inference. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **resource_name** (`str`, optional): Name of the resource to be loaded. Defaults to `'consensus'`. ### Return Type `DataFrame` ### Returns A pandas DataFrame with `['ligand', 'receptor']` columns. ``` -------------------------------- ### select_resource Source: https://liana-py.readthedocs.io/en/latest/api.html Read resource of choice from the pre-generated resources in LIANA. ```APIDOC ## select_resource ### Description Read resource of choice from the pre-generated resources in LIANA. ### Parameters #### Path Parameters - **resource_name** (str, optional) - The name of the resource to select. ``` -------------------------------- ### describe_metalinks() Source: https://liana-py.readthedocs.io/en/latest/generated/liana.resource.describe_metalinks.html Prints the schema information and foreign key details for all tables in the specified SQLite database. ```APIDOC ## describe_metalinks() ### Description Prints the schema information and foreign key details for all tables in the specified SQLite database. ### Parameters #### Path Parameters - **db_path** (str) - Optional - Path to the SQLite database file. If None, the database will be downloaded to the current working directory. - **return_output** (bool) - Optional - If True, the function will return the output as a string instead of printing it. ``` -------------------------------- ### Initialize MISTy with LinearModel and bypass_intra Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Construct a MISTy object using LinearModel for faster and more interpretable analysis. Set bypass_intra=True to exclude intra-view features from predicting intra-view targets. ```python misty(model=LinearModel, k_cv=10, seed=1337, bypass_intra=True, verbose = True) ``` -------------------------------- ### dotplot_by_sample Source: https://liana-py.readthedocs.io/en/latest/api.html Generates a dotplot of interactions by sample. ```APIDOC ## dotplot_by_sample ### Description Generates a dotplot of interactions by sample. ### Parameters #### Path Parameters - **adata** (AnnData) - The input AnnData object. - **uns_key** (str, optional) - Key for unstructured data. - **...** - Other parameters may be available ``` -------------------------------- ### Import rank_aggregate Source: https://liana-py.readthedocs.io/en/latest/notebooks/basic_usage.html Import the rank_aggregate function from the liana.mt module. ```python from liana.mt import rank_aggregate ``` -------------------------------- ### build_prior_network() Source: https://liana-py.readthedocs.io/en/latest/generated/liana.method.build_prior_network.html Builds a prior network using Protein-Protein Interactions (PPIs) and specified input/output nodes. It can optionally split input nodes into ligands and receptors and control verbosity. ```APIDOC ## build_prior_network() ### Description Builds a prior network from PPIs and input/output nodes. ### Parameters #### Path Parameters - **ppis** (list of tuples or pandas DataFrame) - The PPIs to use for the prior network. If a pandas DataFrame is provided, it must have the columns - **input_nodes** (dict) - A dictionary of input nodes. The keys are the node names, the values are the node scores. - **output_nodes** (dict) - A dictionary of output nodes. The keys are the node names, the values are the node scores. - **lr_sep** (str, optional) - The separator to use to split the input nodes into ligand and receptor. If None, the input nodes will be used as is. - **verbose** (bool, optional) - Whether to print progress information. Default: True ### Returns - **corneto.Graph** - The constructed graph object. ``` -------------------------------- ### Visualize Connectivity with `li.pl.connectivity` Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Visualizes the spatial connectivity for a specific spot (index `idx`). This helps in understanding the spatial relationships computed by `li.ut.spatial_neighbors`. ```python li.pl.connectivity(acts_tfs, idx=0, figure_size=(6,5)) ``` -------------------------------- ### MOFA Model Training Output Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofacellular.html This output shows the progress and details of the MOFA model training process, including loaded views, model options, likelihoods, and convergence status. It confirms the saving of the model and embeddings. ```text ######################################################### ### __ __ ____ ______ ### ### | \/ |/ __ \| ____/\ _ ### ### | \ / | | | | |__ / \ _| |_ ### ### | |\/| | | | | __/ /\ \_ _| ### ### | | | | |__| | | / ____ \|_| ### ### |_| |_|\____/|_|/_/ \_\ ### ### ### ######################################################### Loaded view='CD14' group='group1' with N=16 samples and D=2661 features... Loaded view='CD4T' group='group1' with N=16 samples and D=2769 features... Loaded view='DCs' group='group1' with N=16 samples and D=866 features... Loaded view='NK' group='group1' with N=16 samples and D=808 features... Loaded view='CD8T' group='group1' with N=16 samples and D=486 features... Loaded view='B' group='group1' with N=16 samples and D=1235 features... Loaded view='FGR3' group='group1' with N=16 samples and D=1172 features... Model options: - Automatic Relevance Determination prior on the factors: True - Automatic Relevance Determination prior on the weights: True - Spike-and-slab prior on the factors: False - Spike-and-slab prior on the weights: True Likelihoods: - View 0 (CD14): gaussian - View 1 (CD4T): gaussian - View 2 (DCs): gaussian - View 3 (NK): gaussian - View 4 (CD8T): gaussian - View 5 (B): gaussian - View 6 (FGR3): gaussian ###################################### ## Training the model with seed 1337 ## ###################################### Converged! ####################### ## Training finished ## ####################### Output directory does not exist, creating it... Saving model in models/mofacellx.h5ad... Saved MOFA embeddings in .obsm['X_mofa'] slot and their loadings in .varm['LFs']. ``` -------------------------------- ### Load PROGENy Pathways and Ligand-Receptor Pairs Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Loads pathway information from PROGENy and a comprehensive list of ligand-receptor pairs. These are used for subsequent pathway enrichment analysis. ```python # load PROGENy pathways net = dc.op.progeny(organism='human', top=5000, thr_padj=0.25) # load full list of ligand-receptor pairs lr_pairs = li.resource.select_resource('consensus') ``` -------------------------------- ### Estimate Activities with `dc.mt.ulm` Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Estimates activities using the `ulm` method. Ensure `adata` and `net` are properly initialized. The `TypeError` indicates a missing 'data' argument, which might stem from how `adata` or `net` are prepared. ```python dc.mt.ulm( mat=adata, net=net, verbose=True, raw=False ) ``` -------------------------------- ### Fit MOFA Model Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Use `mu.tl.mofa` to fit a MOFA model. Specify the multi-view data, convergence mode, output file, and the number of factors. ```python mu.tl.mofa(mdata, use_obs='union', convergence_mode='medium', outfile='models/mofatalk.h5ad', n_factors=4, ) ``` -------------------------------- ### Select Ligand-Receptor Resource Source: https://liana-py.readthedocs.io/en/latest/notebooks/inflow_score.html Select a consensus ligand-receptor resource for downstream analysis. Note that a mouse-specific resource is available and can be recreated. ```python resource = li.rs.select_resource('consensus') #NOTE: there is a mouse_consensus resource and we should recreate it once we update consensus :) ``` -------------------------------- ### Display Target Metrics Head Source: https://liana-py.readthedocs.io/en/latest/notebooks/misty.html Show the first few rows of the 'target_metrics' DataFrame, which contains metrics like R-squared and contributions from different views per target. ```python misty.uns['target_metrics'].head() ``` -------------------------------- ### Create Custom Rank Aggregate Source: https://liana-py.readthedocs.io/en/latest/notebooks/basic_usage.html Initializes a custom rank aggregate using specified methods (e.g., logfc, geometric_mean). Allows for a tailored aggregation of interaction ranks. ```python methods = [logfc, geometric_mean] new_rank_aggregate = li.mt.AggregateClass(li.mt.aggregate_meta, methods=methods) ``` -------------------------------- ### Plot Ligand-Receptor Loadings with Dotplot Source: https://liana-py.readthedocs.io/en/latest/notebooks/mofatalk.html Generates a dot plot visualizing ligand-receptor loadings, ordered by Factor 1 values. Allows customization of displayed labels, size, and color. ```python my_plot = li.pl.dotplot(liana_res = variable_loadings, size='size', colour='Factor1', orderby='Factor1', top_n=15, source_labels=['NK', 'B', 'CD4T', 'CD8T', 'CD14'], orderby_ascending=False, size_range=(0.1, 5), figure_size=(8, 5) ) ```