Spaces:
Sleeping
Sleeping
#!/usr/bin/env python | |
# coding: utf-8 | |
# # WGCNA (Weighted gene co-expression network analysis) analysis | |
# Weighted gene co-expression network analysis (WGCNA) is a systems biology approach to characterize gene association patterns between different samples and can be used to identify highly synergistic gene sets and identify candidate biomarker genes or therapeutic targets based on the endogeneity of the gene sets and the association between the gene sets and the phenotype. | |
# | |
# Paper: [WGCNA: an R package for weighted correlation network analysis](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-9-559#Sec21) | |
# | |
# Narges Rezaie, Farilie Reese, Ali Mortazavi, PyWGCNA: a Python package for weighted gene co-expression network analysis, Bioinformatics, Volume 39, Issue 7, July 2023, btad415, https://doi.org/10.1093/bioinformatics/btad415 | |
# | |
# Code: Reproduce by Python. Raw is http://www.genetics.ucla.edu/labs/horvath/CoexpressionNetwork/Rpackages/WGCNA | |
# | |
# Colab_Reproducibility:https://colab.research.google.com/drive/1EbP-Tq1IwYO9y1_-zzw23XlPbzrxP0og?usp=sharing | |
# | |
# Here, you will be briefly guided through the basics of how to use omicverse to perform wgcna anlysis. Once you are set | |
# In[1]: | |
import scanpy as sc | |
import omicverse as ov | |
import matplotlib.pyplot as plt | |
ov.plot_set() | |
# ## Load the data | |
# The analysis is based on the in-built WGCNA tutorial data. All the data can be download from https://github.com/mortazavilab/PyWGCNA/tree/main/tutorials/5xFAD_paper | |
# In[2]: | |
import pandas as pd | |
data=ov.utils.read('data/5xFAD_paper/expressionList.csv', | |
index_col=0) | |
data.head() | |
# In[3]: | |
from statsmodels import robust #import package | |
gene_mad=data.apply(robust.mad) #use function to calculate MAD | |
data=data.T | |
data=data.loc[gene_mad.sort_values(ascending=False).index[:2000]] | |
data.head() | |
# In[5]: | |
#import PyWGCNA | |
pyWGCNA_5xFAD = ov.bulk.pyWGCNA(name='5xFAD_2k', | |
species='mus musculus', | |
geneExp=data.T, | |
outputPath='', | |
save=True) | |
pyWGCNA_5xFAD.geneExpr.to_df().head(5) | |
# ## Pre-processing workflow | |
# | |
# PyWGCNA allows you to easily preproces the data including removing genes with too many missing values or lowly-expressed genes across samples (by default we suggest to remove genes without that are expressed below 1 TPM) and removing samples with too many missing values. Keep in your mind that these options can be adjusted by changing `TPMcutoff` and `cut` | |
# In[6]: | |
pyWGCNA_5xFAD.preprocess() | |
# ## Construction of the gene network and identification of modules | |
# | |
# PyWGCNA compresses all the steps of network construction and module detection in one function called `findModules` which performs the following steps: | |
# 1. Choosing the soft-thresholding power: analysis of network topology | |
# 2. Co-expression similarity and adjacency | |
# 3. Topological Overlap Matrix (TOM) | |
# 4. Clustering using TOM | |
# 5. Merging of modules whose expression profiles are very similar | |
# | |
# In this tutorial, we will perform the analysis step by step. | |
# In[7]: | |
pyWGCNA_5xFAD.calculate_soft_threshold() | |
# In[8]: | |
pyWGCNA_5xFAD.calculating_adjacency_matrix() | |
# In[9]: | |
pyWGCNA_5xFAD.calculating_TOM_similarity_matrix() | |
# ## Building a network of co-expressions | |
# | |
# We use the dynamicTree to build the co-expressions module basing TOM matrix | |
# In[10]: | |
pyWGCNA_5xFAD.calculate_geneTree() | |
pyWGCNA_5xFAD.calculate_dynamicMods(kwargs_function={'cutreeHybrid': {'deepSplit': 2, 'pamRespectsDendro': False}}) | |
pyWGCNA_5xFAD.calculate_gene_module(kwargs_function={'moduleEigengenes': {'softPower': 8}}) | |
# In[11]: | |
pyWGCNA_5xFAD.plot_matrix(save=False) | |
# ## Saving and loading your PyWGCNA | |
# You can save or load your PyWGCNA object with the `saveWGCNA()` or `readWGCNA()` functions respectively. | |
# In[12]: | |
pyWGCNA_5xFAD.saveWGCNA() | |
# In[2]: | |
pyWGCNA_5xFAD=ov.bulk.readWGCNA('5xFAD_2k.p') | |
# In[14]: | |
pyWGCNA_5xFAD.mol.head() | |
# In[15]: | |
pyWGCNA_5xFAD.datExpr.var.head() | |
# ## Sub co-expression module | |
# | |
# Sometimes we are interested in a gene, or a module of a pathway, and we need to extract the sub-modules of the gene for analysis and mapping. For example, we have selected two modules, 6 and 12, as sub-modules for analysis | |
# In[13]: | |
sub_mol=pyWGCNA_5xFAD.get_sub_module(['gold','lightgreen'], | |
mod_type='module_color') | |
sub_mol.head(),sub_mol.shape | |
# We found a total of 151 genes for 'gold' and 'lightgreen'. Next, we used the scale-free network constructed earlier, with the threshold set to 0.95, to construct a gene correlation network graph for modules 'gold' and 'lightgreen' | |
# In[17]: | |
G_sub=pyWGCNA_5xFAD.get_sub_network(mod_list=['lightgreen'], | |
mod_type='module_color',correlation_threshold=0.2) | |
G_sub | |
# In[18]: | |
len(G_sub.edges()) | |
# pyWGCNA provides a simple visualisation function `plot_sub_network` to visualise the gene-free network of our interest. | |
# In[19]: | |
pyWGCNA_5xFAD.plot_sub_network(['gold','lightgreen'],pos_type='kamada_kawai',pos_scale=10,pos_dim=2, | |
figsize=(8,8),node_size=10,label_fontsize=8,correlation_threshold=0.2, | |
label_bbox={"ec": "white", "fc": "white", "alpha": 0.6}) | |
# We also can merge two previous steps by calling `runWGCNA()` function. | |
# | |
# ## Updating sample information and assiging color to them for dowstream analysis | |
# In[3]: | |
pyWGCNA_5xFAD.updateSampleInfo(path='data/5xFAD_paper/sampleInfo.csv', sep=',') | |
# add color for metadata | |
pyWGCNA_5xFAD.setMetadataColor('Sex', {'Female': 'green', | |
'Male': 'yellow'}) | |
pyWGCNA_5xFAD.setMetadataColor('Genotype', {'5xFADWT': 'darkviolet', | |
'5xFADHEMI': 'deeppink'}) | |
pyWGCNA_5xFAD.setMetadataColor('Age', {'4mon': 'thistle', | |
'8mon': 'plum', | |
'12mon': 'violet', | |
'18mon': 'purple'}) | |
pyWGCNA_5xFAD.setMetadataColor('Tissue', {'Hippocampus': 'red', | |
'Cortex': 'blue'}) | |
# **note**: For doing downstream analysis, we keep aside the Gray modules which is the collection of genes that could not be assigned to any other module. | |
# | |
# ## Relating modules to external information and identifying important genes | |
# PyWGCNA gather some important analysis after identifying modules in `analyseWGCNA()` function including: | |
# | |
# 1. Quantifying module–trait relationship | |
# 2. Gene relationship to trait and modules | |
# | |
# Keep in your mind before you start analysis to add any sample or gene information. | |
# | |
# For showing module relationship heatmap, PyWGCNA needs user to choose and set colors from [Matplotlib colors](https://matplotlib.org/stable/gallery/color/named_colors.html) for metadata by using `setMetadataColor()` function. | |
# | |
# You also can select which data trait in which order you wish to show in module eigengene heatmap | |
# In[4]: | |
pyWGCNA_5xFAD.analyseWGCNA() | |
# In[5]: | |
metadata = pyWGCNA_5xFAD.datExpr.obs.columns.tolist() | |
# In[10]: | |
pyWGCNA_5xFAD.plotModuleEigenGene('lightgreen', metadata, show=True) | |
# In[11]: | |
pyWGCNA_5xFAD.barplotModuleEigenGene('lightgreen', metadata, show=True) | |
# ## Finding hub genes for each modules | |
# | |
# you can also ask about hub genes in each modules based on their connectivity by using `top_n_hub_genes()` function. | |
# | |
# It will give you dataframe sorted by connectivity with additional gene information you have in your expression data. | |
# In[12]: | |
pyWGCNA_5xFAD.top_n_hub_genes(moduleName="lightgreen", n=10) | |