-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.py
236 lines (192 loc) · 7.39 KB
/
main.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
#!/usr/bin/env python
import argparse
import logging
import multiprocessing
import signal
import sys
import traceback
from pathlib import Path
import coloredlogs
from croissance import GrowthEstimationParameters, estimate_growth
from croissance.estimation.util import normalize_time_unit
from croissance.figures.writer import PDFWriter
from croissance.formats.input import TSVReader
from croissance.formats.output import TSVWriter
class EstimatorWrapper:
def __init__(self, args):
self.params = GrowthEstimationParameters()
self.params.constrain_n0 = args.constrain_N0
self.params.segment_log_n0 = args.segment_log_N0
self.params.n0 = args.N0
self.params.phase_minimum_signal_noise_ratio = (
args.phase_minimum_signal_to_noise
)
self.params.phase_minimum_duration_hours = args.phase_minimum_duration
self.params.phase_minimum_slope = args.phase_minimum_slope
self.input_time_unit = args.input_time_unit
def __call__(self, values):
filepath, idx, name, curve = values
try:
normalized_curve = normalize_time_unit(curve, self.input_time_unit)
annotated_curve = estimate_growth(
normalized_curve,
params=self.params,
name=name,
)
return (filepath, idx, name, annotated_curve)
except Exception:
log = logging.getLogger("croissance")
log.error("Unhandled exception while annotating %r:", name)
for line in traceback.format_exc().splitlines():
log.error("%s", line)
def init_worker():
# Ensure that KeyboardInterrupt exceptions only occur in the main thread
signal.signal(signal.SIGINT, signal.SIG_IGN)
def parse_args(argv):
parser = argparse.ArgumentParser(
description="Estimate growth rates in growth curves",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("infiles", type=Path, nargs="+")
parser.add_argument(
"--threads",
type=int,
default=1,
help="Max number of threads to use during growth estimation",
)
group = parser.add_argument_group("Input")
group.add_argument("--input-format", type=str.lower, choices=("tsv",))
group.add_argument(
"--input-time-unit",
default="hours",
choices=("hours", "minutes"),
help="Time unit in time column",
)
group = parser.add_argument_group("Output")
group.add_argument("--output-format", type=str.lower, choices=("tsv",))
group.add_argument(
"--output-suffix",
type=str,
default=".output",
help="Suffix used for output files in addition to the file extension. By "
"default, an input file `file.tsv` will result in output files named `file. "
"output.tsv` and `file.output.pdf`",
)
group.add_argument(
"--output-exclude-default-phase",
action="store_true",
help="Do not output phase '0' for each curve",
)
group.add_argument(
"--figures",
action="store_true",
help="Renders a PDF file with figures for each curve",
)
group.add_argument(
"--figures-yscale",
type=str.lower,
default="both",
choices=("log", "linear", "both"),
help="Yscale(s) for figures. If both, then two plots are generated per curve",
)
defaults = GrowthEstimationParameters()
group = parser.add_argument_group("Growth model")
group.add_argument(
"--N0",
type=float,
default=defaults.n0,
help="Baseline for constrained regressions and identifying curve segments in "
"log space",
)
group.add_argument(
"--constrain-N0",
action="store_true",
help="All growth phases will begin at N0 when this flag is set",
)
group.add_argument(
"--segment-log-N0",
action="store_true",
help="Identify curve segments using log(N-N0) rather than N; increases "
"sensitivity to changes in exponential growth but has to assume a certain N0",
)
group.add_argument(
"--phase-minimum-signal-to-noise",
type=float,
metavar="SNR",
default=defaults.phase_minimum_signal_noise_ratio,
help="Minimum phase signal-to-noise ratio",
)
group.add_argument(
"--phase-minimum-duration",
type=float,
metavar="HOURS",
default=defaults.phase_minimum_duration_hours,
help="Minimum duration of phases in hours",
)
group.add_argument(
"--phase-minimum-slope",
type=float,
metavar="SLOPE",
default=defaults.phase_minimum_slope,
help="Minimum phase slope",
)
group = parser.add_argument_group("Logging")
group.add_argument(
"--log-level",
type=str.upper,
default="INFO",
choices=("DEBUG", "INFO", "WARNING", "ERROR"),
help="Set verbosity of log messages",
)
return parser.parse_args(argv)
def setup_logging(level):
coloredlogs.install(
fmt="%(asctime)s %(name)s %(levelname)s %(message)s",
level=level,
)
return logging.getLogger("croissance")
def main(argv):
args = parse_args(argv)
log = setup_logging(level=args.log_level)
curves = []
for filepath in args.infiles:
log.info("Reading curves from '%s", filepath)
with TSVReader(filepath) as reader:
for idx, (name, curve) in enumerate(reader.read()):
if curve.empty:
log.warning("Skipping empty curve %r", name)
continue
curves.append((filepath, idx, name, curve))
log.info("Collected a total of %i growth curves", len(curves))
# Dont spawn more processes than tasks
args.threads = max(1, min(args.threads, len(curves)))
log.info("Annotating growth curves using %i threads", args.threads)
return_code = 0
annotated_curves = {filepath: [] for filepath in args.infiles}
with multiprocessing.Pool(processes=args.threads, initializer=init_worker) as pool:
async_calculation = pool.imap_unordered(EstimatorWrapper(args), curves)
for nth, result in enumerate(async_calculation, start=1):
if result is None:
return_code = 1
continue
(filepath, idx, name, curve) = result
log.info("Annotated curve %i of %i: %s", nth, len(curves), name)
annotated_curves[filepath].append((idx, name, curve))
for filepath in args.infiles:
output_filepath = filepath.with_suffix(args.output_suffix + ".tsv")
log.info("Writing annotated curves to '%s'", output_filepath)
with TSVWriter(output_filepath, args.output_exclude_default_phase) as outwriter:
for _, name, annotated_curve in sorted(annotated_curves[filepath]):
outwriter.write(name, annotated_curve)
if args.figures:
figure_filepath = filepath.with_suffix(args.output_suffix + ".pdf")
log.info("Writing PDFs to '%s'", figure_filepath)
with PDFWriter(figure_filepath, yscale=args.figures_yscale) as figwriter:
for _, name, annotated_curve in sorted(annotated_curves[filepath]):
figwriter.write(name, annotated_curve)
log.info("Done ..")
return return_code
def entry_point():
sys.exit(main(sys.argv[1:]))
if __name__ == "__main__":
entry_point()