-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
2684 lines (2443 loc) · 144 KB
/
Copy pathcore.py
File metadata and controls
2684 lines (2443 loc) · 144 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
# core.py — pKaNET Cloud+ (v81 — calibrated heuristic + fast predict API)
#
# ─────────────────────────────────────────────────────────────────────────────
from __future__ import annotations
import inspect
import json
import os
import re
import subprocess
import shutil
import tempfile
import time
import zipfile
from pathlib import Path
from rdkit import Chem
from rdkit.Chem import AllChem, rdMolDescriptors, Descriptors
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions
from rdkit.Chem.MolStandardize import rdMolStandardize
__version__ = "81"
# ─────────────────────────────────────────────────────────────────────────────
# Constants
# ─────────────────────────────────────────────────────────────────────────────
TAUTOMER_PLAUSIBILITY_CUTOFF = 3.0
AMBIGUITY_SCORE_GAP = 0.5
BORDERLINE_PKA_WINDOW = 1.0
PUBCHEM_RATE_LIMIT_S = 0.25
PUBCHEM_CACHE_FILE = "/tmp/pkanet_pubchem_cache.json"
SEP = "=" * 70
W_AROM_RING_LOST = 8.0
W_PHENOL_TO_KETO_FLIP = 6.0
W_PYROGALLOL_TRIKETO = 6.0
W_CATECHOL_DIKETO = 4.0
W_PHENOL_PRESERVED_BONUS = 0.5
# ─────────────────────────────────────────────────────────────────────────────
# Optional dependency probes
# ─────────────────────────────────────────────────────────────────────────────
try:
import requests as _requests
_REQUESTS_OK = True
except ImportError:
_requests = None; _REQUESTS_OK = False
print("⚠️ requests not installed — PubChem lookup disabled.")
try:
import fitz # PyMuPDF
_PYMUPDF_OK = True
except ImportError:
fitz = None; _PYMUPDF_OK = False
print("⚠️ PyMuPDF (fitz) not available — PDF→SMILES tab disabled.")
try:
from dimorphite_dl import protonate_smiles as _dimorphite_fn
_DIMORPHITE_OK = True
except ImportError:
_dimorphite_fn = None; _DIMORPHITE_OK = False
print("⚠️ dimorphite-dl not available.")
_PKASOLVER_OK = False; _PROPKA_OK = False; _UNIPKA_OK = False
_PKA_BACKEND = "heuristic"
print("ℹ️ ML pKa backends disabled — heuristic ionizable-site table will be used.")
# ─────────────────────────────────────────────────────────────────────────────
# Open Babel helper
# ─────────────────────────────────────────────────────────────────────────────
def check_obabel():
return shutil.which("obabel") is not None
def convert_pdb_to_mol2_obabel(pdb_path, mol2_path):
if not check_obabel(): return False
try:
r = subprocess.run(["obabel", pdb_path, "-O", mol2_path],
capture_output=True, text=True, timeout=30)
return r.returncode == 0 and Path(mol2_path).exists()
except Exception: return False
# ─────────────────────────────────────────────────────────────────────────────
# STAGE 0 · PDF → SMILES (scaffold + R-group table builder)
#
# Lets a user upload a PDF page that shows a core scaffold + R-group
# legend/table (e.g. a SAR table from a paper or SI) and turn it into a
# validated batch of SMILES that feeds straight into run_job() exactly like
# a hand-uploaded .smi file does.
#
# Reading the *drawn* scaffold is intentionally a human-in-the-loop step —
# there is no reliable way to OCR bond connectivity out of a PDF. What is
# automated: rendering the page, pulling any extractable text layer, and —
# once the scaffold + substituents are described as SMILES — assembling,
# validating, and exporting the molecules.
#
# Assembly uses RDKit's `molzip`: the scaffold SMILES carries dummy
# attachment atoms ([*:1], [*:2], [*:3]); each R-group fragment is written
# attachment-atom-first (e.g. para-hydroxyphenyl = "c1ccc(O)cc1") and is
# tagged with the matching [*:n] automatically before zipping. This avoids
# all manual SMILES ring-closure-digit bookkeeping, even for fused-ring
# R-groups (e.g. a pyrenyl group).
# ─────────────────────────────────────────────────────────────────────────────
def pdf2smi_get_page_count(pdf_bytes):
"""Number of pages in a PDF (1-indexed page numbers are used elsewhere)."""
if not _PYMUPDF_OK:
raise RuntimeError("PyMuPDF (fitz) is not installed — cannot read PDFs.")
with fitz.open(stream=pdf_bytes, filetype="pdf") as doc:
return doc.page_count
def pdf2smi_render_page(pdf_bytes, page_num, dpi=200):
"""Render one PDF page (1-indexed) to a PIL Image, for visual inspection."""
if not _PYMUPDF_OK:
raise RuntimeError("PyMuPDF (fitz) is not installed — cannot read PDFs.")
from PIL import Image # local import: PDF tab is the only consumer
zoom = dpi / 72.0
matrix = fitz.Matrix(zoom, zoom)
with fitz.open(stream=pdf_bytes, filetype="pdf") as doc:
page = doc[page_num - 1]
pix = page.get_pixmap(matrix=matrix, alpha=False)
return Image.open(__import__("io").BytesIO(pix.tobytes("png")))
def pdf2smi_extract_text(pdf_bytes, page_num):
"""Plain text layer of one PDF page (1-indexed). '' if none exists
(common for flattened/outlined PDF exports — the page is then read
visually instead via pdf2smi_render_page)."""
if not _PYMUPDF_OK:
raise RuntimeError("PyMuPDF (fitz) is not installed — cannot read PDFs.")
with fitz.open(stream=pdf_bytes, filetype="pdf") as doc:
page = doc[page_num - 1]
return page.get_text("text").strip()
def pdf2smi_resolve_fragment(value, library):
"""Look *value* up in the fragment-name library; otherwise treat it as a
literal attachment-first SMILES. Blank/None → None (slot unused)."""
if value is None:
return None
value = str(value).strip()
if not value:
return None
return library.get(value, value)
def pdf2smi_build_molecule(scaffold_smiles, slot_fragments):
"""
scaffold_smiles : SMILES with dummy attachment atoms, e.g.
"Cc1nc([*:1])[nH]c1[*:2]"
slot_fragments : {1: "c1ccccc1", 2: "c1cc(OC)c(O)c(OC)c1", ...} — each
value is an attachment-first SMILES fragment (no [*:n] needed; it is
added automatically for the matching slot number).
Returns (mol, error_message). mol is None on failure.
"""
core_mol = Chem.MolFromSmiles(scaffold_smiles)
if core_mol is None:
return None, f"Could not parse scaffold SMILES: {scaffold_smiles!r}"
combined = core_mol
for slot, frag_smiles in slot_fragments.items():
if frag_smiles is None:
continue
tagged = f"[*:{slot}]{frag_smiles}"
frag_mol = Chem.MolFromSmiles(tagged)
if frag_mol is None:
return None, f"Could not parse fragment for [*:{slot}]: {frag_smiles!r}"
combined = Chem.CombineMols(combined, frag_mol)
try:
zipped = Chem.molzip(combined)
Chem.SanitizeMol(zipped)
except Exception as exc:
return None, f"molzip/sanitize failed: {exc}"
remaining = sum(1 for a in zipped.GetAtoms() if a.GetSymbol() == "*")
if remaining:
return None, (
f"{remaining} unfilled attachment point(s) remain "
"-- check that every [*:n] in the scaffold has a matching slot."
)
return zipped, ""
def pdf2smi_describe_mol(mol):
return {
"smiles": Chem.MolToSmiles(mol),
"formula": rdMolDescriptors.CalcMolFormula(mol),
"mw": round(Descriptors.MolWt(mol), 2),
}
_SLOT_PATTERN = re.compile(r"\[\*:(\d+)\]")
def pdf2smi_count_scaffold_slots(scaffold_smiles):
"""How many distinct [*:n] attachment points a scaffold SMILES declares
(i.e. max slot number found — slots are expected to be numbered 1..N
with no gaps)."""
nums = [int(m.group(1)) for m in _SLOT_PATTERN.finditer(scaffold_smiles)]
return max(nums) if nums else 0
def pdf2smi_parse_slot_roles(roles_str, n_slots):
"""
Turn a Slot_Roles string like "R1,AR,R2" into a list of per-slot role
names, one entry per [*:n] slot (1-indexed: roles[0] is the role for
slot 1, etc.).
The SAME role name can appear more than once — e.g. "R1,R2,R1,R2" means
slots 1 and 3 both take the value of column "R1", slots 2 and 4 both
take the value of column "R2". This is how a fragment gets attached at
more than one equivalent position on a symmetric scaffold (e.g. the
same NR1R2 amide on both arms of a catechol bis-ether).
Blank/None roles_str falls back to the legacy default ["R1", "AR", "R2"]
truncated/padded to n_slots, preserving old behavior for templates that
don't specify Slot_Roles at all.
"""
# Treat None and pandas/NumPy NaN (a truthy float!) as "blank" so an
# empty Slot_Roles cell in a data_editor table falls back to the
# legacy default instead of being parsed as the literal string "nan".
if roles_str is None or (isinstance(roles_str, float) and roles_str != roles_str):
roles_str = ""
roles_str = str(roles_str).strip()
if roles_str:
roles = [r.strip() for r in roles_str.split(",") if r.strip()]
else:
roles = ["R1", "AR", "R2"]
if len(roles) < n_slots:
roles = roles + [None] * (n_slots - len(roles))
return roles[:n_slots]
def pdf2smi_build_all(compounds_df, templates, library, template_roles=None):
"""
Batch-build a compound table into validated molecules.
compounds_df columns expected: Compound_ID, Template, R1, R2, AR (extra
role columns are fine too — see template_roles below)
templates : {template_name: scaffold_smiles_with_dummy_atoms}
library : {fragment_name: attachment_first_smiles}
template_roles : {template_name: "R1,AR,R2"} (optional) — maps each
[*:n] slot in that template's scaffold to a Compounds-table column
name, in slot order. Omit a template here (or leave its string
blank) to get the legacy default mapping (slot1=R1, slot2=AR,
slot3=R2). Repeat a role name to attach the same fragment at more
than one slot (symmetric scaffolds).
Returns (result_df, mols_for_grid, legends_for_grid). result_df has
columns Compound_ID, SMILES, Formula, MW, Status, Error.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("pandas is required for pdf2smi_build_all()")
template_roles = template_roles or {}
rows = []
mols_for_grid = []
legends_for_grid = []
for _, row in compounds_df.iterrows():
cid = str(row.get("Compound_ID", "")).strip()
tmpl_name = str(row.get("Template", "")).strip()
if not cid:
continue
scaffold = templates.get(tmpl_name)
if scaffold is None:
rows.append(dict(Compound_ID=cid, SMILES=None, Formula=None, MW=None,
Status="FAILED", Error=f"Unknown template name: {tmpl_name!r}"))
continue
n_slots = pdf2smi_count_scaffold_slots(scaffold)
role_list = pdf2smi_parse_slot_roles(template_roles.get(tmpl_name), n_slots)
slot_fragments = {}
for slot_idx, role in enumerate(role_list, start=1):
if not role:
continue
val = pdf2smi_resolve_fragment(row.get(role), library)
if val is not None:
slot_fragments[slot_idx] = val
mol, err = pdf2smi_build_molecule(scaffold, slot_fragments)
if mol is None:
rows.append(dict(Compound_ID=cid, SMILES=None, Formula=None, MW=None,
Status="FAILED", Error=err))
continue
desc = pdf2smi_describe_mol(mol)
rows.append(dict(Compound_ID=cid, SMILES=desc["smiles"], Formula=desc["formula"],
MW=desc["mw"], Status="OK", Error=""))
mols_for_grid.append(mol)
legends_for_grid.append(cid)
result_df = pd.DataFrame(rows)
return result_df, mols_for_grid, legends_for_grid
def pdf2smi_make_grid_image(mols, legends, mols_per_row=5, sub_size=(220, 200)):
if not mols:
return None
from rdkit.Chem import Draw
return Draw.MolsToGridImage(mols, molsPerRow=mols_per_row, subImgSize=sub_size, legends=legends)
def pdf2smi_to_smi_bytes(result_df):
"""Render validated rows of a pdf2smi_build_all() result as .smi-format
bytes (SMILES<tab>name per line) — the same shape run_job() already
expects for input_type='SMI_FILE' via parse_smi_lines()."""
lines = []
for _, r in result_df.iterrows():
if r.get("Status") == "OK" and r.get("SMILES"):
lines.append(f"{r['SMILES']}\t{r['Compound_ID']}")
return ("\n".join(lines) + "\n").encode("utf-8")
def pdf2smi_to_csv_bytes(result_df):
return result_df.to_csv(index=False).encode("utf-8")
# ─────────────────────────────────────────────────────────────────────────────
# STAGE A · RDKit standardization
# ─────────────────────────────────────────────────────────────────────────────
def standardize_smiles(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None: return None, f"❌ RDKit cannot parse: {smiles[:80]}"
mol = Chem.RemoveHs(mol, implicitOnly=True)
mol = rdMolStandardize.LargestFragmentChooser().choose(mol)
try: mol = rdMolStandardize.Normalizer().normalize(mol)
except Exception: pass
return Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True), "OK"
def canonicalize(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None: return None
return Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True)
def smiles_to_inchikey(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None: return None
try: return Chem.MolToInchiKey(mol)
except Exception: return None
def enumerate_stereo(smiles, keep_original=True):
mol = Chem.MolFromSmiles(smiles)
if mol is None: raise ValueError(f"Bad SMILES: {smiles[:60]}")
if keep_original:
return [(Chem.MolToSmiles(mol, isomericSmiles=True), None)]
opts = StereoEnumerationOptions(onlyUnassigned=False, unique=True)
isos = list(EnumerateStereoisomers(mol, options=opts)) or [mol]
rows = []
for iso in isos:
smi = Chem.MolToSmiles(iso, isomericSmiles=True)
tag = None
ch = Chem.FindMolChiralCenters(iso, includeUnassigned=True)
if len(ch) == 1 and ch[0][1] in ("R", "S"): tag = ch[0][1]
rows.append((smi, tag))
return rows
# ─────────────────────────────────────────────────────────────────────────────
# STAGE B · PubChem experimental pKa retrieval
# ─────────────────────────────────────────────────────────────────────────────
_PUBCHEM_CACHE = {}
def _load_pubchem_cache():
global _PUBCHEM_CACHE
if Path(PUBCHEM_CACHE_FILE).exists():
try:
with open(PUBCHEM_CACHE_FILE) as f: _PUBCHEM_CACHE = json.load(f)
except Exception: _PUBCHEM_CACHE = {}
def _save_pubchem_cache():
try:
with open(PUBCHEM_CACHE_FILE, "w") as f: json.dump(_PUBCHEM_CACHE, f, indent=2)
except Exception: pass
_load_pubchem_cache()
_PKA_PATTERNS = [
re.compile(r"pK[aA][\w\s\(\)]*?=\s*([+-]?\d+(?:\.\d+)?)", re.IGNORECASE),
re.compile(r"([+-]?\d+(?:\.\d+)?)\s*\((?:pK[aA]|acid dissociation)[^)]*\)", re.IGNORECASE),
re.compile(r"(?:pK[aA]).*?([+-]?\d+(?:\.\d+))", re.IGNORECASE),
]
def _pubchem_get(url, timeout=12):
if not _REQUESTS_OK or _requests is None: return None
try:
time.sleep(PUBCHEM_RATE_LIMIT_S)
r = _requests.get(url, timeout=timeout)
if r.status_code == 200: return r.json()
except Exception: pass
return None
def pubchem_cid_from_inchikey(inchikey):
key = f"cid:{inchikey}"
if key in _PUBCHEM_CACHE: return _PUBCHEM_CACHE[key]
data = _pubchem_get(f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchikey/{inchikey}/cids/JSON")
cid = None
if data:
try: cid = int(data["IdentifierList"]["CID"][0])
except Exception: pass
_PUBCHEM_CACHE[key] = cid; _save_pubchem_cache(); return cid
def _flatten_pubchem_section(section, target_heading):
results = []
if target_heading.lower() in section.get("TOCHeading", "").lower():
for info in section.get("Information", []):
for swm in info.get("Value", {}).get("StringWithMarkup", []):
s = swm.get("String", "").strip()
if s: results.append(s)
for sub in section.get("Section", []): results.extend(_flatten_pubchem_section(sub, target_heading))
return results
def pubchem_get_dissociation_texts(cid):
key = f"diss:{cid}"
if key in _PUBCHEM_CACHE: return _PUBCHEM_CACHE[key]
data = _pubchem_get(f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON?heading=Dissociation+Constants")
texts = []
if data:
try:
for sec in data.get("Record", {}).get("Section", []):
texts.extend(_flatten_pubchem_section(sec, "Dissociation"))
except Exception: pass
_PUBCHEM_CACHE[key] = texts; _save_pubchem_cache(); return texts
def parse_pka_values(texts):
full_text = " ".join(texts).lower()
found = []; src = []
for text in texts:
hits = []
for pat in _PKA_PATTERNS:
for m in pat.finditer(text):
try:
v = float(m.group(1))
if -5.0 <= v <= 20.0: hits.append(v)
except ValueError: pass
if hits: found.extend(hits); src.append(text)
dedup = []
for v in found:
if not any(abs(v - e) < 0.05 for e in dedup): dedup.append(v)
site_labels = bool(re.search(r"pK[aA]\s*[12\(]", " ".join(texts)))
temperature = bool(re.search(r"\d+\s*°\s*[Cc]|at\s+\d+\s*[Cc]", full_text))
solvent = bool(re.search(r"\b(water|aqueous|etoh|dmso|methanol|buffer|solution)\b", full_text))
vague = bool(re.search(r"\b(approximately|approx|about|ca\.|around|range|varies|estimated|uncertain|unclear|conflicting)\b", full_text))
conflicting = len(dedup) >= 2 and any(abs(a-b)>1.5 for i,a in enumerate(dedup) for b in dedup[i+1:])
if not dedup or conflicting or vague: confidence = "low"
elif len(dedup) > 1 or temperature or solvent or site_labels: confidence = "medium"
else: confidence = "high"
flags = {"exact_numeric_match": bool(dedup), "multiple_values_found": len(dedup)>1,
"site_labels_found": site_labels, "temperature_mentioned": temperature,
"solvent_mentioned": solvent, "conflicting_values": conflicting,
"vague_or_approximate": vague, "unclear_site_mapping": len(dedup)>1, "confidence": confidence}
return dedup, src, flags
def pubchem_lookup(smiles):
result = dict(available=False, cid=None, inchikey=None, pka_values=[], source_texts=[], flags={}, confidence="low", error=None)
ik = smiles_to_inchikey(smiles)
if ik is None: result["error"] = "InChIKey computation failed."; return result
result["inchikey"] = ik
cid = pubchem_cid_from_inchikey(ik)
if cid is None: result["error"] = "CID not found."; return result
result["cid"] = cid
texts = pubchem_get_dissociation_texts(cid)
if not texts: result["error"] = "No dissociation constant data on PubChem."; return result
vals, srcs, flags = parse_pka_values(texts)
result.update(available=bool(vals), pka_values=vals, source_texts=srcs, flags=flags, confidence=flags.get("confidence","low"))
return result
# ─────────────────────────────────────────────────────────────────────────────
# STAGE C · ML pKa backends
# ─────────────────────────────────────────────────────────────────────────────
def _unipka_via_pkasolver(smiles):
try:
from pkasolver.query import QueryModel
mol = Chem.MolFromSmiles(smiles)
if mol is None: return []
df = QueryModel().predict_pka(mol)
return [{"pka": float(row.get("pKa", row.get("pka", 0))), "site_type": str(row.get("type","?")),
"site_label": str(row.get("atom_idx","?")), "source": "pkasolver", "confidence": "ml_gnn"}
for _, row in df.iterrows()]
except Exception as e: print(f"⚠️ pkasolver failed: {e}"); return []
def _unipka_via_propka(smiles):
try:
import propka.run as pk
mol = Chem.MolFromSmiles(smiles)
if mol is None: return []
mol = Chem.AddHs(mol)
p = AllChem.ETKDGv3(); p.randomSeed = 42
if AllChem.EmbedMolecule(mol, p) != 0: return []
AllChem.MMFFOptimizeMolecule(mol, maxIters=300)
with tempfile.NamedTemporaryFile(suffix=".pdb", delete=False, mode="w") as tf:
tmppath = tf.name; tf.write(Chem.MolToPDBBlock(mol))
results = []
try:
mc = pk.single(tmppath, optargs=["--quiet"])
for grp in mc.conformations[0].groups:
pv = getattr(grp, "pka_value", None)
if pv is not None:
results.append({"pka": float(pv), "site_label": str(getattr(grp,"atom_name","?")),
"site_type": str(getattr(grp,"type","?")), "source": "propka", "confidence": "semi_empirical"})
finally:
try: os.unlink(tmppath)
except Exception: pass
return results
except Exception as e: print(f"⚠️ propka failed: {e}"); return []
def _unipka_via_cli(smiles):
try:
r = subprocess.run(["unipka","--smiles",smiles,"--json"], capture_output=True, text=True, timeout=60)
if r.returncode != 0: return []
data = json.loads(r.stdout)
return [{"pka": e.get("pka"), "site_label": e.get("site","?"), "site_type": e.get("type","?"),
"source": "unipka_cli", "confidence": "ml"} for e in data.get("microstates",[])]
except Exception as e: print(f"⚠️ unipka CLI failed: {e}"); return []
def unipka_predict(smiles):
if _UNIPKA_OK:
r = _unipka_via_cli(smiles)
if r: return r
if _PKASOLVER_OK:
r = _unipka_via_pkasolver(smiles)
if r: return r
if _PROPKA_OK:
r = _unipka_via_propka(smiles)
if r: return r
return []
def unipka_summary_pka(predictions):
valid = [p for p in predictions if p.get("pka") is not None]
if not valid: return None, "none"
closest = min(valid, key=lambda p: abs(float(p["pka"]) - 7.4))
return float(closest["pka"]), closest.get("source", "?")
# ─────────────────────────────────────────────────────────────────────────────
# STAGE D · Dimorphite-DL protonation enumerator
# ─────────────────────────────────────────────────────────────────────────────
def dimorphite_enumerate(smiles, ph_min, ph_max, precision=1.0, max_variants=128):
if not _DIMORPHITE_OK or _dimorphite_fn is None: return [smiles]
kwarg_variants = [
{"ph_min": ph_min, "ph_max": ph_max, "precision": precision, "max_variants": max_variants},
{"min_ph": ph_min, "max_ph": ph_max, "pka_precision": precision, "max_variants": max_variants},
{"ph_min": ph_min, "ph_max": ph_max, "precision": precision},
{"min_ph": ph_min, "max_ph": ph_max, "pka_precision": precision},
]
errors = []; raw = []
for kwargs in kwarg_variants:
try:
r = _dimorphite_fn(smiles, **kwargs)
raw = [r] if isinstance(r, str) else list(r or [])
if raw: break
except TypeError as e: errors.append(str(e))
if not raw:
try:
sig = inspect.signature(_dimorphite_fn); kw = {}
for name in sig.parameters:
lo = name.lower()
if lo in {"ph_min","min_ph"}: kw[name] = ph_min
elif lo in {"ph_max","max_ph"}: kw[name] = ph_max
elif lo in {"precision","pka_precision"}: kw[name] = precision
elif lo == "max_variants": kw[name] = max_variants
r = _dimorphite_fn(smiles, **kw)
raw = [r] if isinstance(r, str) else list(r or [])
except Exception as e:
errors.append(str(e))
print(f"⚠️ dimorphite-dl failed ({smiles[:50]}). Errors: {errors[-2:]}")
seen = set(); result = []
seed = canonicalize(smiles)
if seed: seen.add(seed); result.append(seed)
for smi in raw:
c = canonicalize(smi)
if c and c not in seen: seen.add(c); result.append(c)
return result or [smiles]
# ─────────────────────────────────────────────────────────────────────────────
# STAGE E+F · HH scoring + ionizable site table
# ─────────────────────────────────────────────────────────────────────────────
def hh_fraction_charged(pka, ph, site_type):
if site_type == "acid": return 1.0 / (1.0 + 10.0 ** (pka - ph))
return 1.0 / (1.0 + 10.0 ** (ph - pka))
def hh_ph_match_score(pka, ph, site_type, actual_charge):
f_charged = hh_fraction_charged(pka, ph, site_type)
dpH = abs(ph - pka)
decisive = (f_charged >= 0.65) or (f_charged <= 0.35)
rwd_mul = pen_mul = 1.6 if decisive else 1.0
if site_type == "acid":
expected_neg = f_charged > 0.5
if expected_neg and actual_charge < 0: return min(1.5, dpH * 0.55 * rwd_mul) + 0.15
elif expected_neg: return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
elif actual_charge >= 0: return 0.15
else: return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
else:
expected_pos = f_charged > 0.5
if expected_pos and actual_charge > 0: return min(1.5, dpH * 0.55 * rwd_mul) + 0.15
elif expected_pos: return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
elif actual_charge <= 0: return 0.15
else: return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
# ─── Ionizable site table ────────────────────────────────────────────────────
_IONIZABLE_SITE_DEF = [
# ── Ultra-strong acids ────────────────────────────────────────────────────
("sulfonic_acid", "[SX4](=O)(=O)[OX2H1]", 1.0, "acid"),
# Split sulfonyl-imide N-H into 2 contexts:
# (a) Cyclic sulfonyl-imide (saccharin pKa=1.6, acesulfame-K pKa~2): N in
# ring with adjacent C=O and SO2.
# (b) Acyclic sulfonylurea (glipizide, glyburide, glimepiride pKa~5.0-6.5):
# Ar-SO2-NH-C(=O)-NHR. Less acidic — no ring strain, additional NH side.
# Both MUST precede sulfonamide_NH (seen_ion dedup gives correct pKa).
("sulfonyl_imide_NH_cyclic", "[CX3;R](=O)[NX3;H1;R][SX4;R](=O)(=O)", 2.0, "acid"),
("sulfonylurea_NH", "[NX3;H0,H1][CX3;!R](=O)[NX3;H1;!R][SX4;!R](=O)(=O)", 5.5, "acid"),
("sulfonyl_imide_NH", "[CX3](=O)[NX3;H1][SX4](=O)(=O)", 2.0, "acid"),
# ── Carboxylic / aromatic hetero-acid ─────────────────────────────────────
# Alpha-amino acid carboxyl: primary alpha-NH2 suppresses COOH pKa to ~2.3 (Gly=2.35, Ala=2.35)
# Recursive SMARTS checks for NH2 WITHOUT including N in the match atoms,
# so the amine site remains unclaimed and can independently fire (giving zwitterion net=0).
# H2 restriction avoids N-alkyl amino acids (sarcosine, N-butylglycine).
# Must precede generic carboxylic_acid.
("amino_acid_COOH", "[OX2H1][CX3](=O)[$([CX4][NX3;H2;!$(NC=O)])]", 2.3, "acid"),
# Aromatic carboxylic acid: benzoic=4.2, avg aryl COOH ~4.2 (bias was -0.27 on generic)
("aryl_carboxylic_acid", "[c][CX3](=O)[OX2H1]", 4.2, "acid"),
("carboxylic_acid", "[CX3](=O)[OX2H1]", 4.5, "acid"),
("tetrazole", "c1nn[nH]n1", 4.9, "acid"),
# ── Phosphorus acids (diprotic handled by Pass 1 in find_ionizable_sites) ─
("phosphonate_fallback", "[PX4](=O)([OX2H1])[OX1-,OX2;!$([OX2H1])]", 6.5, "acid"),
("phosphate_monoester_fb", "[PX4](=O)([OX2H1])([OX2,OX1-])[OX2,OX1-]", 6.1, "acid"),
# ── N-H acids ─────────────────────────────────────────────────────────────
# Heteroaryl sulfonamide N-H: N attached to electron-poor heteroaromatic ring.
# Heterocycle strongly inductively withdraws electron density,
# depressing pKa to ~5-7 (vs ~9.7 for plain aryl sulfonamide).
# sulfisoxazole (isoxazole) pKa 5.0
# sulfamethoxazole (isoxazole) pKa 5.6
# sulfadoxine (pyrimidine) pKa 6.1
# sulfadiazine (pyrimidine) pKa 6.5
# sulfathiazole (thiazole) pKa 7.1
# sulfamerazine (pyrimidine) pKa 7.1
# sulfamethazine (pyrimidine) pKa 7.4
# MUST precede sulfonamide_aryl_NH (first-match-wins).
# 5-membered heteroaromatic (isoxazole/oxazole/thiazole/pyrazole etc.)
("sulfonamide_5het_NH", "[SX4](=O)(=O)[NX3;H1][c;$([c]1[o,n,s][c,n][c,n][c,n]1),$([c]1[c,n][o,n,s][c,n][c,n]1),$([c]1[c,n][c,n][o,n,s][c,n]1)]", 5.7, "acid"),
# Thiazol-2-yl (sulfathiazole pKa 7.1)
("sulfonamide_thiazole_NH", "[SX4](=O)(=O)[NX3;H1]c1nccs1", 7.0, "acid"),
# Oxazol-2-yl
("sulfonamide_oxazole_NH", "[SX4](=O)(=O)[NX3;H1]c1ncco1", 6.5, "acid"),
# 6-membered electron-poor heteroaromatic (pyrimidine, pyrazine, pyridazine)
("sulfonamide_pyrim2_NH", "[SX4](=O)(=O)[NX3;H1]c1ncccn1", 7.0, "acid"), # 2-aminopyrimidine
("sulfonamide_pyrim4_NH", "[SX4](=O)(=O)[NX3;H1]c1ccncn1", 6.5, "acid"), # 4-aminopyrimidine
("sulfonamide_pyrim5_NH", "[SX4](=O)(=O)[NX3;H1]c1cncnc1", 6.5, "acid"), # 5-aminopyrimidine
("sulfonamide_pyrazin_NH", "[SX4](=O)(=O)[NX3;H1]c1cnccn1", 7.0, "acid"), # aminopyrazine
("sulfonamide_pyridazin_NH", "[SX4](=O)(=O)[NX3;H1][c;$([c]1cccnn1),$([c]1ccnnc1)]", 7.0, "acid"), # aminopyridazine
# Aryl sulfonamide N-H: benzenesulfonamide pKa=10.1 but aryl avg ~9.7
# 2-Pyridylsulfonamide: sulfapyridine pKa=8.43. Pyridine N at ortho
# withdraws electron density → pKa lowered vs plain aryl (9.7) but
# still > 7.4 → neutral dominates at pH 7.4. Must precede aryl_NH.
("sulfonamide_2pyridyl_NH", "[SX4](=O)(=O)[NX3;H1]c1ccccn1", 6.4, "acid"),
("sulfonamide_3pyridyl_NH", "[SX4](=O)(=O)[NX3;H1]c1cnccc1", 9.0, "acid"),
("sulfonamide_4pyridyl_NH", "[SX4](=O)(=O)[NX3;H1]c1ccncc1", 9.0, "acid"),
("sulfonamide_aryl_NH", "[SX4](=O)(=O)[NX3;H1,H2][c]", 9.7, "acid"),
("sulfonamide_NH", "[SX4](=O)(=O)[NX3;H1,H2]", 10.1, "acid"), # H2 for primary sulfonamide
# Barbiturate ring N-H: 6-ring with two C=O flanking N-H + a third C=O on
# opposite side. pKa ~7.4 (phenobarbital), much more acidic than simple imide.
# MUST precede imide_NH.
("barbiturate_NH", "[NX3;H1;R]1[CX3;R](=O)[NX3;H1,H0;R][CX3;R](=O)[CX4;R][CX3;R]1=O", 7.4, "acid"),
("imide_NH", "[CX3](=O)[NX3;H1][CX3]=O", 9.6, "acid"),
("acylhydrazone_NH", "[CX3](=O)[NX3;H1][NX2]=[CX3]", 10.5, "acid"),
("hydrazide_NH", "[CX3](=O)[NX3;H1][NX3;H2]", 10.5, "acid"),
("urea_NH", "[NX3;H1][CX3](=O)[NX3;H1,H2]", 13.0, "acid"),
("amide_NH", "[CX3](=O)[NX3;H1,H2;!$([N]~N)]", 15.0, "acid"),
# ── Hydroxamic acid (Bug C fix) ───────────────────────────────────────────
# Recursive SMARTS captures only the O-H; prevents amine-N from being
# mis-claimed as acid site at pKa=9.0.
("hydroxamic_acid", "[OX2H1;$([OX2H1][NX3;H1][CX3](=O))]", 9.0, "acid"),
# ── Aromatic N-H acids (Bug #1/#2 fix: was 6.0/5.5 = BASE pKa, wrong!) ──
# Electron-poor benzimidazole (halo/nitro substituents lower N-H pKa to ~11)
("benzimidazole_EWG_NH", "c1ccc2[nH]cnc2c1[$([F,Cl,Br]),$([NX3+](=O)[O-]),$([NX3](=O)=O),$(C#N)]", 11.0, "acid"),
("benzimidazole_NH", "c1ccc2[nH]cnc2c1", 13.0, "acid"),
# Electron-poor imidazole: 4-nitroimidazole pKa(NH)~9.2; haloimidazole ~12
("imidazole_EWG_NH", "[nH]1ccnc1[$([NX3+](=O)[O-]),$([NX3](=O)=O),$(C#N)]", 9.5, "acid"),
("imidazole_NH", "[nH]1ccnc1", 14.0, "acid"),
("pyrazole_NH", "[nH]1nccc1", 14.0, "acid"),
("indole_NH", "c1ccc2[nH]ccc2c1", 17.0, "acid"),
# ── Enol acids (NEW) ──────────────────────────────────────────────────────
# Enol-lactone: ascorbic acid, dehydroascorbate precursors. C=C-OH adjacent
# to lactone ring C=O. Must precede generic phenol (pKa=10.0).
("enol_lactone", "[OX2H1][CX3]=[CX3][CX3](=O)[OX2;R]", 4.2, "acid"),
# Cyclic 1,3-dicarbonyl enol: pyrazolidinedione (phenylbutazone pKa~4.5),
# dimedone, cyclopentane-1,3-dione type ring enols.
# Aromatic cyclic enol-ketone: phenylbutazone enol (hydroxypyrazolone) pKa~4.5.
("enol_cyclic_dicarbonyl_arom", "[OX2H1][c;R]~[c;R]~[c;R]=O", 5.0, "acid"),
# Non-aromatic cyclic 1,3-dicarbonyl enol: dimedone, cyclopentanedione type.
("enol_cyclic_dicarbonyl", "[OX2H1][CX3;R]=[CX3;R][CX3;R]=O", 5.5, "acid"),
# Open-chain 1,3-dicarbonyl enol: acetylacetone (pKa~8.9), ethyl acetoacetate.
("enol_1_3_dicarbonyl", "[OX2H1][CX3]=[CX3][CX3]=O", 9.0, "acid"),
# ── Oxime acids ──────────────────────────────────────────────────────────
# Oxime R₂C=N-OH: pKa ~8-12. Aryl oximes lower (~8-9), alkyl higher (~10-12).
# Must precede phenol to claim O-H first.
("oxime_aryl", "[OX2H1][NX2]=[CX3][c]", 9.0, "acid"),
("oxime", "[OX2H1][NX2]=[CX3]", 11.0, "acid"),
# ── Phenols (Bug F fix: catechol_OH before phenol_ortho_CO) ──────────────
# Catechol with adjacent EWG: pKa ~8.0 (nitrocatechol ~7.2-8.0)
("catechol_EWG_OH", "[OX2H1][c;R]:[c;R][OX2H1][$([NX3+](=O)[O-]),$([NX3](=O)=O),$(C#N),$([CX3]=O)]", 8.0, "acid"),
("catechol_OH", "[OX2H1][c;R]:[c;R][OX2H1]", 9.2, "acid"), # was 9.4, bias +0.49 → lower to 9.2
("phenol_ortho_CO", "[OX2H1][c;R]:[c;R][CX3;R](=O)", 7.8, "acid"),
("phenol_para_EWG", "[OX2H1]c1ccc([$([NX3+](=O)[O-]),$([NX3](=O)=O),$([CX3]=O),$(C#N),$([SX4](=O)(=O))])cc1", 7.8, "acid"), # para-EWG: avg lit ~7.8 (nitro=7.15, CN=7.97, acyl=8.05)
("phenol_EWG", "[OX2H1][c;R]:[c;R][$([NX3+](=O)[O-]),$([NX3](=O)=O),$([CX3]=O),$(C#N),$([SX4](=O)(=O))]", 8.0, "acid"), # ortho/meta EWG ~8.0
("phenol", "c[OX2H1]", 10.0, "acid"),
# ── Thiols ────────────────────────────────────────────────────────────────
# Bug B fix: Cys-like thiol alpha to amine pKa~8.3; recursive SMARTS.
("thiol_alpha_amino", "[SX2H1;$([SX2H1][CX4][CX4][NX3;!$(NC=O)])]", 8.3, "acid"),
# Aromatic thiol adjacent to ring N (heteroaryl thiol, e.g. quinoline-8-thiol pKa~7.8):
# electron-withdrawing ring N raises pKa vs plain thiophenol (6.6). Must precede thiol_arom.
("thiol_hetarom", "[c;$([c]1[c,n][c,n][c,n][n,s,o]1)][SX2H1]", 7.9, "acid"),
("thiol_arom", "c[SX2H1]", 6.5, "acid"), # thiophenol 6.6
("thiol_aliph", "[CX4][SX2H1]", 9.8, "acid"),
# ── Bases ─────────────────────────────────────────────────────────────────
# N-oxide: Ar-N(+)(-O-) — the conjugate acid has pKa ~ −1.5; neutral (zwitterion) at pH 7.4
# Must precede pyridine_like so the ring N is not also counted as a base.
("n_oxide_neutral", "[$([nX3+]~[OX1-]),$([NX3+](=O)[OX1-])]", -1.5, "base"),
# Aniline with EWG: strongly depressed pKa (4-nitroaniline=1.0, 4-CN=1.7 → avg ~2.5)
("aniline_EWG", "c[NX3;H1,H2;!$(N~[!#6])][$([NX3+](=O)[O-]),$([NX3](=O)=O),$(C#N),$([SX4](=O)(=O))]", 2.5, "base"),
# Aniline with para-EWG on the SAME aromatic ring (through-ring resonance withdrawal).
# sulfanilamide (para-SO2NHR) pKa~1.9, p-nitroaniline pKa~1.0, p-cyanoaniline pKa~1.7
("aniline_para_EWG", "[NX3;H1,H2;!$(N~[!#6])][c]1[c][c][c]([$([NX3+](=O)[O-]),$([NX3](=O)=O),$(C#N),$([SX4](=O)(=O))])[c][c]1", 2.0, "base"),
# Aniline with EDG: pKa elevated (4-methoxyaniline=5.3, 4-methylaniline=5.1 → avg ~5.1)
("aniline_EDG", "c[NX3;H1,H2;!$(N~[!#6])][$([OX2][#6]),$([CX4H3]),$([CX4H2])]", 5.1, "base"),
("aniline", "c[NX3;H1,H2;!$(N~[!#6])]", 4.6, "base"),
# Pyridine with strong EWG on ring — covers ortho (2-bond) and para/meta (3-bond)
# e.g. 3-nitropyridine pKa~0.8, 4-cyanopyridine~1.9, 2-nitropyridine~0.8
# Must precede generic pyridine_like
("pyridine_EWG", "[nX2]:c:c([$([NX3+](=O)[O-]),$(N(=O)=O),$(C#N)])", 2.0, "base"),
("pyridine_EWG_far", "[nX2]:c:c:c([$([NX3+](=O)[O-]),$(N(=O)=O),$(C#N)])", 2.0, "base"),
("pyridine_like", "[$([nX2]1:[c,n]:c:[c,n]:c1),$([nX2]:c:n)]", 5.2, "base"),
# Aliphatic imine alpha to EWG/aryl: strongly suppressed (benzaldimine ~2.5, EWG ~1.5-3.0)
("aliphatic_imine_EWG", "[CX3;!$([c])](=[NX2;H0;!$([n])])[$([c]),$([CX3](=O)),$([SX4](=O)(=O)),$(C#N)]", 2.0, "base"),
("aliphatic_imine", "[CX3;!$([c])](=[NX2;H0;!$([n])])", 5.5, "base"),
# Bug G fix: alpha-EWG amine pKa~7.5; must precede generic aliphatic_amine.
("amine_alpha_EWG", "[NX3;H1,H2;!$(NC=O);!$([nH]);$([NX3][CX4][$([CX3;!$(C(=O)O)](=O)),$([CX3]=S),$(C#N),$([SX4](=O)(=O))])]", 7.5, "base"),
# Beta-EWG amine: pKa ~8.0 (e.g. 2-aminoethanol pKa 9.5, but with beta-CF3 ~7.5)
("amine_beta_EWG", "[NX3;H1,H2;!$(NC=O);!$([nH]);$([NX3][CX4][CX4][$([CX3](=O)),$([SX4](=O)(=O)),$(C#N)])]", 8.0, "base"),
# Fluoroalkyl-adjacent amine: strongly suppressed by induction
("amine_fluoroalkyl", "[NX3;H1,H2;!$(NC=O);!$([nH]);$([NX3][CX4][$([CX4](F)(F)),$([CX4](F)(F)F)])]", 6.5, "base"),
# Gamma-ring-sulfonyl amine: amine on a saturated ring carbon γ to a ring
# sulfone/sulfonyl. Inductive withdrawal through the locked ring strongly
# suppresses amine pKa (dorzolamide exp 6.35, brinzolamide exp 5.9).
# Must precede generic aliphatic_amine (pKa 9.5).
("amine_gamma_ring_sulfonyl", "[NX3;H1,H2;!$(NC=O);!$([nH])][CX4;R][CX4;R][CX4;R][SX4;R](=O)(=O)", 6.5, "base"),
# Hydrazine: N-N bond drastically reduces basicity (pKa 2-5 vs 9.5 for plain amine).
# Match the more protonated terminal nitrogen before generic aliphatic amines.
("hydrazine_aryl", "[NX3;H2;!$(NC=O);$([NX3;H2][NX3]c)]", 5.0, "base"),
("hydrazine_terminal", "[NX3;H2;!$(NC=O);$([NX3;H2][NX3;!$([NX3]c)])]", 3.5, "base"),
("hydrazine_secondary", "[NX3;H1;!$(NC=O);$([NX3;H1][NX3;H1;!$(NC=O)])]", 4.0, "base"),
("aliphatic_amine", "[NX3;H1,H2;!$(NC=O);!$(N~[!#6;!H]);!$([nH]);!$([NX3][CX3](=[NX2])[NX3])]", 9.5, "base"),
# Tertiary aliphatic amine: pKa ~8.5 (trimethylamine=9.8 but multi-subst. lowers; v80 recalibrated)
("aliphatic_amine_t", "[NX3;H0;!$(NC=O);!$(Nc);!$([nH]);!$([N]~[!#6]);!$([NX3]([CX4][CX3]=O)[CX4][CX3]=O)]", 8.5, "base"),
("amidine", "[CX3](=[NX2;H0,H1])[NX3;H1,H2;!$([NX3][CX3](=[NX2])[NX3])]", 12.4, "base"),
("guanidine", "[NX2;H1;$([NX2]=[CX3]([NX3])[NX3])]", 12.5, "base"), # imine =NH only; was 13.0, bias +0.31→ lower to 12.5
]
_IONIZABLE_SITES_COMPILED = []
for _lbl, _sma, _pka_v, _typ in _IONIZABLE_SITE_DEF:
_pat = Chem.MolFromSmarts(_sma)
if _pat is not None: _IONIZABLE_SITES_COMPILED.append((_lbl, _pat, _pka_v, _typ))
else: print(f"⚠️ SMARTS compile failed: {_lbl}")
# ─── Diprotic phosphorus acid handler (Bug A fix) ────────────────────────────
_DIPROTIC_P_DEFS = [
# phosphonate R-PO(OH)2: pKa1=2.1, pKa2=7.5 (lit: methylphosphonic 2.4/7.8,
# aminomethylphosphonic 2.4/5.5, phenylphosphonic 1.8/7.1 → mean ~7.5)
("[PX4](=O)([OX2H1])[OX2H1]", 2.1, 7.0, "phosphonate"),
# phosphate monoester R-O-PO(OH)2: pKa1=1.0, pKa2=6.8 (lit: glucose-6-P 0.9/6.1,
# AMP 0.9/6.1, phenyl phosphate 1.0/5.8 → average closer to 6.5-6.8)
("[PX4](=O)([OX2H1])([OX2H1])[OX2;!$([OX2H1])]", 1.0, 6.1, "phosphate_monoester"),
]
_DIPROTIC_P_COMPILED = []
for _sma_dp, _pk1, _pk2, _lbl_dp in _DIPROTIC_P_DEFS:
_pat_dp = Chem.MolFromSmarts(_sma_dp)
if _pat_dp is not None: _DIPROTIC_P_COMPILED.append((_pat_dp, _pk1, _pk2, _lbl_dp))
else: print(f"⚠️ Diprotic SMARTS compile failed: {_lbl_dp}")
# ─── Targeted special-site handlers (2026-05 validation patch) ───────────────
# These are deliberately narrow and run before the generic SMARTS table. They
# fix residual validation failures without changing the public API.
_PAT_THIAZIDE_PRIMARY_SULFONAMIDE = Chem.MolFromSmarts("[NX3;H2][SX4](=O)(=O)[c]")
_PAT_THIAZIDE_RING = Chem.MolFromSmarts("[NX3;H1][CX4][NX3][SX4,SX3+]")
_PAT_SALICYLIC_PHENOL = Chem.MolFromSmarts("[OX2H1][c;R]:[c;R][CX3](=O)[OX2H1,OX1-]")
_PAT_ALPHA_HYDROXY_CARBOXYL = Chem.MolFromSmarts("[OX2H1][CX4][CX3](=O)[OX2H1,OX1-]")
_PAT_DEFERASIROX_TRIAZOLE_CONTEXT = Chem.MolFromSmarts("[nH]n")
_PAT_THIOXO_AROMATIC = Chem.MolFromSmarts("[c,C]=[SX1]")
_PAT_BIGUANIDE = Chem.MolFromSmarts("[#7][#6](=[#7])[#7][#6](=[#7])[#7]")
_PAT_GUANIDINE_FULL = Chem.MolFromSmarts("[#7][#6](=[#7])[#7]")
# Additional validation-focused functional-group patterns (2026-05-c).
_PAT_TRICHLOROACETIC_ACID = Chem.MolFromSmarts("[CX3](=O)([OX2H1])[CX4](Cl)(Cl)Cl")
_PAT_POLYHALO_METHYL_COOH = Chem.MolFromSmarts("[CX3](=O)([OX2H1])[CX4]([$([F,Cl,Br,I])])([$([F,Cl,Br,I])])[$([F,Cl,Br,I])]")
_PAT_NITROPHENOL_ANY = Chem.MolFromSmarts("[OX2H1][c;R]1[c;R,c;R][c;R,c;R][c;R,c;R]([$([NX3+](=O)[O-]),$([NX3](=O)=O)])[c;R,c;R][c;R,c;R]1")
_PAT_PENTAFLUOROPHENOL = Chem.MolFromSmarts("[OX2H1]c1c(F)c(F)c(F)c(F)c1F")
_PAT_WARFARIN_ENOL = Chem.MolFromSmarts("[OX2H1]c1c([#6])c(=O)oc2ccccc12")
_PAT_CHROMANONE_ENOL_OH = Chem.MolFromSmarts("[OX2H1][CX3;R]([c])=[CX3;R]") # non-aromatic chromanone enol (warfarin keto path)
_PAT_FUROSEMIDE_SULFONAMIDE = Chem.MolFromSmarts("[NX3;H1,H2][SX4](=O)(=O)[c]")
_PAT_BETA_HYDROXY_CARBOXYL = Chem.MolFromSmarts("[OX2H1][CX4][CX4][CX3](=O)[OX2H1,OX1-]")
_PAT_GLYPHOSATE_BACKBONE = Chem.MolFromSmarts("[PX4](=O)([OX2H1,OX1-])([OX2H1,OX1-])[CX4][NX3][CX4][CX3](=O)[OX2H1,OX1-]")
_PAT_MORPHOLINE_TERTIARY_N = Chem.MolFromSmarts("[NX3;R;!$(NC=O);!$(Nc)]1CCOCC1")
# Tertiary cyclic amine with adjacent EWG: pKa suppressed to ~5.5-6.5
# Tertiary cyclic amine with adjacent EWG: pKa suppressed to ~5.5-6.5
# Restriction: alpha-C connected to a STRONG EWG only — ring/aromatic ketone,
# sulfonyl, nitrile, thioketone. Esters (–C(=O)OR) and amides (–C(=O)NR2) are
# excluded because they do not suppress amine pKa enough to match this rule
# (tropane alkaloids like atropine, cocaine, scopolamine have ester groups
# alpha to the bridgehead N but still have pKa ~9-10, not 6.0).
_PAT_CYCLIC_N_ALPHA_EWG = Chem.MolFromSmarts("[NX3;R;!$(NC=O)][CX4][$([CX3;!$(C(=O)[OX2H0,N])](=O)),$([CX3]=S),$(C#N),$([SX4](=O)(=O))]")
# Piperazine secondary N (weaker due to inductive effect from first protonated N): ~5.1
_PAT_PIPERAZINE = Chem.MolFromSmarts("[NX3;R;!$(NC=O)]1CC[NX3;R]CC1")
# Aromatic-fused cyclic amine (tetrahydroisoquinoline, indoline etc.): ~9.0
_PAT_BENZO_FUSED_CYCLIC_N = Chem.MolFromSmarts("[NX3;R;!$(NC=O);!$(Nc)][CX4][c]")
def _is_acylated_ring_nitrogen(mol, nidx):
atom = mol.GetAtomWithIdx(nidx)
if atom.GetAtomicNum() != 7:
return False
for nb in atom.GetNeighbors():
if nb.GetAtomicNum() != 6:
continue
for b in nb.GetBonds():
other = b.GetOtherAtom(nb)
if other.GetAtomicNum() == 8 and b.GetBondTypeAsDouble() == 2.0:
return True
return False
def _ring_has_sulfur(mol, atom_idx):
try:
for ring in mol.GetRingInfo().AtomRings():
if atom_idx in ring and any(mol.GetAtomWithIdx(i).GetAtomicNum() == 16 for i in ring):
return True
except Exception:
pass
return False
def _n_atoms_in_match(mol, match):
return [i for i in match if mol.GetAtomWithIdx(i).GetAtomicNum() == 7]
# ─── Tautomer plausibility scoring ───────────────────────────────────────────
_BONUS_DEF = [
("amide", +2.5, "[CX3](=O)[NX3;H1,H2]"),
("lactam", +2.5, "[C;R](=O)[N;R]"),
("acylhydrazone_NH", +2.0, "[CX3](=O)[NX3;H1][NX2]=[CX3]"),
("hydrazide_NH", +2.0, "[CX3](=O)[NX3;H1][NX3;H2]"),
("urea_NH", +1.5, "[NX3;H1][CX3](=O)[NX3;H1,H2]"),
("thioamide", +1.0, "[CX3](=S)[NX3;H1,H2]"),
("aromatic_ring", +0.3, "c1ccccc1"),
("phenol_preserved", W_PHENOL_PRESERVED_BONUS, "c[OX2H1]"),
# NEW: 1,3-dicarbonyl enol bonus (counteracts enol_simple penalty for these)
("enol_1_3_dicarbonyl_bonus", +1.5, "[OX2H1][CX3]=[CX3][CX3]=O"),
]
_PENALTY_DEF = [
("imidic_acid_open", -4.0, "[CX3;!R](=[NX2])[OX2H1]"),
("lactim_ring", -4.0, "[C;R](=[NX2])[OX2H1]"),
("iminol_general", -3.5, "[NX2]=[CX3][OX2H1]"),
("amide_N_deproton", -5.0, "[$([NX3-]C=O),$([NX3-]c=O)]"),
("enol_simple", -1.2, "[CX3](=[CX3])[OX2H1]"),
("pyrogallol_triketo",-W_PYROGALLOL_TRIKETO, "[#6;!a;R]1(=O)[#6;!a;R](=O)[#6;!a;R](=O)[#6;R][#6;R][#6;R]1"),
("catechol_diketo", -W_CATECHOL_DIKETO, "[#6;!a;R]1(=O)[#6;!a;R](=O)[#6;R][#6;R][#6;R][#6;R]1"),
("ring_carbonyl_onaromring_former", -3.0, "[#6;!a;R](=O)[#6;!a;R]=[#6;!a;R]"),
]
_CHEM_RULES = []
for _lbl, _wt, _sma in _BONUS_DEF + _PENALTY_DEF:
_pat = Chem.MolFromSmarts(_sma)
if _pat is not None: _CHEM_RULES.append((_lbl, _wt, _pat))
else: print(f"⚠️ SMARTS compile failed: {_lbl}")
_TAUTOMER_RICH_DEF = [
("imidazole", "[nH]1ccnc1"),
("benzimidazole","c1ccc2[nH]cnc2c1"),
("tetrazole", "c1nn[nH]n1"),
("triazole", "[nH]1ccnn1"),
("pyridone", "[OH]c1ccccn1"),
("keto_enol", "[CX4][CX3](=O)[CX4]"),
("purine", "c1ncnc2[nH]cnc12"),
]
_TAUTOMER_RICH_COMPILED = [(lbl,pat) for lbl,sma in _TAUTOMER_RICH_DEF if (pat := Chem.MolFromSmarts(sma)) is not None]
def _n_aromatic_rings(mol):
if mol is None: return 0
try: return int(rdMolDescriptors.CalcNumAromaticRings(mol))
except Exception: return 0
def _count_phenolic_OH(mol):
if mol is None: return 0
patt = Chem.MolFromSmarts("c[OX2H1]")
return len(mol.GetSubstructMatches(patt)) if patt else 0
def score_tautomer_plausibility(smiles, ref_mol=None):
mol = Chem.MolFromSmiles(smiles)
if mol is None: return -999.0, {}
bd = {}; total = 0.0
for lbl, wt, pat in _CHEM_RULES:
n = len(mol.GetSubstructMatches(pat))
if n: c = wt * n; bd[lbl] = round(c, 3); total += c
if ref_mol is not None:
rings_lost = max(0, _n_aromatic_rings(ref_mol) - _n_aromatic_rings(mol))
if rings_lost > 0:
pen = -W_AROM_RING_LOST * rings_lost
bd["arom_ring_lost_vs_input"] = round(pen, 3); total += pen
phenols_lost = max(0, _count_phenolic_OH(ref_mol) - _count_phenolic_OH(mol))
if phenols_lost > 0:
pen = -W_PHENOL_TO_KETO_FLIP * phenols_lost
bd["phenol_flipped_to_keto"] = round(pen, 3); total += pen
bd["_total"] = round(total, 3)
return total, bd
def is_tautomer_rich(mol):
hits = [l for l, p in _TAUTOMER_RICH_COMPILED if mol.HasSubstructMatch(p)]
return bool(hits), hits
def enumerate_and_filter_tautomers(smiles, max_states=8, cutoff=TAUTOMER_PLAUSIBILITY_CUTOFF):
mol = Chem.MolFromSmiles(smiles)
if mol is None: raise ValueError(f"Bad SMILES: {smiles[:60]}")
ref_mol = mol
tr_flag, tr_motifs = is_tautomer_rich(mol)
enum = rdMolStandardize.TautomerEnumerator()
seen = set(); scored = []
input_canon = Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True)
seen.add(input_canon)
sc0, bd0 = score_tautomer_plausibility(input_canon, ref_mol=ref_mol)
scored.append({"smiles": input_canon, "score": sc0, "breakdown": bd0})
for tmol in enum.Enumerate(mol):
smi = Chem.MolToSmiles(tmol, isomericSmiles=True, canonical=True)
if smi in seen: continue
seen.add(smi)
sc, bd = score_tautomer_plausibility(smi, ref_mol=ref_mol)
scored.append({"smiles": smi, "score": sc, "breakdown": bd})
if not scored:
smi = Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True)
sc, bd = score_tautomer_plausibility(smi, ref_mol=ref_mol)
scored = [{"smiles": smi, "score": sc, "breakdown": bd}]
scored = sorted(scored, key=lambda x: -x["score"])[:max_states]
best = scored[0]["score"]
eff_cutoff = cutoff * (2.0 if tr_flag else 1.0)
kept = [t for t in scored if t["score"] >= best - eff_cutoff]
discarded = [t for t in scored if t["score"] < best - eff_cutoff]
return kept or [scored[0]], discarded, tr_flag, tr_motifs
# ─────────────────────────────────────────────────────────────────────────────
# Flavonoid A-ring phenols (unchanged from original)
# ─────────────────────────────────────────────────────────────────────────────
def _detect_chromone_system(mol):
ring_info = mol.GetRingInfo()
rings = [set(r) for r in ring_info.AtomRings() if len(r) == 6]
if not rings: return set()
def _has_exocyclic_carbonyl(atom_idx):
atom = mol.GetAtomWithIdx(atom_idx)
if atom.GetSymbol() != "C": return False
for bond in atom.GetBonds():
other = bond.GetOtherAtom(atom)
if other.GetSymbol() != "O" or other.IsInRing(): continue
bo = bond.GetBondTypeAsDouble()
if bo == 2.0: return True
if bo == 1.5 and other.GetTotalNumHs() == 0 and other.GetDegree() == 1: return True
return False
pyrone_rings = []
for ring in rings:
ring_os = [i for i in ring if mol.GetAtomWithIdx(i).GetSymbol() == "O"]
ring_cos = [i for i in ring if _has_exocyclic_carbonyl(i)]
if len(ring_os) == 1 and len(ring_cos) >= 1: pyrone_rings.append(ring)
if not pyrone_rings: return set()
system_atoms = set()
for py in pyrone_rings:
system_atoms.update(py)
for other in rings:
if other is py: continue
if len(py & other) >= 2: system_atoms.update(other)
return system_atoms
def _find_flavone_A_ring_phenols(mol):
# Warfarin / 4-hydroxycoumarin-like systems are enol acids, not ordinary
# flavone A-ring phenols; let the dedicated warfarin handler below claim it.
if globals().get("_PAT_WARFARIN_ENOL") is not None and mol.HasSubstructMatch(_PAT_WARFARIN_ENOL):
return []
chromone_atoms = _detect_chromone_system(mol)
if not chromone_atoms: return []
ring_carbonyl_idx = ring_oxygen_idx = None
for idx in chromone_atoms:
atom = mol.GetAtomWithIdx(idx)
if atom.GetSymbol() == "C":
for bond in atom.GetBonds():
other = bond.GetOtherAtom(atom)
if (other.GetSymbol() == "O" and not other.IsInRing() and
bond.GetBondTypeAsDouble() in (2.0, 1.5) and
other.GetTotalNumHs() == 0 and other.GetDegree() == 1):
ring_carbonyl_idx = idx; break
elif atom.GetSymbol() == "O" and atom.IsInRing():