-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdbanalysis.py
2661 lines (2484 loc) · 98.2 KB
/
pdbanalysis.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
from polypeptide import *
from sparc_distribution import *
import os, gc, time
from os.path import join
import numpy
import random
from scipy.stats import linregress
from scipy.spatial import ConvexHull
import planeregression as plreg
from functools import partial
import multiprocessing
import shutil, subprocess
#MARK: Aggregation and helpers
def aggregate_aadata(source, dest, two_d=True):
if not os.path.exists(dest): os.mkdir(dest)
contents = os.listdir(source)
def _aggregate_mid(ksource, ksources, kfile, kfileName):
for folder in ksources:
sourcePath = join(join(ksource, folder), kfileName)
if not os.path.exists(sourcePath): continue
sfile = open(sourcePath, 'r')
for line in sfile:
file.write(line)
sfile.close()
for i in xrange(AMINO_ACID_COUNT):
if two_d:
for j in xrange(AMINO_ACID_COUNT):
destPath = "%d-%d.txt" % (i, j)
file = open(join(dest, destPath), 'w')
_aggregate_mid(source, contents, file, destPath)
file.close()
print "Saved %r to file" % destPath
else:
destPath = "%d.txt" % i
file = open(join(dest, destPath), 'w')
_aggregate_mid(source, contents, file, destPath)
file.close()
print "Saved %r to file" % destPath
def read_alpha_zones(file):
pzs = []
for line in file:
if not len(line.strip()) or ";" not in line: continue
(x, y, z) = line.split(";")[0].split(",")
pzs.append(Point3D(x, y, z))
return pzs
def read_positional_zones(file, azone=Point3D.zero()):
pzs = []
file.seek(0)
for line in file:
i = 0
zp = PositionZone()
for pointstr in line.split(";"):
try:
(x, y, z) = pointstr.split(",")
if i == 0:
zp.alpha_zone = Point3D(x, y, z)
if azone != Point3D.zero() and zp.alpha_zone != azone:
i = -1
break
elif i == 1: zp.x_axis = Point3D(x, y, z)
elif i == 2: zp.y_axis = Point3D(x, y, z)
elif i == 3: zp.z_axis = Point3D(x, y, z)
else: assert False, "More components than necessary: %r" % line
except ValueError:
print "Exception for", pointstr
i += 1
if i != -1: pzs.append(zp); zp.hash = zp.calchash()
return pzs
def read_axis_zones(file, freqdata, azones, axis=0):
"""Provide 0 for x-axis, 1 for y-axis, 2 for z-axis. Returns a list of points."""
file.seek(0)
for z in azones:
if z not in freqdata: freqdata[z] = {}
for line in file:
try:
comps = line.split(";")
if len(comps) < 4: continue
(x, y, z) = comps[0].split(",")
azone = Point3D(x, y, z)
if azone not in azones: continue
if axis == 0:
(x1, y1, z1) = comps[1].split(",")
elif axis == 1:
(x1, y1, z1) = comps[2].split(",")
elif axis == 2:
(x1, y1, z1) = comps[3].split(",")
else: assert False, "Invalid axis number (must be 0, 1, or 2): %d" % axis
pz = Point3D(x1, y1, z1)
if pz in freqdata[azone]: freqdata[azone][pz] += 1
else: freqdata[azone][pz] = 1
except ValueError:
print "Exception for", pointstr
def read_alpha_frequencies(file):
"""Reads out the alpha frequencies and returns them as a dictionary {zone : frequency }."""
dist = {}
for line in file:
line = line.strip()
if len(line) == 0 or "," not in line: continue
comps = line.split(";")
x, y, z = comps[0].split(",")
comps[1] = comps[1].strip()
if " " in comps[1]: comps[1] = comps[1][:comps[1].find(" ")]
if float(comps[1]) == 0: continue
dist[Point3D(float(x), float(y), float(z))] = float(comps[1])
return dist
def positional_zone_rankings(input, output):
"""This function writes to 'output' the most common position zone rankings found in the file specified by 'input'. The output of this function (most common alpha zones, followed by common axis positions) is to be the standard format for frequency distributions."""
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
rankings = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)
del frequencies
writefile = open(output, 'w')
for x in rankings[0:20]:
print str(x[0]) + ";", x[1]
writefile.write(str(x[0]) + "; " + str(x[1]) + "\n")
pzs = read_positional_zones(file, azone=x[0])
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
rankings2 = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)
for x in rankings2[0:10]:
writefile.write("\t" + str(x[0]) + "; " + str(x[1]) + "\n")
writefile.close()
del rankings
print "Done"
def list_position_zone_frequencies(input, output):
"""This function writes to 'output' ALL position zone frequencies found in the file specified by 'input'."""
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
writefile = open(output, 'w')
i = 0
for x in xrange(-10, 10):
for y in xrange(-10, 10):
for z in xrange(-10, 10):
pt = Point3D(x, y, z)
'''if math.fabs(z) > 20 - math.fabs(x) - math.fabs(y):
if pt in frequencies:
print "Nonzero frequency for %r: %d" % (str(pt), frequencies[pt])
continue
print str(pt), i'''
if pt in frequencies:
freq = frequencies[pt]
writefile.write(str(freq) + "\n")
#print str(pt), freq
else:
writefile.write("0\n")
i += 1
writefile.close()
return
def sorting_function(a, b):
if a.x != b.x: return int(a.x - b.x)
else:
if a.y != b.y: return int(a.y - b.y)
else: return int(a.z - b.z)
data = sorted(frequencies.items(), cmp=sorting_function, key=lambda x: x[0])
for (pz, freq) in data:
writefile.write(str(freq) + "\n")
writefile.close()
def write_median_frequencies(input):
"""Writes the median frequency to the end of the file for each alpha zone file in input."""
for path in os.listdir(input):
if ".txt" not in path: continue
fncomps = path[:path .find(".txt")].split("-")
print path[:path.find(".txt")]
dist = []
with open(os.path.join(input, path), 'r') as file:
for line in file:
line = line.strip()
if len(line) == 0 or ";" not in line: continue
comps = line.split(";")
nums = [float(x) for x in comps[1].split(",")]
i = 0
while i < len(dist):
dist[i].append(nums[i])
i += 1
while i < len(nums):
dist.append([nums[i]])
i += 1
means = []
interaction_medians = []
medians = []
for subdist in dist:
s = sorted(subdist)
if len(s) > 0:
median = s[int(len(s) / 2.0)]
interaction_median = sum(s) / 2.0
runner = 0.0
for x in s:
runner += x
if runner >= interaction_median:
interaction_median = x
break
mean = sum(s) / 5111.0 #float(len(s))
else:
median = 0.0
interaction_median = 0.0
mean = 0.0
means.append(mean)
interaction_medians.append(interaction_median)
medians.append(median)
with open(os.path.join(input, path), 'r') as file:
text = file.readlines()
with open(os.path.join(input, path), 'w') as file:
for line in text:
if len(line.split(";")) > 1:
file.write(line)
def list_str(numbers_string):
ret = ""
for num in numbers_string:
ret += str(num) + ","
return ret[:-1]
file.write(list_str(interaction_medians) + "\n" + list_str(medians) + "\n" + list_str(means) + "\n")
def write_mean_hydrophobicity_dist(input):
"""Writes the mean frequency to the end of the file for each medium file in input. (Deprecated; use format_hydrophobicity_dist instead.)"""
for path in os.listdir(input):
if ".txt" not in path: continue
idx1 = int(path[:path.find(".txt")])
print idx1
dist = []
with open(os.path.join(input, path), 'r') as file:
for line in file:
line = line.strip()
if len(line) == 0 or "," not in line: continue
comps = line.split(",")
dist.append(float(comps[1]))
s = sorted(dist)
if len(s) > 0:
#median = s[int(len(s) / 2.0)]
mean = sum(s) / float(len(s))
else:
#median = 0.0
mean = 0.0
#print median, mean
print mean
with open(os.path.join(input, path), 'a') as file:
file.write("\n" + str(mean) + "\n")
#MARK: - Frequency function
'''The following functions were used as attempts to determine a function relating zone and frequency based on the existing frequency tables.'''
def compute_neighbor_zones(point, offset=1):
neighbor_zones = []
for x in xrange(-offset, offset + 1):
for y in xrange(-offset, offset + 1):
for z in xrange(-offset, offset + 1):
if x > -offset and x < offset and y > -offset and y < offset and z > -offset and z < offset: continue
else: neighbor_zones.append(Point3D(point.x + x, point.y + y, point.z + z))
return neighbor_zones
def iter_neighbor_zones(point, offset=1):
neighbor_zones = []
for x in xrange(-offset, offset + 1):
for y in xrange(-offset, offset + 1):
for z in xrange(-offset, offset + 1):
if x > -offset and x < offset and y > -offset and y < offset and z > -offset and z < offset: continue
else: yield Point3D(point.x + x, point.y + y, point.z + z)
def compute_box_zones(point, offset=1):
neighbor_zones = []
for x in xrange(-offset, offset + 1):
for y in xrange(-offset, offset + 1):
for z in xrange(-offset, offset + 1):
neighbor_zones.append(Point3D(point.x + x, point.y + y, point.z + z))
return neighbor_zones
def coeff_of_determination(data, function):
mean = numpy.mean([x[1] for x in data])
totsum = sum([(x[1] - mean) ** 2 for x in data])
ressum = sum([(x[1] - function(x[0])) ** 2 for x in data])
return 1.0 - ressum / totsum
def average_zp_frequency_change(input, zoneoffset=1, dist=None):
"""This function returns the average frequency percentage change that is undergone when moving 'zoneoffset' units away from a high-ranking position zone in any direction. Pass in a path to a file containing position zones and the relevant distribution."""
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
maxima = {}
neighbor_zones = []
border_zones = []
total_average = 0.0
for (point, frequency) in frequencies.iteritems():
if frequency < 10: continue
neighbor_zones = compute_neighbor_zones(point)
maximum = True
total_difference = 0.0
for neighbor in neighbor_zones:
if neighbor in frequencies:
if frequencies[neighbor] > frequency:
maximum = False
break
if maximum == True:
border_zones = compute_neighbor_zones(point, offset=zoneoffset)
for neighbor in border_zones:
if neighbor in frequencies:
total_difference += float(frequency - frequencies[neighbor]) / float(frequency) * 100.0
else: total_difference += 100.0
average = float(total_difference) / len(border_zones)
maxima[point] = (frequency, average)
total_average += average
#This code computes linear regressions for distance data.
'''border_zones = compute_box_zones(point, offset=2)
distancedata = [(pz.distanceto(point), frequencies[pz]) for pz in border_zones if pz in frequencies]
for (distance, freq) in distancedata:
print distance, freq
slope, intercept, r_value, p_value, std_err = linregress(distancedata)
print "y = {}(1/d)+{}, r^2={}".format(slope, intercept, r_value ** 2)'''
del neighbor_zones[:]
del border_zones[:]
maxima = sorted(maxima.items(), key=lambda x: x[1][0], reverse=True)
for (key, value) in maxima:
print str(key) + ", %d, %.6f" % value
return total_average / float(len(maxima))
def positional_zone_stats(input, dist=None, quantiledata=None):
"""This function logs the distribution of distances from the maximum frequency positional zone. It's not extremely reliable for data because the max positional zone itself is defined only approximately, with the result that apparently there are 0 cases that actually match the max zone.
Input: a path to a single file containing a list of alpha carbon zones. Pass in a FrequencyDistributionManager to use the max zone as the center point; otherwise, the origin will be used. Pass in quantiledata to log the distance-quantile relationship."""
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
file.close()
max = None
if dist is None:
'''frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
rankings = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[:20]
max = rankings[0][0]
del frequencies'''
max = Point3D.zero()
else:
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
max = sorted(dist.alpha_frequencies[int(tag1)][int(tag2)].items(), key=lambda x: x[1], reverse=True)[0][0]
print str(max)
#for (point, frequency) in rankings[1:]:
# print point.distanceto(max)
#Set up a data table with distance to the max as the IV (rounded to array indexes) and frequency as the DV.
cutoffdist = 3
frequencies = {"%.2f" % i: 0 for i in numpy.arange(0,cutoffdist,0.05)}
for pz in pzs:
distance = math.floor(pz.distanceto(max) * 20.0) / 20.0
if quantiledata is not None:
print pz.distanceto(max), quantiledata[pz]
if distance < cutoffdist:
frequencies["%.2f" % distance] += 1
#Determine the mean, median, and mode of the frequencies based on the distance from each point to the maximum. They should be centered at 0.
sum = 0
count = 0
frequencies = sorted(frequencies.items(), key=lambda x: x[0])
for (distance, frequency) in frequencies:
print distance + ", " + str(frequency)
sum += float(distance) * frequency
count += frequency
print "Mean:", float(sum) / float(count)
file.close()
print "Done"
def median_frequency(input):
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
file.close()
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
frequencies = sorted(frequencies.values())
if len(frequencies) == 0: return -1
return frequencies[len(frequencies) / 2]
def compare_dist_frequencies(distribution, input):
"""This function evaluates the difference between predicted frequencies for a particular pair of amino acids and actual frequencies determined from data. Pass in a FrequencyDistributionManager and a path to a file containing positional zones."""
print os.path.basename(input)
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
total_difference = 0
for pz, freq in frequencies.iteritems():
total_difference += math.fabs(freq - distribution.score((int(tag1), int(tag2), pz)))
print "Average difference: %.3f" % (float(total_difference) / len(frequencies))
def frequency_vs_zonepairs(input):
"""This function determines the *number of zone pairs* for each given frequency. 'data' will be output as a list of tuples, with data[x][0] being the frequency and [1] being the number of zone pairs."""
files = os.listdir(input)
avg_frequencies = []
total_freqcount = 0
for path in files:
if path.find(".txt") == -1: continue
print os.path.basename(path)
file = open(join(input, path), 'r')
frequencies = read_alpha_frequencies(file)
file.close()
if len(frequencies) == 0: continue
maximum = max(frequencies.values())
print maximum
data = [0 for i in xrange(maximum + 1)]
for x in xrange(-10, 10):
for y in xrange(-10, 10):
for z in xrange(-10, 10):
#if Point3D.zero().distanceto(Point3D(math.floor(math.fabs(x)), math.floor(math.fabs(y)), math.floor(math.fabs(z)))) > 10.0: continue #To stop skewing the data for samples we don't have
if Point3D(x, y, z) in frequencies:
freq = frequencies[Point3D(x, y, z)]
data[freq] += 1
else: data[0] += 1
total_count = 0
total_frequency = 0
cutoff = 20
total_freqcount += 1
for i, zpcount in enumerate(data):
#if zpcount != 0: print i, zpcount
if len(avg_frequencies) > i: avg_frequencies[i] += zpcount
elif len(avg_frequencies) == i: avg_frequencies.append(zpcount)
else:
while len(avg_frequencies) < i: avg_frequencies.append(0)
avg_frequencies.append(zpcount)
if zpcount > cutoff:
total_count += zpcount
total_frequency += i
print "Average baseline frequency:", float(total_frequency) / float(total_count)
del data[:]
lastvalue = -1
for i, zpcount in enumerate(avg_frequencies):
if zpcount > 0:
value = float(zpcount) / float(total_freqcount)
if value != lastvalue:
print i, value
lastvalue = float(zpcount) / float(total_freqcount)
def _calculate_quantiles(frequencies, n=10):
quantiles = []
distribution = sorted(frequencies.items(), key=lambda x: x[1])
step = int(len(distribution) / n)
for i in xrange(1,n):
quantile = distribution[i * step][1]
quantiles.append(quantile)
return quantiles
def quantiles(input, output=None, n=10, use_frequencies=True):
"""Computes quantiles of frequency distribution into n intervals. Returns two values: a list of all zones found and their quantiles, and a list of the quantile values. Writes the list of the quantile values to 'output' if it is non-nil, otherwise prints a summary to the console. Pass use_frequencies=True to use the methods for raw alpha pz data."""
file = open(input, 'r')
if use_frequencies:
frequencies = read_alpha_frequencies(file)
else:
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
if len(frequencies) == 0: return {}
#Now compute the values of each quantile by sorting the frequencies dictionary by increasing frequency
'''quantiles = _calculate_quantiles(frequencies, n)
if output is not None:
file = open(output, 'w')
for i, quantile in enumerate(quantiles):
print i, quantile
file.write(str(quantile) + "\n")
file.close()
else:
retstr = str(len(frequencies))#str(len([x for x in frequencies if frequencies[x] > 50]))
for quantile in quantiles:
retstr += "\t" + str(quantile)
print retstr'''
#Now compute the quantile that each position zone belongs in based on its frequency.
'''data = {}
for x in xrange(-10, 10):
for y in xrange(-10, 10):
for z in xrange(-10, 10):
zone = Point3D(x, y, z)
if zone in frequencies:
freq = frequencies[zone]
try:
data[zone] = next(key for key, value in enumerate(quantiles) if value > freq)
except StopIteration:
data[zone] = n - 1
#if math.fabs(z) <= 0.01:
# print x, y, data[zone]'''
return len(frequencies)
def _max_zones(flagged_data, startzone):
flagged_data[startzone][1] = 1
zones = [(startzone.x, startzone.y, startzone.z)]
quantile = flagged_data[startzone][0]
for zone in iter_neighbor_zones(startzone):
if math.fabs(zone.x) > 10.0 or math.fabs(zone.y) > 10.0 or math.fabs(zone.z) > 10.0: continue
if zone in flagged_data and flagged_data[zone][0] == quantile and flagged_data[zone][1] == 0:
zones += _max_zones(flagged_data, zone)
return zones
def same_quantile_cluster_size(data):
"""This function determines how many consecutive zones have the same quantile. The 'data' is of the format returned by quantiles()."""
flagged_data = { key: [value, 0] for key, value in data.iteritems() }
for key, list in flagged_data.iteritems():
if list[1] == 0:
zones = _max_zones(flagged_data, key)
if len(zones) > 330:
print "%d consecutive zones for quantile %d" % (len(zones), flagged_data[key][0])
for zone in zones: print zone[0], zone[1], zone[2]
minx, maxx = min(x[0] for x in zones), max(x[0] for x in zones)
miny, maxy = min(x[1] for x in zones), max(x[1] for x in zones)
minz, maxz = min(x[2] for x in zones), max(x[2] for x in zones)
print "Cube from (%d-%d, %d-%d, %d-%d)" % (minx, maxx, miny, maxy, minz, maxz)
excess = math.fabs(maxx - minx + 1) * math.fabs(maxy - miny + 1) * math.fabs(maxz - minz + 1) - len(zones)
print "Excess:", excess
def random_expected_frequency(zone, distribution=None, type1=None, type2=None):
if distribution is not None and type1 is not None and type2 is not None:
if zone in distribution.alpha_frequencies[type1][type2]:
return distribution.alpha_frequencies[type1][type2][zone] * distribution.total_count[type1][type2] / 100.0
return random.randint(0, 100)
def evaluate_random_frequency_function(input, distribution):
print os.path.basename(input)
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
total_difference = 0.0
total_percent_difference = 0.0
for pz, actualfreq in frequencies.iteritems():
predfreq = random_expected_frequency(pz, distribution, int(tag1), int(tag2))
total_difference += math.fabs(actualfreq - predfreq)
print predfreq, actualfreq
total_percent_difference += math.fabs(actualfreq - predfreq) / actualfreq * 100.0
print "Average difference:", total_difference / len(frequencies)
print "Average % difference:", total_percent_difference / len(frequencies)
def evaluate_frequency_function(input, distribution):
print os.path.basename(input)
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
file = open(input, 'r')
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
distribution.load_frequencies(AminoAcid(aatype(int(tag2))), [AminoAcid(aatype(int(tag1)))])
total_difference = 0.0
total_percent_difference = 0.0
for pz, actualfreq in frequencies.iteritems():
predfreq = distribution.zone_frequency(int(tag1), int(tag2), pz)
total_difference += math.fabs(actualfreq - predfreq)
total_percent_difference += math.fabs(actualfreq - predfreq) / actualfreq * 100.0
print "Average difference:", total_difference / len(frequencies)
print "Average % difference:", total_percent_difference / len(frequencies)
def partition_zones_stdev(input, size=5, distribution=None):
"""This function determines the viability of larger partitions of the position zone space to determine if the random frequency function can be used. Pass in distribution to exclude zones that are listed as ranks."""
print os.path.basename(input)
file = open(input, 'r')
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
pzs = read_alpha_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
partition_freqs = {}
for pz, freq in frequencies.iteritems():
if distribution and pz in distribution.alpha_frequencies[int(tag1)][int(tag2)]:
continue
part = Point3D(math.floor(pz.x / float(size)) * size, math.floor(pz.y / float(size)) * size, math.floor(pz.z / float(size)) * size)
if part in partition_freqs:
partition_freqs[part].append(freq)
else:
partition_freqs[part] = [freq]
for part, list in partition_freqs.iteritems():
mean = numpy.mean(list)
stdev = numpy.std(list)
print str(part), mean, stdev
def similar_alpha_frequencies(input, output):
"""Pass in the entire directory of alpha frequencies. This function will list alpha zones whose relative frequencies are fairly close to one another. Pass in the path for an alpha zone frequencies directory to write the non-similar zones to the appropriate files."""
files = os.listdir(input)
data = {}
for path in files:
if ".txt" not in path: continue
print path
with open(join(input, path), 'r') as file:
total_freq = 0
for line in file:
freq = int(line)
total_freq += freq
file.seek(0)
k = 0
if total_freq == 0: continue
for line in file:
freq = float(line) / float(total_freq)
pt = Point3D(math.floor(k / 400) - 10.0, math.floor((k % 400) / 20) - 10.0, (k % 20) - 10.0)
if pt in data: data[pt].append(freq)
else: data[pt] = [freq]
k += 1
for pt, freqs in data.iteritems():
stdev = max(freqs) - min(freqs)
mean = np.mean(freqs)
if stdev < 0.0001:
print str(pt), mean, stdev
data[pt] = None
if output is None:
return
#Writing the whole file
for path in files:
if ".txt" not in path: continue
print path
inddata = {}
values = []
with open(join(input, path), 'r') as file:
total_freq = 0
for line in file:
freq = int(line)
total_freq += freq
file.seek(0)
k = 0
if total_freq == 0: continue
for line in file:
freq = float(line) / float(total_freq)
pt = Point3D(math.floor(k / 400) - 10.0, math.floor((k % 400) / 20) - 10.0, (k % 20) - 10.0)
if data[pt] is not None:
inddata[pt] = freq
if freq != 0.0:
values.append(freq)
k += 1
with open(join(output, path), 'w') as file:
for pt, freq in inddata.iteritems():
file.write("{0:.0f}, {1:.0f}, {2:.0f}; {3}\n".format(pt.x, pt.y, pt.z, freq))
median = sorted(values)[int(math.floor(len(values) / 2.0))]
file.write(str(median) + "\n")
def consecutive_allowed_alpha_zones(input, output, cutoff=0.005):
"""This method determines which alpha zones for every data file are "allowed" (above a certain frequency) and outputs them to the output files.
If cutoff >= 1, an absolute frequency is assumed. If cutoff < 1, it is assumed that this means a fraction of the total number of occurrences of this interaction."""
print os.path.basename(input)
dist = {}
with open(input, 'r') as file:
for line in file:
line = line.strip()
if len(line) == 0 or ";" not in line: continue
comps = line.split(";")
(x, y, z) = comps[0].split(",")
dist[Point3D(x, y, z)] = int(comps[1])
s = sum(dist.values())
min_zones = cutoff
if min_zones < 1.0:
min_zones *= s
with open(output, 'w') as file:
for pz, freq in dist.iteritems():
if freq > min_zones:
file.write("{}, {}, {}\n".format(pz.x, pz.y, pz.z))
#MARK: - Orientation Analysis
# Now for the orientation analysis (as opposed to alpha zone location)
def angle_frequency_dependence(input):
'''This function logs the frequencies of various orientations with respect to the angle formed between the x-axis of the second amino acid and the line connecting the two alpha carbons.'''
print os.path.basename(input)
file = open(input, 'r')
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
pzs = read_positional_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
for pz, freq in frequencies.iteritems():
vector = pz.alpha_zone.multiply(-1.0)
mags = (pz.x_axis.magnitude() * vector.magnitude())
if mags == 0.0 or (dotproduct(pz.x_axis, vector) / mags) > 1.0 or (dotproduct(pz.x_axis, vector) / mags) < -1.0: continue
angle = math.acos(dotproduct(pz.x_axis, vector) / mags)
print angle, freq
def angle_frequency_vs_zonepairs(input):
"""This function prints the *number of angle-containing position zones* for each given frequency."""
files = os.listdir(input)
for path in files:
if path.find(".txt") == -1: continue
print os.path.basename(path)
file = open(join(input, path), 'r')
pzs = read_positional_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
if len(frequencies) == 0: continue
maximum = max(frequencies.values())
print maximum
data = [0 for i in xrange(maximum + 1)]
for pz, freq in frequencies.iteritems():
data[freq] += 1
total_count = 0
total_frequency = 0
cutoff = 20
for i, zpcount in enumerate(data):
#if zpcount != 0: print i, zpcount
if zpcount > cutoff:
total_count += zpcount
total_frequency += i
print "Average baseline frequency:", float(total_frequency) / float(total_count)
del data[:]
def avg_num_angles_used(input):
'''This function logs the frequencies of various orientations with respect to the angle formed between the x-axis of the second amino acid and the line connecting the two alpha carbons.'''
file = open(input, 'r')
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
pzs = read_positional_zones(file)
frequencies = {}
for pz in pzs:
if pz in frequencies:
frequencies[pz] += 1
else:
frequencies[pz] = 1
file.close()
afrequencies = {}
print os.path.basename(input)
for pz, freq in frequencies.iteritems():
if pz.alpha_zone in afrequencies:
afrequencies[pz.alpha_zone][0] += 1
afrequencies[pz.alpha_zone][1] += freq
else:
afrequencies[pz.alpha_zone] = [1, freq]
for apz in afrequencies:
values = afrequencies[apz]
afrequencies[apz] = float(values[0]) / float(values[1])
return float(sum(afrequencies.values())) / float(len(afrequencies))
def axes_for_mode(input):
"""This function finds the most common alpha carbon location in the file and generates a list of all the x-axis locations and their frequencies."""
file = open(input, 'r')
tag1, tag2 = os.path.basename(input).replace(".txt", "").split("-")
pzs = read_positional_zones(file)
frequencies = {}
for pz in pzs:
if pz.alpha_zone in frequencies:
frequencies[pz.alpha_zone] += 1
else:
frequencies[pz.alpha_zone] = 1
file.close()
if len(frequencies) == 0: return -1
mode = (Point3D(-6.0, 1.0, 0.0), frequencies[Point3D(-6.0, 1.0, 0.0)]) #sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[0]
#print str(mode[0]), mode[1]
afrequencies = {}
print os.path.basename(input)
for pz in pzs:
if pz.alpha_zone == mode[0]:
if pz.x_axis in afrequencies:
afrequencies[pz.x_axis] += 1
else:
afrequencies[pz.x_axis] = 1
#for x, freq in afrequencies.iteritems():
# print x.x, x.y, x.z, float(freq) / float(mode[1]) * 100.0
'''y = []
x = [ [], [] ]
for pt in afrequencies.iterkeys():
print pt.x, pt.y, pt.z
for i in xrange(afrequencies[pt]):
y.append(pt.z)
x[0].append(pt.x)
x[1].append(pt.y)'''
'''s = sorted(afrequencies.items(), key=lambda x: x[1], reverse=True)[:40]
y = map(lambda x: x[0].z, s)
x = [map(lambda x: x[0].x, s),
map(lambda x: x[0].y, s)]
plane = plreg.reg_m(y, x)
print plane.summary()'''
#point1, point2, point3 = (x[0] for x in sorted(afrequencies.items(), key=lambda x: x[1], reverse=True)[:3])
'''cp = crossproduct(point2.subtract(point1), point3.subtract(point1)).normalize()
print str(cp)
#ax + by + cz + d = 0
d = -cp.x * point1.x - cp.y * point1.y - cp.z * point1.z
#z = (-ax - by - d) / c
a = -cp.x / cp.z
b = -cp.y / cp.z
c = -d / cp.z'''
'''print str(point1), str(point2), str(point3)
vector1 = [point2.x - point1.x, point2.y - point1.y, point2.z - point1.z]
vector2 = [point3.x - point1.x, point3.y - point1.y, point3.z - point1.z]
cross_product = [vector1[1] * vector2[2] - vector1[2] * vector2[1], -1 * vector1[0] * vector2[2] - vector1[2] * vector2[0], vector1[0] * vector2[1] - vector1[1] * vector2[0]]
d = cross_product[0] * point1.x - cross_product[1] * point1.y + cross_product[2] * point1.z
a = cross_product[0]
b = cross_product[1]
c = cross_product[2]
print "{}x + {}y + {}z = {}".format(a, b, c, d)'''
'''mode = sorted(afrequencies.items(), key=lambda x: x[1], reverse=True)[0]
print "0", mode[1]
for xaxis, freq in afrequencies.iteritems():
print xaxis.distanceto(mode[0]), freq'''
return afrequencies.keys()
'''points = afrequencies.keys()#[(p.x, p.y, p.z) for p in afrequencies.keys()]
#a, b, c = plane_regression(points)
point1 = point2 = point3 = Point3D.zero()
while point1 == point2 or point2 == point3 or point1 == point3:
point1 = random.choice(points)
point2 = random.choice(points)
point3 = random.choice(points)
cp = crossproduct(point1.subtract(point2), point2.subtract(point3))
print str(cp)
#ax + by + cz + d = 0
d = -cp.x * point1.x - cp.y * point1.y - cp.z * point1.z
#z = (-ax - by - d) / c
a = -cp.x / cp.z
b = -cp.y / cp.z
c = -d / cp.z
print "z = {}x + {}y + {}".format(a, b, c)'''
def acarbon_axis_relation(input, axisattr="x_axis"):
"""This function prints the most common axis vector for each alpha carbon location. Pass in the entire directory of data for input. For axisattr, provide a string for the attribute x_axis, y_axis, or z_axis."""
files = os.listdir(input)
#data is a dictionary where the keys are acarbon zones and the values are (dictionaries where the keys are x-axes and the values are frequencies).
data = {}
for path in files:
if path.find(".txt") == -1: continue
print path
with open(join(input, path), 'r') as file:
pzs = read_positional_zones(file)
frequencies = {}
temp = {}
for pz in pzs:
if abs(pz.alpha_zone.distanceto(Point3D.zero()) - 6.0) >= 1.0: continue
if pz.alpha_zone in data:
d = data[pz.alpha_zone]
if getattr(pz, axisattr) in d:
d[getattr(pz, axisattr)] += 1
elif pz.alpha_zone in temp and getattr(pz, axisattr) in temp[pz.alpha_zone]:
d[getattr(pz, axisattr)] = 2
else:
if pz.alpha_zone in temp:
d = temp[pz.alpha_zone]
if getattr(pz, axisattr) in d:
data[pz.alpha_zone] = { getattr(pz, axisattr) : 2 }
else:
d[getattr(pz, axisattr)] = 1
else:
temp[pz.alpha_zone] = { getattr(pz, axisattr) : 1 }
elif pz.alpha_zone in temp:
d = temp[pz.alpha_zone]
if getattr(pz, axisattr) in d:
data[pz.alpha_zone] = { getattr(pz, axisattr) : 2 }
else:
d[getattr(pz, axisattr)] = 1
else:
temp[pz.alpha_zone] = { getattr(pz, axisattr) : 1 }
frequencies.clear()
temp.clear()
del frequencies
del pzs[:]
del temp
gc.collect()
for alphazone, axes in data.iteritems():
maximum = max(axes.iteritems(), key=lambda x: x[1])
print str(alphazone), str(maximum[0]), "(%d)" % maximum[1]
def optimum_radius(input, axisattr="x_axis"):
"""This function determines the radius of the sphere centered at the reference amino acid that passes through the most axis position zones (which axis is used depends on the string value of axisattr - e.g., "x_axis" or "y_axis" or "z_axis"). Only alpha zones with more than 25 occurrences will be used. Input is a single pair of amino acid's path. The output is a list of distances from reference acarbon to subject acarbon paired with the optimum radii."""
frequencies = {}
with open(input, 'r') as file:
pzs = read_positional_zones(file)
for i, pz in enumerate(pzs):
if pz.alpha_zone in frequencies:
frequencies[pz.alpha_zone][0] += 1
frequencies[pz.alpha_zone][1].append(i)
else:
frequencies[pz.alpha_zone] = [ 1, [i] ]
print os.path.basename(input)
pairs = []
for alpha_zone, [freq, idxs] in frequencies.iteritems():
if freq <= 100: continue
axes = {}
for i in idxs:
ax = getattr(pzs[i], axisattr)
if ax in axes:
axes[ax] += 1
else:
axes[ax] = 1
#Compile a list of minimum and maximum radii for each axis zone
radii = {}
for ax in axes:
dist1 = Point3D(math.floor(alpha_zone.x + ax.x), math.floor(alpha_zone.y + ax.y), math.floor(alpha_zone.z + ax.z)).distanceto(Point3D.zero())
dist2 = Point3D(math.ceil(alpha_zone.x + ax.x), math.ceil(alpha_zone.y + ax.y), math.ceil(alpha_zone.z + ax.z)).distanceto(Point3D.zero())
radii[ax] = ( min(dist1, dist2), max(dist1, dist2) )
#Test out which radius will pass through the most position zones
alphadistance = alpha_zone.distanceto(Point3D.zero())
max_satisfied = 0
max_radius = 0.0
for radius in np.arange(alphadistance - 1.0, alphadistance + 1.01, 0.1):
satisfied = 0
for ax, bounds in radii.iteritems():
if radius >= bounds[0] and radius <= bounds[1]:
satisfied += 1