sketchlib 0.3.0

Genome and amino-acid sketching
Documentation
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
use snapbox::cmd::{self, Command};

pub mod common;
use crate::common::*;

#[cfg(test)]

mod tests {
    use snapbox::assert_data_eq;

    use super::*;

    #[test]
    fn inverted_sketch() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "31"])
            .arg("14412_3#82.contigs_velvet.fa.gz")
            .arg("14412_3#84.contigs_velvet.fa.gz")
            .assert()
            .success();

        assert_eq!(true, sandbox.file_exists("inverted.ski"));

        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("info")
            .arg("inverted.ski")
            .arg("-v")
            .assert()
            .stdout_eq(sandbox.snapbox_file("inverted_sketch_info.stdout", TestDir::Correct));

        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("info")
            .arg("--sample-info")
            .arg("inverted.ski")
            .arg("-v")
            .assert()
            .stdout_eq(sandbox.snapbox_file("inverted_sketch_full_info.stdout", TestDir::Correct));
    }

    #[test]
    fn inverted_sketch_with_metadata() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");
        sandbox.copy_input_file_to_wd("metadata.txt");
        sandbox.copy_input_file_to_wd("species_names.txt");
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "31"])
            .args(["-f", "rfile.txt"])
            .args(["--species-names", "species_names.txt"])
            .args(["--metadata", "metadata.txt"])
            .assert()
            .success();

        assert_eq!(true, sandbox.file_exists("inverted.ski"));
    }

    #[test]
    fn inverted_sketch_errors() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");
        sandbox.copy_input_file_to_wd("species_names_empty.txt");

        // This shouldn't give an error, but it is an unfortunate situation with respect to the species-names file the user provided
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "31"])
            .args(["-f", "rfile.txt"])
            .args(["--species-names", "species_names_empty.txt"])
            .assert()
            .success();

        assert_eq!(true, sandbox.file_exists("inverted.ski"));
    }

    #[test]
    fn inverted_sketch_multifile() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile_multi.txt");

        // This shouldn't give an error, but it is an unfortunate situation with respect to the species-names file the user provided
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "31", "-s", "1000"])
            .args(["-f", "rfile_multi.txt"])
            .assert()
            .success();

        assert_eq!(true, sandbox.file_exists("inverted.ski"));
    }

    #[test]
    fn inverted_reorder() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "61", "-s", "63"])
            .arg("--species-names")
            .arg(sandbox.file_string("species_names.txt", TestDir::Input))
            .arg("14412_3#82.contigs_velvet.fa.gz")
            .arg("14412_3#84.contigs_velvet.fa.gz")
            .arg("R6.fa.gz")
            .arg("TIGR4.fa.gz")
            .assert()
            .success();

        assert_eq!(true, sandbox.file_exists("inverted.ski"));

        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("info")
            .arg("inverted.ski")
            .arg("--sample-info")
            .arg("-v")
            .assert()
            .stdout_eq(
                sandbox.snapbox_file("inverted_sketch_info_reorder.stdout", TestDir::Correct),
            );
    }

    #[test]
    fn inverted_query() {
        let sandbox = TestSetup::setup();

        // Move files to test dir
        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");

        // Build an inverted index
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg("rfile.txt")
            .assert()
            .success();

        // Query with the same samples, default is 'match-count'
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("inverted.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_query_count.stdout", TestDir::Correct)
                    .unordered(),
            );

        // Any bin matching gives two pairs
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("inverted.ski")
            .args(&["--query-type", "any-bins"])
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_query_any.stdout", TestDir::Correct)
                    .unordered(),
            );

        // All matching gives self only
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("inverted.ski")
            .args(&["--query-type", "all-bins"])
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_query_all.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    #[test]
    fn inverted_precluster() {
        let sandbox = TestSetup::setup();

        // Move files to test dir
        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");

        // Build an inverted index .ski and .skq
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("inverted")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg("rfile.txt")
            .arg("--write-skq")
            .assert()
            .success();

        // Test that the written .skq is correct (order should be right)
        assert_data_eq!(
            sandbox.snapbox_file("inverted.skq", TestDir::Output),
            sandbox.snapbox_file("inverted.skq", TestDir::Correct)
        );

        // See the match-count results in inverted_query_count.stdout
        // 14412_3#82.contigs_velvet.fa.gz and 14412_3#84.contigs_velvet.fa.gz match
        // R6.fa.gz and TIGR4.fa.gz match
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .arg("-v")
            .arg("--count")
            .arg("inverted.ski")
            .assert()
            .stdout_eq("Identified 2 prefilter pairs from a max of 6\n");

        // Build a standard .skd
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("sketch")
            .arg("-o")
            .arg("standard")
            .args(["-v", "--k-vals", "21", "-s", "1000"])
            .arg("-f")
            .arg("rfile.txt")
            .assert()
            .success();

        // Run preclustering mode
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("inverted.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster.stdout", TestDir::Correct)
                    .unordered(),
            );

        // Same with ANI
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--ani")
            .arg("--skd")
            .arg("standard")
            .arg("inverted.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster_ani.stdout", TestDir::Correct)
                    .unordered(),
            );

        // Default knn, check no junk distances printed
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "50"])
            .arg("--skd")
            .arg("standard")
            .arg("inverted.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    // Helper to set up reordered SKI + standard SKD
    // SKI order (via --species-names): TIGR4, R6, #82, #84
    // SKD order (via rfile.txt):       #82, #84, R6, TIGR4
    fn setup_reordered_precluster(sandbox: &TestSetup) {
        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");

        // Build SKI+SKQ with reordered samples via --species-names
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("reordered_inv")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg("rfile.txt")
            .arg("--write-skq")
            .arg("--species-names")
            .arg(sandbox.file_string("species_names.txt", TestDir::Input))
            .assert()
            .success();

        // Build standard SKD (different sample order)
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("sketch")
            .arg("-o")
            .arg("standard")
            .args(["-v", "--k-vals", "21", "-s", "1000"])
            .arg("-f")
            .arg("rfile.txt")
            .assert()
            .success();
    }

    #[test]
    fn inverted_precluster_reordered() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        // Run preclustering with different SKI vs SKD orderings
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    #[test]
    fn inverted_precluster_reordered_ani() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--ani")
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster_ani.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    #[test]
    fn inverted_precluster_reordered_knn_padding() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        // knn=50 >> n_samples=4, tests padding with reordered indices
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "50"])
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    #[test]
    fn inverted_precluster_reversed_rfile() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");

        // Build SKI with reversed sample order
        let reversed_rfile = sandbox.create_named_rfile(
            "reversed_rfile.txt",
            &[
                "TIGR4.fa.gz",
                "R6.fa.gz",
                "14412_3#84.contigs_velvet.fa.gz",
                "14412_3#82.contigs_velvet.fa.gz",
            ],
        );
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("reversed_inv")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg(&reversed_rfile)
            .arg("--write-skq")
            .assert()
            .success();

        // Build SKD with standard order
        let standard_rfile = sandbox.create_named_rfile(
            "standard_rfile.txt",
            &[
                "14412_3#82.contigs_velvet.fa.gz",
                "14412_3#84.contigs_velvet.fa.gz",
                "R6.fa.gz",
                "TIGR4.fa.gz",
            ],
        );
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("sketch")
            .arg("-o")
            .arg("standard")
            .args(["-v", "--k-vals", "21", "-s", "1000"])
            .arg("-f")
            .arg(&standard_rfile)
            .assert()
            .success();

        // Run precluster with different orderings
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("reversed_inv.ski")
            .assert()
            .stdout_eq(
                sandbox
                    .snapbox_file("inverted_precluster.stdout", TestDir::Correct)
                    .unordered(),
            );
    }

    #[test]
    fn inverted_precluster_reordered_completeness() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        // Create completeness file with asymmetric values
        TestSetup::create_completeness_file(
            &sandbox,
            "completeness_reorder.txt",
            &[
                ("14412_3#82.contigs_velvet.fa.gz", 0.7),
                ("14412_3#84.contigs_velvet.fa.gz", 0.8),
                ("R6.fa.gz", 0.9),
                ("TIGR4.fa.gz", 0.95),
            ],
        );

        // Also build same-order SKI for comparison
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("sameorder_inv")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg("rfile.txt")
            .arg("--write-skq")
            .assert()
            .success();

        // Run with reordered SKI + completeness
        let reordered_output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("--ref-completeness-file")
            .arg(sandbox.file_string("completeness_reorder.txt", TestDir::Output))
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        // Run with same-order SKI + completeness
        let sameorder_output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("--ref-completeness-file")
            .arg(sandbox.file_string("completeness_reorder.txt", TestDir::Output))
            .arg("sameorder_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        // Parse and compare: both orderings must produce the same distances
        let mut reordered_lines: Vec<String> = String::from_utf8(reordered_output)
            .unwrap()
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| l.to_string())
            .collect();
        let mut sameorder_lines: Vec<String> = String::from_utf8(sameorder_output)
            .unwrap()
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| l.to_string())
            .collect();
        reordered_lines.sort();
        sameorder_lines.sort();
        assert_eq!(
            reordered_lines, sameorder_lines,
            "Reordered and same-order precluster with completeness should produce identical results"
        );
    }

    #[test]
    fn inverted_precluster_all_genomes_in_output() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        let input_names = [
            "14412_3#82.contigs_velvet.fa.gz",
            "14412_3#84.contigs_velvet.fa.gz",
            "R6.fa.gz",
            "TIGR4.fa.gz",
        ];

        // Run precluster
        let output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let output_str = String::from_utf8(output).unwrap();
        let mut found_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for line in output_str.lines().filter(|l| !l.is_empty()) {
            let fields: Vec<&str> = line.split('\t').collect();
            found_names.insert(fields[0]);
            found_names.insert(fields[1]);
        }

        for name in &input_names {
            assert!(
                found_names.contains(name),
                "Genome {name} missing from precluster output"
            );
        }
        assert_eq!(
            found_names.len(),
            input_names.len(),
            "Number of unique genomes in output ({}) does not match input ({})",
            found_names.len(),
            input_names.len(),
        );
    }

    #[test]
    fn inverted_precluster_self_skip() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        // knn=3 to get all possible neighbors
        let output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "3"])
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let output_str = String::from_utf8(output).unwrap();
        for line in output_str.lines().filter(|l| !l.is_empty()) {
            let fields: Vec<&str> = line.split('\t').collect();
            assert!(
                fields.len() >= 3,
                "Output line should have at least 3 tab-separated fields: {line}"
            );
            // First two fields are sample names - they must not be the same
            assert_ne!(
                fields[0], fields[1],
                "Self-comparison found in output: {line}"
            );
            // Distance should be between 0 and 1 exclusive
            let dist: f64 = fields[2].parse().expect("Failed to parse distance");
            assert!(
                dist > 0.0 && dist < 1.0,
                "Distance out of range (0,1): {dist} in line: {line}"
            );
        }
    }

    #[test]
    fn inverted_precluster_retain_singleton() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        let input_names = [
            "14412_3#82.contigs_velvet.fa.gz",
            "14412_3#84.contigs_velvet.fa.gz",
            "R6.fa.gz",
            "TIGR4.fa.gz",
        ];

        let output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--retain-unmatched")
            .arg("singleton")
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let output_str = String::from_utf8(output).unwrap();
        let mut found_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for line in output_str.lines().filter(|l| !l.is_empty()) {
            let fields: Vec<&str> = line.split('\t').collect();
            found_names.insert(fields[0]);
            found_names.insert(fields[1]);
            // Self-match lines should have distance 0
            if fields[0] == fields[1] {
                let dist: f64 = fields[2].parse().expect("Failed to parse distance");
                assert_eq!(dist, 0.0, "Singleton self-match should have distance 0");
            }
        }

        for name in &input_names {
            assert!(
                found_names.contains(name),
                "Genome {name} missing from output with --retain-unmatched singleton"
            );
        }
    }

    #[test]
    fn inverted_precluster_retain_bruteforce() {
        let sandbox = TestSetup::setup();
        setup_reordered_precluster(&sandbox);

        let input_names = [
            "14412_3#82.contigs_velvet.fa.gz",
            "14412_3#84.contigs_velvet.fa.gz",
            "R6.fa.gz",
            "TIGR4.fa.gz",
        ];

        let output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("precluster")
            .args(["-v", "--knn", "1"])
            .arg("--retain-unmatched")
            .arg("bruteforce")
            .arg("--skd")
            .arg("standard")
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        let output_str = String::from_utf8(output).unwrap();
        let mut found_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for line in output_str.lines().filter(|l| !l.is_empty()) {
            let fields: Vec<&str> = line.split('\t').collect();
            found_names.insert(fields[0]);
            found_names.insert(fields[1]);
            // No self-matches in bruteforce mode
            assert_ne!(
                fields[0], fields[1],
                "Self-comparison found in bruteforce output: {line}"
            );
            let dist: f64 = fields[2].parse().expect("Failed to parse distance");
            assert!(
                dist > 0.0 && dist < 1.0,
                "Distance out of range (0,1): {dist} in line: {line}"
            );
        }

        for name in &input_names {
            assert!(
                found_names.contains(name),
                "Genome {name} missing from output with --retain-unmatched bruteforce"
            );
        }
    }

    #[test]
    fn inverted_query_reordered() {
        let sandbox = TestSetup::setup();

        sandbox.copy_input_file_to_wd("14412_3#82.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("14412_3#84.contigs_velvet.fa.gz");
        sandbox.copy_input_file_to_wd("R6.fa.gz");
        sandbox.copy_input_file_to_wd("TIGR4.fa.gz");
        sandbox.copy_input_file_to_wd("rfile.txt");

        // Build reordered SKI
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("build")
            .arg("-o")
            .arg("reordered_inv")
            .args(["-v", "-k", "21", "-s", "10"])
            .arg("-f")
            .arg("rfile.txt")
            .arg("--species-names")
            .arg(sandbox.file_string("species_names.txt", TestDir::Input))
            .assert()
            .success();

        // Query with match-count
        let output = Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("reordered_inv.ski")
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();

        // Verify self-matches are 10 and cross-group matches are 0
        let output_str = String::from_utf8(output).unwrap();
        for line in output_str.lines().skip(1).filter(|l| !l.is_empty()) {
            let fields: Vec<&str> = line.split('\t').collect();
            let query_name = fields[0];
            // Find the self-match count (column matching the query name)
            let header: Vec<&str> = output_str.lines().next().unwrap().split('\t').collect();
            for (col_idx, &col_name) in header.iter().enumerate().skip(1) {
                let count: u32 = fields[col_idx].parse().unwrap();
                if col_name == query_name {
                    assert_eq!(count, 10, "Self-match count should be 10 for {query_name}");
                }
            }
        }

        // Query with any-bins
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("reordered_inv.ski")
            .args(&["--query-type", "any-bins"])
            .assert()
            .success();

        // Query with all-bins
        Command::new(cmd::cargo_bin!("sketchlib"))
            .current_dir(sandbox.get_wd())
            .arg("inverted")
            .arg("query")
            .arg("-v")
            .arg("-f")
            .arg("rfile.txt")
            .arg("reordered_inv.ski")
            .args(&["--query-type", "all-bins"])
            .assert()
            .success();
    }
}