use std::fmt;
const DATA_EXTENSIONS: [&str; 13] = [
"bam", "cram", "sam", "vcf", "bcf", "fastq", "fq", "fasta", "fa", "fna", "bed", "gff", "gtf",
];
const COMPRESSION: [&str; 3] = ["gz", "bgz", "bz2"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Shape {
Absolute,
Relative,
Name,
}
impl Shape {
const fn describe(self) -> &'static str {
match self {
Self::Absolute => "an absolute path",
Self::Relative => "a file path",
Self::Name => "a file name",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Note {
SampleIsAFile {
sample: String,
},
ReadingWithoutCoverage,
GeneUnread {
gene: String,
depth: u32,
},
GeneBarelyRead {
gene: String,
read: u32,
scored: u32,
needed: u32,
},
CodonsUnread {
gene: String,
read: u32,
codons: u32,
depth: u32,
},
IdentifierIsADate {
identifier: String,
},
IdentifierUnmapped {
identifier: String,
},
IdentifierAmbiguous {
identifier: String,
},
IdentifierFannedOut {
identifier: String,
},
IdentifierCollides {
identifier: String,
},
IdentifiersDidNotCross {
count: u32,
},
IdentifiersFannedOut {
identifiers: u32,
rows: u32,
},
RanksRenumbered {
first: u32,
},
MoleculeDidNotStandardise {
molecule: String,
},
MoleculesDidNotStandardise {
count: u32,
},
MoleculeNotUnique {
inchikey: String,
},
StereoNotDiscarded,
RemoteRewritten {
locator: String,
},
QueryDrifted {
locator: String,
was: String,
now: String,
},
QueryFieldDropped {
locator: String,
field: String,
},
GraphFieldDropped {
field: String,
},
CodonsUnphased {
gene: String,
unphased: u32,
depth: u32,
},
}
impl Note {
#[must_use]
pub fn about_sample(sample: &str) -> Option<Self> {
shape(sample).map(|_| Self::SampleIsAFile {
sample: sample.to_owned(),
})
}
#[must_use]
pub fn about_identifier(identifier: &str) -> Option<Self> {
looks_like_a_date(identifier.trim()).then(|| Self::IdentifierIsADate {
identifier: identifier.trim().to_owned(),
})
}
#[must_use]
pub const fn code(&self) -> &'static str {
match self {
Self::SampleIsAFile { .. } => "sample-is-a-file",
Self::ReadingWithoutCoverage => "reading-without-coverage",
Self::GeneUnread { .. } => "gene-unread",
Self::GeneBarelyRead { .. } => "gene-barely-read",
Self::CodonsUnread { .. } => "codons-unread",
Self::CodonsUnphased { .. } => "codons-unphased",
Self::RemoteRewritten { .. } => "remote-rewritten",
Self::QueryFieldDropped { .. } => "query-field-dropped",
Self::GraphFieldDropped { .. } => "graph-field-dropped",
Self::QueryDrifted { .. } => "query-drifted",
Self::IdentifierIsADate { .. } => "identifier-is-a-date",
Self::IdentifierUnmapped { .. } => "identifier-unmapped",
Self::IdentifierAmbiguous { .. } => "identifier-ambiguous",
Self::IdentifierCollides { .. } => "identifier-collides",
Self::IdentifiersDidNotCross { .. } => "identifiers-did-not-cross",
Self::IdentifierFannedOut { .. } => "identifier-fanned-out",
Self::IdentifiersFannedOut { .. } => "identifiers-fanned-out",
Self::MoleculeDidNotStandardise { .. } => "molecule-did-not-standardise",
Self::MoleculesDidNotStandardise { .. } => "molecules-did-not-standardise",
Self::MoleculeNotUnique { .. } => "molecule-not-unique",
Self::StereoNotDiscarded => "stereo-not-discarded",
Self::RanksRenumbered { .. } => "ranks-renumbered",
}
}
#[must_use]
pub fn value(&self) -> String {
match self {
Self::SampleIsAFile { sample } => sample.clone(),
Self::RemoteRewritten { locator } => locator.clone(),
Self::QueryFieldDropped { locator, field } => {
format!("field={field} locator={locator}")
}
Self::GraphFieldDropped { field } => format!("field={field}"),
Self::QueryDrifted { locator, was, now } => {
format!("was={was} now={now} locator={locator}")
}
Self::ReadingWithoutCoverage => String::new(),
Self::GeneUnread { gene, depth } => format!("gene={gene} depth={depth}"),
Self::GeneBarelyRead {
gene,
read,
scored,
needed,
} => format!("gene={gene} read={read} scored={scored} needed={needed}"),
Self::CodonsUnread {
gene,
read,
codons,
depth,
} => format!("gene={gene} read={read} codons={codons} depth={depth}"),
Self::CodonsUnphased {
gene,
unphased,
depth,
} => format!("gene={gene} unphased={unphased} depth={depth}"),
Self::IdentifierIsADate { identifier }
| Self::IdentifierUnmapped { identifier }
| Self::IdentifierAmbiguous { identifier }
| Self::IdentifierFannedOut { identifier }
| Self::IdentifierCollides { identifier } => identifier.clone(),
Self::IdentifiersDidNotCross { count } => format!("count={count}"),
Self::IdentifiersFannedOut { identifiers, rows } => {
format!("identifiers={identifiers} rows={rows}")
}
Self::MoleculeDidNotStandardise { molecule } => molecule.clone(),
Self::MoleculesDidNotStandardise { count } => format!("count={count}"),
Self::MoleculeNotUnique { inchikey } => inchikey.clone(),
Self::StereoNotDiscarded => String::new(),
Self::RanksRenumbered { first } => format!("first={first}"),
}
}
#[must_use]
pub const fn explains_a_difference(&self) -> bool {
matches!(self, Self::SampleIsAFile { .. })
}
#[must_use]
pub fn parse(code: &str, value: &str) -> Option<Self> {
match code {
"sample-is-a-file" => Some(Self::SampleIsAFile {
sample: value.to_owned(),
}),
"reading-without-coverage" => Some(Self::ReadingWithoutCoverage),
"gene-unread" => Some(Self::GeneUnread {
gene: named(value, "gene")?.to_owned(),
depth: counted(value, "depth")?,
}),
"gene-barely-read" => Some(Self::GeneBarelyRead {
gene: named(value, "gene")?.to_owned(),
read: counted(value, "read")?,
scored: counted(value, "scored").or_else(|| counted(value, "codons"))?,
needed: counted(value, "needed")?,
}),
"codons-unread" => Some(Self::CodonsUnread {
gene: named(value, "gene")?.to_owned(),
read: counted(value, "read")?,
codons: counted(value, "codons")?,
depth: counted(value, "depth")?,
}),
"identifier-is-a-date" => Some(Self::IdentifierIsADate {
identifier: value.to_owned(),
}),
"identifier-unmapped" => Some(Self::IdentifierUnmapped {
identifier: value.to_owned(),
}),
"identifier-ambiguous" => Some(Self::IdentifierAmbiguous {
identifier: value.to_owned(),
}),
"identifier-collides" => Some(Self::IdentifierCollides {
identifier: value.to_owned(),
}),
"molecule-did-not-standardise" => Some(Self::MoleculeDidNotStandardise {
molecule: value.to_owned(),
}),
"molecules-did-not-standardise" => Some(Self::MoleculesDidNotStandardise {
count: counted(value, "count")?,
}),
"molecule-not-unique" => Some(Self::MoleculeNotUnique {
inchikey: value.to_owned(),
}),
"stereo-not-discarded" => Some(Self::StereoNotDiscarded),
"identifier-fanned-out" => Some(Self::IdentifierFannedOut {
identifier: value.to_owned(),
}),
"identifiers-fanned-out" => Some(Self::IdentifiersFannedOut {
identifiers: counted(value, "identifiers")?,
rows: counted(value, "rows")?,
}),
"identifiers-did-not-cross" => Some(Self::IdentifiersDidNotCross {
count: counted(value, "count")?,
}),
"ranks-renumbered" => Some(Self::RanksRenumbered {
first: counted(value, "first")?,
}),
"remote-rewritten" => Some(Self::RemoteRewritten {
locator: value.to_owned(),
}),
"query-field-dropped" => Some(Self::QueryFieldDropped {
field: named(value, "field")?.to_owned(),
locator: named(value, "locator")?.to_owned(),
}),
"graph-field-dropped" => Some(Self::GraphFieldDropped {
field: named(value, "field")?.to_owned(),
}),
"query-drifted" => Some(Self::QueryDrifted {
was: named(value, "was")?.to_owned(),
now: named(value, "now")?.to_owned(),
locator: named(value, "locator")?.to_owned(),
}),
"codons-unphased" => Some(Self::CodonsUnphased {
gene: named(value, "gene")?.to_owned(),
unphased: counted(value, "unphased")?,
depth: counted(value, "depth")?,
}),
_ => None,
}
}
#[must_use]
pub const fn advice(&self) -> &'static str {
match self {
Self::SampleIsAFile { .. } => {
"Write the read group — `samtools addreplacerg -r ID:<sample> -r SM:<sample>` — \
so the calls below it name the sample."
}
Self::ReadingWithoutCoverage => {
"Pass the alignment — `coverage=aln` — so uncalled positions are reported as \
unread rather than as reference."
}
Self::GeneUnread { .. } => {
"Sequence deeper, or lower the depth this reading asks for — `depth=` — so this \
gene's drugs can be assessed at all."
}
Self::GeneBarelyRead { .. } => {
"Sequence more of this gene, or lower the share this reading asks for — \
`gene_coverage=` — if a floor is of more use to you than no answer."
}
Self::CodonsUnread { .. } => {
"Read a drug whose `unread` column is not empty as a floor, and sequence deeper \
to close it."
}
Self::CodonsUnphased { .. } => {
"Read a mutation at such a codon as a candidate, and sequence longer reads to \
settle it."
}
Self::RemoteRewritten { .. } => {
"Nothing needs doing: the pin still holds. Update it only if you would rather \
pin the new bytes."
}
Self::QueryFieldDropped { .. } => {
"Nothing needs doing where the field was the server's own. If it was your data, \
ask for it under another name: this one is on the list the engine drops."
}
Self::GraphFieldDropped { .. } => {
"Nothing needs doing where the field was the serving system's own. If it was \
your data, move it onto the nodes or edges it belongs to, where nothing is \
dropped."
}
Self::QueryDrifted { .. } => {
"Read what changed before you rely on the new answer. Nothing else needs doing: \
both records are kept, so run without `--refresh` to go on replaying the \
earlier one."
}
Self::IdentifierIsADate { .. } => {
"Export the file again with the identifier column typed as text, or recover the \
symbol from the date -- `2-Sep` was `SEPT7`."
}
Self::IdentifierUnmapped { .. } => {
"Check the mapping table's release: an identifier missing from it is usually one \
renamed or retired since the table was downloaded."
}
Self::IdentifierAmbiguous { .. } => {
"Decide which target you mean and add a one-to-one row for it, or keep the \
identifier in the space it is already in."
}
Self::IdentifierCollides { .. } => {
"Decide which of the colliding identifiers this analysis is about and drop the \
others from the input, or convert in the other direction."
}
Self::IdentifiersDidNotCross { .. } => {
"Compare this against the size of your input before reading the result: check \
the mapping table's release if it is more than a small fraction."
}
Self::IdentifierFannedOut { .. } => {
"Nothing needs doing where the identifier really denotes more than one \
entity -- a bifunctional enzyme, a complex, a family of paralogues. Where it \
does not, drop `ambiguous` back to its default and add a one-to-one row for \
the target you mean."
}
Self::IdentifiersFannedOut { .. } => {
"Compare this against the size of your input before reading the result: a \
fan-out makes the output larger, so anything counting entities is counting \
something else than it was."
}
Self::MoleculeDidNotStandardise { .. } => {
"Look at this structure by hand: a standardiser rejects a mixture with no \
single parent, and a structure it cannot read is usually one that was never \
valid."
}
Self::MoleculesDidNotStandardise { .. } => {
"Compare this against the size of your input before reading the result: a \
large share usually means the structure column is not what it looks like."
}
Self::MoleculeNotUnique { .. } => {
"Decide which row this analysis is about and drop the others from the input, \
or read the table as a ranking, whose rows are not a set."
}
Self::StereoNotDiscarded => {
"Drop `stereo-discarded` from the state you asked for, so this set still \
joins others that kept their stereochemistry."
}
Self::RanksRenumbered { .. } => {
"Take any cut-off -- a top ten, a significance line -- on the ranking before \
it was mapped, not after, and map the cut-off's members instead."
}
}
}
#[must_use]
pub const fn consequence(&self) -> &'static str {
match self {
Self::SampleIsAFile { .. } => {
"A sample set is a dimension, so the identifier is hashed exactly as the file \
writes it. The canonical hash of this output therefore depends on the file it \
was named after, which is not the same file in two places: a bundle written \
here cannot verify elsewhere, and a methods section built from it names a \
file where it should name a sample."
}
Self::ReadingWithoutCoverage => {
"A position missing from a VCF is ambiguous between agreeing with the reference \
and nothing having aligned there, and the two have opposite clinical meanings: \
the first is a susceptible result and the second is no result at all. Taking it \
as reference makes every score in this report a floor that the report itself \
cannot mark, because its `unread` column is empty for want of coverage to read \
rather than because everything was read."
}
Self::GeneUnread { .. } => {
"A drug with nothing to score against is left out of the report rather than \
called susceptible, so the absence of this gene's drugs means no data and not \
a negative result."
}
Self::GeneBarelyRead { .. } => {
"A gene whose scored positions were mostly unread refutes nothing and shows \
nothing, so every drug scored against it would land at zero, which this \
algorithm's own ranges read as susceptible. The gene is left out of the \
report instead, so the absence of its drugs means no data and not a \
negative result."
}
Self::CodonsUnread { .. } => {
"A drug whose rules name an unread position has that position listed in the \
report's `unread` column and its score is a floor: the mutations it looks for \
were not all looked at."
}
Self::CodonsUnphased { .. } => {
"A codon read base by base holds every combination of the alleles the caller \
credited at its three bases, so it can name a mutation no single read carries, \
which overstates resistance where a phased reading would not."
}
Self::RemoteRewritten { .. } => {
"Nothing downstream moves: the pin is over what the file means, and that is \
unchanged. What has changed is the source's habits, which is worth knowing \
before a change that is not cosmetic arrives."
}
Self::QueryFieldDropped { .. } => {
"The field is in neither the stored body nor the hash, so the record repeats \
when the server's own bookkeeping changes -- which is the point. The cost is \
that a field of yours that shares one of those names is not in the record \
either, and this is how you find out."
}
Self::GraphFieldDropped { .. } => {
"The field is not in this graph's canonical hash, so the graph compares equal \
to the same graph served at another moment -- which is the point. The cost is \
that a top-level field of yours sharing one of those names is outside the \
comparison, and this is how you find out."
}
Self::QueryDrifted { .. } => {
"Everything below this input has a new content hash, so every step that uses \
it reruns and its results are the new source's results rather than the \
earlier ones. The earlier record is untouched: the run that produced the \
earlier results can still be replayed exactly as it ran."
}
Self::IdentifierIsADate { .. } => {
"A date is in no identifier space, so this entity matches nothing in any other \
file and silently drops out of every join downstream. It also stops the space \
being inferred for the file at all, because one identifier the engine cannot \
place is a file it will not guess about."
}
Self::IdentifierUnmapped { .. } => {
"An identifier that does not cross is left out of the output rather than carried \
over unchanged, because carrying it would put a name from the old space into a \
set that declares the new one. The output is therefore smaller than the input, \
by exactly the identifiers named in these notes."
}
Self::IdentifierAmbiguous { .. } => {
"One identifier with several targets is left out rather than resolved: emitting \
a row for each would make the set larger than the input without saying so, and \
choosing one of them would be a guess about which the analysis meant."
}
Self::IdentifierCollides { .. } => {
"Two identifiers arriving at one target would make the output name a single \
entity twice, with two sets of attributes, which is not a set. Keeping one of \
them would be a guess about which row's attributes to carry, so every \
identifier that collides is left out and named."
}
Self::IdentifiersDidNotCross { .. } => {
"The output is smaller than the input by this many entities. A conversion is a \
lookup, not a rename, so a count that is a large share of the input usually \
means the mapping table is from a different release than the list."
}
Self::IdentifierFannedOut { .. } => {
"The output holds one row per target, so this entity is named more than once \
in a set that is still a set -- the targets are distinct entities in the new \
space. What it is not is the same entity carried across: a bifunctional \
enzyme's two domains are two genes there, and anything counting entities \
counts them separately."
}
Self::IdentifiersFannedOut { .. } => {
"The output is larger than the input by the difference between these two \
numbers, which is the one direction nothing else in this conversion moves. A \
count of entities taken before and after will disagree, and the second is \
the right one for the space the output is in."
}
Self::MoleculeDidNotStandardise { .. } => {
"A molecule that does not standardise is left out of the output rather than \
carried over unchanged, because carrying it would put a name in the old state \
into a set that declares the new one. The output is therefore smaller than \
the input, by exactly the molecules named in these notes."
}
Self::MoleculesDidNotStandardise { .. } => {
"The output is smaller than the input by this many molecules. Standardisation \
is a computation that can fail, not a rename, so a count that is a large \
share of the input usually means the structures are not what the column \
header says."
}
Self::MoleculeNotUnique { .. } => {
"A molecule set's rows are a set, so a table naming one substance twice is not \
the kind it claims to be: anything counting its compounds double-counts, and \
a join on the key matches both rows. Standardising is what brought them \
together -- a salt and its parent are two structures and one substance -- so \
this is the standardiser telling you what it merged rather than a fault in \
the input."
}
Self::StereoNotDiscarded => {
"The state this set declares is stricter than what was done to it, so it will \
refuse to join sets that kept their stereochemistry and are otherwise \
identical. That is the safe direction -- a refusal rather than a false \
agreement -- which is why it is a note and not an error."
}
Self::RanksRenumbered { .. } => {
"Rank is the row position, so every row below a dropped one has moved up and \
no rank in this output is the rank it had in the input. The ranking is still \
a true ranking of the entities that crossed; what it is not is the same \
ranking with some entities removed, which is what a top-n taken after \
mapping quietly assumes."
}
}
}
}
impl fmt::Display for Note {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SampleIsAFile { sample } => {
let shape = shape(sample).map_or("a file", Shape::describe);
write!(
f,
"the sample identifier `{sample}` is {shape}, not a sample"
)
}
Self::ReadingWithoutCoverage => f.write_str(
"no alignment was supplied, so coverage is unknown, no codon can be phased, \
and every position the caller did not report is taken to be reference",
),
Self::GeneUnread { gene, depth } => write!(
f,
"no codon of {gene} reached {depth}-fold coverage, so no drug scored \
against it could be assessed"
),
Self::GeneBarelyRead {
gene,
read,
scored,
needed,
} => write!(
f,
"only {read} of the {scored} codons this algorithm scores in {gene} were \
read, where this reading required {needed}, so {gene} was not assessed \
rather than scored against what little was seen"
),
Self::CodonsUnread {
gene,
read,
codons,
depth,
} => write!(
f,
"{read} of {gene}'s {codons} codons reached {depth}-fold coverage; \
the rest are reported as unread rather than as reference"
),
Self::CodonsUnphased {
gene,
unphased,
depth,
} => write!(
f,
"{unphased} of {gene}'s codons were read base by base because no read spans \
all three of their bases {depth} times over, so a combination of bases no \
read carries may be reported there"
),
Self::RemoteRewritten { locator } => write!(
f,
"the source rewrote `{locator}`: its bytes differ from the ones recorded, and \
what it means does not, so the pin still holds"
),
Self::QueryFieldDropped { locator, field } => write!(
f,
"`{field}` was dropped from the recorded response to `{locator}`: a field of \
that name is the server's account of how it answered, not part of the answer"
),
Self::GraphFieldDropped { field } => write!(
f,
"`{field}` was dropped from this graph's canonical form: a top-level field of \
that name is an account of how the graph was served, not part of what it says"
),
Self::QueryDrifted { locator, was, now } => write!(
f,
"the source of `{locator}` has changed since it was recorded: the record held \
{was} and it now answers {now}. Both records are kept, so the earlier run is \
still replayable"
),
Self::IdentifierIsADate { identifier } => write!(
f,
"the identifier `{identifier}` is a date, not a name; a spreadsheet does this \
to SEPT7, MARCH1 and DEC1"
),
Self::IdentifierUnmapped { identifier } => write!(
f,
"the identifier `{identifier}` is in no row of the mapping table, so it is not \
in the output"
),
Self::IdentifierAmbiguous { identifier } => write!(
f,
"the identifier `{identifier}` maps to more than one target, so it is not in \
the output"
),
Self::IdentifierCollides { identifier } => write!(
f,
"the identifier `{identifier}` maps to a target another identifier also maps \
to, so it is not in the output"
),
Self::IdentifiersDidNotCross { count } => write!(
f,
"{count} identifiers did not cross into the target space, so the output is \
{count} entities smaller than the input"
),
Self::IdentifierFannedOut { identifier } => write!(
f,
"the identifier `{identifier}` maps to more than one target, and this step \
asked for a fan-out, so the output holds a row for each"
),
Self::IdentifiersFannedOut { identifiers, rows } => write!(
f,
"{identifiers} {} fanned out into {rows} rows, so the output is {} {} larger \
than the input",
if *identifiers == 1 {
"identifier"
} else {
"identifiers"
},
rows.saturating_sub(*identifiers),
if rows.saturating_sub(*identifiers) == 1 {
"entity"
} else {
"entities"
}
),
Self::MoleculeDidNotStandardise { molecule } => write!(
f,
"the molecule `{molecule}` could not be standardised, so it is not in the \
output"
),
Self::MoleculesDidNotStandardise { count } => write!(
f,
"{count} molecules could not be standardised, so the output is {count} \
molecules smaller than the input"
),
Self::MoleculeNotUnique { inchikey } => write!(
f,
"two or more structures standardise to `{inchikey}`, so this table names one \
substance more than once"
),
Self::StereoNotDiscarded => f.write_str(
"`stereo-discarded` was declared, and no molecule in this set lost any \
stereochemistry",
),
Self::RanksRenumbered { first } => write!(
f,
"the ranks were renumbered by the mapping: rank 1 of this ranking was rank \
{first} of the list that was mapped, and every rank below a dropped row has \
moved up by as many rows as were dropped above it"
),
}
}
}
fn named<'a>(value: &'a str, name: &str) -> Option<&'a str> {
value
.split(' ')
.filter_map(|field| field.split_once('='))
.find_map(|(key, found)| (key == name && !found.is_empty()).then_some(found))
}
fn counted(value: &str, name: &str) -> Option<u32> {
named(value, name)?.parse().ok()
}
const MONTHS: [&str; 25] = [
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"sept",
"oct",
"nov",
"dec",
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december",
];
pub(crate) fn looks_like_a_date(identifier: &str) -> bool {
if identifier.is_empty() {
return false;
}
let parts: Vec<&str> = identifier.split(['-', '/']).collect();
match parts[..] {
[left, right] => is_month(left) != is_month(right) && (is_day(left) || is_day(right)),
[a, b, c] => {
let numbers = [a, b, c].iter().filter(|part| is_number(part)).count();
let months = [a, b, c].iter().filter(|part| is_month(part)).count();
numbers == 3 || (numbers == 2 && months == 1)
}
_ => false,
}
}
fn is_month(part: &str) -> bool {
let lowered = part.to_ascii_lowercase();
MONTHS.contains(&lowered.as_str())
}
fn is_number(part: &str) -> bool {
!part.is_empty() && part.chars().all(|c| c.is_ascii_digit())
}
fn is_day(part: &str) -> bool {
is_number(part) && part.parse::<u32>().is_ok_and(|day| (1..=31).contains(&day))
}
fn shape(sample: &str) -> Option<Shape> {
let name = sample.trim();
if name.is_empty() {
return None;
}
if name.starts_with('/') {
return Some(Shape::Absolute);
}
if name.contains('/') || name.contains('\\') {
return Some(Shape::Relative);
}
names_a_format(name).then_some(Shape::Name)
}
fn names_a_format(name: &str) -> bool {
let lowered = name.to_ascii_lowercase();
let mut stem = lowered.as_str();
for suffix in COMPRESSION {
if let Some(trimmed) = stem.strip_suffix(suffix)
&& trimmed.ends_with('.')
{
stem = &trimmed[..trimmed.len() - 1];
break;
}
}
stem.rsplit_once('.')
.is_some_and(|(_, extension)| DATA_EXTENSIONS.contains(&extension))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_inside_the_store_is_a_file() {
let sample = "/Users/kelyn/ligase/.ligase/store/62/7db9fa0cbac.bam";
assert_eq!(shape(sample), Some(Shape::Absolute));
assert!(Note::about_sample(sample).is_some());
}
#[test]
fn a_relative_path_and_a_bare_file_name_are_files_too() {
assert_eq!(shape("alignments/sample_a.bam"), Some(Shape::Relative));
assert_eq!(shape(r"C:\data\sample_a.bam"), Some(Shape::Relative));
assert_eq!(shape("sample_a.bam"), Some(Shape::Name));
assert_eq!(shape("calls.vcf.gz"), Some(Shape::Name));
assert_eq!(shape("READS.FASTQ.GZ"), Some(Shape::Name));
}
#[test]
fn an_ordinary_sample_identifier_is_left_alone() {
for sample in [
"SRR8525904",
"sample_a",
"HG002",
"patient-04",
"K03455.1",
"HG002.final",
"bam",
"",
" ",
] {
assert_eq!(shape(sample), None, "{sample} is a sample identifier");
assert_eq!(Note::about_sample(sample), None, "{sample}");
}
}
fn every_kind() -> Vec<Note> {
vec![
Note::SampleIsAFile {
sample: "/tmp/x.bam".to_owned(),
},
Note::ReadingWithoutCoverage,
Note::GeneUnread {
gene: "CA".to_owned(),
depth: 100,
},
Note::GeneBarelyRead {
gene: "IN".to_owned(),
read: 5,
scored: 26,
needed: 21,
},
Note::CodonsUnread {
gene: "RT".to_owned(),
read: 548,
codons: 560,
depth: 100,
},
Note::CodonsUnphased {
gene: "RT".to_owned(),
unphased: 6,
depth: 100,
},
Note::IdentifierIsADate {
identifier: "2-Sep".to_owned(),
},
Note::IdentifierUnmapped {
identifier: "SEPT7".to_owned(),
},
Note::IdentifierAmbiguous {
identifier: "NKX2-1".to_owned(),
},
Note::IdentifierCollides {
identifier: "TP53P1".to_owned(),
},
Note::IdentifiersDidNotCross { count: 4000 },
Note::MoleculeDidNotStandardise {
molecule: "CC(=O)Oc1ccccc1C(=O)[O-].[Na+]".to_owned(),
},
Note::MoleculesDidNotStandardise { count: 118 },
Note::MoleculeNotUnique {
inchikey: "BSYNRYMUTXBXSQ-UHFFFAOYSA-N".to_owned(),
},
Note::StereoNotDiscarded,
Note::RanksRenumbered { first: 4 },
]
}
#[test]
fn a_note_round_trips_through_its_code_and_value() {
for note in every_kind() {
assert_eq!(
Note::parse(note.code(), ¬e.value()),
Some(note.clone()),
"{}",
note.code()
);
}
}
#[test]
fn a_value_is_one_column_of_a_table() {
for note in every_kind() {
let value = note.value();
assert!(!value.contains('\t'), "{value}");
assert!(!value.contains('\n'), "{value}");
}
}
#[test]
fn every_kind_says_what_it_found_what_it_means_and_what_to_do() {
for note in every_kind() {
assert!(!note.to_string().is_empty(), "{}", note.code());
assert!(note.advice().ends_with('.'), "{}", note.code());
assert!(note.consequence().ends_with('.'), "{}", note.code());
}
}
#[test]
fn only_a_sample_that_is_a_file_explains_a_hash_that_moved() {
for note in every_kind() {
assert_eq!(
note.explains_a_difference(),
note.code() == "sample-is-a-file",
"{}",
note.code()
);
}
}
#[test]
fn a_reading_note_names_its_gene_and_its_counts() {
let note = Note::CodonsUnread {
gene: "RT".to_owned(),
read: 548,
codons: 560,
depth: 100,
};
let said = note.to_string();
assert!(said.contains("548 of RT's 560 codons"), "{said}");
assert!(said.contains("100-fold"), "{said}");
assert_eq!(Note::parse("codons-unread", "gene=RT read=548"), None);
assert_eq!(Note::parse("codons-unread", ""), None);
}
#[test]
fn a_barely_read_note_from_an_older_release_is_still_readable() {
assert_eq!(
Note::parse("gene-barely-read", "gene=IN read=92 codons=288 needed=231"),
Some(Note::GeneBarelyRead {
gene: "IN".to_owned(),
read: 92,
scored: 288,
needed: 231,
})
);
assert_eq!(Note::parse("gene-barely-read", "gene=IN read=92"), None);
}
#[test]
fn a_code_from_a_later_version_is_not_a_note_here() {
assert_eq!(Note::parse("something-else", "x"), None);
}
#[test]
fn a_note_says_what_it_found_and_what_to_do() {
let note = Note::SampleIsAFile {
sample: "/tmp/x.bam".to_owned(),
};
assert!(note.to_string().contains("/tmp/x.bam"));
assert!(note.to_string().contains("an absolute path"));
assert!(note.advice().contains("addreplacerg"));
assert!(note.consequence().contains("dimension"));
}
#[test]
fn a_symbol_excel_turned_into_a_date_is_noticed() {
for identifier in [
"2-Sep",
"1-Mar",
"Sep-02",
"Dec-01",
"2026-09-02",
"9/2/2026",
] {
assert!(
matches!(
Note::about_identifier(identifier),
Some(Note::IdentifierIsADate { .. })
),
"{identifier}"
);
}
}
#[test]
fn a_real_gene_symbol_is_left_alone() {
for identifier in [
"SEPT7",
"MARCH1",
"DEC1",
"NKX2-1",
"HLA-A",
"TP53",
"ENSG00000141510",
"7157",
"P04637",
"",
" ",
"SEPT7-1",
"MARCH1-2",
"MAY",
] {
assert_eq!(Note::about_identifier(identifier), None, "{identifier}");
}
}
#[test]
fn an_identifier_note_says_what_it_found_and_names_it() {
let note = Note::IdentifierIsADate {
identifier: "2-Sep".to_owned(),
};
assert!(note.to_string().contains("2-Sep"));
assert!(note.to_string().contains("date"));
for note in every_kind()
.into_iter()
.filter(|note| note.code().starts_with("identifier-"))
{
assert!(!note.explains_a_difference(), "{}", note.code());
}
}
}