-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmoleculeresolver.py
More file actions
8919 lines (7538 loc) · 369 KB
/
Copy pathmoleculeresolver.py
File metadata and controls
8919 lines (7538 loc) · 369 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
import collections
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing, contextmanager
import copy
from datetime import datetime
from functools import cache
import gzip
import html
import json
import os
from PIL import ImageFont, ImageDraw
import platform
import requests
import shutil
import subprocess
import tempfile
import time
from types import SimpleNamespace
from typing import Any, Generator, Optional, Union
import traceback
import unicodedata
import urllib
import uuid
import warnings
import ssl
import openpyxl
from prompt_toolkit import PromptSession
from prompt_toolkit.shortcuts import yes_no_dialog
import regex
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import Draw
from rdkit.Chem import rdmolops
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem.MolStandardize import rdMolStandardize
from rdkit.Chem.rdchem import ResonanceMolSupplierCallback
from tqdm import tqdm
import urllib3
import xmltodict
from moleculeresolver.rdkitmods import disabling_rdkit_logger
from moleculeresolver.molecule import Molecule
from moleculeresolver.SqliteMoleculeCache import SqliteMoleculeCache
class EmptyResonanceMolSupplierCallback(ResonanceMolSupplierCallback):
"""
A callback class that does nothing when called.
This class is a workaround for the issue described in
https://github.com/rdkit/rdkit/issues/6704.
It inherits from ResonanceMolSupplierCallback but overrides the __call__
method to do nothing, effectively suppressing any callback behavior.
"""
def __call__(self) -> None:
"""
Override the call method to do nothing.
This method is called when an instance of this class is invoked as a function.
It intentionally does nothing as a workaround for the RDKit issue.
Returns:
None
"""
pass
class CustomHttpAdapter(requests.adapters.HTTPAdapter):
"""
A custom HTTP adapter that allows for specifying an SSL context.
This class is a workaround for the SSL error described in
https://stackoverflow.com/questions/71603314/ssl-error-unsafe-legacy-renegotiation-disabled/71646353#71646353
It extends the HTTPAdapter class from the requests library, allowing the use of a custom SSL context
when making HTTP requests.
Attributes:
ssl_context (Optional[ssl.SSLContext]): The SSL context to use for HTTPS connections.
"""
def __init__(self, ssl_context: Optional[ssl.SSLContext] = None, **kwargs) -> None:
"""
Initialize the CustomHttpAdapter.
Args:
ssl_context (Optional[ssl.SSLContext]): The SSL context to use. Defaults to None.
**kwargs: Additional keyword arguments to pass to the parent HTTPAdapter.
Returns:
None
"""
self.ssl_context = ssl_context
super().__init__(**kwargs)
def init_poolmanager(
self, connections: int, maxsize: int, block: bool = False
) -> None:
"""
Initialize the connection pool manager with the custom SSL context.
This method overrides the parent class method to use the custom SSL context
when initializing the pool manager.
Args:
connections (int): The number of connection pools to cache.
maxsize (int): The maximum number of connections to save in the pool.
block (bool): Whether the connection pool should block for connections. Defaults to False.
Returns:
None
"""
self.poolmanager = urllib3.poolmanager.PoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
ssl_context=self.ssl_context,
)
class MoleculeResolver:
def chunker(self, seq: list, size: int) -> set:
"""
Split a sequence into chunks of a specified size.
Args:
seq (list): The sequence to be chunked.
size (int): The size of each chunk.
Returns:
set: A set containing subsequences (chunks) from the input sequence.
Example:
>>> list(self.chunker([1, 2, 3, 4, 5, 6], 2))
[(1, 2), (3, 4), (5, 6)]
"""
return (seq[pos : pos + size] for pos in range(0, len(seq), size))
def take_most_common(
self, container: list, number_to_take: Optional[int] = None
) -> list:
"""
Select the most common elements from a container.
Identifies and returns the most frequently occurring elements in the given container.
Handles both case-sensitive and case-insensitive comparisons for string elements.
Args:
container (list): The input list of elements to process.
number_to_take (Optional[int]): The number of most common elements to return.
If None, returns all elements sorted by frequency. Defaults to None.
Returns:
list: A list of the most common elements, preserving the original case for strings.
Notes:
- If the container has fewer than 2 elements, it returns the container as is.
- For string elements, comparisons are case-insensitive, but the original case is preserved in the output.
- The method maintains the order of elements based on their frequency,
with ties broken by the order of appearance in the original container.
- Whitespace is stripped from string elements before comparison.
"""
if not number_to_take:
number_to_take = len(container)
if len(container) < 2:
return container
original_container = container
is_str = isinstance(container[0], str)
if is_str:
original_container = [item.strip() for item in container]
container = [item.strip().lower() for item in container]
index_container = []
items_seen = []
for item_index, item in enumerate(container):
if item in items_seen:
continue
n = container.count(item)
for i in range(n):
index_container.append(item_index)
items_seen.append(item)
counter = collections.Counter(index_container)
sorted_item_indices_to_take = [
item_index for item_index, _ in counter.most_common(number_to_take)
]
final_container = []
for item_index in sorted_item_indices_to_take:
final_container.append(original_container[item_index])
return final_container
def __init__(
self,
available_service_API_keys: Optional[dict[str, Optional[str]]] = None,
molecule_cache_db_path: Optional[str] = None,
molecule_cache_expiration: Optional[datetime] = None,
standardization_options: Optional[dict] = None,
differentiate_isomers: Optional[bool] = True,
differentiate_tautomers: Optional[bool] = True,
differentiate_isotopes: Optional[bool] = True,
check_for_resonance_structures: Optional[bool] = None,
show_warning_if_non_unique_structure_was_found: Optional[bool] = False,
) -> None:
"""
Initialize a MoleculeResolver instance.
Args:
available_service_API_keys (Optional[dict[str, Optional[str]]]): A dictionary of API keys for various services. Defaults to None.
molecule_cache_db_path (Optional[str]): Path to the molecule cache database. Defaults to using the same cache for all MoleculeResolver instances
on a specific environment.
molecule_cache_expiration (Optional[datetime]): Expiration time for cached molecules. Defaults to None.
standardization_options (Optional[dict]): Options for molecule standardization. Defaults to None.
differentiate_isomers (Optional[bool]): Whether to differentiate between isomers. Defaults to True.
differentiate_tautomers (Optional[bool]): Whether to differentiate between tautomers. Defaults to True.
differentiate_isotopes (Optional[bool]): Whether to differentiate between isotopes. Defaults to True.
check_for_resonance_structures (Optional[bool]): Whether to check for resonance structures. Defaults to None.
show_warning_if_non_unique_structure_was_found (Optional[bool]): Whether to show a warning if a non-unique structure was found. Defaults to False.
Notes:
- Sets up the MoleculeResolver with the provided configuration options.
- Initializes various attributes and sets up the molecule cache if a database path is provided.
"""
if not available_service_API_keys:
available_service_API_keys = {}
if "chemeo" not in available_service_API_keys:
available_service_API_keys["chemeo"] = None
if "comptox" not in available_service_API_keys:
available_service_API_keys["comptox"] = None
self._module_path = os.path.dirname(__file__)
if not molecule_cache_db_path:
molecule_cache_db_path = os.path.join(
self._module_path, "molecule_cache.db"
)
self.molecule_cache_db_path = molecule_cache_db_path
self.molecule_cache_expiration = molecule_cache_expiration
self._OPSIN_executable_path = None
self.available_service_API_keys = available_service_API_keys
default_standardization_options = {
"disconnect_metals": False,
"disconnect_more_metals_for_salts": True,
"normalize": True,
"reionize": True,
"uncharge": False,
"try_assign_sterochemistry": True,
"remove_atom_mapping_number": True,
}
if standardization_options:
missing_entries = set(default_standardization_options) - set(
standardization_options
)
else:
standardization_options = {}
missing_entries = set(default_standardization_options)
for missing_entry in missing_entries:
standardization_options[missing_entry] = default_standardization_options[
missing_entry
]
self._standardization_options = SimpleNamespace(**standardization_options)
self._differentiate_isomers = differentiate_isomers
self._differentiate_tautomers = differentiate_tautomers
self._differentiate_isotopes = differentiate_isotopes
self._check_for_resonance_structures = check_for_resonance_structures
self._show_warning_if_non_unique_structure_was_found = (
show_warning_if_non_unique_structure_was_found
)
self._available_services_with_batch_capabilities = ["srs", "comptox", "pubchem"]
self._message_slugs_shown = []
self._session = None
self._session_CompTox = None
self._java_path = self.get_java_path()
if self._java_path:
self._available_services_with_batch_capabilities.insert(0, "opsin")
self._OPSIN_tempfolder = None
self.supported_modes_by_services = {
"cas_registry": ["name", "smiles", "inchi", "cas"],
"chebi": ["name", "cas", "formula", "smiles", "inchi", "inchikey"],
"chemeo": ["name", "cas", "smiles", "inchi", "inchikey"],
"cir": ["formula", "name", "cas", "smiles", "inchi", "inchikey"],
"comptox": ["name", "cas", "inchikey"],
"cts": [
"cas",
"smiles",
# "name", # I have taken out name because cts works less than 5% of the time
],
"nist": ["formula", "name", "cas", "smiles"],
"opsin": ["name"],
"pubchem": ["name", "cas", "smiles", "formula", "inchi", "inchikey", "cid"],
"srs": ["name", "cas"],
}
self._available_services = sorted(list(self.supported_modes_by_services.keys()))
self.supported_modes = []
self.supported_services_by_mode = {}
for service, service_modes in self.supported_modes_by_services.items():
self.supported_modes.extend(service_modes)
for mode in service_modes:
if mode not in self.supported_services_by_mode:
self.supported_services_by_mode[mode] = []
self.supported_services_by_mode[mode].append(service)
self.supported_services_by_mode = {
k: sorted(self.supported_services_by_mode[k])
for k in sorted(self.supported_services_by_mode)
}
self.supported_modes = sorted(list(set(self.supported_modes)))
self.CAS_regex_with_groups = regex.compile(r"^(\d{2,7})-(\d{2})-(\d)$")
self.CAS_regex = r"(\d{2,7}-\d{2}-\d)"
self.empirical_formula_regex_compiled = regex.compile(
r"([A-IK-Z][a-ik-z]*)([0-9]+(?:[.][0-9]+)?)?"
)
self.formula_bracket_group_regex_compiled = regex.compile(
r"(\((?:[^()]|(?R))*\))(\d+(?:\.\d+)?)"
)
self.non_generic_SMILES_regex_compiled = regex.compile(
r"^[a-ik-zA-IK-Z0-9%=#$@+\-\[\]\(\)\\\/\:\.]*$"
) # non-generic SMILES, no wildcards or unspecified bonds
self.InChI_regex_compiled = regex.compile(
r"^InChI=\dS?\/[0-9a-ik-zA-IK-Z]+\/[0-9a-ik-zA-IK-Z+\-\(\)\\\/,\?]*$"
)
self.InChIKey_regex_compiled = regex.compile(
r"^[A-Z]{14}\-[A-Z]{8}[SN][A-Z]\-[A-Z]$"
)
self.chemeo_API_token_regex_compiled = regex.compile(r"[a-zA-Z0-9_]+")
self.comptox_API_token_regex_compiled = regex.compile(r"[a-z0-9\-]+")
self.html_tag_regex_compiled = regex.compile(r"<.*?>")
self._init_session()
def __enter__(self) -> "MoleculeResolver":
"""
Enter the runtime context for the MoleculeResolver.
This method is called when entering a 'with' statement. It sets up the
necessary resources for the MoleculeResolver to function.
Returns:
MoleculeResolver: The instance of the class (self).
Raises:
Exception: Any exceptions raised during the setup process.
Notes:
- Performs the following actions:
1. Disables the RDKit logger.
2. Initializes the molecule cache.
3. Sets up a temporary folder for OPSIN if it's available.
"""
self._disabling_rdkit_logger = disabling_rdkit_logger()
self._disabling_rdkit_logger.__enter__()
self.molecule_cache = SqliteMoleculeCache(
self.molecule_cache_db_path, self.molecule_cache_expiration
)
self.molecule_cache.__enter__()
if "opsin" in self._available_services_with_batch_capabilities:
self._OPSIN_tempfolder = tempfile.TemporaryDirectory(
prefix="OPSIN_tempfolder_"
)
return self
def __exit__(self, exception_type, exception_value, exception_traceback) -> None:
"""
Exit the runtime context for the MoleculeResolver.
This method is called when exiting a 'with' statement. It cleans up
resources used by the MoleculeResolver.
Args:
exception_type (Type[BaseException] or None): The type of the exception that caused the context to be exited.
exception_value (BaseException or None): The instance of the exception that caused the context to be exited.
exception_traceback (TracebackType or None): A traceback object encoding the stack trace.
Returns:
None
Notes:
- Performs the following cleanup actions:
1. Determines if an error occurred during execution.
2. Exits the RDKit logger disabling context.
3. Exits the molecule cache context.
4. Cleans up the OPSIN temporary folder if no error occurred.
"""
error_ocurred = (
exception_type is not None
or exception_value is not None
or exception_traceback is not None
)
self._disabling_rdkit_logger.__exit__(None, None, None)
self.molecule_cache.__exit__(None, None, None)
self._disabling_rdkit_logger.__exit__(None, None, None)
if self._OPSIN_tempfolder and not error_ocurred:
self._OPSIN_tempfolder.cleanup()
@contextmanager
def query_molecule_cache(
self, service: str, identifier_mode: str, identifier: str
) -> Generator[tuple[bool, list[Molecule]], None, None]:
"""
Query the molecule cache for a given identifier and yield the results.
Searches the molecule cache for a specific identifier using the provided service and identifier mode.
Yields whether an entry is available and the list of molecules found. After the context is exited,
it handles saving new molecules to the cache if necessary.
Args:
service (str): The service used for querying (e.g., "cts", "cir").
identifier_mode (str): The mode of identification used.
identifier (str): The specific identifier to search for.
Returns:
tuple[bool, list[Molecule]]: A tuple containing:
- bool: True if an entry is available in the cache, False otherwise.
- list[Molecule]: The list of molecules found in the cache (empty if not found).
Raises:
Exception: Any exceptions raised by the underlying cache operations.
Notes:
- Uses a context manager to ensure proper handling of cache operations.
- Handles special cases for CTS and CIR services when they are down.
- New molecules are saved to the cache after the context is exited, unless
specific conditions prevent saving (e.g., service is down).
"""
molecules = self.molecule_cache.search(service, identifier_mode, identifier)
entry_available = molecules is not None
if entry_available:
yield entry_available, molecules
else:
molecules = []
yield entry_available, molecules
for molecule in molecules:
molecule.identifier = identifier
should_save = True
if service == "cts" and "CTS_is_down" in self._message_slugs_shown:
should_save = False
elif service == "cir" and "CIR_is_down" in self._message_slugs_shown:
should_save = False
if should_save:
self.molecule_cache.save(
service,
identifier_mode,
identifier,
molecules if molecules else None,
)
return
@contextmanager
def query_molecule_cache_batchmode(
self,
service: str,
identifier_mode: str,
identifiers: list[str],
save_not_found: Optional[bool] = True,
) -> Generator[
tuple[list[str], list[int], Optional[list[Optional[list[Molecule]]]]],
None,
None,
]:
"""
Query the molecule cache for multiple identifiers in batch mode.
Searches the cache for molecules matching the given service, identifier mode, and list of identifiers.
Yields information about identifiers to search, their indices, and the results. After the context is exited,
it saves new molecules to the cache.
Args:
service (str): The service used for querying (e.g., "cts", "cir").
identifier_mode (str): The mode of identification used.
identifiers (list[str]): The list of identifiers to search for.
save_not_found (Optional[bool]): Whether to save entries for identifiers not found. Defaults to True.
Returns:
tuple[list[str], list[int], Optional[list[Optional[list[Molecule]]]]]: A tuple containing:
- list[str]: Identifiers that need to be searched (not found in cache).
- list[int]: Indices of the identifiers to be searched.
- Optional[list[Optional[list[Molecule]]]]: Results from the cache search.
"""
results = self.molecule_cache.search(
[service] * len(identifiers),
[identifier_mode] * len(identifiers),
identifiers,
)
identifiers_to_search = []
indices_of_identifiers_to_search = []
for (molecule_index, molecule), identifier in zip(
enumerate(results), identifiers, strict=True
):
if molecule is None:
identifiers_to_search.append(identifier)
indices_of_identifiers_to_search.append(molecule_index)
yield identifiers_to_search, indices_of_identifiers_to_search, results
identifiers_to_save = []
molecules_to_save = []
for molecule_index, identifier in zip(
indices_of_identifiers_to_search, identifiers_to_search, strict=True
):
molecules = results[molecule_index]
if molecules:
for molecule in molecules:
identifiers_to_save.append(identifier)
molecules_to_save.append(molecule)
else:
if save_not_found:
identifiers_to_save.append(identifier)
molecules_to_save.append(None)
self.molecule_cache.save(
[service] * len(identifiers_to_save),
[identifier_mode] * len(identifiers_to_save),
identifiers_to_save,
molecules_to_save,
)
return
def _init_session(
self, pool_connections: Optional[int] = None, pool_maxsize: Optional[int] = None
) -> None:
"""
Initialize HTTP sessions for making requests.
Sets up two sessions: a general session and a specific session for CompTox.
Configures connection pooling and SSL contexts for these sessions.
Args:
pool_connections (Optional[int]): The number of connection pools to cache.
If None, it's set to twice the number of available services.
pool_maxsize (Optional[int]): The maximum number of connections to save in the pool.
If None, it's set to 10. The minimum value is always 10.
Notes:
- This method is idempotent; it will not reinitialize existing sessions.
- The CompTox session uses a custom SSL context to handle specific SSL requirements.
"""
if self._session is not None:
return
if pool_connections is None:
# reserve two connections for each service in case of different hosts are used.
pool_connections = len(self._available_services) * 2
if pool_maxsize is None:
# default from documentation
pool_maxsize = 10
else:
pool_maxsize = max(pool_maxsize, 10)
self._session = requests.Session()
self._session.mount(
"https://",
requests.adapters.HTTPAdapter(
pool_connections=pool_connections,
pool_maxsize=pool_maxsize,
max_retries=2,
),
)
self._session_CompTox = requests.Session()
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ctx.options |= 0x4
self._session_CompTox.mount(
"https://",
CustomHttpAdapter(
ctx,
pool_connections=pool_connections,
pool_maxsize=pool_maxsize,
max_retries=2,
),
)
def _resilient_request(
self,
url: str,
kwargs: Optional[dict[str, Any]] = None,
request_type: Optional[str] = "get",
accepted_status_codes: list[int] = [200],
rejected_status_codes: list[int] = [404],
offline_status_codes: list[int] = [],
max_retries: Optional[int] = 10,
sleep_time: Union[int, float] = 2,
allow_redirects: Optional[bool] = False,
json: Optional[str] = None,
return_response: Optional[bool] = False,
) -> Optional[str]:
"""
Make a resilient HTTP request with retry logic.
Attempts to make an HTTP request, handling various error conditions and retrying the request if necessary.
Args:
url (str): The URL to send the request to.
kwargs (Optional[dict[str, Any]]): Additional keyword arguments for the request.
request_type (Optional[str]): The type of HTTP request ('get' or 'post'). Defaults to 'get'.
accepted_status_codes (list[int]): List of HTTP status codes to accept. Defaults to [200].
rejected_status_codes (list[int]): List of HTTP status codes to reject. Defaults to [404].
max_retries (Optional[int]): Maximum number of retry attempts. Defaults to 10.
sleep_time (Union[int, float]): Time to sleep between retries in seconds. Defaults to 2.
allow_redirects (Optional[bool]): Whether to allow URL redirection. Defaults to False.
json (Optional[str]): JSON data to send in the request body. Defaults to None.
return_response (Optional[bool]): If True, return the full response object instead of the text. Defaults to False.
Returns:
Optional[str]: The response text if successful, or None if the request failed.
Raises:
ValueError: If an invalid request_type is provided.
requests.exceptions.ConnectionError: If connection errors persist after maximum retries.
Notes:
- Automatically sets a user agent if not provided in the headers.
- Uses different sessions for CompTox and other services.
- Implements exponential backoff for retries.
"""
if not kwargs:
kwargs = {}
if request_type not in ["get", "post"]:
raise ValueError("The request_type must be either 'get' or 'post'.")
if "timeout" not in kwargs:
kwargs["timeout"] = 5
headers = {}
user_agent_is_set = False
if "headers" in kwargs:
headers = kwargs["headers"]
user_agent_is_set = "user-agent" in [key.lower() for key in headers.keys()]
if user_agent_is_set is False:
headers["user-agent"] = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0"
)
kwargs["headers"] = headers
session = (
self._session if "comptox" not in url.lower() else self._session_CompTox
)
n_try = 0
while True:
n_try += 1
try:
response = None
if request_type == "get":
response = session.get(
url, **kwargs, json=json, allow_redirects=allow_redirects
)
if request_type == "post":
response = session.post(
url, **kwargs, json=json, allow_redirects=allow_redirects
)
if response.status_code in accepted_status_codes:
if return_response:
return response
response_text = response.content.decode("utf8", errors="ignore")
response_text = response_text.replace("\u200b", "")
# find encoding errors
if response_text != response.text:
if response_text.count(r"\u") + response_text.count(r"\x") > 0:
raise UnicodeEncodeError(
"Wrong character encoding was used."
)
return response_text
elif response.status_code in rejected_status_codes:
return None
else:
raise requests.exceptions.HTTPError("Wrong status_code.")
except requests.exceptions.RequestException as error:
time.sleep(sleep_time)
if n_try > max_retries:
if isinstance(error, requests.exceptions.ConnectionError):
raise error
if response.status_code in offline_status_codes:
raise requests.exceptions.ConnectionError(
"The service is probably offline."
)
if response is not None:
print(
f"ERROR ocurred during request to:\n{url}\n{kwargs}\n HTTP request status code: {response.status_code}\n"
)
else:
print(
f"ERROR ocurred during request to:\n{url}\n{kwargs}\n",
traceback.format_exc(),
)
return None
@cache
def try_disconnect_more_metals(self, SMILES: str) -> str:
"""
Attempt to disconnect additional metal atoms in a molecule represented by a SMILES string.
This method performs a more extensive metal disconnection process than the standard
RDKit metal disconnector. It includes more metals and handles specific cases like
mercury (Hg) correctly: https://github.com/rdkit/rdkit/discussions/6729
if the issue for Hg is a bug, this should be replaced by the metal disconnector from rdkit
Args:
SMILES (str): The input SMILES string representing the molecule.
Returns:
str: The SMILES string of the molecule after attempting to disconnect metals.
If no changes are made, the original SMILES string is returned.
Notes:
- Uses caching to improve performance for repeated calls with the same input.
- Employs a custom SMARTS pattern to identify metal-nonmetal bonds.
- If the input SMILES is invalid or no metal disconnection is possible, the original SMILES is returned.
- Particularly useful for handling cases where the standard RDKit metal disconnector may not be sufficient
or may have known issues (e.g., with mercury compounds).
"""
metals = "[#3,#11,#19,#37,#55,#87,#4,#12,#20,#38,#56,#88,#21,#22,#23,#24,#25,#26,#27,#28,#29,#30,#13,#31,#39,#40,#41,#42,#43,#44,#45,#46,#47,#48,#49,#50,#72,#73,#74,#75,#76,#77,#78,#79,#80,#81,#82,#83]"
SMARTS = f"{metals}~[B,C,#14,P,#33,#51,S,#34,#52,F,Cl,Br,I,#85]"
mol = Chem.MolFromSmiles(SMILES)
if not mol:
return SMILES
patt = Chem.MolFromSmarts(SMARTS)
hit_ats = list(mol.GetSubstructMatches(patt))
if not hit_ats:
return SMILES
property_name = "molecule_resolver_charge"
cation_charges = {}
bonds_to_be_broken = []
for cation_id, anion_id in hit_ats:
cation = mol.GetAtomWithIdx(cation_id)
if cation_id not in cation_charges:
cation_charge = cation.GetTotalDegree()
cation_charges[cation_id] = cation_charge
cation.SetIntProp(property_name, cation_charge)
else:
cation_charge = cation_charges[cation_id]
bond_to_be_broken = mol.GetBondBetweenAtoms(cation_id, anion_id)
bonds_to_be_broken.append(bond_to_be_broken.GetIdx())
anion_charge = -1 * int(bond_to_be_broken.GetBondType())
anion = mol.GetAtomWithIdx(anion_id)
anion.SetIntProp(property_name, anion_charge)
cation_charges[cation_id] += anion_charge
if not all(v == 0 for v in cation_charges.values()):
return SMILES # charge missmatch
fragment_mols = rdmolops.GetMolFrags(
rdmolops.FragmentOnBonds(mol, bonds_to_be_broken), asMols=True
)
ion_mols = []
for m in fragment_mols:
rwmol = Chem.RWMol(m)
ai_dummy_atoms = []
for a in rwmol.GetAtoms():
if a.HasProp(property_name):
a.SetFormalCharge(a.GetIntProp(property_name))
if a.GetSymbol() == "*":
ai_dummy_atoms.append(a.GetIdx())
for ai in sorted(ai_dummy_atoms, reverse=True):
rwmol.RemoveAtom(ai)
ion_mols.append(rwmol.GetMol())
return self.standardize_SMILES(
".".join([Chem.MolToSmiles(m) for m in ion_mols])
)
@cache
def standardize_SMILES(
self,
SMILES: str,
/,
disconnect_metals: Optional[bool] = None,
normalize: Optional[bool] = None,
reionize: Optional[bool] = None,
uncharge: Optional[bool] = None,
try_assign_sterochemistry: Optional[bool] = None,
remove_atom_mapping_number: Optional[bool] = None,
) -> Optional[str]:
"""
Standardize a SMILES string representation of a molecule.
Applies various standardization procedures to a given SMILES string, including metal disconnection,
normalization, reionization, uncharging, stereochemistry assignment, and atom mapping number removal.
Args:
SMILES (str): The input SMILES string to be standardized.
disconnect_metals (Optional[bool]): Whether to disconnect metals. Defaults to None.
normalize (Optional[bool]): Whether to normalize the molecule. Defaults to None.
reionize (Optional[bool]): Whether to reionize the molecule. Defaults to None.
uncharge (Optional[bool]): Whether to uncharge the molecule. Defaults to None.
try_assign_sterochemistry (Optional[bool]): Whether to attempt stereochemistry assignment. Defaults to None.
remove_atom_mapping_number (Optional[bool]): Whether to remove atom mapping numbers. Defaults to None.
Returns:
Optional[str]: The standardized SMILES string, or None if standardization fails.
Notes:
- Uses caching to improve performance for repeated calls with the same input.
- The standardization process uses the RDKit library for molecular operations.
"""
mol = self.get_from_SMILES(SMILES)
if mol is None:
return None
return Chem.MolToSmiles(
self.standardize_mol(
mol,
disconnect_metals,
normalize,
reionize,
uncharge,
try_assign_sterochemistry,
remove_atom_mapping_number,
)
)
def standardize_mol(
self,
mol: Chem.rdchem.Mol,
/,
disconnect_metals: Optional[bool] = None,
normalize: Optional[bool] = None,
reionize: Optional[bool] = None,
uncharge: Optional[bool] = None,
try_assign_sterochemistry: Optional[bool] = None,
remove_atom_mapping_number: Optional[bool] = None,
) -> Optional[Chem.rdchem.Mol]:
"""
Standardize an RDKit molecule object.
Applies various standardization procedures to a given RDKit molecule, including metal disconnection,
normalization, reionization, uncharging, stereochemistry assignment, and atom mapping number removal.
Args:
mol (Chem.rdchem.Mol): The input RDKit molecule to be standardized.
disconnect_metals (Optional[bool]): Whether to disconnect metals. Defaults to None.
normalize (Optional[bool]): Whether to normalize the molecule. Defaults to None.
reionize (Optional[bool]): Whether to reionize the molecule. Defaults to None.
uncharge (Optional[bool]): Whether to uncharge the molecule. Defaults to None.
try_assign_sterochemistry (Optional[bool]): Whether to attempt stereochemistry assignment. Defaults to None.
remove_atom_mapping_number (Optional[bool]): Whether to remove atom mapping numbers. Defaults to None.
Returns:
Optional[Chem.rdchem.Mol]: The standardized RDKit molecule, or None if standardization fails.
Raises:
Warning: If reionization step cannot be performed.
Notes:
- If any standardization option is None, it defaults to the values set on class creation or default values.
- For molecules with multiple fragments, each fragment is standardized separately.
- Special handling is implemented for certain molecules (e.g., DMSO) during normalization.
- Uses RDKit's standardization tools (e.g., MetalDisconnector, Normalize, Reionizer).
"""
if mol is None:
return None
if disconnect_metals is None:
disconnect_metals = self._standardization_options.disconnect_metals
if normalize is None:
normalize = self._standardization_options.normalize
if reionize is None:
reionize = self._standardization_options.reionize
if uncharge is None:
uncharge = self._standardization_options.uncharge
if try_assign_sterochemistry is None:
try_assign_sterochemistry = (
self._standardization_options.try_assign_sterochemistry
)
if remove_atom_mapping_number is None:
remove_atom_mapping_number = (
self._standardization_options.remove_atom_mapping_number
)
mol_fragments = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
if len(mol_fragments) > 1:
all_mol_fragments = []
for mol_fragment in mol_fragments:
standardized_mol_fragment = self.standardize_mol(
mol_fragment,
disconnect_metals,
normalize,
reionize,
uncharge,
try_assign_sterochemistry,
remove_atom_mapping_number,
)
if standardized_mol_fragment is None:
return None
all_mol_fragments.append(standardized_mol_fragment)
standardize_mol = all_mol_fragments[0]
for mol_fragment in all_mol_fragments[1:]:
standardize_mol = Chem.CombineMols(standardize_mol, mol_fragment)
return standardize_mol
# based on MolVS https://github.com/mcs07/MolVS
mol = copy.deepcopy(mol)
if disconnect_metals:
md = rdMolStandardize.MetalDisconnector()
mol = md.Disconnect(mol)
if normalize:
# for some molecules this gives weird results. e.g. DMSO
if Chem.MolToSmiles(mol) not in ["CS(C)=O"]:
mol = rdMolStandardize.Normalize(mol)
if reionize:
reionizer = rdMolStandardize.Reionizer()
try:
mol = reionizer.reionize(mol)
except:
warnings.warn(
"Reionization step could not be performed. It will be skipped."
)