Skip to main content

dima_core/
config.rs

1//! Analysis parameters, their defaults and their validation.
2//!
3//! Every default lives here, once; the CLI, the GUI and the documentation read them from this
4//! module. Parameters the user did not set are `None` and resolve to these defaults (or to a
5//! value derived from the data, such as the k-mer length from the alphabet), and the provenance
6//! records which happened.
7
8use std::fmt;
9use std::str::FromStr;
10
11use serde::{Deserialize, Serialize};
12
13use crate::error::{DimaError, Result};
14
15/// Default support threshold *T* (Tharanga et al. 2025, Methods: "default is 100 sequences,
16/// arbitrarily defined"; the paper's Fig. 2 shows 30, DiMA v5.0.9's default).
17pub const DEFAULT_SUPPORT_THRESHOLD: u64 = 100;
18/// Default k-mer length for proteins: 9, the length of peptides presented by HLA class I
19/// (Falk et al. 1991; Rammensee 1993; Tharanga et al. 2025).
20pub const DEFAULT_KMER_PROTEIN: usize = 9;
21/// Default k-mer length for nucleotides: 27, the coding sequence of a 9-mer.
22pub const DEFAULT_KMER_NUCLEOTIDE: usize = 27;
23/// Default value for empty or missing header fields (DiMA v5.0.9's `--header-fillna`).
24pub const DEFAULT_FILL: &str = "Unknown";
25/// Default HCS threshold (per cent): the paper's default, 100% (Tharanga et al. 2025, Methods).
26pub const DEFAULT_HCS_THRESHOLD: Percent = Percent::HUNDRED;
27/// Lower bound (exclusive) of the HCS threshold: above 50% the Index variant is unique.
28pub const HCS_THRESHOLD_MIN_EXCLUSIVE: Percent = Percent {
29    mantissa: 50,
30    scale: 0,
31};
32/// Records per input batch (upper bound).
33pub const BATCH_MAX_RECORDS: usize = 10_000;
34/// Bytes per input batch (upper bound, sequence and header bytes).
35pub const BATCH_MAX_BYTES: usize = 64 << 20;
36/// Minimum number of records examined by the first-batch probe (alphabet, header statistics),
37/// when the input has that many.
38pub const PROBE_MIN_RECORDS: usize = 1_000;
39/// Minimum number of probed records before a field can be reported as identifier-like.
40pub const ID_DIAG_MIN_RECORDS: usize = 100;
41/// Maximum number of mismatched headers listed in full.
42pub const MISMATCH_LOG_MAX: usize = 20;
43
44/// Sequence alphabet.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum Alphabet {
48    /// Amino acids.
49    Protein,
50    /// DNA (T; U is folded to T).
51    Dna,
52    /// RNA (U; T is folded to U).
53    Rna,
54}
55
56impl Alphabet {
57    /// `true` for DNA and RNA.
58    #[must_use]
59    pub const fn is_nucleotide(self) -> bool {
60        matches!(self, Self::Dna | Self::Rna)
61    }
62
63    /// Default k-mer length for this alphabet.
64    #[must_use]
65    pub const fn default_kmer_length(self) -> usize {
66        if self.is_nucleotide() {
67            DEFAULT_KMER_NUCLEOTIDE
68        } else {
69            DEFAULT_KMER_PROTEIN
70        }
71    }
72
73    /// Lower-case name.
74    #[must_use]
75    pub const fn as_str(self) -> &'static str {
76        match self {
77            Self::Protein => "protein",
78            Self::Dna => "dna",
79            Self::Rna => "rna",
80        }
81    }
82
83    /// Name used in generated query names ("Unknown Protein").
84    #[must_use]
85    pub const fn display_name(self) -> &'static str {
86        match self {
87            Self::Protein => "Protein",
88            Self::Dna => "DNA",
89            Self::Rna => "RNA",
90        }
91    }
92}
93
94impl fmt::Display for Alphabet {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(self.as_str())
97    }
98}
99
100/// Entropy estimator.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum Estimator {
104    /// The paper's rarefaction-regression correction (Tharanga et al. 2025, Fig. 2), computed
105    /// as its exact expectation.
106    #[default]
107    Dima,
108    /// Chao et al. (2013).
109    ChaoWangJost,
110    /// Miller (1955) and Madow.
111    MillerMadow,
112    /// Plug-in (maximum-likelihood) entropy, uncorrected.
113    Raw,
114}
115
116impl Estimator {
117    /// Every estimator.
118    pub const ALL: [Self; 4] = [Self::Dima, Self::ChaoWangJost, Self::MillerMadow, Self::Raw];
119
120    /// Command-line spelling.
121    #[must_use]
122    pub const fn cli_name(self) -> &'static str {
123        match self {
124            Self::Dima => "dima",
125            Self::ChaoWangJost => "chao-wang-jost",
126            Self::MillerMadow => "miller-madow",
127            Self::Raw => "raw",
128        }
129    }
130
131    /// Serialised (snake_case) name.
132    #[must_use]
133    pub const fn as_str(self) -> &'static str {
134        match self {
135            Self::Dima => "dima",
136            Self::ChaoWangJost => "chao_wang_jost",
137            Self::MillerMadow => "miller_madow",
138            Self::Raw => "raw",
139        }
140    }
141}
142
143/// How characters outside the alphabet are handled.
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum ValidationMode {
147    /// Stop at the first unknown character, reporting record and column.
148    #[default]
149    Strict,
150    /// Exclude k-mers containing unknown characters and report one aggregated diagnostic.
151    Permissive,
152    /// As permissive, and print the per-character table.
153    Report,
154}
155
156impl ValidationMode {
157    /// Serialised name.
158    #[must_use]
159    pub const fn as_str(self) -> &'static str {
160        match self {
161            Self::Strict => "strict",
162            Self::Permissive => "permissive",
163            Self::Report => "report",
164        }
165    }
166}
167
168/// Where a parameter's value came from (recorded in the provenance).
169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum Origin {
172    /// The documented default.
173    Default,
174    /// Set by the user.
175    User,
176    /// Derived from the data (for example the k-mer length from the alphabet).
177    Derived,
178}
179
180/// A resolved parameter value with its origin.
181#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
182pub struct Param<T> {
183    /// The value used.
184    pub value: T,
185    /// Where it came from.
186    pub origin: Origin,
187}
188
189impl<T> Param<T> {
190    /// A user-set value if present, else `fallback` with origin `otherwise`.
191    pub fn resolve(user: Option<T>, fallback: impl FnOnce() -> T, otherwise: Origin) -> Self {
192        match user {
193            Some(value) => Self {
194                value,
195                origin: Origin::User,
196            },
197            None => Self {
198                value: fallback(),
199                origin: otherwise,
200            },
201        }
202    }
203}
204
205/// An exact decimal percentage, used for thresholds that are compared with count ratios.
206///
207/// `"95.5"` is stored as 955 × 10⁻¹, and [`Percent::is_met_by`] compares
208/// `count / total × 100 ≥ value` in exact integer arithmetic, so a threshold never misses its
209/// boundary through floating-point rounding.
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
211pub struct Percent {
212    mantissa: u64,
213    scale: u32,
214}
215
216impl Percent {
217    /// 100%.
218    pub const HUNDRED: Self = Self {
219        mantissa: 100,
220        scale: 0,
221    };
222    /// Maximum number of decimal places accepted.
223    pub const MAX_DECIMALS: u32 = 9;
224
225    /// `true` when `count / total × 100 ≥ self`; `false` when `total` is 0.
226    #[must_use]
227    pub fn is_met_by(self, count: u64, total: u64) -> bool {
228        if total == 0 {
229            return false;
230        }
231        let lhs = u128::from(count) * 100 * 10u128.pow(self.scale);
232        let rhs = u128::from(self.mantissa) * u128::from(total);
233        lhs >= rhs
234    }
235
236    /// The value as a float (for display and serialisation).
237    #[must_use]
238    pub fn to_f64(self) -> f64 {
239        // Formatting then parsing yields the double nearest to the exact decimal.
240        self.to_string()
241            .parse()
242            .expect("a formatted decimal always parses")
243    }
244
245    /// Parses an HCS threshold: a decimal in (50, 100].
246    ///
247    /// # Errors
248    /// A usage error explaining the range when the text is not a decimal in (50, 100].
249    pub fn hcs_threshold(text: &str) -> Result<Self> {
250        let p: Self = text.parse().map_err(|e: ParsePercentError| {
251            DimaError::usage(format!("invalid HCS threshold {text:?}: {e}"))
252        })?;
253        p.check_hcs_range()?;
254        Ok(p)
255    }
256
257    /// Checks that an HCS threshold lies in (50, 100].
258    ///
259    /// # Errors
260    /// A usage error with the rationale when out of range.
261    pub fn check_hcs_range(self) -> Result<()> {
262        if self > HCS_THRESHOLD_MIN_EXCLUSIVE && self <= Self::HUNDRED {
263            Ok(())
264        } else {
265            Err(
266                DimaError::usage(format!("HCS threshold {self}% is outside (50, 100]")).with_hint(
267                    "above 50% the Index (most common) k-mer is unique, so a conserved sequence \
268                 is well defined; use e.g. 70, 90 or 100",
269                ),
270            )
271        }
272    }
273
274    fn cmp_value(self, other: Self) -> std::cmp::Ordering {
275        let s = self.scale.max(other.scale);
276        let a = u128::from(self.mantissa) * 10u128.pow(s - self.scale);
277        let b = u128::from(other.mantissa) * 10u128.pow(s - other.scale);
278        a.cmp(&b)
279    }
280}
281
282// Values are normalised (no trailing fractional zeros), so the derived structural equality is
283// value equality and agrees with this ordering.
284impl Ord for Percent {
285    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
286        self.cmp_value(*other)
287    }
288}
289
290impl PartialOrd for Percent {
291    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
292        Some(self.cmp(other))
293    }
294}
295
296impl fmt::Display for Percent {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        if self.scale == 0 {
299            return write!(f, "{}", self.mantissa);
300        }
301        let div = 10u64.pow(self.scale);
302        write!(
303            f,
304            "{}.{:0width$}",
305            self.mantissa / div,
306            self.mantissa % div,
307            width = self.scale as usize
308        )
309    }
310}
311
312/// Why a percentage could not be parsed.
313#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
314pub enum ParsePercentError {
315    /// Not of the form `digits[.digits]`.
316    #[error("expected a decimal number such as 70 or 95.5")]
317    Syntax,
318    /// More than [`Percent::MAX_DECIMALS`] decimal places.
319    #[error("at most 9 decimal places are supported")]
320    TooPrecise,
321    /// Above 100.
322    #[error("a percentage cannot exceed 100")]
323    AboveHundred,
324}
325
326impl FromStr for Percent {
327    type Err = ParsePercentError;
328
329    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
330        let t = text.trim();
331        let (int, frac) = t.split_once('.').unwrap_or((t, ""));
332        let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
333        if int.is_empty() || !digits(int) || !digits(frac) || (t.contains('.') && frac.is_empty()) {
334            return Err(ParsePercentError::Syntax);
335        }
336        let frac = frac.trim_end_matches('0');
337        let scale = u32::try_from(frac.len()).map_err(|_| ParsePercentError::TooPrecise)?;
338        if scale > Self::MAX_DECIMALS {
339            return Err(ParsePercentError::TooPrecise);
340        }
341        let int = int.trim_start_matches('0');
342        if int.len() > 3 {
343            return Err(ParsePercentError::AboveHundred);
344        }
345        let int_value: u64 = if int.is_empty() {
346            0
347        } else {
348            int.parse().map_err(|_| ParsePercentError::Syntax)?
349        };
350        let frac_value: u64 = if frac.is_empty() {
351            0
352        } else {
353            frac.parse().map_err(|_| ParsePercentError::Syntax)?
354        };
355        let p = Self {
356            mantissa: int_value * 10u64.pow(scale) + frac_value,
357            scale,
358        };
359        if p > Self::HUNDRED {
360            return Err(ParsePercentError::AboveHundred);
361        }
362        Ok(p)
363    }
364}
365
366impl Serialize for Percent {
367    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
368        s.serialize_f64(self.to_f64())
369    }
370}
371
372impl<'de> Deserialize<'de> for Percent {
373    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
374        let v = f64::deserialize(d)?;
375        if !v.is_finite() || v < 0.0 {
376            return Err(serde::de::Error::custom(
377                "percentage must be a finite number of at least 0",
378            ));
379        }
380        // `Display` for f64 is the shortest representation that round-trips, so a value
381        // written from an exact decimal is read back as that decimal.
382        format!("{v}").parse().map_err(serde::de::Error::custom)
383    }
384}
385
386/// Parameters of one analysis. `None` means "use the default" (or derive from the data).
387#[derive(Clone, Debug, Default, PartialEq)]
388pub struct AnalysisParams {
389    /// Sequence alphabet; `None` detects it from the data.
390    pub alphabet: Option<Alphabet>,
391    /// k-mer length; `None` uses the alphabet's default.
392    pub kmer_length: Option<usize>,
393    /// Support threshold *T*.
394    pub support_threshold: Option<u64>,
395    /// Entropy estimator.
396    pub estimator: Option<Estimator>,
397    /// Handling of characters outside the alphabet.
398    pub validation: Option<ValidationMode>,
399    /// Flag positions whose sample coverage is below this value (0–1).
400    pub min_coverage: Option<f64>,
401    /// Name of the analysed protein or gene; `None` derives it from the input file name.
402    pub query_name: Option<String>,
403    /// Names of the `|`-separated header fields.
404    pub header_format: Option<Vec<String>>,
405    /// Header fields to stratify variants by (default: all of `header_format`).
406    pub metadata_fields: Option<Vec<String>>,
407    /// Value used for empty header fields and mismatched headers.
408    pub header_fill: Option<String>,
409}
410
411impl AnalysisParams {
412    /// The `dima analyze` options that reproduce these parameters: long option names, unset
413    /// parameters omitted, header field lists joined with `|`. Front ends use it to record and
414    /// show the equivalent command (D103).
415    #[must_use]
416    pub fn to_args(&self) -> Vec<String> {
417        let mut args = Vec::new();
418        let mut opt = |name: &str, value: Option<String>| {
419            if let Some(v) = value {
420                args.push(format!("--{name}"));
421                args.push(v);
422            }
423        };
424        opt("alphabet", self.alphabet.map(|a| a.as_str().to_owned()));
425        opt("kmer-length", self.kmer_length.map(|k| k.to_string()));
426        opt(
427            "support-threshold",
428            self.support_threshold.map(|t| t.to_string()),
429        );
430        opt("estimator", self.estimator.map(|e| e.cli_name().to_owned()));
431        opt("validation", self.validation.map(|v| v.as_str().to_owned()));
432        opt("min-coverage", self.min_coverage.map(|c| c.to_string()));
433        opt("query-name", self.query_name.clone());
434        opt(
435            "header-format",
436            self.header_format.as_ref().map(|f| f.join("|")),
437        );
438        opt(
439            "metadata-fields",
440            self.metadata_fields.as_ref().map(|f| f.join("|")),
441        );
442        opt("header-fillna", self.header_fill.clone());
443        args
444    }
445
446    /// Checks the parameters that can be checked without data. Header names are checked by
447    /// the header module, `k ≤ alignment length` once the alignment length is known.
448    ///
449    /// # Errors
450    /// A usage error naming the parameter and the accepted range.
451    pub fn validate(&self) -> Result<()> {
452        if self.kmer_length == Some(0) {
453            return Err(DimaError::usage("k-mer length must be at least 1"));
454        }
455        if self.support_threshold == Some(0) {
456            return Err(
457                DimaError::usage("support threshold must be at least 1").with_hint(
458                    "positions with support above the threshold are eligible; the paper uses 100",
459                ),
460            );
461        }
462        if let Some(c) = self.min_coverage {
463            if !(0.0..=1.0).contains(&c) {
464                return Err(
465                    DimaError::usage(format!("minimum coverage {c} is outside [0, 1]"))
466                        .with_hint("sample coverage is a probability; for example 0.95"),
467                );
468            }
469        }
470        if let Some(name) = &self.query_name {
471            if name.trim().is_empty() {
472                return Err(DimaError::usage("query name must not be empty"));
473            }
474        }
475        if let Some(fill) = &self.header_fill {
476            if fill.trim().is_empty() {
477                return Err(DimaError::usage("header fill value must not be empty")
478                    .with_hint("empty values are what the fill value replaces; use e.g. Unknown"));
479            }
480        }
481        if self.metadata_fields.is_some() && self.header_format.is_none() {
482            return Err(
483                DimaError::usage("metadata fields need a header format").with_hint(
484                    "name the header fields with --header-format, e.g. 'Accession|Host|Year'",
485                ),
486            );
487        }
488        Ok(())
489    }
490
491    /// The support threshold with its origin.
492    #[must_use]
493    pub fn support_threshold(&self) -> Param<u64> {
494        Param::resolve(
495            self.support_threshold,
496            || DEFAULT_SUPPORT_THRESHOLD,
497            Origin::Default,
498        )
499    }
500
501    /// The estimator with its origin.
502    #[must_use]
503    pub fn estimator(&self) -> Param<Estimator> {
504        Param::resolve(self.estimator, Estimator::default, Origin::Default)
505    }
506
507    /// The validation mode with its origin.
508    #[must_use]
509    pub fn validation(&self) -> Param<ValidationMode> {
510        Param::resolve(self.validation, ValidationMode::default, Origin::Default)
511    }
512
513    /// The k-mer length with its origin, given the resolved alphabet.
514    #[must_use]
515    pub fn kmer_length(&self, alphabet: Alphabet) -> Param<usize> {
516        Param::resolve(
517            self.kmer_length,
518            || alphabet.default_kmer_length(),
519            Origin::Derived,
520        )
521    }
522
523    /// The header fill value with its origin.
524    #[must_use]
525    pub fn header_fill(&self) -> Param<String> {
526        Param::resolve(
527            self.header_fill.clone(),
528            || DEFAULT_FILL.to_owned(),
529            Origin::Default,
530        )
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn parameters_to_arguments() {
540        assert!(AnalysisParams::default().to_args().is_empty());
541        let p = AnalysisParams {
542            alphabet: Some(Alphabet::Dna),
543            kmer_length: Some(27),
544            estimator: Some(Estimator::ChaoWangJost),
545            min_coverage: Some(0.95),
546            header_format: Some(vec!["Accession".into(), "Host".into()]),
547            ..AnalysisParams::default()
548        };
549        assert_eq!(
550            p.to_args(),
551            [
552                "--alphabet",
553                "dna",
554                "--kmer-length",
555                "27",
556                "--estimator",
557                "chao-wang-jost",
558                "--min-coverage",
559                "0.95",
560                "--header-format",
561                "Accession|Host"
562            ]
563        );
564    }
565
566    #[test]
567    fn percent_parse_and_display() {
568        for (s, d) in [
569            ("70", "70"),
570            ("70.0", "70"),
571            ("095.50", "95.5"),
572            ("100", "100"),
573            ("100.000", "100"),
574            ("0.5", "0.5"),
575            ("99.999999999", "99.999999999"),
576            (" 80 ", "80"),
577        ] {
578            assert_eq!(s.parse::<Percent>().unwrap().to_string(), d, "{s}");
579        }
580        for s in [
581            "",
582            ".5",
583            "5.",
584            "1e2",
585            "-5",
586            "+5",
587            "nan",
588            "100.0000000001",
589            "7 0",
590            "١٠",
591        ] {
592            assert!(s.parse::<Percent>().is_err(), "{s:?}");
593        }
594        assert_eq!(
595            "100.1".parse::<Percent>(),
596            Err(ParsePercentError::AboveHundred)
597        );
598        assert_eq!(
599            "1000".parse::<Percent>(),
600            Err(ParsePercentError::AboveHundred)
601        );
602        assert_eq!(
603            "1.1234567891".parse::<Percent>(),
604            Err(ParsePercentError::TooPrecise)
605        );
606    }
607
608    #[test]
609    fn percent_exact_comparison() {
610        let p: Percent = "95.5".parse().unwrap();
611        // 191/200 = 95.5% exactly.
612        assert!(p.is_met_by(191, 200));
613        assert!(!p.is_met_by(190, 200));
614        let third: Percent = "66.666666667".parse().unwrap();
615        assert!(
616            !third.is_met_by(2, 3),
617            "2/3 = 66.6666666666… < 66.666666667"
618        );
619        assert!(Percent::HUNDRED.is_met_by(7, 7));
620        assert!(!Percent::HUNDRED.is_met_by(6, 7));
621        assert!(!Percent::HUNDRED.is_met_by(0, 0));
622        assert!(Percent::HUNDRED.is_met_by(u64::MAX, u64::MAX));
623        // (2^64 - 2) / (2^64 - 1) = 1 - 5.4e-20 still meets 99.999999999%; no overflow.
624        assert!(
625            "99.999999999"
626                .parse::<Percent>()
627                .unwrap()
628                .is_met_by(u64::MAX - 1, u64::MAX)
629        );
630        assert!(
631            !"99.999999999"
632                .parse::<Percent>()
633                .unwrap()
634                .is_met_by(99_999_999_998, 100_000_000_000)
635        );
636    }
637
638    #[test]
639    fn hcs_threshold_range() {
640        assert!(Percent::hcs_threshold("50").is_err());
641        assert!(Percent::hcs_threshold("50.000000001").is_ok());
642        assert!(Percent::hcs_threshold("100").is_ok());
643        assert!(Percent::hcs_threshold("100.5").is_err());
644        assert!(Percent::hcs_threshold("abc").is_err());
645        let e = Percent::hcs_threshold("40").unwrap_err();
646        assert_eq!(e.to_string(), "HCS threshold 40% is outside (50, 100]");
647        assert!(e.hint().unwrap().contains("Index"));
648    }
649
650    #[test]
651    fn percent_serde_round_trip() {
652        for s in ["70", "95.5", "100", "66.666666667"] {
653            let p: Percent = s.parse().unwrap();
654            let json = serde_json::to_string(&p).unwrap();
655            let back: Percent = serde_json::from_str(&json).unwrap();
656            assert_eq!(back, p, "{s} -> {json}");
657        }
658        assert_eq!(serde_json::to_string(&Percent::HUNDRED).unwrap(), "100.0");
659        assert!(serde_json::from_str::<Percent>("-1").is_err());
660    }
661
662    #[test]
663    fn params_validation_and_resolution() {
664        let mut p = AnalysisParams::default();
665        p.validate().unwrap();
666        assert_eq!(
667            p.support_threshold(),
668            Param {
669                value: 100,
670                origin: Origin::Default
671            }
672        );
673        assert_eq!(p.kmer_length(Alphabet::Dna).value, 27);
674        assert_eq!(p.kmer_length(Alphabet::Protein).origin, Origin::Derived);
675        assert_eq!(p.estimator().value, Estimator::Dima);
676        assert_eq!(p.validation().value, ValidationMode::Strict);
677        assert_eq!(p.header_fill().value, "Unknown");
678        p.support_threshold = Some(30);
679        assert_eq!(
680            p.support_threshold(),
681            Param {
682                value: 30,
683                origin: Origin::User
684            }
685        );
686        for bad in [
687            AnalysisParams {
688                kmer_length: Some(0),
689                ..Default::default()
690            },
691            AnalysisParams {
692                support_threshold: Some(0),
693                ..Default::default()
694            },
695            AnalysisParams {
696                min_coverage: Some(1.5),
697                ..Default::default()
698            },
699            AnalysisParams {
700                min_coverage: Some(f64::NAN),
701                ..Default::default()
702            },
703            AnalysisParams {
704                header_fill: Some(" ".into()),
705                ..Default::default()
706            },
707            AnalysisParams {
708                query_name: Some(String::new()),
709                ..Default::default()
710            },
711            AnalysisParams {
712                metadata_fields: Some(vec!["a".into()]),
713                ..Default::default()
714            },
715        ] {
716            assert_eq!(
717                bad.validate().unwrap_err().class(),
718                crate::error::ExitClass::Usage
719            );
720        }
721    }
722
723    #[test]
724    fn enum_names() {
725        assert_eq!(
726            serde_json::to_string(&Estimator::ChaoWangJost).unwrap(),
727            r#""chao_wang_jost""#
728        );
729        assert_eq!(Estimator::ChaoWangJost.cli_name(), "chao-wang-jost");
730        assert_eq!(serde_json::to_string(&Alphabet::Dna).unwrap(), r#""dna""#);
731        assert_eq!(
732            serde_json::to_string(&Origin::Derived).unwrap(),
733            r#""derived""#
734        );
735        for e in Estimator::ALL {
736            assert_eq!(
737                serde_json::to_string(&e).unwrap(),
738                format!("\"{}\"", e.as_str())
739            );
740        }
741    }
742}