1use std::fmt;
9use std::str::FromStr;
10
11use serde::{Deserialize, Serialize};
12
13use crate::error::{DimaError, Result};
14
15pub const DEFAULT_SUPPORT_THRESHOLD: u64 = 100;
18pub const DEFAULT_KMER_PROTEIN: usize = 9;
21pub const DEFAULT_KMER_NUCLEOTIDE: usize = 27;
23pub const DEFAULT_FILL: &str = "Unknown";
25pub const DEFAULT_HCS_THRESHOLD: Percent = Percent::HUNDRED;
27pub const HCS_THRESHOLD_MIN_EXCLUSIVE: Percent = Percent {
29 mantissa: 50,
30 scale: 0,
31};
32pub const BATCH_MAX_RECORDS: usize = 10_000;
34pub const BATCH_MAX_BYTES: usize = 64 << 20;
36pub const PROBE_MIN_RECORDS: usize = 1_000;
39pub const ID_DIAG_MIN_RECORDS: usize = 100;
41pub const MISMATCH_LOG_MAX: usize = 20;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum Alphabet {
48 Protein,
50 Dna,
52 Rna,
54}
55
56impl Alphabet {
57 #[must_use]
59 pub const fn is_nucleotide(self) -> bool {
60 matches!(self, Self::Dna | Self::Rna)
61 }
62
63 #[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 #[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 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum Estimator {
104 #[default]
107 Dima,
108 ChaoWangJost,
110 MillerMadow,
112 Raw,
114}
115
116impl Estimator {
117 pub const ALL: [Self; 4] = [Self::Dima, Self::ChaoWangJost, Self::MillerMadow, Self::Raw];
119
120 #[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 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum ValidationMode {
147 #[default]
149 Strict,
150 Permissive,
152 Report,
154}
155
156impl ValidationMode {
157 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum Origin {
172 Default,
174 User,
176 Derived,
178}
179
180#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
182pub struct Param<T> {
183 pub value: T,
185 pub origin: Origin,
187}
188
189impl<T> Param<T> {
190 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
211pub struct Percent {
212 mantissa: u64,
213 scale: u32,
214}
215
216impl Percent {
217 pub const HUNDRED: Self = Self {
219 mantissa: 100,
220 scale: 0,
221 };
222 pub const MAX_DECIMALS: u32 = 9;
224
225 #[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 #[must_use]
238 pub fn to_f64(self) -> f64 {
239 self.to_string()
241 .parse()
242 .expect("a formatted decimal always parses")
243 }
244
245 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 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
282impl 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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
314pub enum ParsePercentError {
315 #[error("expected a decimal number such as 70 or 95.5")]
317 Syntax,
318 #[error("at most 9 decimal places are supported")]
320 TooPrecise,
321 #[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 format!("{v}").parse().map_err(serde::de::Error::custom)
383 }
384}
385
386#[derive(Clone, Debug, Default, PartialEq)]
388pub struct AnalysisParams {
389 pub alphabet: Option<Alphabet>,
391 pub kmer_length: Option<usize>,
393 pub support_threshold: Option<u64>,
395 pub estimator: Option<Estimator>,
397 pub validation: Option<ValidationMode>,
399 pub min_coverage: Option<f64>,
401 pub query_name: Option<String>,
403 pub header_format: Option<Vec<String>>,
405 pub metadata_fields: Option<Vec<String>>,
407 pub header_fill: Option<String>,
409}
410
411impl AnalysisParams {
412 #[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 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 #[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 #[must_use]
503 pub fn estimator(&self) -> Param<Estimator> {
504 Param::resolve(self.estimator, Estimator::default, Origin::Default)
505 }
506
507 #[must_use]
509 pub fn validation(&self) -> Param<ValidationMode> {
510 Param::resolve(self.validation, ValidationMode::default, Origin::Default)
511 }
512
513 #[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 #[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 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 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}