-
Notifications
You must be signed in to change notification settings - Fork 47
/
wgcna.py
3583 lines (3165 loc) · 187 KB
/
wgcna.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import requests
from time import sleep
import numpy as np
import pandas as pd
import scipy.stats as stats
import statistics
import sys
import warnings
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, cut_tree, dendrogram, fcluster
from scipy.cluster.hierarchy import to_tree
from scipy.stats import t
from scipy.stats import rankdata
from statsmodels.formula.api import ols
from matplotlib import colors as mcolors
from sklearn.impute import KNNImputer
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
import pickle
import seaborn as sns
import matplotlib.patches as mpatches
import matplotlib.gridspec as gridspec
import gseapy as gp
from gseapy.plot import dotplot
from pyvis.network import Network
from reactome2py import analysis
from PyWGCNA.geneExp import *
try:
import resource
except ImportError:
try:
import rsrc as resource
except ImportError:
sys.exit("resource or rsrc package is not installed!")
# remove runtime warning (divided by zero)
np.seterr(divide='ignore', invalid='ignore')
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings("ignore")
plt.rcParams["axes.edgecolor"] = "black"
plt.rcParams["axes.linewidth"] = 1
plt.rcParams["axes.facecolor"] = "white"
plt.rcParams['legend.title_fontsize'] = 15
sns.set_style("white")
# public values
networkTypes = ["unsigned", "signed", "signed hybrid"]
adjacencyTypes = ["unsigned", "signed", "signed hybrid"]
TOMTypes = ["unsigned", "signed"]
TOMDenoms = ["min", "mean"]
# bcolors
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
class WGCNA(GeneExp):
"""
A class used to do weighted gene co-expression network analysis.
:param name: name of the WGCNA we used to visualize data (default: 'WGCNA')
:type name: str
:param save: indicate if you want to save result of important steps in a figure directory (default: False)
:type save: bool
:param outputPath: path you want to save all you figures and object (default: '', where you rau your script)
:type outputPath: str
:param geneExpr: expression matrix
:type geneExpr: geneExp class
:param datExpr: data expression data that contains preprocessed data
:type datExpr: anndata
:param TPMcutoff: cut off for removing genes that expressed under this number along samples
:type TPMcutoff: int
:param cut: number to remove outlier sample (default: 'inf') By default we don't remove any sample by hierarchical clustering
:type cut: float
:param powers: different powers to test to have scale free network (default: [1:10, 11:21:2])
:type powers: list of int
:param RsquaredCut: R squaered cut to choose power for having scale free network; between 0 to 1 (default: 0.9)
:type RsquaredCut: float
:param MeanCut: mean connectivity to choose power for having scale free network (default: 100)
:type MeanCut: int
:param power: power to have scale free network (default: 6)
:type power: int
:param sft: soft threshold table which has information for each powers
:type sft: pandas dataframe
:param networkType: Type of network we can create including "unsigned", "signed" and "signed hybrid" (default: "signed hybrid")
:type networkType: str
:param adjacency: adjacency matrix calculating base of the type of network
:type adjacency: ndarray
:param geneTree: average hierarchical clustering of dissTOM matrix
:type geneTree: ndarray
:param TOMType: Type of topological overlap matrix(TOM) including "unsigned", "signed" (default: "signed")
:type TOMType: str
:param TOM: topological overlap measure using average linkage hierarchical clustering which inputs a measure of interconnectedness
:param TOM: ndarray
:param minModuleSize: We like large modules, so we set the minimum module size relatively high (default: 50)
:type minModuleSize: int
:param dynamicMods: name of modules by clustering similar genes together
:type dynamicMods: list
:param naColor: color we used to identify genes we don't find any cluster for them (default: "grey")
:type naColor: str
:param MEs: eigengenes
:type MEs: ndarray
:param MEDissThres: diss similarity threshold (default: 0.2)
:type MEDissThres: float
:param datME:
:type datME: pandas dataframe
:param signedKME:(signed) eigengene-based connectivity (module membership)
:type signedKME: pandas dataframe
:param moduleTraitCor: correlation between each module and metadata
:type moduleTraitCor: pandas dataframe
:param moduleTraitPvalue: p-value of correlation between each module and metadata
:type moduleTraitPvalue: pandas dataframe
:param figureType: extension of figure (default: "pdf")
"""
def __init__(self, name='WGCNA',
TPMcutoff=1,
powers=None, RsquaredCut=0.9, MeanCut=100,
networkType="signed hybrid", TOMType="signed",
minModuleSize=50, naColor="grey", cut=float('inf'),
MEDissThres=0.2,
species=None, level='gene', anndata=None, geneExp=None,
geneExpPath=None, sep=',',
save=False, outputPath=None, figureType='pdf'):
super().__init__(species=species, level=level, anndata=anndata, geneExp=geneExp,
geneExpPath=geneExpPath, sep=sep)
if powers is None:
powers = list(range(1, 11)) + list(range(11, 21, 2))
self.name = name
self.save = save
self.outputPath = f"{os.getcwd()}/" if outputPath is None else outputPath
self.TPMcutoff = TPMcutoff
self.cut = cut
self.datExpr = self.geneExpr.copy()
self.metadataColors = {}
self.networkType = networkType
# Choose a set of soft-thresholding powers
self.RsquaredCut = RsquaredCut
self.MeanCut = MeanCut
self.powers = powers
self.power = 0
self.sft = None
self.geneTree = None
self.adjacency = None
self.TOMType = TOMType
self.TOM = None
self.minModuleSize = minModuleSize
self.dynamicMods = [None]
self.naColor = naColor
self.MEs = None
self.MEDissThres = MEDissThres
self.datME = None
self.signedKME = None
self.moduleTraitCor = None
self.moduleTraitPvalue = None
if self.save:
print(f"{OKGREEN}Saving data to be True, checking requirements ...{ENDC}")
if not os.path.exists(self.outputPath + 'figures/'):
print(f"{WARNING}Figure directory does not exist!\nCreating figure directory!{ENDC}")
os.makedirs(self.outputPath + 'figures/')
self.figureType = figureType
def preprocess(self):
"""
Preprocessing PyWGCNA object including removing obvious outlier on genes and samples
"""
print(f"{BOLD}{OKBLUE}Pre-processing...{ENDC}")
# Prepare and clean data
# Remove cols with less than 1 TPM
self.datExpr = self.datExpr[:, (self.datExpr.to_df() > self.TPMcutoff).any(axis=0)]
# Check that all genes and samples have sufficiently low numbers of missing values.
goodGenes, goodSamples, allOK = WGCNA.goodSamplesGenes(self.datExpr.to_df().T)
# if not okay
if not allOK:
# Optionally, print the gene and sample names that were removed:
if np.count_nonzero(goodGenes) > 0:
print(
f"{OKGREEN} {np.size(goodGenes) - np.count_nonzero(goodGenes)} gene(s) detected as an outlier!{ENDC}")
print(f"{OKGREEN}Removing genes: {self.datExpr.obs.columns[not goodGenes].values}{ENDC}")
if np.count_nonzero(goodSamples) > 0:
print(
f"{OKGREEN} {np.size(goodSamples) - np.count_nonzero(goodSamples)} sample(s) detected as an outlier!{ENDC}")
print(f"{OKGREEN}Removing samples: {self.datExpr.obs.index[not goodSamples].values}{ENDC}")
# Remove the offending genes and samples from the data:
self.datExpr.X = self.datExpr.X.loc[goodSamples, goodGenes]
# Clustering
sampleTree = WGCNA.hclust(pdist(self.datExpr.to_df()), method="average")
plt.figure(figsize=(max(25, round(self.datExpr.X.shape[0] / 20)), 10), facecolor='white')
dendrogram(sampleTree, color_threshold=self.cut, labels=self.datExpr.to_df().index, leaf_rotation=90,
leaf_font_size=8)
plt.axhline(y=self.cut, c='grey', lw=1, linestyle='dashed')
plt.title('Sample clustering to detect outliers')
plt.xlabel('Samples')
plt.ylabel('Distances')
plt.tight_layout()
if self.save:
plt.savefig(f"{self.outputPath}/figures/sample_clustering_cleaning.{self.figureType}")
# Determine cluster under the line
clust = WGCNA.cutree(sampleTree, cutHeight=self.cut)
# clust 0 contains the samples we want to keep.
clust = clust.T.tolist()[0]
index = [index for index, element in enumerate(clust) if element == 0]
self.datExpr = self.datExpr[index, :]
print("\tDone pre-processing..\n")
def findModules(self, **kwargs):
"""
Clustering genes through original WGCNA pipeline: 1.pick soft threshold 2.calculating adjacency matrix 3.calculating TOM similarity matrix 4.cluster genes base of dissTOM 5.merge similar cluster dynamically
"""
print(f"{BOLD}{OKBLUE}Run WGCNA...{ENDC}")
# Call the network topology analysis function
self.power, self.sft = WGCNA.pickSoftThreshold(self.datExpr.to_df(), RsquaredCut=self.RsquaredCut,
MeanCut=self.MeanCut, powerVector=self.powers,
networkType=self.networkType, **kwargs)
fig, ax = plt.subplots(ncols=2, figsize=(10, 5), facecolor='white')
ax[0].plot(self.sft['Power'], -1 * np.sign(self.sft['slope']) * self.sft['SFT.R.sq'], 'o')
for i in range(len(self.powers)):
ax[0].text(self.sft.loc[i, 'Power'],
-1 * np.sign(self.sft.loc[i, 'slope']) * self.sft.loc[i, 'SFT.R.sq'],
str(self.sft.loc[i, 'Power']), ha="center", va="center", color='black', weight='bold')
ax[0].axhline(0.9, color='r')
ax[0].set_xlabel("Soft Threshold (power)")
ax[0].set_ylabel("Scale Free Topology Model Fit,signed R^2")
ax[0].title.set_text('Scale independence')
ax[1].plot(self.sft['Power'], self.sft['mean(k)'], 'o')
for i in range(len(self.powers)):
ax[1].text(self.sft.loc[i, 'Power'], self.sft.loc[i, 'mean(k)'],
str(self.sft.loc[i, 'Power']), ha="center", va="center", color='r', weight='bold')
ax[1].set_xlabel("Soft Threshold (power)")
ax[1].set_ylabel("Mean Connectivity")
ax[1].title.set_text('Mean connectivity')
fig.tight_layout()
if self.save:
fig.savefig(f"{self.outputPath}/figures/summary_power.{self.figureType}")
# Set Power
self.adjacency = WGCNA.adjacency(self.datExpr.to_df(), power=self.power, adjacencyType=self.networkType)
self.adjacency = pd.DataFrame(self.adjacency,
columns=self.datExpr.to_df().columns,
index=self.datExpr.to_df().columns)
# Turn adjacency into topological overlap
self.TOM = WGCNA.TOMsimilarity(self.adjacency.to_numpy(), TOMType=self.TOMType)
self.TOM.columns = self.datExpr.to_df().columns
self.TOM.index = self.datExpr.to_df().columns
dissTOM = 1 - self.TOM
dissTOM = dissTOM.round(decimals=8)
a = squareform(dissTOM.values, checks=False)
# Call the hierarchical clustering function
self.geneTree = linkage(a, method="average")
# Module identification using dynamic tree cut:
# dynamicMods = WGCNA.cutreeHybrid(dendro=self.geneTree, distM=dissTOM, deepSplit=2, pamRespectsDendro=False,
# minClusterSize=self.minModuleSize, **kwargs)
dynamicMods = WGCNA.cutreeHybrid(dendro=self.geneTree, distM=dissTOM, deepSplit=2, pamRespectsDendro=False,
minClusterSize=self.minModuleSize, **kwargs)
# Convert numeric labels into colors
self.datExpr.var['dynamicColors'] = WGCNA.labels2colors(labels=dynamicMods)
# Calculate eigengenes
MEList = WGCNA.moduleEigengenes(expr=self.datExpr.to_df(), colors=self.datExpr.var['dynamicColors'])
self.MEs = MEList['eigengenes']
if 'MEgrey' in self.MEs.columns:
self.MEs.drop(['MEgrey'], axis=1, inplace=True)
# Calculate dissimilarity of module eigengenes
MEDiss = pd.DataFrame(1 - np.corrcoef(self.MEs, rowvar=False), index=self.MEs.columns, columns=self.MEs.columns)
if MEDiss.shape != (1, 1):
# Cluster module eigengenes
a = squareform(MEDiss, checks=False)
METree = WGCNA.hclust(a, method="average")
plt.figure(figsize=(max(20, round(MEDiss.shape[1] / 20)), 10), facecolor='white')
dendrogram(METree, color_threshold=self.MEDissThres, labels=MEDiss.columns, leaf_rotation=90,
leaf_font_size=8)
plt.axhline(y=self.MEDissThres, c='grey', lw=1, linestyle='dashed')
plt.title('Clustering of module eigengenes')
plt.xlabel('')
plt.ylabel('')
plt.tight_layout()
if self.save:
plt.savefig(f"{self.outputPath}/figures/eigenesgenes.{self.figureType}")
# Call an automatic merging function
merge = WGCNA.mergeCloseModules(self.datExpr.to_df(), self.datExpr.var['dynamicColors'],
cutHeight=self.MEDissThres)
# The merged module colors; Rename to moduleColors
self.datExpr.var['moduleColors'] = merge['colors']
else:
self.datExpr.var['moduleColors'] = ["black"] * self.datExpr.shape[1]
# Construct numerical labels corresponding to the colors
colorOrder = np.unique(self.datExpr.var['moduleColors']).tolist()
self.datExpr.var['moduleLabels'] = [colorOrder.index(x) if x in colorOrder else None for x in
self.datExpr.var['moduleColors']]
# Eigengenes of the new merged modules:
self.MEs = merge['newMEs']
# Recalculate MEs with color labels
self.datME = WGCNA.moduleEigengenes(self.datExpr.to_df(), self.datExpr.var['moduleColors'])['eigengenes']
if 'MEgrey' in self.datME.columns:
self.datME.drop(['MEgrey'], axis=1, inplace=True)
self.MEs = WGCNA.orderMEs(self.datME)
print("\tDone running WGCNA..\n")
def runWGCNA(self):
"""
Preprocess and find modules
"""
WGCNA.preprocess(self)
WGCNA.findModules(self)
return self
def analyseWGCNA(self, order=None, geneList=None, show=True):
"""
Analysing results: 1.calculating module trait relationship 2.plotting module heatmap eigengene 3.finding GO term for each module
:param order: indicate in which order metadata will show up in plots (should same as metadata name in anndata)
:type order: list
:param geneList: genes information you want to add (keep in mind you can not have multiple row for same gene)
:type geneList: pandas dataframe
:param show: indicate if you want to see plots in when you run your code
:type show: bool
"""
print(f"{BOLD}{OKBLUE}Analysing WGCNA...{ENDC}")
datTraits = self.getDatTraits(self.datExpr.obs.columns.tolist())
print(f"{OKCYAN}Calculating module trait relationship ...{ENDC}")
self.moduleTraitCor = pd.DataFrame(index=self.MEs.columns,
columns=datTraits.columns,
dtype="float")
self.moduleTraitPvalue = pd.DataFrame(index=self.MEs.columns,
columns=datTraits.columns,
dtype="float")
for i in self.MEs.columns:
for j in datTraits.columns:
tmp = stats.pearsonr(self.MEs[i], datTraits[j], alternative='greater')
self.moduleTraitCor.loc[i, j] = tmp[0]
self.moduleTraitPvalue.loc[i, j] = tmp[1]
if self.save:
self.module_trait_relationships_heatmap(metaData=self.datExpr.obs.columns.tolist(),
show=show,
file_name='module-traitRelationships')
print("\tDone..\n")
print(f"{OKCYAN}Adding (signed) eigengene-based connectivity (module membership) ...{ENDC}")
self.CalculateSignedKME()
print("\tDone..\n")
if geneList is not None:
print(f"{OKCYAN}Updating gene information based on given gene list ...{ENDC}")
self.updateGeneInfo(geneInfo=geneList)
print("\tDone..\n")
# Select module probes
modules = np.unique(self.datExpr.var['moduleColors']).tolist()
metadata = self.datExpr.obs.columns.tolist()
if order is not None:
if all(item in metadata for item in order):
metadata = order
else:
sys.exit("Given order is not valid!")
if self.save:
print(f"{OKCYAN}plotting module heatmap eigengene...{ENDC}")
for module in modules:
self.plotModuleEigenGene(module, metadata, show=show)
print("\tDone..\n")
if self.save:
print(f"{OKCYAN}plotting module barplot eigengene...{ENDC}")
for module in modules:
self.barplotModuleEigenGene(module, metadata, colorBar=metadata[-1], show=show)
print("\tDone..\n")
if self.save:
print(f"{OKCYAN}doing Enrichr GO analysis for each module...{ENDC}")
if 'gene_name' not in self.datExpr.var.columns:
print(
f"{WARNING}\tgene name didn't found in gene information!\n\t Go term analysis can not be done{ENDC}")
else:
for module in modules:
self.functional_enrichment_analysis(type="GO",
moduleName=module)
print("\tDone..\n")
@staticmethod
def replaceMissing(x, replaceWith):
"""
Replacing missing (NA) value with appropriate value (for integer number replace with 0 and for string replace with "")
:param x: value want to replace (single item)
:type x: object
:param replaceWith: define character you want to replace na value by looking at type of data
:type replaceWith: object
:return: object without any missing (NA) value
"""
if replaceWith:
if x.isnumeric():
replaceWith = 0
elif x.isalpha():
replaceWith = ""
else:
sys.exit("Need 'replaceWith'.")
x = x.fillna(replaceWith)
return x
@staticmethod
def checkAndScaleWeights(weights, expr, scaleByMax=True):
"""
check and scale weights of gene expression
:param weights: weights of gene expression
:type weights: pandas dataframe
:param expr: gene expression matrix
:type expr: pandas dataframe
:param scaleByMax: if you want to scale your weights by diving to max
:type scaleByMax: boll
:return: processed weights of gene expression
:rtype: pandas dataframe
"""
if weights is None:
return weights
weights = np.asmatrix(weights)
if expr.shape != weights.shape:
sys.exit("When 'weights' are given, they must have the same dimensions as 'expr'.")
if (weights < 0).any():
sys.exit("Found negative weights. All weights must be non-negative.")
nf = np.isinf(weights)
if any(nf):
print(f"{WARNING}Found non-finite weights. The corresponding data points will be removed.{ENDC}")
weights[nf] = None
if scaleByMax:
maxw = np.amax(weights, axis=0)
maxw[maxw == 0] = 1
weights = weights / np.reshape(maxw, weights.shape)
return weights
# Check that all genes and samples have sufficiently low numbers of missing values.
@staticmethod
def goodSamplesGenes(datExpr, weights=None, minFraction=1 / 2, minNSamples=4, minNGenes=4, tol=None,
minRelativeWeight=0.1):
"""
Checks data for missing entries, entries with weights below a threshold, and zero-variance genes. If necessary, the filtering is iterated.
:param datExpr:expression data. A data frame in which columns are genes and rows ar samples.
:type datExpr: pandas dataframe
:param weights: optional observation weights in the same format (and dimensions) as datExpr.
:type weights: pandas dataframe
:param minFraction: minimum fraction of non-missing samples for a gene to be considered good. (default = 1/2)
:type minFraction: float
:param minNSamples: minimum number of non-missing samples for a gene to be considered good. (default = 4)
:type minNSamples: int
:param minNGenes: minimum number of good genes for the data set to be considered fit for analysis. If the actual number of good genes falls below this threshold, an error will be issued. (default = 4)
:type minNGenes: int
:param tol: An optional 'small' number to compare the variance against
:type tol: float
:param minRelativeWeight: observations whose relative weight is below this threshold will be considered missing. Here relative weight is weight divided by the maximum weight in the column (gene). (default = 0.1)
:type minRelativeWeight: float
:return: A triple containing (goodGenes, goodSamples, allOK) goodSamples: A logical vector with one entry per sample that is TRUE if the sample is considered good and FALSE otherwise. goodGenes: A logical vector with one entry per gene that is TRUE if the gene is considered good and FALSE otherwise. allOK: if everything is okay
:rtype: list, list, bool
"""
goodGenes = None
goodSamples = None
nBadGenes = 0
nBadSamples = 0
changed = True
iter = 1
print("\tDetecting genes and samples with too many missing values...", flush=True)
while changed:
goodGenes = WGCNA.goodGenesFun(datExpr, weights, goodSamples, goodGenes, minFraction=minFraction,
minNSamples=minNSamples, minNGenes=minNGenes,
minRelativeWeight=minRelativeWeight,
tol=tol)
goodSamples = WGCNA.goodSamplesFun(datExpr, weights, goodSamples, goodGenes, minFraction=minFraction,
minNSamples=minNSamples, minNGenes=minNGenes,
minRelativeWeight=minRelativeWeight)
changed = np.logical_or((np.logical_not(goodGenes).sum() > nBadGenes),
(np.logical_not(goodSamples).sum() > nBadSamples))
nBadGenes = np.logical_not(goodGenes).sum()
nBadSamples = np.logical_not(goodSamples).sum()
iter = iter + 1
allOK = (nBadGenes + nBadSamples == 0)
return goodGenes, goodSamples, allOK
# Filter genes with too many missing entries
@staticmethod
def goodGenesFun(datExpr, weights=None, useSamples=None, useGenes=None, minFraction=1 / 2,
minNSamples=4, minNGenes=4, tol=None, minRelativeWeight=0.1):
"""
Check data for missing entries and returns a list of genes that have non-zero variance
:param datExpr:expression data. A data frame in which columns are genes and rows ar samples.
:type datExpr: pandas dataframe
:param weights: optional observation weights in the same format (and dimensions) as datExpr.
:type weights: pandas dataframe
:param useSamples: optional specifications of which samples to use for the check (Defaults to using all samples)
:type useSamples: list of bool
:param useGenes: optional specifications of genes for which to perform the check (Defaults to using all genes)
:type useGenes: list of bool
:param minFraction: minimum fraction of non-missing samples for a gene to be considered good. (default = 1/2)
:type minFraction: float
:param minNSamples: minimum number of non-missing samples for a gene to be considered good. (default = 4)
:type minNSamples: int
:param minNGenes: minimum number of good genes for the data set to be considered fit for analysis. If the actual number of good genes falls below this threshold, an error will be issued. (default = 4)
:type minNGenes: int
:param tol: An optional 'small' number to compare the variance against
:type tol: float
:param minRelativeWeight: observations whose relative weight is below this threshold will be considered missing. Here relative weight is weight divided by the maximum weight in the column (gene). (default = 0.1)
:type minRelativeWeight: float
:return: A logical list with one entry per gene that is TRUE if the gene is considered good and FALSE otherwise. Note that all genes excluded by useGenes are automatically assigned FALSE.
:rtype: list of bool
"""
if not datExpr.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all()).all():
sys.exit("datExpr must contain numeric data.")
weights = WGCNA.checkAndScaleWeights(weights, datExpr, scaleByMax=True)
if tol is None:
tol = 1e-10 * datExpr.abs().max().max()
if useGenes is None:
useGenes = np.repeat(True, datExpr.shape[0])
if useSamples is None:
useSamples = np.repeat(True, datExpr.shape[1])
if len(useGenes) != datExpr.shape[0]:
sys.exit("Length of nGenes is not compatible with number of columns in datExpr.")
if len(useSamples) != datExpr.shape[1]:
sys.exit("Length of nSamples is not compatible with number of rows in datExpr.")
nSamples = sum(useSamples)
nGenes = sum(useGenes)
if weights is None:
nPresent = datExpr.loc[useGenes, useSamples].notna().sum(axis=1)
else:
nPresent = (datExpr.loc[useGenes, useSamples].notna() and
weights.loc[useGenes, useSamples] > minRelativeWeight).sum(axis=1)
gg = useGenes
gg[np.logical_and(useGenes, nPresent < minNSamples)] = False
if weights is None:
var = np.var(datExpr.loc[gg, useSamples], axis=1)
# var = var.sort_index(inplace=True)
else:
# need to be fix
# TODO:colWeightedVars
var = np.var(datExpr, w=weights)
var[np.isnan(var)] = 0
nNAsGenes = datExpr.loc[gg, useSamples].isna().sum(axis=1)
gg[gg] = np.logical_and(np.logical_and(nNAsGenes < (1 - minFraction) * nSamples, var > tol ** 2),
nSamples - nNAsGenes >= minNSamples)
if sum(gg) < minNGenes:
sys.exit("Too few genes with valid expression levels in the required number of samples.")
if nGenes - sum(gg) > 0:
print("\n\n ..Excluding", nGenes - sum(gg),
"genes from the calculation due to too many missing samples or zero variance.\n\n", flush=True)
return gg
# Filter samples with too many missing entries
@staticmethod
def goodSamplesFun(datExpr, weights=None, useSamples=None, useGenes=None, minFraction=1 / 2,
minNSamples=4, minNGenes=4, minRelativeWeight=0.1):
"""
Check data for missing entries and returns a list of samples that have non-zero variance
:param datExpr:expression data. A data frame in which columns are genes and rows ar samples.
:type datExpr: pandas dataframe
:param weights: optional observation weights in the same format (and dimensions) as datExpr.
:type weights: pandas dataframe
:param useSamples: optional specifications of which samples to use for the check (Defaults to using all samples)
:type useSamples: list of bool
:param useGenes: optional specifications of genes for which to perform the check (Defaults to using all genes)
:type useGenes: list of bool
:param minFraction: minimum fraction of non-missing samples for a gene to be considered good. (default = 1/2)
:type minFraction: float
:param minNSamples: findModulesminimum number of non-missing samples for a gene to be considered good. (default = 4)
:type minNSamples: int
:param minNGenes: minimum number of good genes for the data set to be considered fit for analysis. If the actual number of good genes falls below this threshold, an error will be issued. (default = 4)
:type minNGenes: int
:param minRelativeWeight: observations whose relative weight is below this threshold will be considered missing. Here relative weight is weight divided by the maximum weight in the column (gene). (default = 0.1)
:type minRelativeWeight: float
:return: A logical list with one entry per sample that is TRUE if the sample is considered good and FALSE otherwise. Note that all samples excluded by useSamples are automatically assigned FALSE.
:rtype: list of bool
"""
if useGenes is None:
useGenes = np.repeat(True, datExpr.shape[0])
if useSamples is None:
useSamples = np.repeat(True, datExpr.shape[1])
if len(useGenes) != datExpr.shape[0]:
sys.exit("Length of nGenes is not compatible with number of columns in datExpr.")
if len(useSamples) != datExpr.shape[1]:
sys.exit("Length of nSamples is not compatible with number of rows in datExpr.")
weights = WGCNA.checkAndScaleWeights(weights, datExpr, scaleByMax=True)
nSamples = sum(useSamples)
nGenes = sum(useGenes)
if weights is None:
nNAsSamples = np.sum((datExpr.loc[useGenes, useSamples]).isnull(), axis=0)
else:
nNAsSamples = np.sum(np.logical_or(datExpr[useGenes, useSamples],
WGCNA.replaceMissing(weights[useGenes, useSamples] < minRelativeWeight,
True))
.isnull(), axis=0)
goodSamples = useSamples
goodSamples[useSamples] = np.logical_and((nNAsSamples < (1 - minFraction) * nGenes),
(nGenes - nNAsSamples >= minNGenes))
if sum(goodSamples) < minNSamples:
sys.exit("Too few samples with valid expression levels for the required number of genes.")
if nSamples - sum(goodSamples) > 0:
print(" ..Excluding", nSamples - sum(goodSamples),
"samples from the calculation due to too many missing genes.", flush=True)
return goodSamples
@staticmethod
def hclust(d, method="complete"):
"""
Hierarchical cluster analysis on a set of dissimilarities and methods for analyzing it.
:param d: a dissimilarity structure as produced by 'pdist'.
:type d: ndarray
:param method: The linkage algorithm to use. (default = complete)
:type method: str
:return: The hierarchical clustering encoded as a linkage matrix.
:rtype: ndarray
"""
METHODS = ["single", "complete", "average", "weighted", "centroid"]
if method not in METHODS:
sys.exit("Invalid clustering method.")
if method == -1:
sys.exit("Ambiguous clustering method.")
dendrogram = linkage(d, method=method)
return dendrogram
# Determine cluster under the line
@staticmethod
def cutree(sampleTree, cutHeight=50000.0):
"""
Given a linkage matrix Z, return the cut tree. remove samples/genes/modules base on hierarchical clustering
:param sampleTree: The linkage matrix.
:type sampleTree: scipy.cluster.linkage array
:param cutHeight: A optional height at which to cut the tree (default = 50000)
:type cutHeight: array_like
:return: An array indicating group membership at each agglomeration step. I.e., for a full cut tree, in the first column each data point is in its own cluster. At the next step, two nodes are merged. Finally, all singleton and non-singleton clusters are in one group. If n_clusters or height are given, the columns correspond to the columns of n_clusters or height.
:rtype: array
"""
cutTree = cut_tree(sampleTree, height=cutHeight)
return cutTree
# Call the network topology analysis function
@staticmethod
def pickSoftThreshold(data, dataIsExpr=True, weights=None, RsquaredCut=0.9, MeanCut=100, powerVector=None,
nBreaks=10,
blockSize=None, corOptions=None, networkType="unsigned", moreNetworkConcepts=False,
gcInterval=None):
"""
Analysis of scale free topology for multiple soft thresholding powers.
:param data: expression data in a matrix or data frame. Rows correspond to samples and columns to genes.
:param data: pandas dataframe
:param dataIsExpr: should the data be interpreted as expression (or other numeric) data, or as a similarity matrix of network nodes?
:type dataIsExpr: bool
:param weights: optional observation weights for data to be used in correlation calculation. A matrix of the same dimensions as datExpr, containing non-negative weights. Only used with Pearson correlation.
:type weights: pandas dataframe
:param RsquaredCut: desired minimum scale free topology fitting index (R^2). (default = 0.9)
:type RsquaredCut: float
:param MeanCut: desired maximum mean connectivity scale free topology fitting index. (default = 100)
:type MeanCut: int
:param powerVector: A list of soft thresholding powers for which the scale free topology fit indices are to be calculated.
:type powerVector: list of int
:param nBreaks: number of bins in connectivity histograms (default = 10)
:type nBreaks: int
:param blockSize: block size into which the calculation of connectivity should be broken up. If not given, a suitable value will be calculated using function blockSize and printed if verbose>0. If R runs into memory problems, decrease this value.
:type blockSize: int
:param corOptions: a list giving further options to the correlation function specified in corFnc.
:type corOptions: list
:param networkType: network type. Allowed values are (unique abbreviations of) "unsigned", "signed", "signed hybrid". (default = unsigned)
:type networkType: str
:param moreNetworkConcepts: should additional network concepts be calculated? If TRUE, the function will calculate how the network density, the network heterogeneity, and the network centralization depend on the power. For the definition of these additional network concepts, see Horvath and Dong (2008). PloS Comp Biol.
:type moreNetworkConcepts: bool
:param gcInterval: a number specifying in interval (in terms of individual genes) in which garbage collection will be performed. The actual interval will never be less than blockSize.
:type gcInterval: int
:return: tuple including powerEstimate: estimate of an appropriate soft-thresholding power which is the lowest power for which the scale free topology fit \(R^2\) exceeds RsquaredCut and conectivity is less than MeanCut. If \(R^2\) is below RsquaredCut for all powers maximum will re returned and datout which is a data frame containing the fit indices for scale free topology. The columns contain the soft-thresholding power, adjusted \(R^2\) for the linear fit, the linear coefficient, adjusted \(R^2\) for a more complicated fit models, mean connectivity, median connectivity and maximum connectivity. If input moreNetworkConcepts is TRUE, 3 additional columns containing network density, centralization, and heterogeneity.
:type: int and pandas dataframe
"""
if powerVector is None:
powerVector = list(range(1, 11)) + list(range(1, 21, 2))
powerVector = np.sort(powerVector)
intType = networkTypes.index(networkType)
if intType is None:
sys.exit(("Unrecognized 'networkType'. Recognized values are", str(networkTypes)))
nGenes = data.shape[1]
if nGenes < 3:
sys.exit("The input data data contain fewer than 3 rows (nodes).\n"
"This would result in a trivial correlation network.")
print(f"{OKCYAN}pickSoftThreshold: calculating connectivity for given powers...{ENDC}")
if not dataIsExpr:
WGCNA.checkSimilarity(data)
if any(np.diag(data) != 1):
data = np.where(np.diag(data), 1)
if blockSize is None:
blockSize = WGCNA.calBlockSize(nGenes, rectangularBlocks=True, maxMemoryAllocation=2 ** 30)
print("will use block size ", blockSize, flush=True)
if gcInterval is None or len(gcInterval) == 0:
gcInterval = 4 * blockSize
colname1 = ["Power", "SFT.R.sq", "slope", "truncated R.sq", "mean(k)", "median(k)", "max(k)"]
if moreNetworkConcepts:
colname1 = colname1.append(["Density", "Centralization", "Heterogeneity"])
datout = pd.DataFrame(np.full((len(powerVector), len(colname1)), 666), columns=colname1, dtype=object)
datout['Power'] = powerVector
datk = np.zeros((nGenes, len(powerVector)))
nPowers = len(powerVector)
startG = 0
lastGC = 0
if corOptions is None:
corOptions = pd.DataFrame()
corOptions['x'] = [data]
else:
corOptions['x'] = [data]
if weights is not None:
if not dataIsExpr:
sys.exit("Weights can only be used when 'data' represents expression data ('dataIsExpr' must be TRUE).")
if data.shape != weights.shape:
sys.exit("When 'weights' are given, dimensions of 'data' and 'weights' must be the same.")
corOptions['weights.x'] = weights
while startG < nGenes:
endG = min(startG + blockSize, nGenes)
useGenes = list(range(startG, endG))
nGenes1 = len(useGenes)
if dataIsExpr:
corOptions['y'] = [data.iloc[:, useGenes]]
if weights is not None:
corOptions['weights.y'] = [weights.iloc[:, useGenes]]
corx = np.corrcoef(corOptions.x[0], corOptions.y[0], rowvar=False)
corx = corx[0:corOptions.x[0].shape[1], useGenes]
if intType == 0:
corx = abs(corx)
elif intType == 1:
corx = (1 + corx) / 2
elif intType == 2:
corx[corx < 0] = 0
if np.count_nonzero(np.isnan(corx)) != 0:
print(
f"{WARNING}Some correlations are NA in block {str(startG)} : {str(endG)}.{ENDC}")
else:
corx = data.iloc[:, useGenes].to_numpy()
corx[useGenes, list(range(len(useGenes)))] = 1
datk_local = np.empty((nGenes1, nPowers))
datk_local[:] = np.nan
corxPrev = np.ones(corx.shape)
powerVector1 = [0]
powerVector1.extend(powerVector[:-1])
powerSteps = powerVector - powerVector1
uniquePowerSteps = np.unique(powerSteps)
def func(power):
return corx ** power
corxPowers = pd.DataFrame()
for p in uniquePowerSteps:
corxPowers[p] = [func(p)]
for j in range(nPowers):
corxCur = corxPrev * corxPowers[powerSteps[j]][0]
datk_local[:, j] = np.nansum(corxCur, axis=0) - 1
corxPrev = corxCur
datk[startG:endG, :] = datk_local
startG = endG
if 0 < gcInterval < startG - lastGC:
lastGC = startG
for i in range(len(powerVector)):
khelp = datk[:, i]
SFT1 = WGCNA.scaleFreeFitIndex(k=khelp, nBreaks=nBreaks)
datout.loc[i, 'SFT.R.sq'] = SFT1.loc[0, 'Rsquared.SFT']
datout.loc[i, 'slope'] = SFT1.loc[0, 'slope.SFT']
datout.loc[i, 'truncated R.sq'] = SFT1.loc[0, 'truncatedExponentialAdjRsquared']
datout.loc[i, 'mean(k)'] = statistics.mean(khelp)
datout.loc[i, 'median(k)'] = statistics.median(khelp)
datout.loc[i, 'max(k)'] = max(khelp)
if moreNetworkConcepts:
Density = sum(khelp) / (nGenes * (nGenes - 1))
datout.loc[i, 'Density'] = Density
Centralization = nGenes * (max(khelp) - statistics.mean(khelp)) / ((nGenes - 1) * (nGenes - 2))
datout.loc[i, 'Centralization'] = Centralization
Heterogeneity = np.sqrt(nGenes * sum(khelp ^ 2) / sum(khelp) ^ 2 - 1)
datout.loc[i, 'Heterogeneity'] = Heterogeneity
print(datout)
# detect threshold more than 0.9 by default
ind = np.logical_and(datout['SFT.R.sq'] > RsquaredCut, datout['mean(k)'] <= MeanCut)
if np.sum(ind) > 0:
powerEstimate = np.min(powerVector[ind])
print(f"{OKGREEN}Selected power to have scale free network is {str(powerEstimate)}.{ENDC}")
else:
ind = np.argsort(datout['SFT.R.sq']).tolist()
powerEstimate = powerVector[ind[-1]]
print(f"{OKGREEN}No power detected to have scale free network!\nFound the best given power which is "
f"{str(powerEstimate)}.{ENDC}")
return powerEstimate, datout
@staticmethod
def checkSimilarity(adjMat, min=-1, max=1):
"""
check similarity matrix format is correct
:param adjMat: data we want to be checked
:type adjMat: pandas dataframe
:param min: minimum value to be allowed for data (default = 0)
:type min: int
:param max: maximum value to be allowed for data (default = 1)
:type max: int
:raises exit: if format is not correct
"""
dim = adjMat.shape
if dim is None or len(dim) != 2:
sys.exit("adjacency is not two-dimensional")
if not (all(np.array_equal(adjMat[ele], adjMat[ele].astype(float)) for ele in adjMat)):
sys.exit("adjacency is not numeric")
if dim[0] != dim[1]:
sys.exit("adjacency is not square")
if all(np.max(np.abs(adjMat - adjMat.transpose())) > 1e-12):
sys.exit("adjacency is not symmetric")
if all(np.min(adjMat) < min) or all(np.max(adjMat) > max):
sys.exit(("some entries are not between", min, "and", max))
@staticmethod
def calBlockSize(matrixSize, rectangularBlocks=True, maxMemoryAllocation=None, overheadFactor=3):
"""
find suitable block size for calculating soft power threshold
"""
if maxMemoryAllocation is None:
maxAlloc = resource.getrlimit(resource.RLIMIT_AS)[1]
else:
maxAlloc = maxMemoryAllocation / 8
maxAlloc = maxAlloc / overheadFactor
if rectangularBlocks:
blockSz = math.floor(maxAlloc / matrixSize)
else:
blockSz = math.floor(math.sqrt(maxAlloc))
return min(matrixSize, blockSz)
# Calculation of fitting statistics for evaluating scale free topology fit.
@staticmethod
def scaleFreeFitIndex(k, nBreaks=10):
"""
calculates several indices (fitting statistics) for evaluating scale free topology fit.
:param k: numeric list whose components contain non-negative values
:type k: list
:param nBreaks: (default = 10)
:type nBreaks: int
"""
df = pd.DataFrame({'data': k})
df['discretized_k'] = pd.cut(df['data'], nBreaks)
dk = df.groupby('discretized_k').mean() # tapply(k, discretized_k, mean)
dk = pd.DataFrame(dk.reset_index())
dk.columns = ['discretized_k', 'dk']
p_dk = df['discretized_k'].value_counts() / len(k) # as.vector(tapply(k, discretized.k, length)/length(k))
p_dk = pd.DataFrame(p_dk.reset_index())
p_dk.columns = ['discretized_k', 'p_dk']
breaks1 = np.linspace(start=min(k), stop=max(k), num=nBreaks + 1)
y, edges = np.histogram(df['data'], bins=breaks1)
dk2 = 0.5 * (edges[1:] + edges[:-1])
df = pd.merge(dk, p_dk, on='discretized_k')
if df['dk'].isnull().values.any():
df.loc[df['dk'].isnull().values, 'dk'] = dk2[df['dk'].isnull().values]
if np.any(df['dk'] == 0):
df.loc[df['dk'] == 0, 'dk'] = dk2[df['dk'] == 0]
if df['p_dk'].isnull().values.any():
df.loc[df['p_dk'].isnull().values, 'p_dk'] = 0
df['log_dk'] = np.log10(df['dk'])
df['log_p_dk'] = np.log10(df['p_dk'] + 1e-09)
df['log_p_dk_10'] = np.power(10, df['log_dk'])
model1 = ols(formula='log_p_dk ~ log_dk', data=df).fit()
model2 = ols(formula='log_p_dk ~ log_dk + log_p_dk_10', data=df).fit()
dfout = pd.DataFrame({'Rsquared.SFT': [model1.rsquared],
'slope.SFT': [model1.params.values[1]],
'truncatedExponentialAdjRsquared': [model2.rsquared_adj]})
return dfout
@staticmethod
def adjacency(datExpr, selectCols=None, adjacencyType="unsigned", power=6, corOptions=pd.DataFrame(), weights=None,
weightArgNames=None):
"""
Calculates (correlation or distance) network adjacency from given expression data or from a similarity
:param datExpr: data frame containing expression data. Columns correspond to genes and rows to samples.
:type datExpr: pandas dataframe
:param selectCols: for correlation networks only; can be used to select genes whose adjacencies will be calculated. Should be either a numeric list giving the indices of the genes to be used, or a boolean list indicating which genes are to be used.
:type selectCols: list
:param adjacencyType: adjacency network type. Allowed values are (unique abbreviations of) "unsigned", "signed", "signed hybrid". (default = unsigned)
:type adjacencyType: str
:param power: soft thresholding power.
:type power: int