Skip to main content

rustdf/data/
dia.rs

1use std::sync::Arc;
2use crate::data::acquisition::AcquisitionMode;
3use rustc_hash::FxHashMap;
4use crate::data::handle::{IndexConverter, TimsData, TimsDataLoader};
5use crate::data::meta::{
6    read_dia_ms_ms_info, read_dia_ms_ms_windows, read_global_meta_sql, read_meta_data_sql,
7    DiaMsMisInfo, DiaMsMsWindow, FrameMeta, GlobalMetaData,
8};
9use mscore::data::spectrum::MsType;
10use mscore::timstof::frame::{RawTimsFrame, TimsFrame};
11use mscore::timstof::slice::TimsSlice;
12use rayon::iter::IntoParallelRefIterator;
13use crate::cluster::peak::{build_frame_bin_view, build_tof_rt_grid_full, expand_many_im_peaks_along_rt, FrameBinView, ImPeak1D, RtExpandParams, RtFrames, TofRtGrid};
14use crate::cluster::utility::{TofScale};
15use crate::data::utility::merge_ranges;
16use rayon::prelude::*;
17use std::collections::{HashMap};
18use rayon::ThreadPoolBuilder;
19use crate::cluster::candidates::{build_pseudo_spectra_all_pairs, build_pseudo_spectra_end_to_end, build_pseudo_spectra_end_to_end_xic, PseudoBuildResult, ScoreOpts};
20use crate::cluster::cluster::{attach_raw_points_for_spec_1d_in_ctx, bin_range_for_win, build_scan_slices, decorate_with_mz_for_cluster, evaluate_spec_1d, make_specs_from_im_and_rt_groups_threads, BuildSpecOpts, ClusterResult1D, ClusterSpec1D, Eval1DOpts, RawAttachContext, RawPoints, ScanSlice};
21use crate::cluster::feature::SimpleFeature;
22use crate::cluster::pseudo::{PseudoSpecOpts};
23use crate::cluster::candidates::CandidateOpts;
24use crate::cluster::scoring::XicScoreOpts;
25
26// ==========================================================
27// Options structs for reducing parameter explosion (Phase 5)
28// ==========================================================
29
30/// Options for cluster extraction from IM peaks.
31#[derive(Clone, Debug)]
32pub struct ClusterExtractionOpts {
33    /// TOF step for grid binning (typically 1, 2, 4, 8).
34    pub tof_step: i32,
35    /// RT expansion parameters.
36    pub rt_params: RtExpandParams,
37    /// Spec building options (window padding, ms_level).
38    pub build_opts: BuildSpecOpts,
39    /// Evaluation options (refine, attach axes/traces).
40    pub eval_opts: Eval1DOpts,
41    /// Whether to require RT overlap for spec generation.
42    pub require_rt_overlap: bool,
43    /// Number of threads for parallel processing.
44    pub num_threads: usize,
45}
46
47impl Default for ClusterExtractionOpts {
48    fn default() -> Self {
49        Self {
50            tof_step: 8,
51            rt_params: RtExpandParams::default(),
52            build_opts: BuildSpecOpts::ms1_defaults(),
53            eval_opts: Eval1DOpts::default(),
54            require_rt_overlap: true,
55            num_threads: 4,
56        }
57    }
58}
59
60impl ClusterExtractionOpts {
61    /// Create options for MS1 (precursor) extraction.
62    pub fn for_ms1() -> Self {
63        Self {
64            build_opts: BuildSpecOpts::ms1_defaults(),
65            ..Self::default()
66        }
67    }
68
69    /// Create options for MS2 (fragment) extraction.
70    pub fn for_ms2() -> Self {
71        Self {
72            build_opts: BuildSpecOpts::ms2_defaults(),
73            ..Self::default()
74        }
75    }
76
77    /// Set the TOF step.
78    pub fn with_tof_step(mut self, step: i32) -> Self {
79        self.tof_step = step;
80        self
81    }
82
83    /// Set the number of threads.
84    pub fn with_threads(mut self, n: usize) -> Self {
85        self.num_threads = n;
86        self
87    }
88}
89
90/// Options for building pseudo spectra from clusters.
91#[derive(Clone, Debug)]
92pub struct PseudoSpectrumBuildOpts<'a> {
93    /// Candidate enumeration options.
94    pub cand_opts: &'a CandidateOpts,
95    /// Geometric scoring options.
96    pub score_opts: &'a ScoreOpts,
97    /// Pseudo spectrum construction options.
98    pub pseudo_opts: &'a PseudoSpecOpts,
99    /// Optional features for grouping.
100    pub features: Option<&'a [SimpleFeature]>,
101}
102
103#[derive(Clone, Debug)]
104pub struct ProgramSlice {
105    pub mz_lo: f64,
106    pub mz_hi: f64,
107    pub scan_lo: u32,
108    pub scan_hi: u32,
109}
110
111#[inline]
112fn ranges_overlap_u32(a: (u32, u32), b: (u32, u32)) -> bool {
113    let lo = a.0.max(b.0);
114    let hi = a.1.min(b.1);
115    hi >= lo
116}
117
118#[derive(Debug, Clone)]
119pub struct Ms2GroupProgram {
120    /// Raw per-row isolation windows (normalized, ascending, finite)
121    pub mz_windows: Vec<(f32, f32)>,
122    /// Raw per-row active scan ranges (normalized, inclusive)
123    pub scan_ranges: Vec<(u32, u32)>,
124    /// Union (convex hull) over all mz_windows for the group; None if no valid rows
125    pub mz_union: Option<(f32, f32)>,
126    /// Merged disjoint scan ranges (inclusive) over the group; empty = permissive fallback
127    pub scan_unions: Vec<(u32, u32)>,
128}
129
130#[derive(Debug, Clone)]
131pub struct DiaIndex {
132    /// MS2 frame_id -> window_group
133    pub frame_to_group: HashMap<u32, u32>,
134    /// window_group -> MS2 frame_ids (sorted by **time**)
135    pub group_to_frames: HashMap<u32, Vec<u32>>,
136    /// window_group -> list of (mz_lo, mz_hi) isolation ranges (normalized)
137    pub group_to_isolation: HashMap<u32, Vec<(f64, f64)>>,
138    /// window_group -> list of (scan_lo, scan_hi) active scan ranges (normalized, inclusive)
139    pub group_to_scan_ranges: HashMap<u32, Vec<(u32, u32)>>,
140    /// window_group -> convex m/z union (lo, hi)
141    pub group_to_mz_union: HashMap<u32, (f64, f64)>,
142    /// window_group -> merged disjoint scan unions (inclusive)
143    pub group_to_scan_unions: HashMap<u32, Vec<(u32, u32)>>,
144    /// frame_id -> time (seconds)
145    pub frame_time: HashMap<u32, f64>,
146    /// New: pre-materialized program slices per group.
147    pub group_to_slices: HashMap<u32, Arc<[ProgramSlice]>>,
148}
149
150impl DiaIndex {
151    pub fn new(meta: &[FrameMeta], info: &[DiaMsMisInfo], wins: &[DiaMsMsWindow]) -> Self {
152        // helpers
153        #[inline]
154        fn norm_f64_pair(a: f64, b: f64) -> Option<(f64, f64)> {
155            if !a.is_finite() || !b.is_finite() { return None; }
156            let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
157            if hi > lo { Some((lo, hi)) } else { None }
158        }
159        #[inline]
160        fn norm_u32_pair(a: u32, b: u32) -> Option<(u32, u32)> {
161            let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
162            Some((lo, hi))
163        }
164        fn merge_scan_ranges(mut ranges: Vec<(u32, u32)>) -> Vec<(u32, u32)> {
165            if ranges.is_empty() { return ranges; }
166            ranges.sort_unstable_by_key(|&(l, r)| (l, r));
167            let mut out: Vec<(u32,u32)> = Vec::with_capacity(ranges.len());
168            let mut cur = ranges[0];
169            for &(l, r) in &ranges[1..] {
170                if l <= cur.1.saturating_add(1) {
171                    if r > cur.1 { cur.1 = r; }
172                } else {
173                    out.push(cur);
174                    cur = (l, r);
175                }
176            }
177            out.push(cur);
178            out
179        }
180
181        // frame_id -> time
182        let mut frame_time: HashMap<u32, f64> = HashMap::new();
183        for m in meta {
184            frame_time.insert(m.id as u32, m.time);
185        }
186
187        // frame_id -> group; group -> frames
188        let mut frame_to_group: HashMap<u32, u32> = HashMap::new();
189        let mut group_to_frames: HashMap<u32, Vec<u32>> = HashMap::new();
190        for r in info {
191            let fid = r.frame_id;
192            frame_to_group.insert(fid, r.window_group);
193            group_to_frames.entry(r.window_group).or_default().push(fid);
194        }
195
196        // raw program rows
197        let mut group_to_isolation: HashMap<u32, Vec<(f64, f64)>> = HashMap::new();
198        let mut group_to_scan_ranges: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();
199        for w in wins {
200            let half = 0.5 * w.isolation_width;
201            if half.is_finite() && half > 0.0 && w.isolation_mz.is_finite() {
202                let lo = w.isolation_mz - half;
203                let hi = w.isolation_mz + half;
204                if let Some(p) = norm_f64_pair(lo, hi) {
205                    group_to_isolation.entry(w.window_group).or_default().push(p);
206                }
207            }
208            if let Some(p) = norm_u32_pair(w.scan_num_begin, w.scan_num_end) {
209                group_to_scan_ranges.entry(w.window_group).or_default().push(p);
210            }
211        }
212
213        // unions + sort frames by time
214        let mut group_to_mz_union: HashMap<u32, (f64, f64)> = HashMap::new();
215        let mut group_to_scan_unions: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();
216
217        for (g, frames) in group_to_frames.iter_mut() {
218            frames.sort_unstable_by(|&a, &b| {
219                let ta = frame_time.get(&a).copied().unwrap_or(f64::NAN);
220                let tb = frame_time.get(&b).copied().unwrap_or(f64::NAN);
221                ta.partial_cmp(&tb).unwrap_or(std::cmp::Ordering::Equal)
222            });
223
224            if let Some(v) = group_to_isolation.get(g) {
225                if !v.is_empty() {
226                    let lo = v.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
227                    let hi = v.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
228                    if lo.is_finite() && hi.is_finite() && hi > lo {
229                        group_to_mz_union.insert(*g, (lo, hi));
230                    }
231                }
232            }
233            let merged = merge_scan_ranges(group_to_scan_ranges.get(g).cloned().unwrap_or_default());
234            group_to_scan_unions.insert(*g, merged);
235        }
236
237        let mut group_to_slices: HashMap<u32, Arc<[ProgramSlice]>> = HashMap::new();
238
239        for (&g, iso_rows) in &group_to_isolation {
240            let scan_rows = group_to_scan_ranges.get(&g).cloned().unwrap_or_default();
241            let n = iso_rows.len().min(scan_rows.len());
242            let mut v = Vec::with_capacity(n);
243            for k in 0..n {
244                let (mz_lo, mz_hi)     = iso_rows[k];
245                let (scan_lo, scan_hi) = scan_rows[k];
246                v.push(ProgramSlice { mz_lo, mz_hi, scan_lo, scan_hi });
247            }
248            group_to_slices.insert(g, v.into());
249        }
250
251        DiaIndex {
252            frame_to_group,
253            group_to_frames,
254            group_to_isolation,
255            group_to_scan_ranges,
256            group_to_mz_union,
257            group_to_scan_unions,
258            frame_time,
259            group_to_slices,
260        }
261    }
262
263    pub fn program_slices_for_group(&self, g: u32) -> Vec<ProgramSlice> {
264        self.slices_for_group(g).to_vec()
265    }
266
267    /// Tiles in group `g` that could have selected this precursor.
268    ///
269    /// Conditions:
270    ///   1) Precursor IM window overlaps tile scan band.
271    ///   2) Precursor m/z lies inside tile's isolation m/z window.
272    /// Tiles in group `g` that could have selected this precursor.
273    ///
274    /// Conditions:
275    ///   1) Precursor **apex** IM scan lies inside tile scan band.
276    ///   2) Precursor m/z lies inside tile's isolation m/z window.
277    pub fn tiles_for_precursor_in_group(
278        &self,
279        g: u32,
280        prec_mz: f32,
281        im_apex: f32,
282    ) -> Vec<usize> {
283        let slices = self.slices_for_group(g);
284        let mut hits = Vec::new();
285
286        if !prec_mz.is_finite() || !im_apex.is_finite() {
287            return hits;
288        }
289
290        for (idx, s) in slices.iter().enumerate() {
291            // Precursor m/z inside isolation window
292            if prec_mz < s.mz_lo as f32 || prec_mz > s.mz_hi as f32 {
293                continue;
294            }
295
296            // Apex inside scan band (no margin for now, same semantics as your debug plot)
297            let scan_lo = s.scan_lo as f32;
298            let scan_hi = s.scan_hi as f32;
299            if im_apex < scan_lo || im_apex > scan_hi {
300                continue;
301            }
302
303            hits.push(idx);
304        }
305
306        hits
307    }
308
309    /// Tiles in group `g` that an MS2 fragment cluster could belong to.
310    ///
311    /// IMPORTANT:
312    ///   Fragment m/z is *not* constrained by isolation window (selection
313    ///   happened before fragmentation). We only check the IM/scan range.
314    pub fn tiles_for_fragment_in_group(
315        &self,
316        g: u32,
317        im_window: (usize, usize),
318    ) -> Vec<usize> {
319        let slices = self.program_slices_for_group(g);
320        let mut hits = Vec::new();
321
322        for (idx, s) in slices.iter().enumerate() {
323            let tile_scans = (s.scan_lo, s.scan_hi);
324
325            if ranges_overlap_u32(
326                (im_window.0 as u32, im_window.1 as u32),
327                tile_scans,
328            ) {
329                hits.push(idx);
330            }
331        }
332
333        hits
334    }
335
336    /// Convenience: materialize a program description for a group.
337    pub fn program_for_group(&self, g: u32) -> Ms2GroupProgram {
338        let mz_windows = self.group_to_isolation
339            .get(&g)
340            .map(|v| v.iter().map(|&(a,b)| (a as f32, b as f32)).collect())
341            .unwrap_or_else(Vec::new);
342
343        let scan_ranges = self.group_to_scan_ranges
344            .get(&g)
345            .cloned()
346            .unwrap_or_else(Vec::new);
347
348        let mz_union = self.group_to_mz_union
349            .get(&g)
350            .map(|&(a,b)| (a as f32, b as f32));
351
352        let scan_unions = self.group_to_scan_unions
353            .get(&g)
354            .cloned()
355            .unwrap_or_else(Vec::new);
356
357        Ms2GroupProgram { mz_windows, scan_ranges, mz_union, scan_unions }
358    }
359
360    pub fn groups_for_precursor(
361        &self,
362        prec_mz: f32,
363        im_apex: f32,
364    ) -> Vec<u32> {
365        if !prec_mz.is_finite() || !im_apex.is_finite() {
366            return Vec::new();
367        }
368
369        let mut out = Vec::new();
370        for (&g, &(mz_lo, mz_hi)) in &self.group_to_mz_union {
371            if prec_mz < mz_lo as f32 || prec_mz > mz_hi as f32 {
372                continue;
373            }
374
375            // optionally also check scan_unions
376            if let Some(unions) = self.group_to_scan_unions.get(&g) {
377
378                if !unions.iter().any(|&(lo, hi)| {
379                    (im_apex as u32) >= lo && (im_apex as u32) <= hi
380                }) {
381                    continue;
382                }
383            }
384
385            let tiles = self.tiles_for_precursor_in_group(g, prec_mz, im_apex);
386            if !tiles.is_empty() {
387                out.push(g);
388            }
389        }
390        out
391    }
392
393    /// Return the m/z isolation bounds (lo, hi) for a given tile index in a group.
394    ///
395    /// If the tile index is out of range for this group, returns (NaN, NaN).
396    /// This is used by the fragment query to decide whether a fragment's m/z
397    /// lies **inside** the precursor-selection band of the shared tile.
398    pub fn tile_mz_bounds(&self, g: u32, tile_idx: usize) -> (f32, f32) {
399        let slices = self.slices_for_group(g);
400        if tile_idx >= slices.len() {
401            return (f32::NAN, f32::NAN);
402        }
403        let s = &slices[tile_idx];
404        (s.mz_lo as f32, s.mz_hi as f32)
405    }
406
407    #[inline]
408    pub fn mz_bounds_for_window_group_core(&self, g: u32) -> Option<(f32, f32)> {
409        self.group_to_mz_union.get(&g).map(|&(a,b)| (a as f32, b as f32))
410    }
411    #[inline]
412    pub fn scan_unions_for_window_group_core(&self, g: u32) -> Option<Vec<(usize, usize)>> {
413        self.group_to_scan_unions.get(&g).map(|v| v.iter().map(|&(l,r)| (l as usize, r as usize)).collect())
414    }
415
416    fn slices_for_group(&self, g: u32) -> &[ProgramSlice] {
417        self.group_to_slices.get(&g).map(|a| &a[..]).unwrap_or(&[])
418    }
419
420}
421
422pub struct TimsDatasetDIA {
423    pub loader: TimsDataLoader,
424    pub global_meta_data: GlobalMetaData,
425    pub meta_data: Vec<FrameMeta>,
426    pub dia_ms_ms_info: Vec<DiaMsMisInfo>,
427    pub dia_ms_ms_windows: Vec<DiaMsMsWindow>,
428    pub dia_index: DiaIndex,
429}
430
431impl TimsDatasetDIA {
432    pub fn new(
433        bruker_lib_path: &str,
434        data_path: &str,
435        in_memory: bool,
436        use_bruker_sdk: bool,
437    ) -> Self {
438        // TODO: error handling
439        let global_meta_data = read_global_meta_sql(data_path).unwrap();
440        let meta_data = read_meta_data_sql(data_path).unwrap();
441        let dia_ms_mis_info = read_dia_ms_ms_info(data_path).unwrap();
442        let dia_ms_ms_windows = read_dia_ms_ms_windows(data_path).unwrap();
443
444        let scan_max_index = meta_data.iter().map(|x| x.num_scans).max().unwrap() as u32;
445        let im_lower = global_meta_data.one_over_k0_range_lower;
446        let im_upper = global_meta_data.one_over_k0_range_upper;
447
448        let tof_max_index = global_meta_data.tof_max_index;
449        let mz_lower = global_meta_data.mz_acquisition_range_lower;
450        let mz_upper = global_meta_data.mz_acquisition_range_upper;
451
452        let loader = match in_memory {
453            true => TimsDataLoader::new_in_memory(
454                bruker_lib_path,
455                data_path,
456                use_bruker_sdk,
457                scan_max_index,
458                im_lower,
459                im_upper,
460                tof_max_index,
461                mz_lower,
462                mz_upper,
463            ),
464            false => TimsDataLoader::new_lazy(
465                bruker_lib_path,
466                data_path,
467                use_bruker_sdk,
468                scan_max_index,
469                im_lower,
470                im_upper,
471                tof_max_index,
472                mz_lower,
473                mz_upper,
474            ),
475        };
476
477        let dia_index = DiaIndex::new(&meta_data, &dia_ms_mis_info, &dia_ms_ms_windows);
478
479        TimsDatasetDIA {
480            loader,
481            global_meta_data,
482            meta_data,
483            dia_ms_ms_info: dia_ms_mis_info,
484            dia_ms_ms_windows,
485            dia_index,
486        }
487    }
488
489    /// Create a DIA dataset using the exact SDK-free Bruker calibration formulas.
490    ///
491    /// See [`crate::data::calibration`]: reads the `MzCalibration` /
492    /// `TimsCalibration` tables and needs no Bruker SDK at build or runtime.
493    /// 1/K0 is machine-exact; m/z is bit-exact for MzCalibration ModelType 1 and
494    /// accurate to a few ppm for ModelType 2.
495    pub fn new_with_bruker_formula(
496        data_path: &str,
497        in_memory: bool,
498        calibration_frame_id: u32,
499    ) -> Self {
500        let meta_data = read_meta_data_sql(data_path).unwrap();
501        let global_meta_data = read_global_meta_sql(data_path).unwrap();
502        let dia_ms_mis_info = read_dia_ms_ms_info(data_path).unwrap();
503        let dia_ms_ms_windows = read_dia_ms_ms_windows(data_path).unwrap();
504
505        let loader = match in_memory {
506            true => TimsDataLoader::new_in_memory_with_bruker_formula(
507                data_path,
508                calibration_frame_id,
509            ),
510            false => {
511                TimsDataLoader::new_lazy_with_bruker_formula(data_path, calibration_frame_id)
512            }
513        };
514
515        let dia_index = DiaIndex::new(&meta_data, &dia_ms_mis_info, &dia_ms_ms_windows);
516
517        TimsDatasetDIA {
518            loader,
519            global_meta_data,
520            meta_data,
521            dia_ms_ms_info: dia_ms_mis_info,
522            dia_ms_ms_windows,
523            dia_index,
524        }
525    }
526
527    /// Create a DIA dataset with regression-derived m/z calibration.
528    ///
529    /// This method uses externally-provided m/z calibration coefficients (e.g., from
530    /// linear regression on SDK data) instead of the simple boundary model.
531    pub fn new_with_mz_calibration(
532        data_path: &str,
533        in_memory: bool,
534        tof_intercept: f64,
535        tof_slope: f64,
536    ) -> Self {
537        let meta_data = read_meta_data_sql(data_path).unwrap();
538        let global_meta_data = read_global_meta_sql(data_path).unwrap();
539        let dia_ms_mis_info = read_dia_ms_ms_info(data_path).unwrap();
540        let dia_ms_ms_windows = read_dia_ms_ms_windows(data_path).unwrap();
541
542        let scan_max_index = meta_data.iter().map(|x| x.num_scans).max().unwrap() as u32;
543        let im_lower = global_meta_data.one_over_k0_range_lower;
544        let im_upper = global_meta_data.one_over_k0_range_upper;
545
546        let loader = match in_memory {
547            true => TimsDataLoader::new_in_memory_with_mz_calibration(
548                data_path,
549                tof_intercept,
550                tof_slope,
551                im_lower,
552                im_upper,
553                scan_max_index,
554            ),
555            false => TimsDataLoader::new_lazy_with_mz_calibration(
556                data_path,
557                tof_intercept,
558                tof_slope,
559                im_lower,
560                im_upper,
561                scan_max_index,
562            ),
563        };
564
565        let dia_index = DiaIndex::new(&meta_data, &dia_ms_mis_info, &dia_ms_ms_windows);
566
567        TimsDatasetDIA {
568            loader,
569            global_meta_data,
570            meta_data,
571            dia_ms_ms_info: dia_ms_mis_info,
572            dia_ms_ms_windows,
573            dia_index,
574        }
575    }
576
577    pub fn program_for_group(&self, g: u32) -> Ms2GroupProgram {
578        self.dia_index.program_for_group(g)
579    }
580
581    /// Collect all program slices for a window group from DiaFrameMsMsWindows.
582    /// Isolation window: [isolation_mz - width/2, isolation_mz + width/2]
583    pub fn program_slices_for_group(&self, group: u32) -> Vec<ProgramSlice> {
584        self.dia_ms_ms_windows
585            .iter()
586            .filter(|w| w.window_group == group)
587            .map(|w| {
588                let half = 0.5 * w.isolation_width;
589                ProgramSlice {
590                    mz_lo: w.isolation_mz - half,
591                    mz_hi: w.isolation_mz + half,
592                    scan_lo: w.scan_num_begin,
593                    scan_hi: w.scan_num_end,
594                }
595            })
596            .collect()
597    }
598
599    /// Sample MS1 noise from `num_frames` random precursor frames in the
600    /// reference dataset, sum them into one combined TimsFrame, and stamp
601    /// the result's `ms_type` as `MsType::Precursor` so downstream
602    /// `simulated + noise` adds don't collapse the simulated frame's type
603    /// to `MsType::Unknown`.
604    ///
605    /// Empty-fallback handling
606    /// -----------------------
607    /// `loader.get_frame()` returns `TimsFrame::default()` (which is
608    /// `frame_id=0, ms_type=MsType::Unknown`) when the requested raw
609    /// frame has no scan data. If one of those Default-shaped frames is
610    /// the first element fed into the inner accumulator, every subsequent
611    /// `sampled_frame + frame` retains `frame_id=0, ms_type=Unknown` via
612    /// `TimsFrame::Add`'s correct "LHS frame_id wins; mismatched ms_type
613    /// → Unknown" semantics. That corrupted noise then leaks through the
614    /// outer simulator add. The fix here:
615    ///   1. Skip empty / Default-shaped candidates before they enter the
616    ///      accumulator (`scan.is_empty()` or `ms_type == Unknown`),
617    ///   2. Use a bounded retry pool so we don't hang on degenerate
618    ///      references (e.g. a near-empty blank gradient),
619    ///   3. Stamp the returned frame's `ms_type` explicitly — purely
620    ///      defensive, documents the post-condition.
621    pub fn sample_precursor_signal(
622        &self,
623        num_frames: usize,
624        max_intensity: f64,
625        take_probability: f64,
626    ) -> TimsFrame {
627        let target_type = MsType::Precursor;
628        let pool: Vec<&FrameMeta> = self
629            .meta_data
630            .iter()
631            .filter(|x| x.ms_ms_type == 0)
632            .collect();
633        let mut rng = rand::thread_rng();
634        let mut sampled_frames: Vec<TimsFrame> =
635            self.collect_typed_noise_samples(&pool, num_frames, max_intensity,
636                                             take_probability, &mut rng,
637                                             |meta| meta.id as u32);
638        Self::accumulate_or_typed_empty(&mut sampled_frames, target_type)
639    }
640
641    /// Sample MS2 noise restricted to a window_group from the reference
642    /// dataset. See `sample_precursor_signal` for the leak diagnosis and
643    /// the design notes; the only difference here is the candidate pool
644    /// (DIA-MS²-info filtered by window_group) and the type stamp
645    /// (`MsType::FragmentDia`).
646    pub fn sample_fragment_signal(
647        &self,
648        num_frames: usize,
649        window_group: u32,
650        max_intensity: f64,
651        take_probability: f64,
652    ) -> TimsFrame {
653        let target_type = MsType::FragmentDia;
654        let pool: Vec<u32> = self
655            .dia_ms_ms_info
656            .iter()
657            .filter(|x| x.window_group == window_group)
658            .map(|x| x.frame_id)
659            .collect();
660        let mut rng = rand::thread_rng();
661        let mut sampled_frames: Vec<TimsFrame> =
662            self.collect_typed_noise_samples(&pool, num_frames, max_intensity,
663                                             take_probability, &mut rng,
664                                             |&fid| fid);
665        Self::accumulate_or_typed_empty(&mut sampled_frames, target_type)
666    }
667
668    /// Internal: pull up to `num_frames` non-empty TimsFrames from `pool`
669    /// via the loader, with bounded retry to skip empty raws.
670    /// `key_fn` lifts a pool element to a frame_id.
671    fn collect_typed_noise_samples<T>(
672        &self,
673        pool: &[T],
674        num_frames: usize,
675        max_intensity: f64,
676        take_probability: f64,
677        rng: &mut impl rand::Rng,
678        key_fn: impl Fn(&T) -> u32,
679    ) -> Vec<TimsFrame> {
680        let mut out: Vec<TimsFrame> = Vec::with_capacity(num_frames);
681        if pool.is_empty() || num_frames == 0 {
682            return out;
683        }
684        let max_attempts = (num_frames * 8).max(16);
685        let mut attempts = 0usize;
686        use rand::seq::SliceRandom;
687        while out.len() < num_frames && attempts < max_attempts {
688            attempts += 1;
689            let Some(candidate_meta) = pool.choose(rng) else { break };
690            let candidate = self
691                .loader
692                .get_frame(key_fn(candidate_meta))
693                .filter_ranged(0.0, 2000.0, 0, 1000, 0.0, 5.0, 1.0,
694                               max_intensity, 0, i32::MAX)
695                .generate_random_sample(take_probability);
696            // Skip the loader's empty-frame Default-fallback so the
697            // returned noise never carries MsType::Unknown into the
698            // outer simulator add.
699            if candidate.scan.is_empty() || candidate.ms_type == MsType::Unknown {
700                continue;
701            }
702            out.push(candidate);
703        }
704        out
705    }
706
707    /// Internal: fold a Vec of typed noise samples into one via Add, and
708    /// return a *typed* empty TimsFrame if the input was empty so callers
709    /// don't get Default::default()'s Unknown back.
710    fn accumulate_or_typed_empty(
711        samples: &mut Vec<TimsFrame>,
712        target_type: MsType,
713    ) -> TimsFrame {
714        if samples.is_empty() {
715            return TimsFrame::new(
716                0, target_type, 0.0,
717                vec![], vec![], vec![], vec![], vec![],
718            );
719        }
720        let mut acc = samples.remove(0);
721        for f in samples.drain(..) {
722            acc = acc + f;
723        }
724        // Belt-and-braces: if the inner Add chain somehow collapsed to
725        // Unknown despite the input filter, restore the type the caller
726        // explicitly asked for.
727        acc.ms_type = target_type;
728        acc
729    }
730
731    /// All DIA window_group IDs present in the file (sorted unique).
732    pub fn dia_window_groups(&self) -> Vec<u32> {
733        let mut gs: Vec<u32> = self
734            .dia_ms_ms_info
735            .iter()
736            .map(|x| x.window_group)
737            .collect();
738        gs.sort_unstable();
739        gs.dedup();
740        gs
741    }
742
743    pub fn window_groups_for_precursor(&self, prec_mz: f32, im_apex: f32) -> Vec<u32> {
744        self.dia_index.groups_for_precursor(prec_mz, im_apex)
745    }
746
747    /// Map frame_id -> (time, ms_ms_type) for quick lookups.
748    fn frame_time_map(&self) -> FxHashMap<u32, (f32, i64)> {
749        let mut m = FxHashMap::default();
750        for fm in &self.meta_data {
751            m.insert(fm.id as u32, (fm.time as f32, fm.ms_ms_type));
752        }
753        m
754    }
755
756    /// RT-sorted **fragment** frames for a given DIA group.
757    pub fn fragment_frame_ids_and_times_for_group_core(&self, window_group: u32) -> (Vec<u32>, Vec<f32>) {
758        let time_map = self.frame_time_map();
759        let mut rows: Vec<(u32, f32)> = self
760            .dia_ms_ms_info
761            .iter()
762            .filter(|x| x.window_group == window_group)
763            .filter_map(|x| {
764                time_map.get(&(x.frame_id)).map(|(t, _ms2)| (x.frame_id, *t))
765            })
766            .collect();
767
768        // Just in case: keep only MS2 frames (ms_ms_type != 0)
769        rows.retain(|(fid, _)| time_map.get(fid).map(|(_, ty)| *ty != 0).unwrap_or(false));
770
771        rows.sort_by(|a,b| a.1.partial_cmp(&b.1).unwrap());
772        let (ids, times): (Vec<_>, Vec<_>) = rows.into_iter().unzip();
773        (ids, times)
774    }
775
776    /// Merged, sorted **global scan** unions for this DIA group, from DiaFrameMsMsWindows.
777    /// Returns None if there are no window rows for this group.
778    pub fn scan_unions_for_window_group_core(&self, window_group: u32) -> Option<Vec<(usize, usize)>> {
779        let ranges: Vec<(usize, usize)> = self
780            .dia_ms_ms_windows
781            .iter()
782            .filter(|w| w.window_group == window_group)
783            .map(|w| {
784                let l = w.scan_num_begin as usize;
785                let r = w.scan_num_end as usize;
786                if l <= r { (l, r) } else { (r, l) }
787            })
788            .collect();
789        if ranges.is_empty() {
790            return None;
791        }
792        Some(merge_ranges(ranges))
793    }
794
795    /// m/z unions (min..max) for the group from DiaFrameMsMsWindows (wide clamp).
796    pub fn mz_bounds_for_window_group_core(&self, window_group: u32) -> Option<(f32, f32)> {
797        let mut lo = f32::INFINITY;
798        let mut hi = f32::NEG_INFINITY;
799        let mut hit = false;
800        for w in &self.dia_ms_ms_windows {
801            if w.window_group == window_group {
802                let c = w.isolation_mz as f32;
803                let half = 0.5f32 * (w.isolation_width as f32);
804                lo = lo.min(c - half);
805                hi = hi.max(c + half);
806                hit = true;
807            }
808        }
809        if hit && hi > lo && lo.is_finite() && hi.is_finite() {
810            Some((lo, hi))
811        } else {
812            None
813        }
814    }
815
816    /// RT-sorted FRAGMENT frames + times for a DIA group, converted into FrameBinView rows.
817    /// `tof_step` controls TOF granularity of CSR binning.
818    pub fn make_rt_frames_for_group(&self, window_group: u32, tof_step: i32) -> RtFrames {
819        assert!(tof_step > 0);
820
821        let (ids, times) = self.fragment_frame_ids_and_times_for_group_core(window_group);
822        assert!(
823            !ids.is_empty(),
824            "No MS2 frames for window_group {}",
825            window_group
826        );
827
828        let global_num_scans = self.meta_data
829            .iter()
830            .filter(|m| ids.binary_search(&(m.id as u32)).is_ok())
831            .map(|m| m.num_scans as usize)
832            .max()
833            .unwrap_or(0);
834
835        // TOF scale for this group
836        let scale = self.tof_scale_for_group(window_group, tof_step);
837
838        let frames: Vec<FrameBinView> = ids.par_iter()
839            .map(|&fid| build_frame_bin_view(self.get_frame(fid), &scale, global_num_scans))
840            .collect();
841
842        RtFrames {
843            frames,
844            frame_ids: ids,
845            rt_times: times,
846            scale: Arc::new(scale),
847        }
848    }
849
850    /// RT-sorted PRECURSOR frames (ms_ms_type == 0) into FrameBinView rows.
851    /// `tof_step` controls TOF granularity of CSR binning.
852    pub fn make_rt_frames_for_precursor(&self, tof_step: i32) -> RtFrames {
853        assert!(tof_step > 0);
854
855        let mut rows: Vec<(u32, f32, usize)> = self.meta_data
856            .iter()
857            .filter(|m| m.ms_ms_type == 0)
858            .map(|m| (m.id as u32, m.time as f32, m.num_scans as usize))
859            .collect();
860
861        assert!(!rows.is_empty(), "No precursor (MS1) frames found");
862        rows.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
863
864        let frame_ids: Vec<u32> = rows.iter().map(|r| r.0).collect();
865        let rt_times:  Vec<f32> = rows.iter().map(|r| r.1).collect();
866        let global_num_scans = rows.iter().map(|r| r.2).max().unwrap_or(1);
867
868        // Build TOF scale from precursor frames
869        let frames_for_scale: Vec<_> = frame_ids.iter().map(|&fid| self.get_frame(fid)).collect();
870        let scale = TofScale::build_from_tof(&frames_for_scale, tof_step)
871            .expect("make_rt_frames_for_precursor: failed to build TOF scale");
872
873        let frames: Vec<FrameBinView> = frame_ids.par_iter()
874            .map(|&fid| build_frame_bin_view(self.get_frame(fid), &scale, global_num_scans))
875            .collect();
876
877        RtFrames {
878            frames,
879            frame_ids,
880            rt_times,
881            scale: Arc::new(scale),
882        }
883    }
884
885    /// Build a TOF-based scale for a DIA group.
886    /// `tof_step = 1` → max TOF resolution; larger steps downsample.
887    pub fn tof_scale_for_group(&self, window_group: u32, tof_step: i32) -> TofScale {
888        assert!(tof_step > 0);
889
890        let (ids, _times) = self.fragment_frame_ids_and_times_for_group_core(window_group);
891        assert!(
892            !ids.is_empty(),
893            "tof_scale_for_group: no MS2 frames for window_group {}",
894            window_group
895        );
896
897        let frames: Vec<_> = ids.iter().map(|&fid| self.get_frame(fid)).collect();
898
899        TofScale::build_from_tof(&frames, tof_step)
900            .expect("tof_scale_for_group: failed to build TOF scale (empty or degenerate)")
901    }
902
903    /// Conservative: derive a TOF scale by scanning actual frame data.
904    pub fn tof_scale_from_frames_scan(
905        &self,
906        frame_ids: &[u32],
907        tof_step: i32,
908    ) -> Option<TofScale> {
909        assert!(tof_step > 0);
910        let frames: Vec<_> = frame_ids.iter().map(|&fid| self.get_frame(fid)).collect();
911        TofScale::build_from_tof(&frames, tof_step)
912    }
913
914    /// Internal helper: go from a set of IM peaks to evaluated 1D clusters
915    /// on a given RtFrames grid (precursor or DIA group).
916    fn clusters_for_im_peaks_on_rt_frames(
917        &self,
918        rt: RtFrames,
919        im_peaks: &[ImPeak1D],
920        rt_params: RtExpandParams,
921        build_opts: &BuildSpecOpts,
922        eval_opts: &Eval1DOpts,
923        require_rt_overlap: bool,
924        num_threads: usize,
925    ) -> Vec<ClusterResult1D> {
926        // 1) Expand IM peaks along RT on this grid
927        let rt_groups = expand_many_im_peaks_along_rt(
928            im_peaks,
929            &rt.frames,
930            rt.ctx(),
931            rt.scale.as_ref(),
932            rt_params,
933        );
934
935        // 2) Build 1D specs (RT × IM × TOF-window)
936        let specs: Vec<ClusterSpec1D> = make_specs_from_im_and_rt_groups_threads(
937            im_peaks,
938            &rt_groups,
939            &rt,
940            build_opts,
941            require_rt_overlap,
942            num_threads,
943        );
944
945        // 3) Evaluate all specs on this RtFrames grid
946        self.evaluate_specs_1d_threads(&rt, &specs, eval_opts, num_threads)
947    }
948
949    /// Evaluate a batch of 1D cluster specs on the given RtFrames.
950    /// - Runs spec evaluation (marginals + moment fits) in parallel.
951    /// - Optionally attaches raw points using the finalized **TOF-bin window**
952    ///   and the spec’s IM/RT windows.
953    /// - `num_threads == 0` => use rayon’s global pool.
954    pub fn evaluate_specs_1d_threads(
955        &self,
956        rt_frames: &RtFrames,
957        specs: &[ClusterSpec1D],
958        opts: &Eval1DOpts,
959        num_threads: usize,
960    ) -> Vec<ClusterResult1D> {
961        if specs.is_empty() {
962            return Vec::new();
963        }
964
965        let scale = &*rt_frames.scale;
966
967        let run = || {
968            // Pre-build raw attach context once if needed
969            let attach_ctx = if opts.attach.attach_points {
970                let frame_ids_local = rt_frames.frame_ids.clone();
971                let slice = self.get_slice(frame_ids_local.clone(), num_threads.max(1));
972                let scan_slices = slice
973                    .frames
974                    .iter()
975                    .map(|fr| build_scan_slices(fr))
976                    .collect::<Vec<_>>();
977                let rt_axis_sec = rt_frames.rt_times.clone();
978
979                Some(RawAttachContext {
980                    slice,
981                    scan_slices,
982                    frame_ids_local,
983                    rt_axis_sec,
984                })
985            } else {
986                None
987            };
988
989            specs
990                .par_iter()
991                .map(|spec| {
992                    // 1) core 1D evaluation (RT/IM/TOF fits etc.)
993                    let mut res = evaluate_spec_1d(rt_frames, spec, opts);
994
995                    // 2) decorate with m/z axis + mz_fit/mz_window
996                    //
997                    //    - uses the already-computed TOF window in `spec.tof_win`
998                    //    - does *not* depend on raw_points being attached
999                    //    - keeps the logic local and cheap
1000                    decorate_with_mz_for_cluster(self, rt_frames, &mut res);(self, rt_frames, spec, scale, &mut res);
1001
1002                    // 3) optional raw point attachment (using shared context)
1003                    if let Some(ref ctx) = attach_ctx {
1004                        if opts.attach.attach_points && res.raw_sum > 0.0 && res.tof_fit.area > 0.0 {
1005                            let (bin_lo, bin_hi) = bin_range_for_win(scale, spec.tof_win);
1006                            let (im_lo, im_hi) = (spec.im_lo, spec.im_hi);
1007                            let (rt_lo, rt_hi) = (spec.rt_lo, spec.rt_hi);
1008
1009                            let raw = attach_raw_points_for_spec_1d_in_ctx(
1010                                ctx,
1011                                scale,
1012                                bin_lo,
1013                                bin_hi,
1014                                im_lo,
1015                                im_hi,
1016                                rt_lo,
1017                                rt_hi,
1018                                opts.attach.max_points,
1019                            );
1020                            res.raw_points = Some(raw);
1021                        }
1022                    }
1023
1024                    res
1025                })
1026                .collect::<Vec<_>>()
1027        };
1028
1029        if num_threads == 0 {
1030            run()
1031        } else {
1032            ThreadPoolBuilder::new()
1033                .num_threads(num_threads)
1034                .build()
1035                .unwrap()
1036                .install(run)
1037        }
1038    }
1039
1040    pub fn clusters_for_group(
1041        &self,
1042        window_group: u32,
1043        tof_step: i32,
1044        im_peaks: &[ImPeak1D],
1045        rt_params: RtExpandParams,
1046        build_opts: &BuildSpecOpts,
1047        eval_opts: &Eval1DOpts,
1048        require_rt_overlap: bool,
1049        num_threads: usize,
1050    ) -> Vec<ClusterResult1D> {
1051        // Guard: all IM peaks must belong to this DIA group
1052        debug_assert!(
1053            im_peaks
1054                .iter()
1055                .all(|p| p.window_group == Some(window_group)),
1056            "clusters_for_group: some IM peaks have wrong or missing window_group"
1057        );
1058
1059        // Build RT+TOF grid for this DIA isolation window group.
1060        let rt = self.make_rt_frames_for_group(window_group, tof_step);
1061
1062        // Force MS level 2 for DIA fragments
1063        let build_opts_ms2 = build_opts.with_ms_level(2);
1064
1065        self.clusters_for_im_peaks_on_rt_frames(
1066            rt,
1067            im_peaks,
1068            rt_params,
1069            &build_opts_ms2,
1070            eval_opts,
1071            require_rt_overlap,
1072            num_threads,
1073        )
1074    }
1075
1076    pub fn clusters_for_precursor(
1077        &self,
1078        tof_step: i32,
1079        im_peaks: &[ImPeak1D],
1080        rt_params: RtExpandParams,
1081        build_opts: &BuildSpecOpts,
1082        eval_opts: &Eval1DOpts,
1083        require_rt_overlap: bool,
1084        num_threads: usize,
1085    ) -> Vec<ClusterResult1D> {
1086        // Guard: all IM peaks must be MS1 (no window_group)
1087        debug_assert!(
1088            im_peaks.iter().all(|p| p.window_group.is_none()),
1089            "clusters_for_precursor: IM peaks unexpectedly carry a window_group"
1090        );
1091
1092        // RT+TOF grid for precursor (MS1) frames
1093        let rt = self.make_rt_frames_for_precursor(tof_step);
1094
1095        // Force MS level 1 for precursor
1096        let build_opts_ms1 = build_opts.with_ms_level(1);
1097
1098        self.clusters_for_im_peaks_on_rt_frames(
1099            rt,
1100            im_peaks,
1101            rt_params,
1102            &build_opts_ms1,
1103            eval_opts,
1104            require_rt_overlap,
1105            num_threads,
1106        )
1107    }
1108
1109    /// End-to-end DIA → pseudo-DDA builder (geometric scoring).
1110    ///
1111    /// Thin wrapper around `build_pseudo_spectra_end_to_end`.
1112    pub fn build_pseudo_spectra_from_clusters_geom(
1113        &self,
1114        ms1: &[ClusterResult1D],
1115        ms2: &[ClusterResult1D],
1116        features: Option<&[SimpleFeature]>,
1117        cand_opts: &CandidateOpts,
1118        score_opts: &ScoreOpts,
1119        pseudo_opts: &PseudoSpecOpts,
1120    ) -> PseudoBuildResult {
1121        build_pseudo_spectra_end_to_end(
1122            self,
1123            ms1,
1124            ms2,
1125            features,
1126            cand_opts,
1127            score_opts,
1128            pseudo_opts,
1129        )
1130    }
1131
1132    /// End-to-end DIA → pseudo-DDA builder (XIC-based scoring).
1133    ///
1134    /// Thin wrapper around `build_pseudo_spectra_end_to_end_xic`.
1135    pub fn build_pseudo_spectra_from_clusters_xic(
1136        &self,
1137        ms1: &[ClusterResult1D],
1138        ms2: &[ClusterResult1D],
1139        features: Option<&[SimpleFeature]>,
1140        cand_opts: &CandidateOpts,
1141        xic_opts: &XicScoreOpts,
1142        pseudo_opts: &PseudoSpecOpts,
1143    ) -> PseudoBuildResult {
1144        build_pseudo_spectra_end_to_end_xic(
1145            self,
1146            ms1,
1147            ms2,
1148            features,
1149            cand_opts,
1150            xic_opts,
1151            pseudo_opts,
1152        )
1153    }
1154
1155    /// Naive "all pairs" builder stays as-is, still returning Vec<PseudoSpectrum>.
1156    pub fn build_pseudo_spectra_all_pairs_from_clusters(
1157        &self,
1158        ms1: &[ClusterResult1D],
1159        ms2: &[ClusterResult1D],
1160        features: Option<&[SimpleFeature]>,
1161        pseudo_opts: &PseudoSpecOpts,
1162    ) -> PseudoBuildResult {
1163        build_pseudo_spectra_all_pairs(self, ms1, ms2, features, pseudo_opts)
1164    }
1165
1166    // ==========================================================
1167    // Convenience methods using ClusterExtractionOpts (Phase 5)
1168    // ==========================================================
1169
1170    /// Extract clusters for a DIA window group using options struct.
1171    pub fn clusters_for_group_opts(
1172        &self,
1173        window_group: u32,
1174        im_peaks: &[ImPeak1D],
1175        opts: &ClusterExtractionOpts,
1176    ) -> Vec<ClusterResult1D> {
1177        self.clusters_for_group(
1178            window_group,
1179            opts.tof_step,
1180            im_peaks,
1181            opts.rt_params.clone(),
1182            &opts.build_opts,
1183            &opts.eval_opts,
1184            opts.require_rt_overlap,
1185            opts.num_threads,
1186        )
1187    }
1188
1189    /// Extract clusters for precursor (MS1) frames using options struct.
1190    pub fn clusters_for_precursor_opts(
1191        &self,
1192        im_peaks: &[ImPeak1D],
1193        opts: &ClusterExtractionOpts,
1194    ) -> Vec<ClusterResult1D> {
1195        self.clusters_for_precursor(
1196            opts.tof_step,
1197            im_peaks,
1198            opts.rt_params.clone(),
1199            &opts.build_opts,
1200            &opts.eval_opts,
1201            opts.require_rt_overlap,
1202            opts.num_threads,
1203        )
1204    }
1205
1206    /// Dense TOF×RT grid for all PRECURSOR (MS1) frames.
1207    /// `tof_step` controls TOF bin granularity (1 = full resolution).
1208    pub fn tof_rt_grid_precursor(&self, tof_step: i32) -> TofRtGrid {
1209        let rt = self.make_rt_frames_for_precursor(tof_step);
1210        build_tof_rt_grid_full(&rt, None)
1211    }
1212
1213    /// Dense TOF×RT grid for FRAGMENT frames in a DIA window group.
1214    /// `tof_step` controls TOF bin granularity (1 = full resolution).
1215    pub fn tof_rt_grid_for_group(&self, window_group: u32, tof_step: i32) -> TofRtGrid {
1216        let rt = self.make_rt_frames_for_group(window_group, tof_step);
1217        build_tof_rt_grid_full(&rt, Some(window_group))
1218    }
1219
1220    /// Debug helper: for a bunch of clusters that all live on the same
1221    /// DIA grid (either MS1 or one MS2 window_group), extract RawPoints
1222    /// per cluster.
1223    ///
1224    /// - `clusters`: precursor *or* fragment clusters.
1225    ///   All must have the same `ms_level`.
1226    /// - `window_group`: if you pass Some(g), we treat them as MS2 clusters
1227    ///   on that DIA group. If None and ms_level == 2, we try to infer g
1228    ///   from the first cluster’s `window_group`.
1229    /// - `tof_step`: must be the same as used during clustering.
1230    /// - `max_points`: optional thinning cap per cluster.
1231    /// - `num_threads`: used for `get_slice` in the raw extractor.
1232    pub fn debug_extract_raw_for_clusters(
1233        &self,
1234        clusters: &[ClusterResult1D],
1235        window_group: Option<u32>,
1236        tof_step: i32,
1237        max_points: Option<usize>,
1238        num_threads: usize,
1239    ) -> Vec<RawPoints> {
1240        if clusters.is_empty() {
1241            return Vec::new();
1242        }
1243
1244        // ---- 1. Basic sanity: consistent ms_level ---------------------------
1245        let ms_level = clusters[0].ms_level;
1246        debug_assert!(
1247            clusters.iter().all(|c| c.ms_level == ms_level),
1248            "debug_extract_raw_for_clusters: mixed ms_level in cluster list"
1249        );
1250
1251        // Optional filter by WG if caller wants to restrict.
1252        let clusters: Vec<ClusterResult1D> = clusters
1253            .iter()
1254            .filter(|c| match window_group {
1255                Some(g) => c.window_group == Some(g),
1256                None => true,
1257            })
1258            .cloned()
1259            .collect();
1260
1261        if clusters.is_empty() {
1262            return Vec::new();
1263        }
1264
1265        // ---- 2. Rebuild the RtFrames grid used for these clusters ----------
1266        //
1267        // For MS1: all clusters live on the precursor RtFrames grid.
1268        // For MS2: all clusters live on the RtFrames grid of a single window group.
1269        let rt_frames = if ms_level == 1 {
1270            // Precursor grid; we ignore window_group here.
1271            self.make_rt_frames_for_precursor(tof_step)
1272        } else {
1273            // Fragments: we need a valid DIA group.
1274            let g = match window_group {
1275                Some(g) => g,
1276                None => clusters[0]
1277                    .window_group
1278                    .expect("MS2 cluster without window_group; pass window_group explicitly"),
1279            };
1280            self.make_rt_frames_for_group(g, tof_step)
1281        };
1282
1283        // ---- 3. For each cluster, call the existing raw extractor ----------
1284        clusters
1285            .iter()
1286            .map(|c| {
1287                let (rt_lo, rt_hi) = c.rt_window;
1288                let (im_lo, im_hi) = c.im_window;
1289                let (tof_lo, tof_hi) = c.tof_window;
1290
1291                attach_raw_points_for_spec_1d_threads(
1292                    self,
1293                    &rt_frames,
1294                    tof_lo,
1295                    tof_hi,
1296                    im_lo,
1297                    im_hi,
1298                    rt_lo,
1299                    rt_hi,
1300                    max_points,
1301                    num_threads,
1302                )
1303            })
1304            .collect()
1305    }
1306}
1307
1308impl TimsData for TimsDatasetDIA {
1309    fn get_frame(&self, frame_id: u32) -> TimsFrame {
1310        self.loader.get_frame(frame_id)
1311    }
1312
1313    fn get_raw_frame(&self, frame_id: u32) -> RawTimsFrame {
1314        self.loader.get_raw_frame(frame_id)
1315    }
1316
1317    fn get_slice(&self, frame_ids: Vec<u32>, num_threads: usize) -> TimsSlice {
1318        self.loader.get_slice(frame_ids, num_threads)
1319    }
1320    fn get_acquisition_mode(&self) -> AcquisitionMode {
1321        self.loader.get_acquisition_mode().clone()
1322    }
1323
1324    fn get_frame_count(&self) -> i32 {
1325        self.loader.get_frame_count()
1326    }
1327
1328    fn get_data_path(&self) -> &str {
1329        &self.loader.get_data_path()
1330    }
1331}
1332
1333impl IndexConverter for TimsDatasetDIA {
1334    fn tof_to_mz(&self, frame_id: u32, tof_values: &Vec<u32>) -> Vec<f64> {
1335        self.loader
1336            .get_index_converter()
1337            .tof_to_mz(frame_id, tof_values)
1338    }
1339
1340    fn mz_to_tof(&self, frame_id: u32, mz_values: &Vec<f64>) -> Vec<u32> {
1341        self.loader
1342            .get_index_converter()
1343            .mz_to_tof(frame_id, mz_values)
1344    }
1345
1346    fn scan_to_inverse_mobility(&self, frame_id: u32, scan_values: &Vec<u32>) -> Vec<f64> {
1347        self.loader
1348            .get_index_converter()
1349            .scan_to_inverse_mobility(frame_id, scan_values)
1350    }
1351
1352    fn inverse_mobility_to_scan(
1353        &self,
1354        frame_id: u32,
1355        inverse_mobility_values: &Vec<f64>,
1356    ) -> Vec<u32> {
1357        self.loader
1358            .get_index_converter()
1359            .inverse_mobility_to_scan(frame_id, inverse_mobility_values)
1360    }
1361}
1362
1363pub fn attach_raw_points_for_spec_1d_threads(
1364    ds: &TimsDatasetDIA,
1365    rt_frames: &RtFrames,
1366    final_bin_lo: usize,
1367    final_bin_hi: usize,
1368    final_im_lo: usize,
1369    final_im_hi: usize,
1370    final_rt_lo: usize,
1371    final_rt_hi: usize,
1372    max_points: Option<usize>,
1373    num_threads: usize,
1374) -> RawPoints {
1375    let scale = &*rt_frames.scale;
1376
1377    // Defensive clamp of bin indices to the valid bin range.
1378    let n_bins = scale.num_bins();
1379    if n_bins == 0 {
1380        return RawPoints::default();
1381    }
1382
1383    let mut bin_lo = final_bin_lo.min(n_bins.saturating_sub(1));
1384    let mut bin_hi = final_bin_hi.min(n_bins.saturating_sub(1));
1385    if bin_lo > bin_hi {
1386        std::mem::swap(&mut bin_lo, &mut bin_hi);
1387    }
1388
1389    // Axis window in *TOF-axis units*:
1390    //   [edges[bin_lo], cushion_hi_edge(edges[bin_hi+1])]
1391    let mut axis_lo = scale.edges[bin_lo];
1392    let hi_edge_idx = (bin_hi + 1).min(scale.edges.len().saturating_sub(1));
1393    let mut axis_hi = cushion_hi_edge(scale, scale.edges[hi_edge_idx]);
1394
1395    // RT frames and slice
1396    let frame_ids_local = rt_frames.frame_ids[final_rt_lo..=final_rt_hi].to_vec();
1397    let slice = ds.get_slice(frame_ids_local.clone(), num_threads.max(1));
1398    let scan_slices: Vec<Vec<ScanSlice>> =
1399        slice.frames.iter().map(|fr| build_scan_slices(fr)).collect();
1400
1401    // 1) Count – now using **TOF** as the search axis.
1402    let mut total = 0usize;
1403    for (fi, fr) in slice.frames.iter().enumerate() {
1404        let tofs = &fr.tof;               // raw TOF indices
1405        for sl in &scan_slices[fi] {
1406            if sl.scan < final_im_lo || sl.scan > final_im_hi {
1407                continue;
1408            }
1409            let l = lower_bound_tof(tofs, sl.start, sl.end, axis_lo);
1410            let r = upper_bound_tof(tofs, sl.start, sl.end, axis_hi);
1411            total += r.saturating_sub(l);
1412        }
1413    }
1414
1415    // 2) Last-chance widen: if empty, expand by ±1 bin in TOF space.
1416    if total == 0 {
1417        let lo_idx = bin_lo.saturating_sub(1);
1418        let hi_edge_idx_wide =
1419            (bin_hi + 2).min(n_bins).min(scale.edges.len().saturating_sub(1));
1420
1421        let try_lo = scale.edges[lo_idx];
1422        let try_hi = cushion_hi_edge(scale, scale.edges[hi_edge_idx_wide]);
1423
1424        let mut total2 = 0usize;
1425        for (fi, fr) in slice.frames.iter().enumerate() {
1426            let tofs = &fr.tof;
1427            for sl in &scan_slices[fi] {
1428                if sl.scan < final_im_lo || sl.scan > final_im_hi {
1429                    continue;
1430                }
1431                let l = lower_bound_tof(tofs, sl.start, sl.end, try_lo);
1432                let r = upper_bound_tof(tofs, sl.start, sl.end, try_hi);
1433                total2 += r.saturating_sub(l);
1434            }
1435        }
1436
1437        if total2 > 0 {
1438            total = total2;
1439            axis_lo = try_lo;
1440            axis_hi = try_hi;
1441        }
1442    }
1443
1444    // Still empty → bail with empty container
1445    if total == 0 {
1446        return RawPoints::default();
1447    }
1448
1449    let stride = max_points.map(|cap| thin_stride(total, cap)).unwrap_or(1);
1450    let reserve = total / stride + 8;
1451
1452    let mut pts = RawPoints {
1453        mz: Vec::with_capacity(reserve),
1454        rt: Vec::with_capacity(reserve),
1455        im: Vec::with_capacity(reserve),
1456        scan: Vec::with_capacity(reserve),
1457        intensity: Vec::with_capacity(reserve),
1458        tof: Vec::with_capacity(reserve),
1459        frame: Vec::with_capacity(reserve),
1460    };
1461
1462    let rt_axis_sec = rt_frames.rt_times[final_rt_lo..=final_rt_hi].to_vec();
1463
1464    // 3) Extraction with thinning – again use TOF range for selection
1465    let mut seen = 0usize;
1466    for (fi, fr) in slice.frames.iter().enumerate() {
1467        let mz   = &fr.ims_frame.mz;
1468        let it   = &fr.ims_frame.intensity;
1469        let ims  = &fr.ims_frame.mobility;
1470        let tofs = &fr.tof;
1471
1472        let len_all = mz.len().min(it.len()).min(ims.len()).min(tofs.len());
1473        let rt_val = rt_axis_sec[fi];
1474        let frame_id = frame_ids_local[fi];
1475
1476        for sl in &scan_slices[fi] {
1477            let s_abs = sl.scan;
1478            if s_abs < final_im_lo || s_abs > final_im_hi {
1479                continue;
1480            }
1481
1482            let mut l = lower_bound_tof(tofs, sl.start, sl.end, axis_lo);
1483            let mut r = upper_bound_tof(tofs, sl.start, sl.end, axis_hi);
1484            if r > len_all {
1485                r = len_all;
1486            }
1487            if l >= r {
1488                continue;
1489            }
1490
1491            while l < r {
1492                if stride == 1 || (seen % stride == 0) {
1493                    // Note: we still *store* m/z, but the selection is done in TOF.
1494                    pts.mz.push(mz[l] as f32);
1495                    pts.rt.push(rt_val);
1496                    pts.im.push(ims[l] as f32);
1497                    pts.scan.push(s_abs as u32);
1498                    pts.intensity.push(it[l] as f32);
1499                    pts.frame.push(frame_id);
1500                    pts.tof.push(tofs[l]);
1501                }
1502                seen += 1;
1503                l += 1;
1504            }
1505        }
1506    }
1507
1508    pts
1509}
1510
1511/// Binary search in TOF array [start, end) for lower bound.
1512#[inline]
1513fn lower_bound_tof(tofs: &[i32], start: usize, end: usize, x: f32) -> usize {
1514    let mut lo = start;
1515    let mut hi = end;
1516    let xf = x as f64;
1517    while lo < hi {
1518        let mid = (lo + hi) >> 1;
1519        if (tofs[mid] as f64) < xf {
1520            lo = mid + 1;
1521        } else {
1522            hi = mid;
1523        }
1524    }
1525    lo
1526}
1527
1528/// Binary search in TOF array [start, end) for upper bound.
1529#[inline]
1530fn upper_bound_tof(tofs: &[i32], start: usize, end: usize, x: f32) -> usize {
1531    let mut lo = start;
1532    let mut hi = end;
1533    let xf = x as f64;
1534    while lo < hi {
1535        let mid = (lo + hi) >> 1;
1536        if (tofs[mid] as f64) <= xf {
1537            lo = mid + 1;
1538        } else {
1539            hi = mid;
1540        }
1541    }
1542    lo
1543}
1544
1545// ----------------------------------------------------------------------
1546// Helpers for axis-based extraction (no ppm, no mz_min/mz_max needed)
1547// ----------------------------------------------------------------------
1548
1549/// Slightly "cushion" the high edge used for upper_bound search.
1550///
1551/// Semantics:
1552/// - `hi_edge` is typically `scale.edges[bin_hi + 1]` (the upper edge of the last bin).
1553/// - We nudge it outward by a tiny fraction of a *typical* bin width so values
1554///   that sit exactly on the edge aren't accidentally excluded.
1555/// - This is axis-generic: it works whether the axis is TOF or m/z-like.
1556#[inline]
1557fn cushion_hi_edge(scale: &TofScale, hi_edge: f32) -> f32 {
1558    let edges = &scale.edges;
1559    if edges.len() >= 2 {
1560        // Use a small fraction of the first bin width as epsilon.
1561        let bw = (edges[1] - edges[0]).abs().max(1e-6);
1562        hi_edge + 0.01 * bw
1563    } else {
1564        hi_edge
1565    }
1566}
1567
1568#[inline]
1569fn thin_stride(total: usize, cap: usize) -> usize {
1570    if cap == 0 || total <= cap {
1571        1
1572    } else {
1573        (total + cap - 1) / cap
1574    }
1575}
1576
1577
1578#[cfg(test)]
1579mod tests {
1580    use super::*;
1581    use mscore::data::spectrum::MsType;
1582    use mscore::timstof::frame::TimsFrame;
1583
1584    fn make_frame(frame_id: i32, ms_type: MsType) -> TimsFrame {
1585        // minimal non-empty frame: one scan at scan=10, mobility=0.8, tof=500,
1586        // mz=500.0, intensity=10.0 — enough for Add to have something to merge.
1587        TimsFrame::new(
1588            frame_id,
1589            ms_type,
1590            0.0,
1591            vec![10],
1592            vec![0.8],
1593            vec![500],
1594            vec![500.0],
1595            vec![10.0],
1596        )
1597    }
1598
1599    #[test]
1600    fn accumulate_or_typed_empty_returns_typed_empty_when_pool_is_empty() {
1601        // The whole point of the fix: an empty sample pool must not
1602        // return TimsFrame::default() (frame_id=0, ms_type=Unknown). It
1603        // must return a typed empty so the caller's `frame + noise`
1604        // doesn't collapse the simulated frame's ms_type to Unknown.
1605        let mut samples: Vec<TimsFrame> = vec![];
1606        let noise = TimsDatasetDIA::accumulate_or_typed_empty(
1607            &mut samples, MsType::Precursor,
1608        );
1609        assert_eq!(noise.ms_type, MsType::Precursor,
1610                   "typed-empty must carry the requested MsType, not Unknown");
1611        assert!(noise.scan.is_empty());
1612        assert!(noise.ims_frame.mz.is_empty());
1613    }
1614
1615    #[test]
1616    fn accumulate_or_typed_empty_stamps_type_even_after_inner_unknown() {
1617        // Belt-and-braces: even if some path managed to insert an
1618        // MsType::Unknown sample into the accumulator (which the outer
1619        // filter should prevent), the final stamp must restore the
1620        // requested type so downstream `simulated + noise` doesn't see
1621        // a mismatched operand.
1622        let mut samples = vec![
1623            make_frame(1, MsType::Unknown),
1624            make_frame(2, MsType::FragmentDia),
1625        ];
1626        let noise = TimsDatasetDIA::accumulate_or_typed_empty(
1627            &mut samples, MsType::FragmentDia,
1628        );
1629        assert_eq!(noise.ms_type, MsType::FragmentDia);
1630    }
1631
1632    #[test]
1633    fn accumulate_preserves_type_on_clean_input() {
1634        let mut samples = vec![
1635            make_frame(1, MsType::FragmentDia),
1636            make_frame(2, MsType::FragmentDia),
1637            make_frame(3, MsType::FragmentDia),
1638        ];
1639        let noise = TimsDatasetDIA::accumulate_or_typed_empty(
1640            &mut samples, MsType::FragmentDia,
1641        );
1642        assert_eq!(noise.ms_type, MsType::FragmentDia);
1643        // Inputs were merged; the accumulator should hold a non-empty frame.
1644        assert!(!noise.scan.is_empty());
1645    }
1646
1647    #[test]
1648    fn typed_empty_frame_uses_correct_default_frame_id() {
1649        // Empty-pool fallback should use frame_id=0 — same as
1650        // TimsFrame::default() — but with the requested ms_type stamped.
1651        // This pairs with the writer-side Frames.Id uniqueness check
1652        // (packages/imspy-simulation/src/imspy_simulation/tdf.py):
1653        // empty noise frames must not silently pollute the Frames table.
1654        let mut samples: Vec<TimsFrame> = vec![];
1655        let noise = TimsDatasetDIA::accumulate_or_typed_empty(
1656            &mut samples, MsType::Precursor,
1657        );
1658        assert_eq!(noise.frame_id, 0);
1659        assert_eq!(noise.ims_frame.retention_time, 0.0);
1660    }
1661}