-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathpubchempy.py
More file actions
2147 lines (1810 loc) · 74.9 KB
/
pubchempy.py
File metadata and controls
2147 lines (1810 loc) · 74.9 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
"""PubChemPy: Python Interface for the PubChem Database."""
from __future__ import annotations
import enum
import functools
import json
import logging
import os
import ssl
import time
import typing as t
import warnings
from http.client import HTTPResponse
from itertools import zip_longest
from urllib.error import HTTPError
from urllib.parse import quote, urlencode
from urllib.request import urlopen
if t.TYPE_CHECKING:
import pandas as pd
# Get SSL certs from env var or certifi package if available.
_CA_FILE = os.getenv("PUBCHEMPY_CA_BUNDLE") or os.getenv("REQUESTS_CA_BUNDLE")
if not _CA_FILE:
try:
import certifi
_CA_FILE = certifi.where()
except ImportError:
_CA_FILE = None
__author__ = "Matt Swain"
__email__ = "m.swain@me.com"
__version__ = "1.0.5"
__license__ = "MIT"
__all__ = [
# Main API functions
"get_compounds",
"get_substances",
"get_assays",
"get_properties",
"get_synonyms",
"get_cids",
"get_sids",
"get_aids",
"get_all_sources",
"download",
"request",
"get",
"get_json",
"get_sdf",
# Core classes
"Compound",
"Substance",
"Assay",
"Atom",
"Bond",
# Enum/constant classes
"CompoundIdType",
"BondType",
"CoordinateType",
"ProjectCategory",
# Data conversion functions
"compounds_to_frame",
"substances_to_frame",
# Constants
"API_BASE",
"ELEMENTS",
"PROPERTY_MAP",
# Exceptions
"PubChemPyError",
"ResponseParseError",
"PubChemHTTPError",
"BadRequestError",
"NotFoundError",
"MethodNotAllowedError",
"ServerError",
"UnimplementedError",
"ServerBusyError",
"TimeoutError",
"PubChemPyDeprecationWarning",
]
#: Base URL for the PubChem PUG REST API.
API_BASE = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
log = logging.getLogger("pubchempy")
log.addHandler(logging.NullHandler())
#: Type alias for URL query parameters.
QueryParam = str | int | float | bool | list[str] | None
class CompoundIdType(enum.IntEnum):
"""Compound record type."""
#: Original Deposited Compound
DEPOSITED = 0
#: Standardized Form of a Deposited Compound
STANDARDIZED = 1
#: Component of a Standardized Compound
COMPONENT = 2
#: Neutralized Form of a Standardized Compound
NEUTRALIZED = 3
#: Substance that is a component of a mixture
MIXTURE = 4
#: Predicted Tautomer Form
TAUTOMER = 5
#: Predicted Ionized pKa Form
IONIZED = 6
#: Unknown Compound Type
UNKNOWN = 255
class BondType(enum.IntEnum):
"""Bond Type Information."""
#: Single Bond
SINGLE = 1
#: Double Bond
DOUBLE = 2
#: Triple Bond
TRIPLE = 3
#: Quadruple Bond
QUADRUPLE = 4
#: Dative Bond
DATIVE = 5
#: Complex Bond
COMPLEX = 6
#: Ionic Bond
IONIC = 7
#: Unknown/Unspecified Connectivity
UNKNOWN = 255
class CoordinateType(enum.IntEnum):
"""Coordinate Set Type Distinctions."""
#: 2D Coordinates
TWO_D = 1
#: 3D Coordinates (should also indicate units, below)
THREE_D = 2
#: Depositor Provided Coordinates
SUBMITTED = 3
#: Experimentally Determined Coordinates
EXPERIMENTAL = 4
#: Computed Coordinates
COMPUTED = 5
#: Standardized Coordinates
STANDARDIZED = 6
#: Hybrid Original with Computed Coordinates (e.g., explicit H)
AUGMENTED = 7
#: Template used to align drawing
ALIGNED = 8
#: Drawing uses shorthand forms (e.g., COOH, OCH3, Et, etc.)
COMPACT = 9
#: (3D) Coordinate units are Angstroms
UNITS_ANGSTROMS = 10
#: (3D) Coordinate units are nanometers
UNITS_NANOMETERS = 11
#: (2D) Coordinate units are pixels
UNITS_PIXEL = 12
#: (2D) Coordinate units are points
UNITS_POINTS = 13
#: (2D) Coordinate units are standard bond lengths (1.0)
UNITS_STDBONDS = 14
#: Coordinate units are unknown or unspecified
UNITS_UNKNOWN = 255
class ProjectCategory(enum.IntEnum):
"""To distinguish projects funded through MLSCN, MLPCN or other."""
#: Assay depositions from MLSCN screen center
MLSCN = 1
#: Assay depositions from MLPCN screen center
MLPCN = 2
#: Assay depositions from MLSCN assay provider
MLSCN_AP = 3
#: Assay depositions from MLPCN assay provider
MLPCN_AP = 4
#: To be deprecated and replaced by options 7, 8 & 9
JOURNAL_ARTICLE = 5
#: Assay depositions from assay vendors
ASSAY_VENDOR = 6
#: Data from literature, extracted by curators
LITERATURE_EXTRACTED = 7
#: Data from literature, submitted by author of articles
LITERATURE_AUTHOR = 8
#: Data from literature, submitted by journals/publishers
LITERATURE_PUBLISHER = 9
#: RNAi screenings from RNAi Global Initiative
RNAIGI = 10
#: Other project category
OTHER = 255
#: Dictionary mapping atomic numbers to their element symbols.
#:
#: This dictionary includes 118 standard chemical elements from Hydrogen (1) to
#: Oganesson (118), plus special atom types used by PubChem for non-standard entities
#: like dummy atoms, R-group labels, and lone pairs.
ELEMENTS: dict[int, str] = {
# Standard chemical elements
1: "H", # Hydrogen
2: "He", # Helium
3: "Li", # Lithium
4: "Be", # Beryllium
5: "B", # Boron
6: "C", # Carbon
7: "N", # Nitrogen
8: "O", # Oxygen
9: "F", # Fluorine
10: "Ne", # Neon
11: "Na", # Sodium
12: "Mg", # Magnesium
13: "Al", # Aluminium
14: "Si", # Silicon
15: "P", # Phosphorus
16: "S", # Sulfur
17: "Cl", # Chlorine
18: "Ar", # Argon
19: "K", # Potassium
20: "Ca", # Calcium
21: "Sc", # Scandium
22: "Ti", # Titanium
23: "V", # Vanadium
24: "Cr", # Chromium
25: "Mn", # Manganese
26: "Fe", # Iron
27: "Co", # Cobalt
28: "Ni", # Nickel
29: "Cu", # Copper
30: "Zn", # Zinc
31: "Ga", # Gallium
32: "Ge", # Germanium
33: "As", # Arsenic
34: "Se", # Selenium
35: "Br", # Bromine
36: "Kr", # Krypton
37: "Rb", # Rubidium
38: "Sr", # Strontium
39: "Y", # Yttrium
40: "Zr", # Zirconium
41: "Nb", # Niobium
42: "Mo", # Molybdenum
43: "Tc", # Technetium
44: "Ru", # Ruthenium
45: "Rh", # Rhodium
46: "Pd", # Palladium
47: "Ag", # Silver
48: "Cd", # Cadmium
49: "In", # Indium
50: "Sn", # Tin
51: "Sb", # Antimony
52: "Te", # Tellurium
53: "I", # Iodine
54: "Xe", # Xenon
55: "Cs", # Cesium
56: "Ba", # Barium
57: "La", # Lanthanum
58: "Ce", # Cerium
59: "Pr", # Praseodymium
60: "Nd", # Neodymium
61: "Pm", # Promethium
62: "Sm", # Samarium
63: "Eu", # Europium
64: "Gd", # Gadolinium
65: "Tb", # Terbium
66: "Dy", # Dysprosium
67: "Ho", # Holmium
68: "Er", # Erbium
69: "Tm", # Thulium
70: "Yb", # Ytterbium
71: "Lu", # Lutetium
72: "Hf", # Hafnium
73: "Ta", # Tantalum
74: "W", # Tungsten
75: "Re", # Rhenium
76: "Os", # Osmium
77: "Ir", # Iridium
78: "Pt", # Platinum
79: "Au", # Gold
80: "Hg", # Mercury
81: "Tl", # Thallium
82: "Pb", # Lead
83: "Bi", # Bismuth
84: "Po", # Polonium
85: "At", # Astatine
86: "Rn", # Radon
87: "Fr", # Francium
88: "Ra", # Radium
89: "Ac", # Actinium
90: "Th", # Thorium
91: "Pa", # Protactinium
92: "U", # Uranium
93: "Np", # Neptunium
94: "Pu", # Plutonium
95: "Am", # Americium
96: "Cm", # Curium
97: "Bk", # Berkelium
98: "Cf", # Californium
99: "Es", # Einsteinium
100: "Fm", # Fermium
101: "Md", # Mendelevium
102: "No", # Nobelium
103: "Lr", # Lawrencium
104: "Rf", # Rutherfordium
105: "Db", # Dubnium
106: "Sg", # Seaborgium
107: "Bh", # Bohrium
108: "Hs", # Hassium
109: "Mt", # Meitnerium
110: "Ds", # Darmstadtium
111: "Rg", # Roentgenium
112: "Cn", # Copernicium
113: "Nh", # Nihonium
114: "Fl", # Flerovium
115: "Mc", # Moscovium
116: "Lv", # Livermorium
117: "Ts", # Tennessine
118: "Og", # Oganesson
# Special atom types
252: "Lp", # Lone Pair
253: "R", # Rgroup Label
254: "*", # Dummy Atom
255: "*", # Unspecified Atom (Asterisk)
}
def request(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
operation: str | None = None,
output: str = "JSON",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> HTTPResponse:
"""Construct API request from parameters and return the response.
Full specification at https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest
"""
if not identifier:
raise ValueError("identifier/cid cannot be None")
# If identifier is a list, join with commas into string
if isinstance(identifier, int):
identifier = str(identifier)
if not isinstance(identifier, str):
identifier = ",".join(str(x) for x in identifier)
# Filter None values from kwargs
kwargs = {k: v for k, v in kwargs.items() if v is not None}
# Build API URL
urlid, postdata = None, None
if namespace == "sourceid":
identifier = identifier.replace("/", ".")
if (
namespace in ["listkey", "formula", "sourceid"]
or searchtype == "xref"
or (searchtype and namespace == "cid")
or domain == "sources"
):
urlid = quote(identifier.encode("utf8"))
else:
postdata = urlencode([(namespace, identifier)]).encode("utf8")
comps = filter(
None, [API_BASE, domain, searchtype, namespace, urlid, operation, output]
)
apiurl = "/".join(comps)
if kwargs:
apiurl += f"?{urlencode(kwargs)}"
# Make request
try:
log.debug(f"Request URL: {apiurl}")
log.debug(f"Request data: {postdata}")
context = ssl.create_default_context(cafile=_CA_FILE)
response = urlopen(apiurl, postdata, context=context)
return response
except HTTPError as e:
raise create_http_error(e) from e
def get(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
operation: str | None = None,
output: str = "JSON",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> bytes:
"""Request wrapper that automatically handles async requests."""
if (searchtype and searchtype != "xref") or namespace in ["formula"]:
response = request(
identifier, namespace, domain, None, "JSON", searchtype, **kwargs
).read()
status = json.loads(response.decode())
if "Waiting" in status and "ListKey" in status["Waiting"]:
identifier = status["Waiting"]["ListKey"]
namespace = "listkey"
while "Waiting" in status and "ListKey" in status["Waiting"]:
time.sleep(2)
response = request(
identifier, namespace, domain, operation, "JSON", **kwargs
).read()
status = json.loads(response.decode())
if not output == "JSON":
response = request(
identifier,
namespace,
domain,
operation,
output,
searchtype,
**kwargs,
).read()
else:
response = request(
identifier, namespace, domain, operation, output, searchtype, **kwargs
).read()
return response
def get_json(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
operation: str | None = None,
searchtype: str | None = None,
**kwargs: QueryParam,
) -> dict[str, t.Any] | None:
"""Request wrapper that automatically parses JSON response into a python dict.
This function suppresses NotFoundError and returns None if no results are found.
"""
try:
return json.loads(
get(
identifier, namespace, domain, operation, "JSON", searchtype, **kwargs
).decode()
)
except NotFoundError as e:
log.info(e)
return None
def get_sdf(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
operation: str | None = None,
searchtype: str | None = None,
**kwargs: QueryParam,
) -> str | None:
"""Request wrapper that automatically extracts SDF from the response.
This function suppresses NotFoundError and returns None if no results are found.
"""
try:
return get(
identifier, namespace, domain, operation, "SDF", searchtype, **kwargs
).decode()
except NotFoundError as e:
log.info(e)
return None
def get_compounds(
identifier: str | int | list[str | int],
namespace: str = "cid",
searchtype: str | None = None,
as_dataframe: bool = False,
**kwargs: QueryParam,
) -> list[Compound] | pd.DataFrame:
"""Retrieve the specified compound records from PubChem.
Args:
identifier: The compound identifier to use as a search query.
namespace: The identifier type, one of cid, name, smiles, sdf, inchi,
inchikey or formula.
searchtype: The advanced search type, one of substructure,
superstructure or similarity.
as_dataframe: Automatically extract the Compound properties into a pandas
DataFrame and return that.
**kwargs: Additional query parameters to pass to the API request.
Returns:
List of :class:`~pubchempy.Compound` objects, or a pandas DataFrame if
``as_dataframe=True``.
"""
results = get_json(identifier, namespace, searchtype=searchtype, **kwargs)
compounds = [Compound(r) for r in results["PC_Compounds"]] if results else []
if as_dataframe:
return compounds_to_frame(compounds)
return compounds
def get_substances(
identifier: str | int | list[str | int],
namespace: str = "sid",
as_dataframe: bool = False,
**kwargs: QueryParam,
) -> list[Substance] | pd.DataFrame:
"""Retrieve the specified substance records from PubChem.
Args:
identifier: The substance identifier to use as a search query.
namespace: The identifier type, one of sid, name or sourceid/<source name>.
as_dataframe: Automatically extract the Substance properties into a pandas
DataFrame and return that.
**kwargs: Additional query parameters to pass to the API request.
Returns:
List of :class:`~pubchempy.Substance` objects, or a pandas DataFrame if
``as_dataframe=True``.
"""
results = get_json(identifier, namespace, "substance", **kwargs)
substances = [Substance(r) for r in results["PC_Substances"]] if results else []
if as_dataframe:
return substances_to_frame(substances)
return substances
def get_assays(
identifier: str | int | list[str | int],
namespace: str = "aid",
**kwargs: QueryParam,
) -> list[Assay]:
"""Retrieve the specified assay records from PubChem.
Args:
identifier: The assay identifier to use as a search query.
namespace: The identifier type.
**kwargs: Additional query parameters to pass to the API request.
Returns:
List of :class:`~pubchempy.Assay` objects.
"""
results = get_json(identifier, namespace, "assay", "description", **kwargs)
return [Assay(r) for r in results["PC_AssayContainer"]] if results else []
#: Dictionary mapping property names to their PubChem API equivalents.
#:
#: Allows properties to optionally be specified as underscore_separated,
#: consistent with Compound attributes.
PROPERTY_MAP: dict[str, str] = {
"molecular_formula": "MolecularFormula",
"molecular_weight": "MolecularWeight",
"smiles": "SMILES",
"connectivity_smiles": "ConnectivitySMILES",
"canonical_smiles": "CanonicalSMILES",
"isomeric_smiles": "IsomericSMILES",
"inchi": "InChI",
"inchikey": "InChIKey",
"iupac_name": "IUPACName",
"xlogp": "XLogP",
"exact_mass": "ExactMass",
"monoisotopic_mass": "MonoisotopicMass",
"tpsa": "TPSA",
"complexity": "Complexity",
"charge": "Charge",
"h_bond_donor_count": "HBondDonorCount",
"h_bond_acceptor_count": "HBondAcceptorCount",
"rotatable_bond_count": "RotatableBondCount",
"heavy_atom_count": "HeavyAtomCount",
"isotope_atom_count": "IsotopeAtomCount",
"atom_stereo_count": "AtomStereoCount",
"defined_atom_stereo_count": "DefinedAtomStereoCount",
"undefined_atom_stereo_count": "UndefinedAtomStereoCount",
"bond_stereo_count": "BondStereoCount",
"defined_bond_stereo_count": "DefinedBondStereoCount",
"undefined_bond_stereo_count": "UndefinedBondStereoCount",
"covalent_unit_count": "CovalentUnitCount",
"volume_3d": "Volume3D",
"conformer_rmsd_3d": "ConformerModelRMSD3D",
"conformer_model_rmsd_3d": "ConformerModelRMSD3D",
"x_steric_quadrupole_3d": "XStericQuadrupole3D",
"y_steric_quadrupole_3d": "YStericQuadrupole3D",
"z_steric_quadrupole_3d": "ZStericQuadrupole3D",
"feature_count_3d": "FeatureCount3D",
"feature_acceptor_count_3d": "FeatureAcceptorCount3D",
"feature_donor_count_3d": "FeatureDonorCount3D",
"feature_anion_count_3d": "FeatureAnionCount3D",
"feature_cation_count_3d": "FeatureCationCount3D",
"feature_ring_count_3d": "FeatureRingCount3D",
"feature_hydrophobe_count_3d": "FeatureHydrophobeCount3D",
"effective_rotor_count_3d": "EffectiveRotorCount3D",
"conformer_count_3d": "ConformerCount3D",
}
def get_properties(
properties: str | list[str],
identifier: str | int | list[str | int],
namespace: str = "cid",
searchtype: str | None = None,
as_dataframe: bool = False,
**kwargs: QueryParam,
) -> list[dict[str, t.Any]] | pd.DataFrame:
"""Retrieve the specified compound properties from PubChem.
Args:
properties: The properties to retrieve.
identifier: The compound identifier to use as a search query.
namespace: The identifier type.
searchtype: The advanced search type, one of substructure, superstructure
or similarity.
as_dataframe: Automatically extract the properties into a pandas DataFrame.
**kwargs: Additional query parameters to pass to the API request.
"""
if isinstance(properties, str):
properties = properties.split(",")
properties = ",".join([PROPERTY_MAP.get(p, p) for p in properties])
properties = f"property/{properties}"
results = get_json(
identifier, namespace, "compound", properties, searchtype=searchtype, **kwargs
)
results = results["PropertyTable"]["Properties"] if results else []
if as_dataframe:
import pandas as pd
return pd.DataFrame.from_records(results, index="CID")
return results
def get_synonyms(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> list[dict[str, t.Any]]:
"""Retrieve synonyms (alternative names) for the specified records from PubChem.
Synonyms include systematic names, common names, trade names, registry numbers,
and other identifiers associated with compounds, substances, or assays.
Args:
identifier: The identifier to use as a search query.
namespace: The identifier type (e.g., cid, name, smiles for compounds).
domain: The PubChem domain to search (compound or substance).
searchtype: The advanced search type, one of substructure, superstructure
or similarity.
**kwargs: Additional parameters to pass to the request.
Returns:
List of dictionaries containing synonym information for each matching record.
Each dictionary contains the record identifier and a list of synonyms.
"""
results = get_json(
identifier, namespace, domain, "synonyms", searchtype=searchtype, **kwargs
)
return results["InformationList"]["Information"] if results else []
def get_cids(
identifier: str | int | list[str | int],
namespace: str = "name",
domain: str = "compound",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> list[int]:
"""Retrieve Compound Identifiers (CIDs) for the specified query from PubChem.
CIDs are unique numerical identifiers assigned to each standardized compound
record in the PubChem Compound database. This function is useful for converting
between different identifier types (names, SMILES, InChI, etc.) and CIDs.
Args:
identifier: The identifier to use as a search query.
namespace: The identifier type (e.g. name, smiles, inchi, formula).
domain: The PubChem domain to search (compound, substance, or assay).
searchtype: The advanced search type, one of substructure, superstructure
or similarity.
**kwargs: Additional parameters to pass to the request.
Returns:
List of CIDs (integers) that match the search criteria. Empty list if no
matches found.
"""
results = get_json(
identifier, namespace, domain, "cids", searchtype=searchtype, **kwargs
)
if not results:
return []
elif "IdentifierList" in results:
return results["IdentifierList"]["CID"]
elif "InformationList" in results:
return results["InformationList"]["Information"]
def get_sids(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> list[int]:
"""Retrieve Substance Identifiers (SIDs) for the specified query from PubChem.
SIDs are unique numerical identifiers assigned to each substance record
in the PubChem Substance database. This function is useful for finding
which substance records are associated with a given compound or other identifier.
Args:
identifier: The identifier to use as a search query.
namespace: The identifier type (e.g., cid, name, smiles for compounds).
domain: The PubChem domain to search (compound, substance, or assay).
searchtype: The advanced search type, one of substructure, superstructure
or similarity.
**kwargs: Additional parameters to pass to the request.
Returns:
List of SIDs (integers) that match the search criteria. Empty list if no
matches found.
"""
results = get_json(
identifier, namespace, domain, "sids", searchtype=searchtype, **kwargs
)
if not results:
return []
elif "IdentifierList" in results:
return results["IdentifierList"]["SID"]
elif "InformationList" in results:
return results["InformationList"]["Information"]
def get_aids(
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
searchtype: str | None = None,
**kwargs: QueryParam,
) -> list[int]:
"""Retrieve Assay Identifiers (AIDs) for the specified query from PubChem.
AIDs are unique numerical identifiers assigned to each biological assay
record in the PubChem BioAssay database. This function is useful for finding
which assays have tested a given compound or substance.
Args:
identifier: The identifier to use as a search query.
namespace: The identifier type (e.g., cid, name, smiles).
domain: The PubChem domain to search (compound, substance, or assay).
searchtype: The advanced search type, one of substructure, superstructure
or similarity.
**kwargs: Additional parameters to pass to the request.
Returns:
List of AIDs (integers) that match the search criteria. Empty list if no
matches found.
"""
results = get_json(
identifier, namespace, domain, "aids", searchtype=searchtype, **kwargs
)
if not results:
return []
elif "IdentifierList" in results:
return results["IdentifierList"]["AID"]
elif "InformationList" in results:
return results["InformationList"]["Information"]
def get_all_sources(domain: str = "substance") -> list[str]:
"""Return a list of all current depositors of substances or assays."""
results = json.loads(get(domain, None, "sources").decode())
return results["InformationList"]["SourceName"]
def download(
outformat: str,
path: str | os.PathLike,
identifier: str | int | list[str | int],
namespace: str = "cid",
domain: str = "compound",
operation: str | None = None,
searchtype: str | None = None,
overwrite: bool = False,
**kwargs: QueryParam,
) -> None:
"""Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT."""
response = get(
identifier, namespace, domain, operation, outformat, searchtype, **kwargs
)
if not overwrite and os.path.isfile(path):
raise OSError(f"{path} already exists. Use 'overwrite=True' to overwrite it.")
with open(path, "wb") as f:
f.write(response)
def memoized_property(fget: t.Callable[[t.Any], t.Any]) -> property:
"""Decorator to create memoized properties.
Used to cache :class:`~pubchempy.Compound` and :class:`~pubchempy.Substance`
properties that require an additional request.
"""
attr_name = f"_{fget.__name__}"
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
return property(fget_memoized)
def deprecated(message: str) -> t.Callable[[t.Callable], t.Callable]:
"""Decorator to mark as deprecated and emit a warning when used."""
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
f"{func.__name__} is deprecated: {message}",
category=PubChemPyDeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapped
return deco
class Atom:
"""Class to represent an atom in a :class:`~pubchempy.Compound`."""
def __init__(
self,
aid: int,
number: int,
x: float | None = None,
y: float | None = None,
z: float | None = None,
charge: int = 0,
) -> None:
"""Initialize with an atom ID, atomic number, coordinates and optional charge.
Args:
aid: Atom ID.
number: Atomic number.
x: X coordinate.
y: Y coordinate.
z: Z coordinate.
charge: Formal charge on atom.
"""
self.aid = aid
"""The atom ID within the owning Compound."""
self.number = number
"""The atomic number for this atom."""
self.x = x
"""The x coordinate for this atom."""
self.y = y
"""The y coordinate for this atom."""
self.z = z
"""The z coordinate for this atom. Will be ``None`` in 2D Compound records."""
self.charge = charge
"""The formal charge on this atom."""
def __repr__(self) -> str:
return f"Atom({self.aid!r}, {self.element!r})"
def __eq__(self, other: object) -> bool:
return (
isinstance(other, type(self))
and self.aid == other.aid
and self.element == other.element
and self.x == other.x
and self.y == other.y
and self.z == other.z
and self.charge == other.charge
)
@deprecated("Dictionary style access to Atom attributes is deprecated")
def __getitem__(self, prop):
"""Allow dict-style access to attributes for backwards compatibility."""
if prop in {"element", "x", "y", "z", "charge"}:
return getattr(self, prop)
raise KeyError(prop)
@deprecated("Dictionary style access to Atom attributes is deprecated")
def __setitem__(self, prop, val):
"""Allow dict-style setting of attributes for backwards compatibility."""
setattr(self, prop, val)
@deprecated("Dictionary style access to Atom attributes is deprecated")
def __contains__(self, prop):
"""Allow dict-style checking of attributes for backwards compatibility."""
if prop in {"element", "x", "y", "z", "charge"}:
return getattr(self, prop) is not None
return False
@property
def element(self) -> str:
"""The element symbol for this atom."""
return ELEMENTS.get(self.number, str(self.number))
def to_dict(self) -> dict[str, t.Any]:
"""Return a dictionary containing Atom data."""
data = {"aid": self.aid, "number": self.number, "element": self.element}
for coord in {"x", "y", "z"}:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge != 0:
data["charge"] = self.charge
return data
def set_coordinates(self, x: float, y: float, z: float | None = None) -> None:
"""Set all coordinate dimensions at once."""
self.x = x
self.y = y
self.z = z
@property
def coordinate_type(self) -> str:
"""Whether this atom has 2D or 3D coordinates."""
return "2d" if self.z is None else "3d"
class Bond:
"""Class to represent a bond between two atoms in a :class:`~pubchempy.Compound`."""
def __init__(
self,
aid1: int,
aid2: int,
order: BondType = BondType.SINGLE,
style: int | None = None,
) -> None:
"""Initialize with begin and end atom IDs, bond order and bond style.
Args:
aid1: Begin atom ID.
aid2: End atom ID.
order: Bond order.
style: Bond style annotation.
"""
self.aid1 = aid1
"""ID of the begin atom of this bond."""
self.aid2 = aid2
"""ID of the end atom of this bond."""
self.order = order
"""Bond order."""
self.style = style
"""Bond style annotation."""
def __repr__(self) -> str:
return f"Bond({self.aid1!r}, {self.aid2!r}, {self.order!r})"
def __eq__(self, other: object) -> bool:
return (
isinstance(other, type(self))
and self.aid1 == other.aid1
and self.aid2 == other.aid2
and self.order == other.order
and self.style == other.style
)
@deprecated("Dictionary style access to Bond attributes is deprecated")
def __getitem__(self, prop):
"""Allow dict-style access to attributes for backwards compatibility."""
if prop in {"order", "style"}:
return getattr(self, prop)
raise KeyError(prop)
@deprecated("Dictionary style access to Bond attributes is deprecated")
def __setitem__(self, prop, val):
"""Allow dict-style setting of attributes for backwards compatibility."""
setattr(self, prop, val)
@deprecated("Dictionary style access to Bond attributes is deprecated")
def __contains__(self, prop):
"""Allow dict-style checking of attributes for backwards compatibility."""
if prop in {"order", "style"}:
return getattr(self, prop) is not None
return False
@deprecated("Dictionary style access to Bond attributes is deprecated")
def __delitem__(self, prop):
"""Allow dict-style deletion of attributes for backwards compatibility."""
if not hasattr(self.__wrapped, prop):
raise KeyError(prop)
delattr(self.__wrapped, prop)
def to_dict(self) -> dict[str, t.Any]:
"""Return a dictionary containing Bond data."""
data = {"aid1": self.aid1, "aid2": self.aid2, "order": self.order}
if self.style is not None:
data["style"] = self.style
return data
class Compound:
"""Represents a standardized chemical structure record from PubChem.