-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpredict.py
More file actions
1824 lines (1645 loc) Β· 93.8 KB
/
Copy pathpredict.py
File metadata and controls
1824 lines (1645 loc) Β· 93.8 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
predict.py β the unified flavor read the workbench screen renders.
One molecule in, one dict out, combining whatever heads exist in taste_models/:
aroma : DEFERRED β honest 'not available' (no clean public data; see docs/AROMA.md)
sweet/bitter/umami : probabilities 0-1 (trained heads, if present)
sweet_intensity : ~relative-to-sucrose estimate (if regressor present)
sour : bool + which acid group (RULE β acidic groups)
salty : bool + reason (RULE β inorganic alkali salt, anion-guarded)
safety : disclaimer + scope + structural alerts + GRAS status + TTC hint
(DEFENSIVE, caution-only β never a safety clearance)
physchem : logP/MW/TPSA/HBD/HBA (computed) + solubility (ESOL estimate)
+ aroma-volatility tier + ionizable-group pKa ranges (qualitative)
stability : oxidation / hydrolysis / photodegradation watch-flags (qualitative)
chemesthesis : trigeminal class flags β cooling / pungent / astringent (qualitative)
Each physchem value is tagged computed / estimate / qualitative so confidence is
explicit and nothing reads as more precise than it is.
labeling : EU declarable fragrance-allergen flag (regulatory lookup)
For formulations, check_mixture(ingredients, processes=[...]) flags documented
food hazards (benzene, nitrosamine, ethyl carbamate, acrylamide, furan, 3-MCPD,
4-MEI, biogenic amines), gated on the process (high_heat/refining/fermentation)
that causes them β active vs conditional. Curated, NOT a reaction predictor.
The taste heads load dynamically: whatever train_taste.py produced shows up
here automatically, so adding an umami/sour model later needs no edit.
Sour note: sourness is a solution/pH property, not a per-molecule ML target,
so we flag acidic functional groups as an honest proxy. True sour balance is
formulation-level (titratable acidity / pH), which their data teaches later.
Salty note: saltiness is an ionic effect, not a molecular-shape one, so it can't
be a trained head either. But it IS partly structure-readable: a simple
inorganic alkali/ammonium salt (NaCl, KCl, NH4Cl...) is reliably salty. The trap
is sodium-bearing organics β MSG (umami), sodium saccharin (sweet), sodium
benzoate (preservative) β where the organic ANION drives taste and the cation is
incidental. So the rule fires only on alkali/ammonium + a simple INORGANIC anion,
and defers to the anion's taste whenever the anion carries carbon. That mirrors
the sour rule's spirit while refusing the naive "has sodium -> salty" mistake.
Hard ceiling: it nails simple salts and honestly can't reach salt-enhancer
peptides or non-ionic salty compounds (little data, weak structure-activity).
"""
import contextlib
import os
import threading as _threading
import time as _time
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from pathlib import Path
import joblib
import numpy as np
from rdkit import Chem
from rdkit.Chem import (
Crippen,
DataStructs,
Descriptors,
rdFingerprintGenerator,
rdMolDescriptors,
)
# Where the trained artifacts live. Defaults to the working directory, which is how the systemd
# deployment has always run (code and models share one directory). Setting FLAVORMANCER_HOME lets
# a container bake the CODE into the image while MOUNTING the ~1 GB of models and parquet tables β
# without it, any bind mount that reached the artifacts would also shadow app.py.
HOME = Path(os.environ.get("FLAVORMANCER_HOME") or ".")
def artifact(name):
"""Resolve one trained artifact (model directory, parquet or csv) under FLAVORMANCER_HOME."""
return HOME / name
FP_BITS, FP_RADIUS = 2048, 2
_MORGAN = rdFingerprintGenerator.GetMorganGenerator(radius=FP_RADIUS, fpSize=FP_BITS)
TASTE = artifact("taste_models")
ACID_SMARTS = {
# Match both protonated (-OH) and deprotonated (-O-) forms β sour compounds are
# routinely drawn as carboxylate/sulfonate/phosphate anions or zwitterions.
# (Lifted the rule's recall on labeled-sour from 0.57 to 0.93.)
"carboxylic acid / carboxylate": "[CX3](=O)[OX2H1,OX1-]",
"sulfonic / sulfonate": "[SX4](=O)(=O)[OX2H1,OX1-]",
"phosphoric / phosphonic (+ anion)": "[PX4](=O)[OX2H1,OX1-]",
}
_ACID = {k: Chem.MolFromSmarts(v) for k, v in ACID_SMARTS.items()}
# Salty rule: alkali metals (Li, Na, K, Rb, Cs) + ammonium are the salt-forming
# cations. Saltiness fires only when one of these pairs with a simple INORGANIC
# anion; an organic (carbon-bearing) anion means the anion drives taste instead.
_ALKALI_Z = {3, 11, 19, 37, 55}
_SYM = {3: "Li", 11: "Na", 19: "K", 37: "Rb", 55: "Cs"}
# ββ SAFETY (all defensive, caution-only β never a clearance) ββββββββββββββββββ
SAFETY_DISCLAIMER = (
"Taste/aroma prediction only. This is NOT a safety, toxicity, GRAS, "
"regulatory, or chemical-stability determination. Every formulation must be "
"validated by qualified toxicology and regulatory review before use."
)
# A SMALL, curated set of high-signal structural alerts. These are PROMPTS FOR
# REVIEW, not toxicity verdicts β some safe compounds share these motifs. Kept
# deliberately to groups that are rare in the GRAS flavor palette to avoid alert
# fatigue (e.g. we do NOT flag aldehydes or Michael acceptors β too many GRAS
# flavor compounds like vanillin or cinnamaldehyde carry them).
TOX_ALERT_SMARTS = {
"aromatic nitro": "[c][$([NX3](=O)=O),$([N+](=O)[O-])]",
"N-nitroso (nitrosamine)": "[NX3][NX2]=O",
"aromatic azo": "[c][NX2]=[NX2][c]",
"epoxide": "[#6]1[#6]O1",
}
_TOX = {k: Chem.MolFromSmarts(v) for k, v in TOX_ALERT_SMARTS.items()}
# Mixture / process hazards: documented, curated β NOT a general reaction predictor.
# Roles are detected per-molecule; each hazard fires on roles (+ optionally a
# declared process condition that actually causes it). Detectors:
_BENZOATE = Chem.MolFromSmarts("[#6;a]C(=O)[OX2H1,OX1-]") # benzoic acid / benzoate
_NITRITE = Chem.MolFromSmarts("[NX2](=O)[OX1-,OX2H1]") # nitrite / nitrous
_SEC_AMINE = Chem.MolFromSmarts("[NX3;H1;!$(N-C=O)]([#6])[#6]") # secondary amine, not amide
_UREA = Chem.MolFromSmarts("[NX3][CX3](=O)[NX3]") # urea / carbamide
_CHLORIDE = Chem.MolFromSmarts("[Cl-]") # ionic chloride source
_AMMONIUM_ION = Chem.MolFromSmarts("[NX4H4+]") # ammonium
_GLYCEROL_BB = Chem.MolFromSmarts("[CH2X4]([OX2])[CHX4]([OX2])[CH2X4][OX2]") # glycerol backbone
_ACYL_ESTER = Chem.MolFromSmarts("[OX2][CX3]=O") # ester linkage
def _ik1(*smiles):
"""InChIKey first-blocks (skeleton hashes) computed from SMILES, so the
reference keys are correct by construction rather than hand-typed."""
s = set()
for smi in smiles:
m = Chem.MolFromSmiles(smi)
if m is not None:
s.add(Chem.MolToInchiKey(m).split("-")[0])
return s
_ASCORBATE_IKS = _ik1("OCC(O)C1OC(=O)C(O)=C1O", "[Na+].OCC(O)C1OC(=O)C(O)=C1[O-]")
_ETHANOL_IKS = _ik1("CCO")
_ASPARAGINE_IKS = _ik1("NC(=O)CC(N)C(=O)O")
_CITRULLINE_IKS = _ik1("NC(=O)NCCCC(N)C(=O)O")
_HISTIDINE_IKS = _ik1("NC(Cc1cnc[nH]1)C(=O)O")
_TYROSINE_IKS = _ik1("NC(Cc1ccc(O)cc1)C(=O)O")
_REDUCING_SUGAR_IKS = _ik1("OCC1OC(O)C(O)C(O)C1O", "OCC1(O)OCC(O)C(O)C1O") # glucose, fructose
# (roles required, process required or None, byproduct, note). Process tags:
# "high_heat", "refining", "fermentation". A None process = forms without a
# special step. Process-gated rules with no declared process surface as CONDITIONAL.
_HAZARDS = [
({"benzoate", "ascorbate"}, None,
"benzene (a carcinogen), favored by heat/light",
"Documented in soft drinks; FDA-investigated."),
({"nitrite", "secondary_amine"}, None,
"N-nitrosamines (carcinogenic)",
"Classic cured-food chemistry."),
({"ethanol", "urea"}, None,
"ethyl carbamate / urethane (probable carcinogen)",
"Relevant to spirits / fermented products."),
({"ethanol", "citrulline"}, None,
"ethyl carbamate (probable carcinogen)",
"Citrulline route β stone-fruit spirits especially."),
({"asparagine", "reducing_sugar"}, {"high_heat"},
"acrylamide (probable carcinogen)",
"Maillard route, >120C. Precursor co-occurrence, not a yield prediction."),
({"reducing_sugar"}, {"high_heat"},
"furan / furfural (possible carcinogen)",
"Sugar pyrolysis under heat (also in heat-processed/canned products)."),
({"ascorbate"}, {"high_heat"},
"furan (possible carcinogen)",
"Ascorbic-acid thermal degradation."),
({"glyceride", "chloride"}, {"high_heat", "refining"},
"3-MCPD / glycidyl esters (process contaminants)",
"Acylglycerol + chloride at high heat / oil refining."),
({"ammonium", "reducing_sugar"}, {"high_heat"},
"4-methylimidazole (in ammonia caramel colours)",
"Caramelisation with an ammonia source."),
({"histidine"}, {"fermentation"},
"histamine (biogenic amine)",
"Amino-acid decarboxylation in fermentation / spoilage."),
({"tyrosine"}, {"fermentation"},
"tyramine (biogenic amine)",
"Amino-acid decarboxylation in fermentation / spoilage."),
]
# EU declarable fragrance/flavor allergens (a regulatory labeling list β a clean
# lookup). A curated subset of the classic 26; expand from the official annex.
_EU_ALLERGEN_IKS = {}
for _nm, _smi in {
"limonene": "CC(=C)C1CCC(C)=CC1", "linalool": "CC(C)=CCCC(C)(O)C=C",
"citronellol": "CC(CCC=C(C)C)CCO", "geraniol": "CC(C)=CCC/C(C)=C/CO",
"eugenol": "C=CCc1ccc(O)c(OC)c1", "isoeugenol": "CC=Cc1ccc(O)c(OC)c1",
"cinnamaldehyde": "O=C/C=C/c1ccccc1", "cinnamyl alcohol": "OC/C=C/c1ccccc1",
"coumarin": "O=c1ccc2ccccc2o1", "citral": "CC(=CCCC(=CC=O)C)C",
"benzyl alcohol": "OCc1ccccc1", "farnesol": "CC(C)=CCC/C(C)=C/CC/C(C)=C/CO",
}.items():
_EU_ALLERGEN_IKS.update({k: _nm for k in _ik1(_smi)})
def _load_rf(path):
"""Load a joblib RF head and pin n_jobs=1. These forests were trained with n_jobs=-1, which
makes a SINGLE-sample predict_proba spawn a joblib thread pool on every call β ~150 ms of
pure overhead that dwarfs the actual work and thrashes all cores under any concurrency.
Single-threaded C tree traversal is far faster for our one-row inference, and it releases
the GIL, so the app can parallelize a level up (e.g. per-ingredient in the Formulation
Studio) instead of fighting joblib. Measured: ~3.8 s -> ~1.2 s per 24-head aroma read."""
mdl = joblib.load(path)
if hasattr(mdl, "n_jobs"):
with contextlib.suppress(Exception): # some wrapped estimators reject the set; harmless
mdl.n_jobs = 1
return mdl
# Model heads are loaded on a BACKGROUND THREAD at import (see _load_all_models below) so that
# `import predict` returns immediately and the web server can bind its port right away, showing a
# friendly "warming up" page while the ~180 forests (628 MB) load β instead of a 34 s startup 502.
# The load is fanned out across cores (joblib.load releases the GIL), which also cuts the wall time.
_CLASSIFIERS = {} # sweet/bitter/umami/... taste heads
_INTENSITY = None # sweet-intensity regressor
_TASTE_META = {} # taste -> {auroc, ...} from taste_models/manifest.json (held-out score)
_TOX_MODELS = {} # Tox21 caution-only assay heads (INDICATIVE, never a determination)
_TOX_META = {} # assay -> {auroc, n_pos, ...} from tox_models/manifest.json (held-out CV)
_TOX_DIR = artifact("tox_models")
_AROMA_MODELS = {} # HSDB odor-descriptor heads (presence/absence; NOT intensity)
_AROMA_META = {}
_AROMA_DIR = artifact("aroma_models")
_MOUTHFEEL_MODELS = {} # trigeminal/chemesthesis heads (warming/astringent/tingling), own modality
_MOUTHFEEL_META = {}
_MOUTHFEEL_DIR = artifact("mouthfeel_models")
MODELS_READY = _threading.Event() # set once every head is loaded; the app gates requests on this
_INFER_POOL = None # shared thread pool for fanning a novel-molecule read across cores (lazy)
def _infer_pool():
"""A process-wide thread pool for parallel head inference on novel molecules. Sized to ~3/4 of
the box (env FLAVORMANCER_INFER_WORKERS overrides) so a fresh 195-head read rips across cores
(~40 s -> a couple of seconds). Shared, so many concurrent novel reads share one bounded pool
instead of each spawning its own β in-corpus reads never touch it (they hit the index)."""
global _INFER_POOL
if _INFER_POOL is None:
env = os.environ.get("FLAVORMANCER_INFER_WORKERS")
# ~3/4 of the box's cores (leaving headroom for the web server), derived from the actual
# cpu count β scales from a 4-core laptop (3 workers) to a 32-core server (24), no fixed cap.
workers = int(env) if env else max(2, (os.cpu_count() or 4) * 3 // 4)
_INFER_POOL = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="infer")
return _INFER_POOL
# live progress for the warming-up page: how many heads are loaded, and the phase label
LOAD_PROGRESS = {"loaded": 0, "total": 0, "phase": "starting", "ready": False, "started": None}
def load_status():
"""Snapshot of the model-load progress for the warming-up page: loaded/total heads, phase,
ready flag, and seconds elapsed since loading began (for a client-side ETA)."""
with _LOAD_LOCK:
s = dict(LOAD_PROGRESS)
started = s.pop("started", None)
s["elapsed"] = round(_time.monotonic() - started, 1) if started else 0.0
s["ready"] = MODELS_READY.is_set()
return s
_LOAD_LOCK = _threading.Lock()
def _load_all_models():
"""Discover and load every trained head (taste + tox + aroma), updating LOAD_PROGRESS as each
lands, then set MODELS_READY. Runs on a daemon thread from import so the port binds instantly.
Loading is SERIAL, and BOTH ways of parallelising it have now been measured and rejected:
threads WORSE than serial (~34 s serial vs ~86 s across 14 threads). joblib.load is
dominated by GIL-bound Python unpickling, so threads only add contention.
processes 3.1x FASTER in isolation β 40 files take 11.5 s serial and 3.7 s across a
ProcessPoolExecutor, transfer of the deserialised forests included. But this
function runs DURING MODULE IMPORT, and forking while the interpreter holds the
import lock deadlocks: the children inherit a locked import machinery they can
never acquire. Tried it; the parent and every worker hung indefinitely.
The process pool is the right answer, but only once loading is deferred out of import time
(a FastAPI startup hook, or an explicit warm() the server calls) β see #225. Until then serial
is correct, and the warming page makes the ~50 s visible rather than mysterious.
The win from cores comes at INFERENCE time instead (predict_proba releases the GIL) β see
_aroma_scores_canon."""
jobs = [] # (kind, name, path)
if TASTE.exists():
jobs += [("taste", p.stem.replace("_rf", ""), p) for p in TASTE.glob("*_rf.joblib")]
if _TOX_DIR.exists():
jobs += [("tox", p.stem.replace("_rf", ""), p) for p in _TOX_DIR.glob("*_rf.joblib")]
if _AROMA_DIR.exists():
jobs += [("aroma", p.stem.replace("_clf", ""), p) for p in _AROMA_DIR.glob("*_clf.joblib")]
if _MOUTHFEEL_DIR.exists():
jobs += [("mouthfeel", p.stem.replace("_clf", ""), p) for p in _MOUTHFEEL_DIR.glob("*_clf.joblib")]
with _LOAD_LOCK:
LOAD_PROGRESS["total"] = len(jobs)
LOAD_PROGRESS["phase"] = "loading models"
LOAD_PROGRESS["started"] = _time.monotonic()
for kind, name, p in jobs:
mdl = _load_rf(p)
if kind == "taste":
if name == "sweet_intensity":
globals()["_INTENSITY"] = mdl
else:
_CLASSIFIERS[name] = mdl
elif kind == "tox":
_TOX_MODELS[name] = mdl
elif kind == "mouthfeel":
_MOUTHFEEL_MODELS[name] = mdl
else:
_AROMA_MODELS[name] = mdl
with _LOAD_LOCK:
LOAD_PROGRESS["loaded"] += 1
# manifests (small JSON, load after the heads)
import json as _json
_tm = TASTE / "manifest.json"
if _tm.exists():
globals()["_TASTE_META"] = _json.loads(_tm.read_text())
_mf = _AROMA_DIR / "manifest.json"
if _mf.exists():
globals()["_AROMA_META"] = _json.loads(_mf.read_text()).get("descriptors", {})
_txf = _TOX_DIR / "manifest.json"
if _txf.exists():
globals()["_TOX_META"] = _json.loads(_txf.read_text()).get("assays", {})
_mff = _MOUTHFEEL_DIR / "manifest.json"
if _mff.exists():
globals()["_MOUTHFEEL_META"] = _json.loads(_mff.read_text()).get("descriptors", {})
with _LOAD_LOCK:
LOAD_PROGRESS["phase"] = "ready"
LOAD_PROGRESS["ready"] = True
MODELS_READY.set()
# Kick off loading in the background. Set FLAVORMANCER_BLOCKING_LOAD=1 (tests, CLI, batch jobs) to
# load synchronously instead. Set FLAVORMANCER_NO_MODELS=1 to skip loading entirely β for tools that
# only need featurization (_feat / _MORGAN), like the parallel index builder, which loads each head
# in its own worker process rather than in this parent.
if os.environ.get("FLAVORMANCER_NO_MODELS") == "1":
# Skip loading, but still mark READY. Leaving the event unset meant the app's warming gate
# returned 503 to every request FOREVER β a models-less install was not "degraded", it was
# dead, which is the opposite of what the docs promised. Structure-derived answers (physchem,
# the sour/salty rules, applicability, substructure) need no heads at all and should be served.
with _LOAD_LOCK:
LOAD_PROGRESS["phase"] = "ready (no models)"
LOAD_PROGRESS["ready"] = True
MODELS_READY.set()
elif os.environ.get("FLAVORMANCER_BLOCKING_LOAD") == "1":
_load_all_models()
else:
_threading.Thread(target=_load_all_models, name="model-loader", daemon=True).start()
# Known-label lookup: ground truth for molecules we actually have data on. This
# is how the salty/sour data works as a FLAG without a model β if a queried
# molecule is in our labeled set, we report the verified fact instead of a guess.
_KNOWN = {} # inchikey -> {taste: 1}
_MASTER = artifact("taste_master.parquet")
# The neighbor / substitute reference set: the FULL molecule universe (every structure we know,
# ~8.8k) so structural neighbors and profile substitutes can surface ANY molecule β e.g. ethyl
# vanillin as the top vanillin substitute β not just the taste-labelled subset. Falls back to
# taste_master when the enrichment table hasn't been built yet.
_UNIVERSE = artifact("master_enrichment.parquet")
if _MASTER.exists():
import pandas as pd
_m = pd.read_parquet(_MASTER)
_basic = [t for t in ("sweet", "bitter", "umami", "sour", "salty") if t in _m.columns]
for _, _r in _m.iterrows():
_labels = {t: 1 for t in _basic if _r[t] == 1}
if _labels:
_KNOWN[_r["inchikey"]] = _labels
# Optional GRAS / approved-flavor reference. The strongest *defensive* signal is
# not a tox model but "is this a recognized food ingredient at all?". Drop a
# reference list (e.g. the FEMA GRAS list) at gras_reference.parquet with an
# 'inchikey' column and we cross-check against it; absent the file we say so
# honestly rather than guessing.
_GRAS = set()
_GRAS_FILE = artifact("gras_reference.parquet")
if _GRAS_FILE.exists():
import pandas as pd
_g = pd.read_parquet(_GRAS_FILE)
if "inchikey" in _g.columns:
_GRAS = {str(k).split("-")[0] for k in _g["inchikey"].dropna()}
# Curated food-clearance supplement (food_safe_supplement.csv) β a few molecules that carry an
# aroma head but are NOT in the FDA SAF crawl, each backed by an OPEN-GOVERNMENT register only:
# the EU Union List (Reg. 1334/2008 Annex I, via data.food.gov.uk under the Open Government
# Licence) or US 21 CFR (public-domain law). Regulatory facts are non-copyrightable (Feist);
# no commercial compilation is used. Union into the same defensive "recognized food ingredient?"
# signal so these read as food-cleared everywhere the SAF list does.
def _foodsafe_label(fl, cfr):
"""Compose an accurate, specific food-use label + jurisdiction from the open-gov citations.
Distinguishes true GRAS (21 CFR 182/184), FEMA GRAS (a FEMA number), an approved food additive
(21 CFR 172), and an EU-authorised flavouring (EU FL) β never a blanket 'GRAS'."""
fl, cfr = (fl or "").strip(), (cfr or "").strip()
refs = [r for r in (f"EU FL {fl}" if fl else "", cfr) if r]
juris = "US + EU" if (fl and cfr) else ("EU" if fl else ("US" if cfr else ""))
low = cfr.lower()
if "fema" in low:
term = "FEMA GRAS"
elif "182" in cfr or "184" in cfr:
term = "GRAS"
elif "172" in cfr:
term = "approved food additive"
elif fl:
term = "EU-authorised flavouring"
else:
term = "authorised food ingredient"
tag = f" ({juris} only)" if juris in ("US", "EU") else (f" ({juris})" if juris else "")
return f"{term} β {' & '.join(refs)}{tag}" if refs else term
_FOODSAFE_FILE = artifact("food_safe_supplement.csv")
_FOODSAFE_BASIS = {} # skeleton -> specific open-gov label (term + refs + jurisdiction)
if _FOODSAFE_FILE.exists():
import pandas as pd
# dtype=str + keep_default_na=False so FL numbers keep leading zeros ("07.142", not 7.142)
# and empty cells read as "" rather than NaN.
_fs = pd.read_csv(_FOODSAFE_FILE, dtype=str, keep_default_na=False)
if "inchikey" in _fs.columns:
_GRAS |= {str(k).split("-")[0] for k in _fs["inchikey"].dropna()}
def _clean(v):
s = str(v).strip()
return "" if s.lower() in ("", "nan", "none") else s
for _, _r in _fs.iterrows():
_sk = str(_r.get("inchikey", "")).split("-")[0]
_fl, _cfr = _clean(_r.get("eu_fl")), _clean(_r.get("us_cfr"))
if _sk and (_fl or _cfr):
_FOODSAFE_BASIS[_sk] = _foodsafe_label(_fl, _cfr)
# Bulk EU/GB flavourings Union List (gb_union_list.csv, ~2,200 authorised entries). The full
# authorisation register from data.food.gov.uk (Open Government Licence v3 β commercial reuse
# permitted); every AUTHORISED row is a food-cleared flavouring cited by its FL number. Union into
# the food-use reference so the whole authorised list reads food-listed with a specific citation.
# The FILE is a private data asset (gitignored); this LOADER is open framework.
_GB_FILE = artifact("gb_union_list.csv")
if _GB_FILE.exists():
import pandas as pd
_gb = pd.read_csv(_GB_FILE, dtype=str, keep_default_na=False)
for _, _r in _gb.iterrows():
if str(_r.get("status", "")).strip().lower() != "authorised":
continue
_sk = str(_r.get("inchikey", "")).split("-")[0]
_fl = str(_r.get("fl", "")).strip()
if not _sk or not _fl:
continue
_GRAS.add(_sk)
_FOODSAFE_BASIS.setdefault(_sk, _foodsafe_label(_fl, "")) # curated citation wins if present
# Optional measured-property + dosing table. Data-gated like GRAS. Drop
# properties.(parquet|csv) with an 'inchikey' column and any of:
# odor_threshold_ppm, fema_use_max_ppm, boiling_point_c, vapor_pressure_pa.
# We use MEASURED values (lookup) rather than structure estimates for these,
# because structure-based volatility (e.g. Joback) is too inaccurate for flavor
# molecules to report as a number β benzaldehyde misses by ~90 C.
_PROPS = {}
_PROP_COLS = ("odor_threshold_ppm", "fema_use_max_ppm", "boiling_point_c",
"boiling_point_pressure_mmhg", "vapor_pressure_pa", "melting_point_c")
for _ext in ("properties.parquet", "properties.csv"):
_pf = Path(_ext)
if _pf.exists():
import pandas as pd
_pp = pd.read_parquet(_pf) if _ext.endswith("parquet") else pd.read_csv(_pf)
if "inchikey" in _pp.columns:
for _, _r in _pp.iterrows():
vals = {c: float(_r[c]) for c in _PROP_COLS if c in _pp.columns and pd.notna(_r.get(c))}
if vals:
_PROPS[str(_r["inchikey"]).split("-")[0]] = vals
break
def _measured(mol):
return _PROPS.get(Chem.MolToInchiKey(mol).split("-")[0], {})
def _fp(mol):
bv = _MORGAN.GetFingerprint(mol)
arr = np.zeros((FP_BITS,), dtype=np.int8)
DataStructs.ConvertToNumpyArray(bv, arr)
return arr.reshape(1, -1)
def _feat(mol):
"""Model input for the taste & aroma heads: the Morgan fingerprint PLUS the shared
physicochemical descriptor block (see chemfeatures.py) β identical to how they were trained.
Tox stays on the pure fingerprint; similarity/UMAP also keep the pure bits."""
from chemfeatures import descriptors as _desc
return np.hstack([_fp(mol).astype(np.float32), _desc(mol).reshape(1, -1)])
def _sour(mol):
hits = [n for n, pat in _ACID.items() if pat is not None and mol.HasSubstructMatch(pat)]
return {"sour": bool(hits), "sour_reason": hits}
def _is_salt_cation(frag):
"""A lone alkali-metal atom, or an ammonium (NH4+) β the salt-forming cations."""
heavy = [a for a in frag.GetAtoms() if a.GetAtomicNum() > 1]
if len(heavy) != 1:
return None
a = heavy[0]
if a.GetAtomicNum() in _ALKALI_Z:
return _SYM[a.GetAtomicNum()]
# ammonium: a single N(+) carrying 4 H and no heavy neighbors
if (a.GetAtomicNum() == 7 and a.GetFormalCharge() == 1
and a.GetTotalNumHs() == 4):
return "NH4"
return None
def _has_carbon(frag):
return any(a.GetAtomicNum() == 6 for a in frag.GetAtoms())
def _salty(mol):
"""Fire only for simple inorganic alkali/ammonium salts; defer on organic anions.
Mirrors the sour rule, but cation-aware: NaCl/KCl/NH4Cl -> salty; MSG /
Na-saccharin / Na-benzoate -> NOT salty (organic anion owns the taste).
"""
frags = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
if len(frags) < 2:
return {"salty": False, "salty_reason": "no alkali-salt structure"}
cations, others = [], []
for f in frags:
sym = _is_salt_cation(f)
(cations if sym else others).append(sym or f)
cations = [c for c in cations if c]
if not cations or not others:
return {"salty": False, "salty_reason": "no alkali-salt structure"}
if any(_has_carbon(f) for f in others):
# cation present, but a carbon-bearing anion drives the percept
return {"salty": False, "salty_reason": "organic anion dominates (defer to anion taste)"}
return {"salty": True, "salty_reason": f"inorganic {'/'.join(sorted(set(cations)))} salt"}
def _tox_alerts(mol):
"""Caution-only structural alerts. NOT toxicity verdicts β prompts for review."""
return [n for n, pat in _TOX.items() if pat is not None and mol.HasSubstructMatch(pat)]
def _gras_status(mol):
"""Defensive 'is this even a recognized food ingredient?' check β NOT a GRAS or safety
determination. The reference is a union of FDA's *Substances Added to Food* (SAF) inventory
(public domain; broader than GRAS) and a curated EU/GB flavourings + 21 CFR set
(`food_safe_supplement.csv`, open-government). We report *listing*, with the specific
authority where known, and never claim a molecule is "GRAS" unless it actually is."""
if not _GRAS:
return "no food-use reference loaded β not checked"
ik = Chem.MolToInchiKey(mol).split("-")[0]
if ik in _FOODSAFE_BASIS:
return _FOODSAFE_BASIS[ik] # e.g. "FEMA GRAS β FDA SAF (FEMA 3434) (US only)"
if ik in _GRAS:
return "listed in the FDA Substances-Added-to-Food food-use reference (US)"
return "not in the food-use reference β unverified for food use"
def _safety(mol):
alerts = _tox_alerts(mol)
return {
"disclaimer": SAFETY_DISCLAIMER,
"scope": "Taste/aroma only β not a safety/toxicity/GRAS/stability determination.",
"structural_alerts": alerts, # caution prompts, may be empty
"gras_status": _gras_status(mol),
"review_required": True,
}
def _roles(mol):
"""Detect the reactive 'roles' used by the hazard screen."""
r = set()
if _BENZOATE is not None and mol.HasSubstructMatch(_BENZOATE):
r.add("benzoate")
if _NITRITE is not None and mol.HasSubstructMatch(_NITRITE):
r.add("nitrite")
if _SEC_AMINE is not None and mol.HasSubstructMatch(_SEC_AMINE):
r.add("secondary_amine")
if _UREA is not None and mol.HasSubstructMatch(_UREA):
r.add("urea")
if _CHLORIDE is not None and mol.HasSubstructMatch(_CHLORIDE):
r.add("chloride")
if _AMMONIUM_ION is not None and mol.HasSubstructMatch(_AMMONIUM_ION):
r.add("ammonium")
if (_GLYCEROL_BB is not None and _ACYL_ESTER is not None
and mol.HasSubstructMatch(_GLYCEROL_BB) and mol.HasSubstructMatch(_ACYL_ESTER)):
r.add("glyceride")
ik = Chem.MolToInchiKey(mol).split("-")[0]
for tag, ikset in (("ascorbate", _ASCORBATE_IKS), ("ethanol", _ETHANOL_IKS),
("asparagine", _ASPARAGINE_IKS), ("citrulline", _CITRULLINE_IKS),
("histidine", _HISTIDINE_IKS), ("tyrosine", _TYROSINE_IKS),
("reducing_sugar", _REDUCING_SUGAR_IKS)):
if ik in ikset:
r.add(tag)
return r
def check_mixture(ingredients, processes=None) -> dict:
"""Flag DOCUMENTED food hazards in a formulation. Curated, NOT a reaction predictor.
ingredients: list of SMILES strings, or list of {"smiles": ...} dicts.
processes: optional set/list of process tags the product undergoes β
"high_heat", "refining", "fermentation". Hazards that require a
process surface as ACTIVE when the process is declared, or as
CONDITIONAL ("would form if ...") when it isn't.
"""
procs = set(processes or [])
present, parsed = set(), []
for ing in ingredients:
smi = ing["smiles"] if isinstance(ing, dict) else ing
m = Chem.MolFromSmiles(smi or "")
if m is not None:
parsed.append(Chem.MolToSmiles(m))
present |= _roles(m)
active, conditional = [], []
for roles, need_proc, product, note in _HAZARDS:
if not roles <= present:
continue
entry = {"precursors": sorted(roles), "possible_product": product, "note": note}
if need_proc is None or (procs & need_proc):
active.append(entry)
else:
entry["requires_process"] = sorted(need_proc)
conditional.append(entry)
return {
"ingredients_parsed": parsed,
"processes_declared": sorted(procs),
"active_hazards": active,
"conditional_hazards": conditional,
"scope_note": "Documented precursor/process hazards only β NOT a general reaction "
"predictor and NOT a yield or stability assay.",
"disclaimer": SAFETY_DISCLAIMER,
}
def labeling(mol):
"""Regulatory labeling flags β currently EU declarable fragrance/flavor allergens (lookup)."""
name = _EU_ALLERGEN_IKS.get(Chem.MolToInchiKey(mol).split("-")[0])
return {"eu_declarable_allergen": bool(name),
"allergen_name": name,
"note": "EU fragrance-allergen labeling list (curated subset) β a regulatory lookup"}
# ββ Physicochemical pack: how the molecule behaves in a beverage ββββββββββββββ
# computed = exact from structure; estimate = published QSPR w/ error; qualitative = a class flag
_OXIDIZABLE = {
"phenol/catechol": "[OX2H][c]",
"thiol": "[SX2H]",
"aldehyde": "[CX3H1]=O",
"1,3-diene (autoxidation)": "[CX3]=[CX3][CX3]=[CX3]",
}
_HYDROLYZABLE = {
"ester": "[CX3](=O)[OX2H0][#6;!$([CX3]=O)]",
"lactone (cyclic ester)": "[CX3;R](=O)[OX2H0;R]",
"acetal/glycoside": "[CX4]([OX2H0])[OX2H0]",
"amide (slow)": "[CX3](=O)[NX3]",
}
_PHOTOLABILE = {
"extended polyene": "[CX3]=[CX3][CX3]=[CX3][CX3]=[CX3]",
"aryl ketone": "[c][CX3](=O)[#6]",
"nitroaromatic": "[c][$([NX3](=O)=O),$([N+](=O)[O-])]",
}
_IONIZABLE = [ # (name, SMARTS, typical pKa, character)
("sulfonic acid", "[SX4](=O)(=O)[OX2H1]", "~ -1 to 2", "strong acid"),
("carboxylic acid", "[CX3](=O)[OX2H1]", "~3-5", "acid"),
("phenol", "[OX2H][c]", "~9-10", "weak acid"),
("aromatic amine (aniline)", "[NX3;H2,H1][c]", "~4-5 (conj. acid)", "weak base"),
("aliphatic amine", "[NX3;H2,H1;!$(N[#6]=[O,N,S]);!$(N[c])]", "~9-11 (conj. acid)", "base"),
]
_OX = {k: Chem.MolFromSmarts(v) for k, v in _OXIDIZABLE.items()}
_HY = {k: Chem.MolFromSmarts(v) for k, v in _HYDROLYZABLE.items()}
_PH = {k: Chem.MolFromSmarts(v) for k, v in _PHOTOLABILE.items()}
_ION = [(n, Chem.MolFromSmarts(s), p, c) for n, s, p, c in _IONIZABLE]
_PHENOL = Chem.MolFromSmarts("[OX2H][c]")
# Chemesthetic / trigeminal classes (curated, qualitative)
_ISOTHIOCYANATE = Chem.MolFromSmarts("[NX2]=[CX2]=[SX1]") # pungent (mustard/wasabi)
_COOLING_IKS = _ik1("CC(C)C1CCC(C)CC1O") # menthol (expand: WS-3/WS-23, etc.)
_PUNGENT_IKS = _ik1("CC(C)/C=C/CCCCC(=O)NCc1ccc(O)c(OC)c1", # capsaicin
"C1CCN(CC1)C(=O)/C=C/C=C/c1ccc2c(c1)OCO2") # piperine
def physchem(mol):
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
tpsa = Descriptors.TPSA(mol)
hbd, hba = Descriptors.NumHDonors(mol), Descriptors.NumHAcceptors(mol)
rot = Descriptors.NumRotatableBonds(mol)
arom = rdMolDescriptors.CalcNumAromaticRings(mol)
heavy = mol.GetNumHeavyAtoms()
ap = (sum(1 for a in mol.GetAtoms() if a.GetIsAromatic()) / heavy) if heavy else 0.0
# ESOL (Delaney 2004): log mol/L water solubility β estimate, ~0.7 log RMSE
logS = 0.16 - 0.63 * logp - 0.0062 * mw + 0.066 * rot - 0.74 * ap
if mw < 250 and hbd <= 1 and tpsa < 60:
vol = "high (likely top/volatile note)"
elif mw < 400 and tpsa < 100:
vol = "moderate (middle note)"
else:
vol = "low (base note / largely non-volatile)"
ions = [{"group": n, "typical_pKa": p, "character": c}
for n, pat, p, c in _ION if pat is not None and mol.HasSubstructMatch(pat)]
result = {
"computed": {
"mol_weight": round(mw, 2), "logP": round(logp, 2), "tpsa": round(tpsa, 1),
"h_bond_donors": hbd, "h_bond_acceptors": hba,
"rotatable_bonds": rot, "aromatic_rings": arom, "heavy_atoms": heavy,
},
"estimate": {
"water_solubility_logS": round(logS, 2),
"note": "ESOL estimate (log mol/L), ~0.7 log RMSE",
},
"qualitative": {
"aroma_volatility": vol,
"volatility_note": "heuristic from size/polarity. Quantitative BP/vapor pressure "
"is a MEASURED lookup, not estimated (Joback too inaccurate here).",
"ionizable_groups": ions,
"pKa_note": "typical group ranges β NOT a computed per-molecule pKa",
},
}
meas = _measured(mol)
if meas:
result["measured"] = {**{k: meas[k] for k in meas}, "source": "loaded property table"}
# Flavorist formulation hints: carrier-solvent need (from estimated water solubility) and
# room-temperature phase (from measured melting/boiling point, when the table has them).
form = {}
if logS <= -3:
form["carrier"] = (f"poorly water-soluble (logS {logS:.1f}) β needs a carrier solvent "
"(propylene glycol, ethanol, or triacetin) to disperse in a water-based product")
elif logS <= -1.5:
form["carrier"] = (f"limited water solubility (logS {logS:.1f}) β a little propylene glycol "
"or ethanol helps it dissolve in water")
else:
form["carrier"] = f"reasonably water-soluble (logS {logS:.1f}) β usually no carrier needed"
bp = (meas or {}).get("boiling_point_c")
mp = (meas or {}).get("melting_point_c")
if bp is not None and bp < 25:
form["phase_at_rt"] = "gas"
elif mp is not None:
form["phase_at_rt"] = "solid" if mp > 25 else "liquid"
result["formulation"] = form
return result
def chirality(mol):
"""Stereo flag: enantiomers can taste/smell differently (R-carvone spearmint vs S caraway).
We detect chiral centers (assigned or potential) and flag it honestly β the current models
are achiral, so this is a caveat, not an enantiomer-specific prediction (see docs/AROMA.md)."""
centers = Chem.FindMolChiralCenters(mol, includeUnassigned=True, useLegacyImplementation=False)
if not centers:
return {"is_chiral": False}
assigned = [c for c in centers if c[1] not in ("?", "u")]
return {"is_chiral": True, "n_centers": len(centers),
"specified": len(assigned) == len(centers),
"note": ("chiral β enantiomers can differ in taste/aroma; the current read is the same "
"for both mirror images (achiral model). Draw the stereochemistry (isomeric "
"SMILES) for the specific enantiomer's documented odor where PubChem has it.")}
def _stereo_label(mol):
"""A compact stereo-descriptor for one fully-specified isomer: tetrahedral R/S per center
(with atom map) and E/Z per double bond β e.g. '(R)', '(2R,3S)', '(E)', '(1Z,2R)'. Covers
ALL stereochemistry RDKit tracks, not just a single R/S center."""
Chem.AssignStereochemistry(mol, cleanIt=True, force=True)
parts = []
# read double-bond E/Z FIRST β FindMolChiralCenters re-perceives stereo and clears bond flags
for b in mol.GetBonds():
s = b.GetStereo()
if s == Chem.BondStereo.STEREOE:
parts.append((b.GetBeginAtomIdx(), "E"))
elif s == Chem.BondStereo.STEREOZ:
parts.append((b.GetBeginAtomIdx(), "Z"))
for idx, code in Chem.FindMolChiralCenters(mol, includeUnassigned=True,
useLegacyImplementation=False):
parts.append((idx, code))
parts.sort()
codes = [c for _, c in parts]
return "(" + ",".join(codes) + ")" if codes else "(achiral)"
def stereoisomers(smiles, max_isomers=24):
"""Enumerate EVERY stereoisomer of a structure β all tetrahedral (R/S) and double-bond (E/Z)
combinations, not just one R/S pair. Returns a list of {smiles (isomeric), inchikey, label,
n_stereo}, capped at max_isomers so a molecule with many centers can't blow up. Empty when the
molecule has no stereochemistry to vary."""
from rdkit.Chem.EnumerateStereoisomers import (
EnumerateStereoisomers,
StereoEnumerationOptions,
)
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return []
centers = Chem.FindMolChiralCenters(mol, includeUnassigned=True, useLegacyImplementation=False)
ez = sum(1 for b in mol.GetBonds() if b.GetStereo() != Chem.BondStereo.STEREONONE
or (b.GetBondType() == Chem.BondType.DOUBLE and not b.GetIsAromatic()
and b.GetBeginAtom().GetDegree() > 1 and b.GetEndAtom().GetDegree() > 1))
if not centers and ez == 0:
return []
# onlyUnassigned=False -> flip ALL centers/bonds (every isomer), unique to dedupe meso forms
opts = StereoEnumerationOptions(onlyUnassigned=False, unique=True, maxIsomers=max_isomers)
out, seen = [], set()
for iso in EnumerateStereoisomers(mol, options=opts):
Chem.AssignStereochemistry(iso, cleanIt=True, force=True)
smi = Chem.MolToSmiles(iso)
ik = Chem.MolToInchiKey(iso)
if ik in seen:
continue
seen.add(ik)
out.append({"smiles": smi, "inchikey": ik, "label": _stereo_label(iso),
"n_stereo": len(centers) + ez})
out.sort(key=lambda r: r["label"])
return out
def stability(mol):
def hits(d):
return [n for n, p in d.items() if p is not None and mol.HasSubstructMatch(p)]
return {
"oxidation_watch": hits(_OX),
"hydrolysis_watch": hits(_HY),
"photodegradation_watch": hits(_PH),
"note": "qualitative 'watch for' flags from reactive motifs β not a shelf-life prediction",
}
def chemesthesis(mol):
"""Trigeminal/chemesthetic class flags (cooling/pungent/astringent) β qualitative."""
classes = []
if _ISOTHIOCYANATE is not None and mol.HasSubstructMatch(_ISOTHIOCYANATE):
classes.append("pungent (isothiocyanate β mustard/wasabi type)")
if _PHENOL is not None and len(mol.GetSubstructMatches(_PHENOL)) >= 3:
classes.append("astringent (polyphenol/tannin-like)")
ik = Chem.MolToInchiKey(mol).split("-")[0]
if ik in _COOLING_IKS:
classes.append("cooling (TRPM8 β menthol type)")
if ik in _PUNGENT_IKS:
classes.append("pungent/warming (TRPV1/TRPA1 β capsaicin/piperine type)")
return {"classes": classes,
"note": "curated structural / known-compound class flags, qualitative"}
def ttc_hint(mol):
"""PRELIMINARY toxicological-concern tier β NOT validated Cramer classification.
Conservative heuristic (errs toward higher concern). Use Toxtree for the real
Cramer/TTC call; this is a first-glance indicator only.
"""
alerts = _tox_alerts(mol)
elements = {a.GetSymbol() for a in mol.GetAtoms()}
uncommon = elements - {"C", "H", "O", "N", "S", "P", "Cl", "Na", "K"}
if alerts or uncommon:
tier = "III β higher concern (structural alert or uncommon element)"
elif elements <= {"C", "H", "O"} and Descriptors.MolWt(mol) < 200:
tier = "I β lower concern (simple, common-element structure)"
else:
tier = "II β intermediate (review)"
return {"preliminary_tier": tier,
"drivers": {"alerts": alerts, "uncommon_elements": sorted(uncommon)},
"note": "PRELIMINARY heuristic, not validated Cramer/TTC β use Toxtree for the real call"}
def retention_index(mol):
"""GC-MS Kovats retention index β a trained-QSPR task (solid on public NIST
data). Hook for a loaded model; honest stub until one is wired in."""
return {"kovats_ri": None,
"note": "needs a trained RI QSPR (public data exists) β not estimated here"}
def analyze_balance(ingredients):
"""Rank a formulation by aroma impact and flag overbearing components.
ingredients: list of {"smiles": str, "ppm": float (optional), "name": str (optional)}
Quantitative when odor thresholds are loaded β odor activity value
OAV = concentration / detection threshold; the highest-OAV component
dominates the blend. Falls back to a qualitative volatility ranking when no
thresholds are loaded. Also flags any dose above a loaded FEMA max use level.
This ranks SINGLE-MOLECULE impact; it does NOT predict finished-blend
perception (suppression/synergy need panel data β see the paid pilot).
"""
rows = []
for ing in ingredients:
m = Chem.MolFromSmiles(ing.get("smiles", ""))
if m is None:
rows.append({"input": ing, "error": "unparseable SMILES"})
continue
meas = _measured(m)
ppm = ing.get("ppm")
thr = meas.get("odor_threshold_ppm")
oav = (ppm / thr) if (ppm is not None and thr) else None
over = (ppm > meas["fema_use_max_ppm"]) if (ppm is not None and meas.get("fema_use_max_ppm")) else None
rows.append({
"name": ing.get("name"), "smiles": Chem.MolToSmiles(m), "ppm": ppm,
"odor_threshold_ppm": thr, "OAV": round(oav, 2) if oav is not None else None,
"volatility": physchem(m)["qualitative"]["aroma_volatility"],
"over_fema_max": over,
})
warnings = []
have = [r for r in rows if r.get("OAV")]
if have:
have.sort(key=lambda r: r["OAV"], reverse=True)
total = sum(r["OAV"] for r in have)
top = have[0]
if total > 0 and top["OAV"] / total > 0.6:
warnings.append(
f"{top['name'] or top['smiles']} dominates (~{round(100 * top['OAV'] / total)}% "
"of total odor activity) β likely overbearing")
ranking = [{"name": r["name"] or r["smiles"], "OAV": r["OAV"]} for r in have]
basis = "quantitative (OAV = ppm / odor threshold)"
else:
order = {"high": 0, "moderate": 1, "low": 2}
sr = sorted((r for r in rows if "volatility" in r),
key=lambda r: order.get(r["volatility"].split()[0], 3))
ranking = [{"name": r["name"] or r["smiles"], "volatility": r["volatility"]} for r in sr]
basis = "qualitative (volatility tier β load odor thresholds for quantitative OAV)"
for r in rows:
if r.get("over_fema_max"):
warnings.append(f"{r['name'] or r['smiles']}: {r['ppm']} ppm exceeds loaded FEMA max use level")
return {
"per_ingredient": rows,
"impact_ranking": ranking,
"basis": basis,
"balance_warnings": warnings,
"scope_note": "Ranks single-molecule odor impact; does NOT predict finished-blend "
"perception (suppression/synergy need panel data).",
"disclaimer": SAFETY_DISCLAIMER,
}
# Canonical one-line odor-descriptor blurbs β the SINGLE source for the "what does this
# note smell like" help text shown under each aroma bar (workbench), in /api/aroma &
# /api/predict, and in the MCP server / skill output. Keep one entry per shipped head.
AROMA_DESC = {
"odorless": "odorless β no documented smell (water, salts, most sugars, involatile solids); the aroma parallel to tasteless",
"pungent": "sharp / irritating β acrid bite",
"sweet": "sweet-smelling β indicative; clears the bar with odorless negatives, weaker at sweet-vs-other-sweet-odors",
"ammoniacal": "ammonia / amine β sharp, pungent",
"fruity": "ripe fruit β esters & lactones",
"ethereal": "light & volatile β fresh, solvent-like",
"phenolic": "phenolic / carbolic β phenol, cresols & alkylphenols",
"sulfurous": "eggy / alliaceous β sulfur volatiles",
"floral": "flowery β rose, jasmine, violet character",
"acidic": "acidic / vinegar β short-chain carboxylic acids (acetic family)",
"garlic": "allium β pungent sulfur",
"fishy": "amine / trimethylamine β marine",
"camphor": "camphoraceous β cooling, penetrating",
"fatty": "oily / tallowy β long-chain aldehydes & acids",
"almond": "marzipan β benzaldehyde, nutty-sweet",
"minty": "cooling mint β menthol / carvone family",
"spicy": "warm spice β eugenol / cinnamaldehyde / piperine / cuminaldehyde family",
"petroleum": "solvent / naphtha β hydrocarbon character",
"cherry": "cherry β benzaldehyde / almond-fruity aromatics",
"grassy": "grassy β mown hay, cis-3-hexenol",
"fresh": "clean / airy β light aldehydes & dihydromyrcenol",
"grape": "grape / foxy β anthranilate esters (methyl anthranilate)",
"berry": "berry β strawberry / raspberry furanones & esters",
"putrid": "putrid β decay / rotten off-note",
"orange": "sweet orange β limonene, decanal & orange esters",
"muguet": "muguet / lily-of-the-valley β hydroxycitronellal & floral aldehydes",
"waxy": "waxy / fatty β long-chain aldehydes, acids & alcohols",
"alcoholic": "boozy / ethanolic β spirituous",
"citrus": "lemon / orange peel β bright, zesty terpenes",
"herbal": "green-herb / medicinal β thymol, carvacrol, cineole",
"earthy": "soil / beetroot β geosmin-like",
"meaty": "savoury / cooked-meat β sulfur volatiles (furanthiols, thiazoles, methional)",
"musky": "musk β macrocyclic ketones / lactones",
"green": "green β fresh-cut leaf, grassy aldehydes",
"woody": "woody β cedar / sandalwood character",
"pine": "pine / resin β coniferous terpenes (Ξ±-pinene)",
"winey": "fermented / vinous β ethyl esters & lactate",
"burnt": "burnt / roasted β pyrolysis furanones & roast pyrazines",
"tropical": "tropical β pineapple / mango / passionfruit esters & thioesters",
"wintergreen": "wintergreen / teaberry β methyl salicylate & salicylate esters",
"lavender": "lavender β linalool & linalyl esters",
"rose": "rosy floral β geraniol / phenylethanol",
"nutty": "roasted nut / hazelnut β alkylpyrazines",
"anise": "anise / licorice β anethole & anisyl aromatics",
"cheesy": "cheesy / fermented β short & branched fatty acids",
"creamy": "creamy / milky β Ξ³ & Ξ΄ dairy lactones",
"soapy": "soapy β C10βC12 fatty aldehydes & ketones",
"jasmine": "jasmine β jasmonoids (hedione, cis-jasmone) & floral esters",
"neroli": "orange-blossom / neroli β anthranilates & indole over a terpene-alcohol base",
"vanilla": "vanilla β vanillin & guaiacol-derived phenolic aldehydes",
"balsamic": "sweet-resinous balsam β benzyl / cinnamyl esters",
"smoky": "smoke / phenolic β guaiacol & alkylphenols",
"banana": "ripe banana β isoamyl acetate & branched esters",
"vegetable": "green vegetable β methoxypyrazines & sulfides",
"bready": "bread / toasted β pyrazines, pyrrolines & furfural",
"melon": "melon / cucumber β (E,Z)-nonadienals",
"cassis": "blackcurrant / cassis β sulfury cassis thiol & berry esters",
"fennel": "fennel / anise-spice β anethole & terpene spice",
"buttery": "butter / cream β vicinal diketones (diacetyl, acetoin)",
"coconut": "creamy coconut β Ξ³ / Ξ΄ lactones (nonalactone, decalactone)",
"apple": "apple β green-fruity esters (ethyl 2-methylbutyrate, hexyl acetate)",
"coffee": "roasted coffee β furfurylthiols & roast pyrazines",
"peach": "peach β Ξ³ / Ξ΄ lactones (undecalactone) & fruity esters",
"violet": "violet / orris β ionones & irones",
"ginger": "ginger β gingerol / zingerone / zingiberene",
"hay": "new-mown hay β dihydrocoumarin & hay lactones",
"tonka": "tonka / coumarinic β dihydrocoumarin, sweet-hay",
"caramel": "caramel β maltol / furaneol / cyclotene sugar-pyrolysis",
"rancid": "rancid β oxidized fat, stale off-note",
"onion": "alliaceous onion β di/propyl disulfides",