-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkov.py
2332 lines (2036 loc) · 92.1 KB
/
markov.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 numpy as np, time, random, os, subprocess,numpy.linalg as npla, matplotlib.pyplot as plt, scipy.linalg as spla, time, scipy.stats as spst, scipy.spatial.distance as spsd
from scipy import weave
from operator import sub, div
#params = {'axes.titlesize':70,
# 'axes.labelsize':60,
# 'text.fontsize':60,
# 'font.size':50,
# 'lines.markersize':6,
# 'lines.linewidth':4,
# 'text.usetex':True,
# 'xtick.major.pad':7,
# 'ytick.major.pad':18}
#plt.rcParams.update(params)
#Takes a .gro file and returns a 1d list of positions, box lengths, and a 1d list of whether the molecule does
#or does not contain a particular residue (used to tell if it's charged or uncharged)
#resInfo is a tuple ('resname',pos), where position is the index within the molecule of the residue
def recluster1(ind,coms,cutoff,box):
currind = ind
#mols = range(np.shape(coms,1)))
inds = np.zeros(np.shape(mols))
masses = np.zeros(np.shape(mols))
while len(mols) > 0:
currmol = mols[0]
mols = mols.remove(currmol)
clust = getClust1(currmol,mols,coms,cutoff,box)
for c in clust:
mols = mols.remove(c)
inds[c] = currind
masses[c] = len(clust)
currind += 1
return (inds,masses)
def readGroQ(fName,resInfo,ats):
with open(fName, 'r') as myF:
myLns = myF.read().splitlines()
boxL1 = float(myLns[len(myLns)-1].split()[0])
boxL2 = float(myLns[len(myLns)-1].split()[1])
boxL3 = float(myLns[len(myLns)-1].split()[2])
resBool = np.zeros([(len(myLns)-2)/ats,1])
j=0
for i in range(resInfo[1]+2,len(myLns)-1,ats):
#print(myLns[i][5:8])
if myLns[i][5:8] == resInfo[0]:
#print(myLns[i][5:8])
#print i
resBool[j]=1.0
j+=1
#print(i/ats)
return (np.array([[float(myLns[i][20:].split()[0]), float(myLns[i][20:].split()[1]), float(myLns[i][20:].split()[2])] for i in range(2, len(myLns)-1)]).flatten(),np.array([boxL1,boxL2,boxL3]),resBool)
def getPosQ(t,trj,tpr,outGro,resInfo,ats):
os.system('echo 0 | trjconv -f ' + trj + ' -o ' + outGro + ' -b ' + str(t) + ' -e ' + str(t) + ' -s ' + tpr)
#subprocess.check_output([])
return readGroQ(outGro,resInfo,ats)
#Takes a .gro file and returns a 1d list of positions. If the gro file format changes, this will break
def readGro(fName):
with open(fName, 'r') as myF:
myLns = myF.read().splitlines()
boxL1 = float(myLns[len(myLns)-1].split()[0])
boxL2 = float(myLns[len(myLns)-1].split()[1])
boxL3 = float(myLns[len(myLns)-1].split()[2])
return (np.array([[float(myLns[i][20:].split()[0]), float(myLns[i][20:].split()[1]), float(myLns[i][20:].split()[2])] for i in range(2, len(myLns)-1)]).flatten(),np.array([boxL1,boxL2,boxL3]))
#Takes a 1d list of positions, a filename, and box vectors and writes out a gro file
#molStructure is a list defining the name,type, and number of each atom (assume all molecules are the same)
def writeGro(snapno,poslist,boxV,qbools,molStructureQ=["1PAQ","BB","1PAQ","SC1","2PHE","BB","2PHE","SC1","2PHE","SC2","2PHE","SC3","3ALA","BB","4GLY","BB","5COA","BB","6COP","BB","6COP","SC1","6COP","BB","7VIN","BB","8BEN","BB","8BEN","SC1","8BEN","BB","9VIN","BB","10COA","BB","11COP","BB","11COP","SC1","11COP","BB","12GLY","BB","13ALA","BB","14PHE","BB","14PHE","SC1","14PHE","SC2","14PHE","SC3","15PAQ","BB","15PAQ","SC1"],molStructure=["1PAS","BB","1PAS","SC1","2PHE","BB","2PHE","SC1","2PHE","SC2","2PHE","SC3","3ALA","BB","4GLY","BB","5COA","BB","6COP","BB","6COP","SC1","6COP","BB","7VIN","BB","8BEN","BB","8BEN","SC1","8BEN","BB","9VIN","BB","10COA","BB","11COP","BB","11COP","SC1","11COP","BB","12GLY","BB","13ALA","BB","14PHE","BB","14PHE","SC1","14PHE","SC2","14PHE","SC3","15PAS","BB","15PAS","SC1"]
):
atomno = len(molStructure)/2
molno = len(poslist)/(3*atomno)
qno = int(np.sum(qbools))
nqno = int(molno-qno)
fName = 'Q'+str(qno)+'NQ'+str(nqno)+'mer_'+str(snapno)+'.gro'
tName = 'Q'+str(qno)+'NQ'+str(nqno)+'mer_'+str(snapno)+'.top'
t = open(tName,'w')
t.write("#include \"martini.itp\"\n")
t.write("#include \"Protein.itp\"\n")
t.write("#include \"Protein_NP.itp\"\n")
t.write("[ system ]\n\n")
t.write(";name\n")
t.write("Martini system for k-mer library\n\n")
t.write("[ molecules ]\n\n")
t.write(";name\tnumber\n")
t.write("Protein\t{}\n".format(nqno))
t.write("ProteinQ\t{}\n".format(qno))
t.close()
f = open(fName,'w')
f.write("This is a k-mer library file\n")
f.write(str(len(poslist)/3)+"\n")
#print atomno
#print molno
#print np.size(poslist)
atomind = 1
for m in range(molno):
for a in range(atomno):
pos = poslist[3*m*atomno+3*a:3*m*atomno+3*a+3]
if qbools[m]:
aname = molStructureQ[2*(a % atomno)]
else:
aname = molStructure[2*(a % atomno)]
atype = molStructure[2*(a % atomno)+1]
#ano = molStructure[2*(a % atomno)+2]
#print pos
line = "%8s%7s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f" % (aname,atype,atomind,pos[0],pos[1],pos[2],0.0,0.0,0.0)
f.write(line+"\n")
atomind+=1
boxline = "%f %f %f \n" % (boxV[0],boxV[1],boxV[2])
f.write(boxline)
f.close()
#Gets the positions of all atoms in trajectory trj, run from tpr file tpr, at time t, written to output gro file outGro.
def getPos(t, trj, tpr, outGro):
os.system('echo 0 | trjconv -f ' + trj + ' -o ' + outGro + ' -b ' + str(t) + ' -e ' + str(t) + ' -s ' + tpr)
return readGro(outGro)[0]
#same as before except also returns box-length variable
def getPosB(t,trj,tpr,outGro):
#os.system('echo 0 | trjconv -f ' + trj + ' -o ' + outGro + ' -b ' + str(t) + ' -e ' + str(t) + ' -s ' + tpr)
p1 = subprocess.Popen(["trjconv","-f",trj,"-o",outGro,"-b",str(t),"-e",str(t),"-s",tpr],stdin = subprocess.PIPE)
p1.communicate("0")
return readGro(outGro)
#same as before except assumes it's given a grofile
def getPosGro(groname):
return readGro(groname)
#same as before except assumes we have the .gro files already
def getPosB2(ind, grobase):
return readGro(grobase + str(ind) + '.gro')
#same as before except also returns box-length variable and makes whole pbcs
def getPosBWhole(t,trj,tpr,outGro):
os.system('echo 0 | trjconv -f ' + trj + ' -o ' + outGro + ' -b ' + str(t) + ' -e ' + str(t) + ' -s ' + tpr + ' -pbc whole')
return readGro(outGro)
#Gets the neighbors of atom ind from a list of potential indices potentialInds (each of which are indices of the list of all peptides listed in peplist). Being neighbors is defined as two peptides having any two atoms separated by less than cutoff. ats is the number of atoms per peptide in peplist. Summary: ind: index to check, cutoff: distance that defines neighbors (as separation of any two atoms), peplist: list of all atoms, potentialInds: potential neighbors, ats: atoms per peptide.
def getNeigh(ind, cutoff, peplist, potentialInds, ats):
ret = []
cutsq = cutoff**2
support = '#include <math.h>'
code = """
int i, j;
return_val = 0;
for(i=0; i<Npep1[0]/3; i++){
for(j=0; j<Npep2[0]/3; j++){
if ((pow(pep1[3*i]-pep2[3*j],2) + pow(pep1[3*i+1]-pep2[3*j+1],2) + pow(pep1[3*i+2]-pep2[3*j+2],2)) < cutsq){
return_val = 1;
break;
}
}
if(return_val == 1)
break;
}
"""
pep1 = peplist[ind*3*ats:(ind+1)*3*ats] #Assumes all peptides have ats atoms in them. The 3 is for 3 coords in 3 dimensions.
for i in range(len(potentialInds)):
pep2 = peplist[potentialInds[i]*3*ats:(potentialInds[i]+1)*3*ats]
test = weave.inline(code,['pep1', 'pep2', 'cutsq'], support_code = support, libraries = ['m'])
if test == 1:
ret.append(potentialInds[i])
return ret
#Gets the neighbors of atom ind from a list of potential indices potentialInds (each of which are indices of the list of all peptides listed in peplist). Being neighbors is defined as two peptides having any two atoms separated by less than cutoff. ats is the number of atoms per peptide in peplist. Summary: ind: index to check, cutoff: distance that defines neighbors (as separation of any two atoms), peplist: list of all atoms, potentialInds: potential neighbors, ats: atoms per peptide. This version assumes periodic boundary conditions
def getNeighPBC(ind, cutoff, peplist, potentialInds, ats,boxlx,boxly,boxlz):
ret = []
cutsq = cutoff**2
support = '#include <math.h>'
code = """
int i, j;
return_val = 0;
double x,y,z;
for(i=0; i<Npep1[0]/3; i++){
for(j=0; j<Npep2[0]/3; j++){
x = pep1[3*i]-pep2[3*j];
y = pep1[3*i+1]-pep2[3*j+1];
z = pep1[3*i+2]-pep2[3*j+2];
x = x - ((double) boxlx)*round(x/((double) boxlx));
y = y - ((double) boxly)*round(y/((double) boxly));
z = z - ((double) boxlz)*round(z/((double) boxlz));
if (x*x + y*y + z*z < cutsq){
return_val = 1;
break;
}
}
if(return_val == 1)
break;
}
"""
pep1 = peplist[ind*3*ats:(ind+1)*3*ats] #Assumes all peptides have ats atoms in them. The 3 is for 3 coords in 3 dimensions.
for i in range(len(potentialInds)):
pep2 = peplist[potentialInds[i]*3*ats:(potentialInds[i]+1)*3*ats]
test = weave.inline(code,['pep1', 'pep2', 'cutsq','boxlx','boxly','boxlz'], support_code = support, libraries = ['m'])
if test == 1:
ret.append(potentialInds[i])
return ret
#Returns an array of arrays. Each inner array is a list of peptide indices that are in the same cluster. A cluster is defined as the largest list of molecules for which each molecule in the list is neighbors either directly or indirectly (neighbors of neighbors of neighbors etc...) neighbors with each other molecule. ind is the atom to check the cluster of, cutoff is the minimum distance that defines neighbors, peplist is a list of all atoms in the simulation, potentialInds is the list of indices that could possibly be neighbors with ind, ats is the number of atoms per peptide (this is important for dividing up pepList and must be constant for all peptides in pepList), and printMe is a boolean that will cause the immediate neighbors of ind to be printed if it is true (more for debuging and checking things).
def getClust(ind, cutoff, pepList, potentialInds, ats, printMe):
#start = time.clock()
neighInds = getNeigh(ind, cutoff, pepList, potentialInds, ats)
if printMe:
print("Neighbors of " + str(ind) + " are found to have indices of: ")
print(neighInds)
for neighInd in neighInds:
potentialInds.remove(neighInd)
for neighInd in neighInds:
vals = getClust(neighInd, cutoff, pepList, potentialInds, ats, printMe)
if len(vals) > 0:
neighInds += vals
#end = time.clock();
#print end - start;
return neighInds
#Returns an array of arrays. Each inner array is a list of peptide indices that are in the same cluster. A cluster is defined as the largest list of molecules for which each molecule in the list is neighbors either directly or indirectly (neighbors of neighbors of neighbors etc...) neighbors with each other molecule. ind is the atom to check the cluster of, cutoff is the minimum distance that defines neighbors, peplist is a list of all atoms in the simulation, potentialInds is the list of indices that could possibly be neighbors with ind, ats is the number of atoms per peptide (this is important for dividing up pepList and must be constant for all peptides in pepList), and printMe is a boolean that will cause the immediate neighbors of ind to be printed if it is true (more for debuging and checking things).
def getClustTest(ind, cutoff, pepList, potentialInds, ats, printMe):
#start = time.clock()
neighInds = getNeighTest(ind, cutoff, pepList, potentialInds, ats)
if printMe:
print("Neighbors of " + str(ind) + " are found to have indices of: ")
print(neighInds)
for neighInd in neighInds:
potentialInds.remove(neighInd)
if ind == 3:
2
for neighInd in neighInds:
vals = getClustTest(neighInd, cutoff, pepList, potentialInds, ats, printMe)
if len(vals) > 0:
neighInds += vals
#end = time.clock();
#print end - start;
return neighInds
def getNeighTest(ind, cutoff, peplist, potentialInds, ats):
ret = []
cutsq = cutoff
# support = '#include <math.h>'
#
# code = """
#
# int i, j;
# return_val = 0;
# for(i=0; i<Npep1[0]/3; i++){
# for(j=0; j<Npep2[0]/3; j++){
# if ((pow(pep1[3*i]-pep2[3*j],2) + pow(pep1[3*i+1]-pep2[3*j+1],2) + pow(pep1[3*i+2]-pep2[3*j+2],2)) < cutsq){
# return_val = 1;
# break;
# }
# }
# if(return_val == 1)
# break;
# }
# """
# pep1 = peplist[ind*3*ats:(ind+1)*3*ats] #Assumes all peptides have ats atoms in them. The 3 is for 3 coords in 3 dimensions.
# for i in range(len(potentialInds)):
# pep2 = peplist[potentialInds[i]*3*ats:(potentialInds[i]+1)*3*ats]
# test = weave.inline(code,['pep1', 'pep2', 'cutsq'], support_code = support, libraries = ['m'])
# if test == 1:
# ret.append(potentialInds[i])
for p in potentialInds:
d = abs(peplist[ind]-peplist[p])
if d < cutsq:
ret.append(p)
return ret
#Returns an array of arrays. Each inner array is a list of peptide indices that are in the same cluster. A cluster is defined as the largest list of molecules for which each molecule in the list is neighbors either directly or indirectly (neighbors of neighbors of neighbors etc...) neighbors with each other molecule. ind is the atom to check the cluster of, cutoff is the minimum distance that defines neighbors, peplist is a list of all atoms in the simulation, potentialInds is the list of indices that could possibly be neighbors with ind, ats is the number of atoms per peptide (this is important for dividing up pepList and must be constant for all peptides in pepList), and printMe is a boolean that will cause the immediate neighbors of ind to be printed if it is true (more for debuging and checking things). Assumes PBC
def getClustPBC(ind, cutoff, pepList, potentialInds, ats, boxlx,boxly,boxlz,printMe):
#start = time.clock()
neighInds = getNeighPBC(ind, cutoff, pepList, potentialInds, ats,boxlx,boxly,boxlz)
if printMe:
print("Neighbors of " + str(ind) + " are found to have indices of: ")
print(neighInds)
for neighInd in neighInds:
potentialInds.remove(neighInd)
for neighInd in neighInds:
vals = getClust(neighInd, cutoff, pepList, potentialInds, ats, printMe)
if len(vals) > 0:
neighInds += vals
#end = time.clock();
#print end - start;
return neighInds
#Returns a numpy array with the cluster size that each peptide is part of (eg. [2, 2, 3, 3, 1, 3, ...] means peptides 0 and 1 are part of dimers, peptides 2, 3, and 5 are part of trimers, peptide 4 is a monomer, etc...). t is the time frame of trajectory xtc to look at from run tpr, outgro is the temporary gro file to write to when getting atom positions, cutoff is the minimum distance between two atoms in a peptide to define the peptides as being part of the same cluster, and ats is the number of atoms in a peptide.
def sizeprof(t, xtc, tpr, outgro, cutoff, ats):
peps = getPos(t, xtc, tpr, outgro)
os.system('rm ' + outgro)
pots = range(len(peps)/3/ats)
sizes = np.zeros(len(peps)/3/ats)
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clust = getClust(init, cutoff, peps, pots, ats, False) + [init]
for at in clust:
sizes[at] = len(clust)
return sizes
def clustInds(t,xtc,tpr,outgro,cutoff,ats,rm=True):
#return the index of which clusters each peptide is in
#start = time.clock();
peps = getPos(t,xtc,tpr,outgro)
if rm:
os.system('rm '+outgro)
pots = range(len(peps)/3/ats)
inds = np.zeros(len(peps)/3/ats)
ind = 1
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClust(init,cutoff,peps,pots,ats,False) + [init]
for clust in clusts:
inds[clust] = ind
ind+=1
#end = time.clock()
#t = end - start
#print "time: ", t
return inds
def hydroRadClust(t,xtc,tpr,outgro,cutoff,ats,rm=True):
#find and return the hydrodynamic radii of all clusters at some timestep t
Rhs = np.array([])
(peps,box_length) = getPosB(t,xtc,tpr,outgro)
if rm:
os.system('rm '+outgro)
pots = range(len(peps)/3/ats)
inds = np.zeros(len(peps)/3/ats)
ind = 1
eigvals = np.array([])
eigvecs = np.array([])
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClust(init,cutoff,peps,pots,ats,False) + [init]
#clusts is a list of peptides that are found in the cluster
#each index in clusts corresponds to the indices index*ats*3:(index+1)*ats*3 in peps
pepList = np.zeros(len(clusts)*ats*3)
curr = 0
for clust in clusts:
inds[clust] = ind
pepList[curr*ats*3:(curr+1)*ats*3]=peps[clust*ats*3:(clust+1)*ats*3]
curr+=1
Rh = hydroRad(pepList)
Rhs = np.append(Rhs,Rh)
return Rhs
def writeClustLibrary(t,xtc,tpr,outgro,cutoff,ats,molStruct,resInfo,rm=True):
#write out a library of .gro files of clusters
(peps,box_length,qbool) = getPosQ(t,xtc,tpr,outgro,resInfo,ats)
if rm:
os.system('rm '+outgro)
pots = range(len(peps)/3/ats)
inds = np.zeros(len(peps)/3/ats)
ind = 1
clustinds = {}
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClustPBC(init,cutoff,peps,pots,ats,box_length[0],box_length[1],box_length[2],False) + [init]
#clusts is a list of peptides that are found in the cluster
#each index in clusts corresponds to the indices index*ats*3:(index+1)*ats*3 in peps
pepList = np.zeros(len(clusts)*ats*3)
qboolc = np.zeros(len(clusts))
curr = 0
for clust in clusts:
pepList[curr*ats*3:(curr+1)*ats*3]=peps[clust*ats*3:(clust+1)*ats*3]
qboolc[curr] = qbool[clust]
curr+=1
pepList = fixPBC(pepList,box_length,ats,cutoff)
mer = len(clusts)
if mer in clustinds:
clustinds[mer]+=1
else:
clustinds[mer] = 1
writeGro(clustinds[mer],pepList,box_length,qboolc)
#use the aromarecluster file which has group index and peptide index in it, to put together a list of clusters as defined in that file and then write those clusters out separately like writeClustLibrary
def writeSubClusterLibrary(aromaFile,t,xtc,tpr,outgro,resInfo,ats,cutoff):
a = open(aromaFile,'r')
lines = a.readline()
a.close()
clusters = dict()
for line in lines:
spline = line.split()
ind = int(spline[1])
pepind = int(spline[30])
if clusters.has_key(ind):
j[ind].append(pepind)
else:
clusters[ind] = [pepind]
(peps,box_length,qbool) = getPosQ(t,xtc,tpr,outgro,resInfo,ats)
for key in clusters.keys():
clustinds = clusters[key]
pepList = np.zeros(3*len(clustinds))
for c in range(len(clustinds)):
pepList[3*c:(3*c+3)] = peps[3*clustinds[c]:(3*clustinds[c]+3)]
pepList = fixPBC(pepList,box_length,ats,cutoff)
def clustMakeup(distrib,nmols):
#given a distribution of cluster sizes, output a list consisting of numbers of k-mers of up to nmols that fits the distribution reasonably well but also the correct number of molecules
#let distrib be a numpy array
nclusts = 0.0
for i in range(len(distrib)):
nclusts += distrib[i]*i
nclusts = nmols/nclusts
ndistrib = np.zeros(np.size(distrib))
for i in range(len(ndistrib)):
ndistrib[i] = round(distrib[i]*nclusts)
nmols = 0
nclusts = 0
print ndistrib
for i in range(len(ndistrib)):
nmols += (i+1)*ndistrib[i]
nclusts += ndistrib[i]
return (ndistrib,nmols,nclusts)
def prepInitConds(distrib,nmols,libraryns,boxsize):
#given a desired distribution of k-mers and a desired number of molecules, prepares a (non-solvated) .gro file with k-mers using library files
#libraryns is a list of how many configurations are available for k-mers as library files
(ndistrib,nmols,nclusts) = clustMakeup(distrib,nmols)
#os.system('echo 0 | trjconv -f ' + trj + ' -o ' + outGro + ' -b ' + str(t) + ' -e ' + str(t) + ' -s ' + tpr)
#cmd = 'export GMX_MAXBACKUP=-1'
#e1 = subprocess.Popen(cmd,stdout=subprocess.PIPE)
#e1.wait()
ind = 0
print "nmols is ", nmols
for k in range(len(ndistrib)-1,-1,-1):
n = ndistrib[k]
for i in range(int(n)):
#randomly choose library file
#call gromacs to insert it into box
nfiles = libraryns[k]
filei = random.randint(1,nfiles)
fnamei = str(k+1)+"mer_"+str(filei)+".gro"
f = open("confs.gro","w")
if ( (k==4) and (i==0)):
#call editconf
command = ['editconf','-f',fnamei,'-o','init_'+str(ind)+'.gro','-bt','triclinic','-box',str(boxsize[0]),str(boxsize[1]),str(boxsize[2])]
p = subprocess.call(command)
#(outdata,errdata) = p.communicate()
ind+=1
f.write("configuration "+fnamei)
else:
tries = 200
trying=-1
while trying==-1:
#call genconf
f.write("configuration "+fnamei)
#print "trying ",tries
#f = open("temp.txt","w")
command = ['genbox','-cp','init_'+str(ind-1)+'.gro','-o','init_'+str(ind)+'.gro','-ci',fnamei,'-nmol','1','-try',str(tries)]
p = subprocess.call(command)
#(outdata,errdata) = p.communicate()
#p.wait()
#f.close()
#f2 = open("temp.txt","r")
#outdata = f2.read()
#trying = outdata.find('Added 1 molecules')
#f2.close()
#tries+=20
ind+=1
trying = 1
#print "START: ",outdata
#print "END: ",errdata
f.close()
for j in range(ind-1):
os.system('rm init_'+str(j)+'.gro')
#cmd = 'export GMX_MAXBACKUP=99'
#e2 = subprocess.Popen(cmd,stdout=subprocess.PIPE)
#e2.wait()
#print "under construction"
def aromaCross(arom,molInds,posList,boxL):
b11 = molInds[arom[0]*3:arom[0]*3+3]
b12 = molInds[arom[1]*3:arom[1]*3+3]
b13 = molInds[arom[2]*3:arom[2]*3+3]
b11p = posList[b11]
b12p = posList[b12]
b13p = posList[b13]
db1 = b13p - b12p
db2 = b12p - b11p
for i in range(3):
db1[i] = db1[i] - boxL[i]*round(db1[i]/boxL[i])
db2[i] = db2[i] - boxL[i]*round(db2[i]/boxL[i])
aromaPlane = np.cross(db1,db2)
return aromaPlane
def aromaticData(posList,ats,beadList,beadMasses,aromBeads,aromMass,boxLs):
#characterize the COM location and orientation of the aromatic rings in the backbone (beads 10, 11, 12, 13, 14, 15, 16, 17, 21, 20, 19 for DFAG)
#right now assumes molecules have been made whole and that there are three aromatic rings in the backbone that we are being given
#orient is the two vectors pointing from the first to the second aromatic ring and from the second to the third
#also return the three vectors of the planes of the aromatic rings as aromaPlanes
N = int(len(posList)/3) #number of atoms
nmols = N/ats
comsPBC = np.zeros([nmols,3])
orients = np.zeros([nmols,6])
aromaPlanes = np.zeros([nmols,9])
#loop over each group of aromatic rings and calculate COM and orient
#molinds = indices of each molecule: 0:3*ats-1, 3*ats:2(3*ats)-1,...,(N-1)(3*ats):N(3*ats)-1
#indices of each aromatic group: molinds[3*beadList:3*beadList+2]
for i in range(nmols):
molInds = range(i*(3*ats),(i+1)*(3*ats))
#aromInds = molinds[3*beadList:3*beadList+2]
#endInds = molinds[3*endList:3*endList+2]
comPBC = np.array([0.0,0.0,0.0])
M = 0.0
j = 0
beadInd0 = molInds[beadList[0]*3:beadList[0]*3+3]
b0 = posList[beadInd0]
#print "b0 ",b0
m0 = beadMasses[0]
for bead in beadList:
beadInds = molInds[bead*3:bead*3+3]
b = posList[beadInds]
m = beadMasses[j]
j+=1
db = b - b0
db = db - boxLs * np.round(db/boxLs)
comPBC += m*db
M+=m
comPBC = comPBC/M + b0
arom1 = aromBeads[0:3]
arom2 = aromBeads[3:6]
arom3 = aromBeads[6:9]
coma1 = np.array([0.0,0.0,0.0])
coma2 = np.array([0.0,0.0,0.0])
coma3 = np.array([0.0,0.0,0.0])
coma1 = aromaCOM(arom1,posList,aromMass[0:3],molInds,boxLs)
coma2 = aromaCOM(arom2,posList,aromMass[3:6],molInds,boxLs)
coma3 = aromaCOM(arom3,posList,aromMass[6:9],molInds,boxLs)
aromaPlane1 = aromaCross(arom1,molInds,posList,boxLs)
aromaPlane2 = aromaCross(arom2,molInds,posList,boxLs)
aromaPlane3 = aromaCross(arom3,molInds,posList,boxLs)
#normalize vectors
aromaPlane1 = aromaPlane1/np.sqrt(sum(aromaPlane1**2))
aromaPlane2 = aromaPlane2/np.sqrt(sum(aromaPlane2**2))
aromaPlane3 = aromaPlane3/np.sqrt(sum(aromaPlane3**2))
comaa = coma3 - coma2
comaa = comaa - boxLs*np.round(comaa/boxLs)
comab = coma2 - coma1
comab = comab - boxLs*np.round(comab/boxLs)
orient = np.concatenate((comaa,comab),axis=0)
#put comPBC inside box if it isn't
#print "comPBC is ",comPBC
comPBC = inBox(comPBC,boxLs)
#print "comPBC is now ",comPBC
comsPBC[i,:] = comPBC
orients[i,:] = orient
aromaPlanes[i,:] = np.concatenate((aromaPlane1,aromaPlane2,aromaPlane3),axis=0)
return (comsPBC,orients,aromaPlanes)
def inBox(r,boxLs):
for i in range(3):
r[i] = r[i] - boxLs[i]*((int(r[i])/int(boxLs[i])))
return r
def aromaCOM(arom,posList,aromMass,molInds,boxL):
b0 = molInds[arom[0]*3:arom[0]*3+3]
b0p = posList[b0]
b1 = molInds[arom[1]*3:arom[1]*3+3]
b1p = posList[b1]
b2 = molInds[arom[2]*3:arom[2]*3+3]
b2p = posList[b2]
db1 = b1p - b0p
db2 = b2p - b0p
#print db1
#print db2
#print boxL
db1 = db1 - boxL*np.round(db1/boxL)
db2 = db2 - boxL*np.round(db2/boxL)
coma = (aromMass[1]*db1 + aromMass[2]*db2)/(aromMass[0]+aromMass[1]+aromMass[2]) + b0p
return coma
def aromaticSnap(infname,cutoff,ats,beadList,beadMasses,aromBeads,aromMass):
(peps,box_length) = getPosGro(infname)
pots = range(len(peps)/3/ats)
inds = np.zeros(len(peps)/3/ats)
ind = 1
achars = np.empty((0,30),float)
cNum = 0
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClust(init,cutoff,peps,pots,ats,False) + [init]
#clusts is a list of peptides that are found in the cluster
#each index in clusts corresponds to the indices index*ats*3:(index+1)*ats*3 in peps
pepList = np.zeros(len(clusts)*ats*3)
curr = 0
#mass = len(clusts);
for clust in clusts:
pepList[curr*ats*3:(curr+1)*ats*3]=peps[clust*ats*3:(clust+1)*ats*3]
curr+=1
(coms,orients,aromaPlanes,aromaCOMs) = aromaticDataC(pepList,ats,beadList,beadMasses,aromBeads,aromMass,box_length)
cNums = cNum*np.ones([len(coms),1])
cSizes = len(clusts)*np.ones([len(coms),1])
clustList = np.array(clusts)
clustList = np.reshape(clustList,[len(coms),1])
try:
adata = np.concatenate((cNums,cSizes,coms,orients,aromaPlanes,aromaCOMs,clustList),axis=1)
achars = np.concatenate((achars,adata),axis=0)
except:
np.shape(clustList)
cNum+=1
return achars
def getCOM(poslist,masslist):
#return com coordinates of a single molecule
com = np.zeros(3)
N = len(poslist)
support = '#include <math.h>'
code = """
double M = 0.0;
double rx = 0.0;
double ry = 0.0;
double rz = 0.0;
for (int i = 0; i < N/3; i++){
rx += double(masslist[i])*double(poslist[3*i]);
ry += double(masslist[i])*double(poslist[3*i+1]);
rz += double(masslist[i])*double(poslist[3*i+2]);
M += double(masslist[i]);
}
rx /= M;
ry /= M;
rz /= M;
com[0] = rx;
com[1] = ry;
com[2] = rz;
"""
weave.inline(code,['poslist','N','com','masslist'],support_code = support,libraries=['m'])
return com
def getCOMpy(poslist,masslist):
#return com coordinates of a single molecule, written in python
N = len(poslist)
com = np.zeros(3)
rx = 0.
ry = 0.
rz = 0.
for i in range(N/3):
rx += masslist[i]*poslist[3*i]
ry += masslist[i]*poslist[3*i+1]
rz += masslist[i]*poslist[3*i+2]
M = np.sum(masslist)
rx /= M
ry /= M
rz /= M
com[0] = rx
com[1] = ry
com[2] = rz
return com
def getCOMnumpy(poslist,masslist):
#return com coordinates of a single molecule, written in python using numpy
poslist3 = poslist.reshape([len(poslist)/3,3])
com = np.dot(masslist,poslist3)/masslist.sum()
return com
def getCOMs(poslist,masslist,ats):
#return the center of mass of each molecule in a position list of peptides
N = len(poslist)/3/ats #total number of molecules
comlocs = np.zeros(3*N)
for i in range(N):
Rcom = getCOM(poslist[3*ats*i:3*ats*i+3*ats],masslist)
comlocs[3*i:3*i+3] = Rcom
return comlocs
'''
def getCOMsWRONG(poslist,masslist,ats):
#return the center of mass of each molecule in a position list of peptides
N = len(poslist)/3/ats #total number of molecules
comlocs = np.zeros(3*N)
for i in range(N):
Rcom = getCOMWRONG(poslist[3*ats*i:3*ats*i+3*ats],masslist)
comlocs[3*i:3*i+3] = Rcom
return comlocs
def getCOMspy(poslist,masslist,ats):
#return the center of mass of each molecule in a position list of peptides
N = len(poslist)/3/ats #total number of molecules
comlocs = np.zeros(3*N)
for i in range(N):
Rcom = getCOMpy(poslist[3*ats*i:3*ats*i+3*ats],masslist)
comlocs[3*i:3*i+3] = Rcom
return comlocs
def getCOMsnumpy(poslist,masslist,ats):
#return the center of mass of each molecule in a position list of peptides
N = len(poslist)/3/ats #total number of molecules
comlocs = np.zeros(3*N)
for i in range(N):
Rcom = getCOMnumpy(poslist[3*ats*i:3*ats*i+3*ats],masslist)
comlocs[3*i:3*i+3] = Rcom
return comlocs
'''
def corrDim(comsnap,emax,estep):
#calculate C(eps) from 0 to emax with steps of estep, where C(eps) is
#the correlation sum on the set of center-of-mass distances given as comsnap
distsq = spsd.pdist(comsnap,'sqeuclidean')
epss = np.arange(estep,emax+estep,estep)
ce = np.zeros(len(epss))
support = '#include <math.h>'
code = """
for (int i = 0; i < Ndistsq[0]; i++){
for (int k = 0; k < Nepss[0]; k++){
if (distsq[i] <= epss[k]*epss[k]){
ce[k]++;
}
}
}
"""
weave.inline(code,['emax','estep','distsq','ce','epss'],support_code=support,libraries=['m'])
N = len(comsnap)
ce = ce/(N*(N-1))
# for i in range(Ndsq):
#
# for k in range(len(epss)):
# if distsq[i] < epss[k]*epss[k]:
# ce[k]+=1
return (epss,ce)
def corrDimP(comsnap,emax,estep):
#calculate C(eps) from 0 to emax with steps of estep, where C(eps) is
#the correlation sum on the set of center-of-mass distances given as comsnap
distsq = spsd.pdist(comsnap,'sqeuclidean')
epss = np.arange(estep,emax+estep,estep)
ce = np.zeros(len(epss))
#support = '#include <math.h>'
#code =
"""
for (int i = 0; i < Ndistsq[0]; i++){
for (int k = 0; k < Nepss[0]; k++){
if (distsq[i] <= epss[k]*epss[k]){
ce[k]++;
}
}
}
"""
# weave.inline(code,['emax','estep','distsq','ce','epss'],support_code=support,libraries=['m'])
N = len(comsnap)
ce = ce/(N*(N-1))
for i in range(len(distsq)):
for k in range(len(epss)):
if distsq[i] <= epss[k]*epss[k]:
ce[k]+=1
return (epss,ce)
def corrcalc(t,xtc,tpr,outgro,ats,emax,estep,masslist,fnbase,rm=True):
#first calculate and write out the C(e) function for a full snapshot
(peps,box_length) = getPosB(t,xtc,tpr,outgro)
if rm:
os.system('rm '+outgro)
comsnap = getCOMs(peps,masslist,ats) #get the center of mass locations of the molecules in the box
comsnapr = comsnap.reshape([len(comsnap)/3,3])
(epsnap,cdsnap) = corrDim(comsnapr,emax,estep) #get a matrix of e in row 1 and C(e) in row 2
f = open(fnbase+'_'+str(t/1000)+'_snap.dat','w')
for i in range(len(cdsnap)):
f.write('{0}\t{1}\n'.format(epsnap[i],cdsnap[i]))
f.close()
def corrcalcClust(t,xtc,tpr,outgro,ats,emax,estep,masslist,fnbase,cutoff,rm=True):
#then calculate and write out the C(e) function for each cluster
(peps,box_length) = getPosB(t,xtc,tpr,outgro)
#print box_length
if rm:
os.system('rm '+outgro)
pots = range(len(peps)/3/ats)
ind = 0
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClust(init,cutoff,peps,pots,ats,False) + [init]
#clusts is a list of peptides that are found in the cluster
#each index in clusts corresponds to the indices index*ats*3:(index+1)*ats*3 in peps
pepList = np.zeros(len(clusts)*ats*3)
curr = 0
#mass = len(clusts);
for clust in clusts:
pepList[curr*ats*3:(curr+1)*ats*3]=peps[clust*ats*3:(clust+1)*ats*3]
curr+=1
pepList = fixPBC(pepList,box_length,ats,cutoff)
#if len(pepList)/3/ats == 1:
# print "help"
pepcoms = getCOMs(pepList,masslist,ats)
pepcomsr = pepcoms.reshape([len(pepcoms)/3,3])
(epc,cdc) = corrDim(pepcomsr,emax,estep)
f = open(fnbase+'_'+str(t/1000)+'_'+str(len(pepList)/3/ats)+'_c_'+str(ind)+'.dat','w')
for i in range(len(cdc)):
f.write('{0}\t{1}\n'.format(epc[i],cdc[i]))
f.close()
ind+=1
def testcorrcalc(infile,outfile,emax,estep):
#make sure corrcalc does the same thing that Jiang's test code does
f = open(infile)
lines = f.readlines()
f.close()
comsnap = np.zeros([len(lines),3])
l = 0
for line in lines:
spline = line.split()
comsnap[l,0] = float(spline[0])
comsnap[l,1] = float(spline[1])
comsnap[l,2] = float(spline[2])
l+=1
(epstest,cdtest) = corrDim(comsnap,emax,estep)
o = open(outfile,'w')
for i in range(len(cdtest)):
o.write('{0}\t{1}\n'.format(epstest[i],cdtest[i]))
o.close()
def aromaticClust(t,xtc,tpr,outgro,cutoff,ats,beadList,beadMasses,aromBeads,aromMass,rm=True):
(peps,box_length) = getPosB(t,xtc,tpr,outgro)
#print box_length
if rm:
os.system('rm '+outgro)
pots = range(len(peps)/3/ats)
inds = np.zeros(len(peps)/3/ats)
ind = 1
achars = np.empty((0,30),float)
cNum = 0
while len(pots) > 0:
init = pots[0]
pots.remove(init)
clusts = getClust(init,cutoff,peps,pots,ats,False) + [init]
#clusts is a list of peptides that are found in the cluster
#each index in clusts corresponds to the indices index*ats*3:(index+1)*ats*3 in peps
pepList = np.zeros(len(clusts)*ats*3)
curr = 0
#mass = len(clusts);
for clust in clusts:
pepList[curr*ats*3:(curr+1)*ats*3]=peps[clust*ats*3:(clust+1)*ats*3]
curr+=1
(coms,orients,aromaPlanes,aromaCOMs) = aromaticDataC(pepList,ats,beadList,beadMasses,aromBeads,aromMass,box_length)
cNums = cNum*np.ones([len(coms),1])
cSizes = len(clusts)*np.ones([len(coms),1])
clustList = np.array(clusts)
clustList = np.reshape(clustList,[len(coms),1])
try:
adata = np.concatenate((cNums,cSizes,coms,orients,aromaPlanes,aromaCOMs,clustList),axis=1)
achars = np.concatenate((achars,adata),axis=0)
except:
np.shape(clustList)
cNum+=1
return achars
def aromaticDataC(posList,ats,beadList,beadMasses,aromBeads,aromMass,boxLs):
coms = aromaticCOMC(posList,ats,beadList,beadMasses,boxLs)
(orients,aromaPlanes,aromaCOMs) = aromaticPlaneC(posList,ats,aromBeads,aromMass,boxLs)
return (coms,orients,aromaPlanes,aromaCOMs)
def aromaticCOMC(posList,ats,beadList,beadMasses,boxLs):
#characterize the COM location and orientation of the aromatic rings in the backbone (beads 10, 11, 12, 13, 14, 15, 16, 17, 21, 20, 19 for DFAG)
#right now assumes molecules have been made whole
N = int(len(posList)/3) #number of atoms
nmols = N/ats
coms = np.zeros(3*nmols)
#loop over each group of aromatic rings and calculate COM and orient
#molinds = indices of each molecule: 0:3*ats-1, 3*ats:2(3*ats)-1,...,(N-1)(3*ats):N(3*ats)-1
#indices of each aromatic group: molinds[3*beadList:3*beadList+2]
support = '#include <math.h>'
code = """
int * molInds;
molInds = (int *) malloc(sizeof(int)*3*ats);
double com [3];
com[0] = 0.0;
com[1] = 0.0;
com[2] = 0.0;
double M,bx,by,bz,m,m0,b0x,b0y,b0z,dbx,dby,dbz;
int bead,beadInd0x,beadInd0y,beadInd0z,beadIndx,beadIndy,beadIndz,end1x,end1y,end1z,end2x,end2y,end2z;
for (int i = 0; i < nmols; i++){
for (int k = 0; k < 3*ats; k++){
molInds[k] = i*3*ats+k;
}
for (int k = 0; k < 3; k++){
com[k] = 0.0;
}
M = 0.0;
beadInd0x = molInds[beadList[0]*3];
beadInd0y = molInds[beadList[0]*3+1];
beadInd0z = molInds[beadList[0]*3+2];
b0x = posList[beadInd0x];
b0y = posList[beadInd0y];
b0z = posList[beadInd0z];
for (int j = 0; j < NbeadList[0]; j++){
bead = beadList[j];
beadIndx = molInds[bead*3];
beadIndy = molInds[bead*3+1];
beadIndz = molInds[bead*3+2];
bx = posList[beadIndx];
by = posList[beadIndy];
bz = posList[beadIndz];
dbx = bx - b0x;
dby = by - b0y;
dbz = bz - b0z;
dbx = dbx - double(boxLs[0])*round(dbx/double(boxLs[0]));
dby = dby - double(boxLs[1])*round(dby/double(boxLs[1]));
dbz = dbz - double(boxLs[2])*round(dbz/double(boxLs[2]));
m = beadMasses[j];
com[0] += m*dbx;
com[1] += m*dby;
com[2] += m*dbz;
M+=m;
}
com[0] = com[0]/M+b0x;
com[1] = com[1]/M+b0y;
com[2] = com[2]/M+b0z;
coms[3*i] = com[0];
coms[3*i+1] = com[1];
coms[3*i+2] = com[2];
}
free(molInds);
"""
weave.inline(code,['posList','ats','nmols','beadList','beadMasses','coms','boxLs'],support_code = support,libraries=['m'])
coms = np.reshape(coms,[nmols,3])
return coms
def aromaticPlaneC(posList,ats,aromBeads,aromMass,boxLs):
N = int(len(posList)/3)
nmols = N/ats
orients = np.zeros(6*nmols)
aromaPlanes = np.zeros(9*nmols)
aromaCOMs = np.zeros(9*nmols)
support = '#include <math.h>'
code = """
int * molInds;
molInds = (int *) malloc(sizeof(int)*3*ats);
double orient [6];
for (int i = 0; i < 6; i++){
orient[i] = 0.0;
}
double comas [9];
int b0 [9];
int b1 [9];
int b2 [9];
double b0p [9];
double b1p [9];
double b2p [9];
double db1 [9];
double db2 [9];
double dc1 [9];
double dc2 [9];