use std::collections::HashMap;
use std::io::BufRead as _;
use std::path::Path;
use super::{Declared, LoadError, open};
use crate::dim::{Contig, CoordinateSystem, Dim, Dimensions, ReferenceId, Source};
use crate::types::{DataKind, Dataset};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IntervalFormat {
Bed,
Gff,
}
impl IntervalFormat {
#[must_use]
pub const fn coordinates(self) -> CoordinateSystem {
match self {
Self::Bed => CoordinateSystem::ZeroBasedHalfOpen,
Self::Gff => CoordinateSystem::OneBasedClosed,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Bed => "bed",
Self::Gff => "gff",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
match name.to_ascii_lowercase().as_str() {
"bed" => Some(Self::Bed),
"gff" | "gff3" | "gtf" => Some(Self::Gff),
_ => None,
}
}
#[must_use]
pub fn from_path(path: &Path) -> Option<Self> {
let name = path.file_name()?.to_string_lossy().to_ascii_lowercase();
let trimmed = name
.strip_suffix(".gz")
.or_else(|| name.strip_suffix(".bgz"))
.unwrap_or(name.as_str());
Self::from_name(trimmed.rsplit_once('.')?.1)
}
const fn coordinate_detail(self) -> &'static str {
match self {
Self::Bed => "BED coordinate convention",
Self::Gff => "GFF coordinate convention",
}
}
const fn record_detail(self) -> &'static str {
match self {
Self::Bed => "BED records",
Self::Gff => "GFF records",
}
}
const fn empty_reason(self) -> &'static str {
match self {
Self::Bed => "the BED has no intervals, so it names no contigs",
Self::Gff => "the GFF has no features, so it names no contigs",
}
}
const fn minimum_fields(self) -> usize {
match self {
Self::Bed => 3,
Self::Gff => 8,
}
}
}
pub fn intervals(
path: &Path,
format: Option<IntervalFormat>,
declared: &Declared,
) -> Result<Dataset, LoadError> {
let format = match format.or_else(|| IntervalFormat::from_path(path)) {
Some(format) => format,
None => {
return Err(LoadError::format(
path,
"cannot tell whether this is a bed or a gff from its name; \
pass the format explicitly",
));
}
};
let contigs = scan(path, format)?;
let (reference, contig_naming) = if contigs.is_empty() {
(
Dim::unknown(format.empty_reason()),
Dim::unknown(format.empty_reason()),
)
} else {
let identity = ReferenceId::from_records(declared.build.clone(), contigs);
let naming = identity.naming();
let source = Source::Inferred {
path: path.to_path_buf(),
detail: format.record_detail(),
};
(
Dim::known(identity, source.clone()),
Dim::known(naming, source),
)
};
let organism = super::organism(
declared,
"an interval file does not record its organism; declare it",
);
let dimensions = Dimensions {
organism,
reference,
contig_naming,
coordinates: Dim::known(
format.coordinates(),
Source::Inferred {
path: path.to_path_buf(),
detail: format.coordinate_detail(),
},
),
..Dimensions::default()
};
Ok(Dataset::new(
DataKind::Intervals,
Some(path.to_path_buf()),
dimensions,
))
}
fn scan(path: &Path, format: IntervalFormat) -> Result<Vec<Contig>, LoadError> {
let reader = open(path)?;
let mut names: Vec<String> = Vec::new();
let mut lengths: HashMap<String, u64> = HashMap::new();
for line in reader.lines() {
let line = line.map_err(|error| LoadError::io(path, error))?;
let line = line.trim_end_matches(['\r', '\n']);
if line.trim().is_empty() {
continue;
}
if format == IntervalFormat::Gff {
if line.trim_end() == "##FASTA" {
break;
}
if let Some(region) = line.strip_prefix("##sequence-region") {
if let Some((name, length)) = sequence_region(region) {
lengths.insert(name, length);
}
continue;
}
}
if line.starts_with('#')
|| (format == IntervalFormat::Bed
&& (line.starts_with("track") || line.starts_with("browser")))
{
continue;
}
let fields: Vec<&str> = line.split('\t').collect();
if fields.len() < format.minimum_fields() {
return Err(LoadError::format(
path,
format!(
"a record has {} tab-separated fields; a {} record needs at least {}",
fields.len(),
format.name(),
format.minimum_fields()
),
));
}
let name = fields[0];
if name.is_empty() {
return Err(LoadError::format(path, "a record has an empty contig name"));
}
if !names.iter().any(|seen| seen == name) {
names.push(name.to_owned());
}
}
Ok(names
.into_iter()
.map(|name| Contig {
length: lengths.get(&name).copied(),
name,
md5: None,
})
.collect())
}
fn sequence_region(rest: &str) -> Option<(String, u64)> {
let mut fields = rest.split_whitespace();
let name = fields.next()?;
let start: u64 = fields.next()?.parse().ok()?;
let end: u64 = fields.next()?.parse().ok()?;
(start == 1).then(|| (name.to_owned(), end))
}