-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
1276 lines (1096 loc) · 40 KB
/
utils.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities for data calculation.
"""
import gzip
from typing import List, Dict, Set, Callable, Union
# import sys
import pandas as pd
from pandas import DataFrame
import numpy as np
import itertools
from scipy import stats
try:
from pandarallel import pandarallel
PARALLEL = True
except ImportError:
PARALLEL = False
try:
from tqdm.notebook import tqdm
tqdm.pandas()
TQDM = True
except ImportError:
TQDM = False
from rdkit.Chem import AllChem as Chem
from rdkit.Chem import Mol
import rdkit.Chem.Descriptors as Desc
import rdkit.Chem.rdMolDescriptors as rdMolDesc
from rdkit.Chem import Fragments
from rdkit.Chem import Crippen
# from rdkit.Chem.MolStandardize import rdMolStandardize
# from rdkit.Chem.MolStandardize.validate import Validator
from rdkit.Chem.MolStandardize.charge import Uncharger
from rdkit.Chem.MolStandardize.fragment import LargestFragmentChooser
from rdkit.Chem.MolStandardize.standardize import Standardizer
from rdkit.Chem.MolStandardize.tautomer import TautomerCanonicalizer
from rdkit import rdBase
rdBase.DisableLog("rdApp.info")
# rdBase.DisableLog("rdApp.warn")
molvs_s = Standardizer()
molvs_l = LargestFragmentChooser()
molvs_u = Uncharger()
molvs_t = TautomerCanonicalizer(max_tautomers=100)
PALETTE = [
"#EB5763", # red
"#47ED47", # green
"#81C0EB", # blue
"#FDD247", # orange
]
# from sklearn import decomposition
# from sklearn import datasets
# from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
import seaborn as sns
def get_value(str_val: str):
"""convert a string into float or int, if possible."""
if not str_val:
return np.nan
try:
val = float(str_val)
if "." not in str_val:
val = int(val)
except ValueError:
val = str_val
return val
def read_sdf(fn, merge_prop: str = None, merge_list: Union[List, Set] = None):
"""Create a DataFrame instance from an SD file.
The input can be a single SD file or a list of files and they can be gzipped (fn ends with `.gz`).
If a list of files is used, all files need to have the same fields.
The molecules will be converted to Smiles.
Parameters:
===========
merge_prop: A property in the SD file on which the file should be merge
during reading.
merge_list: A list or set of values on which to merge.
Only the values of the list are kept.
"""
d = {"Smiles": []}
ctr = {x: 0 for x in ["In", "Out", "Fail_NoMol"]}
if merge_prop is not None:
ctr["NotMerged"] = 0
first_mol = True
sd_props = set()
if not isinstance(fn, list):
fn = [fn]
for f in fn:
do_close = True
if isinstance(f, str):
if f.endswith(".gz"):
file_obj = gzip.open(f, mode="rb")
else:
file_obj = open(f, "rb")
else:
file_obj = f
do_close = False
reader = Chem.ForwardSDMolSupplier(file_obj)
for mol in reader:
ctr["In"] += 1
if not mol:
ctr["Fail_NoMol"] += 1
continue
if first_mol:
first_mol = False
# Is the SD file name property used?
name = mol.GetProp("_Name")
if len(name) > 0:
has_name = True
d["Name"] = []
else:
has_name = False
for prop in mol.GetPropNames():
sd_props.add(prop)
d[prop] = []
if merge_prop is not None:
# Only keep the record when the `merge_prop` value is in `merge_list`:
if get_value(mol.GetProp(merge_prop)) not in merge_list:
ctr["NotMerged"] += 1
continue
mol_props = set()
ctr["Out"] += 1
for prop in mol.GetPropNames():
if prop in sd_props:
mol_props.add(prop)
d[prop].append(get_value(mol.GetProp(prop)))
mol.ClearProp(prop)
if has_name:
d["Name"].append(get_value(mol.GetProp("_Name")))
mol.ClearProp("_Name")
# append NAN to the missing props that were not in the mol:
missing_props = sd_props - mol_props
for prop in missing_props:
d[prop].append(np.nan)
d["Smiles"].append(mol_to_smiles(mol))
if do_close:
file_obj.close()
# Make sure, that all columns have the same length.
# Although, Pandas would also complain, if this was not the case.
d_keys = list(d.keys())
if len(d_keys) > 1:
k_len = len(d[d_keys[0]])
for k in d_keys[1:]:
assert k_len == len(d[k]), f"{k_len=} != {len(d[k])}"
result = pd.DataFrame(d)
print(ctr)
return result
def mol_to_smiles(mol: Mol, canonical: bool = True) -> str:
"""Generate Smiles from mol.
Parameters:
===========
mol: the input molecule
canonical: whether to return the canonical Smiles or not
Returns:
========
The Smiles of the molecule (canonical by default). NAN for failed molecules."""
if mol is None:
return np.nan
try:
smi = Chem.MolToSmiles(mol, canonical=canonical)
return smi
except:
return np.nan
def smiles_to_mol(smiles: str) -> Mol:
"""Generate a RDKit Molecule from a Smiles.
Parameters:
===========
smiles: the input string
Returns:
========
The RDKit Molecule. If the Smiles parsing failed, NAN instead.
"""
try:
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
return mol
return np.nan
except ValueError:
return np.nan
def drop_cols(df: DataFrame, cols: List[str]) -> DataFrame:
"""Remove the list of columns from the dataframe.
Listed columns that are not available in the dataframe are simply ignored."""
df = df.copy()
cols_to_remove = set(cols).intersection(set(df.keys()))
df = df.drop(cols_to_remove, axis=1)
return df
def standardize_mol(
mol: Mol, remove_stereo: bool = False, canonicalize_tautomer: bool = False
):
"""Standardize the molecule structures.
Returns:
========
Smiles of the standardized molecule. NAN for failed molecules."""
if mol is None:
return np.nan
mol = molvs_l.choose(mol)
mol = molvs_u.uncharge(mol)
mol = molvs_s.standardize(mol)
if remove_stereo:
mol = molvs_s.stereo_parent(mol)
if canonicalize_tautomer:
mol = molvs_t.canonicalize(mol)
# mol = largest.choose(mol)
# mol = uncharger.uncharge(mol)
# mol = normal.normalize(mol)
# mol = enumerator.Canonicalize(mol)
return mol_to_smiles(mol)
def apply_to_smiles(
df: DataFrame,
smiles_col: str,
funcs: Dict[str, Callable],
parallel: bool = False,
workers: int = 6,
) -> DataFrame:
"""Calculation of chemical properties,
directly on the Smiles.
Parameters:
===========
df: Pandas DataFrame
smiles_col: Name of the Smiles column
funcs: A dict of names and functions to apply to the mol object.
The keys are the names of the generated columns,
the values are the functions.
If the generation of the intermediary mol object fails, NAN is returned.
parallel: Set to True when the function should be run in parallel (default: False).
pandarallel has to be installed for this.
workers: Number of workers to be used when running in parallel.
Returns:
========
New DataFrame with the calculated properties.
Example:
========
`df` is a DataFrame that contains a "Smiles" column.
>>> from rdkit.Chem import Descriptors as Desc
>>> df2 = apply_to_smiles(df, "Smiles", {"MW": Desc.MolWt, "LogP": Desc.MolLogP})
"""
func_items = funcs.items()
func_keys = {i: x[0] for i, x in enumerate(func_items)}
func_vals = [x[1] for x in func_items]
def _apply(smi):
if not isinstance(smi, str):
res = [np.nan] * len(func_vals)
return pd.Series(res)
mol = Chem.MolFromSmiles(smi)
if mol is None:
res = [np.nan] * len(func_vals)
return pd.Series(res)
res = []
for f in func_vals:
try:
r = f(mol)
res.append(r)
except:
res.append(np.nan)
return pd.Series(res)
df = df.copy()
fallback = True
if parallel:
if not PARALLEL:
print("Parallel option not available. Please install pandarallel.")
print("Using single core calculation.")
else:
pandarallel.initialize(nb_workers=workers, progress_bar=TQDM)
result = df[smiles_col].parallel_apply(_apply)
fallback = False
if fallback:
if TQDM:
result = df[smiles_col].progress_apply(_apply)
else:
result = df[smiles_col].apply(_apply)
result = result.rename(columns=func_keys)
df = pd.concat([df, result], axis=1)
return df
def get_atom_set(mol: Mol):
result = set()
for at in mol.GetAtoms():
result.add(at.GetAtomicNum())
return result
def filter_mols(
df: DataFrame, smiles_col: str, filter: Union[str, List[str]]
) -> DataFrame:
"""Apply different filters to the molecules.
Parameters:
===========
filter [str or list of strings]: The name of the filter to apply.
Available filters:
- Isotopes: Keep only non-isotope molecules
- MedChemAtoms: Keep only molecules with MedChem atoms
- MinHeavyAtoms: Keep only molecules with 3 or more heacy atoms
- MaxHeavyAtoms: Keep only molecules with 75 or less heacy atoms
- Duplicates: Remove duplicates by InChiKey
"""
available_filters = {
"Isotopes",
"MedChemAtoms",
"MinHeavyAtoms",
"MaxHeavyAtoms",
"Duplicates",
}
medchem_atoms = {1, 5, 6, 7, 8, 9, 15, 16, 17, 35, 53}
def has_non_medchem_atoms(mol: Mol):
if len(get_atom_set(mol) - medchem_atoms) > 0:
return True
return False
def has_isotope(mol: Mol) -> bool:
for at in mol.GetAtoms():
if at.GetIsotope() != 0:
return True
return False
df = df.copy()
if isinstance(filter, str):
filter = [filter]
for filt in filter:
if filt not in available_filters:
raise ValueError(f"Unknown filter: {filt}")
calc_ha = False
cols_to_remove = []
print(f"Applying filters ({len(filter)})...")
for filt in filter:
if filt == "Isotopes":
df = apply_to_smiles(df, smiles_col, {"FiltIsotopes": has_isotope})
df = df.query("FiltIsotopes == False")
cols_to_remove.append("FiltIsotopes")
print(f"Applied filter {filt}: ", end="")
elif filt == "MedChemAtoms":
df = apply_to_smiles(
df, smiles_col, {"FiltNonMCAtoms": has_non_medchem_atoms}
)
df = df.query("FiltNonMCAtoms == False")
cols_to_remove.append("FiltNonMCAtoms")
print(f"Applied filter {filt}: ", end="")
elif filt == "MinHeavyAtoms":
if not calc_ha:
df = apply_to_smiles(
df, smiles_col, {"FiltHeavyAtoms": Desc.HeavyAtomCount}
)
calc_ha = True
df = df.query("FiltHeavyAtoms >= 3")
cols_to_remove.append("FiltHeavyAtoms")
print(f"Applied filter {filt}: ", end="")
elif filt == "MaxHeavyAtoms":
if not calc_ha:
df = apply_to_smiles(
df, smiles_col, {"FiltHeavyAtoms": Desc.HeavyAtomCount}
)
calc_ha = True
df = df.query("FiltHeavyAtoms <= 75")
cols_to_remove.append("FiltHeavyAtoms")
print(f"Applied filter {filt}: ", end="")
elif filt == "Duplicates":
df = apply_to_smiles(
df, smiles_col, {"FiltInChiKey": Chem.inchi.MolToInchiKey}
)
df = df.drop_duplicates(subset="FiltInChiKey")
cols_to_remove.append("FiltInChiKey")
print(f"Applied filter {filt}: ", end="")
else:
print()
raise ValueError(f"Unknown filter: {filt}.")
print(len(df))
df = drop_cols(df, cols_to_remove)
return df
def read_tsv(
input_tsv: str, smiles_col: str = "Smiles", parse_smiles: bool = False
) -> pd.DataFrame:
"""Read a tsv file, optionnally converting smiles into RDKit molecules.
Parameters:
===========
input_tsv: Input tsv file
smiles_col: Name of the Smiles column
Returns:
========
The parsed tsv as Pandas DataFrame.
"""
df = pd.read_csv(input_tsv, sep="\t")
if parse_smiles and smiles_col in df.columns:
df[smiles_col] = df[smiles_col].map(smiles_to_mol)
return df
def write_tsv(df: pd.DataFrame, output_tsv: str, smiles_col: str = "Smiles"):
"""Write a tsv file, converting the RDKit molecule column to smiles.
If the Smiles column contains RDKit Molecules instead of strings, these are converted to Smiles with default parameters.
Parameters:
===========
input_tsv: Input tsv file
smiles_col: Name of the Smiles column
Returns:
========
The parsed tsv as Pandas DataFrame.
"""
if len(df) > 0 and smiles_col in df.columns:
probed = df.iloc[0][smiles_col]
if isinstance(probed, Mol):
df[smiles_col] = df[smiles_col].map(mol_to_smiles)
df.to_csv(output_tsv, sep="\t", index=False)
def count_violations_lipinski(
molecular_weight: float, slogp: float, num_hbd: int, num_hba: int
) -> int:
"""Apply the filters described in reference (Lipinski's rule of 5) and count how many rules
are violated. If 0, then the compound is strictly drug-like according to Lipinski et al.
Ref: Lipinski, J Pharmacol Toxicol Methods. 2000 Jul-Aug;44(1):235-49.
Parameters:
===========
molecular_weight: Molecular weight
slogp: LogP computed with RDKit
num_hbd: Number of Hydrogen Donors
num_hba: Number of Hydrogen Acceptors
Returns:
========
The number of violations of the Lipinski's rule.
"""
n = 0
if molecular_weight < 150 or molecular_weight > 500:
n += 1
if slogp > 5:
n += 1
if num_hbd > 5:
n += 1
if num_hba > 10:
n += 1
return n
def count_violations_veber(num_rotatable_bonds: int, tpsa: float) -> int:
"""Apply the filters described in reference (Veber's rule) and count how many rules
are violated. If 0, then the compound is strictly drug-like according to Veber et al.
Ref: Veber DF, Johnson SR, Cheng HY, Smith BR, Ward KW, Kopple KD (June 2002).
"Molecular properties that influence the oral bioavailability of drug candidates".
J. Med. Chem. 45 (12): 2615–23.
Parameters:
===========
num_rotatable_bonds: Number of rotatable bonds
tpsa: Topological Polar Surface Area
Returns:
========
The number of violations of the Veber's rule.
"""
n = 0
if num_rotatable_bonds > 10:
n += 1
if tpsa > 140:
n += 1
return n
def get_min_ring_size(mol: Mol) -> int:
"""Return the minimum ring size of a molecule. If the molecule is linear, 0 is returned.
Parameters:
===========
mol: The input molecule
Returns:
========
The minimal ring size of the input molecule
"""
ring_sizes = [len(x) for x in mol.GetRingInfo().AtomRings()]
try:
return min(ring_sizes)
except ValueError:
return 0
def get_max_ring_size(mol: Mol) -> int:
"""Return the maximum ring size of a molecule. If the molecule is linear, 0 is returned.
Parameters:
===========
mol: The input molecule
Returns:
========
The maximal ring size of the input molecule
"""
ring_sizes = [len(x) for x in mol.GetRingInfo().AtomRings()]
try:
return max(ring_sizes)
except ValueError:
return 0
def compute_descriptors(mol: Mol, descriptors_list: list = None) -> dict:
"""Compute predefined descriptors for a molecule.
If the parsing of a molecule fails, then an Nan values are generated for all properties.
Parameters:
===========
mol: The input molecule
descriptors_list: A list of descriptors, in case the user wants to compute less than default.
Returns:
========
A dictionary with computed descriptors with syntax such as descriptor_name: value.
"""
# predefined descriptors
descriptors = DESCRIPTORS
# update the list of descriptors to compute with whatever descriptor names are in the provided list,
# if the list contains an unknown descriptor, a KeyError will be raised.
if descriptors_list is not None:
descriptors = {k: v for k, v in descriptors.items() if k in descriptors_list}
# parse smiles on the fly
if isinstance(mol, str):
mol = Chem.MolFromSmiles(mol)
# if parsing fails, return dict with missing values
if mol is None:
return {k: None for k in descriptors.keys()}
# run
try:
# compute molecular descriptors
d = {k: v(mol) for k, v in descriptors.items()}
# annotate subsets
d["num_violations_lipinski"] = count_violations_lipinski(
d["molecular_weight"], d["slogp"], d["num_hbd"], d["num_hba"]
)
d["num_violations_veber"] = count_violations_veber(
d["num_rotatable_bond"], d["tpsa"]
)
except ValueError:
d = {k: None for k in descriptors.keys()}
return d
def compute_descriptors_df(df: DataFrame, smiles_col: str) -> DataFrame:
"""Compute descriptors on the smiles column of a DataFrame.
The Smiles is parsed on the fly only once.
Parameters:
===========
df: The input DataFrame
smiles_col: The name of the column with the molecules in smiles format
Returns:
========
The input dictionary concatenated with the computed descriptors
"""
return pd.concat(
[
df,
df.apply(lambda x: compute_descriptors(x[smiles_col]), axis=1).apply(
pd.Series
),
],
axis=1,
)
def lp(obj, label: str = None, lpad=50, rpad=10):
"""log-printing for different kind of objects"""
if isinstance(obj, str):
if label is None:
label = "String"
print(f"{label:{lpad}s}: {obj:>{rpad}s}")
return
try:
fval = float(obj)
if label is None:
label = "Number"
if fval == obj:
print(f"{label:{lpad}s}: {int(obj):{rpad}d}")
else:
print(f"{label:{lpad}s}: {obj:{rpad+6}.5f}")
return
except (ValueError, TypeError):
# print("Exception")
pass
try:
shape = obj.shape
if label is None:
label = "Shape"
else:
label = f"Shape {label}"
key_str = ""
try:
keys = list(obj.keys())
if len(keys) <= 5:
key_str = " [ " + ", ".join(keys) + " ] "
except AttributeError:
pass
num_nan_cols = ((~obj.notnull()).sum() > 0).sum()
has_nan_str = ""
if num_nan_cols > 0: # DF has nans
has_nan_str = f"( NAN values in {num_nan_cols} col(s) )"
print(
f"{label:{lpad}s}: {shape[0]:{rpad}d} / {shape[1]:{4}d} {key_str} {has_nan_str}"
)
return
except (TypeError, AttributeError, IndexError):
pass
try:
shape = obj.data.shape
if label is None:
label = "Shape"
else:
label = f"Shape {label}"
key_str = ""
try:
keys = list(obj.data.keys())
if len(keys) <= 5:
key_str = " [ " + ", ".join(keys) + " ] "
except AttributeError:
pass
num_nan_cols = ((~obj.data.notnull()).sum() > 0).sum()
has_nan_str = ""
if num_nan_cols > 0: # DF has nans
has_nan_str = f"( NAN values in {num_nan_cols} col(s) )"
print(
f"{label:{lpad}s}: {shape[0]:{rpad}d} / {shape[1]:{4}d} {key_str} {has_nan_str}"
)
return
except (TypeError, AttributeError, IndexError):
pass
try:
length = len(obj)
if label is None:
label = "Length"
else:
label = f"len({label})"
print(f"{label:{lpad}s}: {length:{rpad}d}")
return
except (TypeError, AttributeError):
pass
if label is None:
label = "Object"
print(f"{label:{lpad}s}: {obj}")
def get_pca_feature_contrib(pca_model: PCA, features: list) -> DataFrame:
"""Get the feature contribution to each Principal Component.
Parameters:
===========
model: The PCA object
descriptors_list: The list of feature names that were used for the PCA.
Returns:
========
A DataFrame with the feature contribution.
"""
# associate features and pc feature contribution
ds = []
for pc in pca_model.components_:
ds.append(
{k: np.abs(v) for k, v in zip(features, pc)}
) # absolute value of contributions because only the magnitude of the contribution is of interest
df_feature_contrib = (
pd.DataFrame(ds, index=[f"PC{i+1}_feature_contrib" for i in range(3)])
.T.reset_index()
.rename({"index": "Feature"}, axis=1)
)
# compute PC ranks
for c in df_feature_contrib.columns:
if not c.endswith("_feature_contrib"):
continue
df_feature_contrib = df_feature_contrib.sort_values(
c, ascending=False
).reset_index(drop=True)
df_feature_contrib[f"{c.split('_')[0]}_rank"] = df_feature_contrib.index + 1
# add PC-wise ratios
pattern = "_feature_contrib"
for c in df_feature_contrib:
if c.endswith(pattern):
tot = df_feature_contrib[c].sum()
df_feature_contrib = df_feature_contrib.sort_values(c, ascending=False)
df_feature_contrib[
f"{c.replace(pattern, '')}_feature_contrib_cum_ratio"
] = (df_feature_contrib[c].cumsum() / tot)
return df_feature_contrib.sort_values("Feature").reset_index(drop=True)
def format_pca_feature_contrib(df_feature_contrib: DataFrame) -> DataFrame:
"""
Format a DataFrame with explained variance so that the columns for each PC become
new rows.
Parameters:
===========
df_feature_contrib: The DataFrame with PC feature contributions
Returns:
========
A rearranged DataFrame with the feature contribution, with common column names and each PC as different rows.
"""
pcs = list(
set([c.split("_")[0] for c in df_feature_contrib.columns if c.startswith("PC")])
)
# init empty DataFrame
df = pd.DataFrame(None, columns=["PC", "Feature", "Contribution", "Rank"])
for pc in pcs:
df_tmp = df_feature_contrib[
["Feature", f"{pc}_feature_contrib", f"{pc}_rank"]
].rename(
{f"{pc}_feature_contrib": "Contribution", f"{pc}_rank": "Rank"}, axis=1
)
df_tmp["PC"] = pc
df = pd.concat([df, df_tmp])
return df.reset_index(drop=True).sort_values(["PC", "Feature"])
def get_pca_var(pca_model: PCA) -> DataFrame:
"""
Extract the explained variance from a PCA model as a DataFrame.
Parameters:
===========
pca_model: a PCA model containing the explained variance for each PC.
Returns:
========
A DataFrame with the explained variance for each PC.
"""
feature_contrib = pca_model.explained_variance_ratio_
pcs = [f"PC{i+1}" for i in range(len(feature_contrib))]
# generate the variance data
df_pca_var = pd.DataFrame(
{
"var": feature_contrib,
"PC": pcs,
}
)
df_pca_var["var_perc"] = df_pca_var["var"].map(lambda x: f"{x:.2%}")
df_pca_var["var_cum_ratio"] = df_pca_var["var"].cumsum() # total is 1
df_pca_var["var_cum_perc"] = df_pca_var["var_cum_ratio"].map(lambda x: f"{x:.2%}")
return df_pca_var
def plot_pca_var(df_pca_var: DataFrame) -> plt.Figure:
"""Plot the explained variance of each Principal Component.
Parameters:
===========
df_pca_var: a DataFrame with the PCA explained variance
Returns:
========
A barplot with the explained variance for each Principal Component.
"""
total_var = df_pca_var["var"].sum()
df_pca_var["n"] = df_pca_var["PC"].map(lambda x: int(x[2:]))
# generate the variance plot
# initplot
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(24, 9))
fig.subplots_adjust(hspace=0.1, wspace=0.2)
# fig.suptitle("Variance Explained by Principal Components", fontsize=30)
sns.set_style("whitegrid", {"axes.edgecolor": "0.2"})
sns.set_context("paper", font_scale=2)
x_label = "Number of Principal Components"
y_label = "Cumulated % of Total Variance"
# create a red dotted line at 60%
ax.axhline(0.6, ls="--", color="red", zorder=1)
# create the bar plot
sns.barplot(
ax=ax, x="n", y="var_cum_ratio", data=df_pca_var, color="gray", zorder=2
)
# customize the plot
ax.set_title("Variance Explained by Principal Components", fontsize=30, y=1.02)
ax.tick_params(labelsize=20)
ax.set_xlabel(x_label, fontsize=25, labelpad=20)
ax.set_ylabel(y_label, fontsize=25, labelpad=20)
ylabels = [f"{x:,.0%}" for x in ax.get_yticks()]
ax.set_yticklabels(ylabels)
# add % on the bars
for a, i in zip(ax.patches, range(len(df_pca_var.index))):
row = df_pca_var.iloc[i]
ax.text(
row.name,
a.get_height(),
row["var_cum_perc"],
color="black",
ha="center",
fontdict={"fontsize": 20},
)
plt.tight_layout()
figure = ax.get_figure()
return figure
def plot_pc_proj(
df_pca: DataFrame,
palette,
hue_order=["ChEMBL-NP", "DrugBank", "Enamine", "Pseudo-NPs"],
) -> plt.Figure:
"""Plot the PCA data projected into the PC space.
Parameters:
===========
df_pca: a DataFrame with the PCA data
hue_order: The order in which to plot the datasets
palette: a list of colors to use for the datasets
Returns:
========
A multi scatterplot, with a subplot for each Principal Component Combination.
"""
# sort df by the hue order
df_pca = df_pca.copy()
df_pca["Dataset"] = df_pca["Dataset"].astype("category")
df_pca["Dataset"].cat.set_categories(hue_order, inplace=True)
df_pca = df_pca.sort_values(["Dataset"])
# initiate the multiplot
fig_size = (32, 12)
sns.set(rc={"figure.figsize": fig_size})
fig = plt.figure()
fig.subplots_adjust(hspace=0.1, wspace=0.2)
fig.suptitle("Principal Component Analysis", fontsize=30)
sns.set_style("whitegrid", {"axes.edgecolor": "0.2"})
sns.set_context("paper", font_scale=2)
# iterate over the possible combinations
for i, col_pairs in enumerate([["PC1", "PC2"], ["PC1", "PC3"], ["PC2", "PC3"]]):
plt.subplot(1, 3, i + 1)
x_label = col_pairs[0]
y_label = col_pairs[1]
ax = sns.scatterplot(
x=x_label,
y=y_label,
data=df_pca,
hue="Dataset", # color by cluster
legend=True,
palette=palette,
alpha=0.5,
edgecolor="none",
)
ax.set_title(f"{x_label} and {y_label}", fontsize=24, y=1.02)
# clean up plot
plt.tight_layout()
figure = ax.get_figure()
figure.subplots_adjust(bottom=0.2)
return figure
def plot_pc_proj_with_ref(
df_pca: DataFrame, ref: str, palette: Union[str, List] = PALETTE
) -> plt.Figure:
"""Plot the PCA data projected into the PC space.
A new row is added to the multiplot for each combination reference - subset.
Parameters:
===========
df_pca: a DataFrame with the PCA data
ref: the label of the dataset to use as reference
palette: a list of colors to use for the datasets
Returns:
========
A multi scatterplot, with a subplot for each combination of ref - dataset and each Principal Component Combination.
"""
fig_size = (32, 32)
sns.set(rc={"figure.figsize": fig_size})
fig = plt.figure()
fig.subplots_adjust(hspace=1, wspace=0.2)
fig.suptitle("Principal Component Analysis", fontsize=40, y=1)
sns.set_style("whitegrid", {"axes.edgecolor": "0.2"})
sns.set_context("paper", font_scale=2)
dataset_pairs = itertools.product(
*[[ref], [e for e in df_pca["Dataset"].unique() if e != ref]]
)
counter = 1
for i, dataset_pair in enumerate(dataset_pairs):
for col_pairs in [["PC1", "PC2"], ["PC1", "PC3"], ["PC2", "PC3"]]:
plt.subplot(3, 3, counter)
x_label = col_pairs[0]
y_label = col_pairs[1]
palette_curr = [palette[i + 1], palette[0]]
ax = sns.scatterplot(
x=x_label,
y=y_label,
data=df_pca[df_pca["Dataset"].isin(dataset_pair)].iloc[
::-1
], # reverse order to get the ref above the rest
hue="Dataset", # color by cluster
legend=True,
palette=palette_curr,
alpha=0.5,
edgecolor="none",
)
ax.set_ylim([-10, 15])
ax.set_xlim([-10, 25])
ax.set_title(f"{x_label} and {y_label}", fontsize=30, y=1.02)
counter += 1
plt.tight_layout(pad=4.8)
figure = ax.get_figure()
figure.subplots_adjust(bottom=1.0, top=2.5)
plt.tight_layout()
return figure
def plot_pca_cum_feature_contrib_3pc(df_pca_feature_contrib: DataFrame) -> plt.Figure:
"""Plot the cumulated feature contribution to each Principal Component Combination
individually (up to 3 different PCs).
Parameters:
===========
df_pca_feature_contrib: a DataFrame with the feature contributions
Returns:
========
A multi barchart, with a subplot for each Principal Component Combination.
"""
# set up a multiplot for 3 subplots on a same row
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(24, 12), sharey=True)
# configure plot
fig.suptitle("Cumulated Feature Contribution to Principal Components", fontsize=30)
sns.set_style("whitegrid", {"axes.edgecolor": "0.2"})
sns.set_context("paper", font_scale=2)
fig.subplots_adjust(hspace=0.2, wspace=0.2, top=0.8)