use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use md5::{Digest as _, Md5};
use super::ContigNaming;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Contig {
pub name: String,
pub length: Option<u64>,
pub md5: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContigOrder {
Dictionary,
Observed,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReferenceId {
label: Option<String>,
contigs: Vec<Contig>,
order: ContigOrder,
}
impl ReferenceId {
#[must_use]
pub fn new(label: Option<String>, contigs: Vec<Contig>) -> Self {
Self {
label,
contigs,
order: ContigOrder::Dictionary,
}
}
#[must_use]
pub fn from_records(label: Option<String>, contigs: Vec<Contig>) -> Self {
Self {
label,
contigs,
order: ContigOrder::Observed,
}
}
#[must_use]
pub const fn order(&self) -> ContigOrder {
self.order
}
#[must_use]
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
#[must_use]
pub fn contigs(&self) -> &[Contig] {
&self.contigs
}
#[must_use]
pub fn naming(&self) -> ContigNaming {
let prefixed = self
.contigs
.iter()
.filter(|contig| strip_chr(&contig.name).is_some())
.count();
if prefixed == 0 {
ContigNaming::Bare
} else if prefixed == self.contigs.len() {
ContigNaming::Prefixed
} else {
ContigNaming::Mixed
}
}
#[must_use]
pub fn describe(&self) -> String {
if let Some(label) = &self.label {
return label.clone();
}
match self.contigs.as_slice() {
[only] => match only.length {
Some(length) => format!("{} ({length} bp)", only.name),
None => format!("{} (length not recorded)", only.name),
},
contigs => {
let total: u64 = contigs.iter().filter_map(|contig| contig.length).sum();
format!("{} contigs, {total} bp", contigs.len())
}
}
}
#[must_use]
pub fn fingerprint(&self) -> String {
let mut hasher = Md5::new();
for contig in &self.contigs {
hasher.update(normalise(&contig.name).as_bytes());
hasher.update(b"\t");
hasher.update(
contig
.length
.map_or_else(String::new, |n| n.to_string())
.as_bytes(),
);
hasher.update(b"\t");
hasher.update(contig.md5.as_deref().unwrap_or("").to_ascii_lowercase());
hasher.update(b"\n");
}
let digest = hasher.finalize();
digest
.iter()
.take(6)
.map(|byte| format!("{byte:02x}"))
.collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relation {
Identical,
DataWithin,
Compatible,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Agree,
NamingDiffers {
left: ContigNaming,
right: ContigNaming,
example: (String, String),
},
OrderDiffers {
left: Vec<String>,
right: Vec<String>,
},
MissingContig {
name: String,
from: String,
},
ContigConflict {
name: String,
detail: String,
},
}
enum Outcome {
Agree,
Disjoint,
Differs(Verdict),
}
#[must_use]
pub fn relate(left: &ReferenceId, right: &ReferenceId, relation: Relation) -> Verdict {
if matches!(
compare(left, right, relation, Cow::Borrowed),
Outcome::Agree
) {
return Verdict::Agree;
}
match compare(left, right, relation, normalise) {
Outcome::Agree => Verdict::NamingDiffers {
left: left.naming(),
right: right.naming(),
example: naming_example(left, right),
},
Outcome::Disjoint => Verdict::Agree,
Outcome::Differs(verdict) => verdict,
}
}
fn naming_example(left: &ReferenceId, right: &ReferenceId) -> (String, String) {
let index: HashMap<Cow<'_, str>, &Contig> = right
.contigs
.iter()
.map(|contig| (normalise(&contig.name), contig))
.collect();
for contig in &left.contigs {
if let Some(other) = index.get(&normalise(&contig.name))
&& other.name != contig.name
{
return (contig.name.clone(), other.name.clone());
}
}
(String::new(), String::new())
}
fn compare<'a, F>(
left: &'a ReferenceId,
right: &'a ReferenceId,
relation: Relation,
key: F,
) -> Outcome
where
F: Fn(&'a str) -> Cow<'a, str>,
{
let index: HashMap<Cow<'a, str>, (usize, &Contig)> = right
.contigs
.iter()
.enumerate()
.map(|(position, contig)| (key(&contig.name), (position, contig)))
.collect();
let mut matched = Vec::with_capacity(left.contigs.len());
for contig in &left.contigs {
match index.get(&key(&contig.name)) {
Some((position, other)) => {
if let Some(detail) = disagreement(contig, other) {
return Outcome::Differs(Verdict::ContigConflict {
name: contig.name.clone(),
detail,
});
}
matched.push(*position);
}
None if relation == Relation::Compatible => {}
None => {
return Outcome::Differs(Verdict::MissingContig {
name: contig.name.clone(),
from: right.describe(),
});
}
}
}
if relation == Relation::Identical && right.contigs.len() != left.contigs.len() {
let left_keys: Vec<Cow<'a, str>> = left
.contigs
.iter()
.map(|contig| key(&contig.name))
.collect();
if let Some(extra) = right
.contigs
.iter()
.find(|contig| !left_keys.contains(&key(&contig.name)))
{
return Outcome::Differs(Verdict::MissingContig {
name: extra.name.clone(),
from: left.describe(),
});
}
}
let ordered = left.order == ContigOrder::Dictionary && right.order == ContigOrder::Dictionary;
if ordered && matched.windows(2).any(|pair| pair[0] >= pair[1]) {
return Outcome::Differs(Verdict::OrderDiffers {
left: names(left),
right: names(right),
});
}
if relation == Relation::Compatible
&& matched.is_empty()
&& !left.contigs.is_empty()
&& !right.contigs.is_empty()
{
return Outcome::Disjoint;
}
Outcome::Agree
}
fn names(reference: &ReferenceId) -> Vec<String> {
reference
.contigs
.iter()
.map(|contig| contig.name.clone())
.collect()
}
fn disagreement(left: &Contig, right: &Contig) -> Option<String> {
if let (Some(a), Some(b)) = (left.length, right.length)
&& a != b
{
return Some(format!("length {a} against {b}"));
}
match (&left.md5, &right.md5) {
(Some(a), Some(b)) if !a.eq_ignore_ascii_case(b) => Some(format!(
"same name and length but different sequence (MD5 {} against {})",
short(a),
short(b)
)),
_ => None,
}
}
fn short(md5: &str) -> String {
md5.chars().take(8).collect()
}
fn strip_chr(name: &str) -> Option<&str> {
let rest = name
.get(..3)
.filter(|head| head.eq_ignore_ascii_case("chr"))?;
let _ = rest;
let tail = &name[3..];
(!tail.is_empty()).then_some(tail)
}
fn normalise(name: &str) -> Cow<'_, str> {
match strip_chr(name) {
Some(rest) if rest.eq_ignore_ascii_case("m") => Cow::Borrowed("MT"),
Some(rest) => Cow::Borrowed(rest),
None => Cow::Borrowed(name),
}
}
impl fmt::Display for ReferenceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.describe())
}
}