示例#1
0
    def test_run_mrmfeaturefinder(self):

        # load chromatograms
        chromatograms = pyopenms.MSExperiment()
        fh = pyopenms.FileHandler()
        fh.loadExperiment(self.chromatograms, chromatograms)

        # load TraML file
        targeted = pyopenms.TargetedExperiment()
        tramlfile = pyopenms.TraMLFile()
        tramlfile.load(self.tramlfile, targeted)

        # Create empty files as input and finally as output
        empty_swath = pyopenms.MSExperiment()
        trafo = pyopenms.TransformationDescription()
        output = pyopenms.FeatureMap()

        # set up featurefinder and run
        featurefinder = pyopenms.MRMFeatureFinderScoring()
        featurefinder.pickExperiment(chromatograms, output, targeted, trafo,
                                     empty_swath)

        self.assertAlmostEqual(output.size(), 3)
        self.assertAlmostEqual(output[0].getRT(), 3119.092041015, eps)
        self.assertAlmostEqual(output[0].getIntensity(), 3614.99755859375, eps)
        self.assertAlmostEqual(
            output[0].getMetaValue(b"var_xcorr_shape_weighted"),
            0.997577965259552, eps)
        self.assertAlmostEqual(output[0].getMetaValue(b"sn_ratio"),
                               86.00413513183594, eps)
示例#2
0
def reader(path: str, on_disc: bool = True):
    """
    Load `path` file into an OnDiskExperiment. If the file is not indexed, load
    the file.

    Parameters
    ----------
    path : str
        path to read mzML file from.
    on_disc : bool
        if True doesn't load the whole file on memory.

    Returns
    -------
    pyopenms.OnDiskMSExperiment or pyopenms.MSExperiment
    """
    if on_disc:
        try:
            exp_reader = pyopenms.OnDiscMSExperiment()
            exp_reader.openFile(path)
        except RuntimeError:
            msg = "{} is not an indexed mzML file, switching to MSExperiment"
            print(msg.format(path))
            exp_reader = pyopenms.MSExperiment()
            pyopenms.MzMLFile().load(path, exp_reader)
    else:
        exp_reader = pyopenms.MSExperiment()
        pyopenms.MzMLFile().load(path, exp_reader)
    return exp_reader
    def test_extractor(self):
        targeted = pyopenms.TargetedExperiment()
        tramlfile = pyopenms.TraMLFile()
        tramlfile.load(self.filename, targeted)

        exp = pyopenms.MSExperiment()
        pyopenms.MzMLFile().load(self.filename_mzml, exp)

        trafo = pyopenms.TransformationDescription()

        tmp_out = pyopenms.MSExperiment()
        extractor = pyopenms.ChromatogramExtractor()
        extractor.extractChromatograms(exp, tmp_out, targeted, 10, False,
                                       trafo, -1, "tophat")

        # Basically test that the output is non-zero (e.g. the data is
        # correctly relayed to python)
        # The functionality is not tested here!
        self.assertEqual(len(tmp_out.getChromatograms()),
                         len(targeted.getTransitions()))
        self.assertNotEqual(len(tmp_out.getChromatograms()), 0)
        self.assertEqual(tmp_out.getChromatograms()[0].size(), exp.size())
        self.assertNotEqual(tmp_out.getChromatograms()[0].size(), 0)
        self.assertNotEqual(tmp_out.getChromatograms()[0][0].getRT(), 0)
        self.assertNotEqual(tmp_out.getChromatograms()[0][0].getIntensity(), 0)
示例#4
0
    def main(self):
        #after path_parsing method we have self.src_full_name_list
        print("Peak Picking implementation")

        for f in get_list_full_names(self.src):

            # to prepare(init) empty list and entity;
            self.init_entity(**self.kw)

            print("source file:", f)
            
            input_map = oms.MSExperiment() # the 1st step: load map;

            oms.MzMLFile().load(f, input_map)

            centroid_out_map = oms.MSExperiment()

            # the 2nd step: apply_ffm;
            self.pp.entity.pickExperiment(input_map, centroid_out_map)
            
            centroid_out_map.updateRanges()

            # the 3d step: is store result into file:
            #convert_src_to_dst_file_name(src, dst, suffix_dst_files, ext_dst_files)
            dst_full_file_name = os.path.join(self.dst,\
                convert_src_to_dst_file_name(f,
                                            self.dst,
                                            self.suffix_dst_files,
                                            self.ext_dst_files
                                            ) )   #call 'global' function;
            #print("dst=",dst_full_file_name)
            oms.MzMLFile().store(dst_full_file_name, centroid_out_map)
            
            print("Picked data stored into:", dst_full_file_name)
示例#5
0
def main():

    # register command line arguments
    model = CTDModel(
        name='NameOfThePyTOPPTool',  # required
        version='1.0',  # required
        description=
        'This is an example tool how to write pyTOPP tools compatible with the OpenMS workflow ecosystem.',
        manual='RTF',
        docurl='http://dummy.url/docurl.html',
        category='Example',
        executableName='exampletool',
        executablePath='/path/to/exec/exampletool-1.0/exampletool')

    # Register in / out etc. with CTDModel
    model.add(
        'input',
        required=True,
        type='input-file',
        is_list=False,
        file_formats=['mzML'],  # filename restrictions
        description='Input file')

    model.add(
        'output',
        required=True,
        type='output-file',
        is_list=False,
        file_formats=['mzML'],  # filename restrictions
        description='Output file')

    defaults = pms.PeakPickerHiRes().getDefaults()

    # expose algorithm parameters in command line options
    addParamToCTDopts(defaults, model)

    # parse command line
    # if -write_ini is provided, store model in CTD file, exit with error code 0
    # if -ini is provided, load CTD file into defaults Param object and return new model with paraneters set as defaults
    arg_dict, openms_params = parseCTDCommandLine(sys.argv, model, defaults)

    # data processing
    fh = pms.MzMLFile()
    fh.setLogType(pms.LogType.CMD)
    input_map = pms.MSExperiment()

    fh.load(arg_dict["input"], input_map)

    pp = pms.PeakPickerHiRes()
    pp.setParameters(openms_params)
    out_map = pms.MSExperiment()
    pp.pickExperiment(input_map, out_map)

    out_map = addDataProcessing(
        out_map, openms_params,
        pms.DataProcessing.ProcessingAction.PEAK_PICKING)
    fh = pms.FileHandler()
    fh.storeExperiment(arg_dict["output"], out_map)
示例#6
0
def main(options):

    # load TraML file
    targeted = pyopenms.TargetedExperiment()
    pyopenms.TraMLFile().load(options.traml_in, targeted)

    # Create empty files as input and finally as output
    empty_swath = pyopenms.MSExperiment()
    trafo = pyopenms.TransformationDescription()
    output = pyopenms.MSExperiment()

    # load input
    for infile in options.infiles:
        exp = pyopenms.MSExperiment()
        pyopenms.FileHandler().loadExperiment(infile, exp)

        transition_exp_used = pyopenms.TargetedExperiment()

        do_continue = True
        if options.is_swath:
            do_continue = pyopenms.OpenSwathHelper(
            ).checkSwathMapAndSelectTransitions(exp, targeted,
                                                transition_exp_used,
                                                options.min_upper_edge_dist)
        else:
            transition_exp_used = targeted

        if do_continue:
            # set up extractor and run
            tmp_out = pyopenms.MSExperiment()
            extractor = pyopenms.ChromatogramExtractor()
            extractor.extractChromatograms(exp, tmp_out, targeted,
                                           options.extraction_window,
                                           options.ppm, trafo,
                                           options.rt_extraction_window,
                                           options.extraction_function)
            # add all chromatograms to the output
            for chrom in tmp_out.getChromatograms():
                output.addChromatogram(chrom)

    dp = pyopenms.DataProcessing()
    pa = pyopenms.ProcessingAction().SMOOTHING
    dp.setProcessingActions(set([pa]))

    chromatograms = output.getChromatograms()
    for chrom in chromatograms:
        this_dp = chrom.getDataProcessing()
        this_dp.append(dp)
        chrom.setDataProcessing(this_dp)

    output.setChromatograms(chromatograms)

    pyopenms.MzMLFile().store(options.outfile, output)
def main(options):
    
    # generate fragmentationtype lookup
    lookup = {}
    methods = pyopenms.ActivationMethod()
    for attr in dir(methods):
        value = getattr(methods,attr)
        if isinstance(value,int):
            lookup[value] = attr
    
    print "loading MS Experiment "
    exp = pyopenms.MSExperiment()
    fh = pyopenms.FileHandler()
    fh.loadExperiment(options.infile,exp)
    
    print "checking spectra types:"
    fragmentationTypes = {}
    for s in exp:
        typ = getSpectrumType(s,lookup)
        cont = continousSpectrumCheck(s)
        fragmentationTypes[typ] = fragmentationTypes.get(typ, [] ) + [cont]


    isContinousSpectrum = {}
    for typ in fragmentationTypes:
        check = percentile75(fragmentationTypes[typ])
        isContinousSpectrum[typ] = check
        if check == True:
            print "\t" + typ + " has continous spectra data"
        else:
            print "\t" + typ + " has centroided spectra data"

    print "picking spectra"
    expNew = pyopenms.MSExperiment()
    picker = pyopenms.PeakPickerHiRes()
    for s in exp:
        typ = getSpectrumType(s,lookup)
        if isContinousSpectrum[typ] == True:
            newSpec = pyopenms.MSSpectrum()
            picker.pick(s,newSpec)
            expNew.addSpectrum(newSpec)
        else:
            expNew.addSpectrum(s)
    
    print "saving file to ",options.outfile
    mzFile = pyopenms.MzMLFile()
    fileoptions = mzFile.getOptions()
    fileoptions.setCompression(True)
    mzFile.setOptions(fileoptions)
    mzFile.store(options.outfile,expNew)
    print "finished"
示例#8
0
    def compute_bin_im(self, run: int, bin: int, dir: str = '.') -> float:
        """Computes the intensity-weighted average IM value for a given bin.

        Keyword arguments:
        run: the pass that the bin is in (1 or 2)
        bin: the bin to compute the average IM for
        dir: the directory to write and read temporary files to

        Returns: the intensity-weighted average IM value for a given bin.
        """
        exp = ms.MSExperiment()
        ms.MzMLFile().load(dir + '/b-' + str(run) + '-' + str(bin) + '.mzML',
                           exp)
        total_intensity, average_im = 0, 0

        all_points = []
        for i in range(exp.getNrSpectra()):
            spec = exp.getSpectrum(i)
            all_points.extend(util.get_spectrum_points(spec))

        for i in range(len(all_points)):
            total_intensity += all_points[i][2]

        if total_intensity != 0:
            for i in range(len(all_points)):
                average_im += all_points[i][3] * (all_points[i][2] /
                                                  total_intensity)

        return average_im
示例#9
0
    def _read_openMS_file(self, file):
        exp = pyopenms.MSExperiment()
        file.load(self._file, exp)
        file.store(self._file, exp)

        def bin_highres(df_in):
            df = df_in.groupby(df_in['mz'].round()).sum()
            I = df['I'].loc[self.mz].as_matrix()
            I[np.isnan(I)] = 0
            return I

        # TODO: change hardcoded min/max masses to be either taken from config
        # or automatically derived from the data
        self.mz = np.arange(70, 601, 1)
        rt = []
        intensities = []
        spectra = exp.getSpectra()

        print('Binning:')
        for idx, spectrum in enumerate(spectra):
            if ((idx + 1) % 100) == 0:
                print('\t{:>4} / {}'.format(idx + 1, len(spectra)))

            rt.append(spectrum.getRT())
            spectrum_df = pd.DataFrame(list(spectrum.get_peaks()),
                                       index=['mz', 'I']).T
            intensities.append(bin_highres(spectrum_df))
        self.data_raw = np.array(intensities).T
        self.rt = np.array(rt)
        self.scans_per_sec = pd.Series(self.rt.round()) \
            .value_counts().value_counts().index[0]
示例#10
0
def algorithm(chromatograms, targeted):
    # Create empty files as input and finally as output
    empty_swath = pyopenms.MSExperiment()
    trafo = pyopenms.TransformationDescription()
    output = pyopenms.FeatureMap()

    # set up featurefinder and run
    featurefinder = pyopenms.MRMFeatureFinderScoring()
    # set the correct rt use values
    scoring_params = pyopenms.MRMFeatureFinderScoring().getDefaults()
    scoring_params.setValue("Scores:use_rt_score", 'false', '')
    featurefinder.setParameters(scoring_params)
    featurefinder.pickExperiment(chromatograms, output, targeted, trafo,
                                 empty_swath)

    # get the pairs
    pairs = []
    simple_find_best_feature(output, pairs, targeted)
    pairs_corrected = pyopenms.MRMRTNormalizer().rm_outliers(pairs, 0.95, 0.6)
    pairs_corrected = [list(p) for p in pairs_corrected]

    # // store transformation, using a linear model as default
    trafo_out = pyopenms.TransformationDescription()
    trafo_out.setDataPoints(pairs_corrected)
    model_params = pyopenms.Param()
    model_params.setValue("symmetric_regression", 'false', '')
    model_type = "linear"
    trafo_out.fitModel(model_type, model_params)
    return trafo_out
示例#11
0
 def __get_mzml(self, file):
     b_content = file.bcore
     if self.ext == 'raw':
         self.tf = store_byte_in_tmp(
             b_content,
             prefix=self.fname,
             suffix='.RAW',
             directory=self.target_dir.absolute().as_posix()
         )
         self.cmd_msconvert = self.__build_cmd_msconvert()
         self.__run_cmd()
     elif self.ext == 'mzml':
         self.tf = store_byte_in_tmp(
             b_content,
             prefix=self.fname,
             suffix='.mzML',
             directory=self.target_dir.absolute().as_posix()
         )
     elif self.ext == 'mzxml':
         self.tf = store_byte_in_tmp(
             b_content,
             prefix=self.fname,
             suffix='.mzXML',
             directory=self.target_dir.absolute().as_posix()
         )
         exp = pyopenms.MSExperiment()
         pyopenms.MzXMLFile().load(self.tf.name, exp)
         target_path = self.__get_mzml_path().absolute().as_posix()
         pyopenms.MzMLFile().store(target_path, exp)
示例#12
0
    def get_spectrum(self, filepath, retention_time):
        #  See: https://pypi.org/project/pyopenms/
        peak_list = []
        mz_list = []
        rt_list = []
        intensity_list = []
        path = str.encode(filepath)

        try:
            exp = pyopenms.MSExperiment()
            pyopenms.FileHandler().loadExperiment(path, exp)
        except Exception as error:
            print(str(error))
        for spectrum in exp:
            rt = str(spectrum.getRT())
            # So either no rt param passed, or the decimal input exists in the start of the mzml rt float (no rounding)
            if not retention_time or retention_time in rt:
                if rt not in rt_list:
                    rt_list.append(rt)
                for peak in spectrum:
                    mz = peak.getMZ()
                    intensity = peak.getIntensity()
                    peak_list.append({"intensity": intensity, "mz": mz})
                    mz_list.append(mz)
                    intensity_list.append(intensity)

        return peak_list, mz_list, rt_list, intensity_list
示例#13
0
        def run_MSExperiment_copy(self):
            p = pyopenms.FileHandler()
            e1 = pyopenms.MSExperiment()
            p.loadExperiment(self.testfile, e1)
            show_mem("data loaded")

            specs = list(e1)
            for s in specs:
                for _ in range(10):
                    e1.addSpectrum(s)

            li = []
            print("please be patient :")
            N = 5
            for k in range(N):
                sys.stdout.flush()
                for __ in range(400):
                    e2 = copy.copy(e1)
                    li.append(e2)
                    e1 = copy.copy(e2)
                    li.append(e1)
                print(int(100.0 * (k + 1) / N), "%")

            print("\n")
            show_mem("experiment list generated")
            del li
            del e1
            del e2
            del p
            show_mem("experiment list deleted")
    def testFunction(self):

        for method in [self.eightplex, self.fourplex, self.tmt]:
            inst = pyopenms.IsobaricChannelExtractor(method)
            map1 = pyopenms.ConsensusMap()
            exp = pyopenms.MSExperiment()
            assert inst.extractChannels is not None
示例#15
0
def maxq(ctx, filename, zipurl, rawname):
    """Calculate all possible metrics for these files. These data sources will be included in set metrics."""
    exp = oms.MSExperiment()
    oms.MzMLFile().load(click.format_filename(filename), exp)
    rq = basicqc.getBasicQuality(exp)

    ms2num = 0
    for x in rq.qualityMetrics:
        if x.name == "Number of MS2 spectra":
            ms2num = x.value

    if ms2num < 1:
        logging.warn(
            "We seem to have found no MS2 spectra which is unlikely to be true since you have also given some identifications. \
                We continue with symbolic value of 1 for the number of MS2 spectra, \
                however this means some metrics will invariably be incorrect!\
                Please make sure, we have the right inputs.")
        ms2num = 1

    try:
        mq, params = idqcmq.loadMQZippedResults(zipurl)
        if not rawname:
            logging.warning("Infering rawname from mzML")
            rawname = basename(
                exp.getExperimentalSettings().getSourceFiles()
                [0].getNameOfFile().decode())  # TODO split extensions

        rq.qualityMetrics.extend(
            idqcmq.getMQMetrics(rawname, params, mq, ms2num))
        rqs.append(rq)
    except:
        logging.warn("Retrieving any results from the URL failed.")

    finale()
示例#16
0
        def run_fileformats_io(self):
            p = pyopenms.FileHandler()
            e = pyopenms.MSExperiment()

            p.loadExperiment(self.testfile, e)
            show_mem("after load mzXML")

            ct = pyopenms.ChromatogramTools()
            ct.convertChromatogramsToSpectra(e)
            p.storeExperiment(self.testfile, e)
            show_mem("after store mzXML")

            p.loadExperiment(self.testfile, e)
            show_mem("after load mzXML")

            p = pyopenms.FileHandler()
            ct.convertSpectraToChromatograms(e, True)
            p.storeExperiment("../test.mzML".encode(), e)
            show_mem("after store mzML")
            p.loadExperiment("../test.mzML".encode(), e)
            show_mem("after load mzML")

            p = pyopenms.FileHandler()
            ct.convertChromatogramsToSpectra(e)
            p.storeExperiment("../test.mzData".encode(), e)
            show_mem("after store mzData")
            p.loadExperiment("../test.mzData".encode(), e)
            show_mem("after load mzData")

            del e
            del p
            del ct
示例#17
0
    def pick_experiment(self, exp: ms.MSExperiment, peak_radius: int = 1, window_radius: float = 0.015,
            pp_mode: str = 'int', min_int_mult: float = 0.10, strict: bool = True) -> ms.MSExperiment():
        """Peak picks an experiment.

        Keyword arguments:
        exp: the experiment to peak pick
        peak_radius: the minimum peak radius of a peak set
        window_radius: the maximum m/z window radius of a peak set
        pp_mode: the mode to use ('ltr' or 'int')
        min_int_mult: a multiplier to the maximum peak intensity in a set (for differentiating
            between signal and noise)
        strict: if False, allow a single increase in intensity in either direction

        Returns: the peak picked experiment.
        """
        exp.sortSpectra()
        spectra = exp.getSpectra()

        picked_exp = ms.MSExperiment()
        for spec in spectra:
            if spec.getMSLevel() != 1:
                continue
            picked_exp.addSpectrum(self.pick_spectra(spec, peak_radius, window_radius, pp_mode, min_int_mult, strict))

        return picked_exp
示例#18
0
def main(options):
    precursor_tolerance = options.precursor_tolerance
    product_tolerance = options.product_tolerance
    out = options.outfile
    chromat_in = options.infile
    traml_in = options.traml_in

    # precursor_tolerance = 0.05
    # product_tolerance = 0.05
    # out = "/tmp/out.mzML"
    # chromat_in = "../source/TEST/TOPP/MRMMapping_input.chrom.mzML"
    # traml_in = "../source/TEST/TOPP/MRMMapping_input.TraML"

    ff = pyopenms.MRMFeatureFinderScoring()
    chromatogram_map = pyopenms.MSExperiment()
    fh = pyopenms.FileHandler()
    fh.loadExperiment(chromat_in, chromatogram_map)
    targeted = pyopenms.TargetedExperiment()
    tramlfile = pyopenms.TraMLFile()
    tramlfile.load(traml_in, targeted)

    output = algorithm(chromatogram_map, targeted, precursor_tolerance,
                       product_tolerance)

    pyopenms.MzMLFile().store(out, output)
示例#19
0
def _write_spectra_mzml(filename: str, spectra: Iterable[sus.MsmsSpectrum]) \
        -> None:
    """
    Write the given spectra to an mzML file.

    Parameters
    ----------
    filename : str
        The mzML file name where the spectra will be written.
    spectra : Iterable[sus.MsmsSpectrum]
        The spectra to be written to the mzML file.
    """
    experiment = pyopenms.MSExperiment()
    for spectrum in tqdm.tqdm(spectra, desc='Spectra written', unit='spectra'):
        mzml_spectrum = pyopenms.MSSpectrum()
        mzml_spectrum.setMSLevel(2)
        mzml_spectrum.setNativeID(spectrum.identifier)
        precursor = pyopenms.Precursor()
        precursor.setMZ(spectrum.precursor_mz)
        precursor.setCharge(spectrum.precursor_charge)
        mzml_spectrum.setPrecursors([precursor])
        mzml_spectrum.set_peaks([spectrum.mz, spectrum.intensity])
        if hasattr(spectrum, 'retention_time'):
            mzml_spectrum.setRT(spectrum.retention_time)
        if hasattr(spectrum, 'filename'):
            mzml_spectrum.setMetaValue('filename',
                                       str.encode(spectrum.filename))
        if hasattr(spectrum, 'scan'):
            mzml_spectrum.setMetaValue('scan', str.encode(str(spectrum.scan)))
        if hasattr(spectrum, 'cluster'):
            mzml_spectrum.setMetaValue('cluster',
                                       str.encode(str(spectrum.cluster)))
        experiment.addSpectrum(mzml_spectrum)
    pyopenms.MzMLFile().store(filename, experiment)
def main(options):

    # generate fragmentationtype lookup
    lookup = {}
    methods = pyopenms.ActivationMethod()
    for attr in dir(methods):
        value = getattr(methods, attr)
        if isinstance(value, int):
            lookup[value] = attr

    print "loading MS Experiment "
    exp = pyopenms.MSExperiment()
    fh = pyopenms.FileHandler()
    fh.loadExperiment(options.infile, exp)

    print "getting fragment spectra types:"
    fragmentationTypes = set()
    for s in exp:
        if s.getMSLevel() != 1:
            typ = getSpectrumType(s, lookup)
            fragmentationTypes.add(typ)

    # writing new files
    filepart, suffix = os.path.splitext(options.outfile)
    filenames = []
    for typ in fragmentationTypes:
        expNew = pyopenms.MSExperiment()
        for s in exp:
            if s.getMSLevel() == 1 or getSpectrumType(s, lookup) == typ:
                expNew.addSpectrum(s)

        print "saving file"
        mzFile = pyopenms.MzMLFile()
        fileoptions = mzFile.getOptions()
        fileoptions.setCompression(True)
        mzFile.setOptions(fileoptions)
        name = filepart + "_" + typ + ".mzML"
        filenames.append(name)
        mzFile.store(name, expNew)
        del expNew

    print "create zip file", options.outfile
    zipFile = zipfile.ZipFile(options.outfile, "w", allowZip64=True)
    for name in filenames:
        zipFile.write(name, os.path.basename(name))
    zipFile.close()
    print "finished"
示例#21
0
def read_mzml(infile):
    # init variables
    mzml_file = oms.MzMLFile()
    exp = oms.MSExperiment()

    # load spectra into exp
    mzml_file.load(infile, exp)
    return (exp)
示例#22
0
 def toMSExperiment(self):
     """converts peakmap to pyopenms.MSExperiment"""
     exp = pyopenms.MSExperiment()
     for spec in self.spectra:
         exp.push_back(spec.toMSSpectrum())
     exp.updateRanges()
     exp.setLoadedFilePath(self.meta.get("source", ""))
     return exp
示例#23
0
def main(options):

    # generate fragmentationtype lookup
    lookup = {}
    methods = pyopenms.ActivationMethod()
    for attr in dir(methods):
        value = getattr(methods, attr)
        if isinstance(value, int):
            lookup[value] = attr

    print "loading MS Experiment "
    exp = pyopenms.MSExperiment()
    fh = pyopenms.FileHandler()
    fh.loadExperiment(options.infile, exp)

    print "getting fragment spectra types:"
    fragmentationTypes = {}
    for s in exp:
        if s.getMSLevel() != 1:
            typ = getSpectrumType(s, lookup)
            fragmentationTypes[typ] = fragmentationTypes.get(typ, 0) + 1
    print "found the following spectra types:"
    for typ in fragmentationTypes:
        print "typ '" + typ + "' with " + str(
            fragmentationTypes[typ]) + " spectra"

    print "extracting all " + str(
        fragmentationTypes.get(
            options.extractType,
            0)) + " spectra with type " + options.extractType

    expNew = pyopenms.MSExperiment()
    for s in exp:
        if s.getMSLevel() == 1 or getSpectrumType(
                s, lookup) == options.extractType:
            expNew.addSpectrum(s)

    print "saving file"
    mzFile = pyopenms.MzMLFile()
    fileoptions = mzFile.getOptions()
    fileoptions.setCompression(True)
    mzFile.setOptions(fileoptions)

    mzFile.store(options.outfile, expNew)

    print "finished"
示例#24
0
def basic(filename):
    """Calculate the basic metrics available from virtually every mzML file."""
    exp = oms.MSExperiment()
    oms.MzMLFile().load(click.format_filename(filename), exp)
    rq = basicqc.getBasicQuality(exp)
    rqs.append(rq)

    finale()
示例#25
0
    def open_profile_mzml(self):

        self._log('Loading profile data from `%s`.' % self.profile_mzml)

        # As I understand this belongs to the peak picking
        # hence I moved here, we don't need these attributes in __init__
        self.profile_map = oms.MSExperiment()
        oms.MzMLFile().load(self.profile_mzml, self.profile_map)
示例#26
0
    def test_acquisitioninfomemberaccess(self):
        exp = pyopenms.MSExperiment()
        pyopenms.MzMLFile().load(self.filename_mzml, exp)

        # Basically test that the output is non-zero (e.g. the data is
        # correctly relayed to python)
        # The functionality is not tested here!

        # starting point
        self.assertEqual(exp[0].getAcquisitionInfo().size(), 1)
        self.assertNotEqual(exp[0].getAcquisitionInfo().size(), 0)

        # metainfo
        exp[0].getAcquisitionInfo().size()  # is 1
        self.assertEqual(exp[0].getAcquisitionInfo()[0].isMetaEmpty(),
                         True)  # is True

        spectra = exp.getSpectra()
        aqis = spectra[0].getAcquisitionInfo()
        aqi = aqis[0]  # get a copy
        aqi.setMetaValue('key', 420)  # modify it
        aqis[0] = aqi  # and set entry
        spectra[0].setAcquisitionInfo(aqis)
        exp.setSpectra(spectra)
        self.assertEqual(exp[0].getAcquisitionInfo()[0].getMetaValue('key'),
                         420)  # should be 420

        acin = pyopenms.Acquisition()
        acin.setMetaValue('key', 42)
        self.assertEqual(acin.getMetaValue('key'), 42)  # is 42
        self.assertEqual(acin.isMetaEmpty(), False)  # is False

        # list/vector assignment
        magicnumber = 3
        neac = pyopenms.AcquisitionInfo()
        for i in range(0, magicnumber):
            neac.push_back(acin)

        self.assertEqual(neac.size(), magicnumber)  # is magicnumber

        # iteration
        for i in neac:
            self.assertEqual(i.isMetaEmpty(), False)  # always is False

        # accession already tested in 2nd section
        tmp = exp.getSpectra()
        tmp[0].setAcquisitionInfo(neac)
        exp.setSpectra(tmp)

        self.assertEqual(exp[0].getAcquisitionInfo().size(),
                         magicnumber)  # should be magicnumber

        for i in exp[0].getAcquisitionInfo():
            self.assertEqual(i.isMetaEmpty(), False)  # should always be False

        # resize
        neac.resize(0)
        self.assertEqual(neac.size(), 0)
示例#27
0
def addDataProcessing(what, params):
    if isinstance(what, pms.MSExperiment):
        result = pms.MSExperiment()
        for spec in what:
            spec = _addDataProcessing(spec, params)
            result.push_back(spec)
    else:
        result = _addDataProcessing(what, params)
    return result
示例#28
0
文件: common.py 项目: Roestlab/OpenMS
def addDataProcessing(obj, params, action):
    if isinstance(obj, pms.MSExperiment):
        result = pms.MSExperiment()
        for spec in obj:
            spec = _addDataProcessing(spec, params, action)
            result.addSpectrum(spec)
    else:
        result = _addDataProcessing(obj, params, action)
    return result
示例#29
0
 def pickPeakMap(self, pm, showProgress=False):
     assert isinstance(pm, PeakMap)
     eout = pyopenms.MSExperiment()
     if showProgress:
         self.pp.setLogType(pyopenms.LogType.CMD)
     else:
         self.pp.setLogType(pyopenms.LogType.NONE)
     self.pp.pickExperiment(pm.toMSExperiment(), eout)
     return PeakMap.fromMSExperiment(eout)
示例#30
0
 def reset(self) -> None:
     """Resets the feature finder to its default state."""
     self.num_bins, self.bin_size = 0, 0
     self.im_start, self.im_end = 0, 0
     self.im_delta, self.im_offset = 0, 0
     self.im_scan_nums = [
         [], []
     ]  # Keep the intensity-weighted average IM value for each bin
     self.exps = [[], [ms.MSExperiment()]]  # To "cache" mzML writes