mattbitzesty commited on
Commit
45cf13b
·
unverified ·
1 Parent(s): d03a111

feat(scripts): add Pyrfume descriptor and ODT ingestion pipeline

Browse files
Files changed (1) hide show
  1. scripts/ingest_pyrfume_data.py +418 -0
scripts/ingest_pyrfume_data.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ from collections import Counter
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import pyrfume
11
+ from rdkit import Chem, DataStructs
12
+ from rdkit.Chem import AllChem
13
+ from rdkit import RDLogger
14
+
15
+ # Silence RDKit deprecation spam.
16
+ RDLogger.DisableLog("rdApp.*")
17
+
18
+ logger = logging.getLogger("pino.ingest_pyrfume")
19
+
20
+ DESCRIPTOR_DIM = 138
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Descriptor normalisation
24
+ # ---------------------------------------------------------------------------
25
+
26
+
27
+ def _normalise_descriptor(token: str) -> str | None:
28
+ """Normalise a raw descriptor string to a canonical vocabulary token."""
29
+ t = token.strip().lower()
30
+ t = t.replace("/", " ")
31
+ t = t.replace("-", " ")
32
+ t = t.replace("_", " ")
33
+ if t in {"chemical", "aromatic", "organic", "synthetic", "natural", "pungent"}:
34
+ return None
35
+ return t
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Registry identity helpers
40
+ # ---------------------------------------------------------------------------
41
+
42
+
43
+ def _looks_like_cas(value: str) -> bool:
44
+ return bool(value) and value.count("-") == 2 and value.replace("-", "").isdigit()
45
+
46
+
47
+ def _parse_registry_identity(compound: dict[str, Any]) -> tuple[str | None, str | None]:
48
+ """Return (cas, smiles) for a registry compound."""
49
+ cas = compound.get("cas")
50
+ smiles = compound.get("smiles")
51
+ if cas and cas.startswith("SMILES:"):
52
+ smiles = cas[7:]
53
+ cas = None
54
+ return cas, smiles
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Pyrfume archive loaders
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ def _load_pyrfume_molecules() -> dict[int, str]:
63
+ """Load pyrfume molecules archive: CID -> IsomericSMILES."""
64
+ try:
65
+ mol = pyrfume.load_data("molecules/molecules.csv")
66
+ return {
67
+ int(cid): str(row.get("IsomericSMILES") or row.get("SMILES") or "")
68
+ for cid, row in mol.iterrows()
69
+ if row.get("IsomericSMILES") or row.get("SMILES")
70
+ }
71
+ except Exception as exc:
72
+ logger.warning("Could not load pyrfume molecules archive: %s", exc)
73
+ return {}
74
+
75
+
76
+ def _load_goodscents_cas_to_cid() -> dict[str, int]:
77
+ """GoodScents stimuli maps CAS (Stimulus) -> CID."""
78
+ try:
79
+ stim = pyrfume.load_data("goodscents/stimuli.csv")
80
+ return {str(idx): int(row["CID"]) for idx, row in stim.iterrows()}
81
+ except Exception as exc:
82
+ logger.warning("Could not load GoodScents stimuli: %s", exc)
83
+ return {}
84
+
85
+
86
+ def _load_leffingwell_stimuli() -> dict[int, list[str]]:
87
+ """Leffingwell stimuli maps Stimulus ID -> CID; one CID may have multiple stimuli."""
88
+ cid_to_stimuli: dict[int, list[str]] = {}
89
+ try:
90
+ stim = pyrfume.load_data("leffingwell/stimuli.csv")
91
+ for stim_id, row in stim.iterrows():
92
+ try:
93
+ cid = int(row["CID"])
94
+ except Exception:
95
+ continue
96
+ cid_to_stimuli.setdefault(cid, []).append(str(stim_id))
97
+ except Exception as exc:
98
+ logger.warning("Could not load Leffingwell stimuli: %s", exc)
99
+ return cid_to_stimuli
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # Descriptor loaders
104
+ # ---------------------------------------------------------------------------
105
+
106
+
107
+ def _load_goodscents_descriptors(cas_to_cid: dict[str, int]) -> tuple[dict[str, list[str]], Counter]:
108
+ """Load GoodScents descriptors keyed by registry CAS."""
109
+ cas_to_descriptors: dict[str, list[str]] = {}
110
+ counts: Counter = Counter()
111
+ try:
112
+ beh = pyrfume.load_data("goodscents/behavior.csv")
113
+ for cas, row in beh.iterrows():
114
+ cas = str(cas).strip()
115
+ if not _looks_like_cas(cas):
116
+ continue
117
+ raw = str(row.get("Descriptors", ""))
118
+ if not raw or raw.lower() == "nan":
119
+ continue
120
+ tokens = [_normalise_descriptor(d) for d in raw.split(";")]
121
+ tokens = [t for t in tokens if t]
122
+ if not tokens:
123
+ continue
124
+ cas_to_descriptors.setdefault(cas, []).extend(tokens)
125
+ counts.update(tokens)
126
+ except Exception as exc:
127
+ logger.warning("GoodScents descriptor ingestion failed: %s", exc)
128
+ return cas_to_descriptors, counts
129
+
130
+
131
+ def _load_leffingwell_descriptors_by_cid(cid_to_stimuli: dict[int, list[str]]) -> tuple[dict[int, list[str]], Counter]:
132
+ """Load Leffingwell descriptors keyed by pyrfume CID."""
133
+ cid_to_descriptors: dict[int, list[str]] = {}
134
+ counts: Counter = Counter()
135
+ try:
136
+ beh = pyrfume.load_data("leffingwell/behavior.csv")
137
+ descriptor_cols = [c for c in beh.columns if c != "Descriptors"]
138
+ for stim_id, row in beh.iterrows():
139
+ stim_id = str(stim_id)
140
+ # Find which CID this stimulus belongs to.
141
+ cid = next(
142
+ (cid for cid, stimuli in cid_to_stimuli.items() if stim_id in stimuli),
143
+ None,
144
+ )
145
+ if cid is None:
146
+ continue
147
+ tokens = []
148
+ for c in descriptor_cols:
149
+ value = row.get(c, 0)
150
+ try:
151
+ value = int(float(value))
152
+ except (ValueError, TypeError):
153
+ value = 0
154
+ if value == 1:
155
+ tokens.append(c)
156
+ tokens = [_normalise_descriptor(t) for t in tokens]
157
+ tokens = [t for t in tokens if t]
158
+ if not tokens:
159
+ continue
160
+ cid_to_descriptors.setdefault(cid, []).extend(tokens)
161
+ counts.update(tokens)
162
+ except Exception as exc:
163
+ logger.warning("Leffingwell descriptor ingestion failed: %s", exc)
164
+ return cid_to_descriptors, counts
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # ODT loader
169
+ # ---------------------------------------------------------------------------
170
+
171
+
172
+ def _load_abraham_odts_by_cid() -> dict[int, float]:
173
+ """Load Abraham 2012 ODTs as log10(1/ODT) in ppm_v, return mg/m³ keyed by CID."""
174
+ cid_to_odt: dict[int, float] = {}
175
+ try:
176
+ stim = pyrfume.load_data("abraham_2012/stimuli.csv")
177
+ beh = pyrfume.load_data("abraham_2012/behavior.csv")
178
+ # Build CID -> MW from pyrfume molecules if possible.
179
+ mol = pyrfume.load_data("molecules/molecules.csv")
180
+ cid_to_mw = {int(cid): float(row.get("MolecularWeight", 0.0)) for cid, row in mol.iterrows()}
181
+ for stimulus, row in stim.iterrows():
182
+ try:
183
+ cid = int(row["CID"])
184
+ log_inv_odt = float(beh.loc[stimulus, "Log (1/ODT)"])
185
+ except Exception:
186
+ continue
187
+ mw = cid_to_mw.get(cid, 0.0)
188
+ if not mw:
189
+ continue
190
+ ppm_v = 10.0 ** (-log_inv_odt)
191
+ cid_to_odt[cid] = ppm_v * mw / 24.45
192
+ except Exception as exc:
193
+ logger.warning("Abraham ODT ingestion failed: %s", exc)
194
+ return cid_to_odt
195
+
196
+
197
+ # ---------------------------------------------------------------------------
198
+ # Structural similarity fallback
199
+ # ---------------------------------------------------------------------------
200
+
201
+
202
+ def _compute_tanimoto_similarities(
203
+ query_smiles: str,
204
+ candidates: list[tuple[str, str]],
205
+ ) -> list[tuple[str, float]]:
206
+ qmol = Chem.MolFromSmiles(query_smiles)
207
+ if qmol is None:
208
+ return []
209
+ qfp = AllChem.GetMorganFingerprintAsBitVect(qmol, 2, nBits=2048)
210
+ sims: list[tuple[str, float]] = []
211
+ for cas, smi in candidates:
212
+ mol = Chem.MolFromSmiles(smi)
213
+ if mol is None:
214
+ continue
215
+ fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
216
+ sims.append((cas, float(DataStructs.TanimotoSimilarity(qfp, fp))))
217
+ return sims
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Main ingestion pipeline
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def ingest(
226
+ registry_path: str | Path,
227
+ output_dir: str | Path,
228
+ *,
229
+ max_vocab: int = DESCRIPTOR_DIM,
230
+ ) -> dict[str, Any]:
231
+ output_dir = Path(output_dir)
232
+ output_dir.mkdir(parents=True, exist_ok=True)
233
+
234
+ with Path(registry_path).open("r", encoding="utf-8") as f:
235
+ compounds = [json.loads(line) for line in f]
236
+ logger.info("Loaded %d compounds from registry", len(compounds))
237
+
238
+ # Registry identity maps.
239
+ cas_to_compound: dict[str, dict[str, Any]] = {}
240
+ smiles_to_compound: dict[str, dict[str, Any]] = {}
241
+ for c in compounds:
242
+ cas, smiles = _parse_registry_identity(c)
243
+ if cas:
244
+ cas_to_compound[cas] = c
245
+ if smiles:
246
+ smiles_to_compound[smiles] = c
247
+
248
+ # Pyrfume identity maps.
249
+ cid_to_smiles = _load_pyrfume_molecules()
250
+ smiles_to_cid = {smi: cid for cid, smi in cid_to_smiles.items()}
251
+ goodscents_cas_to_cid = _load_goodscents_cas_to_cid()
252
+ leffingwell_cid_to_stimuli = _load_leffingwell_stimuli()
253
+
254
+ # Resolve registry compounds to pyrfume CIDs.
255
+ # Priority: CAS via GoodScents stimuli, then SMILES via pyrfume molecules.
256
+ compound_to_cid: dict[str, int] = {} # key = registry CAS or SMILES
257
+ for cas, c in cas_to_compound.items():
258
+ if cas in goodscents_cas_to_cid:
259
+ compound_to_cid[cas] = goodscents_cas_to_cid[cas]
260
+ for smiles, c in smiles_to_compound.items():
261
+ if smiles in smiles_to_cid:
262
+ compound_to_cid[smiles] = smiles_to_cid[smiles]
263
+ logger.info("Resolved %d registry compounds to pyrfume CIDs", len(compound_to_cid))
264
+
265
+ # Descriptors.
266
+ gs_cas_to_descs, gs_counts = _load_goodscents_descriptors(goodscents_cas_to_cid)
267
+ lf_cid_to_descs, lf_counts = _load_leffingwell_descriptors_by_cid(leffingwell_cid_to_stimuli)
268
+ descriptor_counts = gs_counts + lf_counts
269
+
270
+ top_descriptors = [w for w, _ in descriptor_counts.most_common(max_vocab)]
271
+ vocabulary = sorted(set(top_descriptors))
272
+ word_to_idx = {w: i for i, w in enumerate(vocabulary)}
273
+ logger.info("Built %d-dimensional vocabulary", len(vocabulary))
274
+
275
+ # Build per-compound descriptor vectors.
276
+ cas_to_descriptor_vector: dict[str, list[float]] = {}
277
+ for c in compounds:
278
+ cas, smiles = _parse_registry_identity(c)
279
+ key = cas if cas else smiles
280
+ cid = compound_to_cid.get(key)
281
+ if not cid:
282
+ continue
283
+ descriptors: list[str] = []
284
+ if cas and cas in gs_cas_to_descs:
285
+ descriptors.extend(gs_cas_to_descs[cas])
286
+ if cid in lf_cid_to_descs:
287
+ descriptors.extend(lf_cid_to_descs[cid])
288
+ if not descriptors:
289
+ continue
290
+ vec = [0.0] * DESCRIPTOR_DIM
291
+ for d in descriptors:
292
+ if d in word_to_idx:
293
+ vec[word_to_idx[d]] = 1.0
294
+ if any(v > 0 for v in vec):
295
+ # Record under the CAS if we have one, else under the original registry key.
296
+ record_key = cas if cas else smiles
297
+ cas_to_descriptor_vector[record_key] = vec
298
+
299
+ logger.info("Assigned descriptors to %d registry compounds", len(cas_to_descriptor_vector))
300
+
301
+ # ODTs.
302
+ cid_to_odt = _load_abraham_odts_by_cid()
303
+ compound_to_odt: dict[str, float] = {}
304
+ for c in compounds:
305
+ cas, smiles = _parse_registry_identity(c)
306
+ key = cas if cas else smiles
307
+ cid = compound_to_cid.get(key)
308
+ if cid and cid in cid_to_odt:
309
+ compound_to_odt[key] = cid_to_odt[cid]
310
+ logger.info("Assigned ODTs to %d registry compounds from Abraham data", len(compound_to_odt))
311
+
312
+ observed_odts = list(compound_to_odt.values())
313
+ median_odt = float(sorted(observed_odts)[len(observed_odts) // 2]) if observed_odts else 1.0
314
+ logger.info("Median ODT for fallback: %.6f mg/m³", median_odt)
315
+
316
+ # Fallback ODTs.
317
+ fallback_log: list[dict[str, Any]] = []
318
+ candidates = [
319
+ (key, c.get("smiles"))
320
+ for key, c in {**cas_to_compound, **smiles_to_compound}.items()
321
+ if key in compound_to_odt and c.get("smiles")
322
+ ]
323
+
324
+ for c in compounds:
325
+ cas, smiles = _parse_registry_identity(c)
326
+ key = cas if cas else smiles
327
+ if key in compound_to_odt:
328
+ continue
329
+ if not smiles:
330
+ compound_to_odt[key] = median_odt
331
+ fallback_log.append({"key": key, "fallback": "median", "odt_mg_m3": median_odt})
332
+ continue
333
+ try:
334
+ sims = _compute_tanimoto_similarities(smiles, candidates)
335
+ if sims:
336
+ best_key, best_sim = max(sims, key=lambda x: x[1])
337
+ proxy = compound_to_odt[best_key]
338
+ compound_to_odt[key] = proxy
339
+ fallback_log.append({
340
+ "key": key,
341
+ "fallback": "tanimoto_nearest",
342
+ "nearest_key": best_key,
343
+ "similarity": round(best_sim, 4),
344
+ "odt_mg_m3": round(proxy, 6),
345
+ })
346
+ else:
347
+ compound_to_odt[key] = median_odt
348
+ fallback_log.append({"key": key, "fallback": "median", "odt_mg_m3": median_odt})
349
+ except Exception as exc:
350
+ logger.warning("Tanimoto fallback failed for %s: %s", key, exc)
351
+ compound_to_odt[key] = median_odt
352
+ fallback_log.append({"key": key, "fallback": "median", "odt_mg_m3": median_odt})
353
+
354
+ logger.info("Applied ODT fallback for %d compounds", len(fallback_log))
355
+
356
+ # Write outputs.
357
+ (output_dir / "pyrfume_vocabulary.json").write_text(
358
+ json.dumps({"dimension": len(vocabulary), "vocabulary": vocabulary}, indent=2, ensure_ascii=False),
359
+ encoding="utf-8",
360
+ )
361
+ (output_dir / "pyrfume_descriptors_by_cas.json").write_text(
362
+ json.dumps(cas_to_descriptor_vector, indent=2, ensure_ascii=False),
363
+ encoding="utf-8",
364
+ )
365
+ (output_dir / "pyrfume_odt_by_cas.json").write_text(
366
+ json.dumps({k: round(v, 6) for k, v in compound_to_odt.items()}, indent=2, ensure_ascii=False),
367
+ encoding="utf-8",
368
+ )
369
+
370
+ logs_dir = output_dir.parent / "logs"
371
+ logs_dir.mkdir(parents=True, exist_ok=True)
372
+ (logs_dir / "odt_fallbacks.log").write_text(
373
+ "\n".join(json.dumps(entry, ensure_ascii=False) for entry in fallback_log),
374
+ encoding="utf-8",
375
+ )
376
+
377
+ annotations = []
378
+ for c in compounds:
379
+ cas, smiles = _parse_registry_identity(c)
380
+ key = cas if cas else smiles
381
+ cid = compound_to_cid.get(key)
382
+ ann = {
383
+ "cas": c.get("cas"),
384
+ "smiles": smiles,
385
+ "cid": cid,
386
+ "descriptor_vector": cas_to_descriptor_vector.get(key),
387
+ "odt_mg_m3": compound_to_odt.get(key),
388
+ "odt_fallback": next(
389
+ (e["fallback"] for e in fallback_log if e["key"] == key), None
390
+ ),
391
+ }
392
+ annotations.append(ann)
393
+ (output_dir / "pyrfume_registry_annotations.jsonl").write_text(
394
+ "\n".join(json.dumps(a, ensure_ascii=False) for a in annotations),
395
+ encoding="utf-8",
396
+ )
397
+
398
+ return {
399
+ "vocabulary_size": len(vocabulary),
400
+ "annotated_compounds": len(annotations),
401
+ "descriptor_coverage": len(cas_to_descriptor_vector),
402
+ "odt_from_data": len(observed_odts),
403
+ "odt_fallback_count": len(fallback_log),
404
+ "cid_resolved": len(compound_to_cid),
405
+ }
406
+
407
+
408
+ if __name__ == "__main__":
409
+ parser = argparse.ArgumentParser(description="Ingest pyrfume descriptors and ODTs")
410
+ parser.add_argument("--registry", default="data/aroma_chemicals.jsonl")
411
+ parser.add_argument("--output-dir", default="data")
412
+ parser.add_argument("--vocab-size", type=int, default=DESCRIPTOR_DIM)
413
+ args = parser.parse_args()
414
+
415
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
416
+
417
+ stats = ingest(args.registry, args.output_dir, max_vocab=args.vocab_size)
418
+ print(json.dumps(stats, indent=2))