use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::Path;
const FORMAT: u32 = 1;
pub const VENDORED: &[(&str, &str)] = &[
(
"HIVDB_10.2",
include_str!("../../rulesets/HIVDB_10.2.ruleset"),
),
(
"HIVDB_9.8",
include_str!("../../rulesets/HIVDB_9.8.ruleset"),
),
];
pub const DEFAULT: &str = "HIVDB_9.8";
pub fn fingerprint() -> Result<String, String> {
let mut parts = Vec::with_capacity(VENDORED.len());
for (name, text) in VENDORED.iter().rev() {
let ruleset = Ruleset::parse(text).map_err(|error| format!("{name}: {error}"))?;
parts.push(format!(
"{} {} blake3:{}",
ruleset.version,
ruleset.date,
blake3::hash(text.as_bytes()).to_hex()
));
}
Ok(format!(
"HIVdb rules as shipped: {}; read by ligase {}",
parts.join("; "),
env!("CARGO_PKG_VERSION")
))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Acids(u32);
const DELETION: u32 = 26;
const INSERTION: u32 = 27;
const STOP: u32 = 28;
impl Acids {
#[must_use]
pub const fn none() -> Self {
Self(0)
}
pub fn of(acid: char) -> Result<Self, String> {
match acid {
'A'..='Z' => Ok(Self(1 << (acid as u32 - 'A' as u32))),
'd' => Ok(Self(1 << DELETION)),
'i' => Ok(Self(1 << INSERTION)),
'*' => Ok(Self(1 << STOP)),
other => Err(format!("not an amino acid: {other:?}")),
}
}
pub fn parse(acids: &str) -> Result<Self, String> {
let mut set = Self::none();
for acid in acids.chars() {
set = set.with(Self::of(acid)?);
}
if set == Self::none() {
return Err("no amino acids".to_owned());
}
Ok(set)
}
#[must_use]
pub const fn with(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[must_use]
pub const fn meets(self, other: Self) -> bool {
self.0 & other.0 != 0
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
}
impl fmt::Display for Acids {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
for bit in 0..26 {
if self.0 & (1 << bit) != 0 {
write!(formatter, "{}", char::from(b'A' + bit))?;
}
}
if self.0 & (1 << DELETION) != 0 {
write!(formatter, "d")?;
}
if self.0 & (1 << INSERTION) != 0 {
write!(formatter, "i")?;
}
if self.0 & (1 << STOP) != 0 {
write!(formatter, "*")?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Residue {
pub position: u32,
pub acids: Acids,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Item {
pub residues: Vec<Residue>,
pub score: i32,
}
#[derive(Clone, Debug)]
pub struct Drug {
pub abbreviation: String,
pub name: String,
pub class: String,
pub gene: String,
pub groups: Vec<Vec<Item>>,
}
#[derive(Clone, Debug)]
pub struct Level {
pub order: u8,
pub sir: String,
pub name: String,
}
#[derive(Clone, Debug)]
pub struct Ruleset {
pub algorithm: String,
pub version: String,
pub date: String,
pub drugs: Vec<Drug>,
levels: Vec<Level>,
default_level: u8,
ranges: Vec<(Option<i32>, Option<i32>, u8)>,
}
impl Ruleset {
#[must_use]
pub fn describe(&self) -> String {
format!("{} {} ({})", self.algorithm, self.version, self.date)
}
#[must_use]
pub fn genes(&self) -> Vec<&str> {
let mut genes: Vec<&str> = Vec::new();
for drug in &self.drugs {
if !genes.contains(&drug.gene.as_str()) {
genes.push(&drug.gene);
}
}
genes
}
#[must_use]
pub fn scored(&self, gene: &str) -> BTreeSet<u32> {
self.drugs
.iter()
.filter(|drug| drug.gene == gene)
.flat_map(|drug| &drug.groups)
.flatten()
.flat_map(|item| &item.residues)
.map(|residue| residue.position)
.collect()
}
pub fn level(&self, score: i32) -> Result<&Level, String> {
let order = self
.ranges
.iter()
.find(|(low, high, _)| {
low.is_none_or(|bound| score >= bound) && high.is_none_or(|b| score <= b)
})
.map_or(self.default_level, |(_, _, order)| *order);
self.levels
.iter()
.find(|level| level.order == order)
.ok_or_else(|| format!("no level {order}"))
}
pub fn vendored(name: &str) -> Result<Self, String> {
let (_, text) = VENDORED
.iter()
.find(|(vendored, _)| *vendored == name)
.ok_or_else(|| {
format!(
"no vendored algorithm called {name:?}; this engine ships {}",
VENDORED
.iter()
.map(|(vendored, _)| *vendored)
.collect::<Vec<_>>()
.join(" and ")
)
})?;
Self::parse(text).map_err(|error| format!("{name}: {error}"))
}
pub fn read(path: &Path) -> Result<Self, String> {
let text = std::fs::read_to_string(path)
.map_err(|error| format!("{}: {error}", path.display()))?;
Self::parse(&text).map_err(|error| format!("{}: {error}", path.display()))
}
#[allow(clippy::too_many_lines)]
pub fn parse(text: &str) -> Result<Self, String> {
let mut lines = text.lines();
let first = lines.next().unwrap_or_default();
let format = first
.strip_prefix("#ligase-hivdb-ruleset ")
.ok_or("not a ruleset: no `#ligase-hivdb-ruleset` on the first line")?;
if format.trim() != FORMAT.to_string() {
return Err(format!(
"ruleset format {}, but this engine reads {FORMAT}",
format.trim()
));
}
let mut algorithm = None;
let mut levels = Vec::new();
let mut default_level = None;
let mut ranges = Vec::new();
let mut gene_of_class: BTreeMap<String, String> = BTreeMap::new();
let mut class_of_drug: BTreeMap<String, String> = BTreeMap::new();
let mut drugs: Vec<Drug> = Vec::new();
for (number, line) in lines.enumerate() {
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
let at = |what: &str| format!("line {}: {what}", number + 2);
let fields: Vec<&str> = line.split('\t').collect();
let number_at = |index: usize, what: &str| -> Result<i32, String> {
fields
.get(index)
.ok_or_else(|| at(&format!("no {what}")))?
.parse::<i32>()
.map_err(|_| at(&format!("{what} is not a number")))
};
let field = |index: usize, what: &str| -> Result<String, String> {
fields
.get(index)
.filter(|value| !value.is_empty())
.map(|value| (*value).to_owned())
.ok_or_else(|| at(&format!("no {what}")))
};
match *fields.first().unwrap_or(&"") {
"algorithm" => {
algorithm = Some((
field(1, "algorithm name")?,
field(2, "version")?,
field(3, "date")?,
));
}
"level" => levels.push(Level {
order: u8::try_from(number_at(1, "level order")?)
.map_err(|_| at("level order is out of range"))?,
sir: field(2, "SIR")?,
name: field(3, "level name")?,
}),
"default" => {
default_level = Some(
u8::try_from(number_at(1, "default level")?)
.map_err(|_| at("default level is out of range"))?,
);
}
"range" => {
let bound = |index: usize, what: &str| -> Result<Option<i32>, String> {
match field(index, what)?.as_str() {
"*" => Ok(None),
value => value
.parse::<i32>()
.map(Some)
.map_err(|_| at(&format!("{what} is not a number"))),
}
};
ranges.push((
bound(1, "range lower bound")?,
bound(2, "range upper bound")?,
u8::try_from(number_at(3, "range level")?)
.map_err(|_| at("range level is out of range"))?,
));
}
"gene" => {
let gene = field(1, "gene name")?;
for class in field(2, "drug classes")?.split(',') {
gene_of_class.insert(class.to_owned(), gene.clone());
}
}
"class" => {
let class = field(1, "class name")?;
for drug in field(2, "drugs")?.split(',') {
class_of_drug.insert(drug.to_owned(), class.clone());
}
}
"drug" => {
let abbreviation = field(1, "drug abbreviation")?;
let class = field(3, "drug class")?;
let gene = gene_of_class
.get(&class)
.ok_or_else(|| at(&format!("no gene declares the class {class}")))?
.clone();
drugs.push(Drug {
abbreviation,
name: field(2, "drug name")?,
class,
gene,
groups: Vec::new(),
});
}
"rule" => {
let abbreviation = field(1, "drug abbreviation")?;
let group = usize::try_from(number_at(2, "group")?)
.map_err(|_| at("group is out of range"))?;
let score = number_at(3, "score")?;
let residues = field(4, "residues")?
.split('+')
.map(parse_residue)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| at(&error))?;
let drug = drugs
.iter_mut()
.find(|drug| drug.abbreviation == abbreviation)
.ok_or_else(|| at(&format!("rule for undeclared drug {abbreviation}")))?;
if group > drug.groups.len() {
return Err(at(&format!(
"group {group} follows group {}, leaving a gap",
drug.groups.len().saturating_sub(1)
)));
}
if group == drug.groups.len() {
drug.groups.push(Vec::new());
}
drug.groups[group].push(Item { residues, score });
}
other => return Err(at(&format!("unknown record {other:?}"))),
}
}
let (algorithm, version, date) = algorithm.ok_or("no `algorithm` record")?;
if levels.is_empty() {
return Err("no `level` records".to_owned());
}
if ranges.is_empty() {
return Err("no `range` records".to_owned());
}
if drugs.is_empty() {
return Err("no `drug` records".to_owned());
}
let default_level = default_level.ok_or("no `default` record")?;
for (_, _, order) in &ranges {
if !levels.iter().any(|level| level.order == *order) {
return Err(format!("a range names level {order}, which is not defined"));
}
}
if !levels.iter().any(|level| level.order == default_level) {
return Err(format!("the default level {default_level} is not defined"));
}
Ok(Self {
algorithm,
version,
date,
drugs,
levels,
default_level,
ranges,
})
}
}
fn parse_residue(residue: &str) -> Result<Residue, String> {
let split = residue
.find(|character: char| !character.is_ascii_digit())
.ok_or_else(|| format!("residue {residue:?} names no amino acid"))?;
if split == 0 {
return Err(format!("residue {residue:?} has no position"));
}
let (position, acids) = residue.split_at(split);
Ok(Residue {
position: position
.parse()
.map_err(|_| format!("residue {residue:?} has no position"))?,
acids: Acids::parse(acids).map_err(|error| format!("residue {residue:?}: {error}"))?,
})
}