use std::collections::{BTreeSet, HashMap, HashSet};
use std::error::Error;
use std::fmt;
use crate::check::{self, Binding, CheckError, Scope};
use crate::convert::{Conversion, Target};
use crate::dim::{CoordinateSystem, Dim, Dimension, Dimensions, Source, display_path};
use crate::hivdb::frame;
use crate::types::{DataKind, Dataset};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(usize);
impl NodeId {
#[must_use]
pub const fn from_index(index: usize) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Debug)]
pub struct Argument {
pub param: String,
pub declared: DataKind,
pub node: NodeId,
}
#[derive(Clone, Debug)]
pub struct StepSpec {
pub name: String,
pub output: DataKind,
pub coordinates: Option<CoordinateSystem>,
pub conversion: Option<Converted>,
pub arguments: Vec<Argument>,
}
#[derive(Clone, Debug)]
pub struct Converted {
pub conversion: &'static Conversion,
pub target: Target,
}
#[derive(Clone, Debug)]
pub enum GraphError {
UnknownNode {
step: String,
param: String,
node: NodeId,
},
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownNode { step, param, node } => write!(
f,
"step `{step}` binds {param} to node {}, which is not in the graph",
node.0
),
}
}
}
impl Error for GraphError {}
#[derive(Clone, Debug)]
enum Node {
Input {
label: String,
dataset: Dataset,
},
Step {
spec: StepSpec,
output: Dataset,
},
}
#[derive(Clone, Debug, Default)]
pub struct Graph {
nodes: Vec<Node>,
}
impl Graph {
#[must_use]
pub const fn new() -> Self {
Self { nodes: Vec::new() }
}
pub fn add_input(&mut self, label: &str, dataset: Dataset) -> NodeId {
self.nodes.push(Node::Input {
label: label.to_owned(),
dataset,
});
NodeId(self.nodes.len() - 1)
}
pub fn add_step(&mut self, spec: StepSpec) -> Result<NodeId, GraphError> {
for argument in &spec.arguments {
if argument.node.0 >= self.nodes.len() {
return Err(GraphError::UnknownNode {
step: spec.name.clone(),
param: argument.param.clone(),
node: argument.node,
});
}
}
let output = {
let inputs: Vec<&Dataset> = spec
.arguments
.iter()
.filter_map(|argument| self.dataset(argument.node))
.collect();
propagate(&spec, &inputs)
};
self.nodes.push(Node::Step { spec, output });
Ok(NodeId(self.nodes.len() - 1))
}
#[must_use]
pub fn dataset(&self, node: NodeId) -> Option<&Dataset> {
match self.nodes.get(node.0)? {
Node::Input { dataset, .. } => Some(dataset),
Node::Step { output, .. } => Some(output),
}
}
#[must_use]
pub const fn len(&self) -> usize {
self.nodes.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
#[must_use]
pub fn step(&self, node: NodeId) -> Option<&StepSpec> {
match self.nodes.get(node.index())? {
Node::Step { spec, .. } => Some(spec),
Node::Input { .. } => None,
}
}
#[must_use]
pub fn reachable_nodes(&self, roots: &[NodeId]) -> Vec<NodeId> {
self.reachable(roots)
.into_iter()
.map(NodeId::from_index)
.collect()
}
#[must_use]
pub fn step_names(&self, roots: &[NodeId]) -> Vec<&str> {
self.reachable(roots)
.into_iter()
.filter_map(|index| match &self.nodes[index] {
Node::Step { spec, .. } => Some(spec.name.as_str()),
Node::Input { .. } => None,
})
.collect()
}
#[must_use]
pub fn check(&self, roots: &[NodeId]) -> Vec<CheckError> {
let mut errors = Vec::new();
let mut demanded: HashSet<(usize, Dimension)> = HashSet::new();
let reachable = self.reachable(roots);
let scopes = self.scopes_within(&reachable);
for index in reachable {
let Node::Step { spec, .. } = &self.nodes[index] else {
continue;
};
let mut found = self.kind_errors(spec);
if found.is_empty() {
let bindings = self.bindings(spec);
found.extend(check::disagreements(&spec.name, &bindings));
self.demand(spec, &bindings, &mut demanded, &mut found);
found.extend(frame_errors(spec, &bindings));
}
let scope = scopes.get(&index).cloned();
errors.extend(
found
.into_iter()
.map(|error| error.at_node(index, scope.clone())),
);
}
errors
}
pub fn scopes(&self, roots: &[NodeId]) -> HashMap<NodeId, Scope> {
self.scopes_within(&self.reachable(roots))
.into_iter()
.map(|(index, scope)| (NodeId::from_index(index), scope))
.collect()
}
fn scopes_within(&self, reachable: &BTreeSet<usize>) -> HashMap<usize, Scope> {
let mut shared: HashMap<&str, Vec<usize>> = HashMap::new();
for index in reachable {
if let Some(Node::Step { spec, .. }) = self.nodes.get(*index) {
shared.entry(spec.name.as_str()).or_default().push(*index);
}
}
let mut scopes = HashMap::new();
for nodes in shared.into_values().filter(|nodes| nodes.len() > 1) {
if let Some(named) = self.distinguish(&nodes) {
scopes.extend(named);
}
}
scopes
}
fn distinguish(&self, nodes: &[usize]) -> Option<Vec<(usize, Scope)>> {
for discriminator in Discriminator::ALL {
let Some(named) = nodes
.iter()
.map(|index| {
let value = self.discriminate(NodeId(*index), discriminator)?;
Some((
*index,
Scope {
kind: discriminator.name(),
value,
},
))
})
.collect::<Option<Vec<(usize, Scope)>>>()
else {
continue;
};
let mut values: Vec<&str> = named.iter().map(|(_, s)| s.value.as_str()).collect();
values.sort_unstable();
let before = values.len();
values.dedup();
if values.len() == before {
return Some(named);
}
}
None
}
fn discriminate(&self, node: NodeId, discriminator: Discriminator) -> Option<String> {
match discriminator {
Discriminator::Sample => self.sample_of(node),
Discriminator::File => self.first_file(node),
}
}
fn sample_of(&self, node: NodeId) -> Option<String> {
let output = self.dataset(node)?;
if output.kind().applies(Dimension::SampleSet) {
return single_sample(output);
}
let Some(Node::Step { spec, .. }) = self.nodes.get(node.0) else {
return None;
};
let mut agreed: Option<String> = None;
for argument in &spec.arguments {
let Some(dataset) = self.dataset(argument.node) else {
continue;
};
if !dataset.kind().applies(Dimension::SampleSet) {
continue;
}
match single_sample(dataset) {
Some(sample) if agreed.as_ref().is_none_or(|seen| *seen == sample) => {
agreed = Some(sample);
}
_ => return None,
}
}
agreed
}
fn first_file(&self, node: NodeId) -> Option<String> {
let mut stack = vec![node];
let mut seen = BTreeSet::new();
while let Some(current) = stack.pop() {
if !seen.insert(current.0) {
continue;
}
match self.nodes.get(current.0) {
Some(Node::Input { dataset, .. }) => {
if let Some(path) = dataset.path() {
return Some(display_path(path));
}
}
Some(Node::Step { spec, .. }) => {
stack.extend(spec.arguments.iter().rev().map(|a| a.node));
}
None => {}
}
}
None
}
fn kind_errors(&self, spec: &StepSpec) -> Vec<CheckError> {
spec.arguments
.iter()
.filter_map(|argument| {
let dataset = self.dataset(argument.node)?;
(dataset.kind() != argument.declared).then(|| {
check::step_type_error(
&spec.name,
&argument.param,
argument.declared,
dataset.kind(),
&self.describe(argument.node),
)
})
})
.collect()
}
fn bindings(&self, spec: &StepSpec) -> Vec<Binding> {
spec.arguments
.iter()
.filter_map(|argument| {
Some(Binding {
name: argument.param.clone(),
dataset: self.dataset(argument.node)?.clone(),
})
})
.collect()
}
fn demand(
&self,
spec: &StepSpec,
bindings: &[Binding],
demanded: &mut HashSet<(usize, Dimension)>,
errors: &mut Vec<CheckError>,
) {
for dimension in Dimension::ALL {
if !check::requires(bindings, dimension) {
continue;
}
for argument in &spec.arguments {
let Some(dataset) = self.dataset(argument.node) else {
continue;
};
if !dataset.kind().applies(dimension) || dataset.dimensions().is_known(dimension) {
continue;
}
let origin = self.origin_of(argument.node, dimension);
if !demanded.insert((origin.0, dimension)) {
continue;
}
errors.push(check::undeclared_at(
&spec.name,
dimension,
&self.describe(origin),
self.reason(origin, dimension),
&self.route(argument.node, origin, dimension),
));
}
}
}
fn origin_of(&self, node: NodeId, dimension: Dimension) -> NodeId {
let mut node = node;
loop {
let Some(Node::Step { spec, .. }) = self.nodes.get(node.0) else {
return node;
};
if introduces(spec, dimension) {
return node;
}
match self.first_applicable(spec, dimension) {
Some(next) => node = next,
None => return node,
}
}
}
fn route(&self, from: NodeId, origin: NodeId, dimension: Dimension) -> Vec<&str> {
let mut steps = Vec::new();
let mut node = from;
while node != origin {
let Some(Node::Step { spec, .. }) = self.nodes.get(node.0) else {
break;
};
steps.push(spec.name.as_str());
match self.first_applicable(spec, dimension) {
Some(next) => node = next,
None => break,
}
}
steps.reverse();
steps
}
fn first_applicable(&self, spec: &StepSpec, dimension: Dimension) -> Option<NodeId> {
spec.arguments
.iter()
.find(|argument| {
self.dataset(argument.node)
.is_some_and(|dataset| dataset.kind().applies(dimension))
})
.map(|argument| argument.node)
}
fn reason(&self, node: NodeId, dimension: Dimension) -> &'static str {
self.dataset(node)
.and_then(|dataset| dataset.dimensions().reason(dimension))
.unwrap_or("not recorded")
}
fn describe(&self, node: NodeId) -> String {
match self.nodes.get(node.0) {
Some(Node::Input { label, dataset }) => dataset
.path()
.map_or_else(|| format!("input `{label}`"), display_path),
Some(Node::Step { spec, .. }) => format!("step `{}`", spec.name),
None => "an unknown node".to_owned(),
}
}
fn reachable(&self, roots: &[NodeId]) -> BTreeSet<usize> {
let mut seen = BTreeSet::new();
let mut pending: Vec<NodeId> = roots.to_vec();
while let Some(node) = pending.pop() {
if node.0 >= self.nodes.len() || !seen.insert(node.0) {
continue;
}
if let Node::Step { spec, .. } = &self.nodes[node.0] {
pending.extend(spec.arguments.iter().map(|argument| argument.node));
}
}
seen
}
}
#[derive(Clone, Copy, Debug)]
enum Discriminator {
Sample,
File,
}
impl Discriminator {
const ALL: [Self; 2] = [Self::Sample, Self::File];
const fn name(self) -> &'static str {
match self {
Self::Sample => "sample",
Self::File => "file",
}
}
}
fn single_sample(dataset: &Dataset) -> Option<String> {
match dataset.dimensions().sample_set.value()?.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
}
fn frame_errors(spec: &StepSpec, bindings: &[Binding]) -> Vec<CheckError> {
if spec.output != DataKind::ResistanceReport {
return Vec::new();
}
bindings
.iter()
.filter(|binding| binding.dataset.kind() == DataKind::Reference)
.filter_map(|binding| {
let reference = binding.dataset.dimensions().reference.value()?;
let mismatch = frame::mismatch(reference)?;
Some(check::reference_frame(
&spec.name,
binding,
&frame::expected(),
mismatch.detail(),
mismatch.conclusion(),
))
})
.collect()
}
fn introduces(spec: &StepSpec, dimension: Dimension) -> bool {
dimension == Dimension::Coordinates && spec.output.applies(Dimension::Coordinates)
}
fn propagate(spec: &StepSpec, inputs: &[&Dataset]) -> Dataset {
let step = spec.name.as_str();
let output = spec.output;
let mut dimensions = Dimensions::default();
if output.applies(Dimension::Organism) {
dimensions.organism = inherit(step, Dimension::Organism, inputs, |d| &d.organism);
}
if output.applies(Dimension::Reference) {
dimensions.reference = inherit(step, Dimension::Reference, inputs, |d| &d.reference);
}
if output.applies(Dimension::ContigNaming) {
dimensions.contig_naming =
inherit(step, Dimension::ContigNaming, inputs, |d| &d.contig_naming);
}
if output.applies(Dimension::Coordinates) {
dimensions.coordinates = coordinates(spec);
}
if output.applies(Dimension::SampleSet) {
dimensions.sample_set = inherit(step, Dimension::SampleSet, inputs, |d| &d.sample_set);
}
if output.applies(Dimension::Pairing) {
dimensions.pairing = inherit(step, Dimension::Pairing, inputs, |d| &d.pairing);
}
if output.applies(Dimension::QualityEncoding) {
dimensions.quality_encoding = inherit(step, Dimension::QualityEncoding, inputs, |d| {
&d.quality_encoding
});
}
if output.applies(Dimension::Release) {
dimensions.release = inherit(step, Dimension::Release, inputs, |d| &d.release);
}
if output.applies(Dimension::Subject) {
dimensions.subject = inherit(step, Dimension::Subject, inputs, |d| &d.subject);
}
if output.applies(Dimension::SourceSet) {
dimensions.source_set = inherit(step, Dimension::SourceSet, inputs, |d| &d.source_set);
}
if output.applies(Dimension::IdentifierNamespace) {
dimensions.identifier_namespace =
inherit(step, Dimension::IdentifierNamespace, inputs, |d| {
&d.identifier_namespace
});
}
if output.applies(Dimension::Representation) {
dimensions.representation = inherit(step, Dimension::Representation, inputs, |d| {
&d.representation
});
}
if let Some(converted) = &spec.conversion
&& converted.conversion.converts(output)
{
converted.target.apply(
&mut dimensions,
Source::Derived {
step: step.to_owned(),
},
);
}
Dataset::new(output, None, dimensions)
}
fn coordinates(spec: &StepSpec) -> Dim<CoordinateSystem> {
let derived = Source::Derived {
step: spec.name.clone(),
};
match spec.output {
DataKind::Alignment | DataKind::Variants => {
Dim::known(CoordinateSystem::OneBasedClosed, derived)
}
_ => match spec.coordinates {
Some(system) => Dim::known(system, derived),
None => Dim::unknown(
"a step that writes intervals must state which coordinate \
system it writes; declare it on the step",
),
},
}
}
fn inherit<T: Clone>(
step: &str,
dimension: Dimension,
inputs: &[&Dataset],
field: impl Fn(&Dimensions) -> &Dim<T>,
) -> Dim<T> {
let applicable: Vec<&&Dataset> = inputs
.iter()
.filter(|dataset| dataset.kind().applies(dimension))
.collect();
for dataset in &applicable {
if let Some(value) = field(dataset.dimensions()).value() {
return Dim::known(
value.clone(),
Source::Derived {
step: step.to_owned(),
},
);
}
}
applicable.first().map_or_else(
|| Dim::unknown("no input to this step states it"),
|dataset| field(dataset.dimensions()).clone(),
)
}