Skill Tracer
Skills › Scientific Agent Skills › matchms › importing_exporting.md

importing_exporting.md

349 lines · skills/matchms/references/importing_exporting.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Importing and Exporting (matchms 0.33.1)
2
3Use this reference for file-format selection, return types, streaming behavior,
4and safe serialization. The authoritative APIs are the matchms
5[`importing`](https://matchms.readthedocs.io/en/latest/api/matchms.importing.html)
6and
7[`exporting`](https://matchms.readthedocs.io/en/latest/api/matchms.exporting.html)
8packages.
9

Importing and Exporting (matchms 0.33.1)

Use this reference for file-format selection, return types, streaming behavior, and safe serialization. The authoritative APIs are the matchms [importing](https://matchms.readthedocs.io/en/latest/api/matchms.importing.html) and [exporting](https://matchms.readthedocs.io/en/latest/api/matchms.exporting.html) packages.

Raw lines 1 to 9
10## Recommended Entry Points
12Use extension-based helpers for ordinary local files:
14```python
15from matchms.importing import load_spectra
16from matchms.exporting import save_spectra
18spectra = list(load_spectra("library.msp"))
19save_spectra(spectra, "cleaned.mgf")
20```
22`load_spectra()` supports mzML, mzXML, MGF, MSP, JSON, and `.pickle`.
23`save_spectra()` supports MGF, MSP, JSON, and `.pickle` in 0.33.1. Use
24format-specific functions when you need an MS level, file-like MGF input,
25mzSpecLib output, or precise writer options.
27`save_spectra()` refuses to overwrite an existing output unless
28`append=True`, and append mode is restricted to MGF and MSP. This makes it
29safer than direct writers, whose MGF/MSP defaults are append mode.

Recommended Entry Points

Use extension-based helpers for ordinary local files:

from matchms.importing import load_spectra
from matchms.exporting import save_spectra

spectra = list(load_spectra("library.msp"))
save_spectra(spectra, "cleaned.mgf")

load_spectra() supports mzML, mzXML, MGF, MSP, JSON, and .pickle. save_spectra() supports MGF, MSP, JSON, and .pickle in 0.33.1. Use format-specific functions when you need an MS level, file-like MGF input, mzSpecLib output, or precise writer options.

save_spectra() refuses to overwrite an existing output unless append=True, and append mode is restricted to MGF and MSP. This makes it safer than direct writers, whose MGF/MSP defaults are append mode.

Raw lines 10 to 30
31## Import Matrix

Import Matrix

Raw lines 31 to 32
33### MGF
35```python
36from matchms.importing import load_from_mgf
38spectra = list(load_from_mgf("queries.mgf"))
39```
41Signature:
43```text
44load_from_mgf(filename: str | Path | TextIO,
45 metadata_harmonization: bool = True) -> Generator[Spectrum]
46```
48MGF is a practical interchange format for centroided MS/MS spectra and supports
49streaming iteration. It can also read an already-open text handle:
51```python
52with open("queries.mgf", encoding="utf-8") as handle:
53 spectra = list(load_from_mgf(handle))
54```

MGF

from matchms.importing import load_from_mgf

spectra = list(load_from_mgf("queries.mgf"))

Signature:

load_from_mgf(filename: str | Path | TextIO,
              metadata_harmonization: bool = True) -> Generator[Spectrum]

MGF is a practical interchange format for centroided MS/MS spectra and supports streaming iteration. It can also read an already-open text handle:

with open("queries.mgf", encoding="utf-8") as handle:
    spectra = list(load_from_mgf(handle))
Raw lines 33 to 55
56### MSP
58```python
59from matchms.importing import load_from_msp
61library = list(load_from_msp("library.msp"))
62```
64Signature:
66```text
67load_from_msp(filename: str,
68 metadata_harmonization: bool = True) -> Generator[Spectrum]
69```
71MSP is common for reference libraries. Matchms 0.29+ includes support for
72GOLM-style MSP data, but source metadata still varies substantially by library.

MSP

from matchms.importing import load_from_msp

library = list(load_from_msp("library.msp"))

Signature:

load_from_msp(filename: str,
              metadata_harmonization: bool = True) -> Generator[Spectrum]

MSP is common for reference libraries. Matchms 0.29+ includes support for GOLM-style MSP data, but source metadata still varies substantially by library.

Raw lines 56 to 73
74### mzML and mzXML
76```python
77from matchms.importing import load_from_mzml, load_from_mzxml
79ms2 = list(load_from_mzml("sample.mzML", ms_level=2))
80ms1 = list(load_from_mzxml("legacy.mzXML", ms_level=1))
81```
83Signatures:
85```text
86load_from_mzml(filename: str | Path, ms_level: int = 2,
87 metadata_harmonization: bool = True) -> Generator[Spectrum]
88load_from_mzxml(filename: str | Path, ms_level: int = 2,
89 metadata_harmonization: bool = True) -> Generator[Spectrum]
90```
92These readers select one MS level. For chromatograms, binary arrays beyond the
93Spectrum abstraction, vendor-specific metadata, or more complex raw-data
94parsing, use pyteomics, pymzML, or pyopenms.

mzML and mzXML

from matchms.importing import load_from_mzml, load_from_mzxml

ms2 = list(load_from_mzml("sample.mzML", ms_level=2))
ms1 = list(load_from_mzxml("legacy.mzXML", ms_level=1))

Signatures:

load_from_mzml(filename: str | Path, ms_level: int = 2,
               metadata_harmonization: bool = True) -> Generator[Spectrum]
load_from_mzxml(filename: str | Path, ms_level: int = 2,
                metadata_harmonization: bool = True) -> Generator[Spectrum]

These readers select one MS level. For chromatograms, binary arrays beyond the Spectrum abstraction, vendor-specific metadata, or more complex raw-data parsing, use pyteomics, pymzML, or pyopenms.

Raw lines 74 to 95
96### JSON
98```python
99from matchms.importing import load_from_json
101spectra = load_from_json("spectra.json")
102```
104Signature:
106```text
107load_from_json(filename: str,
108 metadata_harmonization: bool = True) -> list[Spectrum]
109```
111The JSON reader returns a list, not a generator. It supports matchms JSON and
112GNPS-style spectral-library JSON and skips spectra with zero peaks.

JSON

from matchms.importing import load_from_json

spectra = load_from_json("spectra.json")

Signature:

load_from_json(filename: str,
               metadata_harmonization: bool = True) -> list[Spectrum]

The JSON reader returns a list, not a generator. It supports matchms JSON and GNPS-style spectral-library JSON and skips spectra with zero peaks.

Raw lines 96 to 113
114### Metabolomics USI
116```python
117from matchms.importing import load_from_usi
119spectrum = load_from_usi(
120 "mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00000424840"
122```
124Signature:
126```text
127load_from_usi(
128 usi: str,
129 server: str = "https://metabolomics-usi.gnps2.org",
130 metadata_harmonization: bool = True,
132```
134The 0.33.1 helper makes an unauthenticated GET to
135`https://metabolomics-usi.gnps2.org/json/?usi1=<USI>` with a 10-second timeout.
136It expects one JSON object with nonempty `peaks` pairs and `precursor_mz`; there
137is no pagination. It returns one `Spectrum` or `None`, not a generator.
138Only `usi`, `server`, and `precursor_mz` are retained as metadata: the resolver
139also returns fields such as `precursor_charge` and `splash`, which the helper
140does not retain. Save the raw response separately when those fields matter.
142The helper handles some invalid/404 responses with `None` but does not fully
143validate HTTP/schema failures; request, header, or malformed-peak exceptions
144can propagate. Check the result before scoring. Use `load_from_usi` directly: the
145generic `load_spectra` has a `.usi` dispatch branch but first checks local file
146existence, so it is not a reliable entry point for a USI string. Preserve USI,
147resolver, retrieval date, and original response alongside analysis outputs.

Metabolomics USI

from matchms.importing import load_from_usi

spectrum = load_from_usi(
    "mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00000424840"
)

Signature:

load_from_usi(
    usi: str,
    server: str = "https://metabolomics-usi.gnps2.org",
    metadata_harmonization: bool = True,
)

The 0.33.1 helper makes an unauthenticated GET to https://metabolomics-usi.gnps2.org/json/?usi1=<USI> with a 10-second timeout. It expects one JSON object with nonempty peaks pairs and precursor_mz; there is no pagination. It returns one Spectrum or None, not a generator. Only usi, server, and precursor_mz are retained as metadata: the resolver also returns fields such as precursor_charge and splash, which the helper does not retain. Save the raw response separately when those fields matter.

The helper handles some invalid/404 responses with None but does not fully validate HTTP/schema failures; request, header, or malformed-peak exceptions can propagate. Check the result before scoring. Use load_from_usi directly: the generic load_spectra has a .usi dispatch branch but first checks local file existence, so it is not a reliable entry point for a USI string. Preserve USI, resolver, retrieval date, and original response alongside analysis outputs.

Raw lines 114 to 148
Starts an agent dispatch :145
149### Pickle
151```python
152from matchms.importing import load_from_pickle
154spectra = load_from_pickle("trusted-cache.pickle", metadata_harmonization=True)
155```
157The `metadata_harmonization` argument is required in 0.33.1.
159**Security:** Python pickle is executable serialization. Loading an untrusted
160pickle can run arbitrary code. Use MGF, MSP, JSON, or mzSpecLib for exchanged or
161downloaded data. Restrict pickle to trusted, local, reproducible caches.

Pickle

from matchms.importing import load_from_pickle

spectra = load_from_pickle("trusted-cache.pickle", metadata_harmonization=True)

The metadata_harmonization argument is required in 0.33.1.

Security: Python pickle is executable serialization. Loading an untrusted pickle can run arbitrary code. Use MGF, MSP, JSON, or mzSpecLib for exchanged or downloaded data. Restrict pickle to trusted, local, reproducible caches.

Raw lines 149 to 162
163## Generator and Memory Semantics
165MGF, MSP, mzML, and mzXML readers yield generators. JSON and pickle readers
166return lists. Converting a generator with `list(...)` loads all spectra and peak
167arrays into memory.
169Pairwise scoring requires materialized collections. Before scoring, estimate:
171```python
172pair_count = len(references) * len(queries)
173```
175For preprocessing-only MGF/MSP workflows, stream one spectrum at a time:
177```python
178from pathlib import Path
180from matchms.exporting import save_spectra
181from matchms.filtering import default_filters, normalize_intensities
182from matchms.importing import load_from_mgf
184output = Path("cleaned.mgf")
185if output.exists():
186 raise FileExistsError(output)
188first_write = True
189for spectrum in load_from_mgf("large.mgf"):
190 spectrum = default_filters(spectrum)
191 spectrum = normalize_intensities(spectrum)
192 if spectrum is None:
193 continue
194 save_spectra([spectrum], str(output), append=not first_write)
195 first_write = False
196```
198For many spectra, writing larger batches is usually faster than one record per
199call.

Generator and Memory Semantics

MGF, MSP, mzML, and mzXML readers yield generators. JSON and pickle readers return lists. Converting a generator with list(...) loads all spectra and peak arrays into memory.

Pairwise scoring requires materialized collections. Before scoring, estimate:

pair_count = len(references) * len(queries)

For preprocessing-only MGF/MSP workflows, stream one spectrum at a time:

from pathlib import Path

from matchms.exporting import save_spectra
from matchms.filtering import default_filters, normalize_intensities
from matchms.importing import load_from_mgf

output = Path("cleaned.mgf")
if output.exists():
    raise FileExistsError(output)

first_write = True
for spectrum in load_from_mgf("large.mgf"):
    spectrum = default_filters(spectrum)
    spectrum = normalize_intensities(spectrum)
    if spectrum is None:
        continue
    save_spectra([spectrum], str(output), append=not first_write)
    first_write = False

For many spectra, writing larger batches is usually faster than one record per call.

Raw lines 163 to 200
201## Metadata Harmonization
203The importers default to `metadata_harmonization=True`. This harmonizes keys
204and selected values while constructing each `Spectrum`. In 0.33.1, disabling
205this flag skips value harmonization but **still harmonizes keys**, including
206lowercasing and alias replacement; it does not preserve source keys.
208Keep harmonization enabled for cross-source comparisons. Disable it only when:
210- automatic value harmonization must be deferred for inspection;
211- you have a documented custom normalization layer; or
212- you are investigating an importer/harmonization issue.
214When source fidelity matters, retain the original file and export a metadata
215audit before applying repair filters.

Metadata Harmonization

The importers default to metadata_harmonization=True. This harmonizes keys and selected values while constructing each Spectrum. In 0.33.1, disabling this flag skips value harmonization but still harmonizes keys, including lowercasing and alias replacement; it does not preserve source keys.

Keep harmonization enabled for cross-source comparisons. Disable it only when:

  • automatic value harmonization must be deferred for inspection;
  • you have a documented custom normalization layer; or
  • you are investigating an importer/harmonization issue.

When source fidelity matters, retain the original file and export a metadata audit before applying repair filters.

Raw lines 201 to 216
217## Export Matrix
219### Generic writer
221```python
222from matchms.exporting import save_spectra
224save_spectra(spectra, "output.mgf", export_style="matchms")
225save_spectra(spectra, "output.msp", export_style="nist")
226save_spectra(spectra, "output.json", export_style="gnps")
227```
229Signature:
231```text
232save_spectra(spectra, file: str,
233 export_style: str = "matchms",
234 append: bool = False) -> None
235```
237Supported export styles are `matchms`, `massbank`, `nist`, `riken`, and `gnps`.
238Non-matchms export styles retain only their mapped fields, so custom provenance
239fields can disappear. These styles rename metadata; they are not complete
240format-specific validators. In 0.33.1, `massbank`-style MGF/MSP/JSON fails to
241restore `precursor_mz` on matchms reimport in the synthetic roundtrip check.
242Prefer `matchms` style for a local roundtrip; reopen converted data and compare
243identifiers, precursor values, peak counts, and representative peaks.

Generic writer

from matchms.exporting import save_spectra

save_spectra(spectra, "output.mgf", export_style="matchms")
save_spectra(spectra, "output.msp", export_style="nist")
save_spectra(spectra, "output.json", export_style="gnps")

Signature:

save_spectra(spectra, file: str,
             export_style: str = "matchms",
             append: bool = False) -> None

Supported export styles are matchms, massbank, nist, riken, and gnps. Non-matchms export styles retain only their mapped fields, so custom provenance fields can disappear. These styles rename metadata; they are not complete format-specific validators. In 0.33.1, massbank-style MGF/MSP/JSON fails to restore precursor_mz on matchms reimport in the synthetic roundtrip check. Prefer matchms style for a local roundtrip; reopen converted data and compare identifiers, precursor values, peak counts, and representative peaks.

Raw lines 219 to 244
245### Direct MGF writer
247```text
248save_as_mgf(spectra, filename, export_style="matchms", file_mode="a")
249```
251The direct writer's default is append mode. Pass `file_mode="w"` when creating a
252fresh output, or prefer `save_spectra()` for overwrite protection.

Direct MGF writer

save_as_mgf(spectra, filename, export_style="matchms", file_mode="a")

The direct writer's default is append mode. Pass file_mode="w" when creating a fresh output, or prefer save_spectra() for overwrite protection.

Raw lines 245 to 253
254### Direct MSP writer
256```text
257save_as_msp(spectra, filename, write_peak_comments=True,
258 mode="a", style="matchms", peak_sep="\t")
259```
261The direct writer also defaults to append mode. Peak comments can be retained
262when supported by the input and output style.

Direct MSP writer

save_as_msp(spectra, filename, write_peak_comments=True,
            mode="a", style="matchms", peak_sep="\t")

The direct writer also defaults to append mode. Peak comments can be retained when supported by the input and output style.

Raw lines 254 to 263
264### JSON writer
266```text
267save_as_json(spectra, filename, export_style="matchms")
268```
270JSON is portable and preserves matchms-oriented structured metadata better than
271plain text library formats, but it is not a raw-data archive.

JSON writer

save_as_json(spectra, filename, export_style="matchms")

JSON is portable and preserves matchms-oriented structured metadata better than plain text library formats, but it is not a raw-data archive.

Raw lines 264 to 272
273### mzSpecLib writer
275```python
276from matchms.exporting import save_as_mzspeclib
278save_as_mzspeclib(spectra, "library.mzspeclib.txt")
279```
281`save_as_mzspeclib()` is a direct text writer; it does not use psims and has no
282matching matchms importer. In 0.33.1 it overwrites an existing file and formats
283intensities to two decimals, so small normalized peaks can become zero. Its
284`collision_energy` handler expects text and labels the extracted number as eV;
285do not pass normalized collision energy or an unconverted unit. Validate the
286result with the downstream mzSpecLib consumer before treating it as an archive.

mzSpecLib writer

from matchms.exporting import save_as_mzspeclib

save_as_mzspeclib(spectra, "library.mzspeclib.txt")

save_as_mzspeclib() is a direct text writer; it does not use psims and has no matching matchms importer. In 0.33.1 it overwrites an existing file and formats intensities to two decimals, so small normalized peaks can become zero. Its collision_energy handler expects text and labels the extracted number as eV; do not pass normalized collision energy or an unconverted unit. Validate the result with the downstream mzSpecLib consumer before treating it as an archive.

Raw lines 273 to 287
288### Pickled spectra
290The generic writer recognizes a `.pickle` extension:
292```python
293save_spectra(spectra, "trusted-cache.pickle")
294```
296Use the full `.pickle` suffix; `.pkl` is not recognized by `save_spectra()` in
2970.33.1. Pickle is Python-specific, version-sensitive, and unsafe for untrusted
298inputs.

Pickled spectra

The generic writer recognizes a .pickle extension:

save_spectra(spectra, "trusted-cache.pickle")

Use the full .pickle suffix; .pkl is not recognized by save_spectra() in 0.33.1. Pickle is Python-specific, version-sensitive, and unsafe for untrusted inputs.

Raw lines 288 to 299
300## Score Serialization
302A `Scores` object has dedicated serializers:
304```python
305scores.to_json("scores.json")
306scores.to_pickle("scores.pickle")
307```
309Prefer JSON for exchange. Pickled `Scores` objects have the same arbitrary-code
310execution risk as pickled spectra.
312Reload score JSON with the public loader:
314```python
315from matchms.importing import scores_from_json
317restored = scores_from_json("scores.json")
318assert restored.score_names == scores.score_names
319```
321`scores_from_pickle` exists for trusted local caches only.

Score Serialization

A Scores object has dedicated serializers:

scores.to_json("scores.json")
scores.to_pickle("scores.pickle")

Prefer JSON for exchange. Pickled Scores objects have the same arbitrary-code execution risk as pickled spectra.

Reload score JSON with the public loader:

from matchms.importing import scores_from_json

restored = scores_from_json("scores.json")
assert restored.score_names == scores.score_names

scores_from_pickle exists for trusted local caches only.

Raw lines 300 to 322
323## Conversion Pattern
325```python
326from matchms.exporting import save_spectra
327from matchms.importing import load_from_mzml, load_spectra
329spectra = list(load_from_mzml("sample.mzML", ms_level=2))
330save_spectra(spectra, "sample-ms2.mgf")
332roundtrip = list(load_spectra("sample-ms2.mgf"))
333assert len(roundtrip) == len(spectra)
334for before, after in zip(spectra[:10], roundtrip[:10], strict=True):
335 assert len(before.peaks) == len(after.peaks)
336```
338Do not assume conversion preserves all acquisition metadata. MGF and MSP are
339spectral interchange/library formats, not lossless replacements for mzML.

Conversion Pattern

from matchms.exporting import save_spectra
from matchms.importing import load_from_mzml, load_spectra

spectra = list(load_from_mzml("sample.mzML", ms_level=2))
save_spectra(spectra, "sample-ms2.mgf")

roundtrip = list(load_spectra("sample-ms2.mgf"))
assert len(roundtrip) == len(spectra)
for before, after in zip(spectra[:10], roundtrip[:10], strict=True):
    assert len(before.peaks) == len(after.peaks)

Do not assume conversion preserves all acquisition metadata. MGF and MSP are spectral interchange/library formats, not lossless replacements for mzML.

Raw lines 323 to 340
341## Output Validation Checklist
343- Reopen the output with matchms or the intended downstream consumer.
344- Compare spectrum count and non-empty peak count.
345- Compare precursor m/z, charge, ion mode, and identifiers.
346- Compare m/z and intensity arrays for representative records.
347- Confirm the chosen export style and append/overwrite mode.
348- Preserve the original source alongside converted data.
349- Never load exchanged pickle data.

Output Validation Checklist

  • Reopen the output with matchms or the intended downstream consumer.
  • Compare spectrum count and non-empty peak count.
  • Compare precursor m/z, charge, ion mode, and identifiers.
  • Compare m/z and intensity arrays for representative records.
  • Confirm the chosen export style and append/overwrite mode.
  • Preserve the original source alongside converted data.
  • Never load exchanged pickle data.
Raw lines 341 to 349