Repository navigation
Expand file tree
/
Copy pathcreate_query_list.py
More file actions
82 lines (66 loc) · 2.76 KB
/
Copy pathcreate_query_list.py
File metadata and controls
82 lines (66 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import argparse
import logging
from pathlib import Path
from typing import Dict, List, Tuple
import pandas as pd
from rdkit import Chem
from rdkit.Chem import inchi as rdinchi
def inchikey_from_inchi(inchi: str) -> str:
"""Convert InChI to InChIKey using RDKit; return empty string on error."""
if not inchi:
return ""
try:
mol = Chem.MolFromInchi(inchi)
if mol is None:
return ""
return rdinchi.MolToInchiKey(mol) or ""
except Exception:
return ""
def main() -> None:
parser = argparse.ArgumentParser(description="Generate query list (accession|inchi|inchikey) from files.")
parser.add_argument("directory", type=Path, help="Root directory containing files")
parser.add_argument(
"--output", "-o", type=Path, default=Path("results/query_list.tsv"), help="Target TSV file"
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(message)s")
logging.info('\n\n--> Starting create_query_list.py ...\n\n')
directory: Path = args.directory.expanduser().resolve()
output: Path = args.output
# Find files excluding hidden paths
files = [p for p in directory.rglob("MSBNK-*.txt") if not any(part.startswith(".") for part in p.parts)]
logging.info("Processing directory: %s", directory)
logging.info("Total files found: %d", len(files))
cache: Dict[str, str] = {}
rows: List[Tuple[str, str, str]] = []
for fp in files:
accession = None
inchi = None
skip = False
try:
with fp.open("r", encoding="utf-8", errors="ignore") as fh:
for raw in fh:
line = raw.strip()
if line.startswith("ACCESSION:"):
accession = line.split(":", 1)[1].strip()
elif line.startswith("CH$LINK:") and "ChemOnt" in line:
skip = True
break
elif line.startswith("CH$IUPAC:"):
inchi = line.split(":", 1)[1].strip()
except Exception as e:
logging.debug("Error reading %s: %s", fp, e)
continue
if skip:
continue
if accession and inchi and inchi.startswith("InChI="):
if inchi not in cache:
cache[inchi] = inchikey_from_inchi(inchi)
rows.append((accession, inchi, cache[inchi]))
logging.info("Total accessions without ChemOnt classification: %d", len(rows))
df = pd.DataFrame(rows, columns=["accession", "inchi", "inchikey"])
output.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(output, index=False, header=False, sep="|", encoding="utf-8")
logging.info("Query list saved to %s", output)
if __name__ == "__main__":
main()