"""Extract the measured real channel of BMRB bmse000297, experiment 1.""" from argparse import ArgumentParser from pathlib import Path import csv import re import struct from zipfile import ZipFile cli = ArgumentParser(description="Extract BMRB bmse000297, experiment 1, processed real channel") cli.add_argument("archive", type=Path) cli.add_argument("output", type=Path) args = cli.parse_args() source, out = args.archive, args.output with ZipFile(source) as archive: params = archive.read("pdata/1/procs").decode("latin-1") counts = archive.read("pdata/1/1r") def number(key, converter): match = re.search(rf"(?m)^##\${re.escape(key)}=\s*(\S+)", params) if not match: raise ValueError(key) return converter(match[1]) size = number("SI", int) endian = number("BYTORDP", int) assert endian in (0, 1) assert number("DTYPP",int) == 0, "Only the entry's signed int32 processing is supported" assert len(counts) == size * 4 data = struct.unpack(("<" if endian == 0 else ">") + str(size) + "i", counts) offset = number("OFFSET",float) increment = number("SW_p",float) / number("SF",float) / size with out.open("w",newline="",encoding="utf-8") as handle: csv_data = csv.writer(handle) csv_data.writerow(["chemical_shift_ppm","real_intensity_stored_counts"]) for index, value in enumerate(data): csv_data.writerow([f"{offset-index*increment:.11f}", value]) print("Samples:",size,"Range ppm:",offset,offset-(size-1)*increment) print("Stored signed integer scaling preserved; NC_proc header:",number("NC_proc",int)) peak = max(range(size), key=data.__getitem__) print("Maximum stored real intensity and position:",data[peak],round(offset-peak*increment,5)) for center in (1.175, 3.645): within = [index for index in range(size) if abs(offset-index*increment-center)<0.05] peak = max(within,key=data.__getitem__) print("Local maximum:",data[peak],round(offset-peak*increment,5),"ppm")