-
Notifications
You must be signed in to change notification settings - Fork 4
/
normalize_abundance.py
78 lines (58 loc) · 2.54 KB
/
normalize_abundance.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
import argparse
import file_reader
def parse_args():
parser = argparse.ArgumentParser(
description=('Normalize the raw counts in the abundance file'))
parser.add_argument('--abundance-esp',
help='the *_abundance.esp file output by ESPRESSO',
required=True)
parser.add_argument('--output-path',
help='where to write the output file',
required=True)
return parser.parse_args()
def get_totals_by_sample(in_esp_path):
with open(in_esp_path, 'rt') as in_esp:
for line_i, line in enumerate(in_esp):
if line_i == 0:
initial_headers, sample_headers = (
file_reader.read_abundance_esp_header_line(line))
sample_totals = [0] * len(sample_headers)
continue
values = file_reader.read_abundance_esp_line(line, sample_headers)
for i, sample in enumerate(sample_headers):
sample_totals[i] += values[sample]
return sample_totals
def write_columns(out_f, columns):
str_columns = list()
for col in columns:
if isinstance(col, float):
str_val = '{:.2f}'.format(col)
else:
str_val = str(col)
str_columns.append(str_val)
out_f.write('{}\n'.format('\t'.join(str_columns)))
def write_normalized_esp(totals_by_sample, in_esp_path, out_path):
with open(in_esp_path, 'rt') as in_esp:
with open(out_path, 'wt') as out_esp:
for line_i, line in enumerate(in_esp):
if line_i == 0:
initial_headers, sample_headers = (
file_reader.read_abundance_esp_header_line(line))
write_columns(out_esp, initial_headers + sample_headers)
continue
values = file_reader.read_abundance_esp_line(
line, sample_headers)
cpms = list()
for sample_i, sample in enumerate(sample_headers):
sample_val = values[sample]
total = totals_by_sample[sample_i]
cpms.append((sample_val * 1e6) / total)
initial_columns = [values[h] for h in initial_headers]
write_columns(out_esp, initial_columns + cpms)
def main():
args = parse_args()
totals_by_sample = get_totals_by_sample(args.abundance_esp)
write_normalized_esp(totals_by_sample, args.abundance_esp,
args.output_path)
if __name__ == '__main__':
main()