dnacomb 1.0.0

Count the occurances of structured sequence reads and compare to an expected library
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
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
//! Observed variable-region sequences extracted from sequencing reads.
//!
//! This module defines the per-region objects used after read parsing and region
//! extraction but before full combination-level summarisation. It captures both
//! the observed sequence itself and how completely that region was observed,
//! along with optional comparison to an expected library.
use itertools::Itertools;
use std::sync::Arc;

use crate::interning::{RegionID, SeqHandle, seq_from_bytes, seq_to_bytes};
use crate::library::{DistanceMetric, Library, LibraryRegion, PartialMatching, merge_matches};
use crate::seq_diff::{EditOperation, SequenceDiff, TerminalFilter};

/// Additional window size for doing end-anchored diff alignments
const DIFF_WINDOW_EXTRA: usize = 8;

/// Key identifying one distinct observed region state.
///
/// Two observations are considered the same region key if they share:
/// - the same region ID,
/// - the same observed sequence,
/// - and the same completeness status.
///
/// This is used to deduplicate repeated region observations across reads.
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct RegionKey {
    pub id: RegionID,
    pub sequence: SeqHandle,
    pub completeness: RegionCompleteness,
}

impl RegionKey {
    pub fn new(id: RegionID, sequence: SeqHandle, completeness: RegionCompleteness) -> Self {
        Self {
            id,
            sequence,
            completeness,
        }
    }
}

/// Observed sequence for one variable region.
///
/// An `ObservedRegion` stores:
/// - the region ID,
/// - the observed sequence,
/// - how completely that region was observed in the read(s),
/// - and, once performed, the result of comparison to the expected library.
///
/// Identical region observations can be shared across multiple observed
/// combinations to avoid repeating library-comparison work.
#[derive(Debug)]
pub struct ObservedRegion {
    /// Name of the region from LibSpec
    pub id: RegionID,

    /// Observed Sequence
    pub seq: SeqHandle,

    /// Completeness status of the region
    pub completeness: RegionCompleteness,

    /// Library indeces of nearest matches (Vec of Vecs containing indeces from each matching seq)
    pub nearest_matches: RegionMatch,
}

impl ObservedRegion {
    /// Create a new observed region in the uncompared state.
    pub fn new(id: RegionID, seq: SeqHandle, complete: RegionCompleteness) -> Self {
        Self {
            id,
            seq,
            completeness: complete,
            nearest_matches: RegionMatch::Uncompared,
        }
    }

    /// Length of the observed sequence.
    pub fn len(&self) -> usize {
        seq_to_bytes(&self.seq).len()
    }

    /// Return `true` if the observed sequence is empty.
    pub fn is_empty(&self) -> bool {
        seq_to_bytes(&self.seq).is_empty()
    }

    /// Return `true` if library comparison has already been performed for this region.
    pub fn is_compared_to_library(&self) -> bool {
        !matches!(self.nearest_matches, RegionMatch::Uncompared)
    }

    /// Compare this observed region to the expected library.
    ///
    /// The lookup strategy depends on `completeness`:
    /// - `Complete` regions are matched against the full library sequence,
    /// - `Partial5Prime` regions are matched against the library 3' end,
    /// - `Partial3Prime` regions are matched against the library 5' end,
    /// - `MissingCenter` and `Overlapping` regions are split into left/right
    ///   pieces and matched independently before intersecting compatible results.
    ///
    /// The result is returned as a `RegionMatch`, which may represent a unique
    /// match, multiple equally good matches, too many matches, no match, or the
    /// absence of this region from the supplied library.
    ///
    /// Determining variants between observed and matched sequence involves an alignment
    /// between them and can be expensive for long sequences, hence the option to skip.
    pub fn compare_to_library(
        &self,
        library: &Library,
        distance_metric: DistanceMetric,
        max_matches: usize,
        skip_variants: bool,
    ) -> RegionMatch {
        let lib_match = match self.completeness {
            RegionCompleteness::Complete => {
                match library.lookup(&self.id, &self.seq, distance_metric, PartialMatching::Full) {
                    // lookup can only return Err(LibraryError::MissingRegion) which implies the
                    // region isn't in the library. Needs changing if more errors are added to it.
                    Err(_) => return RegionMatch::NoLibrary { seq: None },
                    Ok(x) => x,
                }
            }
            RegionCompleteness::Partial5Prime => {
                match library.lookup(
                    &self.id,
                    &self.seq,
                    distance_metric,
                    PartialMatching::ThreePrimeOnly,
                ) {
                    // lookup can only return Err(LibraryError::MissingRegion) which implies the
                    // region isn't in the library. Needs changing if more errors are added to it.
                    Err(_) => return RegionMatch::NoLibrary { seq: None },
                    Ok(x) => x,
                }
            }
            RegionCompleteness::Partial3Prime => {
                match library.lookup(
                    &self.id,
                    &self.seq,
                    distance_metric,
                    PartialMatching::FivePrimeOnly,
                ) {
                    // lookup can only return Err(LibraryError::MissingRegion) which implies the
                    // region isn't in the library. Needs changing if more errors are added to it.
                    Err(_) => return RegionMatch::NoLibrary { seq: None },
                    Ok(x) => x,
                }
            }
            RegionCompleteness::MissingCenter { split_ind }
            | RegionCompleteness::Overlapping { split_ind } => {
                let seq = seq_to_bytes(&self.seq);
                let left_seq = seq_from_bytes(&seq[0..split_ind]);
                let right_seq = seq_from_bytes(&seq[split_ind + 1..seq.len()]);

                let left_match = library.lookup(
                    &self.id,
                    &left_seq,
                    distance_metric,
                    PartialMatching::FivePrimeOnly,
                );

                let right_match = library.lookup(
                    &self.id,
                    &right_seq,
                    distance_metric,
                    PartialMatching::ThreePrimeOnly,
                );

                match (left_match, right_match) {
                    (Ok(left), Ok(right)) => merge_matches(left, right),

                    // lookup can only return Err(LibraryError::MissingRegion) which implies the
                    // region isn't in the library. Needs changing if more errors are added to it.
                    (_, Err(_)) | (Err(_), _) => return RegionMatch::NoLibrary { seq: None },
                }
            }
        };

        match lib_match {
            None => RegionMatch::Unmatched,
            Some(x) => {
                if x.matches.len() == 1 {
                    RegionMatch::Match {
                        seq_match: x.matches[0].clone(),
                        distance: x.distance,
                        diff: if skip_variants {
                            None
                        } else {
                            Some(compute_region_diff(
                                &self.seq,
                                &x.matches[0].sequence,
                                self.completeness,
                                x.distance,
                            ))
                        },
                    }
                } else if x.matches.len() > max_matches {
                    RegionMatch::Overmatched {
                        distance: x.distance,
                        matches: x.matches.len(),
                    }
                } else {
                    RegionMatch::MultiMatch {
                        distance: x.distance,
                        diffs: if skip_variants {
                            None
                        } else {
                            Some(
                                x.matches
                                    .iter()
                                    .map(|m| {
                                        compute_region_diff(
                                            &self.seq,
                                            &m.sequence,
                                            self.completeness,
                                            x.distance,
                                        )
                                    })
                                    .collect(),
                            )
                        },
                        seq_matches: x.matches,
                    }
                }
            }
        }
    }

    /// Convert this region into display strings for TSV/output generation.
    ///
    /// The returned tuple contains:
    /// * Sequence (with ^ at start or end to represent a partially truncated end)
    /// * nearest match(s)
    /// * difference to match(s)
    /// * distance from match
    /// * number of matches
    pub fn to_strings(&self) -> (String, String, String, String, String) {
        let seq = match self.completeness {
            RegionCompleteness::Complete
            | RegionCompleteness::MissingCenter { .. }
            | RegionCompleteness::Overlapping { .. } => self.seq.to_str_or_log(),
            RegionCompleteness::Partial5Prime => format!("^{}", self.seq.to_str_or_log()),
            RegionCompleteness::Partial3Prime => format!("{}^", self.seq.to_str_or_log()),
        };

        let (match_seq, diff, dist, n_matches) = self.nearest_matches.to_strings();

        (seq, match_seq, diff, dist, n_matches)
    }
}

/// How completely a region was observed in the read data.
///
/// Completeness captures whether the full region sequence is known, whether one
/// end may be truncated by read boundaries, or whether paired-read evidence
/// produced gapped or overlapping partial observations.
///
/// For `MissingCenter` and `Overlapping`, the stored sequence is expected to
/// contain a separator byte at `split_ind`, with left and right observed
/// fragments stored on either side.
#[derive(Debug, Eq, Hash, PartialEq, Clone, Copy)]
pub enum RegionCompleteness {
    /// The full region sequence is believed to be observed.
    Complete,

    /// The 5' end may be truncated; the observed sequence begins inside the region.
    Partial5Prime,

    /// The 3' end may be truncated; the observed sequence ends inside the region.
    Partial3Prime,

    /// Forward/reverse evidence covers both ends of the region but leaves a gap
    /// in the middle. The stored sequence contains a `/` separator at `split_ind`.
    MissingCenter { split_ind: usize },

    /// Forward/reverse evidence covers both ends of the region and overlaps.
    /// The stored sequence contains a `/` separator at `split_ind`.
    Overlapping { split_ind: usize },
}

/// Status of the match between an ObservedRegion and a Library
///
/// This stores both the qualitative match status and any associated library
/// sequence(s), distance(s), and sequence-difference information.
#[derive(Debug, Eq, Hash, PartialEq, Clone)]
pub enum RegionMatch {
    /// Library comparison has not yet been performed.
    Uncompared,

    /// A unique best library-region match was found.
    Match {
        seq_match: Arc<LibraryRegion>,
        distance: u64,
        diff: Option<SequenceDiff>,
    },

    /// Multiple equally good best library-region matches were found.
    MultiMatch {
        seq_matches: Vec<Arc<LibraryRegion>>,
        distance: u64,
        diffs: Option<Vec<SequenceDiff>>,
    },

    /// More than `max_matches` equally good matches were found.
    Overmatched { distance: u64, matches: usize },

    /// No acceptable library-region match was found.
    Unmatched,

    /// This region is not represented in the supplied library.
    ///
    /// The observed sequence may optionally be retained for output.
    NoLibrary { seq: Option<SeqHandle> },
}

impl RegionMatch {
    /// Convert the library-match portion of this region comparison into strings
    /// for TSV/output generation.
    ///
    /// Returns:
    /// - matching sequence(s),
    /// - sequence difference(s),
    /// - match distance,
    /// - number of matches.
    pub fn to_strings(&self) -> (String, String, String, String) {
        match self {
            RegionMatch::Uncompared | RegionMatch::Unmatched | RegionMatch::NoLibrary { .. } => (
                "".to_string(),
                "".to_string(),
                "".to_string(),
                "0".to_string(),
            ),
            RegionMatch::Overmatched { distance, matches } => (
                "".to_string(),
                "".to_string(),
                distance.to_string(),
                matches.to_string(),
            ),
            RegionMatch::Match {
                seq_match,
                distance,
                diff,
            } => (
                seq_match.sequence.to_str_or_log(),
                match diff {
                    Some(x) => x.to_string(),
                    None => "NA".to_string(),
                },
                distance.to_string(),
                "1".to_string(),
            ),
            RegionMatch::MultiMatch {
                seq_matches,
                distance,
                diffs,
            } => {
                let seqs: String = seq_matches
                    .iter()
                    .map(|x| x.sequence.to_str_or_log())
                    .join(",");

                let diff_str: String = match diffs {
                    None => "NA".to_string(),
                    Some(x) => x.iter().map(|x| x.to_string()).join(","),
                };

                let count = seq_matches.len().to_string();

                (seqs, diff_str, distance.to_string(), count)
            }
        }
    }
}

/// Compute the sequence diff for a region accounting for match type
fn compute_region_diff(
    observed: &SeqHandle,
    expected: &SeqHandle,
    completeness: RegionCompleteness,
    distance: u64,
) -> SequenceDiff {
    match completeness {
        RegionCompleteness::Complete => {
            SequenceDiff::compute_ids(observed, expected, TerminalFilter::None)
        }

        RegionCompleteness::Partial5Prime => {
            SequenceDiff::compute_ids(observed, expected, TerminalFilter::Leading)
        }

        RegionCompleteness::Partial3Prime => {
            SequenceDiff::compute_ids(observed, expected, TerminalFilter::Trailing)
        }

        RegionCompleteness::MissingCenter { split_ind } => {
            let obs = seq_to_bytes(observed);
            let exp = seq_to_bytes(expected);

            let left = &obs[..split_ind];
            let right = &obs[(split_ind + 1)..];

            let left_window = left.len() + distance as usize + DIFF_WINDOW_EXTRA;
            let right_window = right.len() + distance as usize + DIFF_WINDOW_EXTRA;

            let left_end = exp.len().min(left_window);
            let right_start = exp.len().saturating_sub(right_window);

            let mut out = SequenceDiff::compute(left, &exp[..left_end], TerminalFilter::Trailing);

            let right_diff =
                SequenceDiff::compute(right, &exp[right_start..], TerminalFilter::Leading)
                    .offset_expected_positions(right_start);

            out.operations.extend(right_diff.operations);
            out
        }

        RegionCompleteness::Overlapping { split_ind } => {
            let obs = seq_to_bytes(observed);
            let exp = seq_to_bytes(expected);

            let left = &obs[..split_ind];
            let right = &obs[(split_ind + 1)..];

            let left_window = left.len() + distance as usize + DIFF_WINDOW_EXTRA;
            let right_window = right.len() + distance as usize + DIFF_WINDOW_EXTRA;

            let left_end = exp.len().min(left_window);
            let right_start = exp.len().saturating_sub(right_window);

            let mut ops =
                SequenceDiff::compute(left, &exp[..left_end], TerminalFilter::Trailing).operations;

            ops.extend(
                SequenceDiff::compute(right, &exp[right_start..], TerminalFilter::Leading)
                    .offset_expected_positions(right_start)
                    .operations,
            );

            ops.sort_by_key(|op| match op {
                EditOperation::Sub(pos, ..) => (*pos, 0),
                EditOperation::Ins(pos, _) => (*pos, 1),
                EditOperation::Del(pos, _) => (*pos, 2),
            });
            ops.dedup();

            SequenceDiff::new(ops)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use crate::{
        interning::{library_id_from_str, region_id_from_str, region_id_to_str},
        seq_diff::EditOperation,
    };

    use super::*;

    fn make_region(id: &str, seq: &[u8], c: RegionCompleteness) -> ObservedRegion {
        ObservedRegion::new(region_id_from_str(id), seq_from_bytes(seq), c)
    }

    /// Creating a Complete region should preserve id, bytes, length, and completeness.
    #[test]
    fn new_complete_region_holds_data() {
        let r = make_region("barcode", b"ACGTACGT", RegionCompleteness::Complete);

        assert_eq!(region_id_to_str(&r.id).to_string(), "barcode");
        assert_eq!(seq_to_bytes(&r.seq).as_ref(), b"ACGTACGT");
        assert_eq!(r.len(), 8);
        assert!(matches!(r.completeness, RegionCompleteness::Complete));
    }

    /// Empty sequences are allowed and correctly reported.
    #[test]
    fn empty_sequence_is_valid() {
        let r = make_region("empty", b"", RegionCompleteness::Complete);
        assert_eq!(region_id_to_str(&r.id).to_string(), "empty");
        assert_eq!(r.len(), 0);
        assert!(r.is_empty());
        assert_eq!(seq_to_bytes(&r.seq).as_ref(), b"");
    }

    /// Byte content must be preserved exactly; no implicit normalisation should occur.
    #[test]
    fn preserves_bytes_verbatim() {
        let weird = b"ACGTNN--acgt\x00\xff";
        let r = make_region("weird", weird, RegionCompleteness::Complete);
        assert_eq!(
            seq_to_bytes(&r.seq).as_ref(),
            weird,
            "region bytes changed unexpectedly"
        );
        assert_eq!(r.len(), weird.len());
    }

    /// Regions should not alias their input slice; subsequent mutations to the source
    /// buffer (if any) must not affect the stored sequence.
    #[test]
    fn owns_its_sequence() {
        let mut buf = b"AAAA".to_vec();
        let r = make_region("id", &buf, RegionCompleteness::Complete);
        buf[0] = b'T'; // mutate the source buffer
        assert_eq!(
            seq_to_bytes(&r.seq).as_ref(),
            b"AAAA",
            "region leaked aliasing to input slice"
        );
    }

    /// Extremely short and extremely long sequences should not panic.
    #[test]
    fn size_extremes_smoke() {
        // Short (including 1-base)
        let r1 = make_region("s", b"A", RegionCompleteness::Complete);
        assert_eq!(r1.len(), 1);

        // Long (1e5 bytes) – keep modest to avoid slow tests; still catches realloc issues.
        let big = vec![b'G'; 100_000];
        let r2 = make_region("big", &big, RegionCompleteness::Complete);
        assert_eq!(r2.len(), 100_000);
        // spot-check end bytes to ensure contiguous storage
        assert_eq!(seq_to_bytes(&r2.seq).as_ref()[0], b'G');
        assert_eq!(seq_to_bytes(&r2.seq).as_ref()[99_999], b'G');
    }

    #[test]
    fn region_key_new() {
        let id = region_id_from_str("r1");
        let key = RegionKey::new(id, seq_from_bytes(b"ACGT"), RegionCompleteness::Complete);
        assert_eq!(&region_id_to_str(&key.id).to_string(), "r1");
        assert_eq!(key.sequence.to_str_or_log(), "ACGT");
        assert!(matches!(key.completeness, RegionCompleteness::Complete));
    }

    #[test]
    fn region_key_equality_all_same() {
        let id = region_id_from_str("r1");
        let key1 = RegionKey::new(
            id.clone(),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        let key2 = RegionKey::new(
            id.clone(),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        assert_eq!(key1, key2);
    }

    #[test]
    fn region_key_inequality_different_id() {
        let key1 = RegionKey::new(
            region_id_from_str("r1"),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        let key2 = RegionKey::new(
            region_id_from_str("r2"),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        assert_ne!(key1, key2);
    }

    #[test]
    fn region_key_inequality_different_sequence() {
        let id = region_id_from_str("r1");
        let key1 = RegionKey::new(
            id.clone(),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        let key2 = RegionKey::new(id, seq_from_bytes(b"GGGG"), RegionCompleteness::Complete);
        assert_ne!(key1, key2);
    }

    #[test]
    fn region_key_inequality_different_completeness() {
        let id = region_id_from_str("r1");
        let key1 = RegionKey::new(
            id.clone(),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        let key2 = RegionKey::new(
            id,
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Partial5Prime,
        );
        assert_ne!(key1, key2);
    }

    #[test]
    fn region_key_hash_consistency() {
        use std::collections::HashSet;

        let id = region_id_from_str("r1");
        let key1 = RegionKey::new(
            id.clone(),
            seq_from_bytes(b"ACGT"),
            RegionCompleteness::Complete,
        );
        let key2 = RegionKey::new(id, seq_from_bytes(b"ACGT"), RegionCompleteness::Complete);

        let mut set = HashSet::new();
        set.insert(key1);
        assert!(set.contains(&key2));
    }

    #[test]
    fn region_is_compared_to_library_uncompared() {
        let r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        assert!(!r.is_compared_to_library());
    }

    #[test]
    fn region_is_compared_after_match() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Unmatched;
        assert!(r.is_compared_to_library());
    }

    #[test]
    fn region_is_compared_after_unmatched() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Unmatched;
        assert!(r.is_compared_to_library());
    }

    #[test]
    fn region_is_compared_after_no_library() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::NoLibrary { seq: None };
        assert!(r.is_compared_to_library());
    }

    #[test]
    fn region_to_strings_uncompared() {
        let r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_to_strings_partial_5prime() {
        let r = make_region("r1", b"GT", RegionCompleteness::Partial5Prime);
        let (seq, _, _, _, _) = r.to_strings();
        assert_eq!(seq, "^GT");
    }

    #[test]
    fn region_to_strings_partial_3prime() {
        let r = make_region("r1", b"AC", RegionCompleteness::Partial3Prime);
        let (seq, _, _, _, _) = r.to_strings();
        assert_eq!(seq, "AC^");
    }

    #[test]
    fn region_to_strings_unmatched() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Unmatched;
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_to_strings_no_library() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::NoLibrary { seq: None };
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_to_strings_single_match() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Match {
            seq_match: Arc::new(LibraryRegion {
                ids: HashSet::from([library_id_from_str("lib1")]),
                inds: HashSet::from([1]),
                sequence: seq_from_bytes(b"ACGT"),
            }),
            distance: 0,
            diff: Some(SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')])),
        };
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "ACGT");
        assert_eq!(diff, "2A>G");
        assert_eq!(dist, "0");
        assert_eq!(count, "1");
    }

    #[test]
    fn region_to_strings_o_diff() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Match {
            seq_match: Arc::new(LibraryRegion {
                ids: HashSet::from([library_id_from_str("lib1")]),
                inds: HashSet::from([1]),
                sequence: seq_from_bytes(b"ACGT"),
            }),
            distance: 0,
            diff: None,
        };
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "ACGT");
        assert_eq!(diff, "NA");
        assert_eq!(dist, "0");
        assert_eq!(count, "1");
    }

    #[test]
    fn region_to_strings_overmatched() {
        let mut r = make_region("r1", b"ACGT", RegionCompleteness::Complete);
        r.nearest_matches = RegionMatch::Overmatched {
            distance: 2,
            matches: 50,
        };
        let (seq, match_seq, diff, dist, count) = r.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(match_seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "2");
        assert_eq!(count, "50");
    }

    #[test]
    fn region_match_to_strings_uncompared() {
        let m = RegionMatch::Uncompared;
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_match_to_strings_unmatched() {
        let m = RegionMatch::Unmatched;
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_match_to_strings_no_library() {
        let m = RegionMatch::NoLibrary { seq: None };
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "");
        assert_eq!(count, "0");
    }

    #[test]
    fn region_match_to_strings_single_match() {
        let m = RegionMatch::Match {
            seq_match: Arc::new(LibraryRegion {
                ids: HashSet::from([library_id_from_str("lib1")]),
                inds: HashSet::from([1]),
                sequence: seq_from_bytes(b"ACGT"),
            }),
            distance: 0,
            diff: Some(SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')])),
        };
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(diff, "2A>G");
        assert_eq!(dist, "0");
        assert_eq!(count, "1");
    }

    #[test]
    fn region_match_to_strings_no_diff() {
        let m = RegionMatch::Match {
            seq_match: Arc::new(LibraryRegion {
                ids: HashSet::from([library_id_from_str("lib1")]),
                inds: HashSet::from([1]),
                sequence: seq_from_bytes(b"ACGT"),
            }),
            distance: 0,
            diff: None,
        };
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "ACGT");
        assert_eq!(diff, "NA");
        assert_eq!(dist, "0");
        assert_eq!(count, "1");
    }

    #[test]
    fn region_match_to_strings_multi_match() {
        let l1 = Arc::new(LibraryRegion {
            ids: HashSet::from([library_id_from_str("lib1")]),
            inds: HashSet::from([1]),
            sequence: seq_from_bytes(b"ACGT"),
        });

        let l2 = Arc::new(LibraryRegion {
            ids: HashSet::from([library_id_from_str("lib2")]),
            inds: HashSet::from([1]),
            sequence: seq_from_bytes(b"CCGT"),
        });

        let d1 = SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')]);

        let d2 = SequenceDiff::new(vec![EditOperation::Sub(2, b'C', b'G')]);

        let m = RegionMatch::MultiMatch {
            seq_matches: vec![l1, l2],
            distance: 1,
            diffs: Some(vec![d1, d2]),
        };
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "ACGT,CCGT");
        assert_eq!(diff, "2A>G,3C>G");
        assert_eq!(dist, "1");
        assert_eq!(count, "2");
    }

    #[test]
    fn region_match_to_strings_overmatched() {
        let m = RegionMatch::Overmatched {
            distance: 5,
            matches: 100,
        };
        let (seq, diff, dist, count) = m.to_strings();
        assert_eq!(seq, "");
        assert_eq!(diff, "");
        assert_eq!(dist, "5");
        assert_eq!(count, "100");
    }

    #[test]
    fn region_match_equality_match_same_distance() {
        let l = Arc::new(LibraryRegion {
            ids: HashSet::from([library_id_from_str("lib1")]),
            inds: HashSet::from([1]),
            sequence: seq_from_bytes(b"ACGT"),
        });

        let d = SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')]);

        let m1 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 0,
            diff: Some(d.clone()),
        };

        let m2 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 0,
            diff: Some(d.clone()),
        };

        assert_eq!(m1, m2);
    }

    #[test]
    fn region_match_inequality_match_different_distance() {
        let l = Arc::new(LibraryRegion {
            ids: HashSet::from([library_id_from_str("lib1")]),
            inds: HashSet::from([1]),
            sequence: seq_from_bytes(b"ACGT"),
        });

        let d = SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')]);

        let m1 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 0,
            diff: Some(d.clone()),
        };

        let m2 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 1,
            diff: Some(d.clone()),
        };

        assert_ne!(m1, m2);
    }

    #[test]
    fn region_match_hash_consistency() {
        use std::collections::HashSet;

        let l = Arc::new(LibraryRegion {
            ids: HashSet::from([library_id_from_str("lib1")]),
            inds: HashSet::from([1]),
            sequence: seq_from_bytes(b"ACGT"),
        });

        let d = SequenceDiff::new(vec![EditOperation::Sub(1, b'A', b'G')]);

        let m1 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 0,
            diff: Some(d.clone()),
        };

        let m2 = RegionMatch::Match {
            seq_match: l.clone(),
            distance: 0,
            diff: Some(d.clone()),
        };

        let mut set = HashSet::new();
        set.insert(m1);
        assert!(set.contains(&m2));
    }

    #[test]
    fn region_len_consistency_with_seq() {
        let r = make_region("r1", b"ACGTACGTACGT", RegionCompleteness::Complete);
        assert_eq!(r.len(), 12);
        assert_eq!(r.len(), seq_to_bytes(&r.seq).len());
    }

    #[test]
    fn region_is_empty_true() {
        let r = make_region("r1", b"", RegionCompleteness::Complete);
        assert!(r.is_empty());
    }

    #[test]
    fn region_is_empty_false() {
        let r = make_region("r1", b"A", RegionCompleteness::Complete);
        assert!(!r.is_empty());
    }

    #[test]
    fn region_clone_yields_equal_ids() {
        let r1 = make_region("region1", b"ACGT", RegionCompleteness::Complete);
        let r1_id = r1.id.clone();
        let recovered = region_id_to_str(&r1_id);
        assert_eq!(&*recovered, "region1");
    }

    #[test]
    fn missing_center_diff_ignores_separator_and_center_gap() {
        let observed = seq_from_bytes(b"ACG/TAC");
        let expected = seq_from_bytes(b"ACGGGTAC");

        let diff = compute_region_diff(
            &observed,
            &expected,
            RegionCompleteness::MissingCenter { split_ind: 3 },
            0,
        );

        assert_eq!(diff.to_string(), "");
    }

    #[test]
    fn missing_center_diff_reports_left_and_right_variants() {
        let observed = seq_from_bytes(b"ATG/TTC");
        let expected = seq_from_bytes(b"ACGGGTAC");

        let diff = compute_region_diff(
            &observed,
            &expected,
            RegionCompleteness::MissingCenter { split_ind: 3 },
            2,
        );

        assert_eq!(diff.to_string(), "2C>T;7A>T");
    }
}