-
Notifications
You must be signed in to change notification settings - Fork 1
/
Tutorial-Command-Line-Interface-Step_2.py
1298 lines (928 loc) · 50.9 KB
/
Tutorial-Command-Line-Interface-Step_2.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
######################################################################
######### Dynamical Network Analysis
######### Tutorial for command line interface - Analysis and Plots
######################################################################
################################################
################################################
### Load necessary python packages
################################################
################################################
# Load the Dynamical Network Analysis package
import dynetan as dna
from dynetan.toolkit import getNodeFromSel, getSelFromNode, getPath, getCartDist
from dynetan.viz import viewPath, getCommunityColors
from dynetan.viz import showCommunityByID, showCommunityByNodes
from dynetan.viz import prepTclViz
# Load auxiliary packages for data analysis
import pandas as pd
import numpy as np
import scipy as sp
import networkx as nx
import MDAnalysis as mda
import os
from scipy import stats
from itertools import islice
from collections import defaultdict
################################################
################################################
### Load R interface and packages
################################################
################################################
# Load R packages
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
rbase = importr('base')
rdt = importr('data.table')
rgg2 = importr('ggplot2')
rggr = importr('ggrepel')
rgdata = importr('gdata')
rColBrew = importr('RColorBrewer')
rColMap = importr('colorRamps')
rPref = importr('rPref')
################################################
################################################
### Files and system definitions (same as in "ProcessTrajectory" notebook)
################################################
################################################
# Path to where data files were saved
dataDir = "./TutorialResults/"
# Path where results will be written (you may want plots and data files in a new location)
workDir = "./TutorialResults/AnalysisResults"
fileNameRoot = "dnaData"
fullPathRoot = os.path.join(dataDir, fileNameRoot)
# Define the segID of the Ligand being studied.
ligandSegID = "OMP"
# System tag
system1 = "OMP_WT"
# Prefix for plots created along this tutorial
plotFilePrefix = "OMP_"
# Creates the workdirectory, and Plots directory.
import os
if not os.path.exists(workDir):
os.makedirs(workDir)
os.makedirs(os.path.join(workDir, "Plots"))
verbosity = True
skipPlots = False
# Plot sizes
plotW = 3500
plotH = 1800
# Cutoff for cartesian contacts
cartCutoff = 4.0
# Load variables into R interpreter.
ro.globalenv['ligandSegID'] = ligandSegID
ro.globalenv['workDir'] = workDir
ro.globalenv['plotFilePrefix'] = plotFilePrefix
################################################
################################################
### Load the Data
################################################
################################################
dnad = dna.datastorage.DNAdata()
dnad.loadFromFile(fullPathRoot)
# Load reduced trajectory, in case this notebook did not load ALL trajectories.
dcdVizFile = fullPathRoot + "_reducedTraj.dcd"
pdbVizFile = fullPathRoot + "_reducedTraj.pdb"
workUviz = mda.Universe(pdbVizFile, dcdVizFile)
# If we are loading the first trajectory of the notebook, we need to create the
# dnad.nodesAtmSel structure to make selections on the universe based on node indices.
# This is mostly used for visualizations.
# We add this to the object for ease of access.
dnad.nodesAtmSel = workUviz.atoms[ dnad.nodesIxArray ]
trgtNodes = getNodeFromSel("segid " + ligandSegID, dnad.nodesAtmSel, dnad.atomToNode)
trgtNode = getNodeFromSel("segid " + ligandSegID + " and name P", dnad.nodesAtmSel, dnad.atomToNode)
print("Main target node: {} ; All target nodes: {}.".format(trgtNode,trgtNodes) )
################################################
################################################
### Analyze Communitites
################################################
################################################
# We keep the communities that have more than 1% of nodes in all windows.
# Then we group communities across replicas by largest intersection.
# This is needed because we have no guarantee that the same community will be
# assigned the same ID in different windows of the same simulation.
# We finally rank the communities by modularity.
# Set a cutoff value for community analysis. Only communities with at least
# `cutoff` nodes will be kept for analysis.
cutoff = max(10, np.ceil(0.01*dnad.numNodes))
import networkx.algorithms.community.quality as nxquality
# Creates a list of windows and order them according to graph modularity.
windModul = []
for window in range(dnad.numWinds):
modul = nxquality.modularity(dnad.nxGraphs[window],
[ set(nodesList) for nodesList in dnad.nodesComm[window]["commNodes"].values()])
windModul.append((window, modul))
windModul.sort(key=lambda x:x[1], reverse=True)
# Keep the window with the highest modularity as a reference for community matching
refWindow = windModul[0][0]
for wind, mod in windModul[:5]:
print( "Window {} has modularity {:1.4f}.".format(wind, mod) )
print("Using reference window {0} with highest modularity {1:<1.4}".format(*windModul[0]))
def matchComm(mCommID, mWindow, refWindow, dnad, cutoff=1):
"""
Returns the community ID for the reference window that has the largest
intersection with the matching community at the matching window.
Communities at the reference window with less than *cutoff* percent of nodes
are ignored.
"""
trgtComm = -1
intersectSize = 0
for commID in dnad.nodesComm[refWindow]["commOrderSize"]:
# Skip community if it has less than one percent of the nodes.
commSize = len(dnad.nodesComm[refWindow]["commNodes"][commID])
if commSize < cutoff:
continue
tmpSize = len( set(dnad.nodesComm[refWindow]["commNodes"][commID]).intersection(
set(dnad.nodesComm[mWindow]["commNodes"][mCommID]) ) )
# Selects the largets intersection
if intersectSize < tmpSize:
intersectSize = tmpSize
trgtComm = commID
return trgtComm, intersectSize
communities = defaultdict(list)
for window in range(dnad.numWinds):
for commID in dnad.nodesComm[window]["commOrderSize"]:
# Skip community if it has less than one percent of the nodes.
commSize = len(dnad.nodesComm[window]["commNodes"][commID])
if commSize < cutoff:
continue
matchID, interSize = matchComm(commID, window, refWindow, dnad, cutoff)
communities[matchID].append( (commID, interSize, window) )
communities = {key:val for (key,val) in communities.items() }
communities.keys()
# Creates a list of communities ID from the dictionary keys
# Orders the keys according to mean intersection size over all windows.
tmpList = []
for key,val in communities.items():
tmpList.append((key, np.mean([pair[1] for pair in val]), len(val)))
tmpList.sort(key=lambda x:x[1], reverse=True)
tmpList
# Creates a pandas data frame for plotting and analysis
commList = []
genCommID = 0
for key in [x[0] for x in tmpList]:
val = communities[key]
for valList in val:
commList.append( [genCommID, *valList ] )
genCommID += 1
commDF = pd.DataFrame(data=commList, columns=["genCommID","commID","interSize","Window"])
# Changes "genCommID" for communities that are matched to the same community in the reference window.
c = commDF.groupby(["genCommID","Window"]).cumcount()
c *= 0.1
commDF[ "genCommID" ] += c
# Creates a NumPy 2D array to organize data and transform it in a pandas DF.
# Not pretty but its pynthon...
nodeCommNP = np.empty([dnad.numNodes, dnad.numWinds])
nodeCommNP.fill(-1)
#Group by general community ID
grpBy = commDF.groupby("genCommID")
for genCommID, group in grpBy:
for winIndx,commID in group[["Window","commID"]].values:
for node in range(dnad.numNodes):
if dnad.nxGraphs[winIndx].nodes[node]["modularity"] == commID:
nodeCommNP[node, winIndx] = genCommID
# Removes nodes that were not classified in a "big-nough" (bigger than 1%) cluster in *any* window.
nodeCommDF = pd.DataFrame(data=nodeCommNP,columns=["Window"+str(i) for i in range(dnad.numWinds)])
nodeCommDF["Node"] = [i for i in range(dnad.numNodes)]
nodeCommDF = nodeCommDF[ nodeCommDF.min(1) >= 0]
# So we don't get "blank"/empty areas in the plot
nodeCommDF["NodePlot"] = [i for i in range(len(np.unique(nodeCommDF["Node"])))]
# Checks that target nodes are classified in ALL windows
print("\nCheck that target nodes are classified in ALL windows.")
print( nodeCommDF.loc[ nodeCommDF["Node"].isin(trgtNodes) ] )
# Melts for plotting.
nodeCommDFmelt = nodeCommDF.melt(id_vars=["Node","NodePlot"], value_name="Cluster", var_name="Window")
# Makes it easier to plot
nodeCommDFmelt["Cluster"] = nodeCommDFmelt["Cluster"].astype('category')
# Makes it easier to plot
for i in range(dnad.numWinds):
nodeCommDFmelt.replace("Window"+str(i),i, inplace=True)
nodeCommDFmelt.loc[nodeCommDFmelt["Node"].isin(trgtNodes)].groupby("Node")["Cluster"].apply(np.unique)
#
trgtClusters = np.unique( nodeCommDFmelt.loc[nodeCommDFmelt["Node"].isin(trgtNodes), "Cluster"].values )
print("\nTarget clusters:",trgtClusters)
# Add readable info to nodes
def getTagStr(i):
# Store atom names for residues with multiple nodes
if len(getNodeFromSel( getSelFromNode(i, dnad.nodesAtmSel), dnad.nodesAtmSel, dnad.atomToNode)) > 1:
atmStr = ":" + dnad.nodesAtmSel.atoms[i].name
else:
atmStr = ""
retStr = dnad.nodesAtmSel.atoms[i].resname.capitalize() + \
":" + str(dnad.nodesAtmSel.atoms[i].resid) + \
atmStr + \
"_" + dnad.nodesAtmSel.atoms[i].segid
return retStr
nodeCommDFmelt['resid'] = np.vectorize(getTagStr)(nodeCommDFmelt["Node"])
# Write data for Ploting (plots from ggplot in R are much better!)
nodeCommDFmelt.to_csv(os.path.join(workDir, "cluster.csv"),index=False)
# Get all nodes that make contact with target nodes in any window
contactNodes = np.unique( np.where( dnad.corrMatAll[:,trgtNodes,:] > 0 )[2] )
contactNodesTrgts = list(trgtNodes)
for node in contactNodes:
if len( set(trgtClusters).intersection(
set(np.unique(nodeCommDFmelt.loc[ nodeCommDFmelt["Node"] == node].Cluster)) ) ) :
contactNodesTrgts.append(node)
# Save data to file
pd.DataFrame(contactNodesTrgts, columns=["contactNodesTrgts"]).to_csv(
os.path.join(workDir, "contactNodesTrgts.csv"),index=False)
pd.DataFrame(trgtNodes, columns=["trgtNodes"]).to_csv(
os.path.join(workDir, "trgtNodes.csv"),index=False)
################################################
### Prepare pandas data frame with community data
################################################
## Initialize color scales
# Prepares variable names for multi-system comparisons.
# In this tutorial, we only have one system.
cDF = nodeCommDFmelt
cDF["system"] = system1
refWindow1 = refWindow
# Loads VMD-compatible color scales to match community colors in R plots and VMD figures.
comColorScale = getCommunityColors()
# %%R R code for analysis and plot
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
# create a function `f`
createColors <- function(comColorScale, verbose=FALSE) {
if (verbose) {
cat("Running createColors R function.\n")
}
dataPath = file.path(workDir, "cluster.csv")
dt <- fread(dataPath)
clusterIDs = dt[, unique(Cluster)]
colourCount = length(unique(dt$Cluster))
cat(paste("Creating palette for",colourCount,"clusters.\n"))
# We only have 50 availabl colors
colourCount <- min(colourCount,50)
rgbCodes <- data.table(comColorScale)
colorValues <- sapply(seq(colourCount), function(x) rgb(rgbCodes[x, .(R,G,B) ], maxColorValue = 255) )
setorder(dt, Cluster)
colorValues = setNames(colorValues, dt[, unique(Cluster)])
colorValues <<- colorValues
clusterIDs <<- clusterIDs
#return( c(colorValues=colorValues, clusterIDs=clusterIDs) )
}
''')
r_createColors = ro.r['createColors']
# This allows us to easily convert between R's data.table object and Panda's data frame.
with localconverter(ro.default_converter + pandas2ri.converter):
r_createColors(comColorScale, verbose=verbosity)
clusterIDs = ro.r['clusterIDs']
colorValues = ro.r['colorValues']
colorValDict = {}
colorValDictRGB = {}
for key,val in zip(clusterIDs, list(colorValues)):
colorValDict[key] = val
for key,val in colorValDict.items():
colorValDictRGB[key] = tuple(int(val.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4))
################################################
################################################
### PLOTS: Clustering of nodes
################################################
################################################
if not skipPlots:
print("\nCreating plot: nodes by window")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotClusterWindow <- function(width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotClusterWindow R function.\n")
}
dataPath = file.path(workDir, "cluster.csv")
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Clusters_Node_vs_Window.png"))
dt <- fread(dataPath)
dt <- dt[,.(NodePlot,Window,Cluster)]
dt <- dt[, Cluster := as.factor(Cluster) ]
p <- ggplot(dt) +
geom_raster(aes(x=NodePlot, y=Window, fill=Cluster)) +
scale_fill_manual(values = colorValues) +
labs(x="Node", y="Window") +
theme_bw(base_size=20)
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotClusterWindow = ro.r['plotClusterWindow']
with localconverter(ro.default_converter + pandas2ri.converter):
r_plotClusterWindow(plotW, plotH, verbose=verbosity)
print("\nCreating plot: nodes (grouped by community) by window")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotClusterGrpWindow <- function(refWindow, trgtNodes, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotClusterGrpWindow R function.\n")
}
dataPath = file.path(workDir, "cluster.csv")
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Clusters_Node_vs_Window_Grouped.png"))
dt <- fread(dataPath)
dt <- dt[, Cluster := as.factor(Cluster) ]
setorder(dt, Cluster, Window)
dt <- dt[, NodePlot := as.factor(NodePlot) ]
# Get the actual indices of the nodes in the re-ordered x-axis (grouped by cluster)
trgtIndices = data.table(trgt = c(which(dt[Window == refWindow]$Node %in% trgtNodes)) )
breaksNodePlot = dt[Window == refWindow,][ Node %in% trgtNodes, NodePlot ]
labelsNode = dt[Window == refWindow,][ Node %in% trgtNodes, Node ]
# Build base plot
p <- ggplot(dt) +
geom_raster(aes(x=NodePlot, y=Window, fill=Cluster))
# Add intercept lines for target nodes
p <- p + geom_vline(data=trgtIndices, aes(xintercept=trgt), alpha=0.8, linetype = "dashed")
p <- p + geom_hline(aes(yintercept=refWindow), alpha=0.9, linetype = "dashed")
# Finish building plot
p <- p + scale_fill_manual(values = colorValues) +
scale_x_discrete(limits=dt[Window == refWindow]$NodePlot, breaks=breaksNodePlot, labels=labelsNode) +
labs(x="Nodes", y="Window") +
theme_bw(base_size=20)
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotClusterGrpWindow = ro.r['plotClusterGrpWindow']
with localconverter(ro.default_converter + pandas2ri.converter):
# We create a new native python list because rPy2 can't directly convert a NP array.
r_plotClusterGrpWindow(refWindow, [int(node) for node in trgtNodes],
plotW, plotH, verbose=verbosity)
print("\nCreating plot: Active site - nodes (grouped by community) by window")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotASClusterGrpWindow <- function(refWindow, trgtNodes, contactNodesTrgts, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotASClusterGrpWindow R function.\n")
}
dataPath = file.path(workDir, "cluster.csv")
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Clusters_Node_vs_Window_Grouped_ActiveSite.png"))
dt <- fread(dataPath)
dt <- dt[,.(Node,Window,Cluster,resid)]
dt <- dt[, Cluster := as.factor(Cluster) ]
dt <- dt[, Node := as.factor(Node) ]
setorder(dt, Cluster, Window)
dt <- dt[ Node %in% contactNodesTrgts, ]
dt <- dt[, resid := sapply(strsplit(resid, "_"), '[', 1) ]
# Build base plot
p <- ggplot(dt) +
geom_raster(aes(x=Node, y=Window, fill=Cluster))
# Get the actual indices of the nodes in the re-ordered x-axis (grouped by cluster)
trgtIndices = data.table(trgt = c(which(dt[Window == refWindow]$Node %in% trgtNodes)) )
# Add intercept lines for target nodes
p <- p + geom_vline(data=trgtIndices, aes(xintercept=trgt), alpha=0.9, linetype = "dashed")
p <- p + geom_hline(aes(yintercept=refWindow), alpha=0.9, linetype = "dashed")
# Finish building plot
p <- p + scale_fill_manual(values = colorValues) +
scale_x_discrete(limits=dt[Window == refWindow]$Node, label=dt[Window == refWindow]$resid) +
labs(x="Nodes", y="Window") +
theme_bw(base_size=20) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotASClusterGrpWindow = ro.r['plotASClusterGrpWindow']
with localconverter(ro.default_converter + pandas2ri.converter):
# We create a new native python list because rPy2 can't directly convert a NP array.
r_plotASClusterGrpWindow(refWindow, [int(node) for node in trgtNodes],
[int(node) for node in contactNodesTrgts], plotW, plotH, verbose=verbosity)
print("\nCreating plot: Ligand - nodes (grouped by community) by window")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotLigandClusterGrpWindow <- function(refWindow, trgtNode, trgtNodes, ligandSegID, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotLigandClusterGrpWindow R function.\n")
}
trgtNode = as.integer(trgtNode)
dataPath = file.path(workDir, "cluster.csv")
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Clusters_Node_vs_Window_Grouped_",ligandSegID,".png"))
dt <- fread(dataPath)
dt <- dt[,.(Node,Window,Cluster,resid)]
dt <- dt[ Node %in% trgtNodes, ]
dt <- dt[, Cluster := as.factor(Cluster) ]
dt <- dt[, Node := as.factor(Node) ]
dt <- dt[, Window := as.factor(Window) ]
dt <- dt[, resid := sapply(strsplit(resid, "_"), '[', 1) ]
dt <- dt[, resid := as.factor(resid) ]
setorder(dt, Cluster, Node)
# Build base plot
p <- ggplot(dt) +
geom_raster(aes(x=Node, y=Window, fill=Cluster))
trgtNodesF <- as.factor(unlist(trgtNodes))
p <- p + scale_fill_manual(values = colorValues) +
scale_x_discrete(limits=trgtNodesF, label=dt[ Node %in% trgtNodesF, unique(resid)]) +
scale_y_discrete(limits=dt[Node == trgtNode]$Window, labels=NULL) +
labs(x="Nodes", y="Window") +
theme_bw(base_size=20) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotLigandClusterGrpWindow = ro.r['plotLigandClusterGrpWindow']
with localconverter(ro.default_converter + pandas2ri.converter):
# We create a new native python list because rPy2 can't directly convert a NP array.
r_plotLigandClusterGrpWindow(refWindow, int(trgtNode),
[int(node) for node in trgtNodes],
ligandSegID, plotW, plotH, verbose=verbosity)
################################################
################################################
### Combine data for Interface and Active Site analysis
################################################
################################################
# Combines interface edges with label information for plots.
# Creates structure wirh optimal paths and labels for Active Site analysis,
# shaping information for interaction between ligand and active site residues.
# Gets all pairs of nodes with non-zero correlations
nonzeroPairs = [(i,j) for i,j in np.asarray(np.where(dnad.contactMat > 0)).T if i < j]
# Combines cartesian distance and correlation
# We use the mean cartesian distance (0:mean, 1:SEM, 2:Min, 3:Max)
carCorMat = [ [i, j,
getCartDist(i,j,dnad.numNodes,dnad.nodeDists, 0),
getCartDist(i,j,dnad.numNodes,dnad.nodeDists, 1),
np.mean(dnad.corrMatAll[:,i,j]),
stats.sem(dnad.corrMatAll[:,i,j])]
for i,j in nonzeroPairs if np.mean(dnad.corrMatAll[:,i,j]) > 0 ]
carCorMat = pd.DataFrame(carCorMat, columns=["i","j","Cart","CartSEM","Corr","CorrSEM"])
def interNode(i,j,dnad):
# Checks if the pair of nodes exists in the "interNodePairs" 2D array.
return len( ( dnad.interNodePairs == [i, j] ).all(axis=1).nonzero()[0] )
# Adds interface information (true/false)
carCorMat["EdgeType"] = carCorMat.apply( lambda x: "Interface" if interNode(x["i"], x["j"], dnad)
else "Internal" , axis=1)
dataTmp = []
window = 0
for window in range(dnad.numWinds):
df = pd.DataFrame(np.asarray([ (i,trgt) for trgt in trgtNodes for i in range(dnad.numNodes)]),
columns=["node", "targets"])
df["distances"] = df.apply( lambda row: dnad.distsAll[window, row["node"], row["targets"]], axis=1)
# Selects the mean distance (0:mean, 1:SEM, 2:Min, 3:Max)
distType = 0
df["cdistances"] = df.apply( lambda row: getCartDist(int(row["node"]),
int(row["targets"]), dnad.numNodes,
dnad.nodeDists, distType), axis=1)
# Selects the standard error of the mean distance (0:mean, 1:SEM, 2:Min, 3:Max)
distType = 1
df["cdistSEM"] = df.apply( lambda row: getCartDist(int(row["node"]),
int(row["targets"]), dnad.numNodes,
dnad.nodeDists, distType), axis=1)
df["path"] = df.apply( lambda row: list(getPath(int(row["node"]),
int(row["targets"]),
dnad.nodesAtmSel, dnad.preds, win= window)), axis=1)
df['path_lens'] = df.apply( lambda row: len(row["path"]), axis=1)
# df["mincdist"] = df.groupby("node")[["cdistances"]].transform(lambda x: np.min(x) )
def getTagStr(i):
return dnad.nodesAtmSel.atoms[i].resname.capitalize() + ":" + str(dnad.nodesAtmSel.atoms[i].resid) + \
"_" + dnad.nodesAtmSel.atoms[i].segid
df['resid'] = np.vectorize(getTagStr)(df["node"])
ptnIXs = dnad.nodesAtmSel.select_atoms("protein").ix_array
nclIXs = dnad.nodesAtmSel.select_atoms("nucleic").ix_array
def getType(nodeIndx):
if dnad.nodesAtmSel.atoms[nodeIndx].ix in ptnIXs:
return "Aminoacid"
elif dnad.nodesAtmSel.atoms[nodeIndx].ix in nclIXs:
return "Nucleotide"
else:
return dnad.nodesAtmSel.atoms[nodeIndx].resname
df["type"] = np.vectorize(getType)(df["node"])
df["Interface"] = df["node"].apply( lambda x: x in dnad.contactNodesInter)
# "Cleans" all -1 distances betweeen nodes not connected by any path.
df.loc[ df["path_lens"] == 0, "distances" ] = 0
df["window"] = window
dataTmp.append(df.copy())
del df
df = pd.concat(dataTmp)
del dataTmp
print("\nCombined data on cartesian distances and correlation.")
print(df.tail())
print("\nFocus data on ligand:")
print(df[ (np.isin(df["node"],getNodeFromSel("segid " + ligandSegID, dnad.nodesAtmSel, dnad.atomToNode))) & (df["window"] == 0) ])
################################################
################################################
### Add labels to selected residues
################################################
################################################
# Manually add labels to residues of interests.
df["Label"] = 0
tags = dict()
tags["OMPn"] = getNodeFromSel("resname OMP and name N1", dnad.nodesAtmSel, dnad.atomToNode)[0]
tags["OMPp"] = getNodeFromSel("resname OMP and name P", dnad.nodesAtmSel, dnad.atomToNode)[0]
for label, node in tags.items():
if not node in df.node:
print("Skiping node not found:",node)
continue
df.loc[ df.node == node, 'Label'] = label
print("\nUpdate dataframe with label information for ligand:")
print(df.loc[ (df["resid"] == "Omp:301_OMP") & (df["window"] == 0) ])
################################################
################################################
### Adds label and type information for all pairs of connected residues in the system
################################################
################################################
carCorMat["iRes"] = carCorMat.apply(lambda row: df[ (df["node"] == row["i"]) &
(df["targets"] == trgtNode[0])]["resid"].iloc[0] , axis=1)
carCorMat["jRes"] = carCorMat.apply(lambda row: df[ (df["node"] == row["j"]) &
(df["targets"] == trgtNode[0])]["resid"].iloc[0] , axis=1)
carCorMat["iType"] = carCorMat.apply(lambda row: df[ (df["node"] == row["i"]) &
(df["targets"] == trgtNode[0])]["type"].iloc[0] , axis=1)
carCorMat["jType"] = carCorMat.apply(lambda row: df[ (df["node"] == row["j"]) &
(df["targets"] == trgtNode[0])]["type"].iloc[0] , axis=1)
print("\nUpdate cartesian and correlation matrix with node types:")
print(carCorMat.head())
print(carCorMat.tail())
carCorMatInterface = carCorMat[ carCorMat["EdgeType"] == "Interface" ]
################################################
################################################
### Compare Intra and Inter segment correlations
################################################
################################################
if not skipPlots:
print("\nCreating plot: Correlation VS Cartesian Distance (at interface)")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotCorrVSCart <- function(workDir, carCorMat, cartCutoff=4.0, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotCorrVSCart R function.\n")
}
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Interf_Intern_Cart_vs_Corr.png"))
dt = data.table(carCorMat)
dt = dt[Cart < cartCutoff]
p <- ggplot(dt) +
geom_point( aes(x=Cart, y=Corr, color=EdgeType), alpha=0.7, size=3 ) +
geom_smooth( aes(x=Cart, y=Corr, color=EdgeType) ) +
labs(x="Mean Cartesian Distance (A)", y="Mean Correlation", color="Edge Type") +
scale_color_brewer(type='qual', palette=6) +
theme_linedraw(base_size=20) + xlim(c(2.5, cartCutoff))
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotCorrVSCart = ro.r['plotCorrVSCart']
with localconverter(ro.default_converter + pandas2ri.converter):
r_plotCorrVSCart(workDir, carCorMat, cartCutoff, plotW, plotH, verbose=verbosity)
################################################
################################################
### Compare network connectivity, network distance and cartesian distance
################################################
################################################
# Select all nodes involved in at least one "Interface" connection.
tmpDF = carCorMat[ carCorMat["EdgeType"] == "Interface" ]
tmpNodeSet = set(tmpDF["i"])
tmpNodeSet.update( set(tmpDF["j"]) )
nodeContacs = []
for node in tmpNodeSet:
tmp = tmpDF.loc[ (tmpDF["i"] == node) | (tmpDF["j"] == node) ]["Corr"]
tmp2 = tmpDF.loc[ (tmpDF["i"] == node) | (tmpDF["j"] == node) ]["Cart"]
label = df.loc[ df["node"] == node ]["resid"].unique()[0]
nodeContacs.append( [node, int(tmp.size),
tmp.mean(), sp.stats.sem( tmp ),
tmp2.mean(), sp.stats.sem( tmp2 ),
label] )
del tmp, tmp2, label, tmpDF
nodeContacs = pd.DataFrame(nodeContacs,
columns=["Node", "NumContacts", "MeanCorr", "SEMCorr",
"MeanCart", "SEMCart", "label"])
nodeContacs = nodeContacs.fillna(0)
if not skipPlots:
print("\nCreating plot: Contacts VS Cartesian Distance (at interface)")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotContVSCart <- function(nodeContacs, contCutoff=10, cartCutoff=3.0, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotContVSCart R function.\n")
}
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Interface_Contacts_vs_Cart.png"))
dt <- data.table(nodeContacs)
#sapply(dt, class)
p <- ggplot(dt) +
geom_point(aes(x=NumContacts, y=MeanCart, color=as.double(MeanCorr)), size=3) +
geom_label_repel(data=dt[NumContacts >= contCutoff | MeanCart <= cartCutoff | MeanCorr > 0.8 ],
aes(x=NumContacts, y=MeanCart, label=label)) +
scale_y_log10() +
scale_x_log10() +
labs(x="Number of Contacts",
y="Mean Cartesian Distance",
color="Mean Correlation") +
scale_color_gradient(low="blue",high="red") +
theme_linedraw(base_size=20)
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotContVSCart = ro.r['plotContVSCart']
with localconverter(ro.default_converter + pandas2ri.converter):
r_plotContVSCart(nodeContacs, 10, 3.0, plotW, plotH, verbose=verbosity)
################################################
################################################
### Active stite connections
################################################
################################################
# Here we visualize the residues that make direct connections to the ligand,
# and display their generalized correlation coefficients.
if not skipPlots:
print("\nCreating plot: AAres VS Correlation (at interface)")
# We use rPy2 inteface to create R code inside the python script, and execute using an R interpreter.
ro.r('''
plotAAresVSCorr <- function(carCorMatInterface, corrCutoff=0, width=800, height=450, verbose=FALSE) {
if (verbose) {
cat("Running plotAAresVSCorr R function.\n")
}
plotPath = file.path(workDir, paste0("Plots/",plotFilePrefix,"Interface_AAres_vs_Corr_NoLabel.png"))
dt <- data.table(carCorMatInterface)
iResList <- dt[iType == "Aminoacid" & jType != "TIP3"][Corr > corrCutoff][,iRes]
dt <- dt[ iRes %in% iResList, ]
dt <- dt[jType != "TIP3", .SD[which.max(Corr)] , by=.(iRes,jRes)]
dt <- dt[, iRes := sapply(strsplit(iRes, "_"), '[', 1) ]
colours <- c("Aminoacid" = "red",
"TIP3" = "blue",
"Nucleotide" = "darkorange")
colours <- c(colours, setNames("purple",ligandSegID))
shapes <- c("Aminoacid" = 19,
"TIP3" = 15,
"Nucleotide" = 17)
shapes <- c(shapes, setNames(19,ligandSegID))
p <- ggplot(dt) +
geom_linerange( aes(x=iRes, y=Corr, ymin=Corr-CorrSEM, ymax=Corr+CorrSEM), size=1 )+
geom_point( aes(x = iRes, y = Corr, color = jType, size=Cart) )+
labs(x="Aminoacid Residue", y="Mean Correlation", color="Residue Type", size="Mean Distance") +
scale_colour_manual(name = "Residue Type",
values = colours) +
guides(colour = guide_legend(override.aes = list(size=5))) +
theme_classic(base_size = 20) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1),
panel.grid.major.x = element_line(color="black", size=0.5, linetype="dotted"))
ggsave(plotPath, p, device="png", width=width, height=height, units="px")
return(0)
}
''')
r_plotAAresVSCorr = ro.r['plotAAresVSCorr']
with localconverter(ro.default_converter + pandas2ri.converter):
r_plotAAresVSCorr(carCorMatInterface, 0.0, plotW, plotH, verbose=verbosity)
################################################
################################################
### Pretty Figures - Preparing files for VMD
################################################
################################################
# The next few steps will define the files that will be created for loading
# into VMD, a popular molecular visualization software.
#
# Important:
#
# Make sure you have all the files created for VMD. For instance, if you are not
# interested in allosteric communications and suboptimal paths, just select two
# arbitrary nodes so that the path files are created correctly. Alternatively,
# you may want to adapt the tcl scripts provided at the end of the notebook to
# your particular case.
import copy
# This will be used to look for the maximum and minimum betweenness value in the graph.
# The maximum value will be used ot normalize all betweenness values for better vizualization.
# The minimum value will be used in case a betweenness value could not be assigned for a given edge,
# also helping visualization.
# Initialize variable with high value.
minimumBetweeness = 100
# Initialize variable with low value.
maximumBetweeness = -1
for pair,btw in dnad.btws[winIndx].items():
if btw < minimumBetweeness:
minimumBetweeness = btw
if btw > maximumBetweeness:
maximumBetweeness = btw
# Normalize the value.
minimumBetweeness /= maximumBetweeness
for winIndx in range(dnad.numWinds):
normCorMat = copy.deepcopy( dnad.corrMatAll[winIndx,:,:] )
normCorMat /= normCorMat.max()
##########################################################################################
### Create PDB file with the system in the first step of each window, for VMD vizualization.
pdbVizFile = os.path.join(workDir,
"networkData_Structure_window_{}.pdb".format(winIndx))
# Calculate number of frames per window.
winLen = int(np.floor(workUviz.trajectory.n_frames/dnad.numWinds))
# Positions the trajectory at the middle of each window.
workUviz.trajectory[(winIndx+1)*round(winLen/2)]
with mda.Writer(pdbVizFile, multiframe=False, bonds="conect", n_atoms=workUviz.atoms.n_atoms) as PDB:
PDB.write(workUviz.atoms)
##########################################################################################
### Create network data file with ALL edges and their normalized weights.
fileName = os.path.join(workDir,
"networkData_AllEdges_window_{}.dat".format(winIndx))
with open(fileName, "w") as outfile:
for pair in np.asarray( np.where( np.triu(normCorMat[:,:]) ) ).T:
node1 = pair[0]
node2 = pair[1]
# Get VMD indices for the atoms
pdbIndx1 = dnad.nodesAtmSel.atoms[node1].id -1
pdbIndx2 = dnad.nodesAtmSel.atoms[node2].id -1
string = "{} {} {}".format(pdbIndx1, pdbIndx2, normCorMat[ node1, node2])
outfile.write( string + "\n" )
##########################################################################################
### Create network data file with ALL NODES, the maximum normalized weight of edges it belongs to,
### and the community it belongs to.
fileName = os.path.join(workDir,
"networkData_AllNodes_window_{}.dat".format(winIndx))
with open(fileName, "w") as outfile:
for node1 in range(dnad.numNodes):
# Get the VMD index for the atom
pdbIndx1 = dnad.nodesAtmSel.atoms[node1].id -1
# Get the community the node belongs to
community1 = int(nodeCommNP[node1, winIndx])
# Find the node to which "node1" is connected with highest correlation.
node2 = np.where( normCorMat[node1,:] == normCorMat[node1,:].max() )[0][0]