msnlib / collate_ms_libraries.py
rohangautam's picture
Mirror pinned MSnLib libraries with verified spectra, source views and compound metadata
28df3ef verified
Raw History Blame Contribute Delete
14 kB
"""Collate pinned Spectraverse or MSnLib spectra without changing their protocol."""
import argparse
import csv
import gzip
import hashlib
import json
import math
import os
import re
import shutil
from collections import Counter
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import yaml
def checksums(path: Path) -> dict:
md5, sha = hashlib.md5(usedforsecurity=False), hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
md5.update(block)
sha.update(block)
return {"bytes": path.stat().st_size, "md5": md5.hexdigest(), "sha256": sha.hexdigest()}
def mgf_records(path: Path):
"""Preserve metadata pairs, peak order, and optional extra peak fields."""
active = False
metadata, mzs, intensities, extras = [], [], [], []
with path.open(encoding="utf-8-sig") as stream:
for line_number, line in enumerate(stream, 1):
value = line.strip()
if value == "BEGIN IONS":
if active:
raise ValueError(f"Nested BEGIN IONS: {path}:{line_number}")
active = True
metadata, mzs, intensities, extras = [], [], [], []
elif value == "END IONS":
if not active:
raise ValueError(f"END IONS without spectrum: {path}:{line_number}")
yield metadata, mzs, intensities, extras
active = False
elif active and value:
if "=" in value:
key, field = value.split("=", 1)
metadata.append([key, field])
elif value.startswith(("#", ";")):
metadata.append(["source_comment", value])
else:
fields = value.split()
if len(fields) < 2:
raise ValueError(f"Malformed peak: {path}:{line_number}: {value}")
mz, intensity = float(fields[0]), float(fields[1])
if not math.isfinite(mz) or not math.isfinite(intensity):
raise ValueError(f"Non-finite peak: {path}:{line_number}")
mzs.append(mz)
intensities.append(intensity)
extras.append(" ".join(fields[2:]))
if active:
raise ValueError(f"Truncated spectrum: {path}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", choices=["spectraverse", "msnlib"], required=True)
parser.add_argument("--work-dir", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--records-per-shard", type=int, default=100000)
args = parser.parse_args()
if args.output_dir.exists() or args.records_per_shard < 1:
parser.error("Use a new output directory and positive shard size")
source = json.loads((args.work_dir / "source_metadata.json").read_text())
mgf_paths = sorted((args.work_dir / "raw").glob("*.mgf"))
if not mgf_paths:
raise ValueError(f"No MGF files found: {args.work_dir / 'raw'}")
source_stats = {}
for item in source["files"]:
path = args.work_dir / "raw" / item["key"]
actual = checksums(path)
if actual["bytes"] != item["size"] or "md5:" + actual["md5"] != item["checksum"]:
raise ValueError(f"Source size/checksum differs: {path}")
source_stats["source/" + path.name] = actual
print("Source verified:", path.name, flush=True)
args.output_dir.mkdir(parents=True)
string_fields = ["source_file", "source_record_id", "source_identifier", "source_library", "polarity", "ms_level", "spectype", "source_fold", "compound_name", "smiles", "inchi", "inchikey", "formula", "adduct", "charge", "precursor_mz_text", "parent_mass_text", "instrument_type", "collision_energy_text", "collision_energies_json", "normalized_collision_energies_json", "source_metadata_json", "source_auxiliary_json", "quality_status"]
schema = pa.schema([(name, pa.string()) for name in string_fields] + [("source_record_index", pa.int64()), ("is_pseudo_ms2", pa.bool_()), ("mzs", pa.list_(pa.float64())), ("intensities", pa.list_(pa.float64())), ("extra_peak_fields", pa.list_(pa.string()))])
csv_metadata = {}
if args.dataset == "spectraverse":
csv_path = next((args.work_dir / "raw").glob("*.csv.gz"))
with gzip.open(csv_path, "rt", newline="") as stream:
reader = csv.DictReader(stream)
print("Spectraverse CSV fields:", reader.fieldnames, flush=True)
for index, row in enumerate(reader):
csv_metadata[str(index)] = row
writer, buffer, current_path, shard_rows = None, [], None, 0
outputs, stats, smiles = {}, Counter(), set()
total = 0
def flush():
nonlocal writer, buffer, current_path, shard_rows
if not buffer:
return
if writer is None:
current_path = args.output_dir / f"data/{args.dataset}/train-{len(outputs):05d}.parquet"
current_path.parent.mkdir(parents=True, exist_ok=True)
writer = pq.ParquetWriter(current_path, schema, compression="zstd")
shard_rows = 0
table = pa.Table.from_pylist(buffer, schema=schema)
if table.to_pylist() != buffer:
raise ValueError(f"Arrow values changed: {current_path}")
writer.write_table(table)
shard_rows += len(buffer)
buffer = []
if shard_rows >= args.records_per_shard:
close_shard()
def close_shard():
nonlocal writer
writer.close()
if pq.ParquetFile(current_path).metadata.num_rows != shard_rows:
raise ValueError(f"Parquet record count differs: {current_path}")
outputs[str(current_path.relative_to(args.output_dir))] = {**checksums(current_path), "rows": shard_rows}
writer = None
for path in mgf_paths:
file_count = 0
for index, (pairs, mzs, intensities, extras) in enumerate(mgf_records(path)):
fields = {key.upper(): value for key, value in pairs}
def get(*names):
return next((fields[name.upper()] for name in names if name.upper() in fields), None)
identifier = get("SPECTRUMID", "SPECTRUM_ID", "FEATURE_ID", "SCANS", "TITLE")
label = get("SMILES", "CANONICAL_SMILES")
if label:
smiles.add(label)
auxiliary = csv_metadata.get(str(index)) if args.dataset == "spectraverse" else None
if args.dataset == "spectraverse" and (auxiliary is None or auxiliary["TITLE"] != identifier):
raise ValueError(f"Spectraverse CSV/MGF identifiers do not align at row {index}: {identifier}")
spectype = get("SPECTYPE")
inchikey = get("INCHIKEY")
if inchikey is None and re.fullmatch(r"[A-Z]{14}-[A-Z]{10}-[A-Z]", get("INCHIAUX") or ""):
inchikey = get("INCHIAUX")
row = {"source_file": path.name, "source_record_id": f"{path.name}:{index}", "source_identifier": identifier,
"source_library": get("SOURCE", "COMPOUND_SOURCE", "LIBRARY", "DESCRIPTION") or re.sub(r"_(pos|neg)_(ms2|msn)$", "", path.stem),
"polarity": get("IONMODE", "ION_MODE", "POLARITY") or ("negative" if "_neg_" in path.name else "positive" if "_pos_" in path.name else None),
"ms_level": get("MSLEVEL", "MS_LEVEL"), "spectype": spectype,
"source_fold": get("FOLD"), "compound_name": get("COMPOUND_NAME", "NAME", "COMPOUNDNAME"),
"smiles": label, "inchi": get("INCHI"), "inchikey": inchikey, "formula": get("FORMULA", "MOLECULAR_FORMULA"),
"adduct": get("ADDUCT", "ION"), "charge": get("CHARGE"), "precursor_mz_text": get("PEPMASS", "PRECURSOR_MZ"),
"parent_mass_text": get("PARENT_MASS", "EXACTMASS", "EXACT_MASS"), "instrument_type": get("INSTRUMENT_TYPE", "INSTRUMENT"),
"collision_energy_text": get("COLLISIONENERGY", "COLLISION_ENERGY", "CE"),
"collision_energies_json": json.dumps({key:value for key,value in fields.items() if key.startswith("COLLISION_ENERGY") or key == "COLLISIONENERGY"}),
"normalized_collision_energies_json": json.dumps({key:value for key,value in fields.items() if key.startswith("NORMALIZED_COLLISION_ENERGY")}),
"source_metadata_json": json.dumps(pairs), "source_auxiliary_json": json.dumps(auxiliary) if auxiliary is not None else None,
"source_record_index": index, "is_pseudo_ms2": (spectype or "").upper() == "ALL_MSN_TO_PSEUDO_MS2",
"mzs": mzs, "intensities": intensities, "extra_peak_fields": extras,
"quality_status": "empty_peaks" if not mzs else "negative_intensity" if min(intensities) < 0 else "finite_peaks"}
buffer.append(row)
if len(buffer) == 1000:
flush()
stats["records/" + path.name] += 1
stats["quality/" + row["quality_status"]] += 1
stats["pseudo_ms2"] += row["is_pseudo_ms2"]
stats["missing_smiles"] += not bool(label)
for name in ("source_library", "source_fold", "ms_level", "polarity", "spectype"):
stats[name + "/" + str(row[name])] += 1
file_count += 1
total += 1
if total % 100000 == 0:
print("Spectra converted:", total, flush=True)
if args.dataset == "spectraverse" and file_count != len(csv_metadata):
raise ValueError(f"Spectraverse MGF/CSV row counts differ: {file_count} != {len(csv_metadata)}")
print("MGF complete:", path.name, file_count, flush=True)
flush()
if writer is not None:
close_shard()
source_dir = args.output_dir / "source"
source_dir.mkdir()
for item in source["files"]:
path = args.work_dir / "raw" / item["key"]
os.link(path, source_dir / path.name)
compound_outputs = []
if args.dataset == "msnlib":
for path in (args.work_dir / "raw").glob("*.parquet"):
relative = "data/compounds/" + path.name
destination = args.output_dir / relative
destination.parent.mkdir(parents=True, exist_ok=True)
os.link(path, destination)
outputs[relative] = {**checksums(path), "rows": pq.ParquetFile(path).metadata.num_rows}
compound_outputs.append(relative)
shutil.copyfile(args.work_dir / "source_metadata.json", source_dir / "source_metadata.json")
shutil.copyfile(Path(__file__), args.output_dir / "collate_ms_libraries.py")
manifest = {"dataset": args.dataset, "source_metadata": source, "source_files": source_stats, "parquet_files": outputs,
"spectra": total, "unique_source_smiles": len(smiles), "statistics": dict(stats),
"validation": {"published_source_md5_matches": True, "source_peak_order_preserved": True,
"peak_vectors_finite_and_matched": True, "no_normalization_filter_or_new_split": True},
"slurm_job_id": os.environ.get("SLURM_JOB_ID"), "script_sha256": checksums(Path(__file__))["sha256"]}
(args.output_dir / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
header = {"license": source["metadata"]["license"]["id"], "pretty_name": args.dataset,
"configs": [{"config_name": "full", "default": True, "data_files": [{"split": "train", "path": f"data/{args.dataset}/*.parquet"}]}]}
if compound_outputs:
header["configs"].append({"config_name": "compounds", "data_files": [{"split": "train", "path": "data/compounds/*.parquet"}]})
card = "---\n" + yaml.safe_dump(header, sort_keys=False) + "---\n\n# " + args.dataset + "\n\n"
card += f"Pinned source: https://zenodo.org/records/{source['record_id']} . This mirror contains {total:,} source MGF records with original peak order and intensities, plus original source files. No molecule standardization, chemistry filter, peak normalization, or new benchmark split is applied. `train` is a storage convention.\n\n"
card += "Metadata values and duplicate metadata keys remain in `source_metadata_json`; source identifiers and record indices are preserved. Raw charge, precursor, adduct, and collision-energy text are retained rather than imputed. Extra peak fields are preserved. Empty/negative-intensity source spectra are flagged and retained.\n\n"
if args.dataset == "msnlib":
card += "MS2 and MSn exports overlap by design: source MS2 files include pseudo-MS2 spectra, and MSn files also contain individual higher fragmentation stages. Do not count merged spectra or duplicate export views as independent measurements. `SPECTYPE` is retained and pseudo-MS2 flagged. The `source_file` suffix distinguishes MS2-only/MSn views and polarity. Source compound metadata and both JSON/MGF representations remain under `source/`. The `compounds` configuration exposes the source detected-compound Parquet unchanged.\n\n"
else:
card += "The source CSV metadata, MGF, and both official retrieval candidate JSONs remain under `source/`. Candidate data are not altered or silently mixed with other benchmark protocols. Every CSV/MGF row is aligned by matching original TITLE values. Original numeric FOLD assignments remain in `source_fold`; no arbitrary mapping to train/validation/test was introduced. Absolute and normalized collision-energy fields remain distinct.\n\n"
card += "Published file MD5 checksums, row counts, peak-vector shapes, and finite values were checked. Full chemical annotation validity and overlap with other datasets remain unaudited. Cite the original source authors and publication described in `source/source_metadata.json`.\n"
(args.output_dir / "README.md").write_text(card)
if __name__ == "__main__":
main()