use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use crate::dim::{Dimension, Dimensions, IdentifierNamespace, Representation, Source};
use crate::load::{self, Table};
use crate::note::Note;
use crate::types::DataKind;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Conversion {
pub name: &'static str,
pub axis: Dimension,
pub kinds: &'static [DataKind],
pub supplies: &'static str,
}
impl Conversion {
pub const ALL: [Self; 2] = [
Self {
name: "map_identifiers",
axis: Dimension::IdentifierNamespace,
kinds: &[DataKind::EntitySet, DataKind::RankedList],
supplies: "a mapping table",
},
Self {
name: "standardize",
axis: Dimension::Representation,
kinds: &[DataKind::MoleculeSet, DataKind::MoleculeRanking],
supplies: "nothing but the state to arrive in",
},
];
pub const TARGET: &'static str = "to";
#[must_use]
pub fn by_name(name: &str) -> Option<&'static Self> {
Self::ALL.iter().find(|entry| entry.name == name)
}
#[must_use]
pub fn across(axis: Dimension) -> Option<&'static Self> {
Self::ALL.iter().find(|entry| entry.axis == axis)
}
#[must_use]
pub fn converts(&self, kind: DataKind) -> bool {
self.kinds.contains(&kind)
}
pub fn target(&self, declared: &str) -> Result<Target, String> {
match self.axis {
Dimension::IdentifierNamespace => {
let namespace = IdentifierNamespace::new(declared);
if namespace.is_empty() {
return Err(format!(
"`{}` needs a namespace to convert to; `{}` was blank",
self.name,
Self::TARGET
));
}
Ok(Target::IdentifierNamespace(namespace))
}
Dimension::Representation => Representation::parse(declared)
.map(Target::Representation)
.map_err(|detail| format!("`{}`: {detail}", self.name)),
other => Err(format!(
"`{}` is registered across {other}, which has no target type yet",
self.name
)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
IdentifierNamespace(IdentifierNamespace),
Representation(Representation),
}
impl Target {
#[must_use]
pub const fn axis(&self) -> Dimension {
match self {
Self::IdentifierNamespace(_) => Dimension::IdentifierNamespace,
Self::Representation(_) => Dimension::Representation,
}
}
pub fn apply(&self, dimensions: &mut Dimensions, source: Source) {
match self {
Self::IdentifierNamespace(namespace) => {
dimensions.identifier_namespace = crate::dim::Dim::known(namespace.clone(), source);
}
Self::Representation(representation) => {
dimensions.representation = crate::dim::Dim::known(representation.clone(), source);
}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Ambiguous {
#[default]
Drop,
FanOut,
}
impl Ambiguous {
pub const DROP: &'static str = "drop";
pub const FAN_OUT: &'static str = "fan-out";
pub fn parse(declared: &str) -> Result<Self, String> {
match declared.trim() {
Self::DROP => Ok(Self::Drop),
Self::FAN_OUT => Ok(Self::FanOut),
other => Err(format!(
"`ambiguous` is `{}` or `{}`; `{other}` is neither",
Self::DROP,
Self::FAN_OUT
)),
}
}
#[must_use]
pub const fn fans_out(self) -> bool {
matches!(self, Self::FanOut)
}
}
const NAMED_AT_MOST: usize = 20;
pub fn map_identifiers(
entities: &Path,
id_column: &str,
table: &Path,
table_id_column: &str,
column: &str,
ambiguous: Ambiguous,
out: &Path,
) -> Result<Vec<Note>, String> {
if column.trim() == table_id_column.trim() {
return Err(format!(
"`{column}` is the mapping table's own identifier column, so every identifier \
would map to itself; name the column holding the identifiers to convert to"
));
}
let mapping = read_mapping(table, table_id_column, column)?;
let colliding = collisions(entities, id_column, &mapping, ambiguous)?;
let reader = load::open(entities).map_err(|error| error.to_string())?;
let mut rows = Table::read(reader).map_err(|error| error.to_string())?;
let at = rows
.column(id_column)
.ok_or_else(|| missing(entities, id_column, rows.header()))?;
let mut written = String::new();
written.push_str(&rows.header().join("\t"));
written.push('\n');
let mut found = Noticed::default();
while let Some(row) = rows.next_row().map_err(|error| error.to_string())? {
let identifier = row.field(at).unwrap_or_default().to_owned();
let write = |written: &mut String, target: &str| {
let mut fields: Vec<&str> = row.line.split('\t').collect();
fields[at] = target;
written.push_str(&fields.join("\t"));
written.push('\n');
};
match mapping.get(&identifier).map(Vec::as_slice) {
Some([target]) if !colliding.contains(target) => write(&mut written, target),
Some([_]) => found.note(Note::IdentifierCollides { identifier }),
Some(targets) if ambiguous.fans_out() => {
let crossed: Vec<&String> = targets
.iter()
.filter(|target| !colliding.contains(*target))
.collect();
for target in &crossed {
write(&mut written, target);
}
if crossed.is_empty() {
found.note(Note::IdentifierCollides { identifier });
} else {
found.fanned(crossed.len(), Note::IdentifierFannedOut { identifier });
}
}
Some(_) => found.note(Note::IdentifierAmbiguous { identifier }),
None => found.note(Note::IdentifierUnmapped { identifier }),
}
}
std::fs::write(out, written).map_err(|error| error.to_string())?;
Ok(found.into_notes())
}
fn collisions(
entities: &Path,
id_column: &str,
mapping: &BTreeMap<String, Vec<String>>,
ambiguous: Ambiguous,
) -> Result<BTreeSet<String>, String> {
let reader = load::open(entities).map_err(|error| error.to_string())?;
let mut rows = Table::read(reader).map_err(|error| error.to_string())?;
let at = rows
.column(id_column)
.ok_or_else(|| missing(entities, id_column, rows.header()))?;
let mut reached: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
while let Some(row) = rows.next_row().map_err(|error| error.to_string())? {
let identifier = row.field(at).unwrap_or_default();
let targets = match mapping.get(identifier).map(Vec::as_slice) {
Some(targets @ [_]) => targets,
Some(targets) if ambiguous.fans_out() => targets,
Some(_) | None => continue,
};
for target in targets {
reached
.entry(target.clone())
.or_default()
.insert(identifier.to_owned());
}
}
Ok(reached
.into_iter()
.filter(|(_, sources)| sources.len() > 1)
.map(|(target, _)| target)
.collect())
}
#[derive(Default)]
struct Noticed {
named: Vec<Note>,
seen: BTreeSet<String>,
count: u32,
fanned: u32,
fanned_rows: u32,
}
impl Noticed {
fn note(&mut self, note: Note) {
if !self.remember(note.clone()) {
return;
}
self.count = self.count.saturating_add(1);
}
fn fanned(&mut self, rows: usize, note: Note) {
if !self.remember(note) {
return;
}
self.fanned = self.fanned.saturating_add(1);
self.fanned_rows = self
.fanned_rows
.saturating_add(u32::try_from(rows).unwrap_or(u32::MAX));
}
fn remember(&mut self, note: Note) -> bool {
if !self.seen.insert(note.value()) {
return false;
}
if self.named.len() < NAMED_AT_MOST {
self.named.push(note);
}
true
}
fn into_notes(mut self) -> Vec<Note> {
if self.count > 0 {
self.named
.push(Note::IdentifiersDidNotCross { count: self.count });
}
if self.fanned > 0 {
self.named.push(Note::IdentifiersFannedOut {
identifiers: self.fanned,
rows: self.fanned_rows,
});
}
self.named
}
}
fn read_mapping(
path: &Path,
id_column: &str,
column: &str,
) -> Result<BTreeMap<String, Vec<String>>, String> {
let reader = load::open(path).map_err(|error| error.to_string())?;
let mut table = Table::read(reader).map_err(|error| error.to_string())?;
let from = table
.column(id_column)
.ok_or_else(|| missing(path, id_column, table.header()))?;
let to = table
.column(column)
.ok_or_else(|| missing(path, column, table.header()))?;
let mut mapping: BTreeMap<String, Vec<String>> = BTreeMap::new();
while let Some(row) = table.next_row().map_err(|error| error.to_string())? {
let (Some(source), Some(target)) = (row.field(from), row.field(to)) else {
continue;
};
if source.is_empty() || target.is_empty() {
continue;
}
let targets = mapping.entry(source.to_owned()).or_default();
if !targets.iter().any(|known| known == target) {
targets.push(target.to_owned());
}
}
Ok(mapping)
}
fn missing(path: &Path, wanted: &str, header: &[String]) -> String {
format!(
"{} has no column named `{wanted}`; its columns are {}",
crate::dim::display_path(path),
header.join(", ")
)
}