twitcher 0.9.2

Find template switch mutations in genomic data
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
//! Startup checks for settings that are legal, but ignored, unreachable or unlikely to be
//! intended.
//!
//! These are only ever warnings: an invocation may take hours, so it must not die on a heuristic.
//! Every finding is emitted as a `tracing::warn!`. Settings that cannot work at all, such as a cost
//! model the selected aligner cannot represent, are errors instead. They are raised where the
//! settings are turned into an aligner or a clusterizer, before these checks run, so the checks
//! here may assume a usable setup.
//!
//! The checks are split into pure functions returning the messages and thin wrappers that log
//! them, so that the logic is unit-testable without capturing logs.

use generic_a_star::cost::AStarCost;
use lib_tsalign::config::TemplateSwitchConfig;
use lib_tsalign::costs::U64Cost;
use lib_tsalign::costs::cost_function::CostFunction;
use lib_tsalign::costs::gap_affine::GapAffineAlignmentCostTable;

use compact_genome::implementation::alphabets::dna_alphabet_or_n::DnaAlphabetOrN;

use crate::common::aligner::chain;
use crate::common::aligner::cli::{CliAlignmentArgs, MLSSelector, URMSelector};
use crate::common::cluster_settings::{ClusterStrategy, ClusteringSettings};

type Costs = TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>;
type EditCosts = GapAffineAlignmentCostTable<DnaAlphabetOrN, U64Cost>;

fn infinite() -> U64Cost {
    U64Cost::from_primitive(u64::MAX)
}

/// Emits a warning for every questionable combination of alignment settings and costs.
pub fn warn_about_alignment_settings(args: &CliAlignmentArgs, costs: &Costs) {
    for message in alignment_setting_warnings(args, costs) {
        tracing::warn!("{message}");
    }
}

/// Emits a warning for every questionable combination of clustering settings.
pub fn warn_about_clustering_settings(settings: &ClusteringSettings) {
    for message in clustering_setting_warnings(settings) {
        tracing::warn!("{message}");
    }
}

/// The aligner selected on the command line, which decides what parts of the cost model are used.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Aligner {
    AStar,
    Fpa,
    Chain,
}

impl Aligner {
    const fn of(args: &CliAlignmentArgs) -> Self {
        if args.use_fpa {
            Self::Fpa
        } else if args.use_chain {
            Self::Chain
        } else {
            Self::AStar
        }
    }

    /// Whether this aligner can find template switches of the given geometry.
    const fn finds(self, inter_strand: bool, forward: bool) -> bool {
        match self {
            Self::AStar => true,
            Self::Fpa => inter_strand,
            Self::Chain => !forward,
        }
    }
}

/// The geometries with a finite base cost, each as `(inter_strand, forward)`.
fn enabled_geometries(costs: &Costs) -> impl Iterator<Item = (bool, bool)> {
    let base = &costs.base_cost;
    [
        (false, true, base.rrf),
        (false, false, base.rrr),
        (false, true, base.qqf),
        (false, false, base.qqr),
        (true, true, base.rqf),
        (true, false, base.rqr),
        (true, true, base.qrf),
        (true, false, base.qrr),
    ]
    .into_iter()
    .filter(|(.., cost)| *cost < infinite())
    .map(|(inter_strand, forward, _)| (inter_strand, forward))
}

/// Whether the aligner finds some enabled inter-strand (or intra-strand) geometry.
fn finds_some(aligner: Aligner, costs: &Costs, inter_strand: bool) -> bool {
    enabled_geometries(costs)
        .any(|(inter, forward)| inter == inter_strand && aligner.finds(inter, forward))
}

/// Whether some enabled geometry is one the aligner cannot find.
fn ignores_some_geometry(aligner: Aligner, costs: &Costs) -> bool {
    enabled_geometries(costs).any(|(inter, forward)| !aligner.finds(inter, forward))
}

/// Renders a finite bound of a cost table, or `unbounded` if there is none.
fn render_bound(bound: Option<isize>) -> String {
    bound.map_or_else(|| "unbounded".to_owned(), |bound| bound.to_string())
}

/// The finite bounds of an offset cost table, where `None` means unbounded in that direction.
///
/// Returns `None` if the table is infinite everywhere, i.e. if it permits no jump at all.
fn offset_bounds(costs: &CostFunction<isize, U64Cost>) -> Option<(Option<isize>, Option<isize>)> {
    let lower = costs.minimum_finite_input()?;
    Some((
        (lower != isize::MIN).then_some(lower),
        costs.maximum_finite_input(),
    ))
}

/// Returns true if the cost table is zero everywhere, i.e. if it imposes no preference and no
/// limit on the values it prices.
fn is_free<Input: Clone>(costs: &CostFunction<Input, U64Cost>) -> bool {
    let points: Vec<(Input, U64Cost)> = costs.clone().into();
    points
        .iter()
        .all(|(_, cost)| *cost == U64Cost::from_primitive(0))
}

/// Returns true if any base or gap in the table costs something to open.
fn charges_gap_open(costs: &EditCosts) -> bool {
    costs.max_gap_open_cost() != U64Cost::from_primitive(0)
}

fn has_flanks(costs: &Costs) -> bool {
    costs.left_flank_length != 0 || costs.right_flank_length != 0
}

/// Warnings about alignment settings that contradict each other or the loaded cost model.
///
/// `padding` bounds where a template switch may jump to, because it is the only ancestor
/// sequence the aligner ever sees. Cost tables that price jumps, inner lengths or geometries
/// beyond what `padding` can reach are therefore partly dead weight.
pub fn alignment_setting_warnings(args: &CliAlignmentArgs, costs: &Costs) -> Vec<String> {
    let mut warnings = Vec::new();
    let aligner = Aligner::of(args);

    if !args.no_ts {
        // `--no-ts` does the same thing but skips the machinery, so it is strictly faster.
        let reason = no_template_switch_reason(aligner, costs);
        if let Some(reason) = reason {
            warnings.push(format!(
                "No template switch can ever be found with these costs, because {reason}. Pass --no-ts to skip the template switch alignment entirely."
            ));
        }

        warnings.extend(reachability_warnings(args, aligner, costs));

        // `preprocess-filter` is implemented for reverse template switches only, so with forward
        // geometries enabled it prunes nothing at all.
        if aligner == Aligner::AStar
            && reason.is_none()
            && matches!(args.min_length_strategy, MLSSelector::PreprocessFilter)
            && enabled_geometries(costs).any(|(_, forward)| forward)
        {
            warnings.push(
                "Forward template switches are enabled, but the minimum length strategy `preprocess-filter` only prunes reverse template switches. Consider --min-length-strategy lookahead."
                    .to_owned(),
            );
        }
    }

    match aligner {
        Aligner::AStar => {
            // Flanks are documented as unsupported, and they additionally disable the equal-cost
            // extension of the alignment beyond its range.
            if has_flanks(costs) {
                warnings.push(format!(
                    "The cost model sets left_flank_length = {} and right_flank_length = {}. Flanks are not supported and additionally disable extending the alignment beyond its range; set both to 0.",
                    costs.left_flank_length, costs.right_flank_length,
                ));
            }
        }
        Aligner::Fpa => warnings.extend(fpa_warnings(costs, !args.no_ts)),
        Aligner::Chain => warnings.extend(chain_warnings(costs, !args.no_ts)),
    }

    // Neither the four-point aligner, the chaining aligner nor a run without template switches
    // acts on the flags that only configure the template switch search in the A* aligner. Passing
    // them is legal, so that one set of flags can be reused across a batch of runs, but it has no
    // effect.
    warnings.extend(ineffective_ts_flag_warnings(args));

    warnings
}

/// Why the aligner can never find a template switch with these costs, if it cannot.
fn no_template_switch_reason(aligner: Aligner, costs: &Costs) -> Option<&'static str> {
    let inter = finds_some(aligner, costs, true);
    let intra = finds_some(aligner, costs, false);
    let jumps = |table: &CostFunction<isize, U64Cost>| table.minimum_finite_input().is_some();

    match aligner {
        Aligner::AStar if costs.length_costs.minimum_finite_input().is_none() => {
            Some("the `Length` table is infinite everywhere")
        }
        Aligner::AStar if !inter && !intra => Some("all eight base costs are infinite"),
        Aligner::AStar
            if !((inter && jumps(&costs.rq_qr_offset_costs))
                || (intra && jumps(&costs.rr_qq_offset_costs))) =>
        {
            Some("every offset table for a geometry with a finite base cost is infinite everywhere")
        }
        Aligner::Fpa if !inter => Some(
            "the four-point aligner only finds inter-strand template switches, and their base costs `rqf`/`rqr`/`qrf`/`qrr` are all infinite",
        ),
        Aligner::Fpa if !jumps(&costs.rq_qr_offset_costs) => {
            Some("the `RQQROffset` table is infinite everywhere")
        }
        // `--chain` has already rejected a `Length` table that allows no length, and it does not
        // enforce the offset tables.
        Aligner::Chain if !inter && !intra => Some(
            "the chaining aligner only finds reverse template switches, and their base costs `rrr`/`rqr`/`qrr`/`qqr` are all infinite",
        ),
        _ => None,
    }
}

/// Warns about flags that only configure the template switch search of the A\* aligner, but were
/// combined with a mode that ignores them. Only a value that differs from the default is reported:
/// passing the default explicitly changes nothing either way, so it is not worth a warning.
fn ineffective_ts_flag_warnings(args: &CliAlignmentArgs) -> Vec<String> {
    let mode = if args.no_ts {
        "--no-ts disables template switch alignment"
    } else if args.use_fpa {
        "--fpa selects the four-point aligner"
    } else if args.use_chain {
        "--chain selects the chaining aligner"
    } else {
        return Vec::new();
    };

    let flags: Vec<_> = [
        (
            "--min-length-strategy",
            args.min_length_strategy != MLSSelector::default(),
        ),
        (
            "--uncertainty-range-mode",
            args.uncertainty_range_mode != URMSelector::default(),
        ),
        ("--allow-mixed-descendants", args.allow_mixed_descendants),
    ]
    .into_iter()
    .filter_map(|(flag, given)| given.then_some(flag))
    .collect();

    if flags.is_empty() {
        Vec::new()
    } else {
        vec![format!("{mode}, so {} has no effect.", flags.join(", "),)]
    }
}

/// Warnings about cost tables that price template switches the padded window can never contain.
fn reachability_warnings(args: &CliAlignmentArgs, aligner: Aligner, costs: &Costs) -> Vec<String> {
    let mut warnings = Vec::new();
    let padding = isize::try_from(args.padding).unwrap_or(isize::MAX);

    // The chaining aligner does not enforce the offset tables at all, see `chain_warnings`.
    let tables = [
        ("RQQROffset", &costs.rq_qr_offset_costs, true),
        ("RRQQOffset", &costs.rr_qq_offset_costs, false),
    ];
    for (name, table, inter_strand) in tables {
        if aligner == Aligner::Chain || !finds_some(aligner, costs, inter_strand) {
            continue;
        }
        let Some((lower, upper)) = offset_bounds(table) else {
            continue;
        };
        if lower.is_none_or(|lower| lower < -padding) || upper.is_none_or(|upper| upper > padding) {
            warnings.push(format!(
                "The `{name}` table prices template switch jumps in [{}, {}], but --padding {} limits reachable jumps to ±{}. Jumps beyond that can never be found; raise --padding or narrow the table.",
                render_bound(lower),
                render_bound(upper),
                args.padding,
                args.padding,
            ));
        }
    }

    // The inner segment is copied from the ancestor, which spans the cluster plus the padding on
    // both sides. Pricing lengths far beyond that only widens the search.
    let max_length = match aligner {
        Aligner::AStar => costs.length_costs.maximum_finite_input(),
        Aligner::Chain => chain::length_as_hard_range(&costs.length_costs)
            .ok()
            .and_then(|lengths| lengths.maximum_finite_input()),
        Aligner::Fpa => None,
    };
    if let Some(max_length) = max_length
        && max_length > args.padding.saturating_mul(2)
    {
        warnings.push(format!(
            "The `Length` table permits template switches of up to {max_length} bases, but with --padding {} only a little more than {} bases of template are available. Lower the longest permitted length, or raise --padding.",
            args.padding,
            args.padding.saturating_mul(2),
        ));
    }

    warnings
}

/// A single warning naming the configured parts of the cost model that the four-point aligner
/// silently disregards. Without template switches, only the edit costs matter.
fn fpa_warnings(costs: &Costs, template_switches: bool) -> Option<String> {
    let mut ignored = Vec::new();

    if charges_gap_open(&costs.primary_edit_costs)
        || (template_switches
            && (charges_gap_open(&costs.secondary_forward_edit_costs)
                || charges_gap_open(&costs.secondary_reverse_edit_costs)))
    {
        ignored.push("the gap open costs (the four-point aligner is not gap-affine)");
    }
    if template_switches {
        if !is_free(&costs.length_costs) {
            ignored.push("the `Length` table");
        }
        if !is_free(&costs.length_difference_costs) {
            ignored.push("the `LengthDifference` table");
        }
        if !is_free(&costs.forward_anti_descendant_gap_costs) {
            ignored.push("the `ForwardAntiDescendantGap` table");
        }
        if !is_free(&costs.reverse_anti_descendant_gap_costs) {
            ignored.push("the `ReverseAntiDescendantGap` table");
        }
        if ignores_some_geometry(Aligner::Fpa, costs) {
            ignored.push(
                "the intra-strand base costs `rrf`/`rrr`/`qqf`/`qqr` and the `RRQQOffset` table (the four-point aligner only finds inter-strand template switches)",
            );
        }
        if has_flanks(costs) {
            ignored.push("the flanks");
        }
    }

    (!ignored.is_empty()).then(|| {
        format!(
            "--fpa ignores parts of the cost model that are configured here: {}.",
            ignored.join(", "),
        )
    })
}

/// A single warning naming the configured parts of the cost model that the chaining aligner
/// silently disregards. Parts it cannot represent at all have failed at startup instead.
fn chain_warnings(costs: &Costs, template_switches: bool) -> Option<String> {
    // The edit costs it cannot represent are rejected, so all it ignores concerns template switches.
    if !template_switches {
        return None;
    }
    let mut ignored = Vec::new();

    if !is_free(&costs.length_difference_costs) {
        ignored.push("the `LengthDifference` table".to_owned());
    }
    if !is_free(&costs.forward_anti_descendant_gap_costs) {
        ignored.push("the `ForwardAntiDescendantGap` table".to_owned());
    }
    // These have to be zero on a single range, but the range is not enforced yet.
    let unenforced: Vec<_> = [
        (
            "`RQQROffset`",
            is_free(&costs.rq_qr_offset_costs) || !finds_some(Aligner::Chain, costs, true),
        ),
        (
            "`RRQQOffset`",
            is_free(&costs.rr_qq_offset_costs) || !finds_some(Aligner::Chain, costs, false),
        ),
        (
            "`ReverseAntiDescendantGap`",
            is_free(&costs.reverse_anti_descendant_gap_costs),
        ),
    ]
    .into_iter()
    .filter_map(|(name, irrelevant)| (!irrelevant).then_some(name))
    .collect();
    if !unenforced.is_empty() {
        ignored.push(format!(
            "the allowed ranges in {} (the chaining aligner does not enforce them, so only --padding bounds the jumps)",
            unenforced.join(", "),
        ));
    }
    if ignores_some_geometry(Aligner::Chain, costs) {
        ignored.push(
            "the forward base costs `rrf`/`rqf`/`qrf`/`qqf` (the chaining aligner only finds reverse template switches)"
                .to_owned(),
        );
    }
    let zero = U64Cost::from_primitive(0);
    let points: Vec<(usize, U64Cost)> = costs.length_costs.clone().into();
    if points
        .iter()
        .any(|(_, cost)| *cost != zero && *cost != infinite())
    {
        ignored.push(
            "the `Length` entries with a finite non-zero cost (those lengths are forbidden rather than penalised)"
                .to_owned(),
        );
    }

    (!ignored.is_empty()).then(|| {
        format!(
            "--chain ignores parts of the cost model that are configured here: {}.",
            ignored.join(", "),
        )
    })
}

/// Warnings about clustering settings whose gates are either inert or so tight that almost
/// nothing can pass them.
pub fn clustering_setting_warnings(settings: &ClusteringSettings) -> Vec<String> {
    let mut warnings = Vec::new();

    // A chain of events spaced `max_gap` apart approaches a density of `1 / (max_gap + 1)` from
    // above, so no legal cluster can ever fall below that.
    #[expect(clippy::cast_precision_loss)]
    let minimum_reachable_density = 1.0 / (settings.max_gap as f64 + 1.0);
    if settings.min_density != 0.0 {
        warnings.push("--cluster-min-density is not recommended to be used. See https://version.helsinki.fi/kraujasp/twitcher/-/work_items/76 for more info.".to_string());
        if settings.min_density <= minimum_reachable_density {
            warnings.push(format!(
            "--cluster-min-density {} can never reject a cluster, because --cluster-max-gap {} already forces a density above {minimum_reachable_density:.4}.",
            settings.min_density, settings.max_gap,
        ));
        } else if settings.strategy == ClusterStrategy::Legacy && settings.min_density > 1.0 {
            warnings.push(format!(
            "--cluster-min-density {} exceeds the density of a run of single nucleotide variants under --cluster-strategy legacy, so almost nothing will be clustered.",
            settings.min_density,
        ));
        }
    }

    if settings.strategy == ClusterStrategy::Legacy && settings.min_records == Some(1) {
        warnings.push(
            "--cluster-min-records 1 under --cluster-strategy legacy turns every single variant into a cluster to be realigned, which is slow and mostly produces noise."
                .to_owned(),
        );
    }

    warnings
}

#[cfg(test)]
mod tests {
    use super::*;

    const DEFAULT_TSA: &str = include_str!("../../default_costs.tsa");

    fn costs_from(tsa: &str) -> Costs {
        TemplateSwitchConfig::read_plain(tsa.as_bytes()).unwrap()
    }

    fn default_costs() -> Costs {
        costs_from(DEFAULT_TSA)
    }

    /// The default cost file with `from` replaced by `to`, to vary a single table per test.
    fn costs_with(from: &str, to: &str) -> Costs {
        assert!(
            DEFAULT_TSA.contains(from),
            "cost file does not contain {from:?}"
        );
        costs_from(&DEFAULT_TSA.replace(from, to))
    }

    fn assert_mentions(warnings: &[String], needle: &str) {
        assert!(
            warnings.iter().any(|w| w.contains(needle)),
            "expected a warning mentioning {needle:?}, got {warnings:#?}"
        );
    }

    /// The bundled costs must be self-consistent with the default padding, otherwise every plain
    /// invocation of twitcher emits warnings.
    #[test]
    fn default_settings_and_default_costs_are_silent() {
        let warnings = alignment_setting_warnings(&CliAlignmentArgs::default(), &default_costs());
        assert!(warnings.is_empty(), "{warnings:#?}");
        assert!(clustering_setting_warnings(&ClusteringSettings::default()).is_empty());
    }

    #[test]
    fn offset_window_wider_than_padding_warns() {
        let args = CliAlignmentArgs {
            padding: 30,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &default_costs()),
            "`RQQROffset` table prices template switch jumps in [-200, 200]",
        );
    }

    /// A table that is finite for every jump is unbounded, not merely too wide.
    #[test]
    fn unbounded_offset_window_warns() {
        let costs = costs_with(
            "RQQROffset\n -inf -200 201\n  inf    0 inf",
            "RQQROffset\n -inf\n    0",
        );
        assert_mentions(
            &alignment_setting_warnings(&CliAlignmentArgs::default(), &costs),
            "jumps in [unbounded, unbounded]",
        );
    }

    /// The intra-strand table is only reachable if some intra-strand geometry has a finite base
    /// cost, which the defaults do not have.
    #[test]
    fn unreachable_offset_table_is_not_warned_about() {
        let args = CliAlignmentArgs {
            padding: 30,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &default_costs());
        assert!(
            !warnings.iter().any(|w| w.contains("RRQQOffset")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn inner_length_beyond_the_available_template_warns() {
        let args = CliAlignmentArgs {
            padding: 30,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &default_costs()),
            "permits template switches of up to 400 bases",
        );
    }

    /// An unbounded `Length` table is taken as deliberate and not warned about.
    #[test]
    fn unbounded_inner_length_is_not_warned_about() {
        let costs = costs_with(
            "Length\n   0  5  6 7 8 401\n inf 15 10 5 0 inf",
            "Length\n   0 5\n inf 0",
        );
        let warnings = alignment_setting_warnings(&CliAlignmentArgs::default(), &costs);
        assert!(
            !warnings
                .iter()
                .any(|w| w.contains("permits template switches")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn cost_model_without_any_usable_geometry_warns() {
        let costs = costs_with(
            "rqr_cost = 2\nqrr_cost = 2",
            "rqr_cost = inf\nqrr_cost = inf",
        );
        assert_mentions(
            &alignment_setting_warnings(&CliAlignmentArgs::default(), &costs),
            "all eight base costs are infinite",
        );
    }

    #[test]
    fn cost_model_without_any_finite_length_warns() {
        let costs = costs_with(
            "Length\n   0  5  6 7 8 401\n inf 15 10 5 0 inf",
            "Length\n   0\n inf",
        );
        assert_mentions(
            &alignment_setting_warnings(&CliAlignmentArgs::default(), &costs),
            "the `Length` table is infinite everywhere",
        );
    }

    #[test]
    fn no_template_switch_possible_is_not_warned_about_with_no_ts() {
        let costs = costs_with(
            "rqr_cost = 2\nqrr_cost = 2",
            "rqr_cost = inf\nqrr_cost = inf",
        );
        let args = CliAlignmentArgs {
            no_ts: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &costs);
        assert!(
            !warnings.iter().any(|w| w.contains("No template switch")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn forward_geometry_with_preprocess_filter_warns() {
        let costs = costs_with("rqf_cost = inf", "rqf_cost = 8");
        assert_mentions(
            &alignment_setting_warnings(&CliAlignmentArgs::default(), &costs),
            "only prunes reverse template switches",
        );
    }

    #[test]
    fn no_ts_with_non_default_ts_flags_warns() {
        let args = CliAlignmentArgs {
            no_ts: true,
            uncertainty_range_mode: URMSelector::None,
            allow_mixed_descendants: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &default_costs()),
            "--uncertainty-range-mode, --allow-mixed-descendants has no effect",
        );
    }

    #[test]
    fn fpa_with_non_default_ts_flags_warns() {
        let args = CliAlignmentArgs {
            use_fpa: true,
            min_length_strategy: MLSSelector::Lookahead,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &default_costs()),
            "--min-length-strategy has no effect",
        );
    }

    /// Passing the default explicitly is indistinguishable from not passing it, and changes
    /// nothing either way, so it must not produce noise.
    #[test]
    fn no_ts_with_default_ts_flags_is_silent() {
        let args = CliAlignmentArgs {
            no_ts: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &default_costs());
        assert!(
            !warnings.iter().any(|w| w.contains("has no effect")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn forward_geometry_with_lookahead_is_silent() {
        let costs = costs_with("rqf_cost = inf", "rqf_cost = 8");
        let args = CliAlignmentArgs {
            min_length_strategy: MLSSelector::Lookahead,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &costs);
        assert!(
            !warnings.iter().any(|w| w.contains("prunes reverse")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn fpa_reports_the_cost_tables_it_ignores() {
        let args = CliAlignmentArgs {
            use_fpa: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &default_costs());
        assert_mentions(&warnings, "--fpa ignores parts of the cost model");
        assert_mentions(&warnings, "gap open costs");
        assert_mentions(&warnings, "the `Length` table");
        // Free everywhere in the defaults, so it must not be listed.
        assert!(
            !warnings
                .iter()
                .any(|w| w.contains("`ReverseAntiDescendantGap`")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn fpa_reports_unsupported_intra_strand_geometries() {
        let costs = costs_with("rrr_cost = inf", "rrr_cost = 3");
        let args = CliAlignmentArgs {
            use_fpa: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &costs),
            "only finds inter-strand template switches",
        );
    }

    #[test]
    fn chain_reports_the_cost_tables_it_ignores() {
        let args = CliAlignmentArgs {
            use_chain: true,
            padding: 30,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &default_costs());
        assert_mentions(&warnings, "--chain ignores parts of the cost model");
        assert_mentions(&warnings, "`LengthDifference`");
        assert_mentions(&warnings, "allowed ranges in `RQQROffset` (");
        assert_mentions(&warnings, "those lengths are forbidden");
        // Free everywhere or disabled in the defaults, so they must not be listed.
        for absent in [
            "`RRQQOffset`",
            "`ReverseAntiDescendantGap`",
            "forward base costs",
            "prices template switch jumps",
        ] {
            assert!(
                !warnings.iter().any(|w| w.contains(absent)),
                "{warnings:#?}"
            );
        }
    }

    #[test]
    fn chain_reports_forward_base_costs() {
        let costs = costs_with("rqf_cost = inf", "rqf_cost = 8");
        let args = CliAlignmentArgs {
            use_chain: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &costs);
        assert_mentions(&warnings, "only finds reverse template switches");
        assert!(
            !warnings.iter().any(|w| w.contains("only prunes reverse")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn chain_with_non_default_ts_flags_warns() {
        let args = CliAlignmentArgs {
            use_chain: true,
            allow_mixed_descendants: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &default_costs()),
            "--chain selects the chaining aligner, so --allow-mixed-descendants has no effect",
        );
    }

    #[test]
    fn chain_reports_the_unenforced_anti_descendant_gap_range() {
        let costs = costs_with(
            "ReverseAntiDescendantGap\n -inf\n    0",
            "ReverseAntiDescendantGap\n -inf -50 51\n  inf   0 inf",
        );
        let args = CliAlignmentArgs {
            use_chain: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &costs),
            "allowed ranges in `RQQROffset`, `ReverseAntiDescendantGap` (",
        );
    }

    /// The four-point aligner ignores the `Length` table, so it neither blocks template switches
    /// nor limits their length.
    #[test]
    fn fpa_does_not_judge_the_length_table() {
        let costs = costs_with(
            "Length\n   0  5  6 7 8 401\n inf 15 10 5 0 inf",
            "Length\n   0\n inf",
        );
        let args = CliAlignmentArgs {
            use_fpa: true,
            padding: 30,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &costs);
        assert!(
            !warnings.iter().any(
                |w| w.contains("No template switch") || w.contains("permits template switches")
            ),
            "{warnings:#?}"
        );
    }

    #[test]
    fn fpa_without_inter_strand_geometry_finds_nothing() {
        let costs = costs_with(
            "rrr_cost = inf\nrqr_cost = 2\nqrr_cost = 2",
            "rrr_cost = 3\nrqr_cost = inf\nqrr_cost = inf",
        );
        let args = CliAlignmentArgs {
            use_fpa: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &costs),
            "No template switch can ever be found with these costs, because the four-point aligner only finds inter-strand",
        );
        // The A* aligner does find the intra-strand geometry.
        let warnings = alignment_setting_warnings(&CliAlignmentArgs::default(), &costs);
        assert!(
            !warnings.iter().any(|w| w.contains("No template switch")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn chain_without_reverse_geometry_finds_nothing() {
        let costs = costs_with(
            "rqf_cost = inf\nqrf_cost = inf\nqqf_cost = inf\nrrr_cost = inf\nrqr_cost = 2\nqrr_cost = 2",
            "rqf_cost = 8\nqrf_cost = inf\nqqf_cost = inf\nrrr_cost = inf\nrqr_cost = inf\nqrr_cost = inf",
        );
        let args = CliAlignmentArgs {
            use_chain: true,
            ..Default::default()
        };
        assert_mentions(
            &alignment_setting_warnings(&args, &costs),
            "because the chaining aligner only finds reverse template switches",
        );
    }

    /// Without template switches, only the edit costs are left to be ignored.
    #[test]
    fn no_ts_reports_only_ignored_edit_costs() {
        let fpa = CliAlignmentArgs {
            use_fpa: true,
            no_ts: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&fpa, &default_costs());
        assert_mentions(&warnings, "gap open costs");
        assert!(
            !warnings.iter().any(|w| w.contains("`Length`")),
            "{warnings:#?}"
        );

        let chain = CliAlignmentArgs {
            use_chain: true,
            no_ts: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&chain, &default_costs());
        assert!(warnings.is_empty(), "{warnings:#?}");
    }

    #[test]
    fn fpa_lists_flanks_as_ignored() {
        let costs = costs_with("left_flank_length = 0", "left_flank_length = 5");
        let args = CliAlignmentArgs {
            use_fpa: true,
            ..Default::default()
        };
        let warnings = alignment_setting_warnings(&args, &costs);
        assert_mentions(&warnings, "the flanks");
        assert!(
            !warnings
                .iter()
                .any(|w| w.contains("Flanks are not supported")),
            "{warnings:#?}"
        );
    }

    #[test]
    fn nonzero_flanks_warn() {
        let costs = costs_with("left_flank_length = 0", "left_flank_length = 5");
        assert_mentions(
            &alignment_setting_warnings(&CliAlignmentArgs::default(), &costs),
            "Flanks are not supported",
        );
    }

    #[test]
    fn density_gate_that_can_never_reject_warns() {
        let settings = ClusteringSettings {
            min_density: 0.01,
            max_gap: 20,
            ..Default::default()
        };
        assert_mentions(
            &clustering_setting_warnings(&settings),
            "can never reject a cluster",
        );
    }

    #[test]
    fn density_gate_above_one_warns_under_legacy() {
        let settings = ClusteringSettings {
            min_density: 1.5,
            ..Default::default()
        };
        assert_mentions(
            &clustering_setting_warnings(&settings),
            "almost nothing will be clustered",
        );
    }

    #[test]
    fn single_record_clusters_warn_under_legacy() {
        let settings = ClusteringSettings {
            min_records: Some(1),
            ..Default::default()
        };
        assert_mentions(
            &clustering_setting_warnings(&settings),
            "--cluster-min-records 1 under --cluster-strategy legacy",
        );
    }

    #[test]
    fn single_record_clusters_are_expected_under_edit_mass() {
        let settings = ClusteringSettings {
            strategy: ClusterStrategy::EditMass,
            min_records: Some(1),
            ..Default::default()
        };
        assert!(clustering_setting_warnings(&settings).is_empty());
    }
}