Skip to content

PubChemView

Online: experimental properties from PubChem's PUG-View service, and the parser that turns their prose into numbers. See Experimental properties from PubChem.

provesid.pubchemview

PubChem's annotations, online: PubChemView, over PUG-View.

PUG-REST (provesid.pubchem) serves what PubChem computes; PUG-View serves what depositors report, which is where the measured properties live --- melting and boiling points, densities, solubilities, vapour pressures --- each with its source. PubChemView fetches one heading of a compound's record, walks it, and turns every value into a PropertyData whose parsed field holds the numbers recovered from PubChem's prose (see provesid.pubchemview_parse).

Every call needs the network and is cached. There is no offline copy of this data.

Examples:

>>> from provesid import PubChemView
>>> view = PubChemView()
>>> [d.value for d in view.get_logp(2244)][:2]
['1.18', 'log Kow = 1.19']
>>> table = view.get_property_table(2244, "Melting Point")
>>> table.loc[0, "StringWithMarkup"], float(table.loc[0, "ValueSI"])
('275 °F (NTP, 1992)', 408.15)

Attributes

Classes

PropertyData dataclass

One value PubChem holds for one property, with its provenance.

Attributes:

Name Type Description
value str

The value exactly as PUG-View reported it, e.g. "138-140 °C". Always populated; nothing the parser cannot read is ever lost.

unit Optional[str]

The unit, normalised — a convenience copy of parsed.unit.

conditions Optional[str]

The measurement conditions, a copy of parsed.conditions.

reference Optional[str]

The first reference string attached to the value.

reference_number Optional[int]

PubChem's reference number, which PubChemView.get_property_table resolves to a full citation.

description Optional[str]

PUG-View's own description of the value, when it gives one.

name Optional[str]

PUG-View's Name field for the value, when it gives one.

heading Optional[str]

The section heading the value was found under, e.g. "Melting Point". This is what tells the parser that a bare number is a temperature.

parsed Optional[ParsedValue]

The value turned into numbers: see ParsedValue for the range, the SI conversion, the measurement temperature and any comparison operator or qualitative term. None only when the value string was empty.

Examples:

>>> view = PubChemView()
>>> first = view.get_melting_point(2244)[0]
>>> first.value, first.unit, first.reference_number
('275 °F (NTP, 1992)', '°F', 9)
>>> first.parsed.value_si, first.parsed.unit_si
(408.15, 'K')
Source code in src/provesid/pubchemview.py
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
@dataclass
class PropertyData:
    """
    One value PubChem holds for one property, with its provenance.

    Attributes:
        value: The value exactly as PUG-View reported it, e.g. ``"138-140 °C"``.
            Always populated; nothing the parser cannot read is ever lost.
        unit: The unit, normalised — a convenience copy of ``parsed.unit``.
        conditions: The measurement conditions, a copy of ``parsed.conditions``.
        reference: The first reference string attached to the value.
        reference_number: PubChem's reference number, which
            [`PubChemView.get_property_table`][provesid.pubchemview.PubChemView.get_property_table]
            resolves to a full citation.
        description: PUG-View's own description of the value, when it gives one.
        name: PUG-View's ``Name`` field for the value, when it gives one.
        heading: The section heading the value was found under, e.g.
            ``"Melting Point"``. This is what tells the parser that a bare
            number is a temperature.
        parsed: The value turned into numbers: see
            [`ParsedValue`][provesid.pubchemview_parse.ParsedValue] for the
            range, the SI conversion, the measurement temperature and any
            comparison operator or qualitative term. None only when the value
            string was empty.

    Examples:
        >>> view = PubChemView()
        >>> first = view.get_melting_point(2244)[0]           # doctest: +SKIP
        >>> first.value, first.unit, first.reference_number   # doctest: +SKIP
        ('275 °F (NTP, 1992)', '°F', 9)
        >>> first.parsed.value_si, first.parsed.unit_si       # doctest: +SKIP
        (408.15, 'K')
    """
    value: str
    unit: Optional[str] = None
    conditions: Optional[str] = None
    reference: Optional[str] = None
    reference_number: Optional[int] = None
    description: Optional[str] = None
    name: Optional[str] = None
    heading: Optional[str] = None
    parsed: Optional[ParsedValue] = None

PubChemViewError

Bases: ServiceError

Base exception class for PubChem View API errors.

Raised on its own when a request could not be completed --- a ServerBusy that outlasted the retries, a throttled host. The extract_* and get_property_table methods let it through rather than report "no data", so a failure is never cached as absence.

Examples:

>>> issubclass(PubChemViewNotFoundError, PubChemViewError)
True
Source code in src/provesid/pubchemview.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class PubChemViewError(ServiceError):
    """
    Base exception class for PubChem View API errors.

    Raised on its own when a request could not be completed --- a
    ``ServerBusy`` that outlasted the retries, a throttled host. The
    ``extract_*`` and ``get_property_table`` methods let it through rather
    than report "no data", so a failure is never cached as absence.

    Examples:
        >>> issubclass(PubChemViewNotFoundError, PubChemViewError)
        True
    """
    pass

PubChemViewNotFoundError

Bases: PubChemViewError, NotFoundError

Exception raised when compound or property is not found.

PUG-View answers 404 for an unknown compound and 400 for a heading the compound does not have; both are absence. Only the raw PubChemView.get_property and PubChemView.get_experimental_properties raise it; the parsing methods turn it into an empty result.

Examples:

>>> view = PubChemView()
>>> view.get_property(2244, "No Such Heading")
Traceback (most recent call last):
...
provesid.pubchemview.PubChemViewNotFoundError: No data for https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/2244/JSON?heading=No+Such+Heading (HTTP 400)
Source code in src/provesid/pubchemview.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class PubChemViewNotFoundError(PubChemViewError, NotFoundError):
    """
    Exception raised when compound or property is not found.

    PUG-View answers 404 for an unknown compound and 400 for a heading the
    compound does not have; both are absence. Only the raw
    [`PubChemView.get_property`][provesid.pubchemview.PubChemView.get_property] and
    [`PubChemView.get_experimental_properties`][provesid.pubchemview.PubChemView.get_experimental_properties]
    raise it; the parsing methods turn it into an empty result.

    Examples:
        >>> view = PubChemView()
        >>> view.get_property(2244, "No Such Heading")        # doctest: +SKIP
        Traceback (most recent call last):
        ...
        provesid.pubchemview.PubChemViewNotFoundError: No data for https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/2244/JSON?heading=No+Such+Heading (HTTP 400)
    """
    pass

PubChemView

A class that uses PUG View for extracting properties reported for each substance in PubChem but are not included in the standard API response for substance, compound, assay, etc. The response to these queries is a large JSON object that requires some post-processing to extract the relevant information.

Three levels, from raw to tabular: get_property returns PUG-View's JSON; extract_property_data returns one PropertyData per value; get_property_table returns a DataFrame with the numbers, SI conversions and resolved citations. The get_melting_point family are shortcuts for common headings. experimental_properties lists the experimental headings, but any PUG-View heading works.

Requests share PubChem's per-address pacing with every PubChemAPI in the process.

Examples:

>>> view = PubChemView()
>>> summary = view.get_property_summary(2244, "Melting Point")
>>> summary["count"], summary["values"][:2]
(7, ['275 °F (NTP, 1992)', '138-140'])
Source code in src/provesid/pubchemview.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
class PubChemView:
    """
    A class that uses PUG View for extracting properties reported for each substance in PubChem but are not
    included in the standard API response for substance, compound, assay, etc.
    The response to these queries is a large JSON object that requires some post-processing to extract the
    relevant information.

    Three levels, from raw to tabular:
    [`get_property`][provesid.pubchemview.PubChemView.get_property] returns
    PUG-View's JSON;
    [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
    returns one [`PropertyData`][provesid.pubchemview.PropertyData] per value;
    [`get_property_table`][provesid.pubchemview.PubChemView.get_property_table]
    returns a DataFrame with the numbers, SI conversions and resolved
    citations. The ``get_melting_point`` family are shortcuts for common
    headings. `experimental_properties` lists the experimental headings, but
    any PUG-View heading works.

    Requests share PubChem's per-address pacing with every
    [`PubChemAPI`][provesid.pubchem.PubChemAPI] in the process.

    Examples:
        >>> view = PubChemView()
        >>> summary = view.get_property_summary(2244, "Melting Point")  # doctest: +SKIP
        >>> summary["count"], summary["values"][:2]                    # doctest: +SKIP
        (7, ['275 °F (NTP, 1992)', '138-140'])
    """

    def __init__(self, base_url: str = "https://pubchem.ncbi.nlm.nih.gov/rest/pug_view",
                 timeout: int = 30, max_retries: int = 3, backoff_factor: float = 1.0, use_cache: bool = True):
        """
        Initialize PubChemView API client

        Args:
            base_url: Base URL for PubChem PUG View API
            timeout: Request timeout in seconds
            max_retries: Maximum number of retry attempts
            backoff_factor: Backoff factor for retries
            use_cache: Whether to use cache for lookups (default: True).
                      When False, skips cache lookup but still stores results.

        Examples:
            >>> view = PubChemView(timeout=60, use_cache=False)
            >>> view.base_url, view.timeout
            ('https://pubchem.ncbi.nlm.nih.gov/rest/pug_view', 60)
        """
        self.base_url = base_url.rstrip('/')
        self.timeout = timeout
        self.max_retries = max_retries
        self.backoff_factor = backoff_factor
        self.logger = logging.getLogger(__name__)
        self.use_cache = use_cache

        # One shared transport. PubChem describes every error in the body, so
        # it supplies its own classifier rather than trusting the status code:
        # see ``provesid.pubchem.pugview_classify``.
        self._http = HTTPClient(
            min_interval=0.2,          # 5 requests per second max
            timeout=timeout,
            max_retries=max_retries,
            backoff=backoff_factor,
            max_elapsed=RETRY_WAIT_BUDGET,
            classify=pugview_classify,
            error_cls=PubChemViewError,
            not_found_cls=PubChemViewNotFoundError,
            # PubChem's five requests per second is a per-IP budget, so this
            # client shares its pacing clock with every other client aimed at
            # the same host --- a PubChemAPI in the same process, above all.
            pace_host=self.base_url,
            logger=self.logger,
        )

        self.experimental_properties = {
            "Accelerating Rate Calorimetry (ARC)": "Accelerating+Rate+Calorimetry+(ARC)",
            "Acid Value": "Acid+Value",
            "Autoignition Temperature": "Autoignition+Temperature",
            "Boiling Point": "Boiling+Point",
            "Caco2 Permeability": "Caco2+Permeability",
            "Collision Cross Section": "Collision+Cross+Section",
            "Color/Form": "Color/Form",
            "Corrosivity": "Corrosivity",
            "Decomposition": "Decomposition",
            "Density": "Density",
            "Dielectric Constant": "Dielectric+Constant",
            "Differential Scanning Calorimetry (DSC)": "Differential+Scanning+Calorimetry+(DSC)",
            "Dispersion": "Dispersion",
            "Dissociation Constants": "Dissociation+Constants",
            "Enthalpy of Sublimation": "Enthalpy+of+Sublimation",
            "Flash Point": "Flash+Point",
            "Heat of Combustion": "Heat+of+Combustion",
            "Heat of Vaporization": "Heat+of+Vaporization",
            "Henry's Law Constant": "Henry's+Law+Constant",
            "Hydrophobicity": "Hydrophobicity",
            "Ionization Efficiency": "Ionization+Efficiency",
            "Ionization Potential": "Ionization+Potential",
            "Isoelectric Point": "Isoelectric+Point",
            "Kovats Retention Index": "Kovats+Retention+Index",
            "LogP": "LogP",
            "LogS": "LogS",
            "Melting Point": "Melting+Point",
            "Odor": "Odor",
            "Odor Threshold": "Odor+Threshold",
            "Optical Rotation": "Optical+Rotation",
            "Other Experimental Properties": "Other+Experimental+Properties",
            "pH": "pH",
            "Physical Description": "Physical+Description",
            "Polymerization": "Polymerization",
            "Refractive Index": "Refractive+Index",
            "Relative Evaporation Rate": "Relative+Evaporation+Rate",
            "Self-Accelerating Decomposition Temperature (SADT)": "Self-Accelerating+Decomposition+Temperature+(SADT)",
            "Solubility": "Solubility",
            "Stability/Shelf Life": "Stability/Shelf+Life",
            "Surface Tension": "Surface+Tension",
            "Taste": "Taste",
            "Vapor Density": "Vapor+Density",
            "Vapor Pressure": "Vapor+Pressure",
            "Viscosity": "Viscosity"
        }
        """PUG-View's experimental-property headings, each mapped to the form
        it takes in a URL. [`get_property`][provesid.pubchemview.PubChemView.get_property]
        looks a heading up here and otherwise swaps its spaces for ``+``, so
        a heading missing from this dict still works."""

    CACHE_SCHEMA_VERSION = 2
    """Bumped whenever the *shape* of what a cached method returns changes, so
    that entries written by an earlier version become unreachable instead of
    being deserialised into the wrong structure. Version 2 introduced
    ``PropertyData.parsed``: a version-1 entry unpickles into an object with
    no such attribute, and every caller that reads it would raise.
    """

    def __cache_key__(self) -> tuple:
        """
        Identify this client for cache-key purposes.

        Only the endpoint distinguishes two clients' results; timeout, retry and
        ``use_cache`` settings change how a call is made, not what it returns.
        The schema version is part of the key so that an upgrade cannot serve a
        stale entry of the previous shape.

        Returns:
            Tuple of the class path, the configured base URL and
            [`CACHE_SCHEMA_VERSION`][provesid.pubchemview.PubChemView.CACHE_SCHEMA_VERSION].
        """
        return ("provesid.pubchemview.PubChemView", self.base_url,
                self.CACHE_SCHEMA_VERSION)

    def clear_cache(self):
        """
        Delete every cached PUG-View answer, in memory and on disk.

        The same as ``provesid.clear_cache(service='pubchemview')``.

        Examples:
            >>> view = PubChemView()
            >>> view.clear_cache()
            >>> view.get_cache_info()['file_count']
            0
        """
        from .cache import clear_cache
        clear_cache(service='pubchemview')

    def get_cache_info(self) -> Dict[str, Any]:
        """
        Size and location of the PUG-View cache.

        Returns:
            The statistics
            [`provesid.cache.get_cache_info`][provesid.cache.get_cache_info]
            reports for
                ``service='pubchemview'``.

        Examples:
            >>> PubChemView().get_cache_info()['cache_directory'].endswith('pubchemview')
            True
        """
        from .cache import get_cache_info
        return get_cache_info(service='pubchemview')

    @property
    def min_request_interval(self) -> float:
        """
        Minimum seconds between two requests from this client.

        Held by the transport, and settable: raising it slows a long batch
        down, and the new value takes effect on the next request, retries
        included.

        Examples:
            >>> view = PubChemView()
            >>> view.min_request_interval
            0.2
            >>> view.min_request_interval = 1.0   # gentler, for a long batch
        """
        return self._http.min_interval

    @min_request_interval.setter
    def min_request_interval(self, seconds: float) -> None:
        self._http.min_interval = seconds

    def _rate_limit(self):
        """
        Sleep, if needed, so this client's requests stay
        ``min_request_interval`` apart.

        Delegates to the shared transport, which paces every request it makes
        including retries.

        Examples:
            >>> PubChemView()._rate_limit()   # doctest: +SKIP
        """
        self._http.rate_limit()

    @property
    def last_request_time(self) -> float:
        """
        When this client last made a request, as a Unix timestamp.

        Kept on the transport; exposed here because it describes the client's
        own pacing.

        Returns:
            Seconds since the epoch, or 0.0 before the first request.

        Examples:
            >>> PubChemView().last_request_time
            0.0
        """
        return self._http.last_request_time

    def _make_request(self, url: str) -> Dict[str, Any]:
        """
        Make one request to PUG-View and return its parsed JSON body.

        The transport handles the pacing, the retries and the back-off; what
        stays here is the shape of a PUG-View request. Classification is
        [`provesid.pubchem.pugview_classify`][provesid.pubchem.pugview_classify],
        which reads the fault code in the body because PubChem's status codes
        alone do not distinguish a compound that has no such data from a
        service shedding load.

        Args:
            url: Request URL

        Returns:
            JSON response as dictionary

        Raises:
            PubChemViewNotFoundError: When the compound or heading does not
                exist. PUG-View answers 404 for an unknown compound and 400
                (``PUGVIEW.BadRequest``) for an unknown heading; both are
                permanent, so both are reported as absence rather than retried.
            PubChemViewError: For any other API error, including a transient
                ``ServerBusy`` that survived every retry. Only transient fault
                codes, 429, 5xx, timeouts and connection errors are retried ---
                a permanent 4xx cannot be fixed by asking again.
        """
        return self._http.get_json(url)

    @cached(service='pubchemview')
    def get_experimental_properties(self, cid: Union[int, str]) -> Dict[str, Any]:
        """
        Get all experimental properties for a compound

        Args:
            cid: PubChem Compound ID

        Returns:
            Raw JSON response containing all experimental properties

        Raises:
            PubChemViewNotFoundError: If the compound does not exist or has no
                experimental properties.
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> view = PubChemView()
            >>> record = view.get_experimental_properties(2244)["Record"]  # doctest: +SKIP
            >>> record["RecordNumber"], record["RecordTitle"]               # doctest: +SKIP
            (2244, 'Aspirin')
        """
        url = f"{self.base_url}/data/compound/{cid}/JSON?heading=Experimental+Properties"
        return self._make_request(url)

    @cached(service='pubchemview')
    def get_property(self, cid: Union[int, str], property_name: str) -> Dict[str, Any]:
        """
        Get a specific property for a compound

        Args:
            cid: PubChem Compound ID
            property_name: Name of the property (can be with spaces or plus signs)

        Returns:
            Raw JSON response for the specific property. The heading sits
            wherever it does in the compound's table of contents, not at a
            fixed path;
            [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
            finds it.

        Raises:
            PubChemViewNotFoundError: If the compound does not exist or does
                not have this heading.
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> view = PubChemView()
            >>> record = view.get_property(2244, "Melting Point")["Record"]  # doctest: +SKIP
            >>> record["Section"][0]["TOCHeading"]                           # doctest: +SKIP
            'Chemical and Physical Properties'
        """
        # Convert property name to URL-safe format
        if property_name in self.experimental_properties:
            url_property = self.experimental_properties[property_name]
        else:
            url_property = property_name.replace(' ', '+')

        url = f"{self.base_url}/data/compound/{cid}/JSON?heading={url_property}"
        return self._make_request(url)


    def _extract_value_info(self, info_item: Dict[str, Any],
                            heading: Optional[str] = None) -> PropertyData:
        """
        Turn one PUG-View ``Information`` item into a
        [`PropertyData`][provesid.pubchemview.PropertyData].

        Args:
            info_item: A single ``Information`` dictionary from a PUG-View
                response.
            heading: The section heading the item was found under. Passed
                through to [`parse_value`][provesid.pubchemview_parse.parse_value],
                which needs it to read a bare number: 138 under "Melting Point"
                is 138 °C, while 1.19 under "LogP" is dimensionless.

        Returns:
            A PropertyData carrying the original string, the parsed numbers and
            the reference it came from.
        """
        value_str = ""
        if "Value" in info_item and "StringWithMarkup" in info_item["Value"]:
            markup = info_item["Value"]["StringWithMarkup"]
            if markup:
                value_str = markup[0].get("String", "")

        # Some headings report a plain number instead of prose, with the unit
        # in its own field; the computed-property sections do this throughout.
        value_block = info_item.get("Value", {})
        if not value_str and value_block.get("Number"):
            number = value_block["Number"][0]
            unit = value_block.get("Unit", "")
            value_str = f"{number} {unit}".strip()

        reference = None
        reference_number = info_item.get("ReferenceNumber")
        if "Reference" in info_item and info_item["Reference"]:
            reference = info_item["Reference"][0]

        name = info_item.get("Name", "")
        description = info_item.get("Description", "")

        parsed = parse_value(value_str, heading)

        return PropertyData(
            value=value_str,
            unit=parsed.unit,
            conditions=parsed.conditions,
            reference=reference,
            reference_number=reference_number,
            description=description if description else None,
            name=name if name else None,
            heading=heading,
            parsed=parsed,
        )

    def _iter_information(self, response: Dict[str, Any]
                          ) -> Iterator[Tuple[Optional[str], Dict[str, Any]]]:
        """
        Walk a PUG-View record and yield every value with its heading.

        PUG-View nests a requested heading wherever it sits in the compound's
        table of contents, and that position differs by heading: "Melting Point"
        arrives under *Chemical and Physical Properties → Experimental
        Properties*, "GHS Classification" under *Safety and Hazards → Hazards
        Identification*, "Drug Indication" under *Drug and Medication
        Information*. Walking the tree instead of following one hard-coded path
        is what lets every heading work, rather than only the experimental ones.

        Args:
            response: Raw JSON response from PUG-View.

        Yields:
            ``(heading, information_item)`` pairs, the heading being the
            innermost ``TOCHeading`` that owns the item.
        """
        def walk(node: Dict[str, Any], inherited: Optional[str]):
            """Yield this node's values, then recurse into its subsections."""
            # A subsection without its own heading belongs to its parent's.
            heading = node.get("TOCHeading", inherited)
            for item in node.get("Information", []) or []:
                yield heading, item
            for child in node.get("Section", []) or []:
                yield from walk(child, heading)

        if not isinstance(response, dict):
            return
        record = response.get("Record", {})
        for section in record.get("Section", []) or []:
            yield from walk(section, None)

    @staticmethod
    def _carries_a_value(info_item: Dict[str, Any]) -> bool:
        """
        Whether an ``Information`` item states a value at all.

        Some items are pointers rather than measurements — PubChem records a
        compound's IUPAC pKa data as ``{"Value": {"ExternalTableName":
        "iupacpka"}}``, which carries a reference and nothing else. Including
        one would put a blank row in a property table.

        Args:
            info_item: A single ``Information`` dictionary.

        Returns:
            True when the item has a string or a number to parse.
        """
        value = info_item.get("Value", {})
        markup = value.get("StringWithMarkup") or []
        return bool((markup and markup[0].get("String")) or value.get("Number"))

    @cached(service='pubchemview', skip_if=is_empty_result)
    def extract_property_data(self, cid: Union[int, str], property_name: str) -> List[PropertyData]:
        """
        Extract structured property data for a specific property.

        Args:
            cid: PubChem Compound ID
            property_name: The PUG-View heading, e.g. ``"Melting Point"``. Any
                heading works, not only the experimental ones.

        Returns:
            List of PropertyData objects, each carrying the value as PubChem
            wrote it plus a ``parsed``
            [`ParsedValue`][provesid.pubchemview_parse.ParsedValue] holding the
            numbers recovered from it. An empty list means PubChem holds no
            such property for this compound.

        Raises:
            PubChemViewError: If the request could not be completed, for example
                a PUG-View ``ServerBusy`` response that survived every retry.
                This is deliberately *not* reported as an empty list: a
                transient failure must stay distinguishable from real absence,
                or it gets cached as "no data" and never retried.

        Examples:
            >>> view = PubChemView()
            >>> data = view.extract_property_data(2244, "Dissociation Constants")  # doctest: +SKIP
            >>> data[0].value, data[0].parsed.value                                # doctest: +SKIP
            ('3.47', 3.47)
            >>> view.extract_property_data(2244, "No Such Heading")               # doctest: +SKIP
            []
        """
        try:
            response = self.get_property(cid, property_name)
        except PubChemViewNotFoundError:
            self.logger.debug(f"Property '{property_name}' not present for CID {cid}")
            return []
        return self._parse_property_response(response)

    def _parse_property_response(self, response: Dict[str, Any]) -> List[PropertyData]:
        """
        Parse a single-heading response into structured values.

        Args:
            response: Raw JSON response from PUG-View, as returned by
                [`get_property`][provesid.pubchemview.PubChemView.get_property].

        Returns:
            One PropertyData per value in the response, in document order.
            Items that carry no value — PubChem's pointers to its own external
            tables — are left out rather than returned blank. An empty list
            means the response carried no values, not that parsing failed.
        """
        return [self._extract_value_info(item, heading)
                for heading, item in self._iter_information(response)
                if self._carries_a_value(item)]

    @cached(service='pubchemview', skip_if=is_empty_result)
    def extract_all_experimental_properties(self, cid: Union[int, str]) -> Dict[str, List[PropertyData]]:
        """
        Extract all experimental properties for a compound in structured format

        Args:
            cid: PubChem Compound ID

        Returns:
            Dictionary mapping property names to lists of PropertyData objects,
            in the order PubChem lists the headings. Empty when the compound
            has no experimental properties.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> view = PubChemView()
            >>> props = view.extract_all_experimental_properties(2244)  # doctest: +SKIP
            >>> list(props)[:4]                                        # doctest: +SKIP
            ['Physical Description', 'Color/Form', 'Odor', 'Boiling Point']
            >>> props["Melting Point"][0].value                        # doctest: +SKIP
            '275 °F (NTP, 1992)'
        """
        try:
            response = self.get_experimental_properties(cid)
            return self._parse_all_properties_response(response)
        except PubChemViewNotFoundError:
            self.logger.warning(f"No experimental properties found for CID {cid}")
            return {}

    def _parse_all_properties_response(self, response: Dict[str, Any]
                                       ) -> Dict[str, List[PropertyData]]:
        """
        Parse a multi-property response, grouped by heading.

        Args:
            response: Raw JSON response from PUG-View, as returned by
                [`get_experimental_properties`][provesid.pubchemview.PubChemView.get_experimental_properties].

        Returns:
            A dict mapping each heading that carried values to its
            PropertyData list, in the order PubChem listed them.
        """
        grouped: Dict[str, List[PropertyData]] = {}
        for heading, item in self._iter_information(response):
            if not self._carries_a_value(item):
                continue
            grouped.setdefault(heading or "Unknown", []).append(
                self._extract_value_info(item, heading))
        return grouped

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_available_properties(self, cid: Union[int, str]) -> List[str]:
        """
        Get list of available experimental properties for a compound

        Args:
            cid: PubChem Compound ID

        Returns:
            List of available property names: the experimental headings this
            compound has values under, in PubChem's order. Empty when it has
            none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> PubChemView().get_available_properties(2244)[:3]  # doctest: +SKIP
            ['Physical Description', 'Color/Form', 'Odor']
        """
        try:
            response = self.get_experimental_properties(cid)
            return list(self._parse_all_properties_response(response).keys())
        except PubChemViewNotFoundError:
            return []

    @cached(service='pubchemview', skip_if=lambda result: not result.get('values'))
    def get_property_summary(self, cid: Union[int, str], property_name: str) -> Dict[str, Any]:
        """
        Get a summary of a property including all values, units, and references

        Args:
            cid: PubChem Compound ID
            property_name: Name of the property

        Returns:
            Dictionary with the raw strings under ``values``, the numbers
            recovered from them under ``numeric_values`` and
            ``numeric_values_si``, plus the references, units and conditions
            seen across the entries and a ``count``. A range or a word
            contributes to ``values`` but not to ``numeric_values``, so the
            two lists need not line up. ``units``, ``units_si`` and
            ``conditions`` are sets as lists, in no particular order.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> summary = PubChemView().get_property_summary(2244, "Melting Point")  # doctest: +SKIP
            >>> summary["values"][:2], summary["numeric_values"][:2]                 # doctest: +SKIP
            (['275 °F (NTP, 1992)', '138-140'], [275.0, 135.0])
        """
        property_data = self.extract_property_data(cid, property_name)

        if not property_data:
            return {"property": property_name, "values": [], "numeric_values": [],
                    "numeric_values_si": [], "references": [], "units": [],
                    "units_si": [], "conditions": [], "count": 0}

        parsed_values = [data.parsed or parse_value(data.value, data.heading)
                         for data in property_data]

        summary = {
            "property": property_name,
            "values": [data.value for data in property_data],
            # The numbers behind those strings, for the common case of wanting
            # a range or a mean rather than the prose.
            "numeric_values": [parsed.value for parsed in parsed_values
                               if parsed.value is not None],
            "numeric_values_si": [parsed.value_si for parsed in parsed_values
                                  if parsed.value_si is not None],
            "references": [data.reference for data in property_data if data.reference],
            "units": list(set([data.unit for data in property_data if data.unit])),
            "units_si": list({parsed.unit_si for parsed in parsed_values
                              if parsed.unit_si}),
            "conditions": list(set([data.conditions for data in property_data if data.conditions])),
            "count": len(property_data)
        }

        return summary

    # Convenience methods for common properties
    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_melting_point(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get melting point data for a compound.

        ``extract_property_data(cid, "Melting Point")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_melting_point(2244)][:2]  # doctest: +SKIP
            ['275 °F (NTP, 1992)', '138-140']
        """
        return self.extract_property_data(cid, "Melting Point")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_boiling_point(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get boiling point data for a compound.

        ``extract_property_data(cid, "Boiling Point")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_boiling_point(2244)][:2]  # doctest: +SKIP
            ['284 °F at 760 mmHg (decomposes) (NTP, 1992)', '140 °C']
        """
        return self.extract_property_data(cid, "Boiling Point")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_density(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get density data for a compound.

        ``extract_property_data(cid, "Density")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_density(2244)][:2]  # doctest: +SKIP
            ['1.4 (NTP, 1992) - Denser than water; will sink', '1.40']
        """
        return self.extract_property_data(cid, "Density")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_solubility(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get solubility data for a compound.

        ``extract_property_data(cid, "Solubility")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_solubility(2244)][:2]  # doctest: +SKIP
            ['less than 1 mg/mL at 73 °F (NTP, 1992)', '10 mg/mL']
        """
        return self.extract_property_data(cid, "Solubility")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_flash_point(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get flash point data for a compound.

        ``extract_property_data(cid, "Flash Point")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_flash_point(2244)][:2]  # doctest: +SKIP
            ['482 °F (NTP, 1992)']
        """
        return self.extract_property_data(cid, "Flash Point")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_vapor_pressure(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get vapor pressure data for a compound.

        ``extract_property_data(cid, "Vapor Pressure")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_vapor_pressure(2244)][:2]  # doctest: +SKIP
            ['0 mmHg (approx) (NIOSH, 2024)', '2.52X10-5 mm Hg at 25 °C (calc)']
        """
        return self.extract_property_data(cid, "Vapor Pressure")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_viscosity(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get viscosity data for a compound.

        ``extract_property_data(cid, "Viscosity")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_viscosity(702)][:2]  # doctest: +SKIP
            ['1.074 mPa.s at 25 °C', '1.074 mPa*s at 20 °C']
        """
        return self.extract_property_data(cid, "Viscosity")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_logp(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get LogP data for a compound.

        ``extract_property_data(cid, "LogP")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_logp(2244)][:2]  # doctest: +SKIP
            ['1.18', 'log Kow = 1.19']
        """
        return self.extract_property_data(cid, "LogP")

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_refractive_index(self, cid: Union[int, str]) -> List[PropertyData]:
        """
        Get refractive index data for a compound.

        ``extract_property_data(cid, "Refractive Index")``, cached separately.

        Args:
            cid: PubChem Compound ID

        Returns:
            List of PropertyData objects; empty when PubChem has none.

        Raises:
            PubChemViewError: If the request could not be completed.

        Examples:
            >>> [d.value for d in PubChemView().get_refractive_index(702)][:2]  # doctest: +SKIP
            ['Index of refraction: 1.3611 at 20 °C/D', '1.364']
        """
        return self.extract_property_data(cid, "Refractive Index")

    def batch_extract_properties(self, cid: Union[int, str],
                                property_names: List[str]) -> Dict[str, List[PropertyData]]:
        """
        Extract multiple properties for a compound

        Args:
            cid: PubChem Compound ID
            property_names: List of property names to extract

        Returns:
            Dictionary mapping property names to PropertyData lists.

        Note:
            One property failing does not abort the batch: that entry is logged
            at WARNING and comes back as an empty list, so here — unlike in
            [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
            — an empty list does not prove the property is absent. Call
            ``extract_property_data`` directly when the difference matters.

        Examples:
            >>> found = PubChemView().batch_extract_properties(
            ...     2244, ["Melting Point", "Boiling Point"])         # doctest: +SKIP
            >>> {name: len(values) for name, values in found.items()}  # doctest: +SKIP
            {'Melting Point': 7, 'Boiling Point': 4}
        """
        results = {}
        for prop_name in property_names:
            try:
                results[prop_name] = self.extract_property_data(cid, prop_name)
            except Exception as e:
                self.logger.warning(f"Failed to extract {prop_name} for CID {cid}: {e}")
                results[prop_name] = []

        return results

    def export_properties_to_dict(self, property_data_list: List[PropertyData]) -> List[Dict[str, Any]]:
        """
        Convert PropertyData objects to plain dictionaries for serialization.

        Args:
            property_data_list: List of PropertyData objects, as returned by
                [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
                or any of the convenience getters.

        Returns:
            One dict per value, carrying the original string, the reference, and
            the parsed numbers flattened into top-level keys
            (``numeric_value``, ``value_min``, ``value_si``, ``unit_si``,
            ``operator``, ``qualitative``, ``temperature_c``) so the result can
            go straight into ``json.dumps`` or ``pd.DataFrame``.

        Examples:
            >>> from provesid.pubchemview_parse import parse_value
            >>> data = PropertyData(value="135 °C", heading="Melting Point",
            ...                     parsed=parse_value("135 °C", "Melting Point"))
            >>> row = PubChemView().export_properties_to_dict([data])[0]
            >>> row["numeric_value"], row["value_si"], row["unit_si"]
            (135.0, 408.15, 'K')
        """
        rows = []
        for data in property_data_list:
            parsed = data.parsed or parse_value(data.value, data.heading)
            rows.append({
                "value": data.value,
                "unit": data.unit,
                "conditions": data.conditions,
                "reference": data.reference,
                "reference_number": data.reference_number,
                "description": data.description,
                "name": data.name,
                "heading": data.heading,
                # The parsed numbers are flattened rather than nested, so the
                # result stays directly serialisable to JSON or a DataFrame.
                "numeric_value": parsed.value,
                "value_min": parsed.value_min,
                "value_max": parsed.value_max,
                "value_si": parsed.value_si,
                "value_min_si": parsed.value_min_si,
                "value_max_si": parsed.value_max_si,
                "unit_si": parsed.unit_si,
                "operator": parsed.operator,
                "qualitative": parsed.qualitative,
                "temperature_c": parsed.temperature_c,
            })
        return rows


    PROPERTY_TABLE_COLUMNS = [
        "CID", "Heading", "StringWithMarkup", "ExperimentalValue",
        "ValueMin", "ValueMax", "Unit", "ValueSI", "ValueMinSI", "ValueMaxSI",
        "UnitSI", "Operator", "Qualitative", "Temperature", "Conditions",
        "FullReference",
    ]
    """Columns of the frame
    [`get_property_table`][provesid.pubchemview.PubChemView.get_property_table]
    returns, in order."""

    @cached(service='pubchemview', skip_if=is_empty_result)
    def get_property_table(self, cid: Union[int, str], property_name: str) -> pd.DataFrame:
        """
        Get a table of property values, parsed into numbers, with references.

        Args:
            cid: PubChem Compound ID.
            property_name: The PUG-View heading, e.g. ``"Melting Point"``. Any
                heading works, not only the experimental ones.

        Returns:
            A DataFrame with the columns in
            [`PROPERTY_TABLE_COLUMNS`][provesid.pubchemview.PubChemView.PROPERTY_TABLE_COLUMNS]:

            - ``StringWithMarkup`` — the value exactly as PubChem wrote it.
            - ``ExperimentalValue`` — the single number, as a float; NaN when
                the entry reports a range or no number at all.
            - ``ValueMin`` / ``ValueMax`` — the bounds, equal to
                ``ExperimentalValue`` for a single value, so a numeric filter
                needs no special case for ranges.
            - ``Unit`` — normalised, so ``torr`` and ``mm Hg`` agree.
            - ``ValueSI`` / ``ValueMinSI`` / ``ValueMaxSI`` / ``UnitSI`` — the
                same quantity in SI units, or NaN where the unit has no
                unambiguous SI equivalent (a percentage, a ppm).
            - ``Operator`` — ``>``, ``<``, ``>=``, ``<=`` or ``~`` when the
                entry bounds the value rather than stating it.
            - ``Qualitative`` — the word that replaced the number, such as
                ``insoluble``.
            - ``Temperature`` — the temperature the measurement was made at, in
                °C. A *condition*, not the value.
            - ``FullReference`` — the resolved citation.

            The frame is empty, with these columns, when PubChem holds no such
            property for this compound.

        Raises:
            PubChemViewError: If the request could not be completed. An empty
                frame always means "no such data", never "the fetch failed".

        Examples:
            >>> view = PubChemView()
            >>> table = view.get_property_table(2244, "Melting Point")  # doctest: +SKIP
            >>> table[["StringWithMarkup", "ValueMin", "ValueMax", "Unit", "ValueSI"]].head(2)  # doctest: +SKIP
                 StringWithMarkup  ValueMin  ValueMax Unit  ValueSI
            0  275 °F (NTP, 1992)     275.0     275.0   °F   408.15
            1             138-140     138.0     140.0   °C      NaN
        """
        try:
            response = self.get_property(cid, property_name)
            reference_map = self._extract_reference_map(response)
            property_data = self._parse_property_response(response)
        except PubChemViewNotFoundError:
            self.logger.debug(f"Property '{property_name}' not present for CID {cid}")
            return pd.DataFrame(columns=self.PROPERTY_TABLE_COLUMNS)
        except PubChemViewError:
            # Transport failure: let it surface rather than pass an empty table
            # off as "this compound has no data".
            raise

        rows = []
        for data in property_data:
            full_reference = ""
            if data.reference_number and data.reference_number in reference_map:
                full_reference = reference_map[data.reference_number]
            elif data.reference:
                full_reference = data.reference

            parsed = data.parsed or parse_value(data.value, data.heading)
            rows.append({
                "CID": cid,
                "Heading": data.heading,
                "StringWithMarkup": data.value,
                "ExperimentalValue": parsed.value,
                "ValueMin": parsed.value_min,
                "ValueMax": parsed.value_max,
                "Unit": parsed.unit,
                "ValueSI": parsed.value_si,
                "ValueMinSI": parsed.value_min_si,
                "ValueMaxSI": parsed.value_max_si,
                "UnitSI": parsed.unit_si,
                "Operator": parsed.operator,
                "Qualitative": parsed.qualitative,
                "Temperature": parsed.temperature_c,
                "Conditions": parsed.conditions,
                "FullReference": full_reference,
            })

        return pd.DataFrame(rows, columns=self.PROPERTY_TABLE_COLUMNS)

    def _extract_reference_map(self, response: Dict[str, Any]) -> Dict[int, str]:
        """
        Extract mapping of reference numbers to full reference strings

        Args:
            response: Raw JSON response from PUG View

        Returns:
            Dictionary mapping reference numbers to full reference strings
        """
        reference_map = {}

        try:
            record = response.get("Record", {})
            references = record.get("Reference", [])

            for ref in references:
                ref_num = ref.get("ReferenceNumber")
                if ref_num:
                    # Build full reference string from available fields
                    ref_parts = []

                    # Add source name
                    if "SourceName" in ref:
                        ref_parts.append(ref["SourceName"])

                    # Add name/title
                    if "Name" in ref:
                        ref_parts.append(ref["Name"])

                    # Add description
                    if "Description" in ref:
                        description = ref["Description"]
                        # Truncate very long descriptions
                        if len(description) > 200:
                            description = description[:200] + "..."
                        ref_parts.append(description)

                    # Add URL if available
                    if "URL" in ref:
                        ref_parts.append(f"URL: {ref['URL']}")

                    # Combine parts with proper separation
                    full_ref = " | ".join(ref_parts) if ref_parts else f"Reference #{ref_num}"
                    reference_map[ref_num] = full_ref

        except Exception as e:
            self.logger.warning(f"Error extracting reference map: {e}")

        return reference_map
Attributes
experimental_properties instance-attribute

PUG-View's experimental-property headings, each mapped to the form it takes in a URL. get_property looks a heading up here and otherwise swaps its spaces for +, so a heading missing from this dict still works.

CACHE_SCHEMA_VERSION class-attribute instance-attribute

Bumped whenever the shape of what a cached method returns changes, so that entries written by an earlier version become unreachable instead of being deserialised into the wrong structure. Version 2 introduced PropertyData.parsed: a version-1 entry unpickles into an object with no such attribute, and every caller that reads it would raise.

min_request_interval property writable

Minimum seconds between two requests from this client.

Held by the transport, and settable: raising it slows a long batch down, and the new value takes effect on the next request, retries included.

Examples:

>>> view = PubChemView()
>>> view.min_request_interval
0.2
>>> view.min_request_interval = 1.0   # gentler, for a long batch
last_request_time property

When this client last made a request, as a Unix timestamp.

Kept on the transport; exposed here because it describes the client's own pacing.

Returns:

Type Description
float

Seconds since the epoch, or 0.0 before the first request.

Examples:

>>> PubChemView().last_request_time
0.0
PROPERTY_TABLE_COLUMNS class-attribute instance-attribute

Columns of the frame get_property_table returns, in order.

Methods:
__init__(base_url='https://pubchem.ncbi.nlm.nih.gov/rest/pug_view', timeout=30, max_retries=3, backoff_factor=1.0, use_cache=True)

Initialize PubChemView API client

Parameters:

Name Type Description Default
base_url str

Base URL for PubChem PUG View API

'https://pubchem.ncbi.nlm.nih.gov/rest/pug_view'
timeout int

Request timeout in seconds

30
max_retries int

Maximum number of retry attempts

3
backoff_factor float

Backoff factor for retries

1.0
use_cache bool

Whether to use cache for lookups (default: True). When False, skips cache lookup but still stores results.

True

Examples:

>>> view = PubChemView(timeout=60, use_cache=False)
>>> view.base_url, view.timeout
('https://pubchem.ncbi.nlm.nih.gov/rest/pug_view', 60)
Source code in src/provesid/pubchemview.py
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
def __init__(self, base_url: str = "https://pubchem.ncbi.nlm.nih.gov/rest/pug_view",
             timeout: int = 30, max_retries: int = 3, backoff_factor: float = 1.0, use_cache: bool = True):
    """
    Initialize PubChemView API client

    Args:
        base_url: Base URL for PubChem PUG View API
        timeout: Request timeout in seconds
        max_retries: Maximum number of retry attempts
        backoff_factor: Backoff factor for retries
        use_cache: Whether to use cache for lookups (default: True).
                  When False, skips cache lookup but still stores results.

    Examples:
        >>> view = PubChemView(timeout=60, use_cache=False)
        >>> view.base_url, view.timeout
        ('https://pubchem.ncbi.nlm.nih.gov/rest/pug_view', 60)
    """
    self.base_url = base_url.rstrip('/')
    self.timeout = timeout
    self.max_retries = max_retries
    self.backoff_factor = backoff_factor
    self.logger = logging.getLogger(__name__)
    self.use_cache = use_cache

    # One shared transport. PubChem describes every error in the body, so
    # it supplies its own classifier rather than trusting the status code:
    # see ``provesid.pubchem.pugview_classify``.
    self._http = HTTPClient(
        min_interval=0.2,          # 5 requests per second max
        timeout=timeout,
        max_retries=max_retries,
        backoff=backoff_factor,
        max_elapsed=RETRY_WAIT_BUDGET,
        classify=pugview_classify,
        error_cls=PubChemViewError,
        not_found_cls=PubChemViewNotFoundError,
        # PubChem's five requests per second is a per-IP budget, so this
        # client shares its pacing clock with every other client aimed at
        # the same host --- a PubChemAPI in the same process, above all.
        pace_host=self.base_url,
        logger=self.logger,
    )

    self.experimental_properties = {
        "Accelerating Rate Calorimetry (ARC)": "Accelerating+Rate+Calorimetry+(ARC)",
        "Acid Value": "Acid+Value",
        "Autoignition Temperature": "Autoignition+Temperature",
        "Boiling Point": "Boiling+Point",
        "Caco2 Permeability": "Caco2+Permeability",
        "Collision Cross Section": "Collision+Cross+Section",
        "Color/Form": "Color/Form",
        "Corrosivity": "Corrosivity",
        "Decomposition": "Decomposition",
        "Density": "Density",
        "Dielectric Constant": "Dielectric+Constant",
        "Differential Scanning Calorimetry (DSC)": "Differential+Scanning+Calorimetry+(DSC)",
        "Dispersion": "Dispersion",
        "Dissociation Constants": "Dissociation+Constants",
        "Enthalpy of Sublimation": "Enthalpy+of+Sublimation",
        "Flash Point": "Flash+Point",
        "Heat of Combustion": "Heat+of+Combustion",
        "Heat of Vaporization": "Heat+of+Vaporization",
        "Henry's Law Constant": "Henry's+Law+Constant",
        "Hydrophobicity": "Hydrophobicity",
        "Ionization Efficiency": "Ionization+Efficiency",
        "Ionization Potential": "Ionization+Potential",
        "Isoelectric Point": "Isoelectric+Point",
        "Kovats Retention Index": "Kovats+Retention+Index",
        "LogP": "LogP",
        "LogS": "LogS",
        "Melting Point": "Melting+Point",
        "Odor": "Odor",
        "Odor Threshold": "Odor+Threshold",
        "Optical Rotation": "Optical+Rotation",
        "Other Experimental Properties": "Other+Experimental+Properties",
        "pH": "pH",
        "Physical Description": "Physical+Description",
        "Polymerization": "Polymerization",
        "Refractive Index": "Refractive+Index",
        "Relative Evaporation Rate": "Relative+Evaporation+Rate",
        "Self-Accelerating Decomposition Temperature (SADT)": "Self-Accelerating+Decomposition+Temperature+(SADT)",
        "Solubility": "Solubility",
        "Stability/Shelf Life": "Stability/Shelf+Life",
        "Surface Tension": "Surface+Tension",
        "Taste": "Taste",
        "Vapor Density": "Vapor+Density",
        "Vapor Pressure": "Vapor+Pressure",
        "Viscosity": "Viscosity"
    }
    """PUG-View's experimental-property headings, each mapped to the form
    it takes in a URL. [`get_property`][provesid.pubchemview.PubChemView.get_property]
    looks a heading up here and otherwise swaps its spaces for ``+``, so
    a heading missing from this dict still works."""
__cache_key__()

Identify this client for cache-key purposes.

Only the endpoint distinguishes two clients' results; timeout, retry and use_cache settings change how a call is made, not what it returns. The schema version is part of the key so that an upgrade cannot serve a stale entry of the previous shape.

Returns:

Type Description
tuple

Tuple of the class path, the configured base URL and CACHE_SCHEMA_VERSION.

Source code in src/provesid/pubchemview.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def __cache_key__(self) -> tuple:
    """
    Identify this client for cache-key purposes.

    Only the endpoint distinguishes two clients' results; timeout, retry and
    ``use_cache`` settings change how a call is made, not what it returns.
    The schema version is part of the key so that an upgrade cannot serve a
    stale entry of the previous shape.

    Returns:
        Tuple of the class path, the configured base URL and
        [`CACHE_SCHEMA_VERSION`][provesid.pubchemview.PubChemView.CACHE_SCHEMA_VERSION].
    """
    return ("provesid.pubchemview.PubChemView", self.base_url,
            self.CACHE_SCHEMA_VERSION)
clear_cache()

Delete every cached PUG-View answer, in memory and on disk.

The same as provesid.clear_cache(service='pubchemview').

Examples:

>>> view = PubChemView()
>>> view.clear_cache()
>>> view.get_cache_info()['file_count']
0
Source code in src/provesid/pubchemview.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def clear_cache(self):
    """
    Delete every cached PUG-View answer, in memory and on disk.

    The same as ``provesid.clear_cache(service='pubchemview')``.

    Examples:
        >>> view = PubChemView()
        >>> view.clear_cache()
        >>> view.get_cache_info()['file_count']
        0
    """
    from .cache import clear_cache
    clear_cache(service='pubchemview')
get_cache_info()

Size and location of the PUG-View cache.

Returns:

Type Description
Dict[str, Any]

The statistics provesid.cache.get_cache_info reports for service='pubchemview'.

Examples:

>>> PubChemView().get_cache_info()['cache_directory'].endswith('pubchemview')
True
Source code in src/provesid/pubchemview.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def get_cache_info(self) -> Dict[str, Any]:
    """
    Size and location of the PUG-View cache.

    Returns:
        The statistics
        [`provesid.cache.get_cache_info`][provesid.cache.get_cache_info]
        reports for
            ``service='pubchemview'``.

    Examples:
        >>> PubChemView().get_cache_info()['cache_directory'].endswith('pubchemview')
        True
    """
    from .cache import get_cache_info
    return get_cache_info(service='pubchemview')
get_experimental_properties(cid)

Get all experimental properties for a compound

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
Dict[str, Any]

Raw JSON response containing all experimental properties

Raises:

Type Description
PubChemViewNotFoundError

If the compound does not exist or has no experimental properties.

PubChemViewError

If the request could not be completed.

Examples:

>>> view = PubChemView()
>>> record = view.get_experimental_properties(2244)["Record"]
>>> record["RecordNumber"], record["RecordTitle"]
(2244, 'Aspirin')
Source code in src/provesid/pubchemview.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
@cached(service='pubchemview')
def get_experimental_properties(self, cid: Union[int, str]) -> Dict[str, Any]:
    """
    Get all experimental properties for a compound

    Args:
        cid: PubChem Compound ID

    Returns:
        Raw JSON response containing all experimental properties

    Raises:
        PubChemViewNotFoundError: If the compound does not exist or has no
            experimental properties.
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> view = PubChemView()
        >>> record = view.get_experimental_properties(2244)["Record"]  # doctest: +SKIP
        >>> record["RecordNumber"], record["RecordTitle"]               # doctest: +SKIP
        (2244, 'Aspirin')
    """
    url = f"{self.base_url}/data/compound/{cid}/JSON?heading=Experimental+Properties"
    return self._make_request(url)
get_property(cid, property_name)

Get a specific property for a compound

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

Name of the property (can be with spaces or plus signs)

required

Returns:

Type Description
Dict[str, Any]

Raw JSON response for the specific property. The heading sits wherever it does in the compound's table of contents, not at a fixed path; extract_property_data finds it.

Raises:

Type Description
PubChemViewNotFoundError

If the compound does not exist or does not have this heading.

PubChemViewError

If the request could not be completed.

Examples:

>>> view = PubChemView()
>>> record = view.get_property(2244, "Melting Point")["Record"]
>>> record["Section"][0]["TOCHeading"]
'Chemical and Physical Properties'
Source code in src/provesid/pubchemview.py
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
@cached(service='pubchemview')
def get_property(self, cid: Union[int, str], property_name: str) -> Dict[str, Any]:
    """
    Get a specific property for a compound

    Args:
        cid: PubChem Compound ID
        property_name: Name of the property (can be with spaces or plus signs)

    Returns:
        Raw JSON response for the specific property. The heading sits
        wherever it does in the compound's table of contents, not at a
        fixed path;
        [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
        finds it.

    Raises:
        PubChemViewNotFoundError: If the compound does not exist or does
            not have this heading.
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> view = PubChemView()
        >>> record = view.get_property(2244, "Melting Point")["Record"]  # doctest: +SKIP
        >>> record["Section"][0]["TOCHeading"]                           # doctest: +SKIP
        'Chemical and Physical Properties'
    """
    # Convert property name to URL-safe format
    if property_name in self.experimental_properties:
        url_property = self.experimental_properties[property_name]
    else:
        url_property = property_name.replace(' ', '+')

    url = f"{self.base_url}/data/compound/{cid}/JSON?heading={url_property}"
    return self._make_request(url)
extract_property_data(cid, property_name)

Extract structured property data for a specific property.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

The PUG-View heading, e.g. "Melting Point". Any heading works, not only the experimental ones.

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects, each carrying the value as PubChem wrote it plus a parsed ParsedValue holding the numbers recovered from it. An empty list means PubChem holds no such property for this compound.

Raises:

Type Description
PubChemViewError

If the request could not be completed, for example a PUG-View ServerBusy response that survived every retry. This is deliberately not reported as an empty list: a transient failure must stay distinguishable from real absence, or it gets cached as "no data" and never retried.

Examples:

>>> view = PubChemView()
>>> data = view.extract_property_data(2244, "Dissociation Constants")
>>> data[0].value, data[0].parsed.value
('3.47', 3.47)
>>> view.extract_property_data(2244, "No Such Heading")
[]
Source code in src/provesid/pubchemview.py
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
@cached(service='pubchemview', skip_if=is_empty_result)
def extract_property_data(self, cid: Union[int, str], property_name: str) -> List[PropertyData]:
    """
    Extract structured property data for a specific property.

    Args:
        cid: PubChem Compound ID
        property_name: The PUG-View heading, e.g. ``"Melting Point"``. Any
            heading works, not only the experimental ones.

    Returns:
        List of PropertyData objects, each carrying the value as PubChem
        wrote it plus a ``parsed``
        [`ParsedValue`][provesid.pubchemview_parse.ParsedValue] holding the
        numbers recovered from it. An empty list means PubChem holds no
        such property for this compound.

    Raises:
        PubChemViewError: If the request could not be completed, for example
            a PUG-View ``ServerBusy`` response that survived every retry.
            This is deliberately *not* reported as an empty list: a
            transient failure must stay distinguishable from real absence,
            or it gets cached as "no data" and never retried.

    Examples:
        >>> view = PubChemView()
        >>> data = view.extract_property_data(2244, "Dissociation Constants")  # doctest: +SKIP
        >>> data[0].value, data[0].parsed.value                                # doctest: +SKIP
        ('3.47', 3.47)
        >>> view.extract_property_data(2244, "No Such Heading")               # doctest: +SKIP
        []
    """
    try:
        response = self.get_property(cid, property_name)
    except PubChemViewNotFoundError:
        self.logger.debug(f"Property '{property_name}' not present for CID {cid}")
        return []
    return self._parse_property_response(response)
extract_all_experimental_properties(cid)

Extract all experimental properties for a compound in structured format

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
Dict[str, List[PropertyData]]

Dictionary mapping property names to lists of PropertyData objects, in the order PubChem lists the headings. Empty when the compound has no experimental properties.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> view = PubChemView()
>>> props = view.extract_all_experimental_properties(2244)
>>> list(props)[:4]
['Physical Description', 'Color/Form', 'Odor', 'Boiling Point']
>>> props["Melting Point"][0].value
'275 °F (NTP, 1992)'
Source code in src/provesid/pubchemview.py
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
@cached(service='pubchemview', skip_if=is_empty_result)
def extract_all_experimental_properties(self, cid: Union[int, str]) -> Dict[str, List[PropertyData]]:
    """
    Extract all experimental properties for a compound in structured format

    Args:
        cid: PubChem Compound ID

    Returns:
        Dictionary mapping property names to lists of PropertyData objects,
        in the order PubChem lists the headings. Empty when the compound
        has no experimental properties.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> view = PubChemView()
        >>> props = view.extract_all_experimental_properties(2244)  # doctest: +SKIP
        >>> list(props)[:4]                                        # doctest: +SKIP
        ['Physical Description', 'Color/Form', 'Odor', 'Boiling Point']
        >>> props["Melting Point"][0].value                        # doctest: +SKIP
        '275 °F (NTP, 1992)'
    """
    try:
        response = self.get_experimental_properties(cid)
        return self._parse_all_properties_response(response)
    except PubChemViewNotFoundError:
        self.logger.warning(f"No experimental properties found for CID {cid}")
        return {}
get_available_properties(cid)

Get list of available experimental properties for a compound

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[str]

List of available property names: the experimental headings this compound has values under, in PubChem's order. Empty when it has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> PubChemView().get_available_properties(2244)[:3]
['Physical Description', 'Color/Form', 'Odor']
Source code in src/provesid/pubchemview.py
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
@cached(service='pubchemview', skip_if=is_empty_result)
def get_available_properties(self, cid: Union[int, str]) -> List[str]:
    """
    Get list of available experimental properties for a compound

    Args:
        cid: PubChem Compound ID

    Returns:
        List of available property names: the experimental headings this
        compound has values under, in PubChem's order. Empty when it has
        none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> PubChemView().get_available_properties(2244)[:3]  # doctest: +SKIP
        ['Physical Description', 'Color/Form', 'Odor']
    """
    try:
        response = self.get_experimental_properties(cid)
        return list(self._parse_all_properties_response(response).keys())
    except PubChemViewNotFoundError:
        return []
get_property_summary(cid, property_name)

Get a summary of a property including all values, units, and references

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

Name of the property

required

Returns:

Type Description
Dict[str, Any]

Dictionary with the raw strings under values, the numbers recovered from them under numeric_values and numeric_values_si, plus the references, units and conditions seen across the entries and a count. A range or a word contributes to values but not to numeric_values, so the two lists need not line up. units, units_si and conditions are sets as lists, in no particular order.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> summary = PubChemView().get_property_summary(2244, "Melting Point")
>>> summary["values"][:2], summary["numeric_values"][:2]
(['275 °F (NTP, 1992)', '138-140'], [275.0, 135.0])
Source code in src/provesid/pubchemview.py
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
@cached(service='pubchemview', skip_if=lambda result: not result.get('values'))
def get_property_summary(self, cid: Union[int, str], property_name: str) -> Dict[str, Any]:
    """
    Get a summary of a property including all values, units, and references

    Args:
        cid: PubChem Compound ID
        property_name: Name of the property

    Returns:
        Dictionary with the raw strings under ``values``, the numbers
        recovered from them under ``numeric_values`` and
        ``numeric_values_si``, plus the references, units and conditions
        seen across the entries and a ``count``. A range or a word
        contributes to ``values`` but not to ``numeric_values``, so the
        two lists need not line up. ``units``, ``units_si`` and
        ``conditions`` are sets as lists, in no particular order.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> summary = PubChemView().get_property_summary(2244, "Melting Point")  # doctest: +SKIP
        >>> summary["values"][:2], summary["numeric_values"][:2]                 # doctest: +SKIP
        (['275 °F (NTP, 1992)', '138-140'], [275.0, 135.0])
    """
    property_data = self.extract_property_data(cid, property_name)

    if not property_data:
        return {"property": property_name, "values": [], "numeric_values": [],
                "numeric_values_si": [], "references": [], "units": [],
                "units_si": [], "conditions": [], "count": 0}

    parsed_values = [data.parsed or parse_value(data.value, data.heading)
                     for data in property_data]

    summary = {
        "property": property_name,
        "values": [data.value for data in property_data],
        # The numbers behind those strings, for the common case of wanting
        # a range or a mean rather than the prose.
        "numeric_values": [parsed.value for parsed in parsed_values
                           if parsed.value is not None],
        "numeric_values_si": [parsed.value_si for parsed in parsed_values
                              if parsed.value_si is not None],
        "references": [data.reference for data in property_data if data.reference],
        "units": list(set([data.unit for data in property_data if data.unit])),
        "units_si": list({parsed.unit_si for parsed in parsed_values
                          if parsed.unit_si}),
        "conditions": list(set([data.conditions for data in property_data if data.conditions])),
        "count": len(property_data)
    }

    return summary
get_melting_point(cid)

Get melting point data for a compound.

extract_property_data(cid, "Melting Point"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_melting_point(2244)][:2]
['275 °F (NTP, 1992)', '138-140']
Source code in src/provesid/pubchemview.py
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
@cached(service='pubchemview', skip_if=is_empty_result)
def get_melting_point(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get melting point data for a compound.

    ``extract_property_data(cid, "Melting Point")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_melting_point(2244)][:2]  # doctest: +SKIP
        ['275 °F (NTP, 1992)', '138-140']
    """
    return self.extract_property_data(cid, "Melting Point")
get_boiling_point(cid)

Get boiling point data for a compound.

extract_property_data(cid, "Boiling Point"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_boiling_point(2244)][:2]
['284 °F at 760 mmHg (decomposes) (NTP, 1992)', '140 °C']
Source code in src/provesid/pubchemview.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
@cached(service='pubchemview', skip_if=is_empty_result)
def get_boiling_point(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get boiling point data for a compound.

    ``extract_property_data(cid, "Boiling Point")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_boiling_point(2244)][:2]  # doctest: +SKIP
        ['284 °F at 760 mmHg (decomposes) (NTP, 1992)', '140 °C']
    """
    return self.extract_property_data(cid, "Boiling Point")
get_density(cid)

Get density data for a compound.

extract_property_data(cid, "Density"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_density(2244)][:2]
['1.4 (NTP, 1992) - Denser than water; will sink', '1.40']
Source code in src/provesid/pubchemview.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
@cached(service='pubchemview', skip_if=is_empty_result)
def get_density(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get density data for a compound.

    ``extract_property_data(cid, "Density")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_density(2244)][:2]  # doctest: +SKIP
        ['1.4 (NTP, 1992) - Denser than water; will sink', '1.40']
    """
    return self.extract_property_data(cid, "Density")
get_solubility(cid)

Get solubility data for a compound.

extract_property_data(cid, "Solubility"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_solubility(2244)][:2]
['less than 1 mg/mL at 73 °F (NTP, 1992)', '10 mg/mL']
Source code in src/provesid/pubchemview.py
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
@cached(service='pubchemview', skip_if=is_empty_result)
def get_solubility(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get solubility data for a compound.

    ``extract_property_data(cid, "Solubility")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_solubility(2244)][:2]  # doctest: +SKIP
        ['less than 1 mg/mL at 73 °F (NTP, 1992)', '10 mg/mL']
    """
    return self.extract_property_data(cid, "Solubility")
get_flash_point(cid)

Get flash point data for a compound.

extract_property_data(cid, "Flash Point"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_flash_point(2244)][:2]
['482 °F (NTP, 1992)']
Source code in src/provesid/pubchemview.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
@cached(service='pubchemview', skip_if=is_empty_result)
def get_flash_point(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get flash point data for a compound.

    ``extract_property_data(cid, "Flash Point")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_flash_point(2244)][:2]  # doctest: +SKIP
        ['482 °F (NTP, 1992)']
    """
    return self.extract_property_data(cid, "Flash Point")
get_vapor_pressure(cid)

Get vapor pressure data for a compound.

extract_property_data(cid, "Vapor Pressure"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_vapor_pressure(2244)][:2]
['0 mmHg (approx) (NIOSH, 2024)', '2.52X10-5 mm Hg at 25 °C (calc)']
Source code in src/provesid/pubchemview.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
@cached(service='pubchemview', skip_if=is_empty_result)
def get_vapor_pressure(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get vapor pressure data for a compound.

    ``extract_property_data(cid, "Vapor Pressure")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_vapor_pressure(2244)][:2]  # doctest: +SKIP
        ['0 mmHg (approx) (NIOSH, 2024)', '2.52X10-5 mm Hg at 25 °C (calc)']
    """
    return self.extract_property_data(cid, "Vapor Pressure")
get_viscosity(cid)

Get viscosity data for a compound.

extract_property_data(cid, "Viscosity"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_viscosity(702)][:2]
['1.074 mPa.s at 25 °C', '1.074 mPa*s at 20 °C']
Source code in src/provesid/pubchemview.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
@cached(service='pubchemview', skip_if=is_empty_result)
def get_viscosity(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get viscosity data for a compound.

    ``extract_property_data(cid, "Viscosity")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_viscosity(702)][:2]  # doctest: +SKIP
        ['1.074 mPa.s at 25 °C', '1.074 mPa*s at 20 °C']
    """
    return self.extract_property_data(cid, "Viscosity")
get_logp(cid)

Get LogP data for a compound.

extract_property_data(cid, "LogP"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_logp(2244)][:2]
['1.18', 'log Kow = 1.19']
Source code in src/provesid/pubchemview.py
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
@cached(service='pubchemview', skip_if=is_empty_result)
def get_logp(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get LogP data for a compound.

    ``extract_property_data(cid, "LogP")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_logp(2244)][:2]  # doctest: +SKIP
        ['1.18', 'log Kow = 1.19']
    """
    return self.extract_property_data(cid, "LogP")
get_refractive_index(cid)

Get refractive index data for a compound.

extract_property_data(cid, "Refractive Index"), cached separately.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects; empty when PubChem has none.

Raises:

Type Description
PubChemViewError

If the request could not be completed.

Examples:

>>> [d.value for d in PubChemView().get_refractive_index(702)][:2]
['Index of refraction: 1.3611 at 20 °C/D', '1.364']
Source code in src/provesid/pubchemview.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
@cached(service='pubchemview', skip_if=is_empty_result)
def get_refractive_index(self, cid: Union[int, str]) -> List[PropertyData]:
    """
    Get refractive index data for a compound.

    ``extract_property_data(cid, "Refractive Index")``, cached separately.

    Args:
        cid: PubChem Compound ID

    Returns:
        List of PropertyData objects; empty when PubChem has none.

    Raises:
        PubChemViewError: If the request could not be completed.

    Examples:
        >>> [d.value for d in PubChemView().get_refractive_index(702)][:2]  # doctest: +SKIP
        ['Index of refraction: 1.3611 at 20 °C/D', '1.364']
    """
    return self.extract_property_data(cid, "Refractive Index")
batch_extract_properties(cid, property_names)

Extract multiple properties for a compound

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_names List[str]

List of property names to extract

required

Returns:

Type Description
Dict[str, List[PropertyData]]

Dictionary mapping property names to PropertyData lists.

Note

One property failing does not abort the batch: that entry is logged at WARNING and comes back as an empty list, so here — unlike in extract_property_data — an empty list does not prove the property is absent. Call extract_property_data directly when the difference matters.

Examples:

>>> found = PubChemView().batch_extract_properties(
...     2244, ["Melting Point", "Boiling Point"])
>>> {name: len(values) for name, values in found.items()}
{'Melting Point': 7, 'Boiling Point': 4}
Source code in src/provesid/pubchemview.py
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
def batch_extract_properties(self, cid: Union[int, str],
                            property_names: List[str]) -> Dict[str, List[PropertyData]]:
    """
    Extract multiple properties for a compound

    Args:
        cid: PubChem Compound ID
        property_names: List of property names to extract

    Returns:
        Dictionary mapping property names to PropertyData lists.

    Note:
        One property failing does not abort the batch: that entry is logged
        at WARNING and comes back as an empty list, so here — unlike in
        [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
        — an empty list does not prove the property is absent. Call
        ``extract_property_data`` directly when the difference matters.

    Examples:
        >>> found = PubChemView().batch_extract_properties(
        ...     2244, ["Melting Point", "Boiling Point"])         # doctest: +SKIP
        >>> {name: len(values) for name, values in found.items()}  # doctest: +SKIP
        {'Melting Point': 7, 'Boiling Point': 4}
    """
    results = {}
    for prop_name in property_names:
        try:
            results[prop_name] = self.extract_property_data(cid, prop_name)
        except Exception as e:
            self.logger.warning(f"Failed to extract {prop_name} for CID {cid}: {e}")
            results[prop_name] = []

    return results
export_properties_to_dict(property_data_list)

Convert PropertyData objects to plain dictionaries for serialization.

Parameters:

Name Type Description Default
property_data_list List[PropertyData]

List of PropertyData objects, as returned by extract_property_data or any of the convenience getters.

required

Returns:

Type Description
List[Dict[str, Any]]

One dict per value, carrying the original string, the reference, and the parsed numbers flattened into top-level keys (numeric_value, value_min, value_si, unit_si, operator, qualitative, temperature_c) so the result can go straight into json.dumps or pd.DataFrame.

Examples:

>>> from provesid.pubchemview_parse import parse_value
>>> data = PropertyData(value="135 °C", heading="Melting Point",
...                     parsed=parse_value("135 °C", "Melting Point"))
>>> row = PubChemView().export_properties_to_dict([data])[0]
>>> row["numeric_value"], row["value_si"], row["unit_si"]
(135.0, 408.15, 'K')
Source code in src/provesid/pubchemview.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
def export_properties_to_dict(self, property_data_list: List[PropertyData]) -> List[Dict[str, Any]]:
    """
    Convert PropertyData objects to plain dictionaries for serialization.

    Args:
        property_data_list: List of PropertyData objects, as returned by
            [`extract_property_data`][provesid.pubchemview.PubChemView.extract_property_data]
            or any of the convenience getters.

    Returns:
        One dict per value, carrying the original string, the reference, and
        the parsed numbers flattened into top-level keys
        (``numeric_value``, ``value_min``, ``value_si``, ``unit_si``,
        ``operator``, ``qualitative``, ``temperature_c``) so the result can
        go straight into ``json.dumps`` or ``pd.DataFrame``.

    Examples:
        >>> from provesid.pubchemview_parse import parse_value
        >>> data = PropertyData(value="135 °C", heading="Melting Point",
        ...                     parsed=parse_value("135 °C", "Melting Point"))
        >>> row = PubChemView().export_properties_to_dict([data])[0]
        >>> row["numeric_value"], row["value_si"], row["unit_si"]
        (135.0, 408.15, 'K')
    """
    rows = []
    for data in property_data_list:
        parsed = data.parsed or parse_value(data.value, data.heading)
        rows.append({
            "value": data.value,
            "unit": data.unit,
            "conditions": data.conditions,
            "reference": data.reference,
            "reference_number": data.reference_number,
            "description": data.description,
            "name": data.name,
            "heading": data.heading,
            # The parsed numbers are flattened rather than nested, so the
            # result stays directly serialisable to JSON or a DataFrame.
            "numeric_value": parsed.value,
            "value_min": parsed.value_min,
            "value_max": parsed.value_max,
            "value_si": parsed.value_si,
            "value_min_si": parsed.value_min_si,
            "value_max_si": parsed.value_max_si,
            "unit_si": parsed.unit_si,
            "operator": parsed.operator,
            "qualitative": parsed.qualitative,
            "temperature_c": parsed.temperature_c,
        })
    return rows
get_property_table(cid, property_name)

Get a table of property values, parsed into numbers, with references.

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID.

required
property_name str

The PUG-View heading, e.g. "Melting Point". Any heading works, not only the experimental ones.

required

Returns:

Type Description
DataFrame

A DataFrame with the columns in PROPERTY_TABLE_COLUMNS:

  • StringWithMarkup — the value exactly as PubChem wrote it.
  • ExperimentalValue — the single number, as a float; NaN when the entry reports a range or no number at all.
  • ValueMin / ValueMax — the bounds, equal to ExperimentalValue for a single value, so a numeric filter needs no special case for ranges.
  • Unit — normalised, so torr and mm Hg agree.
  • ValueSI / ValueMinSI / ValueMaxSI / UnitSI — the same quantity in SI units, or NaN where the unit has no unambiguous SI equivalent (a percentage, a ppm).
  • Operator — >, <, >=, <= or ~ when the entry bounds the value rather than stating it.
  • Qualitative — the word that replaced the number, such as insoluble.
  • Temperature — the temperature the measurement was made at, in °C. A condition, not the value.
  • FullReference — the resolved citation.

The frame is empty, with these columns, when PubChem holds no such property for this compound.

Raises:

Type Description
PubChemViewError

If the request could not be completed. An empty frame always means "no such data", never "the fetch failed".

Examples:

>>> view = PubChemView()
>>> table = view.get_property_table(2244, "Melting Point")
>>> table[["StringWithMarkup", "ValueMin", "ValueMax", "Unit", "ValueSI"]].head(2)
     StringWithMarkup  ValueMin  ValueMax Unit  ValueSI
0  275 °F (NTP, 1992)     275.0     275.0   °F   408.15
1             138-140     138.0     140.0   °C      NaN
Source code in src/provesid/pubchemview.py
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
@cached(service='pubchemview', skip_if=is_empty_result)
def get_property_table(self, cid: Union[int, str], property_name: str) -> pd.DataFrame:
    """
    Get a table of property values, parsed into numbers, with references.

    Args:
        cid: PubChem Compound ID.
        property_name: The PUG-View heading, e.g. ``"Melting Point"``. Any
            heading works, not only the experimental ones.

    Returns:
        A DataFrame with the columns in
        [`PROPERTY_TABLE_COLUMNS`][provesid.pubchemview.PubChemView.PROPERTY_TABLE_COLUMNS]:

        - ``StringWithMarkup`` — the value exactly as PubChem wrote it.
        - ``ExperimentalValue`` — the single number, as a float; NaN when
            the entry reports a range or no number at all.
        - ``ValueMin`` / ``ValueMax`` — the bounds, equal to
            ``ExperimentalValue`` for a single value, so a numeric filter
            needs no special case for ranges.
        - ``Unit`` — normalised, so ``torr`` and ``mm Hg`` agree.
        - ``ValueSI`` / ``ValueMinSI`` / ``ValueMaxSI`` / ``UnitSI`` — the
            same quantity in SI units, or NaN where the unit has no
            unambiguous SI equivalent (a percentage, a ppm).
        - ``Operator`` — ``>``, ``<``, ``>=``, ``<=`` or ``~`` when the
            entry bounds the value rather than stating it.
        - ``Qualitative`` — the word that replaced the number, such as
            ``insoluble``.
        - ``Temperature`` — the temperature the measurement was made at, in
            °C. A *condition*, not the value.
        - ``FullReference`` — the resolved citation.

        The frame is empty, with these columns, when PubChem holds no such
        property for this compound.

    Raises:
        PubChemViewError: If the request could not be completed. An empty
            frame always means "no such data", never "the fetch failed".

    Examples:
        >>> view = PubChemView()
        >>> table = view.get_property_table(2244, "Melting Point")  # doctest: +SKIP
        >>> table[["StringWithMarkup", "ValueMin", "ValueMax", "Unit", "ValueSI"]].head(2)  # doctest: +SKIP
             StringWithMarkup  ValueMin  ValueMax Unit  ValueSI
        0  275 °F (NTP, 1992)     275.0     275.0   °F   408.15
        1             138-140     138.0     140.0   °C      NaN
    """
    try:
        response = self.get_property(cid, property_name)
        reference_map = self._extract_reference_map(response)
        property_data = self._parse_property_response(response)
    except PubChemViewNotFoundError:
        self.logger.debug(f"Property '{property_name}' not present for CID {cid}")
        return pd.DataFrame(columns=self.PROPERTY_TABLE_COLUMNS)
    except PubChemViewError:
        # Transport failure: let it surface rather than pass an empty table
        # off as "this compound has no data".
        raise

    rows = []
    for data in property_data:
        full_reference = ""
        if data.reference_number and data.reference_number in reference_map:
            full_reference = reference_map[data.reference_number]
        elif data.reference:
            full_reference = data.reference

        parsed = data.parsed or parse_value(data.value, data.heading)
        rows.append({
            "CID": cid,
            "Heading": data.heading,
            "StringWithMarkup": data.value,
            "ExperimentalValue": parsed.value,
            "ValueMin": parsed.value_min,
            "ValueMax": parsed.value_max,
            "Unit": parsed.unit,
            "ValueSI": parsed.value_si,
            "ValueMinSI": parsed.value_min_si,
            "ValueMaxSI": parsed.value_max_si,
            "UnitSI": parsed.unit_si,
            "Operator": parsed.operator,
            "Qualitative": parsed.qualitative,
            "Temperature": parsed.temperature_c,
            "Conditions": parsed.conditions,
            "FullReference": full_reference,
        })

    return pd.DataFrame(rows, columns=self.PROPERTY_TABLE_COLUMNS)

Functions:

get_experimental_property(cid, property_name)

Convenience function to get experimental property data

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

Name of the property

required

Returns:

Type Description
List[PropertyData]

List of PropertyData objects

Examples:

>>> [d.value for d in get_experimental_property(2244, "LogP")][:2]
['1.18', 'log Kow = 1.19']
Source code in src/provesid/pubchemview.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def get_experimental_property(cid: Union[int, str], property_name: str) -> List[PropertyData]:
    """
    Convenience function to get experimental property data

    Args:
        cid: PubChem Compound ID
        property_name: Name of the property

    Returns:
        List of PropertyData objects

    Examples:
        >>> [d.value for d in get_experimental_property(2244, "LogP")][:2]  # doctest: +SKIP
        ['1.18', 'log Kow = 1.19']
    """
    pugview = PubChemView()
    return pugview.extract_property_data(cid, property_name)

get_all_experimental_properties(cid)

Convenience function to get all experimental properties

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required

Returns:

Type Description
Dict[str, List[PropertyData]]

Dictionary mapping property names to PropertyData lists

Examples:

>>> len(get_all_experimental_properties(2244))
16
Source code in src/provesid/pubchemview.py
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
def get_all_experimental_properties(cid: Union[int, str]) -> Dict[str, List[PropertyData]]:
    """
    Convenience function to get all experimental properties

    Args:
        cid: PubChem Compound ID

    Returns:
        Dictionary mapping property names to PropertyData lists

    Examples:
        >>> len(get_all_experimental_properties(2244))           # doctest: +SKIP
        16
    """
    pugview = PubChemView()
    return pugview.extract_all_experimental_properties(cid)

get_property_values_only(cid, property_name)

Convenience function to get just the property values as strings

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

Name of the property

required

Returns:

Type Description
List[str]

List of property value strings

Examples:

>>> get_property_values_only(2244, "LogP")
['1.18', 'log Kow = 1.19', '1.19', '1.19', '1.28']
Source code in src/provesid/pubchemview.py
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
def get_property_values_only(cid: Union[int, str], property_name: str) -> List[str]:
    """
    Convenience function to get just the property values as strings

    Args:
        cid: PubChem Compound ID
        property_name: Name of the property

    Returns:
        List of property value strings

    Examples:
        >>> get_property_values_only(2244, "LogP")               # doctest: +SKIP
        ['1.18', 'log Kow = 1.19', '1.19', '1.19', '1.28']
    """
    pugview = PubChemView()
    property_data = pugview.extract_property_data(cid, property_name)
    return [data.value for data in property_data if data.value]

get_property_table(cid, property_name)

Convenience function to get a comprehensive property table with full references

Parameters:

Name Type Description Default
cid Union[int, str]

PubChem Compound ID

required
property_name str

Name of the experimental property

required

Returns:

Type Description
DataFrame

pandas DataFrame with the columns listed in PubChemView.PROPERTY_TABLE_COLUMNS.

Examples:

>>> table = get_property_table(2244, "LogP")
>>> table["ExperimentalValue"].tolist()[:3]
[1.18, 1.19, 1.19]
Source code in src/provesid/pubchemview.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
def get_property_table(cid: Union[int, str], property_name: str) -> pd.DataFrame:
    """
    Convenience function to get a comprehensive property table with full references

    Args:
        cid: PubChem Compound ID
        property_name: Name of the experimental property

    Returns:
        pandas DataFrame with the columns listed in
        [`PubChemView.PROPERTY_TABLE_COLUMNS`][provesid.pubchemview.PubChemView.PROPERTY_TABLE_COLUMNS].

    Examples:
        >>> table = get_property_table(2244, "LogP")             # doctest: +SKIP
        >>> table["ExperimentalValue"].tolist()[:3]              # doctest: +SKIP
        [1.18, 1.19, 1.19]
    """
    pugview = PubChemView()
    return pugview.get_property_table(cid, property_name)

provesid.pubchemview_parse

One parser for the free-text values PubChem's PUG-View returns.

PUG-View reports every experimental property as prose written by whoever deposited it: "138-140 °C", "8.5X10-5 mm Hg at 25 °C", "greater than or equal to 100 mg/mL", "Vapor pressure, kPa at 20°C: 24". A caller that wants to compare two compounds has to turn that back into numbers, and doing it per call site is how PROVESID ended up with two parsers that disagreed with each other.

This module holds the only one. parse_value takes the string and the heading it was found under, and returns a ParsedValue carrying the number (or the range), the unit as written, the same quantity in SI units, the temperature the measurement was made at, and any comparison operator or qualitative term that replaced the number.

Nothing here makes a network request, so it can be tested against real strings without touching PubChem.

Examples:

>>> parse_value("138-140 °C", "Melting Point")
ParsedValue(text='138-140 °C', value=None, value_min=138.0, value_max=140.0, unit='°C', ...)
>>> round(parse_value("8.5X10-5 mm Hg at 25 °C", "Vapor Pressure").value_si, 7)
0.0113324
>>> parse_value("Insoluble in water", "Solubility").qualitative
'insoluble'

Attributes

UNIT_ALIASES module-attribute

Spellings that mean the same unit, mapped to the one this module reports. PubChem's depositors write the same unit half a dozen ways, and a caller grouping by unit should not see mmHg, mm Hg and torr as three different things.

UNIT_TO_SI module-attribute

Conversion of a reported unit to the SI unit this module reports alongside it, as (si_unit, scale, offset) with si = value * scale + offset. The offset is what makes a temperature range need its ends converted separately rather than scaled.

Deliberately absent: %, ppm, ppb and the w/w and v/v variants. They are compositions, not concentrations, and turning one into kg/m³ needs a density this module does not have. A guess there would be worse than the honest None a caller can test for.

CELSIUS_HEADINGS module-attribute

Headings whose bare numbers are degrees Celsius. PubChem's depositors often leave the unit off a melting point, and a melting point without a unit is not ambiguous in practice.

DIMENSIONLESS_HEADINGS module-attribute

Headings whose values are dimensionless, so that a bare number is a complete answer rather than a value missing its unit.

QUALITATIVE_TERMS module-attribute

Words that stand in place of a number. PubChem records "insoluble" as often as it records a solubility, and dropping the row loses the information that somebody measured it and found it negligible.

ICSC_SOLUBILITY_TERMS module-attribute

The International Chemical Safety Cards' words for water solubility, as in "Solubility in water: none" or "…, g/100ml at 20 °C: 0.25 (poor)". none, poor and good are ordinary English, so unlike QUALITATIVE_TERMS they are matched only in that shape, never anywhere in a string. The cards also use miscible and the pharmacopoeia's terms, which are in QUALITATIVE_TERMS.

Classes

ParsedValue dataclass

A PUG-View value string turned into numbers, with the original kept.

Attributes:

Name Type Description
text str

The string exactly as PubChem returned it. Always populated, so nothing this parser fails to understand is ever lost.

value Optional[float]

The single number the string reports, or None when it reports a range, a qualitative term, or nothing numeric at all.

value_min Optional[float]

Low end of the reported quantity. For a single value this equals value, so a numeric filter can use value_min and value_max without special-casing ranges.

value_max Optional[float]

High end of the reported quantity.

unit Optional[str]

The unit as PubChem wrote it, with the spelling normalised through UNIT_ALIASES — torr and mm Hg both report as mmHg. None when the quantity is dimensionless or no unit was found.

value_si Optional[float]

value expressed in unit_si. None when there is no single value, or when the unit has no unambiguous SI equivalent.

value_min_si Optional[float]

value_min expressed in unit_si.

value_max_si Optional[float]

value_max expressed in unit_si.

unit_si Optional[str]

The SI unit the *_si fields are expressed in: K, Pa, kg/m³, mol/m³, Pa·s, m²/s or N/m. None for a dimensionless quantity and for units that cannot be converted without information the string does not carry — a percentage or a ppm needs a density to become a concentration.

temperature_c Optional[float]

The temperature the measurement was made at, in degrees Celsius, read from an at 25 °C clause. This is a condition, not the value: for a melting point of 138 °C the value is 138 and this field is None.

operator Optional[str]

'>', '<', '>=', '<=' or '~' when the string bounds the quantity rather than stating it, as in "greater than 100 mg/mL". The bound itself is in value.

qualitative Optional[str]

The term that stood in place of a number, lowercased — 'insoluble', 'miscible', 'negligible', or an ICSC word such as 'poor' or 'none' (the string, not None). Set whether or not a number was also found.

conditions Optional[str]

Any remaining qualifying text, such as a pressure the measurement was made at or a /Estimated/ note.

Examples:

>>> v = parse_value("2.47 cP at 20 °C", "Viscosity")
>>> v.value, v.unit, round(v.value_si, 5), v.unit_si, v.temperature_c
(2.47, 'cP', 0.00247, 'Pa·s', 20.0)
Source code in src/provesid/pubchemview_parse.py
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
@dataclass(frozen=True)
class ParsedValue:
    """
    A PUG-View value string turned into numbers, with the original kept.

    Attributes:
        text: The string exactly as PubChem returned it. Always populated, so
            nothing this parser fails to understand is ever lost.
        value: The single number the string reports, or None when it reports a
            range, a qualitative term, or nothing numeric at all.
        value_min: Low end of the reported quantity. For a single value this
            equals ``value``, so a numeric filter can use ``value_min`` and
            ``value_max`` without special-casing ranges.
        value_max: High end of the reported quantity.
        unit: The unit as PubChem wrote it, with the spelling normalised
            through [`UNIT_ALIASES`][provesid.pubchemview_parse.UNIT_ALIASES] —
            ``torr`` and ``mm Hg`` both report as ``mmHg``. None when the
            quantity is dimensionless or no unit was found.
        value_si: ``value`` expressed in
            [`unit_si`][provesid.pubchemview_parse.ParsedValue]. None when
            there is no single value, or when the unit has no unambiguous SI
            equivalent.
        value_min_si: ``value_min`` expressed in
            [`unit_si`][provesid.pubchemview_parse.ParsedValue].
        value_max_si: ``value_max`` expressed in
            [`unit_si`][provesid.pubchemview_parse.ParsedValue].
        unit_si: The SI unit the ``*_si`` fields are expressed in: ``K``,
            ``Pa``, ``kg/m³``, ``mol/m³``, ``Pa·s``, ``m²/s`` or ``N/m``. None
            for a dimensionless quantity and for units that cannot be converted
            without information the string does not carry — a percentage or a
            ppm needs a density to become a concentration.
        temperature_c: The temperature the measurement was made at, in degrees
            Celsius, read from an ``at 25 °C`` clause. This is a *condition*,
            not the value: for a melting point of ``138 °C`` the value is 138
            and this field is None.
        operator: ``'>'``, ``'<'``, ``'>='``, ``'<='`` or ``'~'`` when the
            string bounds the quantity rather than stating it, as in
            ``"greater than 100 mg/mL"``. The bound itself is in ``value``.
        qualitative: The term that stood in place of a number, lowercased —
            ``'insoluble'``, ``'miscible'``, ``'negligible'``, or an ICSC
            word such as ``'poor'`` or ``'none'`` (the string, not None).
            Set whether or not a number was also found.
        conditions: Any remaining qualifying text, such as a pressure the
            measurement was made at or a ``/Estimated/`` note.

    Examples:
        >>> v = parse_value("2.47 cP at 20 °C", "Viscosity")
        >>> v.value, v.unit, round(v.value_si, 5), v.unit_si, v.temperature_c
        (2.47, 'cP', 0.00247, 'Pa·s', 20.0)
    """

    text: str
    value: Optional[float] = None
    value_min: Optional[float] = None
    value_max: Optional[float] = None
    unit: Optional[str] = None
    value_si: Optional[float] = None
    value_min_si: Optional[float] = None
    value_max_si: Optional[float] = None
    unit_si: Optional[str] = None
    temperature_c: Optional[float] = None
    operator: Optional[str] = None
    qualitative: Optional[str] = None
    conditions: Optional[str] = None

    @property
    def is_numeric(self) -> bool:
        """
        Whether a number was recovered from the string.

        Returns:
            True when either a single value or a range was parsed.

        Examples:
            >>> parse_value("138-140 °C", "Melting Point").is_numeric
            True
            >>> parse_value("Insoluble in water", "Solubility").is_numeric
            False
        """
        return self.value is not None or self.value_min is not None

    @property
    def is_range(self) -> bool:
        """
        Whether the string reported a range rather than a single number.

        Returns:
            True when the two ends differ.

        Examples:
            >>> parse_value("138-140 °C", "Melting Point").is_range
            True
            >>> parse_value("135 °C", "Melting Point").is_range
            False
        """
        return (self.value is None and self.value_min is not None
                and self.value_max is not None)
Attributes
is_numeric property

Whether a number was recovered from the string.

Returns:

Type Description
bool

True when either a single value or a range was parsed.

Examples:

>>> parse_value("138-140 °C", "Melting Point").is_numeric
True
>>> parse_value("Insoluble in water", "Solubility").is_numeric
False
is_range property

Whether the string reported a range rather than a single number.

Returns:

Type Description
bool

True when the two ends differ.

Examples:

>>> parse_value("138-140 °C", "Melting Point").is_range
True
>>> parse_value("135 °C", "Melting Point").is_range
False

Functions:

parse_value(text, heading=None)

Parse one PUG-View value string into numbers, units and conditions.

This is the only parser in the package for these strings. Every PubChemView method that reports a value routes through it, so a fix here reaches all of them.

Parameters:

Name Type Description Default
text Optional[str]

The value string, as PubChem returned it. None or empty gives a ParsedValue carrying nothing but the (empty) text.

required
heading Optional[str]

The PUG-View heading the value was found under, e.g. "Melting Point". Used for two decisions a string alone cannot settle: a bare number under a temperature heading is degrees Celsius, and a bare number under a dimensionless heading such as "LogP" or "Dissociation Constants" is complete as it stands. Passing None is safe and simply declines both hints.

None

Returns:

Type Description
ParsedValue

A ParsedValue. It always carries text; every other field is None when the string did not state it. Nothing is invented: an unrecognised unit is reported as written with no SI conversion, and a string with no number gives value is None rather than a zero.

Examples:

>>> parse_value("138-140 °C", "Melting Point").value_max_si
413.15
>>> parse_value("greater than or equal to 100 mg/mL", "Solubility").operator
'>='
>>> parse_value("2.7e+0 at 25 °C /Estimated/", "Vapor Pressure").conditions
'Estimated'
Source code in src/provesid/pubchemview_parse.py
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
def parse_value(text: Optional[str], heading: Optional[str] = None) -> ParsedValue:
    """
    Parse one PUG-View value string into numbers, units and conditions.

    This is the only parser in the package for these strings. Every PubChemView
    method that reports a value routes through it, so a fix here reaches all of
    them.

    Args:
        text: The value string, as PubChem returned it. None or empty gives a
            [`ParsedValue`][provesid.pubchemview_parse.ParsedValue] carrying
            nothing but the (empty) text.
        heading: The PUG-View heading the value was found under, e.g.
            ``"Melting Point"``. Used for two decisions a string alone cannot
            settle: a bare number under a temperature heading is degrees
            Celsius, and a bare number under a dimensionless heading such as
            ``"LogP"`` or ``"Dissociation Constants"`` is complete as it
            stands. Passing None is safe and simply declines both hints.

    Returns:
        A [`ParsedValue`][provesid.pubchemview_parse.ParsedValue]. It always
        carries ``text``; every other field is None when the string did not
        state it. Nothing is invented: an unrecognised unit is reported as
        written with no SI conversion, and a string with no number gives
        ``value is None`` rather than a zero.

    Examples:
        >>> parse_value("138-140 °C", "Melting Point").value_max_si
        413.15
        >>> parse_value("greater than or equal to 100 mg/mL", "Solubility").operator
        '>='
        >>> parse_value("2.7e+0 at 25 °C /Estimated/", "Vapor Pressure").conditions
        'Estimated'
    """
    if not text:
        return ParsedValue(text=text or '')

    normalised = _normalise_text(text)

    qualitative = _find_qualitative(normalised)
    operator = _find_operator(normalised)
    temperature_c = _find_temperature_c(normalised)
    conditions = _find_conditions(normalised)

    value, value_min, value_max, unit = _parse_numbers(normalised, heading)

    # A single value is also a degenerate range, so a numeric filter can use the
    # bounds without asking which shape it got.
    if value is not None:
        value_min = value_max = value

    unit_si = UNIT_TO_SI[unit][0] if unit in UNIT_TO_SI else None

    return ParsedValue(
        text=text,
        value=value,
        value_min=value_min,
        value_max=value_max,
        unit=unit,
        value_si=_to_si(value, unit),
        value_min_si=_to_si(value_min, unit),
        value_max_si=_to_si(value_max, unit),
        unit_si=unit_si,
        temperature_c=temperature_c,
        operator=operator,
        qualitative=qualitative,
        conditions=conditions,
    )