use std::io::BufRead;
use std::path::Path;
use noodles::vcf;
use noodles::vcf::header::record::value::Collection;
use noodles::vcf::header::record::value::map::format::Number as FormatNumber;
use noodles::vcf::header::record::value::map::info::Number as InfoNumber;
use super::{Digest, Note, tolerance};
use crate::load::open;
use crate::types::DataKind;
const VOLATILE: [&str; 5] = [
"fileDate",
"fileDay",
"source",
"reference",
"bcftoolsVersion",
];
const VOLATILE_SUFFIXES: [&str; 4] = ["Command", "CommandLine", "Version", "Date"];
const FIXED_COLUMNS: usize = 8;
pub(super) fn canonicalise(path: &Path, digest: &mut Digest) -> Result<(), String> {
let mut reader = vcf::io::Reader::new(open(path).map_err(|error| error.to_string())?);
let header = reader.read_header().map_err(|error| error.to_string())?;
describe_header(&header, digest);
let mut body = reader.into_inner();
let mut line = String::new();
loop {
line.clear();
if body
.read_line(&mut line)
.map_err(|error| error.to_string())?
== 0
{
break;
}
let text = line.trim_end_matches(['\n', '\r']);
if text.is_empty() {
continue;
}
describe_record(text, digest)?;
}
Ok(())
}
fn describe_header(header: &vcf::Header, digest: &mut Digest) {
for (name, map) in header.contigs() {
digest.text("contig", name);
digest.text(
"contig.length",
&map.length()
.map(|length| length.to_string())
.unwrap_or_default(),
);
digest.text("contig.md5", map.md5().unwrap_or_default());
}
for (id, map) in header.infos() {
digest.text("info", id);
digest.text("info.number", &info_number(map.number()));
digest.text("info.type", map.ty().as_ref());
}
for (id, map) in header.formats() {
digest.text("format", id);
digest.text("format.number", &format_number(map.number()));
digest.text("format.type", map.ty().as_ref());
}
for id in header.filters().keys() {
digest.text("filter", id);
}
for id in header.alternative_alleles().keys() {
digest.text("alt", id);
}
for sample in header.sample_names() {
digest.text("sample", sample);
if let Some(note) = Note::about_sample(sample) {
digest.note(note);
}
}
let mut others: Vec<String> = header
.other_records()
.iter()
.filter(|(key, _)| !is_volatile(key.as_ref()))
.map(|(key, collection)| format!("{}={}", key.as_ref(), render(collection)))
.collect();
others.sort();
for other in others {
digest.text("other", &other);
}
}
fn info_number(number: InfoNumber) -> String {
match number {
InfoNumber::Count(count) => count.to_string(),
InfoNumber::AlternateBases => "A".to_owned(),
InfoNumber::ReferenceAlternateBases => "R".to_owned(),
InfoNumber::Samples => "G".to_owned(),
InfoNumber::Unknown => ".".to_owned(),
}
}
fn format_number(number: FormatNumber) -> String {
match number {
FormatNumber::Count(count) => count.to_string(),
FormatNumber::AlternateBases => "A".to_owned(),
FormatNumber::ReferenceAlternateBases => "R".to_owned(),
FormatNumber::Samples => "G".to_owned(),
FormatNumber::LocalAlternateBases => "LA".to_owned(),
FormatNumber::LocalReferenceAlternateBases => "LR".to_owned(),
FormatNumber::LocalSamples => "LG".to_owned(),
FormatNumber::Ploidy => "P".to_owned(),
FormatNumber::BaseModifications => "M".to_owned(),
FormatNumber::Unknown => ".".to_owned(),
}
}
fn render(collection: &Collection) -> String {
match collection {
Collection::Unstructured(values) => values.join(","),
Collection::Structured(maps) => maps
.iter()
.map(|(id, map)| {
let fields: Vec<String> = map
.other_fields()
.iter()
.map(|(tag, value)| format!("{tag}={value}"))
.collect();
format!("{id}<{}>", fields.join(","))
})
.collect::<Vec<_>>()
.join(","),
}
}
fn is_volatile(key: &str) -> bool {
VOLATILE.contains(&key)
|| VOLATILE_SUFFIXES
.iter()
.any(|suffix| key.len() > suffix.len() && key.ends_with(suffix))
}
fn describe_record(line: &str, digest: &mut Digest) -> Result<(), String> {
let fields: Vec<&str> = line.split('\t').collect();
if fields.len() < FIXED_COLUMNS {
return Err(format!(
"a record with {} columns, not {FIXED_COLUMNS} or more",
fields.len()
));
}
if fields[1].parse::<u64>().is_err() {
return Err(format!("a POS that is not a number: {}", fields[1]));
}
let mut parts: Vec<String> = Vec::with_capacity(fields.len());
parts.push(fields[0].to_owned()); parts.push(fields[1].to_owned()); parts.push(fields[2].to_owned()); parts.push(fields[3].to_owned()); parts.push(fields[4].to_owned());
parts.push(quality(fields[5]));
parts.push(sorted_keys(fields[6], ';')); parts.push(sorted_keys(fields[7], ';')); for field in &fields[FIXED_COLUMNS..] {
parts.push((*field).to_owned());
}
let borrowed: Vec<&[u8]> = parts.iter().map(|part| part.as_bytes()).collect();
digest.record(&borrowed);
Ok(())
}
fn quality(field: &str) -> String {
let Some(width) = tolerance(DataKind::Variants, "QUAL") else {
return field.to_owned();
};
match field
.parse::<f64>()
.ok()
.and_then(|value| width.bucket(value))
{
Some(bucket) => format!("~{bucket}"),
None => field.to_owned(),
}
}
fn sorted_keys(field: &str, separator: char) -> String {
let mut parts: Vec<&str> = field.split(separator).collect();
parts.sort_unstable();
parts.join(&separator.to_string())
}