Skip to main content

MZFileReader

Trait MZFileReader 

Source
pub trait MZFileReader<C: CentroidLike = CentroidPeak, D: DeconvolutedCentroidLike = DeconvolutedPeak, S: SpectrumLike<C, D> = MultiLayerSpectrum<C, D>>: SpectrumSource<C, D, S> + Sized {
    // Required methods
    fn construct_index_from_stream(&mut self) -> u64;
    fn open_file(source: File) -> Result<Self>;

    // Provided methods
    fn read_index(&mut self, reader: Box<dyn Read>) -> Result<&mut Self, Error> { ... }
    fn write_index(&self, writer: Box<dyn Write>) -> Result<&Self, Error> { ... }
    fn open_path<P>(path: P) -> Result<Self>
       where P: Into<PathBuf> + Clone { ... }
}
Expand description

A trait defining some helper methods to make efficient use of indices automatic when opening a file from a path-like object.

Required Methods§

Source

fn construct_index_from_stream(&mut self) -> u64

An on-trait method of constructing an index. Assumed to be a trivial wrapper.

Source

fn open_file(source: File) -> Result<Self>

Given a regular file, construct a new instance without indexing.

Provided Methods§

Source

fn read_index(&mut self, reader: Box<dyn Read>) -> Result<&mut Self, Error>

Re-construct an offset index from this readable object, assuming it is a JSON stream over the serialized index.

Source

fn write_index(&self, writer: Box<dyn Write>) -> Result<&Self, Error>

Source

fn open_path<P>(path: P) -> Result<Self>
where P: Into<PathBuf> + Clone,

The preferred method of opening a file from a path-like object. This method will open the file at the provided path, test whether there is an accompanied index file next to it on the file system, and if not, build one and save it or otherwise read in the index.

The index building process is usually neglible on “regular” IO file systems.

Examples found in repository?
examples/mzcat.rs (line 33)
25fn main() -> io::Result<()> {
26    env_logger::init();
27    let path = path::PathBuf::from(
28        env::args()
29            .nth(1)
30            .expect("Please pass an MS data file path"),
31    );
32
33    let mut reader = MZReader::open_path(&path)?;
34    scan_file(&mut reader);
35    Ok(())
36}
More examples
Hide additional examples
examples/mzinfo.rs (line 246)
233fn main() -> io::Result<()> {
234    env_logger::init();
235    let path = path::PathBuf::from(env::args().nth(1).unwrap_or_else(|| {
236        eprintln!("Please provide a path to an MS data file");
237        process::exit(1)
238    }));
239    let mut summarizer = MSDataFileSummary::default();
240
241    if path.as_os_str() == "-" {
242        mzdata::mz_read!(Source::Stdin, reader => {
243            summarizer.scan_file(reader)
244        })?;
245    } else {
246        let mut reader = MZReader::open_path(path)?;
247        eprintln!("Format: {}", reader.as_format());
248        if reader.count_chromatograms() > 0 {
249            summarizer.scan_chromatograms(&mut reader);
250            reader.reset();
251        }
252        summarizer.scan_file(reader)
253    };
254
255    summarizer.write_out();
256    Ok(())
257}
examples/readme.rs (line 7)
6fn main() -> io::Result<()> {
7    let reader = mzdata::MZReader::open_path("./test/data/small.mzML")?;
8
9    let mut ms1_count = 0;
10    let mut msn_count = 0;
11    for spectrum in reader {
12        if spectrum.ms_level() == 1 {
13            ms1_count += 1;
14        } else {
15            msn_count += 1;
16        }
17        println!(
18            "Scan {} => BP {}",
19            spectrum.id(),
20            spectrum.peaks().base_peak().mz
21        );
22        if spectrum.signal_continuity() < SignalContinuity::Profile {
23            let peak_picked = spectrum.into_centroid().unwrap();
24            println!(
25                "Matches for 579.155: {:?}",
26                peak_picked
27                    .peaks
28                    .all_peaks_for(579.155, Tolerance::Da(0.02))
29            );
30        }
31    }
32    println!("MS1 Count: {}\nMSn Count: {}", ms1_count, msn_count);
33    assert_eq!(ms1_count, 14);
34    assert_eq!(msn_count, 34);
35    Ok(())
36}
examples/get_chromatogram_by.rs (line 21)
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\" or \"index\"");
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
23    let chrom = match key.as_str() {
24        "id" => reader.get_chromatogram_by_id(&key_value).unwrap(),
25        "index" => reader
26            .get_chromatogram_by_index(key_value.parse().unwrap())
27            .unwrap(),
28        _ => {
29            panic!("Unknown key type {}", key);
30        }
31    };
32
33    println!("ID: {}; Index: {};", chrom.id(), chrom.index(),);
34    println!("Type: {:?}", chrom.chromatogram_type());
35    if let Some(product) = chrom.product() {
36        println!("Product: {:?}", product);
37    }
38    Ok(())
39}
examples/get_scan_by.rs (line 21)
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}
examples/random_access_iter.rs (line 14)
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 not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§