-
Notifications
You must be signed in to change notification settings - Fork 1
/
maesepedro.py
executable file
·323 lines (234 loc) · 9.69 KB
/
maesepedro.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
import pdb
import sys
import getopt
import stats
import os
import subprocess
from scipy.stats import norm
from time import strftime
import pprint
pp = pprint.PrettyPrinter(indent=4)
#######################################################
def easterEgg():
print u"""
Real y verdaderamente os digo, señores que me oís, que a mí me pareció todo lo
que aquí ha pasado que pasaba al pie de la letra: que Melisendra era
Melisendra, don Gaiferos don Gaiferos, Marsilio Marsilio, y Carlomagno
Carlomagno: por eso se me alteró la cólera, y, por cumplir con mi profesión de
caballero andante, quise dar ayuda y favor a los que huían, y con este buen
propósito hice lo que habéis visto; si me ha salido al revés, no es culpa mía,
sino de los malos que me persiguen.
Don Quixote, Part Two, Chapter XXVI."""
# print u"""
# Si me ha salido al revés, no es culpa mía, sino de los malos que me persiguen.
# Don Quixote, Part Two, Chapter XXVI."""
#------------------------------------------------------
def readAndWriteNewFASTAFile(inputFileName,
outPutFileName,
digestionPoints = "KR",
maxPepLength = 200,
minPepLength = 1,
removePalindromes = False):
reader = open(inputFileName, "r")
writer = open(outPutFileName, "w")
proteinHeader = ""
proteinSequence = ""
stringLength = 0
for readerLine in reader:
line = readerLine.strip()
if len(line) > 0:
newProtein = line.startswith(">")
if newProtein:
if len(proteinHeader) > 0:
newProteinHeader = generateInvertedProteinHeader(proteinHeader)
newProteinSequence = pseudoInvertProteinSequence(proteinSequence,
digestionPoints,
maxPepLength,
minPepLength,
removePalindromes)
writeInvertedProtein(writer, newProteinHeader, newProteinSequence, stringLength)
proteinHeader = line
proteinSequence = ""
newProtein = False
else:
if len(line) > stringLength: stringLength = len(line)
proteinSequence += line
# adding the last element
newProteinHeader = generateInvertedProteinHeader(proteinHeader)
newProteinSequence = pseudoInvertProteinSequence(proteinSequence)
writeInvertedProtein(writer, newProteinHeader, newProteinSequence, stringLength)
writer.close()
#------------------------------------------------------
def generateInvertedProteinHeader(header, invertedSuffix = "_INV_"):
invertedProteinHeader = ">" + invertedSuffix + header[1:]
return invertedProteinHeader
#------------------------------------------------------
def writeInvertedProtein(writer, header, sequence, stringLength = 60):
if stringLength < 1:
stringLength = 60
rowList = []
for position in range(len(sequence))[::stringLength]:
rowList.append(sequence[position:position + stringLength])
sequenceWithLineBreaks = "\n".join(rowList)
writer.write(header + "\n" + sequenceWithLineBreaks + "\n")
return
#------------------------------------------------------
def pseudoInvertProteinSequence(proteinSequence,
digestionPoints = "KR",
maxPepLength = 200,
minPepLength = 1,
removePalindromes = False):
peptides = separatePeptides(proteinSequence, digestionPoints)
newPeptides = []
for peptide in peptides:
invertedPeptide = pseudoInvertPeptideSequence(peptide, digestionPoints)
newPeptides.append(invertedPeptide)
newProteinSequence = joinPeptideSequences(newPeptides, maxPepLength, minPepLength, removePalindromes)
return newProteinSequence
#------------------------------------------------------
def separatePeptides(proteinSequence, digestionPoints = "KR"):
for cutpoint in digestionPoints:
proteinSequence = proteinSequence.replace(cutpoint, cutpoint + " ")
peptideList = proteinSequence.split(" ")
return peptideList
#------------------------------------------------------
def pseudoInvertPeptideSequence(peptide, digestionPoints = "KR"):
invertedPeptideSequence = peptide[::-1]
for cleaveSite in digestionPoints:
if peptide.endswith(cleaveSite):
SequenceToInvert = peptide[0:-1]
SequenceInvertedPart = SequenceToInvert[::-1]
invertedPeptideSequence = SequenceInvertedPart + cleaveSite
return invertedPeptideSequence
#------------------------------------------------------
def joinPeptideSequences(peptideList,
maxPepLength = 200,
minPepLength = 1,
removePalindromes = False,
digestionPoints = "KR"):
newPeptides = []
for peptide in peptideList:
if len(peptide) <= maxPepLength and len(peptide) >= minPepLength and not(removePalindromes and isPalindrome(peptide, digestionPoints)):
newPeptides.append(peptide)
newPeptides = "".join(newPeptides)
return newPeptides
#------------------------------------------------------
def isPalindrome (peptide, digestionPoints = "KR"):
return peptide == pseudoInvertPeptideSequence(peptide, digestionPoints)
#------------------------------------------------------
def printHelp(version = None):
print """
MaesePedro %s is a program made in the Jesus Vazquez Cardiovascular
Proteomics Lab at Centro Nacional de Investigaciones Cardiovasculares, used to
generate pseudoinverted FASTA files.
Sanson needs one input files:
* a FASTA file (using the -f command)
And delivers two output files:
* the inverted FASTA file
* a log file (default suffix: "_logFile")
Usage: maesepedro.py -f[FASTAFile]
-h, --help Display this help and exit.
-a, --analysis=string
Use a prefix for the output files.
-p, --place, --folder=foldername
To use a different common folder for the output files.
If this is not provided, the the folder used will be the
same as the FASTA file folder.
-c, --cleavesites=string
The residues after which the protease is cleaving.
Default is trypsin (KR). Note that only C-terminal
cleaving proteases are being considered in this version.
-f, --fastafile=string
The input FASTA file to invert.
-r, --removepalindromes
Remove peptides unchanged upon pseudoinversion, i.e.,
peptides such as ASSAK, EGTGER (when using trypsin).
Palindromic peptides are not removed by default.
""" % version
return
#------------------------------------------------------
def main(argv):
version = "v0.04"
analysisName = ""
cleaveSites = "KR" # trypsin default
removePalindromes = False
defaultAnalysisName = "inversor"
analysisFolder = ""
defaultTableExtension = ".xls"
defaultTextExtension = ".txt"
defaultFastaExtension = ".fasta"
graphFileFormat = "png"
defaultFastaFile = "fastadef"
invertedFastaFile = ""
defaultInvertedFileSuffix = "inv"
defaultLogFile = "logFile"
fastaFile = ""
logFile = ""
logList = [["Inversor " + version], ["Start: " + strftime("%Y-%m-%d %H:%M:%S")]]
try:
opts, args = getopt.getopt(argv, "a:p:f:c:rh", ["analysis=", "folder=", "fastafile=", "cleavesites=", "place=", "removepalindromes", "help", "egg", "easteregg"])
except getopt.GetoptError:
logList.append(["Error while getting parameters."])
sys.exit(2)
if len(opts) == 0:
printHelp(version)
sys.exit()
for opt, arg in opts:
if opt in ("-a", "--analysis"):
analysisName = arg
elif opt in ("-p", "--place", "--folder"):
analysisFolder = arg
elif opt in ("-f", "--fastafile"):
fastaFile = arg
elif opt in ("-c", "--cleavesites"):
cleaveSites = arg.strip()
elif opt in ("-r", "--removepalindromes"):
removePalindromes = True
elif opt in ("-h", "--help"):
printHelp(version)
sys.exit()
elif opt in ("--egg", "--easteregg"):
easterEgg()
sys.exit()
# REGION: FILE NAMES SETUP
if len(analysisName) == 0:
if len(fastaFile) > 0:
analysisName = os.path.splitext(os.path.basename(fastaFile))[0]
else:
analysisName = defaultAnalysisName
if len(os.path.dirname(analysisName)) > 0:
analysisNameFirstPart = os.path.dirname(analysisName)
analysisName = os.path.basename(analysisName)
if len(analysisFolder) == 0:
analysisFolder = analysisNameFirstPart
if len(fastaFile) > 0 and len(analysisFolder) == 0:
if len(os.path.dirname(fastaFile)) > 0:
analysisFolder = os.path.dirname(fastaFile)
# input
if len(os.path.dirname(fastaFile)) == 0 and len(fastaFile) > 0:
fastaFile = os.path.join(analysisFolder, fastaFile)
# output
if len(invertedFastaFile) == 0:
invertedFastaFile = os.path.join(analysisFolder, analysisName + "_" + defaultInvertedFileSuffix + defaultFastaExtension)
if len(logFile) == 0:
logFile = os.path.join(analysisFolder, analysisName + "_" + defaultLogFile + defaultTextExtension)
logList.append([""])
logList.append(["Input FASTA file: " + fastaFile])
logList.append(["Inverted FASTA file: " + invertedFastaFile])
logList.append(["Cleave sites used: " + cleaveSites])
logList.append([""])
# END REGION: FILE NAMES SETUP
try:
readAndWriteNewFASTAFile(fastaFile,
invertedFastaFile,
digestionPoints = cleaveSites,
removePalindromes = removePalindromes)
logList.append(["Everything went fine."])
except getopt.GetoptError:
logList.append(["Error."])
stats.saveFile(logFile, logList, "LOG FILE")
sys.exit(2)
stats.saveFile(logFile, logList, "LOG FILE")
#######################################################
if __name__ == "__main__":
main(sys.argv[1:])