File: hrefpkg_query.py

package info (click to toggle)
pplacer 1.1~alpha19-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,056 kB
  • sloc: ml: 20,927; ansic: 9,002; python: 1,641; makefile: 171; xml: 50; sh: 33
file content (283 lines) | stat: -rwxr-xr-x 11,042 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
import collections
import subprocess
import itertools
import argparse
import tempfile
import logging
import os.path
import sqlite3
import atexit
import shutil
import errno
import shlex
import csv

from taxtastic.refpkg import Refpkg
from Bio import SeqIO

log = logging.getLogger(__name__)

def logging_check_call(cmd, *a, **kw):
    log.info(' '.join(cmd))
    return subprocess.check_call(cmd, *a, **kw)

def silently_unlink(path):
    try:
        os.unlink(path)
    except OSError, e:
        if e.errno != errno.ENOENT:
            raise

input_suffixes = {'align-each': 'fasta', 'merge-each': 'sto', 'none': 'sto'}

def main():
    logging.basicConfig(
        level=logging.INFO, format="%(levelname)s: %(message)s")

    parser = argparse.ArgumentParser(
        description="Classify query sequences using a hrefpkg.")
    parser.add_argument('hrefpkg', help="hrefpkg to classify using")
    parser.add_argument('query_seqs', help="input query sequences")
    parser.add_argument('classification_db', help="output sqlite database")
    parser.add_argument('-j', '--ncores', default=1, type=int, metavar='CORES',
                        help="number of cores to tell commands to use")
    parser.add_argument('-r', '--classification-rank', metavar='RANK',
                        help="rank to perform the initial NBC classification at")
    parser.add_argument('--classifier', default='pplacer',
                        help="which classifier to use with guppy classify")
    parser.add_argument('--pplacer-args', default=[], type=shlex.split,
                        help="additional arguments for pplacer")
    parser.add_argument('--classification-args', default=[], type=shlex.split,
                        help="additional arguments for guppy classification")
    parser.add_argument('--post-prob', default=False, action='store_true',
                        help="place with posterior probabilities")
    parser.add_argument('--workdir', metavar='DIR',
                        help=("directory to write intermediate files to "
                              "(default: a temporary directory)"))
    parser.add_argument('--disable-cleanup', default=False, action='store_true',
                        help="don't remove the work directory as the final step")
    parser.add_argument('--use-mpi', default=False, action='store_true',
                        help="run refpkg_align with MPI")
    parser.add_argument(
        '--alignment', choices=['align-each', 'merge-each', 'none'], default='align-each',
        help=("respectively: align each input sequence; subset an input stockholm "
              "alignment and merge each sequence to a reference alignment; only subset "
              "an input stockholm alignment (default: align-each)"))
    parser.add_argument(
        '--cmscores', type=argparse.FileType('w'), metavar='FILE',
        help="in align-each mode, write out a file containing the cmalign scores")

    programs = parser.add_argument_group("external binaries")
    programs.add_argument(
        '--pplacer', default='pplacer', metavar='PROG', help="pplacer binary to call")
    programs.add_argument(
        '--guppy', default='guppy', metavar='PROG', help="guppy binary to call")
    programs.add_argument(
        '--rppr', default='rppr', metavar='PROG', help="rppr binary to call")
    programs.add_argument(
        '--refpkg-align', default='refpkg_align.py', metavar='PROG',
        help="refpkg_align binary to call")
    programs.add_argument(
        '--cmalign', default='cmalign', metavar='PROG', help="cmalign binary to call")


    args = parser.parse_args()

    if args.ncores < 0:
        args.error('ncores must be >= 0')

    mpi_args = []
    if args.use_mpi and args.ncores > 0:
        mpi_args = ['--use-mpi', '--mpi-arguments', '-np %d' % (args.ncores,)]

    if args.workdir is None:
        workdir = tempfile.mkdtemp()
    else:
        workdir = args.workdir
        try:
            os.makedirs(workdir)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise

    if not args.disable_cleanup:
        @atexit.register
        def cleanup_workdir():
            shutil.rmtree(workdir, ignore_errors=True)

    classif_db = os.path.join(workdir, 'classifications.sqlite')
    index_refpkg = os.path.join(args.hrefpkg, 'index.refpkg')
    index = Refpkg(index_refpkg)
    index_rank = index.metadata('index_rank')
    classif_rank = args.classification_rank or index_rank
    index_counts = os.path.join(args.hrefpkg, 'index-%s.counts' % (classif_rank,))
    log.info('performing initial classification at %s', classif_rank)
    silently_unlink(classif_db)
    logging_check_call(
        [args.rppr, 'prep_db', '--sqlite', classif_db, '-c', index_refpkg])
    logging_check_call(
        [args.guppy, 'classify', '--sqlite', classif_db, '-c', index_refpkg,
         '--classifier', 'nbc', '--nbc-rank', classif_rank, '--no-pre-mask',
         '--nbc-sequences', args.query_seqs, '--nbc-counts', index_counts,
         '-j', str(args.ncores)])

    with open(os.path.join(args.hrefpkg, 'index.csv'), 'rU') as fobj:
        refpkg_map = dict(csv.reader(fobj))

    log.info('determining bins at %s', index_rank)
    conn = sqlite3.connect(classif_db)
    curs = conn.cursor()
    curs.execute("""
        SELECT name,
               tax_id
        FROM   multiclass
        WHERE  want_rank = ?
               AND rank = want_rank
    """, (index_rank,))
    seq_bins = dict(curs)
    all_bins = set(seq_bins.itervalues()) & set(refpkg_map)
    log.info('classified into %d bins', len(all_bins))
    log.debug('bins: %r', all_bins)
    bin_outputs = {}
    bin_counts = collections.Counter()

    input_suffix = input_suffixes[args.alignment]
    def binfile(bin):
        return os.path.join(workdir, '%s.%s' % (bin, input_suffix))

    for bin in all_bins:
        bin_outputs[bin] = open(binfile(bin), 'w')

    if args.alignment == 'align-each':
        for seq in SeqIO.parse(args.query_seqs, 'fasta'):
            bin = seq_bins.get(seq.id)
            if bin is None or bin not in bin_outputs:
                continue
            SeqIO.write([seq], bin_outputs[bin], 'fasta')
            bin_counts[bin] += 1

    # Gross ad-hoc stockholm parser. This is only necessary because biopython
    # can't handle the metadata that cmalign adds to the file.
    else:
        def write_all(lines):
            for line in lines:
                for fobj in bin_outputs.itervalues():
                    fobj.write(line)

        with open(args.query_seqs, 'r') as fobj:
            # Copy the stockholm header,
            write_all(itertools.islice(fobj, 3))

            # then partition the sequences,
            for line in fobj:
                # (stopping if we reach the metadata at the end (hopefully it's at
                # the end))
                if line.startswith('#=GC'):
                    break
                id, seq = line.split()
                bin = seq_bins.get(id)
                if bin is None or bin not in bin_outputs:
                    continue
                bin_outputs[bin].write(line)
                bin_counts[bin] += 1

            # and then copy the footer.
            write_all([line])
            write_all(fobj)

    for fobj in bin_outputs.itervalues():
        fobj.close()

    # This is a bit nasty but I think it's Good Enough. We can change it if we
    # encounter problems or need to be more portable.
    if args.cmscores is not None:
        cmscores_proc = subprocess.Popen(
            ['romp', 'cmscores', '/dev/stdin'],
            stdin=subprocess.PIPE, stdout=args.cmscores)
        cmscores_args = [
            '--alignment-method', 'INFERNAL',
            '--stdout', '/dev/fd/%d' % (cmscores_proc.stdin.fileno(),)]
        cmscores_stdout = cmscores_proc.stdout
    else:
        cmscores_proc = None
        cmscores_args = []
        cmscores_stdout = open(os.devnull, 'w')

    for e, bin in enumerate(all_bins):
        log.info('classifying bin %s (%d/%d; %d seqs)',
                 bin, e + 1, len(all_bins), bin_counts[bin])
        input = binfile(bin)
        aligned = os.path.join(workdir, bin + '-aligned.sto')
        placed = os.path.join(workdir, bin + '.jplace')
        refpkg = os.path.join(args.hrefpkg, refpkg_map[bin])

        if args.alignment == 'align-each':
            logging_check_call(
                [args.refpkg_align, 'align', '--output-format', 'stockholm',
                 refpkg, input, aligned] + mpi_args + cmscores_args)
        elif args.alignment == 'merge-each':
            refpkg_obj = Refpkg(refpkg)
            logging_check_call(
                [args.cmalign, '--merge', '-o', aligned, '-1', '--hbanded',
                 '--sub', '--dna', refpkg_obj.resource_path('profile'),
                 refpkg_obj.resource_path('aln_sto'), input],
                stdout=cmscores_stdout)
        elif args.alignment == 'none':
            raise NotImplementedError('none')

        classifier_args, pplacer_args = [], []
        if args.classifier.startswith('nbc') or args.classifier.startswith('hybrid'):
            if '--no-pre-mask' not in args.classification_args:
                classifier_args.append('--no-pre-mask')
            classifier_args.extend(['--nbc-sequences', input])
        if args.post_prob:
            classifier_args.append('--pp')
            pplacer_args.extend(
                ['-p', '--inform-prior', '--prior-lower', '0.01'])

        logging_check_call(
            [args.pplacer, '--discard-nonoverlapped', '-c', refpkg,
             '-j', str(args.ncores), aligned, '-o', placed]
            + args.pplacer_args
            + pplacer_args)

        logging_check_call(
            [args.guppy, 'classify', '--sqlite', classif_db, '-c', refpkg, placed,
             '-j', str(args.ncores), '--classifier', args.classifier]
            + args.classification_args
            + classifier_args)

    if cmscores_proc is not None:
        cmscores_proc.communicate()

    log.info('cleaning up `multiclass` table')
    conn.rollback()
    curs = conn.cursor()
    curs.execute("""
        CREATE TEMPORARY TABLE classified AS
          SELECT name,
                 COUNT(DISTINCT run_id) n_runs
            FROM multiclass
                 JOIN placements USING (placement_id)
           GROUP BY name
          HAVING n_runs > 1
    """)
    curs.execute("SELECT name FROM classified WHERE n_runs > 2")
    too_many_classifications = [name for name, in curs]
    if too_many_classifications:
        raise ValueError("some sequences got classified more than twice",
                         too_many_classifications)
    curs.execute("""
        DELETE FROM multiclass
         WHERE (SELECT run_id
                  FROM placements p
                 WHERE p.placement_id = multiclass.placement_id) = 1
           AND name IN (SELECT name
                          FROM classified)
    """)
    conn.commit()

    shutil.copy(classif_db, args.classification_db)

main()