use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use pixelfold_core::parser::{Load, ParsedStructure};
use pixelfold_core::{AtomSet, Protein, select};
use crate::resolve::{self, Resolution};
pub fn structure_path(input: &str, cache_dir: &Path) -> Result<PathBuf> {
match resolve::resolve(input, cache_dir)? {
Resolution::Found(path) => Ok(path),
Resolution::Fetch { id, dest } => {
std::fs::create_dir_all(cache_dir)?;
eprintln!("Fetching {id} from RCSB...");
pixelfold_fetch::fetch_cif(&id, cache_dir)?;
Ok(dest)
}
}
}
pub fn analysis_structure(input: &str, cache_dir: &Path, load: &Load) -> Result<Protein> {
let path = structure_path(input, cache_dir)?;
read(&path)
.and_then(|parsed| parsed.protein(load))
.with_context(|| format!("failed to load {}", path.display()))
}
pub fn parsed(input: &str, cache_dir: &Path) -> Result<ParsedStructure> {
let path = structure_path(input, cache_dir)?;
read(&path).with_context(|| format!("failed to load {}", path.display()))
}
pub fn model_numbers(input: &str, cache_dir: &Path) -> Result<Vec<usize>> {
let path = structure_path(input, cache_dir)?;
let parsed = ParsedStructure::read(&path)
.with_context(|| format!("failed to load {}", path.display()))?;
Ok(parsed.model_numbers())
}
fn read(path: &Path) -> Result<ParsedStructure> {
let parsed = ParsedStructure::read(path)?;
for warning in parsed.warnings() {
eprintln!("Warning: {warning}");
}
Ok(parsed)
}
pub fn selection(protein: &Protein, query: Option<&str>) -> Result<AtomSet> {
select(query.unwrap_or("all"), protein).map_err(|error| anyhow::anyhow!("{error}"))
}
pub fn chosen(protein: &Protein, query: Option<&str>) -> Result<AtomSet> {
let set = selection(protein, query)?;
if set.is_empty() {
anyhow::bail!(
"the selection `{}` matched no atoms",
query.unwrap_or("all")
);
}
Ok(set)
}