1use 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#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConvertReport {
20 pub n_frames: usize,
22 pub n_atoms_last: usize,
24 pub native_con: bool,
26}
27
28#[derive(Debug)]
30pub enum ConvertError {
31 InputMissing(String),
33 Empty,
35 Io(io::Error),
37 Parse(String),
39 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
77pub 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 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
92pub 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 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
131pub fn convert_path_to_con(input: &Path, output: &Path) -> Result<ConvertReport, ConvertError> {
136 let (frames, native_con) = read_frames_for_convert(input)?;
137 let n_frames = frames.len();
138 let n_atoms_last = frames.last().map(|f| f.atom_data.len()).unwrap_or(0);
139 let mut writer = ConFrameWriter::from_path(output)?;
140 writer
141 .extend(frames.iter())
142 .map_err(|e| ConvertError::Io(io::Error::other(e.to_string())))?;
143 Ok(ConvertReport {
144 n_frames,
145 n_atoms_last,
146 native_con,
147 })
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153 use std::fs;
154 use std::path::PathBuf;
155
156 fn fixture(name: &str) -> PathBuf {
157 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
158 .join("resources/test")
159 .join(name)
160 }
161
162 #[test]
163 fn path_looks_like_con_suffixes() {
164 assert!(path_looks_like_con(Path::new("a.con")));
165 assert!(path_looks_like_con(Path::new("a.convel")));
166 assert!(path_looks_like_con(Path::new("a.con.gz")));
167 assert!(!path_looks_like_con(Path::new("a.xyz")));
168 assert!(!path_looks_like_con(Path::new("a.pdb")));
169 }
170
171 #[test]
172 fn convert_native_con_roundtrip() {
173 let dir = tempfile_dir();
174 let out = dir.join("out.con");
175 let report = convert_path_to_con(&fixture("tiny_multi_cuh2.con"), &out).unwrap();
176 assert!(report.native_con);
177 assert_eq!(report.n_frames, 2);
178 assert_eq!(report.n_atoms_last, 4);
179 let (back, native) = read_frames_for_convert(&out).unwrap();
180 assert!(native);
181 assert_eq!(back.len(), 2);
182 assert_eq!(back[0].atom_data.len(), 4);
183 assert_eq!(back[0].atom_data[0].atom_id, 0);
184 }
185
186 #[test]
187 #[cfg(feature = "chemfiles")]
188 fn convert_xyz_via_chemfiles() {
189 let dir = tempfile_dir();
190 let xyz = dir.join("water.xyz");
191 fs::write(
192 &xyz,
193 "3\nwater migrate\nO 0 0 0\nH 0.96 0 0\nH -0.24 0.93 0\n",
194 )
195 .unwrap();
196 let out = dir.join("water.con");
197 let report = convert_path_to_con(&xyz, &out).unwrap();
198 assert!(!report.native_con);
199 assert_eq!(report.n_frames, 1);
200 assert_eq!(report.n_atoms_last, 3);
201 let (back, _) = read_frames_for_convert(&out).unwrap();
202 assert_eq!(back[0].atom_data.len(), 3);
203 let symbols: Vec<_> = back[0]
204 .atom_data
205 .iter()
206 .map(|a| a.symbol.as_ref())
207 .collect();
208 assert!(symbols.contains(&"O"));
209 assert_eq!(symbols.iter().filter(|s| **s == "H").count(), 2);
210 }
211
212 #[test]
213 #[cfg(not(feature = "chemfiles"))]
214 fn convert_xyz_fails_without_chemfiles() {
215 let dir = tempfile_dir();
216 let xyz = dir.join("water.xyz");
217 fs::write(&xyz, "3\nx\nO 0 0 0\nH 1 0 0\nH 0 1 0\n").unwrap();
218 let out = dir.join("water.con");
219 let err = convert_path_to_con(&xyz, &out).unwrap_err();
220 assert!(matches!(
221 err,
222 ConvertError::Chemfiles(ChemfilesImportError::FeatureDisabled)
223 ));
224 }
225
226 fn tempfile_dir() -> PathBuf {
227 let dir = std::env::temp_dir().join(format!(
228 "readcon-convert-{}-{}",
229 std::process::id(),
230 std::time::SystemTime::now()
231 .duration_since(std::time::UNIX_EPOCH)
232 .unwrap()
233 .as_nanos()
234 ));
235 fs::create_dir_all(&dir).unwrap();
236 dir
237 }
238}