whittle 1.0.0

Coordinate-consistent trimming of long-read uBAM and tagged FASTQ
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
//! De novo adapter inference from recurrent read-end sequences.
//!
//! Exact k-mer graphs establish consensus boundaries. Batched approximate
//! matching validates support and aligns primer extensions to conserved insert
//! starts. Catalog sequences annotate discoveries without choosing their bases.

use crate::adapter::search::{AmbiguousSearcher, hits, is_plain_acgt, new_ambiguous_searcher};
use crate::adapter::{Adapter, AdapterConfig, MIN_PATTERN_LEN, Role, edit_budget};

mod assemble;
mod boundary;
mod consensus;
mod degenerate;
mod kmer;
mod layers;
mod linkage;
mod support;
use assemble::*;
use boundary::*;
use consensus::*;
use degenerate::*;
use kmer::*;
use layers::*;
use linkage::*;
use support::*;

/// The physical read end from which a consensus was assembled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum End {
    /// Discovered in the 5' windows.
    Five,
    /// Discovered in the 3' windows.
    Three,
}

/// k-mer length used for end-window counting and assembly graph nodes.
const KMER_K: usize = 16;

/// Number of top exact k-mers retained per end for graph assembly.
const TOP_KMERS: usize = 500;

/// Length of the 5'/3' end window scanned per read for adapter discovery.
const WINDOW_LEN: usize = 100;

/// Minimum presence-fraction support required to keep a discovered adapter.
/// Support is the fraction of sampled end windows containing the consensus
/// within its length-scaled edit budget. Absolute support also limits sparse
/// discoveries in small samples.
const KEEP_SUPPORT: f64 = 0.01;

/// Minimum independently supporting read windows for a retained consensus.
const MIN_SUPPORT_WINDOWS: usize = 20;

/// Maximum windows used for alignment and support validation.
const RECOUNT_WINDOWS: usize = 4000;

/// Minimum k-mer support relative to the path peak at an assembly boundary.
const BOUNDARY_SUPPORT: f64 = 0.45;

/// Exact prefix length used to locate recurrent unprimed read starts.
const START_K: usize = 11;

/// Max total emitted length of a single `bounded_heaviest_path` consensus,
/// used by `peel_paths` so no single peel can run away in length.
const LMAX: usize = 100;

/// Maximum distinct insert-boundary anchors evaluated for one consensus.
/// Anchors are ranked by unprimed read-start support.
const MAX_BOUNDARY_ANCHORS: usize = 8;

/// Minimum fraction of a layer's windows that one member of a variable
/// layer must hold, below which a barcode panel would exceed 1000 members.
const VARIABLE_MEMBER_SUPPORT: f64 = 0.001;

/// Max number of adapters `peel_paths` will extract from one end's k-mer graph.
/// A barcode layer holds one family per barcode.
const MAX_ADAPTERS_PER_END: usize = 128;

/// Maximum discovery layers at one read end.
const MAX_LAYERS: usize = 8;

/// Bases from the physical read end searched for a candidate and its mirror.
const MIRROR_WINDOW: usize = 300;

/// Window tested for a mirror at the opposite end.
const MIRROR_SEGMENT: usize = KMER_K;

/// Depth difference between an inner segment and its mirror accepted as
/// symmetric, in bases.
const SYMMETRY_TOLERANCE: usize = 35;

/// Fraction of the terminal error rate allowed when locating a mirror, so
/// that a mirror does not extend past the sequence present at the read end.
const MIRROR_ERROR_RATE: f64 = 0.5;

/// Bases by which the tested window slides per mirror search.
const MIRROR_STEP: usize = 4;

/// Divisor of a candidate's support giving the fewest mirror occurrences
/// that count. A mirror occurs only in reads of the other orientation and is
/// searched at the stricter mirror error rate.
const MIRROR_SUPPORT_DIVISOR: usize = 8;

/// Percentage of a candidate's supporting windows in which it must start
/// within `ANCHOR_SLACK` of the boundary. A majority suffices once earlier
/// layers explain only part of the reads.
const ANCHORED_PERCENT: usize = 60;

/// Bases from the current boundary within which a hit counts as anchored at
/// it and advances it. The slack covers eroded or variable-length remnants
/// of the preceding layer.
const ANCHOR_SLACK: usize = 50;

/// Largest median distance from the physical read end at which an outermost
/// discovered sequence is a sequencing adapter, which splits reads at
/// interior hits; deeper sequences are end-only.
const ADAPTER_FLUSH: usize = 20;

/// Shortest end shared by candidates of one layer that is treated as a
/// neighbouring layer rather than part of the candidate.
const SHARED_END_MIN: usize = 12;

/// Percentage of the shorter of two candidates that their longest common
/// substring must cover for them to count as one family.
const FAMILY_OVERLAP_PERCENT: usize = 60;

/// Percentage of a candidate's supporting windows that a stronger candidate
/// of the same layer must share for the candidate to count as a sequencing
/// variant of it rather than a distinct family.
const VARIANT_OVERLAP_PERCENT: usize = 80;

/// Minimum percent identity for a catalog entry to be reported as the match
/// of an inferred adapter. A 16 to 32 bp anchor searched against every catalog
/// entry on both strands names something spurious well above the 60 percent
/// that its trimming budget alone would allow.
const NAME_IDENTITY_MIN: f32 = 85.0;

/// One discovered adapter with inference metadata. The bare `Adapter` (without
/// `support` and `name_hits`) is extracted only when building the trim config.
#[derive(Debug, Clone)]
pub struct InferredAdapter {
    /// Sequence used for trimming (or printed as the recommendation), named
    /// `inferred_N` by presentation order.
    pub adapter: Adapter,
    /// Complete sequence retained after boundary validation.
    pub assembled_seq: Vec<u8>,
    /// Fraction of sampled end windows containing the consensus within its
    /// edit budget.
    pub support: f64,
    /// Catalog entries within `NAME_IDENTITY_MIN` of the consensus, best
    /// first, as `(name, percent identity)`. An annotation, not the name.
    pub name_hits: Vec<(String, f32)>,
    /// Discovery layer, counted from the read end after any known sequences.
    pub layer: usize,
}

impl InferredAdapter {
    /// Returns the number of assembled bases excluded from the trimming sequence.
    pub fn uncertain_bases(&self) -> usize {
        self.assembled_seq
            .len()
            .saturating_sub(self.adapter.seq.len())
    }
}

/// A merged layer family ready for variant suppression: sequence, support,
/// supporting windows, their count, whether it carries an insert boundary,
/// its end, and its path weight.
type Ranked = (Vec<u8>, f64, Vec<bool>, usize, bool, End, u64);

/// Discovers supported technical sequences in layers from each read end. Known
/// sequences in `base` explain the outermost layers first; each accepted layer
/// moves the boundary inward and the next layer is assembled from the
/// unexplained sequence. A barcode construct is not a known sequence: its `N`
/// block would explain any read end. Equivalent assemblies share one trimming
/// pattern. Catalog and supplied FASTA entries provide names only after the
/// inferred boundaries are fixed.
pub fn discover(sample: &[&[u8]], base: &AdapterConfig) -> Vec<InferredAdapter> {
    let mut bounds = Boundaries::new(sample);
    let known: Vec<Vec<u8>> = base
        .adapters
        .iter()
        .filter(|a| !crate::adapter::is_construct(a))
        .map(|a| a.seq.to_ascii_uppercase())
        .collect();
    if !known.is_empty() {
        let mut active = vec![true; sample.len()];
        for _ in 0..MAX_LAYERS {
            active = advance_boundaries(
                sample,
                &mut bounds,
                &known,
                base.error_rate,
                &active,
                true,
                true,
            );
            if active.is_empty() {
                break;
            }
        }
    }
    let physical = Boundaries::new(sample);
    let (five_p, three_p) = layer_windows(sample, &physical, MIRROR_WINDOW);
    let five_phys: Vec<&[u8]> = stride_sample(
        &five_p.iter().map(|(_, w)| *w).collect::<Vec<_>>(),
        RECOUNT_WINDOWS,
    );
    let three_phys: Vec<&[u8]> = stride_sample(
        &three_p.iter().map(|(_, w)| *w).collect::<Vec<_>>(),
        RECOUNT_WINDOWS,
    );

    let mut searcher = crate::adapter::search::new_searcher_fwd();
    let mut strand_searcher = crate::adapter::search::new_searcher_fwd();
    let mut distinct: Vec<(Vec<u8>, f64, usize, bool, bool)> = Vec::new();
    // An accepted primer marks the insert boundary at its end; no layer lies
    // beyond it.
    let mut open = [true, true];
    // Opening k-mers of the strand-specific layers behind the divisions of
    // earlier layers.
    let mut strand_words: Vec<Vec<u8>> = Vec::new();
    // Sequences whose inner end is the insert boundary, as each read end
    // holds them: the marker-gene primers, and the accepted sequences that
    // end at the insert boundary.
    let mut insert_bounds: [Vec<Vec<u8>>; 2] = [
        crate::adapter::catalog::MARKER_PRIMERS
            .iter()
            .map(|p| p.to_vec())
            .collect(),
        crate::adapter::catalog::MARKER_PRIMERS
            .iter()
            .map(|p| crate::adapter::reverse_complement(p))
            .collect(),
    ];
    for layer in 0..MAX_LAYERS {
        let (mut five_w, mut three_w) = layer_windows(sample, &bounds, 2 * WINDOW_LEN);
        if !open[0] {
            five_w.clear();
        }
        if !open[1] {
            three_w.clear();
        }
        // Where the known sequences end at the start of the template of an
        // amplicon, as a primer does, no layer lies beyond them at that end.
        // A discovered layer that ends there ends at the insert boundary
        // itself and closes its end when accepted.
        if layer == 0 && !known.is_empty() {
            for (index, (end, windows)) in [(End::Five, &mut five_w), (End::Three, &mut three_w)]
                .into_iter()
                .enumerate()
            {
                let moved = |i: usize| match end {
                    End::Five => bounds.five[i] > 0,
                    End::Three => bounds.three[i] < sample[i].len(),
                };
                let texts: Vec<&[u8]> = windows
                    .iter()
                    .filter(|(i, _)| moved(*i))
                    .map(|(_, w)| *w)
                    .collect();
                let texts = stride_sample(&texts, RECOUNT_WINDOWS);
                if template_at_boundary(&texts, end) {
                    tracing::debug!(layer = layer + 1, ?end, "Template begins at the boundary");
                    windows.clear();
                    open[index] = false;
                }
            }
        }
        let five_texts: Vec<&[u8]> = five_w.iter().map(|(_, w)| *w).collect();
        let three_texts: Vec<&[u8]> = three_w.iter().map(|(_, w)| *w).collect();
        // Ranking statistics use windows distributed across the sample.
        let five_sample = stride_sample(&five_texts, RECOUNT_WINDOWS);
        let three_sample = stride_sample(&three_texts, RECOUNT_WINDOWS);
        let mut five = assemble(&five_texts, &three_phys, base, End::Five, layer == 0);
        let mut three = assemble(&three_texts, &five_phys, base, End::Three, layer == 0);
        // The insert boundary of a candidate that ends at it holds at both
        // read ends: at its own end, and reverse complemented at the other,
        // where the far primer of the molecule is read. A marker-gene primer
        // ends at the insert boundary as well. A candidate that reads on
        // past such an inner end continues into the insert.
        let mut layer_bounds = insert_bounds.clone();
        for (own, other, index) in [(&five, &three, 0), (&three, &five, 1)] {
            layer_bounds[index].extend(
                own.iter()
                    .filter(|c| c.2)
                    .map(|c| c.0.clone())
                    .chain(
                        other
                            .iter()
                            .filter(|c| c.2)
                            .map(|c| crate::adapter::reverse_complement(&c.0)),
                    )
                    .collect::<Vec<_>>(),
            );
        }
        end_at_insert_boundaries(&mut five, &layer_bounds[0], End::Five);
        end_at_insert_boundaries(&mut three, &layer_bounds[1], End::Three);
        strip_shared_ends(&mut five, base.error_rate);
        strip_shared_ends(&mut three, base.error_rate);
        let (five, five_variable) = with_variable_layer(
            &mut searcher,
            five,
            &five_texts,
            &five_sample,
            End::Five,
            base.error_rate,
        );
        let (three, three_variable) = with_variable_layer(
            &mut searcher,
            three,
            &three_texts,
            &three_sample,
            End::Three,
            base.error_rate,
        );
        let variable: Vec<Vec<u8>> = five_variable.into_iter().chain(three_variable).collect();
        let background = background_windows(sample, &bounds, WINDOW_LEN);
        let background = stride_sample(&background, RECOUNT_WINDOWS);

        // Insert stretches identified by their mirror also reject the graph
        // fragments that reconstruct part of them.
        let mut inserts: Vec<Vec<u8>> = Vec::new();
        let mut next_words: Vec<Vec<u8>> = Vec::new();
        let cut: Vec<(Vec<u8>, f64, bool, u64, End)> = five
            .into_iter()
            .map(|c| (c, End::Five))
            .chain(three.into_iter().map(|c| (c, End::Three)))
            .filter(|((seq, support, _, _, _, _), _)| {
                seq.len() >= MIN_PATTERN_LEN && (*support >= KEEP_SUPPORT || variable.contains(seq))
            })
            .filter_map(
                |((seq, support, boundary, weight, unbounded, divided), end)| {
                    // A division into strand-specific layers marks the
                    // candidate and the layers it divides into technical;
                    // their mirrors lie at a depth that depends on how much
                    // outer adapter each end keeps.
                    let strand = strand_words.iter().any(|word| {
                        !hits(
                            &mut strand_searcher,
                            word,
                            &seq,
                            edit_budget(base.error_rate, word.len()),
                        )
                        .is_empty()
                    });
                    if !divided.is_empty() || strand {
                        next_words.extend(divided);
                        return Some((seq, support, boundary, weight, end));
                    }
                    let (own, opposite) = match end {
                        End::Five => (&five_phys, &three_phys),
                        End::Three => (&three_phys, &five_phys),
                    };
                    // A mirror at the opposite end is the only insert evidence
                    // for a candidate the assembly window could not bound.
                    let (cut, insert) = symmetry_cut(&seq, end, own, opposite, base.error_rate);
                    if insert.len() >= MIN_PATTERN_LEN {
                        inserts.push(crate::adapter::reverse_complement(&insert));
                        inserts.push(insert);
                    }
                    let cut = cut?;
                    if unbounded && cut.len() == seq.len() {
                        return None;
                    }
                    Some((cut, support, boundary, weight, end))
                },
            )
            .collect();
        strand_words.extend(next_words);
        let mut candidates: Vec<(Vec<u8>, f64, u32, bool, u64, End)> = cut
            .into_iter()
            .filter(|(seq, _, _, _, _)| {
                !inserts
                    .iter()
                    .any(|insert| same_family(seq, insert, base.error_rate))
            })
            .filter_map(|(seq, support, boundary, weight, end)| {
                let count = windows_containing(
                    &mut searcher,
                    &seq,
                    &background,
                    edit_budget(base.error_rate, seq.len()),
                );
                if !background.is_empty() && count as f64 * 4.0 >= support * background.len() as f64
                {
                    return None;
                }
                let exact = windows_containing(&mut searcher, &seq, &five_sample, 0)
                    + windows_containing(&mut searcher, &seq, &three_sample, 0);
                tracing::debug!(sequence = %String::from_utf8_lossy(&seq), exact, "Layer candidate");
                Some((seq, support, exact, boundary, weight, end))
            })
            .collect();
        // Independently supported insert boundaries take precedence over graph
        // fragments that may include conserved insert sequence. Exact support
        // then distinguishes reconstructions from nearby sequencing-error variants.
        candidates.sort_by(|a, b| {
            b.3.cmp(&a.3)
                .then_with(|| {
                    if a.3 && b.3 {
                        b.2.cmp(&a.2)
                    } else {
                        std::cmp::Ordering::Equal
                    }
                })
                .then(b.4.cmp(&a.4))
                .then(b.2.cmp(&a.2))
                .then(b.1.total_cmp(&a.1))
                .then(b.0.len().cmp(&a.0.len()))
                .then(a.0.cmp(&b.0))
        });
        // Contained reconstructions and fragments merge into the heaviest
        // reconstruction of their family. A sequence supported `RUN_JUMP`
        // times better than the candidate containing it is the shared layer
        // of that candidate, not its fragment.
        let layer_candidates: Vec<(Vec<u8>, f64, u64, End)> = candidates
            .iter()
            .map(|(seq, support, _, _, weight, end)| (seq.clone(), *support, *weight, *end))
            .collect();
        let mut merged: Vec<(Vec<u8>, f64, u64, bool, End)> = Vec::new();
        for (seq, support, _, boundary, weight, end) in candidates {
            let matched = weight;
            // A family found again in a later layer, in reads its first
            // occurrence did not match, is not a new layer; a shorter
            // sequence contained in an earlier candidate is a layer that the
            // candidate fused with its neighbour. The heaviest
            // reconstruction represents a family with its own support.
            if distinct.iter().any(|(other, _, _, _, _)| {
                other.len() <= seq.len() + edit_budget(base.error_rate, seq.len())
                    && same_adapter(&seq, other, base.error_rate)
            }) {
                continue;
            } else if let Some((other, previous, best, _, _)) =
                merged.iter_mut().find(|(other, previous, _, _, _)| {
                    support < *previous * f64::from(RUN_JUMP)
                        && *previous < support * f64::from(RUN_JUMP)
                        && fragment_of(&seq, other, base.error_rate)
                })
            {
                if matched > *best {
                    *other = seq;
                    *best = matched;
                    *previous = support;
                }
            } else {
                merged.push((seq, support, matched, boundary, end));
            }
        }
        // Sequencing variants of a family occupy the same reads as the
        // family; distinct families occupy different reads.
        let layer_texts: Vec<&[u8]> = five_sample.iter().chain(&three_sample).copied().collect();
        let mut ranked: Vec<Ranked> = merged
            .into_iter()
            .map(|(seq, support, matched, boundary, end)| {
                let k = edit_budget(base.error_rate, seq.len());
                let mut windows = windows_covered(&mut searcher, &seq, &layer_texts, k);
                let mirror = crate::adapter::reverse_complement(&seq);
                for (window, hit) in
                    windows
                        .iter_mut()
                        .zip(windows_covered(&mut searcher, &mirror, &layer_texts, k))
                {
                    *window |= hit;
                }
                let own = windows.iter().filter(|&&w| w).count();
                (seq, support, windows, own, boundary, end, matched)
            })
            .collect();
        // Complete reconstructions rank above fragments that run into the
        // insert, which match more windows over fewer exact bases.
        ranked.sort_by(|a, b| {
            b.6.cmp(&a.6)
                .then(b.3.cmp(&a.3))
                .then(b.0.len().cmp(&a.0.len()))
                .then(a.0.cmp(&b.0))
        });
        let mut accepted: Vec<Vec<u8>> = Vec::new();
        let mut accepted_windows: Vec<Vec<bool>> = Vec::new();
        let mut accepted_ends: Vec<End> = Vec::new();
        let mut own_forms: Vec<(Vec<u8>, f64, End)> = Vec::new();
        for (seq, support, windows, own, boundary, end, matched) in ranked {
            // Members of a variable layer share their reads with the
            // constant layer behind them by construction.
            let member = variable
                .iter()
                .any(|v| same_adapter(&seq, v, base.error_rate));
            let shared = accepted_windows
                .iter()
                .map(|other| {
                    windows
                        .iter()
                        .zip(other)
                        .filter(|(a, b)| **a && **b)
                        .count()
                })
                .max()
                .unwrap_or(0);
            let variant = !member && shared * 100 >= own * VARIANT_OVERLAP_PERCENT;
            tracing::debug!(sequence = %String::from_utf8_lossy(&seq), matched, own, shared, variant, "Ranked candidate");
            if variant {
                continue;
            }
            let flush = layer == 0
                && known.is_empty()
                && [(End::Five, &five_phys), (End::Three, &three_phys)]
                    .iter()
                    .any(|(end, phys)| {
                        outer_depth(&mut searcher, &seq, phys, *end, base.error_rate)
                            <= ADAPTER_FLUSH
                    });
            if boundary {
                let index = usize::from(end == End::Three);
                open[index] = false;
                insert_bounds[index].push(seq.clone());
                insert_bounds[1 - index].push(crate::adapter::reverse_complement(&seq));
            }
            accepted_ends.push(end);
            accepted.push(seq.clone());
            if !member {
                accepted_windows.push(windows);
                // The other read end can hold a form of the family that
                // ends at a different base on the insert side. It is kept
                // beside the accepted form, so that an interior copy of it
                // aligns without paying for bases it lacks.
                let other_windows = match end {
                    End::Five => &three_sample,
                    End::Three => &five_sample,
                };
                if let Some(form) =
                    other_end_form(&seq, end, &layer_candidates, other_windows, base.error_rate)
                    && !distinct.iter().any(|(other, _, _, _, _)| *other == form.0)
                {
                    tracing::debug!(sequence = %String::from_utf8_lossy(&form.0), "Other end form");
                    distinct.push((form.0, form.1, layer, flush, false));
                }
                // The other end can also read the family in a form that the
                // accepted sequence does not trim, such as the same strand
                // of a hairpin adapter; that form is a layer of its own end.
                if let Some(own) =
                    untrimmed_other_end(&seq, end, &layer_candidates, other_windows, base)
                {
                    own_forms.push(own);
                }
            }
            distinct.push((seq, support, layer, flush, member));
        }
        for (seq, support, end) in own_forms {
            if accepted.contains(&seq) || distinct.iter().any(|(other, _, _, _, _)| *other == seq) {
                continue;
            }
            tracing::debug!(sequence = %String::from_utf8_lossy(&seq), "Other end layer");
            let flush = layer == 0
                && known.is_empty()
                && [(End::Five, &five_phys), (End::Three, &three_phys)]
                    .iter()
                    .any(|(end, phys)| {
                        outer_depth(&mut searcher, &seq, phys, *end, base.error_rate)
                            <= ADAPTER_FLUSH
                    });
            accepted_ends.push(end);
            accepted.push(seq.clone());
            distinct.push((seq, support, layer, flush, false));
        }
        tracing::debug!(
            layer = layer + 1,
            accepted = accepted.len(),
            "Discovery layer"
        );
        // An end without a layer here has none deeper either.
        for (index, end) in [End::Five, End::Three].into_iter().enumerate() {
            if !accepted_ends.contains(&end) {
                open[index] = false;
            }
        }
        if accepted.is_empty()
            || advance_boundaries(
                sample,
                &mut bounds,
                &accepted,
                base.error_rate,
                &vec![true; sample.len()],
                false,
                layer == 0,
            )
            .is_empty()
        {
            break;
        }
    }

    // A random tag behind an accepted layer has no recurrent k-mers and is
    // read from the base composition of the windows that hold the layer,
    // oriented inward from either physical end.
    let oriented: Vec<Vec<u8>> = five_phys
        .iter()
        .map(|w| w.to_ascii_uppercase())
        .chain(
            three_phys
                .iter()
                .map(|w| crate::adapter::reverse_complement(&w.to_ascii_uppercase())),
        )
        .collect();
    let oriented: Vec<&[u8]> = oriented.iter().map(Vec::as_slice).collect();
    let composition = base_composition(&oriented);
    // Known sequences precede every discovered layer. Barcodes are skipped:
    // a shared flank, not a random tag, lies behind the members of a panel.
    let known_layers = base
        .adapters
        .iter()
        .filter(|a| a.role != Role::Barcode && !crate::adapter::is_construct(a))
        .map(|a| (a.seq.to_ascii_uppercase(), 0));
    let discovered_layers = distinct
        .iter()
        .filter(|(_, _, _, _, member)| !member)
        .map(|(seq, _, layer, _, _)| (seq.clone(), *layer + 1));
    let preceding: Vec<(Vec<u8>, usize)> = known_layers.chain(discovered_layers).collect();
    let mut tags: Vec<(Vec<u8>, f64, usize, bool, bool)> = Vec::new();
    for (seq, layer) in preceding {
        for pattern in [seq.clone(), crate::adapter::reverse_complement(&seq)] {
            if let Some((tag, present)) = degenerate_layer(
                &mut searcher,
                &pattern,
                &oriented,
                composition,
                base.error_rate,
            ) && !tags.iter().any(|(other, _, _, _, _)| {
                *other == tag || *other == crate::adapter::reverse_complement(&tag)
            }) && !known
                .iter()
                .filter(|k| !is_plain_acgt(k))
                .any(|k| same_adapter(&tag, k, base.error_rate))
            {
                tracing::debug!(sequence = %String::from_utf8_lossy(&tag), "Degenerate layer");
                tags.push((
                    tag,
                    present as f64 / oriented.len() as f64,
                    layer,
                    false,
                    false,
                ));
            }
        }
    }
    let tag_seqs: Vec<Vec<u8>> = tags.iter().map(|t| t.0.clone()).collect();
    distinct.extend(tags);

    let refs = crate::adapter::preset::preset(crate::adapter::preset::Kit::ALL);
    let name_refs: Vec<Adapter> = refs
        .into_iter()
        .chain(base.adapters.iter().cloned())
        .collect();
    // Ambiguity codes align to any of their bases, so a degenerate layer is
    // named only by degenerate entries.
    let degenerate_refs: Vec<Adapter> = name_refs
        .iter()
        .filter(|r| !is_plain_acgt(&r.seq))
        .cloned()
        .collect();
    distinct.sort_by(|a, b| a.2.cmp(&b.2).then(b.1.total_cmp(&a.1)).then(a.0.cmp(&b.0)));
    distinct
        .into_iter()
        .enumerate()
        .map(|(i, (seq, support, layer, flush, member))| {
            let tag = tag_seqs.contains(&seq);
            let refs = if tag { &degenerate_refs } else { &name_refs };
            let name_hits = name_against(&seq, refs, base.error_rate);
            // A flush layer is an adapter unless it is a marker-gene primer,
            // whose site also lies inside genomic reads.
            let role = if flush && !crate::adapter::matches_marker_primer(&seq, base.error_rate) {
                Role::Adapter
            } else if member {
                Role::Barcode
            } else {
                Role::Primer
            };
            InferredAdapter {
                adapter: Adapter {
                    name: format!("inferred_{}", i + 1),
                    seq: if tag {
                        seq.clone()
                    } else {
                        crate::adapter::with_marker_codes(&seq, base.error_rate)
                    },
                    role,
                },
                assembled_seq: seq,
                support,
                name_hits,
                layer,
            }
        })
        .collect()
}

#[cfg(test)]
mod tests;