flowcells.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. use std::{
  2. collections::{HashMap, HashSet},
  3. fmt,
  4. fs::{self, File, OpenOptions},
  5. io::{BufReader, Read},
  6. os::unix::fs::MetadataExt,
  7. path::Path,
  8. };
  9. use anyhow::Context;
  10. use chrono::{DateTime, TimeZone, Utc};
  11. use glob::glob;
  12. use log::{info, warn};
  13. use serde::{Deserialize, Serialize};
  14. use crate::{
  15. collection::minknow::{parse_pore_activity_from_reader, parse_throughput_from_reader},
  16. helpers::{find_files, list_directories},
  17. io::{readers::get_gz_reader, writers::get_gz_writer},
  18. };
  19. use super::minknow::{MinKnowSampleSheet, PoreStateEntry, PoreStateEntryExt, ThroughputEntry};
  20. /// A collection of `IdInput` records, with utility methods
  21. /// for loading, saving, deduplication, and construction from TSV.
  22. #[derive(Debug, Serialize, Deserialize, Clone, Default)]
  23. pub struct IdsInput {
  24. /// The list of ID entries.
  25. pub data: Vec<IdInput>,
  26. }
  27. /// A unique sample identifier from sequencing metadata.
  28. ///
  29. /// Uniqueness is defined by the combination of all fields.
  30. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
  31. pub struct IdInput {
  32. /// Case or patient ID.
  33. pub case_id: String,
  34. /// Time point or sample type.
  35. pub sample_type: String,
  36. /// Barcode number (sequencing index).
  37. pub barcode: String,
  38. /// Flow cell identifier.
  39. pub flow_cell_id: String,
  40. }
  41. impl IdsInput {
  42. /// Load `IdsInput` from a JSON file.
  43. pub fn load_json<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
  44. let file = File::open(&path)?;
  45. Ok(serde_json::from_reader(file)?)
  46. }
  47. /// Save `IdsInput` to a JSON file (pretty-printed).
  48. pub fn save_json<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
  49. let file = File::create(&path)?;
  50. serde_json::to_writer_pretty(file, self)?;
  51. Ok(())
  52. }
  53. /// Remove duplicate `IdInput` entries, retaining the first occurrence.
  54. pub fn dedup(&mut self) {
  55. let mut seen = HashSet::new();
  56. self.data.retain(|item| seen.insert(item.clone()));
  57. }
  58. /// Add a new `IdInput` and deduplicate.
  59. pub fn add_input(&mut self, entry: IdInput) {
  60. self.data.push(entry);
  61. self.dedup();
  62. }
  63. }
  64. /// Container for a deduplicated and enriched collection of flowcells (`FlowCel`).
  65. ///
  66. /// `FlowCells` represents the aggregated result of scanning multiple sources:
  67. /// - A cached archive of flowcells (`archive_store_path`)
  68. /// - A live scan of the local run directory (`local_run_dir`)
  69. ///
  70. /// Each [`FlowCel`] contains all necessary metadata for downstream processing,
  71. /// including parsed MinKNOW sample sheet data, `.pod5` file statistics, experiment layout,
  72. /// and optional sample/case annotations from an [`IdsInput`] file.
  73. ///
  74. /// The [`FlowCells::load`] method performs the following:
  75. /// - Loads existing flowcells from the archive if available
  76. /// - Scans local directories for new or updated flowcells
  77. /// - Deduplicates flowcells using the `flowcell_id`
  78. /// - Retains the most recently modified version of each flowcell
  79. /// - Enriches each flowcell with case-level annotations
  80. ///
  81. /// # Fields
  82. /// - `flow_cells`: A deduplicated list of fully parsed [`FlowCel`] instances.
  83. ///
  84. /// # Example
  85. /// ```
  86. /// let flow_cells = FlowCells::load(
  87. /// "/mnt/data/runs",
  88. /// "inputs.json",
  89. /// "flowcell_cache.json"
  90. /// )?;
  91. /// println!("Loaded {} unique flowcells", flow_cells.flow_cells.len());
  92. /// ```
  93. ///
  94. /// # Deduplication
  95. /// Flowcells are uniquely identified by their `flowcell_id`, a combination of
  96. /// `{experiment_id}/{sample_id}`. If both archived and local versions exist,
  97. /// the one with the latest `.pod5` modification time is retained.
  98. ///
  99. /// # Related Types
  100. /// - [`FlowCel`]: Describes a flowcell, its metadata, and files
  101. /// - [`FlowCellExperiment`]: Muxed vs. demuxed layout classification
  102. /// - [`FlowCellLocation`]: Indicates source (local or archive)
  103. /// - [`MinKnowSampleSheet`]: Parsed sample sheet data
  104. /// - [`IdInput`]: Case-level annotation applied to flowcells
  105. #[derive(Debug, Serialize, Deserialize, Clone, Default)]
  106. pub struct FlowCells {
  107. /// A collection of parsed flowcell metadata records.
  108. pub flow_cells: Vec<FlowCell>,
  109. }
  110. impl FlowCells {
  111. /// Load and merge flowcells from archive and local directories, then annotate with `IdsInput`.
  112. ///
  113. /// # Arguments
  114. /// * `local_run_dir` - Root directory containing local flowcell run folders.
  115. /// * `inputs_path` - Path to a JSON file with [`IdInput`] annotations.
  116. /// * `archive_store_path` - Path to a cached JSON file of archived flowcells.
  117. ///
  118. /// # Returns
  119. /// A deduplicated and annotated [`FlowCells`] collection.
  120. ///
  121. /// # Errors
  122. /// Returns an error if any input file cannot be read or parsed, or if local scanning fails.
  123. pub fn load(
  124. local_run_dir: &str,
  125. inputs_path: &str,
  126. archive_store_path: &str,
  127. ) -> anyhow::Result<Self> {
  128. let mut instance = Self::default();
  129. instance.load_from_archive(archive_store_path)?;
  130. instance.load_from_local(local_run_dir)?;
  131. instance.annotate_with_inputs(inputs_path)?;
  132. instance.save_to_archive(archive_store_path)?;
  133. Ok(instance)
  134. }
  135. /// Load flowcells from a cached archive and merge into `self.flow_cells`.
  136. ///
  137. /// Retains only the most recently modified entry for each `flowcell_id`.
  138. ///
  139. /// # Arguments
  140. /// * `archive_path` - Path to archive JSON file.
  141. ///
  142. /// # Errors
  143. /// Returns an error if the file cannot be read or parsed.
  144. pub fn load_from_archive(&mut self, archive_path: &str) -> anyhow::Result<()> {
  145. if !Path::new(archive_path).exists() {
  146. return Ok(());
  147. }
  148. let file = get_gz_reader(archive_path)
  149. .with_context(|| format!("Failed to open archive file: {archive_path}"))?;
  150. let archived: Vec<FlowCell> = serde_json::from_reader(BufReader::new(file))
  151. .with_context(|| format!("Failed to parse FlowCells from: {archive_path}"))?;
  152. self.insert_flowcells(archived);
  153. Ok(())
  154. }
  155. pub fn save_to_archive(&mut self, archive_path: &str) -> anyhow::Result<()> {
  156. // let file = OpenOptions::new()
  157. // .write(true)
  158. // .create(true)
  159. // .truncate(true)
  160. // .open(archive_path)
  161. // .with_context(|| format!("Failed to open archive file for writing: {archive_path}"))?;
  162. let file = get_gz_writer(archive_path, true)
  163. .with_context(|| format!("Failed to open archive file for writing: {archive_path}"))?;
  164. serde_json::to_writer_pretty(file, &self.flow_cells)
  165. .with_context(|| format!("Failed to write FlowCells to: {archive_path}"))?;
  166. Ok(())
  167. }
  168. /// Scan local run directories for flowcells and merge into `self.flow_cells`.
  169. ///
  170. /// Uses `scan_local()` to parse local metadata and selects the most recently modified
  171. /// version if duplicates exist.
  172. ///
  173. /// # Arguments
  174. /// * `local_dir` - Root directory containing flowcell runs.
  175. ///
  176. /// # Errors
  177. /// Returns an error if scanning fails or if directory layout is invalid.
  178. pub fn load_from_local(&mut self, local_dir: &str) -> anyhow::Result<()> {
  179. info!("Scanning {local_dir} for sample sheets.");
  180. let sample_sheets = find_files(&format!("{local_dir}/**/sample_sheet*"))?;
  181. info!("{} sample sheets found.", sample_sheets.len());
  182. for path in sample_sheets {
  183. let dir = path
  184. .parent()
  185. .ok_or_else(|| anyhow::anyhow!("Invalid sample_sheet path: {}", path.display()))?;
  186. let dir_str = dir.to_string_lossy();
  187. let (sheet, pore, throughput, files) = scan_local(&dir_str)
  188. .with_context(|| format!("Failed to scan local dir: {dir_str}"))?;
  189. let fc = FlowCell::new(
  190. sheet,
  191. pore,
  192. throughput,
  193. FlowCellLocation::Local(dir_str.to_string()),
  194. files,
  195. )
  196. .with_context(|| format!("Failed to create FlowCell from dir: {dir_str}"))?;
  197. self.insert_flowcells(vec![fc]);
  198. }
  199. Ok(())
  200. }
  201. /// Annotate flowcells with matching `IdInput` records from JSON.
  202. ///
  203. /// Assigns to `FlowCell.cases` all matching `IdInput`s by `flow_cell_id`.
  204. ///
  205. /// # Arguments
  206. /// * `inputs_path` - Path to JSON file containing a list of `IdInput` records.
  207. ///
  208. /// # Errors
  209. /// Returns an error if the file is unreadable or malformed.
  210. pub fn annotate_with_inputs(&mut self, inputs_path: &str) -> anyhow::Result<()> {
  211. if !Path::new(inputs_path).exists() {
  212. warn!("IdsInput file not found at {}", inputs_path);
  213. return Ok(());
  214. }
  215. let inputs = IdsInput::load_json(inputs_path)
  216. .with_context(|| format!("Failed to load IdsInput from: {inputs_path}"))?;
  217. self.cross_cases(&inputs)
  218. .with_context(|| format!("Failed to cross with IdsInput from: {inputs_path}"))?;
  219. Ok(())
  220. }
  221. pub fn cross_cases(&mut self, inputs: &IdsInput) -> anyhow::Result<()> {
  222. for fc in &mut self.flow_cells {
  223. fc.cases = inputs
  224. .data
  225. .iter()
  226. .filter(|id| id.flow_cell_id == fc.sample_sheet.flow_cell_id)
  227. .cloned()
  228. .collect();
  229. }
  230. Ok(())
  231. }
  232. /// Insert new flowcells into the current collection, deduplicating by `flowcell_id`.
  233. ///
  234. /// For duplicates, retains the flowcell with the newer `.modified` timestamp.
  235. ///
  236. /// # Arguments
  237. /// * `new_cells` - A vector of parsed `FlowCell` instances.
  238. pub fn insert_flowcells(&mut self, new_cells: Vec<FlowCell>) {
  239. // let mut map: HashMap<String, FlowCell> = self
  240. // .flow_cells
  241. // .drain(..)
  242. // .map(|fc| {
  243. // (fc.sample_sheet.flow_cell_id.clone(), fc)
  244. // })
  245. // .collect();
  246. //
  247. for fc in new_cells {
  248. self.flow_cells.push(fc);
  249. // map.entry(fc.sample_sheet.flow_cell_id.clone())
  250. // .and_modify(|existing| {
  251. // if fc.modified > existing.modified {
  252. // *existing = fc.clone();
  253. // }
  254. // })
  255. // .or_insert(fc);
  256. }
  257. self.sort_by_modified();
  258. self.flow_cells.dedup_by_key(|fc| fc.id());
  259. // self.flow_cells = map.into_values().collect();
  260. }
  261. /// Discover new archived flowcells in `archive_dir` and update the JSON at `store_path`.
  262. ///
  263. /// - Loads existing archive (gzip-aware) into `self`.
  264. /// - Recursively scans **all** `.tar` files under `archive_dir`.
  265. /// - For each archive, runs `scan_archive`, builds a `FlowCell` with
  266. /// `FlowCellLocation::Archived(archive_dir)`, and merges it via `insert_flowcells`.
  267. /// - Logs how many new flowcells were added.
  268. /// - Saves back to `store_path` (gzip-compressed).
  269. pub fn update_archive_from_scan(
  270. &mut self,
  271. archive_dir: &str,
  272. store_path: &str,
  273. ) -> anyhow::Result<()> {
  274. // 1) Load whatever’s already in the archive (if present)
  275. self.load_from_archive(store_path)
  276. .with_context(|| format!("Loading existing archive from {}", store_path))?;
  277. let before = self.flow_cells.len();
  278. info!("Scanning '{}' for .tar archives…", archive_dir);
  279. // 2) Find & process every .tar (recursive)
  280. let pattern = format!("{}/*.tar", archive_dir);
  281. let entries =
  282. glob(&pattern).with_context(|| format!("Invalid glob pattern: {}", &pattern))?;
  283. for entry in entries.filter_map(Result::ok) {
  284. let path = entry.to_string_lossy();
  285. match scan_archive(&path) {
  286. Ok((sheet, pore, throughput, files)) => {
  287. match FlowCell::new(
  288. sheet,
  289. pore,
  290. throughput,
  291. FlowCellLocation::Archived(path.to_string()),
  292. files,
  293. ) {
  294. Ok(fc) => {
  295. // merge & dedup
  296. self.insert_flowcells(vec![fc]);
  297. }
  298. Err(e) => {
  299. warn!("Failed to build FlowCell from '{}': {}", path, e);
  300. }
  301. }
  302. }
  303. Err(e) => warn!("Failed to scan archive '{}': {}", path, e),
  304. }
  305. }
  306. let added = self.flow_cells.len().saturating_sub(before);
  307. info!("Discovered {} new archived flowcell(s).", added);
  308. // 3) Save the merged list back
  309. self.save_to_archive(store_path)
  310. .with_context(|| format!("Saving updated archive to {}", store_path))?;
  311. Ok(())
  312. }
  313. /// Sorts `flow_cells` in-place from oldest (`modified` smallest) to newest.
  314. pub fn sort_by_modified(&mut self) {
  315. self.flow_cells.sort_by_key(|fc| fc.modified);
  316. }
  317. }
  318. /// Represents a fully described flowcell unit, including experimental metadata,
  319. /// physical location (local or archived), sample sheet data, and associated pod5 files.
  320. ///
  321. /// A `FlowCell` object serves as the central unit in the data model for sample aggregation
  322. /// and downstream processing.
  323. ///
  324. /// # Fields
  325. /// - `sample_sheet`: The original MinKNOW sample sheet metadata (`MinKnowSampleSheet`).
  326. /// - `experiment`: Experiment type inferred from `.pod5` files (see `FlowCellExperiment`).
  327. /// - `location`: Whether the flowcell was loaded from a local directory or archive store.
  328. /// - `modified`: Last modification timestamp among `.pod5` files.
  329. /// - `pod5_size`: Total size (in bytes) of `.pod5` files.
  330. /// - `n_pod5`: Number of `.pod5` files found.
  331. /// - `cases`: List of sample/case-level annotations associated with this flowcell (from `IdsInput`).
  332. #[derive(Debug, Serialize, Deserialize, Clone)]
  333. pub struct FlowCell {
  334. pub sample_sheet: MinKnowSampleSheet,
  335. pub experiment: FlowCellExperiment,
  336. pub location: FlowCellLocation,
  337. pub modified: DateTime<Utc>,
  338. pub pod5_size: usize,
  339. pub n_pod5: usize,
  340. pub cases: Vec<IdInput>,
  341. pub pore_activity: Option<Vec<PoreStateEntry>>,
  342. pub throughput: Option<Vec<ThroughputEntry>>,
  343. }
  344. /// Describes the physical origin of a flowcell when loaded.
  345. ///
  346. /// This is used to differentiate flowcells discovered during a local scan
  347. /// versus those restored from an archived store.
  348. #[derive(Debug, Serialize, Deserialize, Clone)]
  349. pub enum FlowCellLocation {
  350. /// Flowcell discovered in a local filesystem path.
  351. Local(String),
  352. /// Flowcell restored from a `.tar` archive or a serialized cache.
  353. Archived(String),
  354. }
  355. impl fmt::Display for FlowCellLocation {
  356. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  357. write!(
  358. f,
  359. "{}",
  360. match self {
  361. FlowCellLocation::Local(_) => "local",
  362. FlowCellLocation::Archived(_) => "archived",
  363. }
  364. )
  365. }
  366. }
  367. impl FlowCell {
  368. /// Constructs a new `FlowCell` from a sample sheet and associated file list.
  369. ///
  370. /// This method aggregates information from a parsed `MinKnowSampleSheet` and the
  371. /// corresponding `.pod5` file metadata, and infers the experiment type from
  372. /// file paths using `FlowCellExperiment::from_pod5_paths`.
  373. ///
  374. /// # Arguments
  375. /// - `sample_sheet`: Parsed sample sheet metadata.
  376. /// - `location`: Origin of the flowcell (local or archived).
  377. /// - `files`: List of files associated with the flowcell, each with:
  378. /// - `String`: file path
  379. /// - `u64`: size in bytes
  380. /// - `DateTime<Utc>`: modification time
  381. ///
  382. /// # Returns
  383. /// - `Ok(FlowCell)` if experiment type and file metadata are successfully resolved.
  384. /// - `Err` if the experiment type cannot be determined.
  385. ///
  386. /// # Errors
  387. /// - If `FlowCellExperiment::from_pod5_paths` fails (e.g., unknown layout).
  388. ///
  389. /// # Example
  390. /// ```
  391. /// let fc = FlowCell::new(sample_sheet, FlowCellLocation::Local(dir), files)?;
  392. /// println!("Flowcell ID: {}", fc.flowcell_id);
  393. /// ```
  394. pub fn new(
  395. sample_sheet: MinKnowSampleSheet,
  396. pore_activity: Option<Vec<PoreStateEntry>>,
  397. throughput: Option<Vec<ThroughputEntry>>,
  398. location: FlowCellLocation,
  399. files: Vec<(String, u64, DateTime<Utc>)>,
  400. ) -> anyhow::Result<Self> {
  401. let flowcell_id = sample_sheet.flow_cell_id.clone();
  402. // Filter .pod5 files
  403. let pod5s: Vec<_> = files
  404. .iter()
  405. .filter(|(path, _, _)| path.ends_with(".pod5"))
  406. .cloned()
  407. .collect();
  408. let n_pod5 = pod5s.len();
  409. // Infer experiment type from pod5 paths
  410. let experiment = FlowCellExperiment::from_pod5_paths(
  411. &files.iter().map(|(p, _, _)| p.to_string()).collect(),
  412. )
  413. .ok_or_else(|| anyhow::anyhow!("Can't find experiment type for {flowcell_id}"))?;
  414. // Aggregate pod5 size and latest modification time
  415. let (pod5_size, modified): (usize, DateTime<Utc>) = files
  416. .into_iter()
  417. .filter(|(path, _, _)| path.ends_with(".pod5"))
  418. .fold(
  419. (0, DateTime::<Utc>::MIN_UTC),
  420. |(acc_size, acc_time), (_, size, time)| {
  421. (
  422. acc_size + size as usize,
  423. if acc_time < time { time } else { acc_time },
  424. )
  425. },
  426. );
  427. Ok(Self {
  428. experiment,
  429. location,
  430. modified,
  431. sample_sheet,
  432. pod5_size,
  433. n_pod5,
  434. cases: Vec::new(),
  435. pore_activity,
  436. throughput,
  437. })
  438. }
  439. pub fn id(&self) -> String {
  440. match &self.experiment {
  441. FlowCellExperiment::WGSPod5Mux(p) => p,
  442. FlowCellExperiment::WGSPod5Demux(p) => p,
  443. }.to_string()
  444. }
  445. }
  446. /// Describes the type of experiment layout based on `.pod5` file structure.
  447. ///
  448. /// Used to distinguish between whole-genome sequencing (WGS) `.pod5` files
  449. /// organized in a single (muxed) directory or demultiplexed (`pod5_pass`) structure.
  450. #[derive(Debug, Serialize, Deserialize, Clone)]
  451. pub enum FlowCellExperiment {
  452. /// `.pod5` files are stored in a single unbarcoded directory, typically `/pod5/`.
  453. WGSPod5Mux(String),
  454. /// `.pod5` files are organized by barcode in subdirectories, typically `/pod5_pass/`.
  455. WGSPod5Demux(String),
  456. }
  457. impl fmt::Display for FlowCellExperiment {
  458. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  459. write!(
  460. f,
  461. "{}",
  462. match self {
  463. FlowCellExperiment::WGSPod5Mux(_) => "WGS Pod5 Muxed",
  464. FlowCellExperiment::WGSPod5Demux(_) => "WGS Pod5 Demuxed",
  465. }
  466. )
  467. }
  468. }
  469. impl FlowCellExperiment {
  470. /// Attempts to infer the experiment type from the immediate subdirectories of the given path.
  471. ///
  472. /// This is useful when scanning a flowcell directory directly and checking
  473. /// whether it contains a `pod5/` or `pod5_pass/` structure.
  474. ///
  475. /// # Arguments
  476. /// - `flowcell_path`: Path to the root of a flowcell directory.
  477. ///
  478. /// # Returns
  479. /// - `Some(FlowCellExperiment)` if a known subdirectory is found.
  480. /// - `None` if no match is detected.
  481. pub fn from_path(flowcell_path: &str) -> Option<Self> {
  482. for dir in list_directories(flowcell_path).ok().unwrap_or_default() {
  483. if dir == "pod5" {
  484. return Some(FlowCellExperiment::WGSPod5Mux(dir.to_string()));
  485. }
  486. if dir == "pod5_pass" {
  487. return Some(FlowCellExperiment::WGSPod5Demux(dir.to_string()));
  488. }
  489. }
  490. None
  491. }
  492. /// Attempts to infer the experiment type from a list of `.pod5` file paths.
  493. ///
  494. /// This is typically used when files have already been collected and their
  495. /// parent directories can be checked for naming conventions.
  496. ///
  497. /// # Arguments
  498. /// - `all_paths`: Vector of paths (as strings) to `.pod5` files or directories.
  499. ///
  500. /// # Returns
  501. /// - `Some(FlowCellExperiment)` if a known suffix is detected.
  502. /// - `None` if no matching pattern is found.
  503. pub fn from_pod5_paths(all_paths: &Vec<String>) -> Option<Self> {
  504. for path in all_paths {
  505. if path.ends_with("/pod5/") || path.ends_with("/pod5") {
  506. return Some(FlowCellExperiment::WGSPod5Mux(path.to_string()));
  507. }
  508. if path.ends_with("/pod5_pass/") || path.ends_with("/pod5_pass") {
  509. return Some(FlowCellExperiment::WGSPod5Demux(path.to_string()));
  510. }
  511. }
  512. None
  513. }
  514. /// Returns the underlying string (directory path) for the experiment.
  515. ///
  516. /// This is useful when you need access to the directory path used to classify the experiment.
  517. pub fn inner(&self) -> &str {
  518. match self {
  519. FlowCellExperiment::WGSPod5Mux(v) => v,
  520. FlowCellExperiment::WGSPod5Demux(v) => v,
  521. }
  522. }
  523. }
  524. /// Represents the result of scanning a MinKNOW experiment source.
  525. ///
  526. /// This tuple includes:
  527. /// - `MinKnowSampleSheet`: Parsed metadata describing the experiment/sample.
  528. /// - `Vec<(String, u64, DateTime<Utc>)>`: A list of files with:
  529. /// - `String`: file path
  530. /// - `u64`: file size in bytes
  531. /// - `DateTime<Utc>`: last modification time (UTC)
  532. type ExperimentData = (
  533. MinKnowSampleSheet,
  534. Option<Vec<PoreStateEntry>>,
  535. Option<Vec<ThroughputEntry>>,
  536. Vec<(String, u64, DateTime<Utc>)>,
  537. );
  538. /// Scans a local directory for MinKNOW experiment files and metadata.
  539. ///
  540. /// This function recursively walks a directory using globbing,
  541. /// collects file paths, sizes, and modification timestamps,
  542. /// and identifies a `sample_sheet` file to parse as `MinKnowSampleSheet`.
  543. ///
  544. /// # Arguments
  545. /// - `dir`: Root directory to scan (absolute or relative).
  546. ///
  547. /// # Returns
  548. /// - `Ok(ExperimentData)` containing the sample sheet and a list of file records.
  549. /// - `Err` if the directory can't be accessed, no sample sheet is found, or parsing fails.
  550. ///
  551. /// # Requirements
  552. /// - A file path containing `"sample_sheet"` must be present and readable.
  553. /// - The sample sheet must be formatted according to MinKNOW expectations
  554. /// (1 header + 1 data row).
  555. ///
  556. /// # Errors
  557. /// - If reading files or metadata fails.
  558. /// - If the sample sheet is missing or invalid.
  559. ///
  560. /// # Example
  561. /// ```
  562. /// let (sheet, files) = scan_local("/data/run001")?;
  563. /// println!("Kit used: {}", sheet.kit);
  564. /// println!("Number of files found: {}", files.len());
  565. /// ```
  566. pub fn scan_local(dir: &str) -> anyhow::Result<ExperimentData> {
  567. let mut result = Vec::new();
  568. let mut sample_sheet: Option<String> = None;
  569. let mut pore_activity = None;
  570. let mut throughput = None;
  571. for entry in glob(&format!("{}/**/*", dir))? {
  572. let file = entry.context("Failed to read an entry from the tar archive")?;
  573. // Extract file properties safely
  574. let metadata = file.metadata().context(format!(
  575. "Failed to access file metadata: {}",
  576. file.display()
  577. ))?;
  578. let size = metadata.size();
  579. let modified = metadata.mtime();
  580. let modified_utc: DateTime<Utc> = Utc.timestamp_opt(modified as i64, 0).unwrap();
  581. let path = file.to_string_lossy().into_owned();
  582. if path.contains("pore_activity") {
  583. let mut reader =
  584. File::open(&file).with_context(|| format!("Failed to open: {}", file.display()))?;
  585. pore_activity = Some(
  586. parse_pore_activity_from_reader(&mut reader)
  587. .map(|d| d.group_by_state_and_time(60.0))
  588. .with_context(|| {
  589. format!(
  590. "Failed to parse pore activity date from: {}",
  591. file.display()
  592. )
  593. })?,
  594. );
  595. } else if path.contains("sample_sheet") {
  596. sample_sheet = Some(path.clone());
  597. } else if path.contains("throughput") {
  598. let mut reader =
  599. File::open(&file).with_context(|| format!("Failed to open: {}", file.display()))?;
  600. throughput = Some(
  601. parse_throughput_from_reader(&mut reader)
  602. .with_context(|| {
  603. format!("Failed to parse throughput data from: {}", file.display())
  604. })?
  605. .into_iter()
  606. .enumerate()
  607. .filter_map(|(i, item)| if i % 60 == 0 { Some(item) } else { None })
  608. .collect(),
  609. );
  610. }
  611. result.push((path, size, modified_utc));
  612. }
  613. let sample_sheet = sample_sheet.ok_or(anyhow::anyhow!("No sample sheet detected in: {dir}"))?;
  614. let sample_sheet = MinKnowSampleSheet::from_path(&sample_sheet)
  615. .context(anyhow::anyhow!("Can't parse sample sheet data"))?;
  616. // info!("{} files found in {}", result.len(), dir);
  617. Ok((sample_sheet, pore_activity, throughput, result))
  618. }
  619. /// Scans a `.tar` archive containing a MinKNOW sequencing experiment.
  620. ///
  621. /// This function opens a TAR archive, searches for the `sample_sheet` CSV file,
  622. /// extracts its metadata, and parses it into a `MinKnowSampleSheet`.
  623. /// All other entries in the archive are collected with their path, size, and modification time.
  624. ///
  625. /// # Arguments
  626. /// - `tar_path`: Path to the `.tar` archive file.
  627. ///
  628. /// # Returns
  629. /// - `Ok(ExperimentData)`: A tuple containing the parsed sample sheet and the list of file metadata.
  630. /// - `Err`: If the archive is unreadable, malformed, or missing the `sample_sheet`.
  631. ///
  632. /// # Archive Requirements
  633. /// - Must contain exactly one file matching `"sample_sheet"` in its path.
  634. /// - The sample sheet must contain a valid CSV header and a single data row.
  635. ///
  636. /// # Errors
  637. /// - Fails if the archive can't be opened or read.
  638. /// - Fails if any entry is malformed (e.g., missing timestamp).
  639. /// - Fails if no sample sheet is found or if it is malformed.
  640. ///
  641. /// # Example
  642. /// ```no_run
  643. /// let (sample_sheet, files) = scan_archive("archive.tar")?;
  644. /// println!("Sample ID: {}", sample_sheet.sample_id);
  645. /// println!("Total files in archive: {}", files.len());
  646. /// ```
  647. pub fn scan_archive(tar_path: &str) -> anyhow::Result<ExperimentData> {
  648. info!("Scanning archive: {tar_path}");
  649. let file = File::open(tar_path)
  650. .with_context(|| format!("Failed to open tar file at path: {}", tar_path))?;
  651. let mut archive = tar::Archive::new(file);
  652. let mut result = Vec::new();
  653. let mut sample_sheet: Option<String> = None;
  654. let mut throughput = None;
  655. let mut pore_activity = None;
  656. // Iterate through the entries in the archive
  657. for entry in archive.entries_with_seek()? {
  658. let mut file = entry.context("Failed to read an entry from the tar archive")?;
  659. // Extract file properties safely
  660. let size = file.size();
  661. let modified = file
  662. .header()
  663. .mtime()
  664. .context("Failed to get modification time")?;
  665. let modified_utc: DateTime<Utc> = Utc.timestamp_opt(modified as i64, 0).unwrap();
  666. let path = file
  667. .path()
  668. .context("Failed to get file path from tar entry")?
  669. .to_string_lossy()
  670. .into_owned();
  671. if path.contains("pore_activity") {
  672. pore_activity = Some(
  673. parse_pore_activity_from_reader(&mut file)
  674. .context("Failed to read pore_activity data: {path}")?,
  675. );
  676. } else if path.contains("sample_sheet") {
  677. let mut buffer = String::new();
  678. file.read_to_string(&mut buffer)
  679. .context("Failed to read file contents as string")?;
  680. sample_sheet = Some(buffer);
  681. } else if path.contains("throughput") {
  682. throughput = Some(
  683. parse_throughput_from_reader(&mut file)
  684. .context("Failed to read throughput data: {path}")?,
  685. );
  686. }
  687. result.push((path, size, modified_utc));
  688. }
  689. let sample_sheet = sample_sheet.ok_or(anyhow::anyhow!(
  690. "No sample sheet detected in archive: {tar_path}"
  691. ))?;
  692. let (_, data) = sample_sheet
  693. .split_once("\n")
  694. .ok_or(anyhow::anyhow!("Can't parse sample sheet data"))?;
  695. let sample_sheet: MinKnowSampleSheet = data
  696. .try_into()
  697. .map_err(|e| anyhow::anyhow!("Can't parse sample sheet.\n{e}"))?;
  698. Ok((sample_sheet, pore_activity, throughput, result))
  699. }