pub trait SpectrumSource<C: CentroidLike = CentroidPeak, D: DeconvolutedCentroidLike = DeconvolutedPeak, S: SpectrumLike<C, D> = MultiLayerSpectrum<C, D>>: Iterator<Item = S> {
Show 17 methods
// Required methods
fn reset(&mut self);
fn detail_level(&self) -> &DetailLevel;
fn set_detail_level(&mut self, detail_level: DetailLevel);
fn get_spectrum_by_id(&mut self, id: &str) -> Option<S>;
fn get_spectrum_by_index(&mut self, index: usize) -> Option<S>;
fn get_index(&self) -> &OffsetIndex;
fn set_index(&mut self, index: OffsetIndex);
// Provided methods
fn get_spectrum_by_time(&mut self, time: f64) -> Option<S> { ... }
fn len(&self) -> usize { ... }
fn is_empty(&self) -> bool { ... }
fn _offset_of_id(&self, id: &str) -> Option<u64> { ... }
fn _offset_of_index(&self, index: usize) -> Option<u64> { ... }
fn _offset_of_time(&mut self, time: f64) -> Option<u64> { ... }
fn iter(&mut self) -> SpectrumIterator<'_, C, D, S, Self> ⓘ
where Self: Sized { ... }
fn get_group_by_index(
&mut self,
index: usize,
) -> Option<SpectrumGroup<C, D, S>>
where Self: Sized { ... }
fn groups(
&mut self,
) -> SpectrumGroupingIterator<SpectrumIterator<'_, C, D, S, Self>, C, D, S> ⓘ
where Self: Sized { ... }
fn into_groups(self) -> SpectrumGroupingIterator<Self, C, D, S> ⓘ
where Self: Sized { ... }
}Expand description
A base trait defining the behaviors of a source of spectra.
A SpectrumSource is the basis for many data access methods
in mzdata.
Required Methods§
Sourcefn detail_level(&self) -> &DetailLevel
fn detail_level(&self) -> &DetailLevel
Get the DetailLevel the reader currently uses
Sourcefn set_detail_level(&mut self, detail_level: DetailLevel)
fn set_detail_level(&mut self, detail_level: DetailLevel)
Set the DetailLevel for the reader, changing
the amount of work done immediately on loading a
spectrum.
§Note
Not all readers support all detail levels, and the behavior when requesting one of those levels will depend upon the underlying reader.
Sourcefn get_spectrum_by_id(&mut self, id: &str) -> Option<S>
fn get_spectrum_by_id(&mut self, id: &str) -> Option<S>
Retrieve a spectrum by it’s native ID
Sourcefn get_spectrum_by_index(&mut self, index: usize) -> Option<S>
fn get_spectrum_by_index(&mut self, index: usize) -> Option<S>
Retrieve a spectrum by it’s integer index
Sourcefn get_index(&self) -> &OffsetIndex
fn get_index(&self) -> &OffsetIndex
Access the spectrum offset index to enumerate all spectra by ID
Sourcefn set_index(&mut self, index: OffsetIndex)
fn set_index(&mut self, index: OffsetIndex)
Set the spectrum offset index. This method shouldn’t be needed if not writing a new adapter
Provided Methods§
Sourcefn get_spectrum_by_time(&mut self, time: f64) -> Option<S>
fn get_spectrum_by_time(&mut self, time: f64) -> Option<S>
Retrieve a spectrum by its scan start time Considerably more complex than seeking by ID or index, this involves a binary search over the spectrum index and assumes that spectra are stored in chronological order.
Examples found in repository?
7fn main() -> io::Result<()> {
8 env_logger::init();
9 let mut args = env::args().skip(1);
10
11 let path = path::PathBuf::from(args.next().expect("Please pass an MS data file path"));
12
13 let key = args
14 .next()
15 .expect("Please provide a key type, \"id\", \"index\" or \"time\"");
16 let key_value = args
17 .next()
18 .expect("Please provide a key value matching the key type");
19
20 info!("Opening {}", path.display());
21 let mut reader = MZReader::open_path(path)?;
22 info!("{} spectra detected", reader.len());
23 let spectrum = match key.as_str() {
24 "id" => reader.get_spectrum_by_id(&key_value).unwrap(),
25 "index" => reader
26 .get_spectrum_by_index(key_value.parse().unwrap())
27 .unwrap(),
28 "time" => reader
29 .get_spectrum_by_time(key_value.parse().unwrap())
30 .unwrap(),
31 _ => {
32 panic!("Unknown key type {}", key);
33 }
34 };
35
36 // dbg!(spectrum);
37 println!(
38 "ID: {}; Index: {}; Time: {}",
39 spectrum.id(),
40 spectrum.index(),
41 spectrum.start_time()
42 );
43 println!(
44 "Num data points: {}",
45 spectrum
46 .raw_arrays()
47 .and_then(|r| Some(r.mzs().ok()?.len()))
48 .unwrap_or_default()
49 );
50 if spectrum.signal_continuity().is_centroid() && spectrum.raw_arrays().is_none() {
51 println!("Num peaks: {}", spectrum.peaks().len());
52 }
53 Ok(())
54}Sourcefn len(&self) -> usize
fn len(&self) -> usize
Retrieve the number of spectra in source file, usually by getting the length of the index. If the index isn’t initialized, this will be 0.
Examples found in repository?
7fn main() -> io::Result<()> {
8 env_logger::init();
9 let mut args = env::args().skip(1);
10
11 let path = path::PathBuf::from(args.next().expect("Please pass an MS data file path"));
12
13 let key = args
14 .next()
15 .expect("Please provide a key type, \"id\", \"index\" or \"time\"");
16 let key_value = args
17 .next()
18 .expect("Please provide a key value matching the key type");
19
20 info!("Opening {}", path.display());
21 let mut reader = MZReader::open_path(path)?;
22 info!("{} spectra detected", reader.len());
23 let spectrum = match key.as_str() {
24 "id" => reader.get_spectrum_by_id(&key_value).unwrap(),
25 "index" => reader
26 .get_spectrum_by_index(key_value.parse().unwrap())
27 .unwrap(),
28 "time" => reader
29 .get_spectrum_by_time(key_value.parse().unwrap())
30 .unwrap(),
31 _ => {
32 panic!("Unknown key type {}", key);
33 }
34 };
35
36 // dbg!(spectrum);
37 println!(
38 "ID: {}; Index: {}; Time: {}",
39 spectrum.id(),
40 spectrum.index(),
41 spectrum.start_time()
42 );
43 println!(
44 "Num data points: {}",
45 spectrum
46 .raw_arrays()
47 .and_then(|r| Some(r.mzs().ok()?.len()))
48 .unwrap_or_default()
49 );
50 if spectrum.signal_continuity().is_centroid() && spectrum.raw_arrays().is_none() {
51 println!("Num peaks: {}", spectrum.peaks().len());
52 }
53 Ok(())
54}More examples
6fn main() -> io::Result<()> {
7 let path = path::PathBuf::from(
8 env::args()
9 .nth(1)
10 .expect("Please pass an MS data file path"),
11 // "test/data/batching_test.mzML"
12 );
13
14 let mut reader = mzml::MzMLReader::open_path(path)?;
15
16 let n_spectra = reader.len();
17
18 // Find the spectrum at the midpoint of the run
19 let spec = reader.get_spectrum_by_index(n_spectra / 2).unwrap();
20 eprintln!(
21 "Midpoint spectrum {} (level {}) at time {}",
22 spec.id(),
23 spec.ms_level(),
24 spec.start_time()
25 );
26
27 // Jump the iterator to that point in time
28 reader.start_from_time(spec.start_time())?;
29 let s = reader.next().unwrap();
30 eprintln!(
31 "Resuming at {} (level {}) at time {}",
32 s.id(),
33 s.ms_level(),
34 s.start_time()
35 );
36
37 // Convert the iterator into a group iterator
38 let mut group_iter = reader.into_groups();
39 // Jump the group iterator to that point in time (If an MSn spectrum was found, the next MS1 may be shown instead)
40 group_iter.start_from_time(spec.start_time())?;
41 let g = group_iter.next().unwrap();
42 eprintln!(
43 "Resuming at group having {:?} at time {:?}",
44 g.earliest_spectrum().map(|s| s.id()),
45 g.earliest_spectrum().map(|s| s.start_time())
46 );
47
48 // Convert the group iterator into an averaging group iterator
49 let mut avg_iter = group_iter.averaging(1, 200.0, 2200.0, 0.005);
50 // Jump the group iterator to that point in time (If an MSn spectrum was found, the next MS1 may be shown instead)
51 avg_iter.start_from_time(spec.start_time())?;
52 let g = avg_iter.next().unwrap();
53 eprintln!(
54 "Resuming at group having {:?} at time {:?}",
55 g.earliest_spectrum().map(|s| s.id()),
56 g.earliest_spectrum().map(|s| s.start_time())
57 );
58
59 Ok(())
60}fn is_empty(&self) -> bool
Sourcefn _offset_of_id(&self, id: &str) -> Option<u64>
fn _offset_of_id(&self, id: &str) -> Option<u64>
Helper method to support seeking to an ID
Sourcefn _offset_of_index(&self, index: usize) -> Option<u64>
fn _offset_of_index(&self, index: usize) -> Option<u64>
Helper method to support seeking to an index
Sourcefn _offset_of_time(&mut self, time: f64) -> Option<u64>
fn _offset_of_time(&mut self, time: f64) -> Option<u64>
Helper method to support seeking to a specific time. Considerably more complex than seeking by ID or index.
Sourcefn iter(&mut self) -> SpectrumIterator<'_, C, D, S, Self> ⓘwhere
Self: Sized,
fn iter(&mut self) -> SpectrumIterator<'_, C, D, S, Self> ⓘwhere
Self: Sized,
Open a new iterator over this stream
Sourcefn get_group_by_index(&mut self, index: usize) -> Option<SpectrumGroup<C, D, S>>where
Self: Sized,
fn get_group_by_index(&mut self, index: usize) -> Option<SpectrumGroup<C, D, S>>where
Self: Sized,
Get the nth SpectrumGroup from this source
Sourcefn groups(
&mut self,
) -> SpectrumGroupingIterator<SpectrumIterator<'_, C, D, S, Self>, C, D, S> ⓘwhere
Self: Sized,
fn groups(
&mut self,
) -> SpectrumGroupingIterator<SpectrumIterator<'_, C, D, S, Self>, C, D, S> ⓘwhere
Self: Sized,
Create a new SpectrumIterator over self and use that state to drive a SpectrumGroupingIterator
Examples found in repository?
21fn main() -> io::Result<()> {
22 let path = path::PathBuf::from(
23 env::args()
24 .nth(1)
25 .expect("Please pass an MS data file path"),
26 );
27
28 let mut reader = MZReader::open_path(path)?;
29 let mut writer = MzMLWriter::new(io::BufWriter::new(io::stdout()));
30 writer.copy_metadata_from(&reader);
31
32 let (input_sender, input_receiver) = sync_channel(5000);
33 let (output_sender, output_receiver) = sync_channel(5000);
34
35 let start = Instant::now();
36 let reader_task = thread::spawn(move || {
37 let (grouper, averager, _reprofiler) =
38 reader.groups().averaging_deferred(1, 120.0, 2000.1, 0.002);
39 grouper
40 .enumerate()
41 .par_bridge()
42 .map_init(
43 || averager.clone(),
44 |averager, (i, g)| {
45 let (mut g, arrays) = g.average_with(averager);
46 if let Some(p) = g.precursor_mut() {
47 p.arrays = Some(arrays.into());
48 p.description_mut().signal_continuity = SignalContinuity::Profile;
49 }
50 (i, g)
51 },
52 )
53 .for_each(|(i, g)| {
54 input_sender.send((i, g)).unwrap();
55 });
56 let end_read = Instant::now();
57 eprintln!(
58 "Finished reading all spectra and averaging in {:0.3?}",
59 end_read - start
60 );
61 });
62
63 let collator_task =
64 thread::spawn(move || Collator::collate_sync(input_receiver, output_sender));
65
66 let writer_task = thread::spawn(move || -> io::Result<()> {
67 for (_, group) in output_receiver {
68 writer.write_group(&group)?;
69 }
70 writer.close().unwrap();
71 let end_write = Instant::now();
72 eprintln!("Finished writing all spectra in {:0.3?}", end_write - start);
73 Ok(())
74 });
75
76 if let Err(e) = reader_task.join() {
77 eprintln!("An error occurred while joining processing spectra task: {e:?}")
78 }
79
80 if let Err(e) = collator_task.join() {
81 eprintln!("An error occurred while joining collating spectra task: {e:?}")
82 }
83
84 match writer_task.join() {
85 Ok(r) => {
86 r?;
87 }
88 Err(e) => {
89 eprintln!("An error occurred while joining writing spectra task: {e:?}")
90 }
91 }
92
93 Ok(())
94}Sourcefn into_groups(self) -> SpectrumGroupingIterator<Self, C, D, S> ⓘwhere
Self: Sized,
fn into_groups(self) -> SpectrumGroupingIterator<Self, C, D, S> ⓘwhere
Self: Sized,
Consume self to create a SpectrumGroupingIterator. This is ideal for non-rewindable streams
like io::stdin which don’t implement io::Seek
Examples found in repository?
255fn main() -> io::Result<()> {
256 let path = path::PathBuf::from(
257 env::args()
258 .nth(1)
259 .expect("Please pass an MS data file path"),
260 );
261 env_logger::init();
262
263 let reader = mzdata::MzMLReader::new(fs::File::open(path)?);
264 let group_iter = reader.into_groups();
265 let tracking_iter = MSnTargetTrackingIterator::new(group_iter, 2.0, Tolerance::PPM(5.0));
266 for (group, targets) in tracking_iter {
267 if group.precursor.is_some() {
268 let prec = group.precursor.as_ref().unwrap();
269 eprintln!("{} {}: {}", prec.id(), prec.start_time(), targets.len());
270 }
271 }
272 Ok(())
273}More examples
14fn main() -> io::Result<()> {
15 let input = env::args().nth(1).unwrap_or_else(|| {
16 eprintln!("Please provide a file path or '-' for STDIN");
17 exit(1)
18 });
19 let start = Instant::now();
20 let groups = if input == "-" {
21 let stream =
22 RestartableGzDecoder::new(io::BufReader::new(PreBufferedStream::new(io::stdin())?));
23 let reader = MzMLReader::new(stream);
24 let groups: Vec<_> = reader.into_groups().collect();
25 groups
26 } else {
27 let stream = RestartableGzDecoder::new(io::BufReader::new(fs::File::open(input)?));
28 let reader = MzMLReader::new(stream);
29 let groups: Vec<_> = reader.into_groups().collect();
30 groups
31 };
32 let spectra: Vec<_> = groups
33 .iter()
34 .flat_map(|g| g.precursor.iter().chain(g.products.iter()))
35 .collect();
36 let end = Instant::now();
37 eprintln!(
38 "Read {} groups with {} spectra in {:0.3?}",
39 groups.len(),
40 spectra.len(),
41 end - start
42 );
43 assert!(!spectra.is_empty());
44
45 Ok(())
46}13fn main() -> io::Result<()> {
14 env_logger::init();
15 let start = Instant::now();
16 let stream = io::stdin();
17 let mut stream = PreBufferedStream::new(stream)?;
18 let (fmt, compressed) = infer_from_stream(&mut stream)?;
19 stream.seek(io::SeekFrom::Start(0))?;
20 let groups: Vec<_> = match fmt {
21 MassSpectrometryFormat::MGF => {
22 if compressed {
23 MGFReader::new(RestartableGzDecoder::new(io::BufReader::new(stream)))
24 .into_groups()
25 .collect()
26 } else {
27 MGFReader::new(stream).into_groups().collect()
28 }
29 }
30 MassSpectrometryFormat::MzML => {
31 if compressed {
32 MzMLReader::new(RestartableGzDecoder::new(io::BufReader::new(stream)))
33 .into_groups()
34 .collect()
35 } else {
36 MzMLReader::new(stream).into_groups().collect()
37 }
38 }
39 x => {
40 panic!("Cannot identify file format ({:?})", x)
41 }
42 };
43 let spectra: Vec<_> = groups
44 .iter()
45 .flat_map(|g| g.precursor.iter().chain(g.products.iter()))
46 .collect();
47 let end = Instant::now();
48 eprintln!(
49 "Read {} groups with {} spectra in {:0.3?}",
50 groups.len(),
51 spectra.len(),
52 end - start
53 );
54 assert!(!spectra.is_empty());
55 Ok(())
56}6fn main() -> io::Result<()> {
7 let path = path::PathBuf::from(
8 env::args()
9 .nth(1)
10 .expect("Please pass an MS data file path"),
11 // "test/data/batching_test.mzML"
12 );
13
14 let mut reader = mzml::MzMLReader::open_path(path)?;
15
16 let n_spectra = reader.len();
17
18 // Find the spectrum at the midpoint of the run
19 let spec = reader.get_spectrum_by_index(n_spectra / 2).unwrap();
20 eprintln!(
21 "Midpoint spectrum {} (level {}) at time {}",
22 spec.id(),
23 spec.ms_level(),
24 spec.start_time()
25 );
26
27 // Jump the iterator to that point in time
28 reader.start_from_time(spec.start_time())?;
29 let s = reader.next().unwrap();
30 eprintln!(
31 "Resuming at {} (level {}) at time {}",
32 s.id(),
33 s.ms_level(),
34 s.start_time()
35 );
36
37 // Convert the iterator into a group iterator
38 let mut group_iter = reader.into_groups();
39 // Jump the group iterator to that point in time (If an MSn spectrum was found, the next MS1 may be shown instead)
40 group_iter.start_from_time(spec.start_time())?;
41 let g = group_iter.next().unwrap();
42 eprintln!(
43 "Resuming at group having {:?} at time {:?}",
44 g.earliest_spectrum().map(|s| s.id()),
45 g.earliest_spectrum().map(|s| s.start_time())
46 );
47
48 // Convert the group iterator into an averaging group iterator
49 let mut avg_iter = group_iter.averaging(1, 200.0, 2200.0, 0.005);
50 // Jump the group iterator to that point in time (If an MSn spectrum was found, the next MS1 may be shown instead)
51 avg_iter.start_from_time(spec.start_time())?;
52 let g = avg_iter.next().unwrap();
53 eprintln!(
54 "Resuming at group having {:?} at time {:?}",
55 g.earliest_spectrum().map(|s| s.id()),
56 g.earliest_spectrum().map(|s| s.start_time())
57 );
58
59 Ok(())
60}Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
impl<C: CentroidLike + From<CentroidPeak> + BuildFromArrayMap, D: DeconvolutedCentroidLike + From<DeconvolutedPeak> + BuildFromArrayMap, R: Read + Seek> SpectrumSource<C, D> for MZReaderType<R, C, D>
impl<C: CentroidLike + From<CentroidPeak>, D: DeconvolutedCentroidLike> SpectrumSource<C, D> for ThermoRawReaderType<C, D>
impl<C: CentroidLike, D: DeconvolutedCentroidLike, S: SpectrumLike<C, D> + Clone> SpectrumSource<C, D, S> for MemorySpectrumSource<C, D, S>
impl<C: CentroidLike, D: DeconvolutedCentroidLike, S: SpectrumLike<C, D>, I: Iterator<Item = S>> SpectrumSource<C, D, S> for StreamingSpectrumIterator<C, D, S, I>
impl<C: CentroidLike, D: DeconvolutedCentroidLike, S: SpectrumLike<C, D>, R: SpectrumSource<C, D, S>> SpectrumSource<C, D, S> for SpectrumIterator<'_, C, D, S, R>
impl<C: FeatureLike<MZ, IonMobility>, D: FeatureLike<Mass, IonMobility> + KnownCharge, CP: CentroidLike + From<CentroidPeak>, DP: DeconvolutedCentroidLike> SpectrumSource<CP, DP> for TDFSpectrumReaderType<C, D, CP, DP>
impl<R: Read + Seek, S: Read + Seek, C: CentroidLike + BuildFromArrayMap, D: DeconvolutedCentroidLike + BuildFromArrayMap> SpectrumSource<C, D> for ImzMLReaderType<R, S, C, D>
They can also be used to fetch specific spectra by ID, index, or start
time when the underlying file stream supports io::Seek.
impl<R: SeekRead, C: CentroidLike + BuildFromArrayMap, D: DeconvolutedCentroidLike + BuildFromArrayMap> SpectrumSource<C, D> for MzMLReaderType<R, C, D>
They can also be used to fetch specific spectra by ID, index, or start
time when the underlying file stream supports io::Seek.