1
2
3
4
5
6 """
7 Parser for PHD files output by PHRED and used by PHRAP and CONSED.
8
9 This module can be used used directly which will return Record objects
10 which should contain all the original data in the file.
11
12 Alternatively, using Bio.SeqIO with the "phd" format will call this module
13 internally. This will give SeqRecord objects for each contig sequence.
14 """
15
16 from Bio import Seq
17 from Bio.Alphabet import generic_dna
18
19 CKEYWORDS=['CHROMAT_FILE','ABI_THUMBPRINT','PHRED_VERSION','CALL_METHOD',\
20 'QUALITY_LEVELS','TIME','TRACE_ARRAY_MIN_INDEX','TRACE_ARRAY_MAX_INDEX',\
21 'TRIM','TRACE_PEAK_AREA_RATIO','CHEM','DYE']
22
24 """Hold information from a PHD file."""
26 self.file_name = ''
27 self.comments={}
28 for kw in CKEYWORDS:
29 self.comments[kw.lower()]=None
30 self.sites = []
31 self.seq = ''
32 self.seq_trimmed = ''
33
34
36 """Reads the next PHD record from the file, returning it as a Record object.
37
38 This function reads PHD file data line by line from the handle,
39 and returns a single Record object.
40 """
41 for line in handle:
42 if line.startswith("BEGIN_SEQUENCE"):
43 record = Record()
44 record.file_name = line[15:].rstrip()
45 break
46 else:
47 return
48
49 for line in handle:
50 if line.startswith("BEGIN_COMMENT"):
51 break
52 else:
53 raise ValueError("Failed to find BEGIN_COMMENT line")
54
55 for line in handle:
56 line = line.strip()
57 if not line:
58 continue
59 if line=="END_COMMENT":
60 break
61 keyword, value = line.split(":", 1)
62 keyword = keyword.lower()
63 value = value.strip()
64 if keyword in ('chromat_file',
65 'phred_version',
66 'call_method',
67 'chem',
68 'dye',
69 'time',
70 'basecaller_version',
71 'trace_processor_version'):
72 record.comments[keyword] = value
73 elif keyword in ('abi_thumbprint',
74 'quality_levels',
75 'trace_array_min_index',
76 'trace_array_max_index'):
77 record.comments[keyword] = int(value)
78 elif keyword=='trace_peak_area_ratio':
79 record.comments[keyword] = float(value)
80 elif keyword=='trim':
81 first, last, prob = value.split()
82 record.comments[keyword] = (int(first), int(last), float(prob))
83 else:
84 raise ValueError("Failed to find END_COMMENT line")
85
86 for line in handle:
87 if line.startswith('BEGIN_DNA'):
88 break
89 else:
90 raise ValueError("Failed to find BEGIN_DNA line")
91
92 for line in handle:
93 if line.startswith('END_DNA'):
94 break
95 else:
96 base, quality, location = line.split()
97 record.sites.append((base, quality, location))
98
99 for line in handle:
100 if line.startswith("END_SEQUENCE"):
101 break
102 else:
103 raise ValueError("Failed to find END_SEQUENCE line")
104
105 record.seq = Seq.Seq(''.join([n[0] for n in record.sites]), generic_dna)
106 if record.comments['trim'] is not None:
107 first, last = record.comments['trim'][:2]
108 record.seq_trimmed = record.seq[first:last]
109
110 return record
111
113 """Iterates over a file returning multiple PHD records.
114
115 The data is read line by line from the handle. The handle can be a list
116 of lines, an open file, or similar; the only requirement is that we can
117 iterate over the handle to retrieve lines from it.
118
119 Typical usage:
120
121 records = parse(handle)
122 for record in records:
123 # do something with the record object
124 """
125 while True:
126 record = read(handle)
127 if not record:
128 return
129 yield record
130
131
132
133
134 from Bio import File
135 from Bio.ParserSupport import *
136
137
139 """Iterates over a file of multiple PHD records (DEPRECATED).
140
141 Methods:
142 next Return the next record from the stream, or None.
143 """
144
145 - def __init__(self, handle, parser=None):
146 """Create a new iterator.
147
148 Create a new iterator. handle is a file-like object. parser
149 is an optional Parser object to change the results into another form.
150 If set to None, then the raw contents of the file will be returned.
151 """
152 import warnings
153 warnings.warn("Bio.Sequencing.Phd.Iterator is deprecated. Please use Bio.Sequencing.Phd.parse(handle) instead of Bio.Sequencing.Phd.Iterator(handle, RecordParser())", DeprecationWarning)
154 self._uhandle = File.UndoHandle(handle)
155 self._parser = parser
156
158 lines = []
159 while 1:
160 line = self._uhandle.readline()
161 if not line:
162 break
163
164 if lines and line[:14] == 'BEGIN_SEQUENCE':
165 self._uhandle.saveline(line)
166 break
167 lines.append(line)
168
169 if not lines:
170 return None
171
172 data = ''.join(lines)
173 if self._parser is not None:
174 return self._parser.parse(File.StringHandle(data))
175 return data
176
178 """Iterate over the PHY file record by record."""
179 return iter(self.next, None)
180
182 """Parses PHD file data into a Record object (DEPRECATED)."""
184 import warnings
185 warnings.warn("Bio.Sequencing.Phd.RecordParser is deprecated. Please use Bio.Sequencing.Phd.read(handle) instead of Bio.Sequencing.Phd.RecordParser().parse(handle)", DeprecationWarning)
186 self._scanner = _Scanner()
187 self._consumer = _RecordConsumer()
188
189 - def parse(self, handle):
196
197
199 """Scans a PHD-formatted file (DEPRECATED).
200
201 Methods:
202 feed - Feed one PHD record.
203 """
204 - def feed(self, handle, consumer):
205 """Reads in PDH data from the handle for scanning.
206
207 Feed in PHD data for scanning. handle is a file-like object
208 containing PHD data. consumer is a Consumer object that will
209 receive events as the PHD data is scanned.
210 """
211 assert isinstance(handle, File.UndoHandle), \
212 "handle must be an UndoHandle"
213 if handle.peekline():
214 self._scan_record(handle, consumer)
215
221
224
240
242 while 1:
243 line = uhandle.readline()
244 if is_blank_line(line) or line == 'BEGIN_DNA\n':
245 continue
246 elif line == 'END_DNA\n':
247 break
248 consumer.read_dna(line)
249
250
252 """Consumer that converts a PHD record to a Record object (DEPRECATED)."""
255
259
266
269
272
275
278
281
282 - def time(self, line):
284
287
290
291 - def trim(self, line):
292 first, last, prob = line[5:-1].split()
293 self.data.comments['trim'] = (int(first), int(last), float(prob))
294
297
298 - def chem(self, line):
300
301 - def dye(self, line):
303
307
308 if __name__ == "__main__" :
309 print "Quick self test"
310
311 handle = open("../../Tests/Phd/phd1")
312 records = parse(handle)
313 for record in records:
314 print record.file_name, len(record.seq)
315 handle.close()
316 print "Done"
317