Mercurial > repos > recetox > matchms_remove_spectra
comparison matchms_split.py @ 0:80df426e7e47 draft
planemo upload for repository https://github.com/RECETOX/galaxytools/tree/master/tools/matchms commit 113433b8b9790405c2c5d054aee4a29a21b77dc7
author | recetox |
---|---|
date | Thu, 30 May 2024 18:07:29 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:80df426e7e47 |
---|---|
1 import argparse | |
2 import itertools | |
3 import os | |
4 | |
5 import matchms | |
6 from matchms.exporting import save_as_msp | |
7 from matchms.importing import load_from_msp | |
8 | |
9 | |
10 matchms.Metadata.set_key_replacements({}) | |
11 | |
12 | |
13 def make_outdir(outdir: str): | |
14 """Create destination directory. | |
15 | |
16 Args: | |
17 outdir (str): Path to destination directory where split spectra files are generated. | |
18 """ | |
19 return os.mkdir(outdir) | |
20 | |
21 | |
22 def write_spectra(spectra, outdir): | |
23 """Generates MSP files of individual spectra. | |
24 | |
25 Args: | |
26 spectra (List[Spectrum]): Spectra to write to file | |
27 outdir (str): Path to destination directory. | |
28 """ | |
29 for i in range(len(spectra)): | |
30 save_as_msp(spectra[i], os.path.join(outdir, f"{i}.msp")) | |
31 | |
32 | |
33 def split_round_robin(iterable, num_chunks): | |
34 chunks = [list() for _ in range(num_chunks)] | |
35 index = itertools.cycle(range(num_chunks)) | |
36 for value in iterable: | |
37 chunks[next(index)].append(value) | |
38 chunks = filter(lambda x: len(x) > 0, chunks) | |
39 return chunks | |
40 | |
41 | |
42 listarg = argparse.ArgumentParser() | |
43 listarg.add_argument('--filename', type=str) | |
44 listarg.add_argument('--method', type=str) | |
45 listarg.add_argument('--outdir', type=str) | |
46 listarg.add_argument('--parameter', type=int) | |
47 args = listarg.parse_args() | |
48 outdir = args.outdir | |
49 filename = args.filename | |
50 method = args.method | |
51 parameter = args.parameter | |
52 | |
53 | |
54 if __name__ == "__main__": | |
55 spectra = load_from_msp(filename, metadata_harmonization=False) | |
56 make_outdir(outdir) | |
57 | |
58 if method == "one-per-file": | |
59 write_spectra(list(spectra), outdir) | |
60 else: | |
61 if method == "chunk-size": | |
62 chunks = iter(lambda: list(itertools.islice(spectra, parameter)), []) | |
63 elif method == "num-chunks": | |
64 chunks = split_round_robin(spectra, parameter) | |
65 for i, x in enumerate(chunks): | |
66 save_as_msp(x, os.path.join(outdir, f"chunk_{i}.msp")) |