Skip to main content

readcon_core/
convert.rs

1//! Foreign path or CON → multi-frame CON write (migration surface).
2//!
3//! Used by the CLI (`readcon-core convert …`) and callable from Rust without
4//! inventing a second conversion stack. Non-CON inputs require the `chemfiles`
5//! feature at runtime ([`chemfiles_import::chemfiles_enabled`]).
6
7use std::fmt;
8use std::io;
9use std::path::Path;
10
11use crate::chemfiles_import::{self, ChemfilesImportError};
12use crate::compression;
13use crate::iterators::ConFrameIterator;
14use crate::types::ConFrame;
15use crate::writer::ConFrameWriter;
16
17/// Outcome of a successful convert.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConvertReport {
20    /// Number of frames written.
21    pub n_frames: usize,
22    /// Atom count of the last frame (0 if no frames — should not happen on success).
23    pub n_atoms_last: usize,
24    /// True when the input was treated as native CON/convel (no chemfiles).
25    pub native_con: bool,
26}
27
28/// Errors from path conversion.
29#[derive(Debug)]
30pub enum ConvertError {
31    /// Input path does not exist or is not a file.
32    InputMissing(String),
33    /// No frames could be read.
34    Empty,
35    /// I/O while reading or writing.
36    Io(io::Error),
37    /// CON parse failure.
38    Parse(String),
39    /// Chemfiles import failure (includes feature disabled).
40    Chemfiles(ChemfilesImportError),
41}
42
43impl fmt::Display for ConvertError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            ConvertError::InputMissing(p) => write!(f, "input not found: {p}"),
47            ConvertError::Empty => write!(f, "no frames produced from input"),
48            ConvertError::Io(e) => write!(f, "I/O error: {e}"),
49            ConvertError::Parse(msg) => write!(f, "parse error: {msg}"),
50            ConvertError::Chemfiles(e) => write!(f, "{e}"),
51        }
52    }
53}
54
55impl std::error::Error for ConvertError {
56    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57        match self {
58            ConvertError::Io(e) => Some(e),
59            ConvertError::Chemfiles(e) => Some(e),
60            _ => None,
61        }
62    }
63}
64
65impl From<io::Error> for ConvertError {
66    fn from(e: io::Error) -> Self {
67        ConvertError::Io(e)
68    }
69}
70
71impl From<ChemfilesImportError> for ConvertError {
72    fn from(e: ChemfilesImportError) -> Self {
73        ConvertError::Chemfiles(e)
74    }
75}
76
77/// True when the path looks like native CON/convel (including compressed suffixes).
78pub fn path_looks_like_con(path: &Path) -> bool {
79    let name = path
80        .file_name()
81        .and_then(|s| s.to_str())
82        .unwrap_or("")
83        .to_ascii_lowercase();
84    // strip compression
85    let base = name
86        .strip_suffix(".gz")
87        .or_else(|| name.strip_suffix(".zst"))
88        .unwrap_or(&name);
89    base.ends_with(".con") || base.ends_with(".convel")
90}
91
92/// Read frames from a path: native CON/convel via the hot-path iterator, else chemfiles.
93pub fn read_frames_for_convert(input: &Path) -> Result<(Vec<ConFrame>, bool), ConvertError> {
94    if !input.is_file() {
95        return Err(ConvertError::InputMissing(input.display().to_string()));
96    }
97    if path_looks_like_con(input) {
98        // gzip/zstd-aware (same path as library readers)
99        let contents = compression::read_file_contents(input)
100            .map_err(|e| ConvertError::Io(io::Error::other(e.to_string())))?;
101        let text = contents
102            .as_str()
103            .map_err(|e| ConvertError::Parse(format!("input is not valid UTF-8: {e}")))?;
104        let mut frames = Vec::new();
105        for item in ConFrameIterator::new(text) {
106            match item {
107                Ok(f) => frames.push(f),
108                Err(e) => {
109                    return Err(ConvertError::Parse(e.to_string()));
110                }
111            }
112        }
113        if frames.is_empty() {
114            return Err(ConvertError::Empty);
115        }
116        Ok((frames, true))
117    } else {
118        if !chemfiles_import::chemfiles_enabled() {
119            return Err(ConvertError::Chemfiles(
120                ChemfilesImportError::FeatureDisabled,
121            ));
122        }
123        let frames = chemfiles_import::con_frames_from_trajectory_path(input)?;
124        if frames.is_empty() {
125            return Err(ConvertError::Empty);
126        }
127        Ok((frames, false))
128    }
129}
130
131/// Convert `input` (CON or chemfiles-readable foreign format) to CON at `output`.
132///
133/// Returns a [`ConvertReport`]. Fails if the foreign path needs chemfiles and
134/// this build is lean, or if zero frames are produced. This is the call the
135/// `readcon-core convert` binary makes.
136///
137/// ```
138/// use readcon_core::convert::convert_path_to_con;
139/// use std::path::Path;
140///
141/// let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
142/// let base = Path::new(env!("CARGO_MANIFEST_DIR")).join("build");
143/// std::fs::create_dir_all(&base).unwrap();
144/// let dir = tempfile::Builder::new()
145///     .prefix("readcon-convert-")
146///     .tempdir_in(&base)
147///     .unwrap();
148/// let out = dir.path().join("out.con");
149/// let report = convert_path_to_con(&src, &out).unwrap();
150/// assert!(report.native_con);
151/// assert_eq!(report.n_frames, 1);
152/// assert_eq!(report.n_atoms_last, 4);
153/// ```
154pub fn convert_path_to_con(input: &Path, output: &Path) -> Result<ConvertReport, ConvertError> {
155    let (frames, native_con) = read_frames_for_convert(input)?;
156    let n_frames = frames.len();
157    let n_atoms_last = frames.last().map(|f| f.atom_data.len()).unwrap_or(0);
158    let mut writer = ConFrameWriter::from_path(output)?;
159    writer
160        .extend(frames.iter())
161        .map_err(|e| ConvertError::Io(io::Error::other(e.to_string())))?;
162    Ok(ConvertReport {
163        n_frames,
164        n_atoms_last,
165        native_con,
166    })
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use std::fs;
173    use std::path::PathBuf;
174
175    fn fixture(name: &str) -> PathBuf {
176        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
177            .join("resources/test")
178            .join(name)
179    }
180
181    #[test]
182    fn path_looks_like_con_suffixes() {
183        assert!(path_looks_like_con(Path::new("a.con")));
184        assert!(path_looks_like_con(Path::new("a.convel")));
185        assert!(path_looks_like_con(Path::new("a.con.gz")));
186        assert!(!path_looks_like_con(Path::new("a.xyz")));
187        assert!(!path_looks_like_con(Path::new("a.pdb")));
188    }
189
190    #[test]
191    fn convert_native_con_roundtrip() {
192        let dir = scratch_dir();
193        let out = dir.path().join("out.con");
194        let report = convert_path_to_con(&fixture("tiny_multi_cuh2.con"), &out).unwrap();
195        assert!(report.native_con);
196        assert_eq!(report.n_frames, 2);
197        assert_eq!(report.n_atoms_last, 4);
198        let (back, native) = read_frames_for_convert(&out).unwrap();
199        assert!(native);
200        assert_eq!(back.len(), 2);
201        assert_eq!(back[0].atom_data.len(), 4);
202        assert_eq!(back[0].atom_data[0].atom_id, 0);
203    }
204
205    #[test]
206    #[cfg(feature = "chemfiles")]
207    fn convert_xyz_via_chemfiles() {
208        let dir = scratch_dir();
209        let xyz = dir.path().join("water.xyz");
210        fs::write(
211            &xyz,
212            "3\nwater migrate\nO 0 0 0\nH 0.96 0 0\nH -0.24 0.93 0\n",
213        )
214        .unwrap();
215        let out = dir.path().join("water.con");
216        let report = convert_path_to_con(&xyz, &out).unwrap();
217        assert!(!report.native_con);
218        assert_eq!(report.n_frames, 1);
219        assert_eq!(report.n_atoms_last, 3);
220        let (back, _) = read_frames_for_convert(&out).unwrap();
221        assert_eq!(back[0].atom_data.len(), 3);
222        let symbols: Vec<_> = back[0]
223            .atom_data
224            .iter()
225            .map(|a| a.symbol.as_ref())
226            .collect();
227        assert!(symbols.contains(&"O"));
228        assert_eq!(symbols.iter().filter(|s| **s == "H").count(), 2);
229    }
230
231    #[test]
232    #[cfg(not(feature = "chemfiles"))]
233    fn convert_xyz_fails_without_chemfiles() {
234        let dir = scratch_dir();
235        let xyz = dir.path().join("water.xyz");
236        fs::write(&xyz, "3\nx\nO 0 0 0\nH 1 0 0\nH 0 1 0\n").unwrap();
237        let out = dir.path().join("water.con");
238        let err = convert_path_to_con(&xyz, &out).unwrap_err();
239        assert!(matches!(
240            err,
241            ConvertError::Chemfiles(ChemfilesImportError::FeatureDisabled)
242        ));
243    }
244
245    fn scratch_dir() -> tempfile::TempDir {
246        let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("build");
247        fs::create_dir_all(&base).unwrap();
248        tempfile::Builder::new()
249            .prefix("readcon-convert-")
250            .tempdir_in(&base)
251            .unwrap()
252    }
253
254    fn convert_names(dir: &std::path::Path) -> Vec<std::ffi::OsString> {
255        let mut names = Vec::new();
256        let Ok(entries) = fs::read_dir(dir) else {
257            return names;
258        };
259        for entry in entries.flatten() {
260            let name = entry.file_name();
261            let text = name.to_string_lossy();
262            if text.starts_with("readcon-convert-") || text == "water.xyz" {
263                names.push(name);
264            }
265        }
266        names.sort();
267        names
268    }
269
270    #[test]
271    fn convert_scratch_leaves_the_system_tempdir_clean() {
272        let system = std::env::temp_dir();
273        let before = convert_names(&system);
274        let dir = scratch_dir();
275        let xyz = dir.path().join("water.xyz");
276        fs::write(&xyz, b"3\nx\nO 0 0 0\nH 1 0 0\nH 0 1 0\n").unwrap();
277        let build = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("build");
278        assert!(
279            dir.path().starts_with(&build),
280            "convert scratch {} is outside build/",
281            dir.path().display()
282        );
283        assert!(
284            !dir.path().starts_with(&system),
285            "convert scratch {} is in the system tempdir",
286            dir.path().display()
287        );
288        assert!(xyz.is_file());
289        drop(dir);
290        assert_eq!(convert_names(&system), before);
291    }
292}