/
test_tax_utils.py
3270 lines (2716 loc) · 148 KB
/
test_tax_utils.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
357
358
359
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tests for functions in taxonomy submodule.
"""
import pytest
from pytest import approx
import os
from os.path import basename
import gzip
from pathlib import Path
import sourmash_tst_utils as utils
from sourmash.tax.tax_utils import (ascending_taxlist, get_ident, load_gather_results,
collect_gather_csvs, check_and_load_gather_csvs,
LineagePair, QueryInfo, GatherRow, TaxResult, QueryTaxResult,
SummarizedGatherResult, ClassificationResult, AnnotateTaxResult,
BaseLineageInfo, RankLineageInfo, LINLineageInfo,
aggregate_by_lineage_at_rank, format_for_krona,
write_krona, write_lineage_sample_frac, read_lingroups,
LineageTree, LineageDB, LineageDB_Sqlite, MultiLineageDB)
# utility functions for testing
def make_mini_taxonomy(tax_info, LIN=False):
#pass in list of tuples: (name, lineage)
taxD = {}
for (name, lin) in tax_info:
if LIN:
lineage = LINLineageInfo(lineage_str=lin)
else:
lineage = RankLineageInfo(lineage_str=lin)
taxD[name] = lineage.filled_lineage
return taxD
def make_mini_taxonomy_with_taxids(tax_info, LIN=False):
taxD = {}
for (name, lin, taxids) in tax_info:
if LIN:
lineage = LINLineageInfo(lineage_str=lin)
else:
ranks = RankLineageInfo.ranks
txs = taxids.split(';')
lns = lin.split(';')
lineage_tups = []
for n, taxname in enumerate(lns):
rk = ranks[n]
tx = txs[n]
this_lineage = LineagePair(rk, name=taxname, taxid=tx)
lineage_tups.append(this_lineage)
lineage = RankLineageInfo(lineage=lineage_tups)
taxD[name] = lineage.filled_lineage
return taxD
def make_GatherRow(gather_dict=None, exclude_cols=[]):
"""Load artificial gather row (dict) into GatherRow class"""
# default contains just the essential cols
gatherD = {'query_name': 'q1',
'query_md5': 'md5',
'query_filename': 'query_fn',
'name': 'gA',
'f_unique_weighted': 0.2,
'f_unique_to_query': 0.1,
'query_bp':100,
'unique_intersect_bp': 20,
'remaining_bp': 1,
'ksize': 31,
'scaled': 1}
if gather_dict is not None:
gatherD.update(gather_dict)
for col in exclude_cols:
gatherD.pop(col)
gatherRaw = GatherRow(**gatherD)
return gatherRaw
def make_TaxResult(gather_dict=None, taxD=None, keep_full_ident=False, keep_ident_version=False, skip_idents=None, LIN=False):
"""Make TaxResult from artificial gather row (dict)"""
gRow = make_GatherRow(gather_dict)
taxres = TaxResult(raw=gRow, keep_full_identifiers=keep_full_ident,
keep_identifier_versions=keep_ident_version, lins=LIN)
if taxD is not None:
taxres.get_match_lineage(tax_assignments=taxD, skip_idents=skip_idents)
return taxres
def make_QueryTaxResults(gather_info, taxD=None, single_query=False, keep_full_ident=False, keep_ident_version=False,
skip_idents=None, summarize=False, classify=False, classify_rank=None, c_thresh=0.1, ani_thresh=None,
LIN=False):
"""Make QueryTaxResult(s) from artificial gather information, formatted as list of gather rows (dicts)"""
gather_results = {}
this_querytaxres = None
for gather_infoD in gather_info:
taxres = make_TaxResult(gather_infoD, taxD=taxD, keep_full_ident=keep_full_ident,
keep_ident_version=keep_ident_version, skip_idents=skip_idents, LIN=LIN)
query_name = taxres.query_name
# add to matching QueryTaxResult or create new one
if not this_querytaxres or not this_querytaxres.is_compatible(taxres):
# get existing or initialize new
this_querytaxres = gather_results.get(query_name, QueryTaxResult(taxres.query_info, lins=LIN))
this_querytaxres.add_taxresult(taxres)
# print('missed_ident?', taxres.missed_ident)
gather_results[query_name] = this_querytaxres
if summarize:
for query_name, qres in gather_results.items():
qres.build_summarized_result()
if classify:
for query_name, qres in gather_results.items():
qres.build_classification_result(rank=classify_rank, containment_threshold=c_thresh, ani_threshold=ani_thresh)
# for convenience: If working with single query, just return that QueryTaxResult.
if single_query:
if len(gather_results.keys()) > 1:
raise ValueError("You passed in results for more than one query")
else:
return next(iter(gather_results.values()))
return gather_results
## tests
def test_ascending_taxlist_1():
assert list(ascending_taxlist()) == ['strain', 'species', 'genus', 'family', 'order', 'class', 'phylum', 'superkingdom']
def test_ascending_taxlist_2():
assert list(ascending_taxlist(include_strain=False)) == ['species', 'genus', 'family', 'order', 'class', 'phylum', 'superkingdom']
def test_QueryInfo_basic():
"basic functionality of QueryInfo dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
assert qInf.query_name == 'q1'
assert isinstance(qInf.query_n_hashes, int)
assert isinstance(qInf.ksize, int)
assert isinstance(qInf.scaled, int)
assert qInf.total_weighted_hashes == 200
assert qInf.total_weighted_bp == 2000
def test_QueryInfo_no_hash_info():
"QueryInfo dataclass for older gather results without query_n_hashes or total_weighted_hashes"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',ksize=31,scaled=10)
assert qInf.query_name == 'q1'
assert qInf.query_n_hashes == 0
assert qInf.total_weighted_hashes == 0
assert qInf.total_weighted_bp == 0
def test_QueryInfo_missing():
"check that required args"
with pytest.raises(TypeError) as exc:
QueryInfo(query_name='q1', query_filename='f1',query_bp='100',query_n_hashes='10',ksize=31,scaled=10, total_weighted_hashes=200)
print(str(exc))
assert "missing 1 required positional argument: 'query_md5'" in str(exc)
def test_SummarizedGatherResult():
"basic functionality of SummarizedGatherResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
print(sgr)
assert sgr.rank=='phylum'
sumD = sgr.as_summary_dict(query_info=qInf)
print(sumD)
assert sumD == {'rank': 'phylum', 'fraction': "0.2", 'lineage': 'a;b', 'f_weighted_at_rank': "0.3",
'bp_match_at_rank': "30", 'query_ani_at_rank': None, 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
hD = sgr.as_human_friendly_dict(query_info=qInf)
print(hD)
assert hD == {'rank': 'phylum', 'fraction': '0.200', 'lineage': 'a;b', 'f_weighted_at_rank': '30.0%',
'bp_match_at_rank': "30", 'query_ani_at_rank': '- ', 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
krD = sgr.as_kreport_dict(query_info=qInf)
print(krD)
assert krD == {'ncbi_taxid': None, 'sci_name': 'b', 'rank_code': 'P', 'num_bp_assigned': "0",
'percent_containment': '30.00', 'num_bp_contained': "600"}
lD = sgr.as_lineage_dict(ranks = RankLineageInfo().ranks, query_info=qInf)
print(lD)
assert lD == {'ident': 'q1', 'superkingdom': 'a', 'phylum': 'b', 'class': '', 'order': '',
'family': '', 'genus': '', 'species': '', 'strain': ''}
cami = sgr.as_cami_bioboxes()
print(cami)
assert cami == [None, 'phylum', None, 'a|b', '30.00']
def test_SummarizedGatherResult_withtaxids():
"basic functionality of SummarizedGatherResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
lin = [LineagePair(rank='superkingdom', name='a', taxid='1'), LineagePair(rank='phylum', name='b', taxid=2)]
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage=lin),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
print(sgr)
assert sgr.rank=='phylum'
sumD = sgr.as_summary_dict(query_info=qInf)
print(sumD)
assert sumD == {'rank': 'phylum', 'fraction': "0.2", 'lineage': 'a;b', 'f_weighted_at_rank': "0.3",
'bp_match_at_rank': "30", 'query_ani_at_rank': None, 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
hD = sgr.as_human_friendly_dict(query_info=qInf)
print(hD)
assert hD == {'rank': 'phylum', 'fraction': '0.200', 'lineage': 'a;b', 'f_weighted_at_rank': '30.0%',
'bp_match_at_rank': "30", 'query_ani_at_rank': '- ', 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
krD = sgr.as_kreport_dict(query_info=qInf)
print(krD)
assert krD == {'ncbi_taxid': '2', 'sci_name': 'b', 'rank_code': 'P', 'num_bp_assigned': "0",
'percent_containment': '30.00', 'num_bp_contained': "600"}
lD = sgr.as_lineage_dict(ranks = RankLineageInfo().ranks, query_info=qInf)
print(lD)
assert lD == {'ident': 'q1', 'superkingdom': 'a', 'phylum': 'b', 'class': '', 'order': '',
'family': '', 'genus': '', 'species': '', 'strain': ''}
cami = sgr.as_cami_bioboxes()
print(cami)
assert cami == ['2', 'phylum', '1|2', 'a|b', '30.00']
def test_SummarizedGatherResult_LINs():
"SummarizedGatherResult with LINs"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=LINLineageInfo(lineage_str="0;0;1"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
lgD = sgr.as_lingroup_dict(query_info=qInf, lg_name="lg_name")
print(lgD)
assert lgD == {'name': "lg_name", "lin": "0;0;1",
'percent_containment': '30.00', 'num_bp_contained': "600"}
lgD = sgr.as_lingroup_dict(query_info=qInf, lg_name="lg_name")
print(lgD)
assert lgD == {'name': "lg_name", "lin": "0;0;1",
'percent_containment': '30.00', 'num_bp_contained': "600"}
with pytest.raises(ValueError) as exc:
sgr.as_kreport_dict(query_info=qInf)
print(str(exc))
assert "Cannot produce 'kreport' with LIN taxonomy." in str(exc)
with pytest.raises(ValueError) as exc:
sgr.as_cami_bioboxes()
print(str(exc))
assert "Cannot produce 'bioboxes' with LIN taxonomy." in str(exc)
def test_SummarizedGatherResult_set_query_ani():
"Check ANI estimation within SummarizedGatherResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
sgr.set_query_ani(query_info=qInf)
print(sgr.query_ani_at_rank)
assert sgr.query_ani_at_rank == approx(0.949, rel=1e-3)
# ANI can be calculated with query_bp OR query_n_hashes. Remove each and check the results are identical
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes=0,ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
sgr.set_query_ani(query_info=qInf)
print(sgr.query_ani_at_rank)
assert sgr.query_ani_at_rank == approx(0.949, rel=1e-3)
# try without query_bp
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp=0,
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
sgr.set_query_ani(query_info=qInf)
print(sgr.query_ani_at_rank)
assert sgr.query_ani_at_rank == approx(0.949, rel=1e-3)
def test_SummarizedGatherResult_greater_than_1():
"basic functionality of SummarizedGatherResult dataclass"
# fraction > 1
with pytest.raises(ValueError) as exc:
SummarizedGatherResult(rank="phylum", fraction=0.3, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=1.2, bp_match_at_rank=30)
print(str(exc))
assert "> 100% of the query!" in str(exc)
# f_weighted > 1
with pytest.raises(ValueError) as exc:
SummarizedGatherResult(rank="phylum", fraction=1.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
print(str(exc))
assert "> 100% of the query!" in str(exc)
def test_SummarizedGatherResult_0_fraction():
with pytest.raises(ValueError) as exc:
SummarizedGatherResult(rank="phylum", fraction=-.1, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
err_msg = "Summarized fraction is <=0% of the query! This should not occur."
assert err_msg in str(exc)
#assert cr.status == 'nomatch'
with pytest.raises(ValueError) as exc:
SummarizedGatherResult(rank="phylum", fraction=.1, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0, bp_match_at_rank=30)
print(str(exc))
assert err_msg in str(exc)
def test_SummarizedGatherResult_species_kreport():
"basic functionality of SummarizedGatherResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="species", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b;c;d;e;f;g"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
print(sgr)
assert sgr.rank=='species'
krD = sgr.as_kreport_dict(query_info=qInf)
print(krD)
assert krD == {'ncbi_taxid': None, 'sci_name': 'g', 'rank_code': 'S', 'num_bp_assigned': "600",
'percent_containment': '30.00', 'num_bp_contained': "600"}
def test_SummarizedGatherResult_summary_dict_limit_float():
"basic functionality of SummarizedGatherResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
sgr = SummarizedGatherResult(rank="phylum", fraction=0.123456, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.345678, bp_match_at_rank=30)
print(sgr)
assert sgr.rank=='phylum'
sumD = sgr.as_summary_dict(query_info=qInf)
print(sumD)
assert sumD == {'rank': 'phylum', 'fraction': "0.123456", 'lineage': 'a;b', 'f_weighted_at_rank': "0.345678",
'bp_match_at_rank': "30", 'query_ani_at_rank': None, 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
sumD = sgr.as_summary_dict(query_info=qInf, limit_float=True)
print(sumD)
assert sumD == {'rank': 'phylum', 'fraction': "0.123", 'lineage': 'a;b', 'f_weighted_at_rank': "0.346",
'bp_match_at_rank': "30", 'query_ani_at_rank': None, 'query_name': 'q1',
'query_md5': 'md5', 'query_filename': 'f1', 'total_weighted_hashes': "200"}
def test_ClassificationResult():
"basic functionality of ClassificationResult dataclass"
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
cr = ClassificationResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30, query_ani_at_rank=0.97)
cr.set_status(query_info=qInf, containment_threshold=0.1)
assert cr.status == 'match'
print(cr.query_ani_at_rank)
assert cr.query_ani_at_rank == approx(0.949, rel=1e-3)
cr.set_status(query_info=qInf, containment_threshold=0.35)
assert cr.status == 'below_threshold'
lD = cr.as_lineage_dict(ranks = RankLineageInfo().ranks, query_info=qInf)
print(lD)
assert lD == {'ident': 'q1', 'superkingdom': 'a', 'phylum': 'b', 'class': '', 'order': '',
'family': '', 'genus': '', 'species': '', 'strain': ''}
def test_ClassificationResult_greater_than_1():
"basic functionality of SummarizedGatherResult dataclass"
# fraction > 1
with pytest.raises(ValueError) as exc:
ClassificationResult(rank="phylum", fraction=0.3, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=1.2, bp_match_at_rank=30)
print(str(exc))
assert "> 100% of the query!" in str(exc)
# f_weighted > 1
with pytest.raises(ValueError) as exc:
ClassificationResult(rank="phylum", fraction=1.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
print(str(exc))
assert "> 100% of the query!" in str(exc)
def test_ClassificationResult_0_fraction():
with pytest.raises(ValueError) as exc:
ClassificationResult(rank="phylum", fraction=-.1, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30)
err_msg = "Summarized fraction is <=0% of the query! This should not occur."
assert err_msg in str(exc)
#assert cr.status == 'nomatch'
with pytest.raises(ValueError) as exc:
ClassificationResult(rank="phylum", fraction=.1, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0, bp_match_at_rank=30)
print(str(exc))
assert err_msg in str(exc)
def test_ClassificationResult_build_krona_result():
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
cr = ClassificationResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30, query_ani_at_rank=0.97)
#cr.set_status(query_info=qInf, rank='phylum')
kr, ukr = cr.build_krona_result(rank='phylum')
print(kr)
assert kr == (0.2, 'a', 'b')
print(ukr)
assert ukr == (0.8, 'unclassified', 'unclassified')
def test_ClassificationResult_build_krona_result_no_rank():
qInf = QueryInfo(query_name='q1', query_md5='md5', query_filename='f1',query_bp='100',
query_n_hashes='10',ksize='31',scaled='10', total_weighted_hashes='200')
cr = ClassificationResult(rank="phylum", fraction=0.2, lineage=RankLineageInfo(lineage_str="a;b"),
f_weighted_at_rank=0.3, bp_match_at_rank=30, query_ani_at_rank=0.97)
cr.set_status(query_info=qInf, containment_threshold=0.1)
def test_GatherRow_old_gather():
# gather does not contain query_name column
gA = {"name": "gA.1 name"}
with pytest.raises(TypeError) as exc:
make_GatherRow(gA, exclude_cols=['query_bp'])
print(str(exc))
assert "__init__() missing 1 required positional argument: 'query_bp'" in str(exc)
def test_get_ident_default():
ident = "GCF_001881345.1"
n_id = get_ident(ident)
assert n_id == "GCF_001881345"
def test_TaxResult_get_ident_default():
gA = {"name": "GCF_001881345.1"} # gather result with match name as GCF_001881345.1
taxres = make_TaxResult(gA)
print(taxres.match_ident)
assert taxres.match_ident == "GCF_001881345"
def test_AnnotateTaxResult_get_ident_default():
gA = {"name": "GCF_001881345.1"} # gather result with match name as GCF_001881345.1
taxres = AnnotateTaxResult(raw=gA)
print(taxres.match_ident)
assert taxres.match_ident == "GCF_001881345"
def test_AnnotateTaxResult_get_ident_idcol():
gA = {"name": "n1", "match_name": "n2", "ident": "n3", "accession": "n4"} # gather result with match name as GCF_001881345.1
taxres = AnnotateTaxResult(raw=gA)
print(taxres.match_ident)
assert taxres.match_ident == "n1"
taxres = AnnotateTaxResult(raw=gA, id_col="match_name")
print(taxres.match_ident)
assert taxres.match_ident == "n2"
taxres = AnnotateTaxResult(raw=gA, id_col="ident")
print(taxres.match_ident)
assert taxres.match_ident == "n3"
taxres = AnnotateTaxResult(raw=gA, id_col="accession")
print(taxres.match_ident)
assert taxres.match_ident == "n4"
def test_AnnotateTaxResult_get_ident_idcol_fail():
gA = {"name": "n1", "match_name": "n2", "ident": "n3", "accession": "n4"} # gather result with match name as GCF_001881345.1
with pytest.raises(ValueError) as exc:
AnnotateTaxResult(raw=gA, id_col="NotACol")
print(str(exc))
assert "ID column 'NotACol' not found." in str(exc)
def test_get_ident_split_but_keep_version():
ident = "GCF_001881345.1 secondname"
n_id = get_ident(ident, keep_identifier_versions=True)
assert n_id == "GCF_001881345.1"
def test_TaxResult_get_ident_split_but_keep_version():
gA = {"name": "GCF_001881345.1 secondname"}
taxres = make_TaxResult(gA, keep_ident_version=True)
print("raw ident: ", taxres.raw.name)
print("keep_full?: ", taxres.keep_full_identifiers)
print("keep_version?: ",taxres.keep_identifier_versions)
print("final ident: ", taxres.match_ident)
assert taxres.match_ident == "GCF_001881345.1"
def test_AnnotateTaxResult_get_ident_split_but_keep_version():
gA = {"name": "GCF_001881345.1 secondname"}
taxres = AnnotateTaxResult(gA, keep_identifier_versions=True)
print("raw ident: ", taxres.raw['name'])
print("keep_full?: ", taxres.keep_full_identifiers)
print("keep_version?: ",taxres.keep_identifier_versions)
print("final ident: ", taxres.match_ident)
assert taxres.match_ident == "GCF_001881345.1"
def test_get_ident_no_split():
ident = "GCF_001881345.1 secondname"
n_id = get_ident(ident, keep_full_identifiers=True)
assert n_id == "GCF_001881345.1 secondname"
def test_TaxResult_get_ident_keep_full():
gA = {"name": "GCF_001881345.1 secondname"}
taxres = make_TaxResult(gA, keep_full_ident=True)
print("raw ident: ", taxres.raw.name)
print("keep_full?: ", taxres.keep_full_identifiers)
print("keep_version?: ",taxres.keep_identifier_versions)
print("final ident: ", taxres.match_ident)
assert taxres.match_ident == "GCF_001881345.1 secondname"
def test_AnnotateTaxResult_get_ident_keep_full():
gA = {"name": "GCF_001881345.1 secondname"}
taxres = AnnotateTaxResult(gA, keep_full_identifiers=True)
print("raw ident: ", taxres.raw['name'])
print("keep_full?: ", taxres.keep_full_identifiers)
print("keep_version?: ",taxres.keep_identifier_versions)
print("final ident: ", taxres.match_ident)
assert taxres.match_ident == "GCF_001881345.1 secondname"
def test_collect_gather_csvs(runtmp):
g_csv = utils.get_test_data('tax/test1.gather.csv')
from_file = runtmp.output("tmp-from-file.txt")
with open(from_file, 'w') as fp:
fp.write(f"{g_csv}\n")
gather_files = collect_gather_csvs([g_csv], from_file=from_file)
print("gather_files: ", gather_files)
assert len(gather_files) == 1
assert basename(gather_files[0]) == 'test1.gather.csv'
def test_check_and_load_gather_csvs_empty(runtmp):
g_res = runtmp.output('empty.gather.csv')
with open(g_res, 'w') as fp:
fp.write("")
csvs = [g_res]
# load taxonomy csv
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv], keep_full_identifiers=1)
print(tax_assign)
# check gather results and missing ids
with pytest.raises(Exception) as exc:
check_and_load_gather_csvs(csvs, tax_assign)
assert "Cannot read gather results from" in str(exc.value)
def test_check_and_load_gather_csvs_with_empty_force(runtmp):
g_csv = utils.get_test_data('tax/test1.gather.csv')
# make gather results with taxonomy name not in tax_assign
g_res2 = runtmp.output('gA.gather.csv')
g_results = [x.replace("GCF_001881345.1", "gA") + "\n" for x in Path(g_csv).read_text().splitlines()]
with open(g_res2, 'w') as fp:
fp.writelines(g_results)
# make empty gather results
g_res3 = runtmp.output('empty.gather.csv')
with open(g_res3, 'w') as fp:
fp.write("")
csvs = [g_res2, g_res3]
# load taxonomy csv
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv],
keep_full_identifiers=False,
keep_identifier_versions=False)
print(tax_assign)
# check gather results and missing ids
gather_results = check_and_load_gather_csvs(csvs, tax_assign, force=True)
assert len(gather_results) == 1
q_res = gather_results[0]
assert len(q_res.raw_taxresults) == 4
assert q_res.n_missed == 1
assert 'gA' in q_res.missed_idents
assert q_res.n_skipped == 0
def test_check_and_load_gather_lineage_csvs_empty(runtmp):
# try loading an empty annotated gather file
g_res = runtmp.output('empty.gather-tax.csv')
with open(g_res, 'w') as fp:
fp.write("")
with pytest.raises(ValueError) as exc:
tax_assign = LineageDB.load_from_gather_with_lineages(g_res)
assert "cannot read taxonomy assignments" in str(exc.value)
def test_check_and_load_gather_lineage_csvs_bad_header(runtmp):
# test on file with wrong headers
g_res = runtmp.output('empty.gather-tax.csv')
with open(g_res, 'w', newline="") as fp:
fp.write("x,y,z")
with pytest.raises(ValueError) as exc:
tax_assign = LineageDB.load_from_gather_with_lineages(g_res)
assert "Expected headers 'name' and 'lineage' not found. Is this a with-lineages file?" in str(exc.value)
def test_check_and_load_gather_lineage_csvs_dne(runtmp):
# test loading with-lineage file that does not exist
g_res = runtmp.output('empty.gather-tax.csv')
with pytest.raises(ValueError) as exc:
tax_assign = LineageDB.load_from_gather_with_lineages(g_res)
assert "does not exist" in str(exc.value)
def test_check_and_load_gather_lineage_csvs_isdir(runtmp):
# test loading a with-lineage file that is actually a directory
g_res = runtmp.output('empty.gather-tax.csv')
os.mkdir(g_res)
with pytest.raises(ValueError) as exc:
tax_assign = LineageDB.load_from_gather_with_lineages(g_res)
assert "is a directory" in str(exc.value)
def test_check_and_load_gather_csvs_fail_on_missing(runtmp):
g_csv = utils.get_test_data('tax/test1.gather.csv')
# make gather results with taxonomy name not in tax_assign
g_res2 = runtmp.output('gA.gather.csv')
g_results = [x.replace("GCF_001881345.1", "gA") + "\n" for x in Path(g_csv).read_text().splitlines()]
with open(g_res2, 'w') as fp:
fp.writelines(g_results)
csvs = [g_res2]
# load taxonomy csv
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv], keep_full_identifiers=1)
print(tax_assign)
# check gather results and missing ids
with pytest.raises(ValueError) as exc:
check_and_load_gather_csvs(csvs, tax_assign, fail_on_missing_taxonomy=True, force=True)
assert "Failing, as requested via --fail-on-missing-taxonomy" in str(exc)
def test_load_gather_results():
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv],
keep_full_identifiers=False,
keep_identifier_versions=False)
gather_csv = utils.get_test_data('tax/test1.gather.csv')
gather_results, header = load_gather_results(gather_csv, tax_assignments=tax_assign)
assert len(gather_results) == 1
for query_name, res in gather_results.items():
assert query_name == 'test1'
assert len(res.raw_taxresults) == 4
def test_load_gather_results_gzipped(runtmp):
gather_csv = utils.get_test_data('tax/test1.gather.csv')
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv],
keep_full_identifiers=False,
keep_identifier_versions=False)
gather_csv = utils.get_test_data('tax/test1.gather.csv')
# rewrite gather_csv as gzipped csv
gz_gather = runtmp.output('g.csv.gz')
with open(gather_csv, 'rb') as f_in, gzip.open(gz_gather, 'wb') as f_out:
f_out.writelines(f_in)
#gather_results, header, seen_queries = load_gather_results(gz_gather)
gather_results, header = load_gather_results(gz_gather, tax_assignments=tax_assign)
assert len(gather_results) == 1
for query_name, res in gather_results.items():
assert query_name == 'test1'
assert len(res.raw_taxresults) == 4
def test_load_gather_results_bad_header(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv],
keep_full_identifiers=False,
keep_identifier_versions=False)
g_csv = utils.get_test_data('tax/test1.gather.csv')
bad_g_csv = runtmp.output('g.csv')
#creates bad gather result
bad_g = [x.replace("f_unique_to_query", "nope") + "\n" for x in Path(g_csv).read_text().splitlines()]
with open(bad_g_csv, 'w') as fp:
fp.writelines(bad_g)
print("bad_gather_results: \n", bad_g)
with pytest.raises(ValueError) as exc:
gather_results, header = load_gather_results(bad_g_csv, tax_assignments=tax_assign)
assert f"'{bad_g_csv}' is missing columns needed for taxonomic summarization" in str(exc.value)
def test_load_gather_results_empty(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv],
keep_full_identifiers=False,
keep_identifier_versions=False)
empty_csv = runtmp.output('g.csv')
#creates empty gather result
with open(empty_csv, 'w') as fp:
fp.write('')
with pytest.raises(ValueError) as exc:
gather_results, header = load_gather_results(empty_csv, tax_assignments=tax_assign)
assert f"Cannot read gather results from '{empty_csv}'. Is file empty?" in str(exc.value)
def test_load_taxonomy_csv():
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv])
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345.1', 'GCF_009494285.1', 'GCF_013368705.1', 'GCF_003471795.1', 'GCF_000017325.1', 'GCF_000021665.1']
assert len(tax_assign) == 6 # should have read 6 rows
def test_load_taxonomy_csv_LIN():
taxonomy_csv = utils.get_test_data('tax/test.LIN-taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv], lins=True)
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345.1', 'GCF_009494285.1', 'GCF_013368705.1', 'GCF_003471795.1', 'GCF_000017325.1', 'GCF_000021665.1']
#assert list(tax_assign.keys()) == ["GCF_000010525.1", "GCF_000007365.1", "GCF_000007725.1", "GCF_000009605.1", "GCF_000021065.1", "GCF_000021085.1"]
assert len(tax_assign) == 6 # should have read 6 rows
print(tax_assign.available_ranks)
assert tax_assign.available_ranks == {str(x) for x in range(0,20)}
def test_load_taxonomy_csv_LIN_fail():
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
with pytest.raises(ValueError) as exc:
MultiLineageDB.load([taxonomy_csv], lins=True)
assert f"'lin' column not found: cannot read LIN taxonomy assignments from {taxonomy_csv}." in str(exc.value)
def test_load_taxonomy_csv_LIN_mismatch_in_taxfile(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.LIN-taxonomy.csv')
mimatchLIN_csv = runtmp.output('mmLIN-taxonomy.csv')
with open(mimatchLIN_csv, 'w') as mm:
tax21=[]
tax = [x.rstrip() for x in Path(taxonomy_csv).read_text().splitlines()]
for n, taxline in enumerate(tax):
if n == 2: # add ;0 to a LIN
taxlist = taxline.split(',')
taxlist[1] += ';0' # add 21st position to LIN
tax21.append(",".join(taxlist))
else:
tax21.append(taxline)
mm.write("\n".join(tax21))
with pytest.raises(ValueError) as exc:
MultiLineageDB.load([mimatchLIN_csv], lins=True)
assert "For taxonomic summarization, all LIN assignments must use the same number of LIN positions." in str(exc.value)
def test_load_taxonomy_csv_gzip(runtmp):
# test loading a gzipped taxonomy csv file
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_gz = runtmp.output('tax.csv.gz')
with gzip.open(tax_gz, 'wt') as outfp:
with open(taxonomy_csv, 'rt') as infp:
data = infp.read()
outfp.write(data)
tax_assign = MultiLineageDB.load([tax_gz])
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345.1', 'GCF_009494285.1', 'GCF_013368705.1', 'GCF_003471795.1', 'GCF_000017325.1', 'GCF_000021665.1']
assert len(tax_assign) == 6 # should have read 6 rows
def test_load_taxonomy_csv_split_id():
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
tax_assign = MultiLineageDB.load([taxonomy_csv], keep_full_identifiers=0,
keep_identifier_versions=False)
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345', 'GCF_009494285', 'GCF_013368705', 'GCF_003471795', 'GCF_000017325', 'GCF_000021665']
assert len(tax_assign) == 6 # should have read 6 rows
def test_load_taxonomy_csv_with_ncbi_id(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
upd_csv = runtmp.output("updated_taxonomy.csv")
with open(upd_csv, 'w') as new_tax:
tax = [x.rstrip() for x in Path(taxonomy_csv).read_text().splitlines()]
ncbi_id = "ncbi_id after_space"
fake_lin = [ncbi_id] + ["sk", "phy", "cls", "ord", "fam", "gen", "sp"]
ncbi_tax = ",".join(fake_lin)
tax.append(ncbi_tax)
new_tax.write("\n".join(tax))
tax_assign = MultiLineageDB.load([upd_csv], keep_full_identifiers=True)
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345.1', 'GCF_009494285.1', 'GCF_013368705.1', 'GCF_003471795.1', 'GCF_000017325.1', 'GCF_000021665.1', "ncbi_id after_space"]
assert len(tax_assign) == 7 # should have read 7 rows
def test_load_taxonomy_csv_split_id_ncbi(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
upd_csv = runtmp.output("updated_taxonomy.csv")
with open(upd_csv, 'w') as new_tax:
tax = [x.rstrip() for x in Path(taxonomy_csv).read_text().splitlines()]
ncbi_id = "ncbi_id after_space"
fake_lin = [ncbi_id] + ["sk", "phy", "cls", "ord", "fam", "gen", "sp"]
ncbi_tax = ",".join(fake_lin)
tax.append(ncbi_tax)
new_tax.write("\n".join(tax))
tax_assign = MultiLineageDB.load([upd_csv], keep_full_identifiers=False,
keep_identifier_versions=False)
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345', 'GCF_009494285', 'GCF_013368705', 'GCF_003471795', 'GCF_000017325', 'GCF_000021665', "ncbi_id"]
assert len(tax_assign) == 7 # should have read 7 rows
# check for non-sensical args.
with pytest.raises(ValueError):
tax_assign = MultiLineageDB.load([upd_csv], keep_full_identifiers=1,
keep_identifier_versions=False)
def test_load_taxonomy_csv_duplicate(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
duplicated_csv = runtmp.output("duplicated_taxonomy.csv")
with open(duplicated_csv, 'w') as dup:
tax = [x.rstrip() for x in Path(taxonomy_csv).read_text().splitlines()]
tax.append(tax[1] + 'FOO') # add first tax_assign again
print(tax[-1])
dup.write("\n".join(tax))
with pytest.raises(Exception) as exc:
MultiLineageDB.load([duplicated_csv])
assert "cannot read taxonomy assignments" in str(exc.value)
assert "multiple lineages for identifier GCF_001881345.1" in str(exc.value)
def test_load_taxonomy_csv_duplicate_force(runtmp):
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
duplicated_csv = runtmp.output("duplicated_taxonomy.csv")
with open(duplicated_csv, 'w') as dup:
tax = [x.rstrip() for x in Path(taxonomy_csv).read_text().splitlines()]
tax.append(tax[1]) # add first tax_assign again
dup.write("\n".join(tax))
# now force
tax_assign = MultiLineageDB.load([duplicated_csv], force=True)
print("taxonomy assignments: \n", tax_assign)
assert list(tax_assign.keys()) == ['GCF_001881345.1', 'GCF_009494285.1', 'GCF_013368705.1', 'GCF_003471795.1', 'GCF_000017325.1', 'GCF_000021665.1']
def test_format_for_krona_summarization():
"""test format for krona"""
# make gather results
# make mini taxonomy
gA_tax = ("gA", "a;b")
gB_tax = ("gB", "a;c")
taxD = make_mini_taxonomy([gA_tax,gB_tax])
gather_results = [{'query_name': 'queryA', 'name': 'gA', 'f_unique_weighted': 0.2,'f_unique_to_query': 0.2,'unique_intersect_bp': 50},
{'query_name': 'queryA', "name": 'gB', 'f_unique_weighted': 0.3,'f_unique_to_query': 0.3,'unique_intersect_bp': 30}]
q_res = make_QueryTaxResults(gather_info=gather_results, taxD=taxD, summarize=True, single_query=True)
kres, header = format_for_krona([q_res], 'superkingdom')
assert header == ['fraction', 'superkingdom']
print("krona_res: ", kres)
assert kres == [(0.5, 'a'), (0.5, 'unclassified')]
kres, header = format_for_krona([q_res], 'phylum')
assert header == ['fraction', 'superkingdom', 'phylum']
assert kres == [(0.3, 'a', 'c'), (0.2, 'a', 'b'), (0.5, 'unclassified', 'unclassified')]
def test_format_for_krona_classification():
"""test format for krona"""
# make gather results
# make mini taxonomy
gA_tax = ("gA", "a;b")
gB_tax = ("gB", "a;c")
taxD = make_mini_taxonomy([gA_tax,gB_tax])
gather_results = [{'query_name': 'queryA', 'name': 'gA', 'f_unique_weighted': 0.2,'f_unique_to_query': 0.2,'unique_intersect_bp': 50},
{'query_name': 'queryA', "name": 'gB', 'f_unique_weighted': 0.3,'f_unique_to_query': 0.3,'unique_intersect_bp': 30}]
q_res = make_QueryTaxResults(gather_info=gather_results, taxD=taxD, classify=True, single_query=True)
kres, header = format_for_krona([q_res], 'superkingdom', classification=True)
assert header == ['fraction', 'superkingdom']
print("krona_res: ", kres)
assert kres == [(0.5, 'a')]#, (0.5, 'unclassified')]
kres, header = format_for_krona([q_res], 'phylum', classification=True)
assert header == ['fraction', 'superkingdom', 'phylum']
assert kres == [(0.3, 'a', 'c')]#, (0.7, 'unclassified', 'unclassified')]
def test_format_for_krona_improper_rank():
"""test format for krona"""
# make gather results
# make mini taxonomy
gA_tax = ("gA", "a;b")
gB_tax = ("gB", "a;c")
taxD = make_mini_taxonomy([gA_tax,gB_tax])
gather_results = [{'query_name': 'queryA', 'name': 'gA', 'f_unique_weighted': 0.2,'f_unique_to_query': 0.2,'unique_intersect_bp': 50},
{'query_name': 'queryA', "name": 'gB', 'f_unique_weighted': 0.3,'f_unique_to_query': 0.3,'unique_intersect_bp': 30}]
q_res = make_QueryTaxResults(gather_info=gather_results, taxD=taxD, summarize=True, single_query=True)
with pytest.raises(ValueError) as exc:
format_for_krona([q_res], 'NotARank')
print(str(exc))
assert "Rank 'NotARank' not present in summarized ranks." in str(exc)
def test_format_for_krona_summarization_two_queries():
"""test format for krona with multiple queries (normalize by n_queries)"""
# make gather results
# make mini taxonomy
gA_tax = ("gA", "a;b")
gB_tax = ("gB", "a;c")
taxD = make_mini_taxonomy([gA_tax,gB_tax])
gather_results = [{'query_name': 'queryA', 'name': 'gA', 'f_unique_weighted': 0.2,'f_unique_to_query': 0.2,'unique_intersect_bp': 50},
{'query_name': 'queryA', "name": 'gB', 'f_unique_weighted': 0.3,'f_unique_to_query': 0.3,'unique_intersect_bp': 30},
{'query_name': 'queryB', "name": 'gB', 'f_unique_weighted': 0.5,'f_unique_to_query': 0.5,'unique_intersect_bp': 50}]
gres = make_QueryTaxResults(gather_info=gather_results, taxD=taxD, summarize=True)
kres, header = format_for_krona(list(gres.values()), 'superkingdom')
assert header == ['fraction', 'superkingdom']
print("krona_res: ", kres)
assert kres == [(0.5, 'a'), (0.5, 'unclassified')]
kres, header = format_for_krona(list(gres.values()), 'phylum')
assert header == ['fraction', 'superkingdom', 'phylum']
assert kres == [(0.4, 'a', 'c'), (0.1, 'a', 'b'), (0.5, 'unclassified', 'unclassified')]
def test_write_krona(runtmp):
"""test two matches, equal f_unique_to_query"""
krona_results = [(0.5, 'a', 'b', 'c'), (0.5, 'a', 'b', 'd')]
header = ['fraction', 'superkingdom', 'phylum', 'class']
outk= runtmp.output("outkrona.tsv")
with open(outk, 'w') as out_fp:
write_krona(header, krona_results, out_fp)
kr = [x.strip().split('\t') for x in Path(outk).read_text().splitlines()]
print("krona_results_from_file: \n", kr)
assert kr[0] == ["fraction", "superkingdom", "phylum", "class"]
assert kr[1] == ["0.5", "a", "b", "c"]
assert kr[2] == ["0.5", "a", "b", "d"]
def test_write_lineage_sample_frac(runtmp):
outfrac = runtmp.output('outfrac.csv')
sample_names = ['sample1', 'sample2']
sk_linD = {'a': {'sample1': '0.500' ,'sample2': '0.700'}}
with open(outfrac, 'w') as out_fp:
write_lineage_sample_frac(sample_names, sk_linD, out_fp)
frac_lines = [x.strip().split('\t') for x in Path(outfrac).read_text().splitlines()]
print("csv_lines: ", frac_lines)
assert frac_lines == [['lineage', 'sample1', 'sample2'], ['a', '0.500', '0.700']]
phy_linD = {'a;b': {'sample1': '0.500'}, 'a;c': {'sample2': '0.700'}}
with open(outfrac, 'w') as out_fp:
write_lineage_sample_frac(sample_names, phy_linD, out_fp)
frac_lines = [x.strip().split('\t') for x in Path(outfrac).read_text().splitlines()]
print("csv_lines: ", frac_lines)
assert frac_lines == [['lineage', 'sample1', 'sample2'], ['a;b', '0.500', '0'], ['a;c', '0', '0.700']]
def test_write_lineage_sample_frac_format_lineage(runtmp):
outfrac = runtmp.output('outfrac.csv')
sample_names = ['sample1', 'sample2']
sk_lineage='a'
print(sk_lineage)
sk_linD = {sk_lineage: {'sample1': '0.500' ,'sample2': '0.700'}}
with open(outfrac, 'w') as out_fp:
write_lineage_sample_frac(sample_names, sk_linD, out_fp)
frac_lines = [x.strip().split('\t') for x in Path(outfrac).read_text().splitlines()]
print("csv_lines: ", frac_lines)
assert frac_lines == [['lineage', 'sample1', 'sample2'], ['a', '0.500', '0.700']]
phy_lineage='a;b'
print(phy_lineage)
phy2_lineage = 'a;c'
print(phy2_lineage)
phy_linD = {phy_lineage: {'sample1': '0.500'}, phy2_lineage: {'sample2': '0.700'}}
with open(outfrac, 'w') as out_fp:
write_lineage_sample_frac(sample_names, phy_linD, out_fp)
frac_lines = [x.strip().split('\t') for x in Path(outfrac).read_text().splitlines()]
print("csv_lines: ", frac_lines)
assert frac_lines == [['lineage', 'sample1', 'sample2'], ['a;b', '0.500', '0'], ['a;c', '0', '0.700']]
def test_tax_multi_load_files(runtmp):
# test loading various good and bad files
taxonomy_csv = utils.get_test_data('tax/test.taxonomy.csv')
taxonomy_csv2 = utils.get_test_data('tax/test-strain.taxonomy.csv')
badcsv = utils.get_test_data('tax/47+63_x_gtdb-rs202.gather.csv')
db = MultiLineageDB.load([taxonomy_csv])
assert len(db) == 6
assert 'strain' not in db.available_ranks
db = MultiLineageDB.load([taxonomy_csv2])
assert len(db) == 6
assert 'strain' in db.available_ranks
assert db['GCF_001881345.1'][0].rank == 'superkingdom'
# load a string rather than a list
with pytest.raises(TypeError):
MultiLineageDB.load(badcsv)
# load a bad CSV
with pytest.raises(ValueError):
MultiLineageDB.load([badcsv])