use std::collections::BTreeSet;
use super::{Prov, ProvError, Record, ReferenceRecord, cite};
use crate::canon::Note;
use crate::exec::{RunReport, Task};
use crate::graph::{Graph, NodeId};
const KNIT: char = '\u{1}';
const WIDTH: usize = 76;
#[derive(Clone, Debug)]
pub struct Group {
pub step: String,
pub nodes: Vec<NodeId>,
pub scopes: Vec<String>,
pub scope_kind: Option<&'static str>,
pub record: Record,
pub template: Option<String>,
pub declared: Vec<String>,
pub per_sample: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct Gap {
pub step: String,
pub scopes: Vec<String>,
pub scope_kind: Option<&'static str>,
pub nodes: usize,
}
#[derive(Clone, Debug)]
pub struct Noticed {
pub step: String,
pub scope: Option<String>,
pub scope_kind: Option<&'static str>,
pub note: Note,
}
#[derive(Clone, Debug, Default)]
pub struct Methods {
pub groups: Vec<Group>,
pub gaps: Vec<Gap>,
pub noticed: Vec<Noticed>,
pub engine: String,
pub platform: String,
}
impl Methods {
#[must_use]
pub fn tools(&self) -> Vec<(String, String)> {
let mut seen: Vec<(String, String)> = Vec::new();
for group in &self.groups {
for (tool, version) in &group.record.tools {
let named = (tool.clone(), version.clone());
if !seen.contains(&named) {
seen.push(named);
}
}
}
seen.sort();
seen
}
#[must_use]
pub fn references(&self) -> Vec<ReferenceRecord> {
let mut seen: Vec<ReferenceRecord> = Vec::new();
for group in &self.groups {
for reference in &group.record.references {
if !seen
.iter()
.any(|held| held.fingerprint == reference.fingerprint)
{
seen.push(reference.clone());
}
}
}
seen
}
#[must_use]
pub fn citations(&self) -> (Vec<String>, Vec<String>) {
let mut cited: BTreeSet<String> = BTreeSet::new();
let mut uncited: BTreeSet<String> = BTreeSet::new();
for group in &self.groups {
for text in &group.declared {
cited.insert(text.clone());
}
for (tool, _) in &group.record.tools {
match cite::of(tool) {
Some(citation) => {
cited.insert(citation.render());
}
None if group.declared.is_empty() => {
uncited.insert(tool.clone());
}
None => {}
}
}
}
(cited.into_iter().collect(), uncited.into_iter().collect())
}
#[must_use]
pub fn paragraph(&self) -> String {
let mut paragraphs = vec![wrap(&format!(
"Analyses were run with Ligase {} on {}.",
self.engine, self.platform
))];
for group in &self.groups {
paragraphs.push(wrap(&group.sentence()));
}
for gap in &self.gaps {
paragraphs.push(wrap(&format!(
"`{}` ({}) is in the cache from a run that recorded no \
provenance, so how it was produced is not known here. \
`ligase run --force` runs it again and records it.",
gap.step,
counted(gap.nodes, &gap.scopes, gap.scope_kind),
)));
}
paragraphs.join("\n\n")
}
#[must_use]
pub fn text(&self) -> String {
let mut out = self.paragraph();
let (cited, uncited) = self.citations();
if !cited.is_empty() {
out.push_str("\n\nReferences\n\n");
out.push_str(
&cited
.iter()
.map(|reference| wrap_hanging(reference))
.collect::<Vec<_>>()
.join("\n"),
);
}
if !uncited.is_empty() {
out.push_str("\n\n");
out.push_str(&wrap(&format!(
"No reference is recorded for {}. Add one with \
`@lg.step(cite=...)`, or cite it by hand.",
join_names(&uncited)
)));
}
for notice in self.notices() {
out.push_str("\n\n");
out.push_str(¬ice);
}
out
}
#[must_use]
pub fn notices(&self) -> Vec<String> {
let mut gathered: Vec<Vec<&Noticed>> = Vec::new();
for item in &self.noticed {
match gathered.iter_mut().find(|seen| {
seen.first().is_some_and(|first| {
first.step == item.step && first.note.code() == item.note.code()
})
}) {
Some(seen) => seen.push(item),
None => gathered.push(vec![item]),
}
}
gathered
.iter()
.filter_map(|seen| {
let (first, rest) = seen.split_first()?;
let mut scopes: Vec<String> =
seen.iter().filter_map(|item| item.scope.clone()).collect();
scopes.sort();
scopes.dedup();
let mut sentence = format!(
"`{}` ran on {}, where {}",
first.step,
counted(seen.len(), &scopes, first.scope_kind),
first.note,
);
if !rest.is_empty() {
let others: Vec<String> = rest
.iter()
.map(|item| format!("`{}`", item.note.value()))
.collect();
sentence.push_str(&format!(" — and the same for {}", join_names(&others)));
}
sentence.push_str(&format!(
". {} {}",
first.note.consequence(),
first.note.advice()
));
Some(wrap(&sentence))
})
.collect()
}
#[must_use]
pub fn summary(&self) -> String {
let accounted: usize = self.groups.iter().map(|group| group.nodes.len()).sum();
let missing: usize = self.gaps.iter().map(|gap| gap.nodes).sum();
let total = accounted + missing;
let noun = if total == 1 { "step" } else { "steps" };
if missing == 0 {
return format!("{total} {noun}, all accounted for.");
}
format!("{total} {noun}: {accounted} accounted for, {missing} not.")
}
}
impl Group {
fn sentence(&self) -> String {
let mut sentence = format!(
"`{}` ran on {}",
self.step,
counted(self.nodes.len(), &self.scopes, self.scope_kind)
);
match self.record.tools.as_slice() {
[] => {}
tools => {
let named: Vec<String> = tools
.iter()
.map(|(tool, version)| describe_tool(tool, version))
.collect();
sentence.push_str(&format!(" with {}", join_names(&named)));
}
}
match (&self.template, &self.record.command) {
(Some(template), _) => sentence.push_str(&format!(", as `{template}`")),
(None, None) => sentence.push_str(", by a function in the pipeline itself"),
(None, Some(command)) => sentence.push_str(&format!(", as `{command}`")),
}
let settings: Vec<String> = self
.record
.parameters
.iter()
.filter(|(name, _)| !self.per_sample.contains(name))
.map(|(name, value)| format!("{name}{KNIT}={KNIT}{value}"))
.collect();
if !settings.is_empty() {
sentence.push_str(&format!(", with {}", join_names(&settings)));
}
if !self.per_sample.is_empty() {
let named = join_names(&self.per_sample);
let verb = if self.per_sample.len() == 1 {
"naming"
} else {
"each naming"
};
let joined = if settings.is_empty() {
"with"
} else {
"and with"
};
sentence.push_str(&format!(", {joined} {named} {verb} the sample"));
}
for reference in &self.record.references {
sentence.push_str(&format!(", against {}", describe_reference(reference)));
}
sentence.push('.');
sentence
}
}
pub fn methods(
graph: &Graph,
roots: &[NodeId],
tasks: &[Task],
report: &RunReport,
prov: &Prov,
) -> Result<Methods, ProvError> {
let scopes = graph.scopes(roots);
let scope_of = |node: NodeId| scopes.get(&node).map(|scope| scope.value.clone());
let kind_of = |node: NodeId| scopes.get(&node).map(|scope| scope.kind);
let template_of = |node: NodeId| {
tasks
.iter()
.find(|task| task.node == node)
.and_then(|task| match &task.recipe {
crate::exec::Recipe::Shell(command) => Some(command.clone()),
crate::exec::Recipe::Callback(_) => None,
})
};
let declared_of = |node: NodeId| {
tasks
.iter()
.find(|task| task.node == node)
.map(|task| task.citations.clone())
.unwrap_or_default()
};
let mut groups: Vec<Group> = Vec::new();
let mut gaps: Vec<Gap> = Vec::new();
let mut noticed: Vec<Noticed> = Vec::new();
for result in &report.results {
let node = result.node;
let Some(record) = prov.lookup(result.key)? else {
match gaps.iter_mut().find(|gap| gap.step == result.step) {
Some(gap) => {
gap.nodes += 1;
gap.scopes.extend(scope_of(node));
}
None => gaps.push(Gap {
step: result.step.clone(),
scopes: scope_of(node).into_iter().collect(),
scope_kind: kind_of(node),
nodes: 1,
}),
}
continue;
};
for note in &record.output_notes {
noticed.push(Noticed {
step: record.step.clone(),
scope: scope_of(node),
scope_kind: kind_of(node),
note: note.clone(),
});
}
let template = template_of(node);
let per_sample = restating(&record, scope_of(node).as_deref());
let signature = signature(&record, template.as_deref(), &per_sample);
match groups
.iter_mut()
.find(|group| group.step == record.step && signature == signature_of(group))
{
Some(group) => {
group.nodes.push(node);
group.scopes.extend(scope_of(node));
}
None => groups.push(Group {
step: record.step.clone(),
nodes: vec![node],
scopes: scope_of(node).into_iter().collect(),
scope_kind: kind_of(node),
record,
template,
declared: declared_of(node),
per_sample,
}),
}
}
let (engine, platform) = groups.first().map_or_else(
|| (crate::version().to_owned(), super::platform()),
|group| (group.record.engine.clone(), group.record.platform.clone()),
);
for group in &mut groups {
group.scopes.sort();
group.scopes.dedup();
}
for gap in &mut gaps {
gap.scopes.sort();
gap.scopes.dedup();
}
Ok(Methods {
groups,
gaps,
noticed,
engine,
platform,
})
}
fn signature(record: &Record, template: Option<&str>, per_sample: &[String]) -> String {
let mut parts = vec![record.step.clone(), template.unwrap_or("").to_owned()];
for (name, value) in &record.parameters {
if per_sample.contains(name) {
parts.push(format!("{name}=<sample>"));
continue;
}
parts.push(format!("{name}={value}"));
}
for (tool, version) in &record.tools {
parts.push(format!("{tool}@{version}"));
}
for reference in &record.references {
parts.push(reference.fingerprint.clone());
}
parts.join("\u{1f}")
}
fn signature_of(group: &Group) -> String {
signature(&group.record, group.template.as_deref(), &group.per_sample)
}
fn restating(record: &Record, scope: Option<&str>) -> Vec<String> {
let Some(scope) = scope else {
return Vec::new();
};
record
.parameters
.iter()
.filter(|(_, value)| unquote(value) == scope)
.map(|(name, _)| name.clone())
.collect()
}
fn unquote(value: &str) -> &str {
for quote in ['\'', '"'] {
if let Some(inner) = value
.strip_prefix(quote)
.and_then(|v| v.strip_suffix(quote))
{
return inner;
}
}
value
}
fn describe_tool(tool: &str, version: &str) -> String {
let first = version.lines().next().unwrap_or(version).trim();
if first.to_lowercase().starts_with(&tool.to_lowercase()) {
return first.to_owned();
}
format!("{tool} {first}")
}
fn describe_reference(reference: &ReferenceRecord) -> String {
let name = match &reference.build {
Some(build) => format!("the {build} reference"),
None => "the reference".to_owned(),
};
let mut pinned = Vec::new();
match &reference.accession {
Some(accession) => pinned.push(accession.clone()),
None => pinned.push(format!("fingerprint {}", reference.fingerprint)),
}
if reference.contigs > 1 {
pinned.push(format!("{} sequences", reference.contigs));
}
pinned.push(format!("{} bp", reference.length));
if let Some(checksum) = &reference.checksum {
pinned.push(format!("MD5 {checksum}"));
}
format!("{name} ({})", pinned.join(", "))
}
fn counted(nodes: usize, scopes: &[String], kind: Option<&str>) -> String {
let Some(kind) = kind.filter(|_| !scopes.is_empty()) else {
return match nodes {
1 => "one input".to_owned(),
many => format!("{many} inputs"),
};
};
let noun = if scopes.len() == 1 {
kind.to_owned()
} else {
format!("{kind}s")
};
format!("{} {noun} ({})", scopes.len(), noun_list(scopes))
}
fn noun_list(scopes: &[String]) -> String {
scopes.join(", ")
}
fn join_names(names: &[String]) -> String {
match names {
[] => String::new(),
[only] => only.clone(),
[first, second] => format!("{first} and {second}"),
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
}
}
fn wrap(text: &str) -> String {
fold(text, WIDTH, "")
}
fn wrap_hanging(text: &str) -> String {
fold(text, WIDTH, " ")
}
fn fold(text: &str, width: usize, indent: &str) -> String {
let mut lines: Vec<String> = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
let margin = if lines.is_empty() { 0 } else { indent.len() };
if !line.is_empty() && margin + line.len() + 1 + word.len() > width {
lines.push(line);
line = String::new();
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
if !line.is_empty() {
lines.push(line);
}
lines
.iter()
.enumerate()
.map(|(at, line)| {
if at == 0 {
line.clone()
} else {
format!("{indent}{line}")
}
})
.collect::<Vec<_>>()
.join("\n")
.replace(KNIT, " ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_tool_that_prints_its_own_name_does_not_get_it_twice() {
assert_eq!(describe_tool("samtools", "samtools 1.24"), "samtools 1.24");
assert_eq!(
describe_tool("minimap2", "2.31-r1287"),
"minimap2 2.31-r1287"
);
}
#[test]
fn only_a_tools_first_line_reaches_a_sentence() {
assert_eq!(
describe_tool("samtools", "samtools 1.24\nUsing htslib 1.24\n"),
"samtools 1.24"
);
}
#[test]
fn names_are_joined_as_english_joins_them() {
let one = ["a".to_owned()];
let two = ["a".to_owned(), "b".to_owned()];
let three = ["a".to_owned(), "b".to_owned(), "c".to_owned()];
assert_eq!(join_names(&one), "a");
assert_eq!(join_names(&two), "a and b");
assert_eq!(join_names(&three), "a, b and c");
}
#[test]
fn a_setting_is_never_broken_across_lines() {
let settings: Vec<String> = (0..9)
.map(|n| format!("parameter_number_{n}{KNIT}={KNIT}0.0{n}"))
.collect();
let text = wrap(&format!("`align` ran with {}.", join_names(&settings)));
for line in text.lines() {
assert!(line.len() <= WIDTH, "{line:?}");
}
for n in 0..9 {
assert!(
text.contains(&format!("parameter_number_{n} = 0.0{n}")),
"a setting was split: {text}"
);
}
}
#[test]
fn wrapping_breaks_between_words_only() {
let text = "one two three four five six seven eight nine ten eleven \
twelve thirteen fourteen fifteen sixteen seventeen";
for line in wrap(text).lines() {
assert!(line.len() <= WIDTH, "{line:?} is {} long", line.len());
}
assert_eq!(
wrap(text).split_whitespace().collect::<Vec<_>>(),
text.split_whitespace().collect::<Vec<_>>(),
"wrapping changes where the lines break and nothing else"
);
}
}