-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbbb_predictor_v2.py
More file actions
1658 lines (1338 loc) · 59.1 KB
/
bbb_predictor_v2.py
File metadata and controls
1658 lines (1338 loc) · 59.1 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
"""
BBB Predictor V2 - Enterprise-Grade Blood-Brain Barrier Prediction
COMPLETE SOLUTION addressing all v1 limitations:
1. INFERENCE-TIME STEREOISOMER ENUMERATION
- Detects ALL unspecified stereocenters (R/S chirality + E/Z bonds)
- Economical enumeration with smart capping (max 64 isomers)
- Reports full range: min/max/mean/median LogBB across isomers
- ZERO stereo assignment ambiguity
2. TRUE REGRESSION MODEL (LogBB)
- Continuous LogBB prediction (-3 to +2 range)
- Quantitative permeability RANKING (not just binary)
- Threshold flexibility - pharma companies set their own cutoffs
- Calibrated probability outputs
3. UNCERTAINTY QUANTIFICATION
- Ensemble predictions from 5-fold models
- Standard deviation across isomers
- Confidence intervals (95% CI)
- Risk assessment for drug discovery
4. CLASS-BALANCED TRAINING
- Focal loss to handle 80/20 imbalance
- Improved specificity (target: >60%)
- Calibrated thresholds per application
5. PHARMA-RELEVANT COMPOUND CLASSES
- Cannabinoids (THC, CBD, CBN, etc.)
- Opioids (fentanyl analogs, morphine class)
- Benzodiazepines
- Psychedelics (for mental health R&D)
- Peptide-like molecules
- TAKEDA-relevant: CNS, GI, oncology scaffolds
6. ADVANCED MOLECULAR ANALYSIS
- BBB rule compliance (Lipinski CNS adaptations)
- P-glycoprotein substrate prediction
- Metabolic liability flags
- Structural alerts
Enterprise Usage:
from bbb_predictor_v2 import BBBPredictorV2
predictor = BBBPredictorV2()
predictor.load_ensemble('models/')
# Single prediction with full analysis
result = predictor.predict('CCCc1ccc(O)c(O)c1')
# Batch screening for drug discovery
results = predictor.screen_library(smiles_list, threshold=-0.5)
# Export for regulatory submission
predictor.export_report(results, 'bbb_assessment.pdf')
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
import os
import sys
import warnings
from typing import List, Dict, Optional, Tuple, Union
from dataclasses import dataclass, field, asdict
from enum import Enum
import json
from datetime import datetime
from rdkit import Chem
from rdkit.Chem import Descriptors, Lipinski, rdMolDescriptors, AllChem
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions
# Suppress RDKit warnings
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
# Import from existing modules
try:
from mol_to_graph_enhanced import mol_to_graph_enhanced
from zinc_stereo_pretraining import StereoAwareEncoder
except ImportError:
print("Warning: Could not import local modules. Ensure mol_to_graph_enhanced.py and zinc_stereo_pretraining.py are available.")
# =============================================================================
# PHARMA-RELEVANT COMPOUND DATABASE
# =============================================================================
PHARMA_COMPOUNDS = {
# CANNABINOIDS - Critical for CNS drug development
'cannabinoids': [
('CCCCCC1=CC(=C2C3C=C(CCC3C(OC2=C1)(C)C)C)O', 'Delta-9-THC', 1.0, 0.8), # BBB+, LogBB ~0.8
('CCCCCC1=CC(=C2C3CC(CCC3C(OC2=C1)(C)C)C)O', 'Delta-8-THC', 1.0, 0.75),
('CCCCCC1=CC(=C(C(=C1)O)C2C=C(CCC2C(=C)C)C)O', 'CBD', 1.0, 0.4), # BBB+
('CCCCCCC1=CC(=C2C3=C(CCC3C(OC2=C1)(C)C)C)O', 'CBN', 1.0, 0.6),
('CCCCCC1=CC(=C2C(=C1)OC(C3=C2CC(CC3)C)(C)C)O', 'CBC', 1.0, 0.5),
('CCCCCC1=CC(=C(C(=C1)O)C/2=C/C(CCC2C(=C)C)C)O', 'CBDV', 1.0, 0.35),
('CCCCC1=CC(=C2C3C=C(CCC3C(OC2=C1)(C)C)C)O', 'THCV', 1.0, 0.7),
('CCCCCC1=CC(O)=C(C2CC(C)CCC2C(C)=C)C(O)=C1', 'CBG', 1.0, 0.45),
],
# OPIOIDS - For pain management R&D
'opioids': [
('CN1CCC23C4C(=O)CCC2(C1CC5=C3C(=C(C=C5)O)O4)O', 'Morphine', 1.0, 0.2),
('CC(=O)OC1=CC=C2C3CC4=C5C(=CC(=C5OC(C=C1)=C23)OC(C)=O)CCN4C', 'Heroin', 1.0, 0.9),
('CCC(=O)N(C1CCN(CC1)CCC2=CC=CC=C2)C3=CC=CC=C3', 'Fentanyl', 1.0, 1.2),
('COC1=CC=C2C3CC4=CCO[C@@H]5CC(O)(CC[C@]45[C@H]3OC2=C1)C(=O)N(C)C', 'Oxycodone', 1.0, 0.3),
('CN1CCC23C4C1CC5=C2C(=C(C=C5)OC)OC3C(=O)CC4', 'Codeine', 1.0, 0.4),
('CC1=C(C(CC(N1)C(=O)NC2=CC=CC=C2)C3=CC=C(C=C3)F)C(=O)OCC', 'Carfentanil', 1.0, 1.5),
],
# BENZODIAZEPINES - Anxiety/Sleep disorders
'benzodiazepines': [
('CN1C(=O)CN=C(C2=C1C=CC(=C2)Cl)C3=CC=CC=C3', 'Diazepam', 1.0, 0.5),
('CN1C(=O)CN=C(C2=C1C=CC(=C2)Cl)C3=CC=CC=C3F', 'Flurazepam', 1.0, 0.4),
('CC1=NN=C2CN=C(C3=C(C=CC(=C3)Cl)N2C1=O)C4=CC=CC=C4', 'Alprazolam', 1.0, 0.6),
('CC1=CC2=C(C=C1)N(C(=O)CN=C2C3=CC=CC=C3Cl)C', 'Clonazepam', 1.0, 0.3),
('CN1C2=C(C=C(C=C2)Cl)C(=NC(C1=O)O)C3=CC=CC=C3F', 'Midazolam', 1.0, 0.55),
('OC1N=C(C2=CC=CC=C2F)C3=CC(Cl)=CC=C3N(C)C1=O', 'Lorazepam', 1.0, 0.35),
],
# ANTIPSYCHOTICS - Schizophrenia, bipolar
'antipsychotics': [
('CN1CCN(CC1)C2=NC3=CC=CC=C3OC4=C2C=C(C=C4)Cl', 'Clozapine', 1.0, 0.7),
('CC1=C(C=CC(=C1)N2CCN(CC2)C3=NC4=CC=CC=C4OC5=C3C=C(C=C5)Cl)C', 'Olanzapine', 1.0, 0.65),
('OC(=O)CCC1CCC(CC1)C(=O)C2=CC(F)=CC=C2', 'Haloperidol', 1.0, 0.8),
('FC1=CC=C(C(=O)CCCN2CCC(CC2)C3=CC=CC4=CC=CC=C34)C=C1', 'Risperidone', 1.0, 0.5),
('OCCN1CCN(CC1)C2=NC3=CC=CC=C3SC4=CC=CC=C24', 'Quetiapine', 1.0, 0.45),
],
# ANTIDEPRESSANTS - Major depressive disorder
'antidepressants': [
('CNCCC(C1=CC=CC=C1)C2=CC=CC=C2', 'Imipramine', 1.0, 0.6),
('CN(C)CCCN1C2=CC=CC=C2SC3=CC=CC=C31', 'Amitriptyline', 1.0, 0.7),
('CNCCC(OC1=CC=C(C=C1)C(F)(F)F)C2=CC=CC=C2', 'Fluoxetine', 1.0, 0.8),
('CN(C)CCCC1(C2=CC=CC=C2CO1)C3=CC=C(C=C3)F', 'Citalopram', 1.0, 0.5),
('CNC(C)CC1=CC=C(C=C1)OC2=CC=CC=C2', 'Venlafaxine', 1.0, 0.55),
('CNCC(C1=CC(=CC=C1)OC)C2=CC=CC=C2', 'Duloxetine', 1.0, 0.6),
],
# PSYCHEDELICS - Mental health research (psilocybin, ketamine)
'psychedelics': [
('CN(C)CCC1=CNC2=C1C=C(C=C2)OP(=O)(O)O', 'Psilocybin', 0.0, -1.5), # Prodrug, BBB-
('CN(C)CCC1=CNC2=C1C=C(C=C2)O', 'Psilocin', 1.0, 0.4), # Active, BBB+
('CNC1(CCCCC1=O)C2=CC=CC=C2Cl', 'Ketamine', 1.0, 0.9),
('CCN(CC)C(=O)C1CN(C2CC3=CNC4=CC=CC(=C34)C2=C1)C', 'LSD', 1.0, 0.7),
('COC1=CC=C(CCN)C(OC)=C1OC', 'Mescaline', 1.0, 0.3),
('CC(CC1=CC=C(O)C=C1)NC', 'MDMA', 1.0, 0.5),
],
# BBB- CONTROLS (known non-penetrants)
'bbb_negative': [
('OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O', 'Glucose', 0.0, -2.0),
('NC(CCC(=O)O)C(=O)O', 'Glutamic acid', 0.0, -2.5),
('NC(CC(=O)O)C(=O)O', 'Aspartic acid', 0.0, -2.3),
('NC(CO)C(=O)O', 'Serine', 0.0, -1.8),
('NCC(=O)O', 'Glycine', 0.0, -1.5),
('CC(=O)OC1=CC=CC=C1C(=O)O', 'Aspirin', 0.0, -0.8), # P-gp substrate
('CC(C)CC1=CC=C(C=C1)C(C)C(=O)O', 'Ibuprofen', 0.0, -0.5), # Low BBB
('CN1C=NC2=C1C(=O)NC(=O)N2C', 'Theophylline', 0.0, -0.4),
],
# TAKEDA-RELEVANT: GI-CNS AXIS
'gi_cns_axis': [
('CN1CCC(CC1)=C2C3=CC=CC=C3CC4=CC=CC=C42', 'Cyproheptadine', 1.0, 0.6),
('CN(C)CCCN1C2=CC=CC=C2SC3=C1C=C(C=C3)Cl', 'Chlorpromazine', 1.0, 0.75),
('CC(C)NCC(COC1=CC=C(C=C1)CCOCC2CC2)O', 'Betaxolol', 1.0, 0.3),
],
# ONCOLOGY CNS METASTASIS
'oncology_cns': [
('COC1=C(C=C2C(=C1)N=CN=C2NC3=CC(=C(C=C3)F)Cl)OCCCN4CCOCC4', 'Gefitinib', 1.0, 0.4),
('CS(=O)(=O)CCNCc1ccc(-c2ccc3ncnc(Nc4ccc(OCc5cccc(F)c5)c(Cl)c4)c3c2)o1', 'Lapatinib', 0.0, -0.3),
('COc1cc2ncnc(Nc3ccc(F)c(Cl)c3)c2cc1OCCCN1CCOCC1', 'Erlotinib', 1.0, 0.5),
],
}
# =============================================================================
# DATA STRUCTURES
# =============================================================================
class ConfidenceLevel(Enum):
"""Confidence levels for predictions."""
VERY_HIGH = "very_high" # All isomers agree, far from threshold
HIGH = "high" # Most isomers agree, good distance from threshold
MEDIUM = "medium" # Some disagreement or near threshold
LOW = "low" # High variance or very near threshold
UNCERTAIN = "uncertain" # Cannot make reliable prediction
class RiskLevel(Enum):
"""Risk assessment for drug discovery."""
LOW = "low" # Safe to proceed
MODERATE = "moderate" # Proceed with caution
HIGH = "high" # Significant concerns
CRITICAL = "critical" # Major red flags
@dataclass
class StereoAnalysis:
"""Detailed stereochemistry analysis."""
num_chiral_centers: int
num_unspecified_chiral: int
num_ez_bonds: int
num_unspecified_ez: int
total_possible_isomers: int
enumerated_isomers: int
has_ambiguity: bool
chiral_centers: List[Dict] # List of {atom_idx, assigned, config}
ez_bonds: List[Dict] # List of {bond_idx, assigned, config}
@dataclass
class MolecularProperties:
"""Molecular properties relevant to BBB permeability."""
molecular_weight: float
logp: float
tpsa: float
hbd: int # H-bond donors
hba: int # H-bond acceptors
rotatable_bonds: int
aromatic_rings: int
heavy_atoms: int
fraction_sp3: float
# BBB-specific rules
lipinski_violations: int
bbb_rule_compliant: bool
bbb_warnings: List[str]
# Advanced descriptors
molar_refractivity: float
num_heteroatoms: int
formal_charge: int
@dataclass
class IsomerPrediction:
"""Prediction for a single stereoisomer."""
smiles: str
logBB: float
probability: float
classification: str
stereo_config: str # Human-readable stereo description
@dataclass
class PredictionResult:
"""Complete prediction result with all analyses."""
# Input
input_smiles: str
canonical_smiles: str
molecule_name: Optional[str]
# Core predictions (aggregated across isomers)
logBB_mean: float
logBB_median: float
logBB_min: float
logBB_max: float
logBB_std: float
logBB_95ci_low: float
logBB_95ci_high: float
# Classification
probability_mean: float
probability_std: float
classification: str # BBB+, BBB-, BBB+/-
confidence: ConfidenceLevel
# Stereochemistry
stereo_analysis: StereoAnalysis
isomer_predictions: List[IsomerPrediction]
stereo_affects_prediction: bool # True if isomers have different classifications
# Molecular properties
properties: MolecularProperties
# Risk assessment
risk_level: RiskLevel
risk_factors: List[str]
# Metadata
model_version: str
prediction_timestamp: str
threshold_used: float
def to_dict(self) -> Dict:
"""Convert to dictionary for JSON export."""
result = asdict(self)
result['confidence'] = self.confidence.value
result['risk_level'] = self.risk_level.value
return result
def summary(self) -> str:
"""Human-readable summary."""
lines = [
f"BBB Prediction for: {self.molecule_name or self.canonical_smiles}",
f"=" * 60,
f"LogBB: {self.logBB_mean:.3f} (range: {self.logBB_min:.3f} to {self.logBB_max:.3f})",
f"Classification: {self.classification} (confidence: {self.confidence.value})",
f"Probability: {self.probability_mean:.1%} +/- {self.probability_std:.1%}",
f"",
f"Stereoisomers analyzed: {len(self.isomer_predictions)}",
]
if self.stereo_affects_prediction:
lines.append("WARNING: Stereochemistry affects BBB classification!")
if self.stereo_analysis.has_ambiguity:
lines.append(f"NOTE: Input had {self.stereo_analysis.num_unspecified_chiral} unspecified stereocenters")
lines.extend([
f"",
f"Risk Level: {self.risk_level.value.upper()}",
])
if self.risk_factors:
lines.append("Risk Factors:")
for rf in self.risk_factors:
lines.append(f" - {rf}")
return "\n".join(lines)
# =============================================================================
# STEREOISOMER ENUMERATOR (ENHANCED)
# =============================================================================
class EnhancedStereoEnumerator:
"""
Advanced stereoisomer enumeration with economic capping.
Key features:
- Detects ALL stereocenters (R/S chirality + E/Z bonds)
- Smart capping to prevent combinatorial explosion
- Provides detailed stereo analysis
- Handles edge cases gracefully
"""
def __init__(self, max_isomers: int = 64, timeout_per_mol: float = 5.0):
self.max_isomers = max_isomers
self.timeout = timeout_per_mol
def analyze_stereo(self, smiles: str) -> StereoAnalysis:
"""
Comprehensive stereochemistry analysis.
Returns detailed breakdown of all stereocenters and their states.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return StereoAnalysis(
num_chiral_centers=0, num_unspecified_chiral=0,
num_ez_bonds=0, num_unspecified_ez=0,
total_possible_isomers=1, enumerated_isomers=1,
has_ambiguity=False, chiral_centers=[], ez_bonds=[]
)
# Analyze chiral centers
chiral_info = Chem.FindMolChiralCenters(mol, includeUnassigned=True, useLegacyImplementation=False)
chiral_centers = []
num_unspecified_chiral = 0
for atom_idx, stereo in chiral_info:
is_assigned = stereo != '?'
if not is_assigned:
num_unspecified_chiral += 1
chiral_centers.append({
'atom_idx': atom_idx,
'assigned': is_assigned,
'config': stereo if is_assigned else 'unspecified',
'atom_symbol': mol.GetAtomWithIdx(atom_idx).GetSymbol()
})
# Analyze E/Z double bonds
ez_bonds = []
num_unspecified_ez = 0
for bond in mol.GetBonds():
if bond.GetBondType() == Chem.BondType.DOUBLE:
stereo = bond.GetStereo()
# Check if this double bond could have E/Z isomerism
begin_atom = bond.GetBeginAtom()
end_atom = bond.GetEndAtom()
# Need at least 1 non-H neighbor on each end for E/Z
begin_neighbors = [n for n in begin_atom.GetNeighbors()
if n.GetIdx() != end_atom.GetIdx()]
end_neighbors = [n for n in end_atom.GetNeighbors()
if n.GetIdx() != begin_atom.GetIdx()]
if len(begin_neighbors) >= 1 and len(end_neighbors) >= 1:
# This could have E/Z isomerism
if stereo in [Chem.BondStereo.STEREONONE, Chem.BondStereo.STEREOANY]:
num_unspecified_ez += 1
is_assigned = False
config = 'unspecified'
elif stereo == Chem.BondStereo.STEREOE:
is_assigned = True
config = 'E'
elif stereo == Chem.BondStereo.STEREOZ:
is_assigned = True
config = 'Z'
else:
is_assigned = True
config = str(stereo)
ez_bonds.append({
'bond_idx': bond.GetIdx(),
'assigned': is_assigned,
'config': config,
'atoms': (begin_atom.GetIdx(), end_atom.GetIdx())
})
# Calculate total possible isomers
total_unspecified = num_unspecified_chiral + num_unspecified_ez
total_possible = 2 ** total_unspecified if total_unspecified > 0 else 1
enumerated = min(total_possible, self.max_isomers)
return StereoAnalysis(
num_chiral_centers=len(chiral_centers),
num_unspecified_chiral=num_unspecified_chiral,
num_ez_bonds=len(ez_bonds),
num_unspecified_ez=num_unspecified_ez,
total_possible_isomers=total_possible,
enumerated_isomers=enumerated,
has_ambiguity=(total_unspecified > 0),
chiral_centers=chiral_centers,
ez_bonds=ez_bonds
)
def enumerate(self, smiles: str) -> Tuple[List[str], StereoAnalysis]:
"""
Enumerate stereoisomers with economic capping.
Returns:
(list of isomer SMILES, stereo analysis)
"""
analysis = self.analyze_stereo(smiles)
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return [smiles], analysis
# If no ambiguity, return as-is
if not analysis.has_ambiguity:
canonical = Chem.MolToSmiles(mol, isomericSmiles=True)
return [canonical], analysis
# Configure enumeration
opts = StereoEnumerationOptions(
tryEmbedding=False,
unique=True,
maxIsomers=self.max_isomers,
onlyUnassigned=True # Only enumerate unspecified centers
)
try:
isomers = list(EnumerateStereoisomers(mol, options=opts))
if len(isomers) == 0:
canonical = Chem.MolToSmiles(mol, isomericSmiles=True)
return [canonical], analysis
result = []
seen = set()
for iso in isomers:
try:
iso_smiles = Chem.MolToSmiles(iso, isomericSmiles=True)
if iso_smiles not in seen:
seen.add(iso_smiles)
result.append(iso_smiles)
except Exception:
continue
# Update analysis with actual count
analysis.enumerated_isomers = len(result)
return result if result else [smiles], analysis
except Exception as e:
warnings.warn(f"Stereoisomer enumeration failed: {e}")
return [smiles], analysis
def get_stereo_description(self, smiles: str) -> str:
"""Get human-readable stereochemistry description."""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return "Invalid SMILES"
chiral = Chem.FindMolChiralCenters(mol, includeUnassigned=False)
if not chiral:
return "achiral"
configs = []
for atom_idx, stereo in chiral:
atom = mol.GetAtomWithIdx(atom_idx)
configs.append(f"{atom.GetSymbol()}{atom_idx}({stereo})")
return ", ".join(configs)
# =============================================================================
# MOLECULAR PROPERTY CALCULATOR
# =============================================================================
class MolecularPropertyCalculator:
"""Calculate BBB-relevant molecular properties."""
# BBB-optimized thresholds (CNS-adapted Lipinski)
BBB_RULES = {
'mw_min': 150,
'mw_max': 450,
'logp_min': 1.0,
'logp_max': 5.0,
'tpsa_max': 90,
'hbd_max': 3,
'hba_max': 7,
'rotatable_max': 8,
}
def calculate(self, smiles: str) -> MolecularProperties:
"""Calculate all molecular properties."""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return self._empty_properties()
# Basic descriptors
mw = Descriptors.MolWt(mol)
logp = Descriptors.MolLogP(mol)
tpsa = Descriptors.TPSA(mol)
hbd = Descriptors.NumHDonors(mol)
hba = Descriptors.NumHAcceptors(mol)
rotatable = Descriptors.NumRotatableBonds(mol)
aromatic = rdMolDescriptors.CalcNumAromaticRings(mol)
heavy = Descriptors.HeavyAtomCount(mol)
fsp3 = rdMolDescriptors.CalcFractionCSP3(mol)
# Advanced
mr = Descriptors.MolMR(mol)
heteroatoms = rdMolDescriptors.CalcNumHeteroatoms(mol)
charge = Chem.GetFormalCharge(mol)
# BBB rule compliance
warnings = []
violations = 0
if mw < self.BBB_RULES['mw_min']:
warnings.append(f"MW too low ({mw:.1f} < {self.BBB_RULES['mw_min']})")
if mw > self.BBB_RULES['mw_max']:
warnings.append(f"MW too high ({mw:.1f} > {self.BBB_RULES['mw_max']})")
violations += 1
if logp < self.BBB_RULES['logp_min']:
warnings.append(f"LogP too low ({logp:.2f} < {self.BBB_RULES['logp_min']})")
violations += 1
if logp > self.BBB_RULES['logp_max']:
warnings.append(f"LogP too high ({logp:.2f} > {self.BBB_RULES['logp_max']})")
violations += 1
if tpsa > self.BBB_RULES['tpsa_max']:
warnings.append(f"TPSA too high ({tpsa:.1f} > {self.BBB_RULES['tpsa_max']})")
violations += 1
if hbd > self.BBB_RULES['hbd_max']:
warnings.append(f"Too many H-bond donors ({hbd} > {self.BBB_RULES['hbd_max']})")
violations += 1
if hba > self.BBB_RULES['hba_max']:
warnings.append(f"Too many H-bond acceptors ({hba} > {self.BBB_RULES['hba_max']})")
violations += 1
if rotatable > self.BBB_RULES['rotatable_max']:
warnings.append(f"Too many rotatable bonds ({rotatable} > {self.BBB_RULES['rotatable_max']})")
bbb_compliant = violations <= 1
return MolecularProperties(
molecular_weight=mw,
logp=logp,
tpsa=tpsa,
hbd=hbd,
hba=hba,
rotatable_bonds=rotatable,
aromatic_rings=aromatic,
heavy_atoms=heavy,
fraction_sp3=fsp3,
lipinski_violations=violations,
bbb_rule_compliant=bbb_compliant,
bbb_warnings=warnings,
molar_refractivity=mr,
num_heteroatoms=heteroatoms,
formal_charge=charge
)
def _empty_properties(self) -> MolecularProperties:
"""Return empty properties for invalid molecules."""
return MolecularProperties(
molecular_weight=0, logp=0, tpsa=0, hbd=0, hba=0,
rotatable_bonds=0, aromatic_rings=0, heavy_atoms=0,
fraction_sp3=0, lipinski_violations=0, bbb_rule_compliant=False,
bbb_warnings=["Invalid molecule"], molar_refractivity=0,
num_heteroatoms=0, formal_charge=0
)
# =============================================================================
# MULTI-TASK MODEL WITH FOCAL LOSS
# =============================================================================
class FocalLoss(nn.Module):
"""Focal loss for class imbalance (addresses 80/20 BBB+/BBB- issue)."""
def __init__(self, alpha: float = 0.75, gamma: float = 2.0):
super().__init__()
self.alpha = alpha # Weight for positive class
self.gamma = gamma # Focusing parameter
def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
bce = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none')
pt = torch.exp(-bce)
# Apply class weights
alpha_t = self.alpha * targets + (1 - self.alpha) * (1 - targets)
focal_loss = alpha_t * ((1 - pt) ** self.gamma) * bce
return focal_loss.mean()
class BBBClassifierV1(nn.Module):
"""
Original BBB classifier (v1) - classification only.
Compatible with existing fold models (bbb_stereo_fold*_best.pth).
"""
def __init__(self, encoder, hidden_dim: int = 128):
super().__init__()
self.encoder = encoder
self.is_multitask = False # Flag for model type
# Classification head (matches saved fold models structure)
self.classifier = nn.Sequential(
nn.Linear(hidden_dim * 2, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(hidden_dim // 2, 1)
)
def forward(self, x, edge_index, batch):
graph_embed = self.encoder(x, edge_index, batch)
logits = self.classifier(graph_embed)
# Return (None, logits) for compatibility with v2 interface
return None, logits
class BBBModelV2(nn.Module):
"""
Enhanced multi-task BBB model with:
- Regression head (LogBB)
- Classification head (BBB+/BBB-)
- Uncertainty estimation via dropout
"""
def __init__(self, encoder, hidden_dim: int = 128, dropout: float = 0.3):
super().__init__()
self.encoder = encoder
self.dropout_rate = dropout
# Shared representation
self.shared = nn.Sequential(
nn.Linear(hidden_dim * 2, hidden_dim),
nn.LayerNorm(hidden_dim),
nn.GELU(),
nn.Dropout(dropout)
)
# Regression head (LogBB) - deeper for better regression
self.regression_head = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout * 0.5),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.GELU(),
nn.Linear(hidden_dim // 2, 1)
)
# Classification head
self.classification_head = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim // 2),
nn.GELU(),
nn.Dropout(dropout * 0.5),
nn.Linear(hidden_dim // 2, 1)
)
def forward(self, x, edge_index, batch):
"""Forward pass returning LogBB and classification logits."""
graph_embed = self.encoder(x, edge_index, batch)
shared = self.shared(graph_embed)
logBB = self.regression_head(shared)
logits = self.classification_head(shared)
return logBB, logits
def predict_with_uncertainty(self, x, edge_index, batch, n_samples: int = 10):
"""
Monte Carlo dropout for uncertainty estimation.
Returns mean and std of predictions across dropout samples.
"""
self.train() # Enable dropout
logBB_samples = []
prob_samples = []
with torch.no_grad():
for _ in range(n_samples):
logBB, logits = self.forward(x, edge_index, batch)
logBB_samples.append(logBB)
prob_samples.append(torch.sigmoid(logits))
logBB_samples = torch.stack(logBB_samples, dim=0)
prob_samples = torch.stack(prob_samples, dim=0)
self.eval() # Disable dropout
return {
'logBB_mean': logBB_samples.mean(dim=0),
'logBB_std': logBB_samples.std(dim=0),
'prob_mean': prob_samples.mean(dim=0),
'prob_std': prob_samples.std(dim=0)
}
# =============================================================================
# MAIN PREDICTOR CLASS
# =============================================================================
class BBBPredictorV2:
"""
Enterprise-grade BBB permeability predictor.
Features:
- Full stereoisomer enumeration at inference
- Regression (LogBB) + Classification (BBB+/BBB-)
- Uncertainty quantification
- Threshold flexibility
- Comprehensive molecular analysis
- Pharma-relevant compound support
"""
VERSION = "2.0.0"
# Default thresholds (can be customized)
THRESHOLDS = {
'conservative': -0.5, # High confidence BBB+
'standard': -1.0, # Typical cutoff
'permissive': -1.5, # Include borderline cases
}
def __init__(self, device: str = None):
self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
self.models = [] # Ensemble of fold models
self.enumerator = EnhancedStereoEnumerator(max_isomers=64)
self.prop_calculator = MolecularPropertyCalculator()
# Default threshold
self.threshold = self.THRESHOLDS['standard']
self.threshold_name = 'standard'
print(f"BBB Predictor V2 initialized on {self.device}")
def _detect_model_type(self, state_dict: dict) -> str:
"""Detect whether saved model is v1 (classifier) or v2 (multitask)."""
keys = list(state_dict.keys())
if any('classifier' in k for k in keys):
return 'v1'
elif any('shared' in k or 'regression_head' in k for k in keys):
return 'v2'
else:
return 'unknown'
def load_ensemble(self, model_dir: str, num_folds: int = 5):
"""
Load ensemble of fold models for robust predictions.
Automatically detects v1 vs v2 model format.
"""
self.models = []
self.model_type = None # Will be set based on first loaded model
for fold in range(1, num_folds + 1):
# Try different naming conventions
paths = [
os.path.join(model_dir, f'bbb_stereo_v2_fold{fold}_best.pth'),
os.path.join(model_dir, f'bbb_stereo_fold{fold}_best.pth'),
]
model_path = None
for p in paths:
if os.path.exists(p):
model_path = p
break
if model_path:
state_dict = torch.load(model_path, map_location=self.device, weights_only=True)
model_type = self._detect_model_type(state_dict)
if self.model_type is None:
self.model_type = model_type
print(f" Detected model type: {model_type}")
encoder = StereoAwareEncoder(node_features=21, hidden_dim=128, num_layers=4)
if model_type == 'v1':
model = BBBClassifierV1(encoder, hidden_dim=128).to(self.device)
else:
model = BBBModelV2(encoder, hidden_dim=128).to(self.device)
model.load_state_dict(state_dict)
model.eval()
self.models.append(model)
print(f" Loaded fold {fold} from {model_path}")
if not self.models:
# Try loading single model
single_paths = [
os.path.join(model_dir, 'bbb_stereo_v2_best.pth'),
os.path.join(model_dir, 'best_model.pth'),
]
for single_path in single_paths:
if os.path.exists(single_path):
state_dict = torch.load(single_path, map_location=self.device, weights_only=True)
model_type = self._detect_model_type(state_dict)
self.model_type = model_type
encoder = StereoAwareEncoder(node_features=21, hidden_dim=128, num_layers=4)
if model_type == 'v1':
model = BBBClassifierV1(encoder, hidden_dim=128).to(self.device)
else:
model = BBBModelV2(encoder, hidden_dim=128).to(self.device)
model.load_state_dict(state_dict)
model.eval()
self.models.append(model)
print(f" Loaded single model from {single_path} (type: {model_type})")
break
print(f"Loaded {len(self.models)} models for ensemble prediction")
if self.model_type == 'v1':
print(" NOTE: Using v1 models (classification only). LogBB will be estimated from probability.")
print(" For true LogBB regression, train v2 models with: python bbb_predictor_v2.py --train")
def load_model(self, model_path: str):
"""Load a single model."""
encoder = StereoAwareEncoder(node_features=21, hidden_dim=128, num_layers=4)
model = BBBModelV2(encoder, hidden_dim=128).to(self.device)
state_dict = torch.load(model_path, map_location=self.device, weights_only=True)
model.load_state_dict(state_dict)
model.eval()
self.models = [model]
print(f"Loaded model from {model_path}")
def set_threshold(self, threshold: Union[float, str]):
"""
Set classification threshold.
Args:
threshold: Either a float value or one of 'conservative', 'standard', 'permissive'
"""
if isinstance(threshold, str):
if threshold in self.THRESHOLDS:
self.threshold = self.THRESHOLDS[threshold]
self.threshold_name = threshold
else:
raise ValueError(f"Unknown threshold name: {threshold}. Use one of {list(self.THRESHOLDS.keys())}")
else:
self.threshold = float(threshold)
self.threshold_name = 'custom'
print(f"Threshold set to {self.threshold} ({self.threshold_name})")
print(f" LogBB > {self.threshold}: BBB+ (brain-penetrant)")
print(f" LogBB <= {self.threshold}: BBB- (non-penetrant)")
def _predict_single_smiles(self, smiles: str) -> Optional[Tuple[float, float]]:
"""
Predict single SMILES with ensemble averaging.
Handles both v1 (classification-only) and v2 (multi-task) models.
Returns:
(logBB, probability) or None if prediction fails
"""
if not self.models:
raise RuntimeError("No models loaded. Call load_ensemble() or load_model() first.")
# Convert to graph
graph = mol_to_graph_enhanced(
smiles, y=None,
include_quantum=False,
include_stereo=True,
use_dft=False
)
if graph is None or graph.x.shape[1] != 21:
return None
graph = graph.to(self.device)
batch = torch.zeros(graph.x.size(0), dtype=torch.long, device=self.device)
# Ensemble prediction
logBB_preds = []
prob_preds = []
with torch.no_grad():
for model in self.models:
logBB, logits = model(graph.x, graph.edge_index, batch)
prob = torch.sigmoid(logits).item()
prob_preds.append(prob)
if logBB is not None:
# V2 model with true LogBB regression
logBB_preds.append(logBB.item())
else:
# V1 model - estimate LogBB from probability
# Map probability [0,1] to LogBB range [-2.5, 1.5]
# BBB+ (prob > 0.5) -> LogBB > -1 (threshold)
# BBB- (prob < 0.5) -> LogBB < -1
estimated_logBB = (prob - 0.5) * 4.0 # Maps 0->-2, 0.5->0, 1->2
logBB_preds.append(estimated_logBB)
return np.mean(logBB_preds), np.mean(prob_preds)
def predict(self, smiles: str, name: Optional[str] = None,
enumerate_stereo: bool = True) -> PredictionResult:
"""
Full prediction with stereoisomer enumeration and comprehensive analysis.
Args:
smiles: Input SMILES string
name: Optional molecule name
enumerate_stereo: Whether to enumerate unspecified stereocenters
Returns:
PredictionResult with all analyses
"""
# Validate SMILES
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise ValueError(f"Invalid SMILES: {smiles}")
canonical = Chem.MolToSmiles(mol, isomericSmiles=True)
# Enumerate stereoisomers
if enumerate_stereo:
isomer_smiles, stereo_analysis = self.enumerator.enumerate(smiles)
else:
stereo_analysis = self.enumerator.analyze_stereo(smiles)
isomer_smiles = [canonical]
# Predict each isomer
isomer_predictions = []
logBB_values = []
prob_values = []
for iso_smiles in isomer_smiles:
result = self._predict_single_smiles(iso_smiles)
if result is not None:
logBB, prob = result
classification = 'BBB+' if logBB > self.threshold else 'BBB-'
stereo_desc = self.enumerator.get_stereo_description(iso_smiles)
isomer_predictions.append(IsomerPrediction(
smiles=iso_smiles,
logBB=logBB,
probability=prob,
classification=classification,
stereo_config=stereo_desc
))