Add globplot and disembl to web services descriptors
[jabaws.git] / binaries / src / globplot / GlobPlot.py
1 #!/usr/bin/env python
2 # Copyright (C) 2003 Rune Linding - EMBL
3 # GlobPlot TM
4 # GlobPlot is licensed under the Academic Free license
5
6 from string import *
7 from sys import argv
8 import sys,re
9 import os
10 from os import system,popen3
11
12 relpath = re.sub("/GlobPipe.py$","",argv[0])
13 newpath =os.getcwd()+"/"+relpath+"/biopython-1.50"
14 sys.path.append(newpath)
15
16 import Bio
17 from Bio import File
18 from Bio import Fasta
19 import fpformat
20 import tempfile
21 import math
22
23 # Russell/Linding
24 RL = {'N':0.229885057471264,'P':0.552316012226663,'Q':-0.187676577424997,'A':-0.261538461538462,'R':-0.176592654077609, \
25       'S':0.142883029808825,'C':-0.0151515151515152,'T':0.00887797506611258,'D':0.227629796839729,'E':-0.204684629516228, \
26       'V':-0.386174834235195,'F':-0.225572305974316,'W':-0.243375458622095,'G':0.433225711769886,'H':-0.00121743364986608, \
27       'Y':-0.20750516775322,'I':-0.422234699606962,'K':-0.100092289621613,'L':-0.337933495925287,'M':-0.225903614457831}
28
29 def Sum(seq,par_dict):
30     sum = 0
31     results = []
32     raws = []
33     sums = []
34     p = 1
35     for residue in seq:
36         try:
37             parameter = par_dict[residue]
38         except:
39             parameter = 0
40         if p == 1:
41             sum = parameter
42         else:
43             sum = sum + parameter#*math.log10(p)
44         ssum = float(fpformat.fix(sum,10))
45         sums.append(ssum)
46         p +=1
47     return sums
48
49 def getSlices(dydx_data, DOM_join_frame, DOM_peak_frame, DIS_join_frame, DIS_peak_frame):
50     DOMslices = []
51     DISslices = []
52     in_DOMslice = 0
53     in_DISslice = 0
54     beginDOMslice = 0
55     endDOMslice = 0
56     beginDISslice = 0
57     endDISslice = 0
58     for i in range( len(dydx_data) ):
59     #close dom slice
60         if in_DOMslice and dydx_data[i] > 0:
61             DOMslices.append([beginDOMslice, endDOMslice])
62             in_DOMslice = 0
63     #close dis slice
64         elif in_DISslice and dydx_data[i] < 0:
65             DISslices.append([beginDISslice, endDISslice])
66             in_DISslice = 0
67         # elseif inSlice expandslice
68         elif in_DOMslice:
69             endDOMslice += 1
70         elif in_DISslice:
71             endDISslice += 1
72     # if not in slice and dydx !== 0 start slice
73         if dydx_data[i] > 0 and not in_DISslice:
74             beginDISslice = i
75             endDISslice = i
76             in_DISslice = 1
77         elif dydx_data[i] < 0 and not in_DOMslice:
78             beginDOMslice = i
79             endDOMslice = i
80             in_DOMslice = 1
81     #last slice
82     if in_DOMslice:
83         DOMslices.append([beginDOMslice, endDOMslice])
84     if in_DISslice:
85         DISslices.append([beginDISslice,endDISslice])
86     k = 0
87     l = 0
88     while k < len(DOMslices):
89         if k+1 < len(DOMslices) and DOMslices[k+1][0]-DOMslices[k][1] < DOM_join_frame:
90             DOMslices[k] = [ DOMslices[k][0], DOMslices[k+1][1] ]
91             del DOMslices[k+1]
92         elif DOMslices[k][1]-DOMslices[k][0]+1 < DOM_peak_frame:
93             del DOMslices[k]
94         else:
95             k += 1
96     while l < len(DISslices):
97         if l+1 < len(DISslices) and DISslices[l+1][0]-DISslices[l][1] < DIS_join_frame:
98             DISslices[l] = [ DISslices[l][0], DISslices[l+1][1] ]
99             del DISslices[l+1]
100         elif DISslices[l][1]-DISslices[l][0]+1 < DIS_peak_frame:
101             del DISslices[l]
102         else:
103             l += 1
104     return DOMslices, DISslices
105
106
107 def SavitzkyGolay(window,derivative,datalist):
108     SG_bin = relpath +'/'+ 'sav_gol -V0 '
109     stdin, stdout, stderr = popen3(SG_bin + '-D' + str(derivative) + ' -n' + str(window)+','+str(window))
110     for data in datalist:
111         stdin.write(`data`+'\n')
112     try:
113         stdin.close()
114     except:
115         print stderr.readlines()
116     results = stdout.readlines()
117     stdout.close()
118     SG_results = []
119     for result in results:
120         SG_results.append(float(fpformat.fix(result,6)))
121     return SG_results
122
123
124 def reportSlicesTXT(slices, sequence, maskFlag):
125     if maskFlag == 'DOM':
126         coordstr = 'GlobDoms '
127     elif maskFlag == 'DIS':
128         coordstr = 'Disorder '
129     else:
130         raise SystemExit
131     if slices == []:
132         #by default the sequence is in uppercase which is our search space
133         s = sequence
134     else:
135         # insert seq before first slide
136         if slices[0][0] > 0:
137             s = sequence[0:slices[0][0]]
138         else:
139             s = ''
140         for i in range(len(slices)):
141             #skip first slice
142             if i > 0:
143                 coordstr = coordstr + ', '
144             coordstr = coordstr + str(slices[i][0]+1) + '-' + str(slices[i][1]+1)
145             #insert the actual slice
146             if maskFlag == 'DOM':
147                 s = s + lower(sequence[slices[i][0]:(slices[i][1]+1)])
148                 if i < len(slices)-1:
149                     s = s + upper(sequence[(slices[i][1]+1):(slices[i+1][0])])
150                 #last slice
151                 elif slices[i][1] < len(sequence)-1:
152                     s = s + lower(sequence[(slices[i][1]+1):(len(sequence))])
153             elif maskFlag == 'DIS':
154                 s = s + upper(sequence[slices[i][0]:(slices[i][1]+1)])
155                 #insert untouched seq between disorder segments, 2-run labelling
156                 if i < len(slices)-1:
157                     s = s + sequence[(slices[i][1]+1):(slices[i+1][0])]
158                 #last slice
159                 elif slices[i][1] < len(sequence)-1:
160                     s = s + sequence[(slices[i][1]+1):(len(sequence))]
161     return s,coordstr
162
163
164 def runGlobPlot():
165     try:
166         smoothFrame = 10
167         DOM_joinFrame = 15
168         DOM_peakFrame = 74
169         DIS_joinFrame = 4
170         DIS_peakFrame = 5
171         file = str(sys.argv[1])
172         db = open(file,'r')
173     except:
174         print 'Usage:'
175         print '         ./GlobPipe.py FASTAfile'
176         raise SystemExit
177     parser = Fasta.RecordParser()
178     iterator = Fasta.Iterator(db,parser)
179     while 1:
180         try:
181             cur_record = iterator.next()
182             #uppercase is searchspace
183             seq = upper(cur_record.sequence)
184             # sum function
185             sum_vector = Sum(seq,RL)
186             # Run Savitzky-Golay
187             smooth = SavitzkyGolay(`smoothFrame`,0, sum_vector)
188             dydx_vector = SavitzkyGolay(`smoothFrame`,1, sum_vector)
189             #test
190             sumHEAD = sum_vector[:smoothFrame]
191             sumTAIL = sum_vector[len(sum_vector)-smoothFrame:]
192             newHEAD = []
193             newTAIL = []
194             for i in range(len(sumHEAD)):
195                 try:
196                     dHEAD = (sumHEAD[i+1]-sumHEAD[i])/2
197                 except:
198                     dHEAD = (sumHEAD[i]-sumHEAD[i-1])/2
199                 try:
200                     dTAIL = (sumTAIL[i+1]-sumTAIL[i])/2
201                 except:
202                     dTAIL = (sumTAIL[i]-sumTAIL[i-1])/2
203                 newHEAD.append(dHEAD)
204                 newTAIL.append(dTAIL)
205             dydx_vector[:smoothFrame] = newHEAD
206             dydx_vector[len(dydx_vector)-smoothFrame:] = newTAIL
207             globdoms, globdis = getSlices(dydx_vector, DOM_joinFrame, DOM_peakFrame, DIS_joinFrame, DIS_peakFrame)
208             s_domMask, coordstrDOM = reportSlicesTXT(globdoms, seq, 'DOM')
209             s_final, coordstrDIS = reportSlicesTXT(globdis, s_domMask, 'DIS')
210             sys.stdout.write('>'+cur_record.title+'\n')
211             sys.stdout.write('# '+coordstrDOM+'\n')
212             sys.stdout.write('# '+coordstrDIS+'\n')
213
214 # UNCOMMENT THIS IF NEED TO PRODUCE PER RESEDUE VALUES 
215             sys.stdout.write('# RESIDUE' + '\t' + 'DYDX' + '\t' + 'RAW' + '\t' +'SMOOTHED\n')
216             for i in range(len(dydx_vector)):
217 # dydx (positive values seems to indicate disorder in rows more than ~6 chars)  raw    smoothed
218                sys.stdout.write(seq[i]+'\t'+fpformat.fix(dydx_vector[i],4)+ '\t'+fpformat.fix(smooth[i],4)+'\t'+fpformat.fix(sum_vector[i],4)+ '\n')
219     
220 #            print s_final
221             print '\n'
222         except AttributeError:
223             break
224     return
225
226 runGlobPlot()