use std::fmt;
use super::english_list;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Identity {
InChIKey,
Smiles,
}
impl Identity {
pub const ALL: [Self; 2] = [Self::InChIKey, Self::Smiles];
#[must_use]
pub const fn describe(self) -> &'static str {
match self {
Self::InChIKey => "InChIKey",
Self::Smiles => "SMILES",
}
}
#[must_use]
pub const fn spelling(self) -> &'static str {
match self {
Self::InChIKey => "inchikey",
Self::Smiles => "smiles",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
let name = name.trim().to_ascii_lowercase();
Self::ALL
.into_iter()
.find(|identity| identity.spelling() == name)
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.describe())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Standardisation {
SaltStripped,
TautomerNormalised,
ChargeNeutralised,
StereoDiscarded,
}
impl Standardisation {
pub const ALL: [Self; 4] = [
Self::SaltStripped,
Self::TautomerNormalised,
Self::ChargeNeutralised,
Self::StereoDiscarded,
];
#[must_use]
pub const fn describe(self) -> &'static str {
match self {
Self::SaltStripped => "salt-stripped",
Self::TautomerNormalised => "tautomer-normalised",
Self::ChargeNeutralised => "charge-neutralised",
Self::StereoDiscarded => "stereo-discarded",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
let name = name.trim().to_ascii_lowercase();
Self::ALL
.into_iter()
.find(|operation| operation.describe() == name)
}
fn all_named() -> String {
english_list(
&Self::ALL
.into_iter()
.map(Self::describe)
.collect::<Vec<&str>>(),
)
}
}
impl fmt::Display for Standardisation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.describe())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Representation {
identity: Identity,
applied: Vec<Standardisation>,
}
impl Representation {
#[must_use]
pub fn new<I>(identity: Identity, applied: I) -> Self
where
I: IntoIterator<Item = Standardisation>,
{
let given: Vec<Standardisation> = applied.into_iter().collect();
Self {
identity,
applied: Standardisation::ALL
.into_iter()
.filter(|operation| given.contains(operation))
.collect(),
}
}
pub fn parse(spelled: &str) -> Result<Self, String> {
let spelled = spelled.trim();
if spelled.is_empty() {
return Err(format!(
"a representation needs an identity to compare by; name one of {}",
english_list(
&Identity::ALL
.into_iter()
.map(Identity::spelling)
.collect::<Vec<&str>>()
)
));
}
let (identity, operations) = match spelled.split_once(';') {
Some((identity, operations)) => (identity, operations.trim()),
None => (spelled, ""),
};
let identity = Identity::from_name(identity).ok_or_else(|| {
format!(
"`{}` is not an identity this engine can compare molecules by; name one of {}",
identity.trim(),
english_list(
&Identity::ALL
.into_iter()
.map(Identity::spelling)
.collect::<Vec<&str>>()
)
)
})?;
if operations.is_empty() || operations.eq_ignore_ascii_case(AS_GIVEN) {
return Ok(Self::new(identity, []));
}
let mut applied = Vec::new();
for named in operations.split(',') {
if named.trim().is_empty() {
continue;
}
applied.push(Standardisation::from_name(named).ok_or_else(|| {
format!(
"`{}` is not a standardisation this engine knows; it knows {}",
named.trim(),
Standardisation::all_named()
)
})?);
}
Ok(Self::new(identity, applied))
}
#[must_use]
pub const fn identity(&self) -> Identity {
self.identity
}
#[must_use]
pub fn applied(&self) -> &[Standardisation] {
&self.applied
}
#[must_use]
pub fn operations_beyond(&self, other: &Self) -> Vec<&'static str> {
self.applied
.iter()
.filter(|operation| !other.applied.contains(operation))
.map(|operation| operation.describe())
.collect()
}
#[must_use]
pub fn spell(&self) -> String {
let operations = if self.applied.is_empty() {
AS_GIVEN.to_owned()
} else {
self.applied
.iter()
.map(|operation| operation.describe())
.collect::<Vec<&str>>()
.join(", ")
};
format!("{}; {operations}", self.identity.spelling())
}
}
const AS_GIVEN: &str = "as given";
impl fmt::Display for Representation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, ", self.identity)?;
if self.applied.is_empty() {
return f.write_str(AS_GIVEN);
}
f.write_str(&english_list(
&self
.applied
.iter()
.map(|operation| operation.describe())
.collect::<Vec<&str>>(),
))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn the_operations_are_held_in_one_order_however_they_arrive() {
let forwards = Representation::new(
Identity::InChIKey,
[
Standardisation::SaltStripped,
Standardisation::ChargeNeutralised,
],
);
let backwards = Representation::new(
Identity::InChIKey,
[
Standardisation::ChargeNeutralised,
Standardisation::SaltStripped,
],
);
assert_eq!(forwards, backwards);
assert_eq!(forwards.applied(), backwards.applied());
}
#[test]
fn an_operation_given_twice_is_applied_once() {
assert_eq!(
Representation::new(
Identity::InChIKey,
[Standardisation::SaltStripped, Standardisation::SaltStripped]
)
.applied(),
[Standardisation::SaltStripped]
);
}
#[test]
fn what_a_standardiser_writes_is_what_the_loader_reads() {
for representation in [
Representation::new(Identity::InChIKey, []),
Representation::new(Identity::Smiles, []),
Representation::new(
Identity::InChIKey,
[
Standardisation::SaltStripped,
Standardisation::TautomerNormalised,
Standardisation::ChargeNeutralised,
Standardisation::StereoDiscarded,
],
),
] {
assert_eq!(
Representation::parse(&representation.spell()).as_ref(),
Ok(&representation)
);
}
}
#[test]
fn a_blank_is_refused_rather_than_read_as_as_given() {
for blank in ["", " ", "; as given"] {
assert!(Representation::parse(blank).is_err(), "{blank:?}");
}
}
#[test]
fn an_error_names_what_the_engine_does_know() {
let said = Representation::parse("inchikey; desalted-twice").unwrap_err();
assert!(said.contains("desalted-twice"), "{said}");
for operation in Standardisation::ALL {
assert!(said.contains(operation.describe()), "{said}");
}
let said = Representation::parse("fingerprint").unwrap_err();
assert!(said.contains("fingerprint"), "{said}");
assert!(said.contains("inchikey"), "{said}");
assert!(said.contains("smiles"), "{said}");
}
}