Newer
Older
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
# SPDX-FileCopyrightText: Copyright © 2023 Idiap Research Institute <contact@idiap.ch>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for our CLI applications."""
import contextlib
import os
import re
from click.testing import CliRunner
@contextlib.contextmanager
def stdout_logging():
# copy logging messages to std out
import io
import logging
buf = io.StringIO()
ch = logging.StreamHandler(buf)
ch.setFormatter(logging.Formatter("%(message)s"))
ch.setLevel(logging.INFO)
logger = logging.getLogger("ptbench")
logger.addHandler(ch)
yield buf
logger.removeHandler(ch)
def _assert_exit_0(result):
assert (
result.exit_code == 0
), f"Exit code {result.exit_code} != 0 -- Output:\n{result.output}"
def _check_help(entry_point):
runner = CliRunner()
result = runner.invoke(entry_point, ["--help"])
_assert_exit_0(result)
assert result.output.startswith("Usage:")
def test_config_help():
from ptbench.scripts.config import config
_check_help(config)
def test_config_list_help():
from ptbench.scripts.config import list
_check_help(list)
def test_config_list():
from ptbench.scripts.config import list
runner = CliRunner()
result = runner.invoke(list)
_assert_exit_0(result)
assert "module: ptbench.configs.datasets" in result.output
assert "module: ptbench.configs.models" in result.output
def test_config_list_v():
from ptbench.scripts.config import list
result = CliRunner().invoke(list, ["--verbose"])
_assert_exit_0(result)
assert "module: ptbench.configs.datasets" in result.output
assert "module: ptbench.configs.models" in result.output
def test_config_describe_help():
from ptbench.scripts.config import describe
_check_help(describe)
def test_config_describe_montgomery():
from ptbench.scripts.config import describe
runner = CliRunner()
result = runner.invoke(describe, ["montgomery"])
_assert_exit_0(result)
assert "Montgomery dataset for TB detection" in result.output
def test_dataset_help():
from ptbench.scripts.dataset import dataset
_check_help(dataset)
def test_dataset_list_help():
from ptbench.scripts.dataset import list
_check_help(list)
def test_dataset_list():
from ptbench.scripts.dataset import list
runner = CliRunner()
result = runner.invoke(list)
_assert_exit_0(result)
assert result.output.startswith("Supported datasets:")
def test_dataset_check_help():
from ptbench.scripts.dataset import check
_check_help(check)
def test_dataset_check():
from ptbench.scripts.dataset import check
runner = CliRunner()
result = runner.invoke(check, ["--verbose", "--limit=2"])
_assert_exit_0(result)
def test_main_help():
from ptbench.scripts.cli import cli
_check_help(cli)
def test_train_help():
from ptbench.scripts.train import train
_check_help(train)
def _str_counter(substr, s):
return sum(1 for _ in re.finditer(substr, s, re.MULTILINE))
def test_predict_help():
from ptbench.scripts.predict import predict
_check_help(predict)
def test_predtojson_help():
from ptbench.scripts.predtojson import predtojson
_check_help(predtojson)
def test_aggregpred_help():
from ptbench.scripts.aggregpred import aggregpred
_check_help(aggregpred)
def test_evaluate_help():
from ptbench.scripts.evaluate import evaluate
_check_help(evaluate)
def test_compare_help():
from ptbench.scripts.compare import compare
_check_help(compare)

André Anjos
committed
def test_train_pasa_montgomery(temporary_basedir):
from ptbench.scripts.train import train

André Anjos
committed
runner = CliRunner()

André Anjos
committed
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "results")
result = runner.invoke(
train,
[
"pasa",
"montgomery",
"-vv",
"--epochs=1",
"--batch-size=1",
"--normalization=current",
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)

André Anjos
committed
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
assert os.path.exists(
os.path.join(output_folder, "model_final_epoch.pth")
)
assert os.path.exists(
os.path.join(output_folder, "model_lowest_valid_loss.pth")
)
assert os.path.exists(os.path.join(output_folder, "last_checkpoint"))
assert os.path.exists(os.path.join(output_folder, "constants.csv"))
assert os.path.exists(os.path.join(output_folder, "trainlog.csv"))
assert os.path.exists(os.path.join(output_folder, "model_summary.txt"))
keywords = {
r"^Found \(dedicated\) '__train__' set for training$": 1,
r"^Found \(dedicated\) '__valid__' set for validation$": 1,
r"^Continuing from epoch 0$": 1,
r"^Saving model summary at.*$": 1,
r"^Model has.*$": 1,
r"^Saving checkpoint": 2,
r"^Total training time:": 1,
r"^Z-normalization with mean": 1,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"

André Anjos
committed
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
def test_predict_pasa_montgomery(temporary_basedir, datadir):
from ptbench.scripts.predict import predict
runner = CliRunner()
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "predictions")
result = runner.invoke(
predict,
[
"pasa",
"montgomery",
"-vv",
"--batch-size=1",
"--relevance-analysis",
f"--weight={str(datadir / 'lfs' / 'models' / 'pasa.pth')}",
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
# check predictions are there
predictions_file1 = os.path.join(output_folder, "train/predictions.csv")
predictions_file2 = os.path.join(
output_folder, "validation/predictions.csv"
)
predictions_file3 = os.path.join(output_folder, "test/predictions.csv")
assert os.path.exists(predictions_file1)
assert os.path.exists(predictions_file2)
assert os.path.exists(predictions_file3)
keywords = {
r"^Loading checkpoint from.*$": 1,
r"^Total time:.*$": 3,
r"^Relevance analysis.*$": 3,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"

André Anjos
committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def test_predtojson(datadir, temporary_basedir):
from ptbench.scripts.predtojson import predtojson
runner = CliRunner()
with stdout_logging() as buf:
predictions = str(datadir / "test_predictions.csv")
output_folder = str(temporary_basedir / "pred_to_json")
result = runner.invoke(
predtojson,
[
"-vv",
"train",
f"{predictions}",
"test",
f"{predictions}",
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
# check json file is there
assert os.path.exists(os.path.join(output_folder, "dataset.json"))
keywords = {
f"Output folder: {output_folder}": 1,
r"Saving JSON file...": 1,
r"^Loading predictions from.*$": 2,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"

André Anjos
committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def test_evaluate_pasa_montgomery(temporary_basedir):
from ptbench.scripts.evaluate import evaluate
runner = CliRunner()
with stdout_logging() as buf:
prediction_folder = str(temporary_basedir / "predictions")
output_folder = str(temporary_basedir / "evaluations")
result = runner.invoke(
evaluate,
[
"-vv",
"montgomery",
f"--predictions-folder={prediction_folder}",
f"--output-folder={output_folder}",
"--threshold=train",
"--steps=2000",
],
)
_assert_exit_0(result)
# check evaluations are there
assert os.path.exists(os.path.join(output_folder, "test.csv"))
assert os.path.exists(os.path.join(output_folder, "train.csv"))
assert os.path.exists(
os.path.join(output_folder, "test_score_table.pdf")
)
assert os.path.exists(
os.path.join(output_folder, "train_score_table.pdf")
)
keywords = {
r"^Skipping dataset '__train__'": 1,
r"^Evaluating threshold on.*$": 1,
r"^Maximum F1-score of.*$": 4,
r"^Set --f1_threshold=.*$": 1,
r"^Set --eer_threshold=.*$": 1,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"

André Anjos
committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def test_compare_pasa_montgomery(temporary_basedir):
from ptbench.scripts.compare import compare
runner = CliRunner()
with stdout_logging() as buf:
predictions_folder = str(temporary_basedir / "predictions")
output_folder = str(temporary_basedir / "comparisons")
result = runner.invoke(
compare,
[
"-vv",
"train",
f"{predictions_folder}/train/predictions.csv",
"test",
f"{predictions_folder}/test/predictions.csv",
f"--output-figure={output_folder}/compare.pdf",
f"--output-table={output_folder}/table.txt",
"--threshold=0.5",
],
)
_assert_exit_0(result)
# check comparisons are there
assert os.path.exists(os.path.join(output_folder, "compare.pdf"))
assert os.path.exists(os.path.join(output_folder, "table.txt"))
keywords = {
r"^Dataset '\*': threshold =.*$": 1,
r"^Loading predictions from.*$": 2,
r"^Tabulating performance summary...": 1,
}
buf.seek(0)
logging_output = buf.read()

André Anjos
committed
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)
def test_train_signstotb_montgomery_rs(temporary_basedir, datadir):
from ptbench.scripts.train import train
runner = CliRunner()
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "results")
result = runner.invoke(
train,
[
"signs_to_tb",
"montgomery_rs",
"-vv",
"--epochs=1",
"--batch-size=1",
f"--weight={str(datadir / 'lfs' / 'models' / 'signstotb.pth')}",
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
assert os.path.exists(
os.path.join(output_folder, "model_final_epoch.pth")
)
assert os.path.exists(
os.path.join(output_folder, "model_lowest_valid_loss.pth")
)
assert os.path.exists(os.path.join(output_folder, "last_checkpoint"))
assert os.path.exists(os.path.join(output_folder, "constants.csv"))
assert os.path.exists(os.path.join(output_folder, "trainlog.csv"))
assert os.path.exists(os.path.join(output_folder, "model_summary.txt"))
keywords = {
r"^Found \(dedicated\) '__train__' set for training$": 1,
r"^Found \(dedicated\) '__valid__' set for validation$": 1,
r"^Continuing from epoch 0$": 1,
r"^Saving model summary at.*$": 1,
r"^Model has.*$": 1,
r"^Saving checkpoint": 2,
r"^Total training time:": 1,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)
def test_predict_signstotb_montgomery_rs(temporary_basedir, datadir):
from ptbench.scripts.predict import predict
runner = CliRunner()
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "predictions")
result = runner.invoke(
predict,
[
"signs_to_tb",
"montgomery_rs",
"-vv",
"--batch-size=1",
"--relevance-analysis",
f"--weight={str(datadir / 'lfs' / 'models' / 'signstotb.pth')}",
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
# check predictions are there
predictions_file = os.path.join(output_folder, "train/predictions.csv")
RA1 = os.path.join(output_folder, "train_RA.pdf")
RA2 = os.path.join(output_folder, "validation_RA.pdf")
RA3 = os.path.join(output_folder, "test_RA.pdf")
assert os.path.exists(predictions_file)
assert os.path.exists(RA1)
assert os.path.exists(RA2)
assert os.path.exists(RA3)
keywords = {
r"^Loading checkpoint from.*$": 1,
r"^Total time:.*$": 3 * 15,
r"^Starting relevance analysis for subset.*$": 3,
r"^Creating and saving plot at.*$": 3,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)
def test_train_logreg_montgomery_rs(temporary_basedir, datadir):
from ptbench.scripts.train import train
runner = CliRunner()
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "results")
result = runner.invoke(
train,
[
"logistic_regression",
"montgomery_rs",
"-vv",
"--epochs=1",
"--batch-size=1",
f"--weight={str(datadir / 'lfs' / 'models' / 'logreg.pth')}",
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
assert os.path.exists(
os.path.join(output_folder, "model_final_epoch.pth")
)
assert os.path.exists(
os.path.join(output_folder, "model_lowest_valid_loss.pth")
)
assert os.path.exists(os.path.join(output_folder, "last_checkpoint"))
assert os.path.exists(os.path.join(output_folder, "constants.csv"))
assert os.path.exists(os.path.join(output_folder, "trainlog.csv"))
assert os.path.exists(os.path.join(output_folder, "model_summary.txt"))
keywords = {
r"^Found \(dedicated\) '__train__' set for training$": 1,
r"^Found \(dedicated\) '__valid__' set for validation$": 1,
r"^Continuing from epoch 0$": 1,
r"^Saving model summary at.*$": 1,
r"^Model has.*$": 1,
r"^Saving checkpoint": 2,
r"^Total training time:": 1,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)
def test_predict_logreg_montgomery_rs(temporary_basedir, datadir):
from ptbench.scripts.predict import predict
runner = CliRunner()
with stdout_logging() as buf:
output_folder = str(temporary_basedir / "predictions")
result = runner.invoke(
predict,
[
"logistic_regression",
"montgomery_rs",
"-vv",
"--batch-size=1",
f"--weight={str(datadir / 'lfs' / 'models' / 'logreg.pth')}",
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)
# check predictions are there
predictions_file = os.path.join(output_folder, "train/predictions.csv")
wfile = os.path.join(output_folder, "LogReg_Weights.pdf")
assert os.path.exists(predictions_file)
assert os.path.exists(wfile)
keywords = {
r"^Loading checkpoint from.*$": 1,
r"^Total time:.*$": 3,
r"^Logistic regression identified: saving model weights.*$": 1,
}
buf.seek(0)
logging_output = buf.read()
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)

André Anjos
committed
def test_aggregpred(temporary_basedir):
from ptbench.scripts.aggregpred import aggregpred

André Anjos
committed
runner = CliRunner()

André Anjos
committed
with stdout_logging() as buf:
predictions = str(
temporary_basedir / "predictions" / "train" / "predictions.csv"
)
output_folder = str(temporary_basedir / "aggregpred")
result = runner.invoke(
aggregpred,
[
"-vv",
f"{predictions}",
f"{predictions}",
f"--output-folder={output_folder}",
],
)
_assert_exit_0(result)

André Anjos
committed
# check csv file is there
assert os.path.exists(os.path.join(output_folder, "aggregpred.csv"))

André Anjos
committed
keywords = {
f"Output folder: {output_folder}": 1,
r"Saving aggregated CSV file...": 1,
r"^Loading predictions from.*$": 2,
}
buf.seek(0)
logging_output = buf.read()

André Anjos
committed
for k, v in keywords.items():
assert _str_counter(k, logging_output) == v, (
f"Count for string '{k}' appeared "
f"({_str_counter(k, logging_output)}) "
f"instead of the expected {v}:\nOutput:\n{logging_output}"
)

André Anjos
committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# def test_predict_densenetrs_montgomery(temporary_basedir, datadir):
# from ptbench.scripts.predict import predict
# runner = CliRunner()
# with stdout_logging() as buf:
# output_folder = str(temporary_basedir / "predictions")
# result = runner.invoke(
# predict,
# [
# "densenet_rs",
# "montgomery_f0_rgb",
# "-vv",
# "--batch-size=1",
# f"--weight={str(datadir / 'lfs' / 'models' / 'densenetrs.pth')}",
# f"--output-folder={output_folder}",
# "--grad-cams"
# ],
# )
# _assert_exit_0(result)
# # check predictions are there
# predictions_file1 = os.path.join(output_folder, "train/predictions.csv")
# predictions_file2 = os.path.join(output_folder, "validation/predictions.csv")
# predictions_file3 = os.path.join(output_folder, "test/predictions.csv")
# assert os.path.exists(predictions_file1)
# assert os.path.exists(predictions_file2)
# assert os.path.exists(predictions_file3)
# # check some grad cams are there
# cam1 = os.path.join(output_folder, "train/cams/MCUCXR_0002_0_cam.png")
# cam2 = os.path.join(output_folder, "train/cams/MCUCXR_0126_1_cam.png")
# cam3 = os.path.join(output_folder, "train/cams/MCUCXR_0275_1_cam.png")
# cam4 = os.path.join(output_folder, "validation/cams/MCUCXR_0399_1_cam.png")
# cam5 = os.path.join(output_folder, "validation/cams/MCUCXR_0113_1_cam.png")
# cam6 = os.path.join(output_folder, "validation/cams/MCUCXR_0013_0_cam.png")
# cam7 = os.path.join(output_folder, "test/cams/MCUCXR_0027_0_cam.png")
# cam8 = os.path.join(output_folder, "test/cams/MCUCXR_0094_0_cam.png")
# cam9 = os.path.join(output_folder, "test/cams/MCUCXR_0375_1_cam.png")
# assert os.path.exists(cam1)
# assert os.path.exists(cam2)
# assert os.path.exists(cam3)
# assert os.path.exists(cam4)
# assert os.path.exists(cam5)
# assert os.path.exists(cam6)
# assert os.path.exists(cam7)
# assert os.path.exists(cam8)
# assert os.path.exists(cam9)
# keywords = {
# r"^Loading checkpoint from.*$": 1,
# r"^Total time:.*$": 3,
# r"^Grad cams folder:.*$": 3,
# }
# buf.seek(0)
# logging_output = buf.read()
# for k, v in keywords.items():
# assert _str_counter(k, logging_output) == v, (
# f"Count for string '{k}' appeared "
# f"({_str_counter(k, logging_output)}) "
# f"instead of the expected {v}:\nOutput:\n{logging_output}"
# )