/
profile.go
3192 lines (2738 loc) · 92.9 KB
/
profile.go
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
// Copyright © 2020-2022 Wei Shen <shenwei356@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cmd
import (
"bufio"
"fmt"
"io"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/shenwei356/bio/taxdump"
"github.com/shenwei356/breader"
"github.com/shenwei356/util/cliutil"
"github.com/shenwei356/util/stats"
"github.com/spf13/cobra"
"github.com/twotwotwo/sorts"
"github.com/zeebo/wyhash"
)
var profileCmd = &cobra.Command{
Use: "profile",
Short: "Generate the taxonomic profile from search results",
Long: `Generate the taxonomic profile from search results
Methods:
1. Reference genomes can be split into chunks when computing
k-mers (sketches), which could help to increase the specificity
via a threshold, i.e., the minimum proportion of matched chunks
(-p/--min-chunks-fraction). (***highly recommended***)
Another flag -d/--max-chunks-depth-stdev further reduces false positives.
2. We require a part of the uniquely matched reads of a reference
having high similarity, i.e., with high confidence for decreasing
the false positive rate.
3. We also use the two-stage taxonomy assignment algorithm in MegaPath
to reduce the false positives of ambiguous matches.
You can also disable this step by the flag --no-amb-corr.
If stage 1/4 produces thousands of candidates, you can use
the flag --no-amb-corr to reduce analysis time, which has very little
effect on the results.
4. Abundance are estimated using an Expectation-Maximization (EM) algorithm.
5. Input files are parsed for multiple times, therefore STDIN is not supported.
Reference:
1. MegaPath: https://doi.org/10.1186/s12864-020-06875-6
Accuracy notes:
*. Smaller -t/--min-qcov increase sensitivity at the cost of higher false
positive rate (-f/--max-fpr) of a query.
*. We require a part of the uniquely matched reads of a reference
having high similarity, i.e., with high confidence for decreasing
the false positive rate.
E.g., -H >= 0.8 and -P >= 0.1 equals to 90th percentile >= 0.8
*. -U/--min-hic-ureads, minimum number, >= 1
*. -H/--min-hic-ureads-qcov, minimum query coverage, >= -t/--min-qcov
*. -P/--min-hic-ureads-prop, minimum proportion, higher values
increase precision at the cost of sensitivity.
*. -R/--max-mismatch-err and -D/--min-dreads-prop is for determing
the right reference for ambiguous reads with the algorithm in MegaPath.
*. --keep-perfect-matches is not recommended, which decreases sensitivity.
*. --keep-main-matches is not recommended, which affects accuracy of
abundance estimation.
*. -n/--keep-top-qcovs is not recommended, which affects accuracy of
abundance estimation.
Profiling modes:
We preset six profiling modes, available with the flag -m/--mode:
- 0 (for pathogen detection)
- 1 (higher recall)
- 2 (high recall)
- 3 (default)
- 4 (high precision)
- 5 (higher precision)
You can still change the values of some options below as usual.
options m=0 m=1 m=2 m=3 m=4 m=5
--------------------------- ---- --- --- ---- --- ----
-r/--min-chunks-reads 1 5 10 50 100 100
-p/--min-chunks-fraction 0.2 0.6 0.7 0.8 1 1
-d/--max-chunks-depth-stdev 10 2 2 2 2 1.5
-u/--min-uniq-reads 1 2 5 20 50 50
-U/--min-hic-ureads 1 1 2 5 10 10
-H/--min-hic-ureads-qcov 0.7 0.7 0.7 0.75 0.8 0.8
-P/--min-hic-ureads-prop 0.01 0.1 0.2 0.1 0.1 0.15
--keep-main-matches true
--max-qcov-gap 0.4
Taxonomy data:
1. Mapping references IDs to TaxIds: -T/--taxid-map
2. NCBI taxonomy dump files: -X/--taxdump
For databases built with a custom genome collection, you can use
"taxonkit create-taxdump" (https://github.com/shenwei356/taxonkit)
to create NCBI-style taxdump files, which also generates a TaxId mapping file.
Performance notes:
1. Searching results are parsed in parallel, and the number of
lines proceeded by a thread can be set by the flag --line-chunk-size.
2. However using a lot of threads does not always accelerate
processing, 4 threads with a chunk size of 500-5000 is fast enough.
*3. If stage 1/4 produces thousands of candidates, then stage 2/4
would be very slow. You can use the flag --no-amb-corr to disable
ambiguous reads correction which has very little effect on the results.
Profiling output formats:
1. KMCP (-o/--out-file)
Note that: abundances are only computed for target references rather than
each taxon at all taxonomic ranks, so please also output CAMI or MetaPhlAn format.
2. CAMI (-M/--metaphlan-report, --metaphlan-report-version,
-s/--sample-id, --taxonomy-id)
Related tools (https://github.com/shenwei356/taxonkit):
- taxonkit profile2cami: convert any metagenomic profile table with
TaxIds to CAMI format. Use this if you forget to output CAMI format.
- taxonkit cami-filter: remove taxa of given TaxIds and their
descendants in a CAMI metagenomic profile.
3. MetaPhlAn (-C/--cami-report, -s/--sample-id)
KMCP format:
Tab-delimited format with 17 columns:
1. ref, Identifier of the reference genome
2. percentage, Relative abundance of the reference
3. coverage, Average coverage of the reference
4. score, The 90th percentile of qCov of uniquely matched reads
5. chunksFrac, Genome chunks fraction
6. chunksRelDepth, Relative depths of reference chunks
7. chunksRelDepthStd, The standard deviation of chunksRelDepth
8. reads, Total number of matched reads of this reference
9. ureads, Number of uniquely matched reads
10. hicureads, Number of uniquely matched reads with high-confidence
11. refsize, Reference size
12. refname, Reference name, optional via name mapping file
13. taxid, TaxId of the reference
14. rank, Taxonomic rank
15. taxname, Taxonomic name
16. taxpath, Complete lineage
17. taxpathsn, Corresponding TaxIds of taxa in the complete lineage
Taxonomic binning formats:
1. CAMI (-B/--binning-result)
Examples:
1. Default mode:
kmcp profile -X taxdump/ -T taxid.map -m 3 \
sample.kmcp.tsv.gz -o sample.k.profile \
-C sample.c.profile -s sample
2. For pathogen detection (you may create databases with lower FPRs,
e.g., kmcp index -f 0.1 -n 2 for bacteria and fungi genomes,
and search with a low k-mer coverage threshold -t 0.4):
kmcp profile -X taxdump/ -T taxid.map -m 3 -t 0.4 \
sample.kmcp.tsv.gz -o sample.k.profile
`,
Run: func(cmd *cobra.Command, args []string) {
opt := getOptions(cmd)
var fhLog *os.File
if opt.Log2File {
fhLog = addLog(opt.LogFile, opt.Verbose)
}
timeStart := time.Now()
defer func() {
if opt.Verbose || opt.Log2File {
log.Info()
log.Infof("elapsed time: %s", time.Since(timeStart))
log.Info()
}
if opt.Log2File {
fhLog.Close()
}
}()
var err error
// ---------------- debug ---------
debugFile := getFlagString(cmd, "debug")
// debugFile := ""
debug := debugFile != ""
var outfhD *bufio.Writer
var gwD io.WriteCloser
var wD *os.File
if debug {
outfhD, gwD, wD, err = outStream(debugFile, strings.HasSuffix(strings.ToLower(debugFile), ".gz"), opt.CompressionLevel)
checkError(err)
defer func() {
outfhD.Flush()
if gwD != nil {
gwD.Close()
}
wD.Close()
}()
}
// ---------------- debug ---------
// ---------------- preset modes ----------------
type profileParams struct {
minReads float64
minFragsProp float64
maxFragsDepthStdev float64
minUReads float64
minHicUreads float64
hicUreadsMinQcov float64
HicUreadsMinProp float64
keepMainMatch bool
maxScoreGap float64
}
presetParams := make([]profileParams, 6)
presetParams[0] = profileParams{
minReads: 1,
minFragsProp: 0.2,
maxFragsDepthStdev: 10,
minUReads: 1,
minHicUreads: 1,
hicUreadsMinQcov: 0.7,
HicUreadsMinProp: 0.01,
keepMainMatch: true,
maxScoreGap: 0.4,
}
presetParams[1] = profileParams{
minReads: 5,
minFragsProp: 0.6,
maxFragsDepthStdev: 2,
minUReads: 2,
minHicUreads: 1,
hicUreadsMinQcov: 0.7,
HicUreadsMinProp: 0.1,
keepMainMatch: false,
maxScoreGap: 0.4,
}
presetParams[2] = profileParams{
minReads: 10,
minFragsProp: 0.7,
maxFragsDepthStdev: 2,
minUReads: 5,
minHicUreads: 2,
hicUreadsMinQcov: 0.7,
HicUreadsMinProp: 0.2,
keepMainMatch: false,
maxScoreGap: 0.4,
}
presetParams[3] = profileParams{
minReads: float64(minReads0),
minFragsProp: minFragsProp0,
maxFragsDepthStdev: maxFragsDepthStdev0,
minUReads: float64(minUReads0),
minHicUreads: float64(minHicUreads0),
hicUreadsMinQcov: hicUreadsMinQcov0,
HicUreadsMinProp: HicUreadsMinProp0,
keepMainMatch: keepMainMatch0,
maxScoreGap: maxScoreGap0,
}
presetParams[4] = profileParams{
minReads: 100,
minFragsProp: 1,
maxFragsDepthStdev: 2,
minUReads: 50,
minHicUreads: 10,
hicUreadsMinQcov: 0.8,
HicUreadsMinProp: 0.1,
keepMainMatch: false,
maxScoreGap: 0.4,
}
presetParams[5] = profileParams{
minReads: 100,
minFragsProp: 1,
maxFragsDepthStdev: 1.5,
minUReads: 50,
minHicUreads: 10,
hicUreadsMinQcov: 0.8,
HicUreadsMinProp: 0.15,
keepMainMatch: false,
maxScoreGap: 0.4,
}
mode := getFlagNonNegativeInt(cmd, "mode")
if mode > 5 {
checkError(fmt.Errorf("invalid profiling mode: %d", mode))
}
mode0 := mode == 0
para := presetParams[mode]
minReads := para.minReads
minFragsProp := para.minFragsProp
maxFragsDepthStdev := para.maxFragsDepthStdev
minUReads := para.minUReads
minHicUreads := para.minHicUreads
hicUreadsMinQcov := para.hicUreadsMinQcov
HicUreadsMinProp := para.HicUreadsMinProp
keepMainMatch := para.keepMainMatch
maxScoreGap := para.maxScoreGap
// ---------------- preset modes ----------------
maxIters := getFlagPositiveInt(cmd, "abund-max-iters")
abundPctThreshold := getFlagPositiveFloat64(cmd, "abund-pct-threshold")
noAmbCorr := getFlagBool(cmd, "no-amb-corr")
outFile := getFlagString(cmd, "out-file")
maxFPR := getFlagPositiveFloat64(cmd, "max-fpr")
minQcov := getFlagNonNegativeFloat64(cmd, "min-query-cov")
topNScore := getFlagNonNegativeInt(cmd, "keep-top-qcovs")
keepFullMatch := getFlagBool(cmd, "keep-perfect-matches")
var _minReads float64
var _minFragsProp float64
var _maxFragsDepthStdev float64
var _minUReads float64
var _minHicUreads float64
var _hicUreadsMinQcov float64
var _HicUreadsMinProp float64
var _keepMainMatch bool
var _maxScoreGap float64
_minReads = float64(getFlagPositiveInt(cmd, "min-chunks-reads"))
_minFragsProp = getFlagNonNegativeFloat64(cmd, "min-chunks-fraction")
if _minFragsProp > 1 {
checkError(fmt.Errorf("the value of -P/--min-hic-ureads-prop (%f) should be in range of [0, 1]", _minFragsProp))
}
_maxFragsDepthStdev = getFlagPositiveFloat64(cmd, "max-chunks-depth-stdev")
_minUReads = float64(getFlagPositiveInt(cmd, "min-uniq-reads"))
_minHicUreads = float64(getFlagPositiveInt(cmd, "min-hic-ureads"))
if _minHicUreads > _minUReads {
_minUReads = _minHicUreads
}
_hicUreadsMinQcov = getFlagPositiveFloat64(cmd, "min-hic-ureads-qcov")
if _hicUreadsMinQcov > 1 || _hicUreadsMinQcov < minQcov {
checkError(fmt.Errorf("the value of -H/--min-hic-ureads-qcov (%f) should be in range of [<-t/--min-query-cov>, 1]", _hicUreadsMinQcov))
}
_HicUreadsMinProp = getFlagPositiveFloat64(cmd, "min-hic-ureads-prop")
_keepMainMatch = getFlagBool(cmd, "keep-main-matches")
_maxScoreGap = getFlagFloat64(cmd, "max-qcov-gap")
if false {
minReads = _minReads
minFragsProp = _minFragsProp
maxFragsDepthStdev = _maxFragsDepthStdev
minUReads = _minUReads
minHicUreads = _minHicUreads
hicUreadsMinQcov = _hicUreadsMinQcov
HicUreadsMinProp = _HicUreadsMinProp
keepMainMatch = _keepMainMatch
maxScoreGap = _maxScoreGap
} else {
// only change the value when a new value is given
if minReads != _minReads && cmd.Flags().Lookup("min-chunks-reads").Changed {
minReads = _minReads
}
if minFragsProp != _minFragsProp && cmd.Flags().Lookup("min-chunks-fraction").Changed {
minFragsProp = _minFragsProp
}
if maxFragsDepthStdev != _maxFragsDepthStdev && cmd.Flags().Lookup("max-chunks-depth-stdev").Changed {
maxFragsDepthStdev = _maxFragsDepthStdev
}
if minUReads != _minUReads && cmd.Flags().Lookup("min-uniq-reads").Changed {
minUReads = _minUReads
}
if minHicUreads != _minHicUreads && cmd.Flags().Lookup("min-hic-ureads").Changed {
minHicUreads = _minHicUreads
}
if hicUreadsMinQcov != _hicUreadsMinQcov && cmd.Flags().Lookup("min-hic-ureads-qcov").Changed {
hicUreadsMinQcov = _hicUreadsMinQcov
}
if HicUreadsMinProp != _HicUreadsMinProp && cmd.Flags().Lookup("min-hic-ureads-prop").Changed {
HicUreadsMinProp = _HicUreadsMinProp
}
if keepMainMatch != _keepMainMatch && cmd.Flags().Lookup("keep-main-matches").Changed {
keepMainMatch = _keepMainMatch
}
if maxScoreGap != _maxScoreGap && cmd.Flags().Lookup("max-qcov-gap").Changed {
maxScoreGap = _maxScoreGap
}
}
// fmt.Println("mode", mode)
// fmt.Println("-r/--min-chunks-reads", minReads)
// fmt.Println("-p/--min-chunks-fraction", minFragsProp)
// fmt.Println("-d/--max-chunks-depth-stdev", maxFragsDepthStdev)
// fmt.Println("-u/--min-uniq-reads", minUReads)
// fmt.Println("-U/--min-hic-ureads", minHicUreads)
// fmt.Println("-H/--min-hic-ureads-qcov", hicUreadsMinQcov)
// fmt.Println("-P/--min-hic-ureads-prop", HicUreadsMinProp)
// fmt.Println("--keep-main-matches", keepMainMatch)
// fmt.Println("--max-qcov-gap", maxScoreGap)
minDReadsProp := getFlagPositiveFloat64(cmd, "min-dreads-prop")
if minDReadsProp > 1 {
checkError(fmt.Errorf("the value of -D/--min-dreads-prop (%f) should be in range of (0, 1]", minDReadsProp))
}
maxMismatchErr := getFlagPositiveFloat64(cmd, "max-mismatch-err")
if maxMismatchErr >= 1 {
checkError(fmt.Errorf("the value of -R/--max-mismatch-err (%f) should be in range of (0, 1)", maxMismatchErr))
}
lowAbcPct := getFlagNonNegativeFloat64(cmd, "filter-low-pct")
if lowAbcPct >= 100 {
checkError(fmt.Errorf("the value of -F/--filter-low-pct (%f) should be in range of [0, 100)", lowAbcPct))
} else if lowAbcPct > 10 {
log.Warningf("the value of -F/--filter-low-pct (%v) may be too big", lowAbcPct)
}
fileterLowAbc := lowAbcPct > 0
level := strings.ToLower(getFlagString(cmd, "level"))
var levelSpecies bool
switch level {
case "species":
levelSpecies = true
case "strain", "assembly":
levelSpecies = false
default:
checkError(fmt.Errorf("invalid value for --level, available values: species, strain/assembly"))
}
// -----
// -----
nameMappingFiles := getFlagStringSlice(cmd, "name-map")
taxidMappingFiles := getFlagStringSlice(cmd, "taxid-map")
taxonomyDataDir := getFlagString(cmd, "taxdump")
if len(taxidMappingFiles) > 0 && taxonomyDataDir == "" {
checkError(fmt.Errorf("flag -X/--taxdump is needed when -T/--taxid-map given"))
}
if len(taxidMappingFiles) == 0 && taxonomyDataDir != "" {
checkError(fmt.Errorf("flag -T/--taxid-map is needed when -X/--taxdump given"))
}
if len(taxidMappingFiles) == 0 || taxonomyDataDir == "" {
log.Warningf("TaxID mapping files (-T/--taxid-map) and taxonomy dump files are recommended to add taxonomy information")
}
mappingTaxids := len(taxidMappingFiles) != 0
if levelSpecies && !mappingTaxids {
checkError(fmt.Errorf("-T/--taxid-map needed for --level species"))
}
separator := getFlagString(cmd, "separator")
if separator == "" {
log.Warningf("value of -s/--separator better not be empty")
}
chunkSize := getFlagPositiveInt(cmd, "line-chunk-size")
if opt.NumCPUs > 4 {
if opt.Verbose || opt.Log2File {
log.Infof("using a lot of threads does not always accelerate processing, 4-threads is fast enough")
}
opt.NumCPUs = 4
runtime.GOMAXPROCS(opt.NumCPUs)
}
sampleID := getFlagString(cmd, "sample-id")
taxonomyID := getFlagString(cmd, "taxonomy-id")
binningFile := getFlagString(cmd, "binning-result")
outputBinningResult := binningFile != ""
if outputBinningResult && !(strings.HasSuffix(binningFile, ".binning") || strings.HasSuffix(binningFile, ".binning.gz")) {
binningFile = binningFile + ".binning.gz"
}
if outputBinningResult && (len(taxidMappingFiles) == 0 || taxonomyDataDir == "") {
checkError(fmt.Errorf("flag -T/--taxid-map and -T/--taxid-map needed when -B/--binning-result given"))
}
camiReportFile := getFlagString(cmd, "cami-report")
outputCamiReport := camiReportFile != ""
if outputCamiReport && !strings.HasSuffix(camiReportFile, ".profile") {
camiReportFile = camiReportFile + ".profile"
}
metaphlanReportFile := getFlagString(cmd, "metaphlan-report")
outputMetaphlanReport := metaphlanReportFile != ""
if outputMetaphlanReport && !strings.HasSuffix(metaphlanReportFile, ".profile") {
metaphlanReportFile = metaphlanReportFile + ".profile"
}
metaphlanReportVersion := getFlagString(cmd, "metaphlan-report-version")
switch metaphlanReportVersion {
case "2", "3":
default:
checkError(fmt.Errorf("invalid --metaphlan-report-version: %s", metaphlanReportVersion))
}
if (outputBinningResult || outputCamiReport || outputMetaphlanReport) && !mappingTaxids {
log.Warningf("TaxID mapping files (-T/--taxid-map) and taxonomy dump files are needed to output CAMI/MetaPhlAn/binning report")
}
showRanks := getFlagStringSlice(cmd, "show-rank")
rankPrefixes := getFlagStringSlice(cmd, "rank-prefix")
if outputMetaphlanReport && len(showRanks) != len(rankPrefixes) {
checkError(fmt.Errorf("number of ranks to show and ther prefixes should match"))
}
rankOrder := make(map[string]int, len(showRanks))
for _i, _r := range showRanks {
rankOrder[_r] = _i
}
normAbund := getFlagString(cmd, "norm-abund")
switch normAbund {
case "mean", "min", "max":
default:
checkError(fmt.Errorf("invalid value of --norm-abund: %s. available: mean, min, max", normAbund))
}
// ---------------------------------------------------------------
if opt.Verbose || opt.Log2File {
log.Infof("kmcp v%s", VERSION)
log.Info(" https://github.com/shenwei356/kmcp")
log.Info()
log.Info("checking input files ...")
}
files := getFileListFromArgsAndFile(cmd, args, true, "infile-list", true)
if opt.Verbose || opt.Log2File {
if len(files) == 1 && isStdin(files[0]) {
// log.Info("no files given, reading from stdin")
checkError(fmt.Errorf("stdin not supported"))
} else {
log.Infof(" %d input file(s) given", len(files))
}
}
outFileClean := filepath.Clean(outFile)
for _, file := range files {
if isStdin(file) {
checkError(fmt.Errorf("stdin not supported"))
} else if filepath.Clean(file) == outFileClean {
checkError(fmt.Errorf("out file should not be one of the input file"))
}
}
// ---------------------------------------------------------------
// name mapping files
var namesMap map[string]string
mappingNames := len(nameMappingFiles) != 0
if mappingNames {
if opt.Verbose || opt.Log2File {
log.Infof("loading name mapping file ...")
}
nameMappingFile := nameMappingFiles[0]
namesMap, err = cliutil.ReadKVs(nameMappingFile, false)
if err != nil {
checkError(errors.Wrap(err, nameMappingFile))
}
if len(nameMappingFiles) > 1 {
for _, _nameMappingFile := range nameMappingFiles[1:] {
_namesMap, err := cliutil.ReadKVs(_nameMappingFile, false)
if err != nil {
checkError(errors.Wrap(err, nameMappingFile))
}
for _k, _v := range _namesMap {
namesMap[_k] = _v
}
}
}
if opt.Verbose || opt.Log2File {
log.Infof(" %d pairs of name mapping values from %d file(s) loaded", len(namesMap), len(nameMappingFiles))
}
mappingNames = len(namesMap) > 0
}
// ---------------------------------------------------------------
// taxid mapping files
var taxdb *taxdump.Taxonomy
var taxidMap map[string]uint32
if mappingTaxids {
if opt.Verbose || opt.Log2File {
log.Infof("loading TaxId mapping file ...")
}
taxidMappingFile := taxidMappingFiles[0]
taxidMapStr, err := cliutil.ReadKVs(taxidMappingFile, false)
if err != nil {
checkError(errors.Wrap(err, taxidMappingFile))
}
taxidMap = make(map[string]uint32, len(taxidMapStr))
var taxid uint64
for k, s := range taxidMapStr {
taxid, err = strconv.ParseUint(s, 10, 32)
if err != nil {
checkError(fmt.Errorf("invalid TaxId: %s", s))
}
taxidMap[k] = uint32(taxid)
}
if len(taxidMappingFiles) > 1 {
for _, taxidMappingFile := range taxidMappingFiles[1:] {
_taxidMapStr, err := cliutil.ReadKVs(taxidMappingFile, false)
if err != nil {
checkError(errors.Wrap(err, taxidMappingFile))
}
for _k, _v := range _taxidMapStr {
taxid, err = strconv.ParseUint(_v, 10, 32)
if err != nil {
checkError(fmt.Errorf("invalid TaxId: %s", _v))
}
taxidMap[_k] = uint32(taxid)
}
}
}
if opt.Verbose || opt.Log2File {
log.Infof(" %d pairs of TaxId mapping values from %d file(s) loaded", len(taxidMap), len(taxidMappingFiles))
}
mappingTaxids = len(taxidMap) > 0
if mappingTaxids {
taxdb = loadTaxonomy(opt, taxonomyDataDir)
taxdb.CacheLCA()
} else {
checkError(fmt.Errorf("no valid TaxIds found in TaxId mapping file: %s", strings.Join(taxidMappingFiles, ", ")))
}
}
if opt.Verbose || opt.Log2File {
log.Info()
log.Infof("-------------------- [main parameters] --------------------")
log.Infof("match filtration: ")
log.Infof(" maximum false positive rate: %f", maxFPR)
log.Infof(" minimum query coverage: %4f", minQcov)
log.Infof(" keep matches with the top N scores: N=%d", topNScore)
log.Infof(" only keep the full matches: %v", keepFullMatch)
log.Infof(" only keep main matches: %v, maximum score gap: %f", keepMainMatch, maxScoreGap)
log.Info()
log.Infof("deciding the existence of a reference:")
log.Infof(" preset profiling mode: %d", mode)
log.Infof(" minimum number of reads per reference chunk: %.0f", minReads)
log.Infof(" minimum number of uniquely matched reads: %.0f", minUReads)
log.Infof(" minimum proportion of matched reference chunks: %f", minFragsProp)
log.Infof(" maximum standard deviation of relative depths of all chunks: %f", maxFragsDepthStdev)
log.Info()
log.Infof(" minimum number of high-confidence uniquely matched reads: %.0f", minHicUreads)
log.Infof(" minimum query coverage of high-confidence uniquely matched reads: %f", hicUreadsMinQcov)
log.Infof(" minimum proportion of high-confidence uniquely matched reads: %f", HicUreadsMinProp)
log.Info()
if mappingTaxids {
log.Infof("taxonomy data:")
log.Infof(" taxdump directory: %s", taxonomyDataDir)
log.Infof(" mapping reference IDs to TaxIds: %s", taxidMappingFiles)
log.Info()
}
log.Infof("reporting:")
if mappingNames {
log.Infof(" mapping reference IDs to names: %s", nameMappingFiles)
}
if fileterLowAbc {
log.Infof(" filter out predictions with the smallest relative abundances summing up %d%%", lowAbcPct)
}
log.Infof(" default format : %s", outFile)
if outputCamiReport {
log.Infof(" CAMI format : %s", camiReportFile)
log.Infof(" Sample ID : %s", sampleID)
}
if outputMetaphlanReport {
log.Infof(" MetaPhlAn%s format: %s", metaphlanReportVersion, metaphlanReportFile)
log.Infof(" Sample ID : %s", sampleID)
log.Infof(" Taxonomy ID : %s", taxonomyID)
}
if outputBinningResult {
log.Infof(" Binning result : %s", binningFile)
}
log.Infof("-------------------- [main parameters] --------------------")
log.Info()
}
// ---------------------------------------------------------------
numFields := 13
profile := make(map[uint64]*Target, 128)
floatOne := float64(1)
// ---------------------------------------------------------------
pool := &sync.Pool{New: func() interface{} {
tmp := make([]string, numFields)
return &tmp
}}
fn := func(line string) (interface{}, bool, error) {
if line == "" || line[0] == '#' { // ignoring blank line and comment line
return "", false, nil
}
items := pool.Get().(*[]string)
match, ok := parseMatchResult(line, numFields, items, maxFPR, minQcov)
if !ok {
pool.Put(items)
return nil, false, nil
}
pool.Put(items)
return match, true, nil
}
var nReads float64
// ---------------------------------------------------------------
// stage 1/4
if opt.Verbose || opt.Log2File {
log.Infof("stage 1/4: counting matches and unique matches for filtering out low-confidence references")
}
timeStart1 := time.Now()
var timeStart2 time.Time
for _, file := range files {
if opt.Verbose || opt.Log2File {
timeStart2 = time.Now()
log.Infof(" parsing file: %s", file)
}
var matches map[uint64]*[]*MatchResult // target -> match result
var m *MatchResult
var ms *[]*MatchResult
var t *Target
var ok bool
var hTarget, h uint64
var prevQuery string
var floatMsSize float64
var match *MatchResult
var first bool
onlyTopNScore := topNScore > 0
var nScore int
var pScore float64
var processThisMatch bool
taxids := make([]uint32, 0, 128)
var taxid1, taxid2 uint32
var theSameSpecies bool
reader, err := breader.NewBufferedReader(file, opt.NumCPUs, chunkSize, fn)
checkError(err)
var data interface{}
matches = make(map[uint64]*[]*MatchResult)
pScore = 1024
nScore = 0
processThisMatch = true
for chunk := range reader.Ch {
checkError(chunk.Err)
for _, data = range chunk.Data {
match = data.(*MatchResult)
if prevQuery != match.Query { // new query
if len(matches) > 0 { // not the first query
nReads++
if levelSpecies {
taxids = taxids[:0]
for h, ms = range matches {
taxid1, ok = taxidMap[(*ms)[0].Target]
if !ok {
checkError(fmt.Errorf("unknown taxid for %s, please check taxid mapping file(s)", (*ms)[0].Target))
}
taxids = append(taxids, taxid1)
}
// LCA
theSameSpecies = false
taxid1 = taxids[0]
for _, taxid2 = range taxids[1:] {
taxid1 = taxdb.LCA(taxid1, taxid2)
}
if taxdb.AtOrBelowRank(taxid1, "species") {
theSameSpecies = true
}
}
for h, ms = range matches {
floatMsSize = float64(len(*ms))
first = true
for _, m = range *ms { // multiple matches in different chunks
if t, ok = profile[h]; !ok {
t0 := Target{
Name: m.Target,
GenomeSize: m.GSize,
Match: make([]float64, m.IdxNum),
UniqMatch: make([]float64, m.IdxNum),
UniqMatchHic: make([]float64, m.IdxNum),
// QLen: make([]float64, m.IdxNum),
// RelDepth: make([]float64, m.IdxNum),
StatsA: stats.NewQuantiler(),
}
profile[h] = &t0
t = &t0
}
if first { // count once
if len(matches) == 1 || theSameSpecies {
t.UniqMatch[m.FragIdx]++
if m.QCov >= hicUreadsMinQcov {
t.UniqMatchHic[m.FragIdx]++
}
}
t.StatsA.Add(m.QCov)
first = false
}
// t.QLen[m.FragIdx] += float64(m.QLen) / floatMsSize
// for a read matching multiple regions of a reference, distribute count to multiple regions,
// the sum is still one.
// Besides, we add one for ambiguous reads too.
t.Match[m.FragIdx] += floatOne / floatMsSize
}
poolMatchResults.Put(ms)
}
}
matches = make(map[uint64]*[]*MatchResult)
pScore = 1024
nScore = 0
processThisMatch = true
} else if keepFullMatch { // not the first match
if !processThisMatch {
prevQuery = match.Query
continue
}
if pScore == 1 && match.QCov < 1 {
processThisMatch = false
prevQuery = match.Query
continue
}
} else if keepMainMatch && pScore <= 1 {
if !processThisMatch {
prevQuery = match.Query
continue
}
if pScore-match.QCov > maxScoreGap {
processThisMatch = false
prevQuery = match.Query
continue
}
}
if onlyTopNScore {
if !processThisMatch {
prevQuery = match.Query
continue
}
if match.QCov < pScore { // match with a smaller score
nScore++
if nScore > topNScore {
processThisMatch = false
prevQuery = match.Query
continue
}
}
}
hTarget = wyhash.HashString(match.Target, 1)
if ms, ok = matches[hTarget]; !ok {
// tmp := []*MatchResult{match}
tmp := poolMatchResults.Get().(*[]*MatchResult)
*tmp = (*tmp)[:0]
*tmp = append(*tmp, match)
matches[hTarget] = tmp
} else {
*ms = append(*ms, match)
}
prevQuery = match.Query
pScore = match.QCov
}
}
if len(matches) > 0 {
nReads++
if levelSpecies {
taxids = taxids[:0]
for h, ms = range matches {
taxid1, ok = taxidMap[(*ms)[0].Target]
if !ok {
checkError(fmt.Errorf("unknown taxid for %s, please check taxid mapping file(s)", (*ms)[0].Target))
}
taxids = append(taxids, taxid1)
}
theSameSpecies = false
taxid1 = taxids[0]
for _, taxid2 = range taxids[1:] {
taxid1 = taxdb.LCA(taxid1, taxid2)
}
if taxdb.AtOrBelowRank(taxid1, "species") {
theSameSpecies = true
}
}
for h, ms = range matches {
floatMsSize = float64(len(*ms))
first = true
for _, m = range *ms { // multiple matches in different chunks
if t, ok = profile[h]; !ok {
t0 := Target{
Name: m.Target,
GenomeSize: m.GSize,
Match: make([]float64, m.IdxNum),
UniqMatch: make([]float64, m.IdxNum),
UniqMatchHic: make([]float64, m.IdxNum),
// QLen: make([]float64, m.IdxNum),
// RelDepth: make([]float64, m.IdxNum),
StatsA: stats.NewQuantiler(),
}
profile[h] = &t0
t = &t0
}
if first { // count once
if len(matches) == 1 || theSameSpecies {
t.UniqMatch[m.FragIdx]++
if m.QCov >= hicUreadsMinQcov {
t.UniqMatchHic[m.FragIdx]++
}
}
t.StatsA.Add(m.QCov)
first = false
}
// t.QLen[m.FragIdx] += float64(m.QLen) / floatMsSize
// for a read matching multiple regions of a reference, distribute count to multiple regions,
// the sum is still one.
t.Match[m.FragIdx] += floatOne / floatMsSize
}
poolMatchResults.Put(ms)
}
}
}