Source code

Download source archive ↓

upstream/tabular_to_fasta/tabular_to_fasta.py

1#!/usr/bin/env python
2"""
3Input: fasta, minimal length, maximal length
4Output: fasta
5Return sequences whose lengths are within the range.
6"""
7import os
8import sys
9
10
11def stop_err(msg):
12    sys.exit(msg)
13
14
15def __main__():
16    infile = sys.argv[1]
17    title_col = sys.argv[2]
18    seq_col = sys.argv[3]
19    outfile = sys.argv[4]
20
21    if title_col == None or title_col == 'None' or seq_col == None or seq_col == 'None':
22        stop_err("Columns not specified.")
23    try:
24        seq_col = int(seq_col) - 1
25    except:
26        stop_err("Invalid Sequence Column: %s." % str(seq_col))
27
28    title_col_list = title_col.split(',')
29    skipped_lines = 0
30    first_invalid_line = 0
31    invalid_line = ""
32    i = 0
33
34    with open(outfile, 'w') as out:
35        for i, line in enumerate(open(infile)):
36            error = False
37            line = line.rstrip('\r\n')
38            if line and not line.startswith('#'):
39                fields = line.split('\t')
40                fasta_title = []
41                for j in title_col_list:
42                    try:
43                        j = int(j) - 1
44                        fasta_title.append(fields[j])
45                    except:
46                        skipped_lines += 1
47                        if not invalid_line:
48                            first_invalid_line = i + 1
49                            invalid_line = line
50                        error = True
51                        break
52                if not error:
53                    try:
54                        fasta_seq = fields[seq_col]
55                        if fasta_title[0].startswith(">"):
56                            fasta_title[0] = fasta_title[0][1:]
57                        print(">%s\n%s" % ("_".join(fasta_title), fasta_seq), file=out)
58                    except:
59                        skipped_lines += 1
60                        if not invalid_line:
61                            first_invalid_line = i + 1
62                            invalid_line = line
63
64    if skipped_lines > 0:
65        print('Data issue: skipped %d blank or invalid lines starting at #%d: "%s"' % (skipped_lines, first_invalid_line, invalid_line))
66
67
68if __name__ == "__main__":
69    __main__()