use std::error::Error;
use std::fmt;
use crate::dim::{ContigNaming, Dimension, ReferenceId, Relation, Verdict, relate};
use crate::types::{DataKind, Dataset};
#[derive(Clone, Debug)]
pub struct Binding {
pub name: String,
pub dataset: Dataset,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Dimension,
ContigNaming,
ContigOrder,
Undeclared,
StepType,
}
impl ErrorKind {
#[must_use]
pub const fn heading(self) -> &'static str {
match self {
Self::Dimension => "DimensionError",
Self::ContigNaming => "ContigNamingError",
Self::ContigOrder => "ContigOrderError",
Self::Undeclared => "UndeclaredDimensionError",
Self::StepType => "StepTypeError",
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Dimension => "dimension",
Self::ContigNaming => "contig_naming",
Self::ContigOrder => "contig_order",
Self::Undeclared => "undeclared",
Self::StepType => "step_type",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Scope {
pub kind: &'static str,
pub value: String,
}
impl Scope {
#[must_use]
pub fn describe(&self) -> String {
format!("{} {}", self.kind, self.value)
}
#[must_use]
pub fn kinds(&self) -> String {
format!("{}s", self.kind)
}
}
impl fmt::Display for Scope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.describe())
}
}
#[derive(Clone, Debug)]
pub struct CheckError {
kind: ErrorKind,
step: String,
node: Option<usize>,
scope: Option<Scope>,
dimension: Option<Dimension>,
lines: Vec<String>,
detail: Option<String>,
conclusion: String,
}
impl CheckError {
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn step(&self) -> &str {
&self.step
}
#[must_use]
pub const fn node(&self) -> Option<usize> {
self.node
}
#[must_use]
pub const fn scope(&self) -> Option<&Scope> {
self.scope.as_ref()
}
#[must_use]
pub fn at_node(mut self, node: usize, scope: Option<Scope>) -> Self {
self.node = Some(node);
self.scope = scope;
self
}
#[must_use]
pub const fn dimension(&self) -> Option<Dimension> {
self.dimension
}
}
impl fmt::Display for CheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&write_error(self, true))
}
}
fn write_error(error: &CheckError, scoped: bool) -> String {
let mut out = format!("{} in step `{}`", error.kind.heading(), error.step);
if scoped && let Some(scope) = &error.scope {
out.push_str(&format!(" ({scope})"));
}
out.push(':');
for line in &error.lines {
out.push_str("\n ");
out.push_str(line);
}
if let Some(detail) = &error.detail {
out.push_str("\n ");
out.push_str(detail);
}
out.push_str("\n ");
out.push_str(&error.conclusion);
out
}
impl Error for CheckError {}
#[must_use]
pub fn check_step(step: &str, bindings: &[Binding]) -> Vec<CheckError> {
let mut errors = Vec::new();
for dimension in Dimension::ALL {
check_dimension(step, bindings, dimension, &mut errors);
}
errors
}
#[must_use]
pub fn disagreements(step: &str, bindings: &[Binding]) -> Vec<CheckError> {
let mut errors = Vec::new();
for dimension in Dimension::ALL {
let Some(applicable) = joined_on(bindings, dimension) else {
continue;
};
compare_known(step, dimension, &applicable, &mut errors);
}
errors
}
#[must_use]
pub fn requires(bindings: &[Binding], dimension: Dimension) -> bool {
joined_on(bindings, dimension).is_some_and(|applicable| is_required(dimension, &applicable))
}
fn check_dimension(
step: &str,
bindings: &[Binding],
dimension: Dimension,
errors: &mut Vec<CheckError>,
) {
let Some(applicable) = joined_on(bindings, dimension) else {
return;
};
let (known, unknown): (Vec<&Binding>, Vec<&Binding>) = applicable
.iter()
.partition(|binding| binding.dataset.dimensions().is_known(dimension));
if is_required(dimension, &applicable) && !unknown.is_empty() {
match known.first() {
Some(pivot) => errors.extend(
unknown
.iter()
.map(|binding| undeclared(step, dimension, binding, Some(pivot))),
),
None => errors.push(undeclared_all(step, dimension, &unknown)),
}
}
compare_known(step, dimension, &applicable, errors);
}
fn joined_on(bindings: &[Binding], dimension: Dimension) -> Option<Vec<&Binding>> {
let applicable: Vec<&Binding> = bindings
.iter()
.filter(|binding| binding.dataset.kind().applies(dimension))
.collect();
if applicable.len() < 2 {
return None;
}
if dimension == Dimension::ContigNaming
&& applicable
.iter()
.filter(|binding| binding.dataset.dimensions().reference.is_known())
.count()
>= 2
{
return None;
}
Some(applicable)
}
fn compare_known(
step: &str,
dimension: Dimension,
applicable: &[&Binding],
errors: &mut Vec<CheckError>,
) {
let known: Vec<&Binding> = applicable
.iter()
.copied()
.filter(|binding| binding.dataset.dimensions().is_known(dimension))
.collect();
if let Some((pivot, rest)) = known.split_first() {
errors.extend(
rest.iter()
.filter_map(|other| compare(step, dimension, pivot, other)),
);
}
}
fn is_required(dimension: Dimension, applicable: &[&Binding]) -> bool {
applicable.iter().enumerate().any(|(index, left)| {
applicable[index + 1..].iter().any(|right| {
required_pair(left.dataset.kind(), right.dataset.kind()).contains(&dimension)
})
})
}
#[must_use]
pub const fn required_pair(left: DataKind, right: DataKind) -> &'static [Dimension] {
use DataKind as K;
const REF: &[Dimension] = &[Dimension::Reference];
const COORDINATES: &[Dimension] = &[Dimension::Coordinates];
const REF_AND_SAMPLES: &[Dimension] = &[Dimension::Reference, Dimension::SampleSet];
const SAMPLES: &[Dimension] = &[Dimension::SampleSet];
const SAMPLES_AND_PAIRING: &[Dimension] = &[Dimension::SampleSet, Dimension::Pairing];
const NONE: &[Dimension] = &[];
match (left, right) {
(K::ResistanceReport, _) | (_, K::ResistanceReport) => NONE,
(K::Reads, K::Reference) | (K::Reference, K::Reads) => NONE,
(K::Reads, K::Intervals) | (K::Intervals, K::Reads) => NONE,
(K::Reads, K::Reads) => SAMPLES_AND_PAIRING,
(K::Reads, _) | (_, K::Reads) => SAMPLES,
(K::Intervals, _) | (_, K::Intervals) => COORDINATES,
(K::Reference, _) | (_, K::Reference) => REF,
(K::Alignment, K::Alignment) => REF,
(K::Alignment, K::Variants) | (K::Variants, K::Alignment) => REF_AND_SAMPLES,
(K::Variants, K::Variants) => REF_AND_SAMPLES,
}
}
fn compare(
step: &str,
dimension: Dimension,
left: &Binding,
right: &Binding,
) -> Option<CheckError> {
if dimension == Dimension::Reference {
return compare_reference(step, left, right);
}
let (a, b) = (left.dataset.dimensions(), right.dataset.dimensions());
let same = match dimension {
Dimension::Organism => a.organism.value() == b.organism.value(),
Dimension::ContigNaming => a.contig_naming.value() == b.contig_naming.value(),
Dimension::Coordinates => a.coordinates.value() == b.coordinates.value(),
Dimension::SampleSet => a.sample_set.value() == b.sample_set.value(),
Dimension::Pairing => a.pairing.value() == b.pairing.value(),
Dimension::QualityEncoding => a.quality_encoding.value() == b.quality_encoding.value(),
Dimension::Reference => unreachable(),
};
if same {
return None;
}
let kind = if dimension == Dimension::ContigNaming {
ErrorKind::ContigNaming
} else {
ErrorKind::Dimension
};
let detail = match dimension {
Dimension::SampleSet => {
let (Some(x), Some(y)) = (a.sample_set.value(), b.sample_set.value()) else {
return None;
};
x.same_members(y)
.then(|| "The same samples appear in both, in a different order.".to_owned())
}
_ => None,
};
Some(CheckError {
kind,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(dimension),
lines: vec![
value_line(left, dimension, None),
value_line(right, dimension, None),
],
detail,
conclusion: dimension.leading_question().to_owned(),
})
}
fn compare_reference(step: &str, left: &Binding, right: &Binding) -> Option<CheckError> {
let a = left.dataset.dimensions().reference.value()?;
let b = right.dataset.dimensions().reference.value()?;
let (data, reference, relation) = match (left.dataset.kind(), right.dataset.kind()) {
(DataKind::Reference, DataKind::Reference) => (a, b, Relation::Identical),
(DataKind::Reference, _) => (b, a, Relation::DataWithin),
(_, DataKind::Reference) => (a, b, Relation::DataWithin),
_ => (a, b, Relation::Compatible),
};
match relate(data, reference, relation) {
Verdict::Agree => None,
Verdict::NamingDiffers {
left: x,
right: y,
example,
} => Some(CheckError {
kind: ErrorKind::ContigNaming,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(Dimension::ContigNaming),
lines: vec![naming_line(left), naming_line(right)],
detail: None,
conclusion: naming_conclusion(x, y, &example),
}),
Verdict::OrderDiffers { .. } => Some(CheckError {
kind: ErrorKind::ContigOrder,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(Dimension::Reference),
lines: vec![order_line(left), order_line(right)],
detail: None,
conclusion: "The contigs agree but their order differs. Tools that require a \
matching sequence dictionary order, such as GATK, will reject this."
.to_owned(),
}),
Verdict::MissingContig { name, from } => Some(reference_error(
step,
left,
right,
format!("Contig `{name}` is not in {from}."),
)),
Verdict::ContigConflict { name, detail } => Some(reference_error(
step,
left,
right,
format!("Contig `{name}`: {detail}."),
)),
}
}
fn reference_error(step: &str, left: &Binding, right: &Binding, detail: String) -> CheckError {
let (a, b) = (left.dataset.dimensions(), right.dataset.dimensions());
let suffixes = match (a.reference.value(), b.reference.value()) {
(Some(x), Some(y)) if x.describe() == y.describe() => (
Some(format!(" [fingerprint {}]", x.fingerprint())),
Some(format!(" [fingerprint {}]", y.fingerprint())),
),
_ => (None, None),
};
CheckError {
kind: ErrorKind::Dimension,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(Dimension::Reference),
lines: vec![
value_line(left, Dimension::Reference, suffixes.0.as_deref()),
value_line(right, Dimension::Reference, suffixes.1.as_deref()),
],
detail: Some(detail),
conclusion: Dimension::Reference.leading_question().to_owned(),
}
}
fn naming_conclusion(
left: ContigNaming,
right: ContigNaming,
example: &(String, String),
) -> String {
if left == right && !example.0.is_empty() {
return format!(
"The contigs are otherwise identical, but the names differ (`{}` against `{}`). \
Add a renaming step, or use one naming style throughout.",
example.0, example.1
);
}
Dimension::ContigNaming.leading_question().to_owned()
}
fn value_line(binding: &Binding, dimension: Dimension, suffix: Option<&str>) -> String {
let dimensions = binding.dataset.dimensions();
let value = dimensions
.render(dimension)
.unwrap_or_else(|| "unknown".to_owned());
let source = dimensions
.source(dimension)
.map(crate::dim::Source::describe)
.unwrap_or_else(|| "source unknown".to_owned());
format!(
"{}.{dimension} = {value}{} ({source})",
binding.name,
suffix.unwrap_or_default()
)
}
fn naming_line(binding: &Binding) -> String {
let dimensions = binding.dataset.dimensions();
let value = dimensions
.render(Dimension::ContigNaming)
.or_else(|| {
dimensions
.reference
.value()
.map(|reference| reference.naming().describe().to_owned())
})
.unwrap_or_else(|| "unknown".to_owned());
let source = dimensions
.source(Dimension::ContigNaming)
.or_else(|| dimensions.source(Dimension::Reference))
.map(crate::dim::Source::describe)
.unwrap_or_else(|| "source unknown".to_owned());
format!("{}.contig_naming = {value} ({source})", binding.name)
}
fn order_line(binding: &Binding) -> String {
let dimensions = binding.dataset.dimensions();
let order = dimensions
.reference
.value()
.map(contig_order)
.unwrap_or_else(|| "unknown".to_owned());
let source = dimensions
.source(Dimension::Reference)
.map(crate::dim::Source::describe)
.unwrap_or_else(|| "source unknown".to_owned());
format!(
"{}.reference lists contigs in the order {order} ({source})",
binding.name
)
}
fn contig_order(reference: &ReferenceId) -> String {
const SHOWN: usize = 6;
let contigs = reference.contigs();
let listed: Vec<&str> = contigs
.iter()
.take(SHOWN)
.map(|contig| contig.name.as_str())
.collect();
if contigs.len() > SHOWN {
format!("{}, ... ({} in all)", listed.join(", "), contigs.len())
} else {
listed.join(", ")
}
}
fn undeclared(
step: &str,
dimension: Dimension,
binding: &Binding,
known: Option<&&Binding>,
) -> CheckError {
let mut lines = vec![unknown_line(binding, dimension)];
if let Some(other) = known {
lines.push(value_line(other, dimension, None));
}
CheckError {
kind: ErrorKind::Undeclared,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(dimension),
lines,
detail: None,
conclusion: format!(
"`{step}` needs {dimension} to agree. Declare it where you load the data."
),
}
}
fn undeclared_all(step: &str, dimension: Dimension, unknown: &[&Binding]) -> CheckError {
CheckError {
kind: ErrorKind::Undeclared,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(dimension),
lines: unknown
.iter()
.map(|binding| unknown_line(binding, dimension))
.collect(),
detail: None,
conclusion: format!(
"`{step}` needs {dimension} to agree, and nothing states it. \
Declare it where you load the data."
),
}
}
fn unknown_line(binding: &Binding, dimension: Dimension) -> String {
let reason = binding
.dataset
.dimensions()
.reason(dimension)
.unwrap_or("not recorded");
format!("{}.{dimension} is unknown ({reason})", binding.name)
}
const fn unreachable() -> bool {
false
}
#[must_use]
pub fn step_type_error(
step: &str,
param: &str,
expected: DataKind,
found: DataKind,
origin: &str,
) -> CheckError {
CheckError {
kind: ErrorKind::StepType,
step: step.to_owned(),
node: None,
scope: None,
dimension: None,
lines: vec![
format!("`{step}` declares {param}: {}", expected.name()),
format!("{param} was given {} (from {origin})", found.name()),
],
detail: None,
conclusion: format!(
"These must match. Did you pass the wrong value, or annotate `{step}` \
with the wrong type?"
),
}
}
#[must_use]
pub fn undeclared_at(
step: &str,
dimension: Dimension,
origin: &str,
reason: &str,
through: &[&str],
) -> CheckError {
let detail = match through {
[] => None,
steps => Some(format!(
"It reaches `{step}` through {}.",
list_steps(steps)
)),
};
CheckError {
kind: ErrorKind::Undeclared,
step: step.to_owned(),
node: None,
scope: None,
dimension: Some(dimension),
lines: vec![format!("{dimension} is unknown in {origin} ({reason})")],
detail,
conclusion: format!(
"`{step}` needs {dimension} to agree. Declare it where you load the data."
),
}
}
fn list_steps(steps: &[&str]) -> String {
let quoted: Vec<String> = steps.iter().map(|step| format!("`{step}`")).collect();
match quoted.split_last() {
None => String::new(),
Some((last, [])) => format!("step {last}"),
Some((last, rest)) => format!("steps {} and {last}", rest.join(", ")),
}
}
#[must_use]
pub fn summarise(errors: &[CheckError]) -> String {
if errors.is_empty() {
return "no problems found.".to_owned();
}
let mut places: Vec<String> = errors.iter().map(place).collect();
places.sort_unstable();
places.dedup();
format!(
"{} {} in {} {}.",
errors.len(),
plural(errors.len(), "error", "errors"),
places.len(),
plural(places.len(), "step", "steps")
)
}
fn place(error: &CheckError) -> String {
match error.node {
Some(node) => format!("#{node}"),
None => format!("`{}`", error.step),
}
}
#[must_use]
pub fn render(errors: &[CheckError]) -> String {
if errors.is_empty() {
return summarise(errors);
}
let mut groups: Vec<Group<'_>> = Vec::new();
for error in errors {
let key = error.scope.as_ref().map(|_| write_error(error, false));
let existing = key.as_deref().and_then(|key| {
groups
.iter()
.position(|group| group.key.as_deref() == Some(key))
});
match existing {
Some(at) => groups[at].rest.push(error),
None => groups.push(Group {
key,
first: error,
rest: Vec::new(),
}),
}
}
let mut paragraphs: Vec<String> = groups.iter().map(Group::render).collect();
paragraphs.push(summarise(errors));
paragraphs.join("\n\n")
}
struct Group<'a> {
key: Option<String>,
first: &'a CheckError,
rest: Vec<&'a CheckError>,
}
impl Group<'_> {
fn render(&self) -> String {
let mut out = self.first.to_string();
let named: Vec<&str> = self
.rest
.iter()
.filter_map(|error| error.scope.as_ref())
.map(|scope| scope.value.as_str())
.collect();
if let Some(scope) = self.first.scope.as_ref()
&& !named.is_empty()
{
let kind = if named.len() == 1 {
scope.kind.to_owned()
} else {
scope.kinds()
};
out.push_str(&format!(
"\n The same problem affects {} other {kind}: {}.",
named.len(),
named.join(", ")
));
}
out
}
}
const fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str {
if count == 1 { one } else { many }
}