Skip to content

MSP file export in Python #7

@tobigithub

Description

@tobigithub

Here is the MSP file exporter that reads the accuratemass.jdx from plotms

### -----------------------------------------------------------------------
### MSP spectrum file exporter in NIST MSP format
### (Tobias Kind // Fiehnlab 2020 // CC-BY license) v1.1 Dec 2020
###
### format the MS2 file for accurate mass output and meta-data inclusion
### requires as input: metadata.txt in input subfolder
### reads: accuratemass.jdx from plotms
### exports: result-ms2.msp
### -----------------------------------------------------------------------

# === metadata.txt has 8 pre-defined lines ====================================
# Name: Valine
# Precursor_type: [M+H]+
# Spectrum_type: MS2
# PrecursorMZ: 118.0863
# Ion_mode: P
# InChIKey: KZSNJWFQEVHDMF-UHFFFAOYSA-N
# Formula: C5H11NO2
# Comments: protomer of valine [M+H]+
#==============================================================================

import os
import pathlib

### get current file path
workPath = os.getcwd() + '/'
os.sys.path.append(workPath)

### should not contain CR/LF at the end of file
### multiple CR/LF are not handled or need to be stripped
metadataFilename = ('input/metadata.txt')
metadataHandle = workPath + metadataFilename
metadataText = pathlib.Path(metadataHandle).read_text()

# read spectrum file from plotms
spectrumFilename = ('accuratemass.jdx')
spectrumHandle = workPath + spectrumFilename
spectrumText = pathlib.Path(spectrumHandle).read_text()

# get number of peaks from accuratemass.jdx (element [5] in line 6)
numPeaks = spectrumText.split('\n')[5].split('=')[1]

# get mz-abd pairs and add all peaks and annotations
peakPairs = spectrumText.split('\n')[7:int(numPeaks)+7]
peakPairsText = '\n'.join(peakPairs)

# open file for writing new MSP (NIST format)
exportFilename = ('result-ms2.msp')
exportHandle = workPath + exportFilename
with open(exportHandle, 'w+') as f:
    # write complete metadata block
    f.write(metadataText)
    # add number of peaks
    numPeaksText = 'NumPeaks: ' + str(numPeaks) +'\n'
    f.write(numPeaksText)
    # write m/z - abundance pairs with annotation
    f.write(peakPairsText)
    # close the file
    f.close()

# Program finished

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions