How to use the pythoms.mzml.mzML function in pythoms

To help you get started, we’ve selected a few pythoms examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github larsyunker / PythoMS / tests.py View on Github external
def test_mzml(self):
        mzml = mzML(
            validation_path / 'MultiTest',
            verbose=False
        )
        self.assertEqual(  # check that the correct function keys were pulled
            mzml.functions.keys(),
            {1, 3, 4},
        )

        @mzml.foreachchrom
        def testperchrom(chromatogram):
            attr = branch_attributes(chromatogram)
            return attr['id']

        self.assertEqual(  # test chromatogram decorator
            testperchrom(),
            [u'TIC', u'SRM SIC Q1=200 Q3=100 function=2 offset=0']
github larsyunker / PythoMS / isotope pattern overlay.py View on Github external
}
    try:
        sys.stdout.write('Using figure preset "%s"\n' % (setting))
        sys.stdout.flush()
        return ipsetting[typ]
    except KeyError:
        raise KeyError('\nThe specified figure setting "%s" is not defined.\nPlease check your spelling' % setting)


if __name__ == '__main__':
    os.chdir(curdir)  # change to current working directory

    keywords = presets(setting)  # pull preset kwargs

    if spectrum.lower().endswith('.mzml.gz') or spectrum.lower().endswith('.raw'):  # if supplied with a mass spec file
        mzml = mzML(spectrum)
        exp = mzml.sum_scans()
        keywords.update({'outname': mzml.filename.split('.')[0]})  # set default output filename

    else:  # otherwise assume that it is an excel file
        xlfile = XLSX(spectrum, verbose=True)  # load excel file
        if sheetname is None:  # otherwise use the first sheet
            sheetname = xlfile.wb.sheetnames[0]
        exp = xlfile.pullspectrum(sheetname, skiplines=skiplines)[0]  # load spectrum from first sheet in workbook
        keywords.update({  # set default output filename
            'outname': f'{xlfile.bookname[:-5]} ({sheetname})',
        })

    keywords.update(override)  # apply any user overrides
    plot_mass_spectrum(exp, simdict, **keywords)
    import gc
github larsyunker / PythoMS / PyRSIR.py View on Github external
newpeaks = False
    if rd is True:
        newsp = {}
        sum_spectra = None
        for key in sp:  # checks whether there is a MS species that does not have raw data
            if 'raw' not in sp[key]:
                newsp[key] = sp[key]  # create references in the namespace
        if len(newsp) is not 0:
            newpeaks = True
            if verbose is True:
                sys.stdout.write('Some peaks are not in the raw data, extracting these from raw file.\n')
            ips = xlfile.pullmultispectrum(
                'Isotope Patterns')  # pull predefined isotope patterns and add them to species
            for species in ips:  # set spectrum list
                sp[species]['spectrum'] = [ips[species]['x'], ips[species]['y']]
            mzml = mzML(filename)  # load mzML class
            sp = prepformula(sp)  # prep formula etc for summing
            newsp = prepformula(newsp)  # prep formula species for summing
            for species in newsp:
                if 'spectrum' not in newsp[species]:
                    newsp[species]['spectrum'] = Spectrum(3, newsp[species]['bounds'][0], newsp[species]['bounds'][1])
            newsp = mzml.pull_species_data(newsp)  # pull data
        else:
            if verbose is True:
                sys.stdout.write('No new peaks were specified. Proceeding directly to summing and normalization.\n')

    if rd is False:  # if no raw data is present, process mzML file
        mzml = mzML(filename, verbose=verbose)  # load mzML class
        sp = prepformula(sp)
        sp, sum_spectra = mzml.pull_species_data(sp, combine_spectra)  # pull relevant data from mzML
        chroms = mzml.pull_chromatograms()  # pull chromatograms from mzML
        rtime = {}
github larsyunker / PythoMS / ED-ESI plot.py View on Github external
plt.savefig('../{OUTFILE}.png'.format(OUTFILE=outputFile + str(minFilter)), bbox_inches='tight')


##################################

###############################################################
# MAIN
###############################################################
# _mzML processing variables
filename = 'HZ-140516_HOTKEYMSMS 1376 II.raw'  # raw or mzml file name
fillzeros = True  # fills spectrum with zeros
decpl = 1  # number of decimal places to track
mzrange = None  # mzrange to track
sr = 'all'  # scan range to track
mzml = mzML(filename, verbose=True)

# EDESI Plot Production variable
minFilter = 20  # minFilter intensity value
threshold = 1156  # threshold of peak height for Breakdown tracing
plotBreakdown = True  # Construct Plot with Breakdown?
plotZoom = True  # Construct Plot with Zoom in region of interest? (Autozoom)

msmsfns = []
for func in mzml.functions:  # identify MSMS functions in the provided file
    if mzml.functions[func]['type'] == 'MS' and mzml.functions[func]['level'] > 1:
        msmsfns.append(func)
if len(msmsfns) > 1:  # if there is more than one msms function, ask the user which one to process
    sys.stdout.write(
        'More than one MS/MS function is contained in this mzML file. Please indicate which one you wish to process:\nFunction\ttarget\n')
    for func in msmsfns:
        sys.stdout.write('%d\t%.3f\n' % (func, mzml.functions[func]['target']))
github larsyunker / PythoMS / PyRSIR.py View on Github external
'Isotope Patterns')  # pull predefined isotope patterns and add them to species
            for species in ips:  # set spectrum list
                sp[species]['spectrum'] = [ips[species]['x'], ips[species]['y']]
            mzml = mzML(filename)  # load mzML class
            sp = prepformula(sp)  # prep formula etc for summing
            newsp = prepformula(newsp)  # prep formula species for summing
            for species in newsp:
                if 'spectrum' not in newsp[species]:
                    newsp[species]['spectrum'] = Spectrum(3, newsp[species]['bounds'][0], newsp[species]['bounds'][1])
            newsp = mzml.pull_species_data(newsp)  # pull data
        else:
            if verbose is True:
                sys.stdout.write('No new peaks were specified. Proceeding directly to summing and normalization.\n')

    if rd is False:  # if no raw data is present, process mzML file
        mzml = mzML(filename, verbose=verbose)  # load mzML class
        sp = prepformula(sp)
        sp, sum_spectra = mzml.pull_species_data(sp, combine_spectra)  # pull relevant data from mzML
        chroms = mzml.pull_chromatograms()  # pull chromatograms from mzML
        rtime = {}
        tic = {}
        for key in sp:  # compare predicted isotope patterns to the real spectrum and save standard error of the regression
            func = sp[key]['function']
            if mzml.functions[func]['type'] == 'MS':  # determine mode key
                if combine_spectra is True:
                    sp[key]['spectrum'] = sum_spectra[sp[key]['function']].trim(
                        xbounds=sp[key]['bounds'])  # extract the spectrum object
                mode = 'raw' + mzml.functions[func]['mode']
            if mzml.functions[func]['type'] == 'UV':
                mode = 'rawUV'
            if mode not in rtime:  # if rtime and tic have not been pulled from that function
                rtime[mode] = mzml.functions[func]['timepoints']
github larsyunker / PythoMS / spectrum binner.py View on Github external
def bin_spectra(filename, start=None, end=None, save=True, dec=3):
    """
    Sums spectra from raw file and outputs to excel file

    :param filename: raw or mzML filename
    :param start: start scan (None will default to 1)
    :param end: end scan (None will default to the last scan)
    :param save: whether to save into an excel document (if a string is provided, that filename will be used)
    :param dec: decimal places to track when binning the spectrum
    :return: paired x, summed y lists
    """

    st = ScriptTime()
    st.printstart()
    mzml = mzML(filename)  # create mzML object
    if start is None:
        start = mzml.functions[1]['sr'][0] + 1
    if end is None:
        end = mzml.functions[1]['sr'][1] + 1
    x, y = mzml.sum_scans(
        start=start,
        end=end,
        dec=dec,
    )
    if save is not False:
        if type(save) == str:  # if a filename was provided for the Excel file
            xlfile = XLSX(save, create=True)
        else:  # otherwise use the mzML filename
            xlfile = XLSX(filename, create=True)
        xlfile.writespectrum(  # write the spectrum to file
            x,
github larsyunker / PythoMS / pythoms / mzml.py View on Github external
if attr['index'] > end:
                break
            if self.verbose is True and mute is False:
                prog.write(attr['index'] + 1)
            if start <= attr['index'] <= end:  # if within the specified bounds
                x, y = extract_spectrum(spectrum)  # pull spectrum
                spec.add_spectrum(x, y)  # add spectrum to Spectrum object
        out = spec.trim()
        if self.verbose is True and mute is False:
            prog.fin()
        return out


if __name__ == '__main__':
    filename = 'MultiTest'
    mzml = mzML(filename, verbose=True, ftt=True)
    # sp = {