-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbestSequenceEachSpecies.py
executable file
·261 lines (221 loc) · 9.2 KB
/
bestSequenceEachSpecies.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
#! /usr/bin/env python3
# Copyright 2023 Hal W Canary III, Lindsay R Saunders PhD.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
Create a new FASTA database with only best sequence per species.
The accession, genus, and species epithet are assumed to be the first three
fields in the description.
'''
import argparse
import collections
import logging
import os
import re
import sys
_noSpeciesRe = re.compile(r'^\S+ \S+ sp. ')
_strainRe = re.compile(
r'^(\S+) (\S+) (\S+) ((?:.* )?)(strain .*?)( 16S(?: .*)?)$')
_strainRe2 = re.compile(
r'^(\S+) (\S+) (\S+) ((?:.* )?)\((strain .*?)\)((?: .*)?)$')
_strainRe3 = re.compile(
r'^(\S+) (\S+) (\S+) ((?:.* )?)(strain \S+(?: \S+)?)((?: .*)??)$')
###################################################################################################
# FASTA file format parsing functions
# These may be moved to another package at a later time.
###################################################################################################
def parse_fasta_format(f):
'''
@param f file object open for reading in FASTA format.
@yield tuples of form (description, sequence)
Ignores data before the first description.
'''
description, sequence = None, None
for line in f:
if line.startswith('>'):
if description and sequence:
yield (description, sequence)
# Remove '>' character
description, sequence = line[1:].strip(), ''
elif sequence is not None:
sequence += line.strip()
if description and sequence:
yield (description, sequence)
def print_fasta_description(o, description, sequence):
'''
@param o file object open for writing.
@param description string describing the sequence.
The '>' character is prepended.
@param sequence string in FASTA Sequence Representation.
'''
o.write('>%s\n%s\n\n' % (description, split_str(sequence, 70)))
def split_str(s, n):
'''
Inserts newlines into string `s` so that lines are no longer than
`n` characters long.
'''
return '\n'.join(s[i:i+n] for i in range(0, len(s), n))
###################################################################################################
ProcessedDescription = collections.namedtuple(
'ProcessedDescription', ['genus', 'species', 'strain', 'accession', 'description'])
def process_sequence_description(description):
'''
Expect description to be a string of the form:
"ACCESSION GENUS EPITHET [MORE...]"
New description is:
"GENUS_EPITHET_ACCESSION [MORE...] ACCESSION"
If "strain" present:
"ACCESSION GENUS ...strain [MORE...]"
New description is:
"GENUS_..._strain [MORE...] ACCESSION"
'''
m = _strainRe.match(description)
if m is None:
m = _strainRe2.match(description)
if m is None:
m = _strainRe3.match(description)
if m is not None:
accession, genus, epithet, extra1, strain, extra2 = m.groups()
species = genus + '_' + epithet
strain = species + '_' + strain.replace(' ', '_')
extra = (extra1 if extra1 else '') + extra2.strip()
else:
fields = description.split()
if len(fields) < 3:
# `description` is missing an epithet; this is an error.
raise ValueError('Unable to parse description: %r' % description)
(accession, genus, epithet), extra = fields[:3], ' '.join(fields[3:])
species = genus + '_' + epithet
strain = species + '_' + accession
new_description = ' '.join([strain, extra, accession])
return ProcessedDescription(genus, species, strain, accession, new_description)
def get_score(accession, description, sequence):
'''
Returns a comparable 4-tuple of non-negative numbers.
'''
agtc_count = sum(1 for c in sequence if c in ['A', 'G', 'T', 'C'])
return (
1 if ' type strain ' in description else 0,
float(agtc_count) / len(sequence),
1 if accession.startswith('NR_') else 0,
len(sequence),
)
def get_best_sequence(values, count=1):
'''
@param values nonempty list of (accession, description, sequence) tuples.
@return list of the best count (accession, description, sequence) tuples based on `get_score`
@raises ValueError if no values are provided
'''
if not values:
raise ValueError('No sequences provided')
return sorted(values, key=lambda v: get_score(*v))[-min(len(values), count):]
# TODO(halcanry): Add unit tests for this function.
def get_best_sequence_each_species(infile, outfile, genus, logger, count=1, skipNoSpecies=False):
if genus:
logger.info('Filtering by Genus %r', genus)
sourceCount, speciesSequenceListMap = 0, collections.defaultdict(
lambda: collections.defaultdict(list))
for (description, sequence) in parse_fasta_format(infile):
sourceCount += 1
if skipNoSpecies and _noSpeciesRe.match(description):
logger.debug('NO SPECIES: %s', description)
continue
info = process_sequence_description(description)
if genus and info.genus != genus:
logger.debug('BAD MATCH: %s', description)
continue
logger.debug('good match: %s', description)
speciesSequenceListMap[info.species][info.strain].append(
(info.accession, info.description, sequence))
if len(speciesSequenceListMap) == 0:
raise RuntimeError(
'None of %d sequences match given genus %r.' % (sourceCount, genus))
if logger.isEnabledFor(logging.INFO):
matchCount = sum(len(v) for v in speciesSequenceListMap.values())
logger.info('Matched %d of %d sequences.', matchCount, sourceCount)
taxaTotalCount = 0
# Sort output by sepcies for reproducability.
for species, strainMap in sorted(speciesSequenceListMap.items()):
values = []
for sequence, strainValues in sorted(strainMap.items()):
values.extend(get_best_sequence(strainValues))
try:
best = get_best_sequence(values, count=count)
except Exception as e:
raise RuntimeError("Error with species %s. %r" %
(species, e)) from e
for accession, description, sequence in best:
print_fasta_description(outfile, description, sequence)
taxaTotalCount += 1
logger.debug('Best of %3d for species %r', len(values), species)
logger.info('%d different species processed.', len(speciesSequenceListMap))
logger.info('%d total taxa output.', taxaTotalCount)
def parse_args(argv):
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
exit_on_error=False, description=__doc__)
parser.add_argument(
'INFILE',
nargs='?',
type=argparse.FileType('r'),
default=sys.stdin,
help='Path of FASTA file to read. (default: STDIN)')
parser.add_argument(
'-o',
'--outfile',
nargs='?',
type=argparse.FileType('w'),
default=sys.stdout,
help='Where to write FASTA file. (default: STDOUT)')
parser.add_argument(
'-g',
'--genus',
help='Genus to filter on. (default: None)')
parser.add_argument(
'--loglevel',
choices=['debug', 'info', 'warning'],
default='info',
help='Verbosity level. (default: info)')
parser.add_argument(
'-c',
'--count',
type=int,
default=1,
help='How many top matches. (default: 1)')
parser.add_argument(
'-s',
'--skipnone',
default=False,
action='store_true',
help='if set, skip species with epithet "sp.". (default: False)')
return parser.parse_args(argv)
###################################################################################################
def main():
args = parse_args(sys.argv[1:])
logging.basicConfig(format='%(levelname)s: %(message)s',
level=args.loglevel.upper())
try:
get_best_sequence_each_species(
args.INFILE, args.outfile, args.genus, logging.getLogger(),
args.count, skipNoSpecies=args.skipnone)
except Exception as e:
logging.error(e)
sys.exit(1)
if __name__ == '__main__':
main()