Skip to content

CompToxID

Offline: the EPA CompTox chemicals list, with DTXSIDs, curated CAS–name pairs, and a name index over every synonym. See Using the local databases directly.

provesid.comptox

CompToxID - Interface to CompTox Chemicals Dashboard SQLite database for fast identifier lookup and conversion.

This class provides access to a local SQLite database containing CompTox chemicals with their identifiers (DTXSID, DTXCID, CASRN, InChIKey, SMILES, PREFERRED_NAME, etc.) and chemical properties (molecular formula, average mass, monoisotopic mass, etc.).

The database is read from comptox_chemicals.db file.

Attributes:

Name Type Description
db_path str

Path to the SQLite database file

conn Connection

Database connection

Records are dicts keyed by the database's upper-case column names (DTXSID, PREFERRED_NAME, CASRN, INCHIKEY, SMILES ...), plus identifiers, the IDENTIFIER column split into a list.

Examples:

>>> from provesid import CompToxID
>>> db = CompToxID()
>>> result = db.get_by_casrn("50-78-2")  # Aspirin
>>> result['PREFERRED_NAME'], result['DTXSID']
('Aspirin', 'DTXSID5020108')
>>> db.batch_casrn_to_dtxsid(["50-78-2", "50-00-0"])
{'50-78-2': 'DTXSID5020108', '50-00-0': 'DTXSID7020637'}

Attributes

NAME_INDEX_TABLE module-attribute

The table CompToxID.build_name_index adds to the database: one row per distinct name of each chemical, keyed by name_key.

LOOKUP_INDEXES module-attribute

The indexes on chemicals that the first lookup by each column adds, by column: get_by_inchikey, get_by_smiles, get_by_dtxcid and search_by_formula. The downloaded database indexes DTXSID, CASRN and PREFERRED_NAME only.

NAME_KINDS module-attribute

Where a name came from, in the order an exact lookup ranks its matches: a chemical called the query outranks one that merely lists it as a synonym.

Classes

CompToxID

Bases: SQLiteClient

Interface to CompTox Chemicals Dashboard SQLite database.

The database file is automatically downloaded on first use when missing.

Inherits its connection handling from SQLiteClient: use it as a context manager, or call close when finished, and query it from as many threads as you like --- each gets its own connection.

Examples:

>>> with CompToxID() as db:
...     db.casrn_to_dtxsid("50-78-2")
'DTXSID5020108'
Source code in src/provesid/comptox.py
 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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
class CompToxID(SQLiteClient):
    """
    Interface to CompTox Chemicals Dashboard SQLite database.

    The database file is automatically downloaded on first use when missing.

    Inherits its connection handling from
    [`SQLiteClient`][provesid.sqlite_client.SQLiteClient]: use it as a context
    manager, or call [`close`][provesid.sqlite_client.SQLiteClient.close] when
    finished, and query it from as many threads as you like --- each gets its
    own connection.

    Examples:
        >>> with CompToxID() as db:
        ...     db.casrn_to_dtxsid("50-78-2")
        'DTXSID5020108'
    """

    # Default database filename
    DEFAULT_DB_NAME = "comptox_chemicals.db"
    DEFAULT_DB_URL = (
        "https://zenodo.org/records/18833587/files/comptox_chemicals.db"
    )
    DEFAULT_DB_SIZE_MB = 856

    logger = logging.getLogger(__name__)

    # The index state is declared here rather than in __init__, so that a
    # client built with object.__new__ and _adopt_connection (see
    # SQLiteClient) has it too; the first lookup sets it on the instance.
    # Whether exact name lookups can use the name index: None until the
    # first one checks, then True, or False for good when it cannot be built
    # (a read-only file).  The LOOKUP_INDEXES columns whose first lookup has
    # made sure of their index; without one, lookups still work, by scanning.
    # The lock keeps two threads, or two clients, from building any at once.
    _name_index_ready: Optional[bool] = None
    _lookup_indexes_checked: frozenset = frozenset()
    _index_lock = threading.Lock()

    def __init__(
        self,
        db_path: Optional[str] = None,
        auto_download: bool = True,
        db_url: Optional[str] = None,
        data_dir: Optional[str] = None,
        redownload: bool = False,
    ):
        """
        Initialize CompToxID database connection.

        Args:
            db_path (str, optional): Path to SQLite database. If None, uses default
                                    location in the persistent user dataset directory.
            auto_download (bool, optional): If True, automatically download the
                database when missing (default: True).
            db_url (str, optional): Custom URL for database download. If None,
                uses the default Zenodo URL.
            data_dir (str, optional): Directory to store the database when
                ``db_path`` is not provided. If None, uses platformdirs-based
                user data directory.
            redownload (bool, optional): If True, force a fresh download when
                ``auto_download`` is enabled.

        Raises:
            FileNotFoundError: If database file doesn't exist and auto_download is False.
        """
        if db_path is None:
            base_dir = data_dir or user_dataset_path()
            db_path = os.path.join(base_dir, self.DEFAULT_DB_NAME)

        self.db_path = os.path.abspath(os.path.expanduser(db_path))
        self.db_url = db_url or self.DEFAULT_DB_URL

        needs_download = redownload or not os.path.exists(self.db_path)

        # Check if database exists
        if needs_download:
            if auto_download:
                if redownload and os.path.exists(self.db_path):
                    self.logger.warning(
                        "Forced CompTox redownload requested for: %s", self.db_path
                    )
                else:
                    self.logger.warning(f"CompTox database not found at: {self.db_path}")
                self.logger.warning(
                    "The CompTox database is large (~856 MB). "
                    "Initial setup may take several minutes depending on your connection."
                )
                self.logger.warning(
                    f"Downloading CompTox database from: {self.db_url}"
                )
                self.download_database(url=self.db_url, force=redownload)
            else:
                raise FileNotFoundError(
                    f"CompTox database not found at: {self.db_path}\n"
                    "Database size: ~856 MB\n"
                    f"Run CompToxID.download_database() or set auto_download=True\n"
                    f"Download URL: {self.db_url}"
                )

        # Connect to the database.  One connection per thread, released by
        # close() or by leaving a ``with`` block --- see
        # ``SQLiteClient``.
        self._open_database(self.db_path)

        # Verify the database has the expected table
        self._verify_database()

    def download_database(self, url: Optional[str] = None, force: bool = False) -> str:
        """
        Download the CompTox SQLite database from Zenodo.

        The file is approximately 856 MB and is not shipped with the GitHub
        repository due to size limitations.

        The transfer is resumable: an interrupted download leaves a ``.part``
        file beside the destination and the next call continues from it rather
        than fetching the 856 MB again. The file is checked before it is moved
        into place, so a failed download never replaces a working database.

        Args:
            url (str, optional): Download URL. If None, uses `self.db_url`.
            force (bool, optional): If True, overwrite existing database file.

        Returns:
            (str): Path to the downloaded database file.

        Raises:
            FileExistsError: If the database already exists and `force` is False.
            provesid.datasets.DownloadError: If the download could not be
                completed.
            RuntimeError: If the file that arrived is not the CompTox database.

        Examples:
            >>> db = CompToxID()
            >>> db.download_database(force=True)            # doctest: +SKIP
            '/home/me/.local/share/provesid/comptox_chemicals.db'
        """
        download_url = url or self.db_url

        if os.path.exists(self.db_path) and not force:
            raise FileExistsError(
                f"Database already exists at: {self.db_path}. Use force=True to overwrite."
            )

        def must_contain_the_chemicals_table(path):
            """Reject a download that is not the CompTox database.

            Run on the ``.part`` file, before it is moved into place. The
            previous implementation renamed first and checked afterwards, so a
            failed check left the broken file where the good one had been.
            """
            connection = sqlite3.connect(path)
            try:
                found = connection.execute(
                    "SELECT name FROM sqlite_master "
                    "WHERE type='table' AND name='chemicals'"
                ).fetchone()
            finally:
                connection.close()
            if not found:
                raise RuntimeError(
                    "Downloaded database does not contain 'chemicals' table"
                )

        self.logger.warning(
            "CompTox database download starting (~856 MB). "
            "Please ensure you have enough disk space and stable internet."
        )
        download_file(
            download_url,
            self.db_path,
            verify=must_contain_the_chemicals_table,
            description="CompTox database",
            log=self.logger,
        )

        # Built now, while the user is already waiting for a download, rather
        # than on the first lookup.  A failure here costs nothing that the
        # lazy builds in search_by_name and the lookups will not retry.
        self.logger.warning("Building the CompTox name and lookup indexes (~24 s, ~440 MiB).")
        connection = sqlite3.connect(self.db_path)
        try:
            _build_name_index(connection)
            for column in LOOKUP_INDEXES:
                _build_lookup_index(connection, column)
        except sqlite3.Error as exc:
            self.logger.warning("CompTox indexes not built: %s", exc)
        finally:
            connection.close()
        self._name_index_ready = None
        self._lookup_indexes_checked = frozenset()
        return self.db_path

    @property
    def has_name_index(self) -> bool:
        """Whether the database holds the name index (see
        [`build_name_index`][provesid.comptox.CompToxID.build_name_index]).

        Returns:
            True when [`NAME_INDEX_TABLE`][provesid.comptox.NAME_INDEX_TABLE] exists.

        Examples:
            >>> isinstance(CompToxID().has_name_index, bool)
            True
        """
        return self.conn.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
            (NAME_INDEX_TABLE,),
        ).fetchone() is not None

    def build_name_index(self) -> int:
        """Index every name of every chemical, so that exact lookups find synonyms.

        The downloaded database indexes ``PREFERRED_NAME`` only; the synonyms,
        former CAS numbers and registry codes sit together in the
        ``|``-separated ``IDENTIFIER`` column, which only a full scan can read.
        This adds a table,
        [`NAME_INDEX_TABLE`][provesid.comptox.NAME_INDEX_TABLE], with one row
        per distinct name of each chemical (compared by
        [`name_key`][provesid.comptox.name_key]), and
        [`search_by_name`][provesid.comptox.CompToxID.search_by_name] with
        ``exact=True`` uses it from then on.

        It is built automatically after
        [`download_database`][provesid.comptox.CompToxID.download_database],
        and by the first exact
        [`search_by_name`][provesid.comptox.CompToxID.search_by_name] on a
        database downloaded before the index existed.  Call it yourself to pay
        the ~20 s at a time of your choosing.  Building it again is a no-op.

        Returns:
            (int): The number of rows in the index (5.1 M on the 2025 release).

        Raises:
            sqlite3.OperationalError: If the database file is read-only.

        Examples:
            >>> with CompToxID() as db:                     # doctest: +SKIP
            ...     db.build_name_index()
            5128983
        """
        with self._index_lock:
            rows = _build_name_index(self.conn)
            self._name_index_ready = True
        return rows

    def _ensure_name_index(self) -> bool:
        """Make sure the name index exists, building it once if it does not.

        Returns:
            True when exact lookups can use the index; False when it is missing
            and cannot be built, in which case they fall back to
            ``PREFERRED_NAME`` alone.  The failure is logged once.
        """
        if self._name_index_ready is not None:
            return self._name_index_ready
        with self._index_lock:
            if self._name_index_ready is None:
                if self.has_name_index:
                    self._name_index_ready = True
                else:
                    self.logger.warning(
                        "Building the CompTox name index, once, so exact name "
                        "lookups find synonyms (~20 s, ~290 MiB added to %s).",
                        self.db_file,
                    )
                    try:
                        _build_name_index(self.conn)
                        self._name_index_ready = True
                    except sqlite3.OperationalError as exc:
                        self.logger.warning(
                            "CompTox name index could not be built (%s); exact "
                            "name lookups will match preferred names only.",
                            exc,
                        )
                        self._name_index_ready = False
        return self._name_index_ready

    def _ensure_lookup_index(self, column: str) -> None:
        """Make sure the index on ``column`` exists, building it once if it does not.

        Called by every lookup by a
        [`LOOKUP_INDEXES`][provesid.comptox.LOOKUP_INDEXES] column; only the
        first one per column and client looks.  When the index cannot be built
        (a read-only file) the failure is logged once per column and lookups
        scan the table instead.

        Args:
            column: A key of [`LOOKUP_INDEXES`][provesid.comptox.LOOKUP_INDEXES].
        """
        if column in self._lookup_indexes_checked:
            return
        with self._index_lock:
            if column in self._lookup_indexes_checked:
                return
            exists = self.conn.execute(
                "SELECT 1 FROM sqlite_master WHERE type='index' AND name=?",
                (LOOKUP_INDEXES[column],),
            ).fetchone()
            if not exists:
                self.logger.warning(
                    "Building the CompTox %s index, once (~1 s, up to ~60 MiB "
                    "added to %s).",
                    column,
                    self.db_file,
                )
                try:
                    _build_lookup_index(self.conn, column)
                except sqlite3.OperationalError as exc:
                    self.logger.warning(
                        "CompTox %s index could not be built (%s); %s lookups "
                        "will scan the table (~0.2 s each).",
                        column,
                        exc,
                        column,
                    )
            # A new set, not an update: the class attribute is shared.
            self._lookup_indexes_checked = self._lookup_indexes_checked | {column}

    def _verify_database(self):
        """Verify the database has the expected table structure."""
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='chemicals'"
        )
        if not cursor.fetchone():
            raise RuntimeError("Database does not contain 'chemicals' table")

        # Check for required columns
        cursor.execute("PRAGMA table_info(chemicals)")
        columns = [row[1] for row in cursor.fetchall()]
        required_columns = {
            "DTXSID",
            "PREFERRED_NAME",
            "CASRN",
            "DTXCID",
            "INCHIKEY",
            "SMILES",
            "MOLECULAR_FORMULA",
        }
        missing = required_columns - set(columns)
        if missing:
            raise RuntimeError(f"Database table missing required columns: {missing}")

    # Basic lookup methods

    @staticmethod
    def _parse_identifiers(identifier_string: Optional[str]) -> List[str]:
        """
        Parse pipe-separated identifier string into list of identifiers.

        The IDENTIFIER column contains pipe-separated identifiers and synonyms.
        Format: "identifier1 | identifier2 | identifier3"

        Args:
            identifier_string: Pipe-separated identifier string

        Returns:
            List of identifiers (stripped of whitespace)
        """
        if not identifier_string:
            return []

        # Split by pipe character, strip whitespace
        identifiers = [id.strip() for id in identifier_string.split("|")]
        # Filter out empty strings
        return [id for id in identifiers if id]

    def get_by_dtxsid(self, dtxsid: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by DTXSID.

        Args:
            dtxsid (str): DSSTox Substance ID (e.g., "DTXSID7020001")

        Returns:
            (dict): Every column of the ``chemicals`` row --- ``DTXSID``,
            ``DTXCID``, ``PREFERRED_NAME``, ``CASRN``, ``INCHIKEY``,
            ``IUPAC_NAME``, ``SMILES``, ``MS_READY_SMILES``,
            ``QSAR_READY_SMILES``, ``MOLECULAR_FORMULA``, ``AVERAGE_MASS``,
            ``MONOISOTOPIC_MASS`` and ``IDENTIFIER`` --- plus ``identifiers``,
            the last split into a list. None if not found.

        Examples:
            >>> record = CompToxID().get_by_dtxsid("DTXSID5020108")
            >>> record["PREFERRED_NAME"], record["CASRN"], record["identifiers"][:2]
            ('Aspirin', '50-78-2', ['50-78-2', '11126-35-5'])
        """
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE DTXSID = ?
        """,
            (dtxsid,),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)

        # Parse identifiers
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))

        return result

    def get_by_casrn(self, casrn: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by CAS Registry Number.

        Args:
            casrn (str): CAS Registry Number (e.g., "50-78-2")

        Returns:
            (dict): The
                [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                record, or None if not found. Only
            the chemical's own ``CASRN`` matches; for a retired or alternate
            number see
            [`get_by_alternate_casrn`][provesid.comptox.CompToxID.get_by_alternate_casrn].

        Examples:
            >>> CompToxID().get_by_casrn("50-78-2")["DTXSID"]
            'DTXSID5020108'
        """
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE CASRN = ?
        """,
            (casrn,),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def get_by_alternate_casrn(self, casrn: str) -> Optional[Dict[str, Any]]:
        """
        Get the chemical that lists a CAS number other than its own ``CASRN``.

        CAS deletes and merges registry numbers, and old datasets still carry
        the numbers it retired. CompTox keeps them, together with alternate
        numbers, among a chemical's ``IDENTIFIER`` tokens, where
        [`get_by_casrn`][provesid.comptox.CompToxID.get_by_casrn] does not
        look. For example, atrazine is ``1912-24-9`` but also lists
        ``39400-72-1``. This method reads the name index (see
        [`build_name_index`][provesid.comptox.CompToxID.build_name_index]) for
        such a number.

        It answers only when **exactly one** chemical lists the number.
        Of the 83,933 numbers CompTox holds only in ``IDENTIFIER``, four are
        listed by two unrelated chemicals, and picking one of the two would
        be a guess. Call
        [`get_by_casrn`][provesid.comptox.CompToxID.get_by_casrn] first: a
        number that is some chemical's own ``CASRN`` belongs to that chemical,
        whatever else lists it.

        Args:
            casrn (str): CAS Registry Number (e.g., "39400-72-1")

        Returns:
            (dict): Chemical information, or None if ``casrn`` is not shaped
            like a CAS number, no chemical lists it, more than one does, or the
            name index is unavailable (a read-only database that predates it).

        Examples:
            >>> with CompToxID() as db:                     # doctest: +SKIP
            ...     db.get_by_alternate_casrn("39400-72-1")["PREFERRED_NAME"]
            'Atrazine'
        """
        # IDENTIFIER also holds synonyms; without this, a name one chemical
        # lists would come back as its "alternate CAS number".
        if not _CAS_NUMBER.fullmatch(casrn.strip()):
            return None
        if not self._ensure_name_index():
            return None
        cursor = self.conn.cursor()
        cursor.execute(
            f"""
            SELECT c.* FROM {NAME_INDEX_TABLE} n
            JOIN chemicals c ON c.rowid = n.chemical_rowid
            WHERE n.name_key = ? AND n.kind = ?
            LIMIT 2
        """,
            (name_key(casrn), NAME_KINDS["identifier"]),
        )
        rows = cursor.fetchall()
        if len(rows) != 1:
            if rows:
                self.logger.debug(
                    "CAS %s is listed by more than one CompTox chemical; not guessing.",
                    casrn,
                )
            return None

        result = dict(rows[0])
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def get_by_inchikey(self, inchikey: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by InChIKey.

        About 11% of CompTox's substances are stored under a non-standard
        InChIKey (flag ``N``, as in ``PGRHXDWITVMQBC-UHFFFAOYNA-N``). A key is
        also looked up with its other flag, so a standard key finds those rows
        where only the flag differs, about 98% of them. The key given is
        preferred when both exist. The record returned carries the key as
        CompTox stores it.

        The first call adds an index on ``INCHIKEY`` to the database, about
        1 s and 41 MiB, so that lookups take microseconds rather than a 0.2 s
        scan. A read-only database is scanned instead.

        Args:
            inchikey (str): InChIKey (27 characters), standard or not

        Returns:
            (dict): The
                [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                record, or None if not found

        Examples:
            >>> CompToxID().get_by_inchikey("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")["DTXSID"]
            'DTXSID5020108'
            >>> CompToxID().get_by_inchikey("PGRHXDWITVMQBC-UHFFFAOYSA-N")["INCHIKEY"]
            'PGRHXDWITVMQBC-UHFFFAOYNA-N'
        """
        self._ensure_lookup_index("INCHIKEY")
        spellings = inchikey_flag_variants(inchikey)
        placeholders = ", ".join("?" * len(spellings))
        cursor = self.conn.cursor()
        cursor.execute(
            f"""
            SELECT * FROM chemicals WHERE INCHIKEY IN ({placeholders})
            ORDER BY INCHIKEY = ? DESC
            LIMIT 1
        """,
            (*spellings, inchikey),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def get_by_smiles(self, smiles: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by SMILES string.

        The first call adds an index on ``SMILES`` to the database, about
        1 s and 57 MiB, so that lookups take well under a millisecond rather
        than a 0.17 s scan. A read-only database is scanned instead.

        Args:
            smiles (str): SMILES string, matched as a string against CompTox's
                own: another valid SMILES for the same structure finds nothing

        Returns:
            (dict): The
                [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                record, or None if not found

        Examples:
            >>> db = CompToxID()
            >>> db.get_by_smiles("CC(=O)OC1=C(C=CC=C1)C(O)=O")["CASRN"]
            '50-78-2'
            >>> db.get_by_smiles("CC(=O)OC1=CC=CC=C1C(O)=O") is None
            True
        """
        self._ensure_lookup_index("SMILES")
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE SMILES = ?
        """,
            (smiles,),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def get_by_name(self, name: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by preferred name (exact match).

        Args:
            name (str): Preferred name, case included.
                [`search_by_name`][provesid.comptox.CompToxID.search_by_name]
                with ``exact=True`` matches any name, ignoring case.

        Returns:
            (dict): The
                [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                record, or None if not found

        Examples:
            >>> db = CompToxID()
            >>> db.get_by_name("Aspirin")["CASRN"], db.get_by_name("aspirin")
            ('50-78-2', None)
        """
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE PREFERRED_NAME = ?
        """,
            (name,),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def get_by_dtxcid(self, dtxcid: str) -> Optional[Dict[str, Any]]:
        """
        Get chemical information by DTXCID.

        The first call adds an index on ``DTXCID`` to the database, about
        0.6 s and 27 MiB, so that lookups take well under a millisecond rather
        than a 0.15 s scan. A read-only database is scanned instead.

        Args:
            dtxcid (str): DSSTox Compound ID (e.g., "DTXCID101")

        Returns:
            (dict): The
                [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                record, or None if not found

        Examples:
            >>> CompToxID().get_by_dtxcid("DTXCID50108")["PREFERRED_NAME"]
            'Aspirin'
        """
        self._ensure_lookup_index("DTXCID")
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE DTXCID = ?
        """,
            (dtxcid,),
        )

        row = cursor.fetchone()
        if not row:
            return None

        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        return result

    def search_by_name(
        self, name: str, exact: bool = False, limit: int = 10
    ) -> List[Dict[str, Any]]:
        """
        Search chemicals by name or synonym.

        With ``exact=True`` the query is compared, case-insensitively, with
        every name the database holds for a chemical: its preferred name, its
        IUPAC name and each synonym or identifier in ``IDENTIFIER``.  Chemicals
        *called* the query come first, then those whose IUPAC name it is, then
        those that list it as a synonym; ties keep the database's order.  This
        reads the name index, which the first exact call builds if the database
        predates it (see
        [`build_name_index`][provesid.comptox.CompToxID.build_name_index]); on
        a read-only file without one, only preferred names are matched,
        case-sensitively, as before the index existed.

        With ``exact=False`` the query is matched as a substring, first of the
        preferred name and then of ``IDENTIFIER``.  That is a full scan, about
        3 s a call.

        Args:
            name (str): Chemical name or synonym to search for
            exact (bool): If True, exact (case-insensitive) match on any name.
                If False, partial match (case-insensitive)
            limit (int): Maximum number of results to return

        Returns:
            (list): List of matching chemicals

        Examples:
            >>> with CompToxID() as db:                     # doctest: +SKIP
            ...     [r["PREFERRED_NAME"] for r in db.search_by_name("Acetaldoxime", exact=True)]
            ['Acetaldehyde oxime']
        """
        cursor = self.conn.cursor()
        results = []

        if exact and self._ensure_name_index():
            cursor.execute(
                f"""
                SELECT c.* FROM {NAME_INDEX_TABLE} n
                JOIN chemicals c ON c.rowid = n.chemical_rowid
                WHERE n.name_key = ?
                ORDER BY n.kind, n.chemical_rowid
                LIMIT ?
            """,
                (name_key(name), limit),
            )
        elif exact:
            cursor.execute(
                """
                SELECT * FROM chemicals WHERE PREFERRED_NAME = ? LIMIT ?
            """,
                (name, limit),
            )
        else:
            # Partial match with LIKE (case-insensitive)
            search_term = f"%{name}%"
            cursor.execute(
                """
                SELECT * FROM chemicals WHERE PREFERRED_NAME LIKE ? LIMIT ?
            """,
                (search_term, limit),
            )

        rows = cursor.fetchall()
        for row in rows:
            result = dict(row)
            result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
            results.append(result)

        # If not enough results and not exact, also search in identifiers
        if len(results) < limit and not exact:
            search_term = f"%{name}%"
            cursor.execute(
                """
                SELECT * FROM chemicals WHERE IDENTIFIER LIKE ? LIMIT ?
            """,
                (search_term, limit - len(results)),
            )

            # Need to deduplicate by DTXSID
            seen_dtxsids = {r["DTXSID"] for r in results}
            for row in cursor.fetchall():
                if row["DTXSID"] not in seen_dtxsids:
                    result = dict(row)
                    result["identifiers"] = self._parse_identifiers(
                        result.get("IDENTIFIER")
                    )
                    results.append(result)
                    seen_dtxsids.add(row["DTXSID"])
                if len(results) >= limit:
                    break

        return results

    def search_by_formula(self, formula: str, limit: int = 100) -> List[Dict[str, Any]]:
        """
        Search chemicals by molecular formula.

        The first call adds an index on ``MOLECULAR_FORMULA`` to the
        database, about 0.7 s and 21 MiB, so that a formula no chemical has
        is answered at once rather than after a 0.16 s scan. A read-only
        database is scanned instead.

        Args:
            formula (str): Molecular formula (e.g., "C9H8O4")
            limit (int): Maximum number of results to return

        Returns:
            (list): [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
                records, in database order

        Examples:
            >>> [r["PREFERRED_NAME"] for r in CompToxID().search_by_formula("C9H8O4", limit=2)]
            ['Aspirin', '3,4-Dihydroxycinnamic acid']
        """
        self._ensure_lookup_index("MOLECULAR_FORMULA")
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE MOLECULAR_FORMULA = ? LIMIT ?
        """,
            (formula, limit),
        )

        results = []
        for row in cursor.fetchall():
            result = dict(row)
            result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
            results.append(result)

        return results

    # Conversion methods

    def casrn_to_dtxsid(self, casrn: str) -> Optional[str]:
        """
        Convert CAS Registry Number to DTXSID.

        Args:
            casrn: CAS Registry Number.

        Returns:
            The DTXSID, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.casrn_to_dtxsid("50-78-2")
            'DTXSID5020108'
        """
        result = self.get_by_casrn(casrn)
        return result["DTXSID"] if result else None

    def casrn_to_inchikey(self, casrn: str) -> Optional[str]:
        """
        Convert CAS Registry Number to InChIKey.

        Args:
            casrn: CAS Registry Number.

        Returns:
            The InChIKey, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.casrn_to_inchikey("50-78-2")
            'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
        """
        result = self.get_by_casrn(casrn)
        return result["INCHIKEY"] if result else None

    def casrn_to_smiles(self, casrn: str) -> Optional[str]:
        """
        Convert CAS Registry Number to SMILES.

        Args:
            casrn: CAS Registry Number.

        Returns:
            CompTox's SMILES, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.casrn_to_smiles("50-78-2")
            'CC(=O)OC1=C(C=CC=C1)C(O)=O'
        """
        result = self.get_by_casrn(casrn)
        return result["SMILES"] if result else None

    def inchikey_to_casrn(self, inchikey: str) -> Optional[str]:
        """
        Convert InChIKey to CAS Registry Number.

        Args:
            inchikey: Standard InChIKey.

        Returns:
            The CAS number, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.inchikey_to_casrn("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
            '50-78-2'
        """
        result = self.get_by_inchikey(inchikey)
        return result["CASRN"] if result else None

    def inchikey_to_dtxsid(self, inchikey: str) -> Optional[str]:
        """
        Convert InChIKey to DTXSID.

        Args:
            inchikey: Standard InChIKey.

        Returns:
            The DTXSID, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.inchikey_to_dtxsid("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
            'DTXSID5020108'
        """
        result = self.get_by_inchikey(inchikey)
        return result["DTXSID"] if result else None

    def dtxsid_to_casrn(self, dtxsid: str) -> Optional[str]:
        """
        Convert DTXSID to CAS Registry Number.

        Args:
            dtxsid: DSSTox Substance ID.

        Returns:
            The CAS number, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.dtxsid_to_casrn("DTXSID5020108")
            '50-78-2'
        """
        result = self.get_by_dtxsid(dtxsid)
        return result["CASRN"] if result else None

    def dtxsid_to_inchikey(self, dtxsid: str) -> Optional[str]:
        """
        Convert DTXSID to InChIKey.

        Args:
            dtxsid: DSSTox Substance ID.

        Returns:
            The InChIKey, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.dtxsid_to_inchikey("DTXSID5020108")
            'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
        """
        result = self.get_by_dtxsid(dtxsid)
        return result["INCHIKEY"] if result else None

    def dtxsid_to_smiles(self, dtxsid: str) -> Optional[str]:
        """
        Convert DTXSID to SMILES.

        Args:
            dtxsid: DSSTox Substance ID.

        Returns:
            CompTox's SMILES, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.dtxsid_to_smiles("DTXSID5020108")
            'CC(=O)OC1=C(C=CC=C1)C(O)=O'
        """
        result = self.get_by_dtxsid(dtxsid)
        return result["SMILES"] if result else None

    def smiles_to_casrn(self, smiles: str) -> Optional[str]:
        """
        Convert SMILES to CAS Registry Number.

        Args:
            smiles: SMILES, matched as a string; see
                [`get_by_smiles`][provesid.comptox.CompToxID.get_by_smiles].

        Returns:
            The CAS number, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.smiles_to_casrn("CC(=O)OC1=C(C=CC=C1)C(O)=O")
            '50-78-2'
        """
        result = self.get_by_smiles(smiles)
        return result["CASRN"] if result else None

    def smiles_to_dtxsid(self, smiles: str) -> Optional[str]:
        """
        Convert SMILES to DTXSID.

        Args:
            smiles: SMILES, matched as a string; see
                [`get_by_smiles`][provesid.comptox.CompToxID.get_by_smiles].

        Returns:
            The DTXSID, or None if not found.

        Examples:
            >>> db = CompToxID()
            >>> db.smiles_to_dtxsid("CCO")
            'DTXSID9020584'
        """
        result = self.get_by_smiles(smiles)
        return result["DTXSID"] if result else None

    # Batch conversion methods

    def batch_casrn_to_dtxsid(self, casrn_list: List[str]) -> Dict[str, Optional[str]]:
        """
        Convert multiple CAS numbers to DTXSIDs.

        Args:
            casrn_list (list): List of CAS numbers

        Returns:
            (dict): Mapping of CAS -> DTXSID (None if not found)

        Examples:
            >>> CompToxID().batch_casrn_to_dtxsid(["50-78-2", "0-00-0"])
            {'50-78-2': 'DTXSID5020108', '0-00-0': None}
        """
        results = {}
        for casrn in casrn_list:
            results[casrn] = self.casrn_to_dtxsid(casrn)
        return results

    def batch_casrn_to_inchikey(
        self, casrn_list: List[str]
    ) -> Dict[str, Optional[str]]:
        """
        Convert multiple CAS numbers to InChIKeys.

        Args:
            casrn_list (list): List of CAS numbers

        Returns:
            (dict): Mapping of CAS -> InChIKey (None if not found)

        Examples:
            >>> CompToxID().batch_casrn_to_inchikey(["50-78-2", "0-00-0"])
            {'50-78-2': 'BSYNRYMUTXBXSQ-UHFFFAOYSA-N', '0-00-0': None}
        """
        results = {}
        for casrn in casrn_list:
            results[casrn] = self.casrn_to_inchikey(casrn)
        return results

    def batch_inchikey_to_casrn(
        self, inchikey_list: List[str]
    ) -> Dict[str, Optional[str]]:
        """
        Convert multiple InChIKeys to CAS numbers.

        Args:
            inchikey_list (list): List of InChIKeys

        Returns:
            (dict): Mapping of InChIKey -> CAS (None if not found)

        Examples:
            >>> CompToxID().batch_inchikey_to_casrn(
            ...     ["BSYNRYMUTXBXSQ-UHFFFAOYSA-N", "LFQSCWFLJHTTHZ-UHFFFAOYSA-N"])
            {'BSYNRYMUTXBXSQ-UHFFFAOYSA-N': '50-78-2', 'LFQSCWFLJHTTHZ-UHFFFAOYSA-N': '64-17-5'}
        """
        results = {}
        for inchikey in inchikey_list:
            results[inchikey] = self.inchikey_to_casrn(inchikey)
        return results
Attributes
has_name_index property

Whether the database holds the name index (see build_name_index).

Returns:

Type Description
bool

True when NAME_INDEX_TABLE exists.

Examples:

>>> isinstance(CompToxID().has_name_index, bool)
True
Methods:
__init__(db_path=None, auto_download=True, db_url=None, data_dir=None, redownload=False)

Initialize CompToxID database connection.

Parameters:

Name Type Description Default
db_path str

Path to SQLite database. If None, uses default location in the persistent user dataset directory.

None
auto_download bool

If True, automatically download the database when missing (default: True).

True
db_url str

Custom URL for database download. If None, uses the default Zenodo URL.

None
data_dir str

Directory to store the database when db_path is not provided. If None, uses platformdirs-based user data directory.

None
redownload bool

If True, force a fresh download when auto_download is enabled.

False

Raises:

Type Description
FileNotFoundError

If database file doesn't exist and auto_download is False.

Source code in src/provesid/comptox.py
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
def __init__(
    self,
    db_path: Optional[str] = None,
    auto_download: bool = True,
    db_url: Optional[str] = None,
    data_dir: Optional[str] = None,
    redownload: bool = False,
):
    """
    Initialize CompToxID database connection.

    Args:
        db_path (str, optional): Path to SQLite database. If None, uses default
                                location in the persistent user dataset directory.
        auto_download (bool, optional): If True, automatically download the
            database when missing (default: True).
        db_url (str, optional): Custom URL for database download. If None,
            uses the default Zenodo URL.
        data_dir (str, optional): Directory to store the database when
            ``db_path`` is not provided. If None, uses platformdirs-based
            user data directory.
        redownload (bool, optional): If True, force a fresh download when
            ``auto_download`` is enabled.

    Raises:
        FileNotFoundError: If database file doesn't exist and auto_download is False.
    """
    if db_path is None:
        base_dir = data_dir or user_dataset_path()
        db_path = os.path.join(base_dir, self.DEFAULT_DB_NAME)

    self.db_path = os.path.abspath(os.path.expanduser(db_path))
    self.db_url = db_url or self.DEFAULT_DB_URL

    needs_download = redownload or not os.path.exists(self.db_path)

    # Check if database exists
    if needs_download:
        if auto_download:
            if redownload and os.path.exists(self.db_path):
                self.logger.warning(
                    "Forced CompTox redownload requested for: %s", self.db_path
                )
            else:
                self.logger.warning(f"CompTox database not found at: {self.db_path}")
            self.logger.warning(
                "The CompTox database is large (~856 MB). "
                "Initial setup may take several minutes depending on your connection."
            )
            self.logger.warning(
                f"Downloading CompTox database from: {self.db_url}"
            )
            self.download_database(url=self.db_url, force=redownload)
        else:
            raise FileNotFoundError(
                f"CompTox database not found at: {self.db_path}\n"
                "Database size: ~856 MB\n"
                f"Run CompToxID.download_database() or set auto_download=True\n"
                f"Download URL: {self.db_url}"
            )

    # Connect to the database.  One connection per thread, released by
    # close() or by leaving a ``with`` block --- see
    # ``SQLiteClient``.
    self._open_database(self.db_path)

    # Verify the database has the expected table
    self._verify_database()
download_database(url=None, force=False)

Download the CompTox SQLite database from Zenodo.

The file is approximately 856 MB and is not shipped with the GitHub repository due to size limitations.

The transfer is resumable: an interrupted download leaves a .part file beside the destination and the next call continues from it rather than fetching the 856 MB again. The file is checked before it is moved into place, so a failed download never replaces a working database.

Parameters:

Name Type Description Default
url str

Download URL. If None, uses self.db_url.

None
force bool

If True, overwrite existing database file.

False

Returns:

Type Description
str

Path to the downloaded database file.

Raises:

Type Description
FileExistsError

If the database already exists and force is False.

DownloadError

If the download could not be completed.

RuntimeError

If the file that arrived is not the CompTox database.

Examples:

>>> db = CompToxID()
>>> db.download_database(force=True)
'/home/me/.local/share/provesid/comptox_chemicals.db'
Source code in src/provesid/comptox.py
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
def download_database(self, url: Optional[str] = None, force: bool = False) -> str:
    """
    Download the CompTox SQLite database from Zenodo.

    The file is approximately 856 MB and is not shipped with the GitHub
    repository due to size limitations.

    The transfer is resumable: an interrupted download leaves a ``.part``
    file beside the destination and the next call continues from it rather
    than fetching the 856 MB again. The file is checked before it is moved
    into place, so a failed download never replaces a working database.

    Args:
        url (str, optional): Download URL. If None, uses `self.db_url`.
        force (bool, optional): If True, overwrite existing database file.

    Returns:
        (str): Path to the downloaded database file.

    Raises:
        FileExistsError: If the database already exists and `force` is False.
        provesid.datasets.DownloadError: If the download could not be
            completed.
        RuntimeError: If the file that arrived is not the CompTox database.

    Examples:
        >>> db = CompToxID()
        >>> db.download_database(force=True)            # doctest: +SKIP
        '/home/me/.local/share/provesid/comptox_chemicals.db'
    """
    download_url = url or self.db_url

    if os.path.exists(self.db_path) and not force:
        raise FileExistsError(
            f"Database already exists at: {self.db_path}. Use force=True to overwrite."
        )

    def must_contain_the_chemicals_table(path):
        """Reject a download that is not the CompTox database.

        Run on the ``.part`` file, before it is moved into place. The
        previous implementation renamed first and checked afterwards, so a
        failed check left the broken file where the good one had been.
        """
        connection = sqlite3.connect(path)
        try:
            found = connection.execute(
                "SELECT name FROM sqlite_master "
                "WHERE type='table' AND name='chemicals'"
            ).fetchone()
        finally:
            connection.close()
        if not found:
            raise RuntimeError(
                "Downloaded database does not contain 'chemicals' table"
            )

    self.logger.warning(
        "CompTox database download starting (~856 MB). "
        "Please ensure you have enough disk space and stable internet."
    )
    download_file(
        download_url,
        self.db_path,
        verify=must_contain_the_chemicals_table,
        description="CompTox database",
        log=self.logger,
    )

    # Built now, while the user is already waiting for a download, rather
    # than on the first lookup.  A failure here costs nothing that the
    # lazy builds in search_by_name and the lookups will not retry.
    self.logger.warning("Building the CompTox name and lookup indexes (~24 s, ~440 MiB).")
    connection = sqlite3.connect(self.db_path)
    try:
        _build_name_index(connection)
        for column in LOOKUP_INDEXES:
            _build_lookup_index(connection, column)
    except sqlite3.Error as exc:
        self.logger.warning("CompTox indexes not built: %s", exc)
    finally:
        connection.close()
    self._name_index_ready = None
    self._lookup_indexes_checked = frozenset()
    return self.db_path
build_name_index()

Index every name of every chemical, so that exact lookups find synonyms.

The downloaded database indexes PREFERRED_NAME only; the synonyms, former CAS numbers and registry codes sit together in the |-separated IDENTIFIER column, which only a full scan can read. This adds a table, NAME_INDEX_TABLE, with one row per distinct name of each chemical (compared by name_key), and search_by_name with exact=True uses it from then on.

It is built automatically after download_database, and by the first exact search_by_name on a database downloaded before the index existed. Call it yourself to pay the ~20 s at a time of your choosing. Building it again is a no-op.

Returns:

Type Description
int

The number of rows in the index (5.1 M on the 2025 release).

Raises:

Type Description
OperationalError

If the database file is read-only.

Examples:

>>> with CompToxID() as db:
...     db.build_name_index()
5128983
Source code in src/provesid/comptox.py
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
def build_name_index(self) -> int:
    """Index every name of every chemical, so that exact lookups find synonyms.

    The downloaded database indexes ``PREFERRED_NAME`` only; the synonyms,
    former CAS numbers and registry codes sit together in the
    ``|``-separated ``IDENTIFIER`` column, which only a full scan can read.
    This adds a table,
    [`NAME_INDEX_TABLE`][provesid.comptox.NAME_INDEX_TABLE], with one row
    per distinct name of each chemical (compared by
    [`name_key`][provesid.comptox.name_key]), and
    [`search_by_name`][provesid.comptox.CompToxID.search_by_name] with
    ``exact=True`` uses it from then on.

    It is built automatically after
    [`download_database`][provesid.comptox.CompToxID.download_database],
    and by the first exact
    [`search_by_name`][provesid.comptox.CompToxID.search_by_name] on a
    database downloaded before the index existed.  Call it yourself to pay
    the ~20 s at a time of your choosing.  Building it again is a no-op.

    Returns:
        (int): The number of rows in the index (5.1 M on the 2025 release).

    Raises:
        sqlite3.OperationalError: If the database file is read-only.

    Examples:
        >>> with CompToxID() as db:                     # doctest: +SKIP
        ...     db.build_name_index()
        5128983
    """
    with self._index_lock:
        rows = _build_name_index(self.conn)
        self._name_index_ready = True
    return rows
get_by_dtxsid(dtxsid)

Get chemical information by DTXSID.

Parameters:

Name Type Description Default
dtxsid str

DSSTox Substance ID (e.g., "DTXSID7020001")

required

Returns:

Type Description
dict

Every column of the chemicals row --- DTXSID, DTXCID, PREFERRED_NAME, CASRN, INCHIKEY, IUPAC_NAME, SMILES, MS_READY_SMILES, QSAR_READY_SMILES, MOLECULAR_FORMULA, AVERAGE_MASS, MONOISOTOPIC_MASS and IDENTIFIER --- plus identifiers, the last split into a list. None if not found.

Examples:

>>> record = CompToxID().get_by_dtxsid("DTXSID5020108")
>>> record["PREFERRED_NAME"], record["CASRN"], record["identifiers"][:2]
('Aspirin', '50-78-2', ['50-78-2', '11126-35-5'])
Source code in src/provesid/comptox.py
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
def get_by_dtxsid(self, dtxsid: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by DTXSID.

    Args:
        dtxsid (str): DSSTox Substance ID (e.g., "DTXSID7020001")

    Returns:
        (dict): Every column of the ``chemicals`` row --- ``DTXSID``,
        ``DTXCID``, ``PREFERRED_NAME``, ``CASRN``, ``INCHIKEY``,
        ``IUPAC_NAME``, ``SMILES``, ``MS_READY_SMILES``,
        ``QSAR_READY_SMILES``, ``MOLECULAR_FORMULA``, ``AVERAGE_MASS``,
        ``MONOISOTOPIC_MASS`` and ``IDENTIFIER`` --- plus ``identifiers``,
        the last split into a list. None if not found.

    Examples:
        >>> record = CompToxID().get_by_dtxsid("DTXSID5020108")
        >>> record["PREFERRED_NAME"], record["CASRN"], record["identifiers"][:2]
        ('Aspirin', '50-78-2', ['50-78-2', '11126-35-5'])
    """
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE DTXSID = ?
    """,
        (dtxsid,),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)

    # Parse identifiers
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))

    return result
get_by_casrn(casrn)

Get chemical information by CAS Registry Number.

Parameters:

Name Type Description Default
casrn str

CAS Registry Number (e.g., "50-78-2")

required

Returns:

Type Description
dict

The get_by_dtxsid record, or None if not found. Only the chemical's own CASRN matches; for a retired or alternate number see get_by_alternate_casrn.

Examples:

>>> CompToxID().get_by_casrn("50-78-2")["DTXSID"]
'DTXSID5020108'
Source code in src/provesid/comptox.py
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
def get_by_casrn(self, casrn: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by CAS Registry Number.

    Args:
        casrn (str): CAS Registry Number (e.g., "50-78-2")

    Returns:
        (dict): The
            [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            record, or None if not found. Only
        the chemical's own ``CASRN`` matches; for a retired or alternate
        number see
        [`get_by_alternate_casrn`][provesid.comptox.CompToxID.get_by_alternate_casrn].

    Examples:
        >>> CompToxID().get_by_casrn("50-78-2")["DTXSID"]
        'DTXSID5020108'
    """
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE CASRN = ?
    """,
        (casrn,),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
get_by_alternate_casrn(casrn)

Get the chemical that lists a CAS number other than its own CASRN.

CAS deletes and merges registry numbers, and old datasets still carry the numbers it retired. CompTox keeps them, together with alternate numbers, among a chemical's IDENTIFIER tokens, where get_by_casrn does not look. For example, atrazine is 1912-24-9 but also lists 39400-72-1. This method reads the name index (see build_name_index) for such a number.

It answers only when exactly one chemical lists the number. Of the 83,933 numbers CompTox holds only in IDENTIFIER, four are listed by two unrelated chemicals, and picking one of the two would be a guess. Call get_by_casrn first: a number that is some chemical's own CASRN belongs to that chemical, whatever else lists it.

Parameters:

Name Type Description Default
casrn str

CAS Registry Number (e.g., "39400-72-1")

required

Returns:

Type Description
dict

Chemical information, or None if casrn is not shaped like a CAS number, no chemical lists it, more than one does, or the name index is unavailable (a read-only database that predates it).

Examples:

>>> with CompToxID() as db:
...     db.get_by_alternate_casrn("39400-72-1")["PREFERRED_NAME"]
'Atrazine'
Source code in src/provesid/comptox.py
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
def get_by_alternate_casrn(self, casrn: str) -> Optional[Dict[str, Any]]:
    """
    Get the chemical that lists a CAS number other than its own ``CASRN``.

    CAS deletes and merges registry numbers, and old datasets still carry
    the numbers it retired. CompTox keeps them, together with alternate
    numbers, among a chemical's ``IDENTIFIER`` tokens, where
    [`get_by_casrn`][provesid.comptox.CompToxID.get_by_casrn] does not
    look. For example, atrazine is ``1912-24-9`` but also lists
    ``39400-72-1``. This method reads the name index (see
    [`build_name_index`][provesid.comptox.CompToxID.build_name_index]) for
    such a number.

    It answers only when **exactly one** chemical lists the number.
    Of the 83,933 numbers CompTox holds only in ``IDENTIFIER``, four are
    listed by two unrelated chemicals, and picking one of the two would
    be a guess. Call
    [`get_by_casrn`][provesid.comptox.CompToxID.get_by_casrn] first: a
    number that is some chemical's own ``CASRN`` belongs to that chemical,
    whatever else lists it.

    Args:
        casrn (str): CAS Registry Number (e.g., "39400-72-1")

    Returns:
        (dict): Chemical information, or None if ``casrn`` is not shaped
        like a CAS number, no chemical lists it, more than one does, or the
        name index is unavailable (a read-only database that predates it).

    Examples:
        >>> with CompToxID() as db:                     # doctest: +SKIP
        ...     db.get_by_alternate_casrn("39400-72-1")["PREFERRED_NAME"]
        'Atrazine'
    """
    # IDENTIFIER also holds synonyms; without this, a name one chemical
    # lists would come back as its "alternate CAS number".
    if not _CAS_NUMBER.fullmatch(casrn.strip()):
        return None
    if not self._ensure_name_index():
        return None
    cursor = self.conn.cursor()
    cursor.execute(
        f"""
        SELECT c.* FROM {NAME_INDEX_TABLE} n
        JOIN chemicals c ON c.rowid = n.chemical_rowid
        WHERE n.name_key = ? AND n.kind = ?
        LIMIT 2
    """,
        (name_key(casrn), NAME_KINDS["identifier"]),
    )
    rows = cursor.fetchall()
    if len(rows) != 1:
        if rows:
            self.logger.debug(
                "CAS %s is listed by more than one CompTox chemical; not guessing.",
                casrn,
            )
        return None

    result = dict(rows[0])
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
get_by_inchikey(inchikey)

Get chemical information by InChIKey.

About 11% of CompTox's substances are stored under a non-standard InChIKey (flag N, as in PGRHXDWITVMQBC-UHFFFAOYNA-N). A key is also looked up with its other flag, so a standard key finds those rows where only the flag differs, about 98% of them. The key given is preferred when both exist. The record returned carries the key as CompTox stores it.

The first call adds an index on INCHIKEY to the database, about 1 s and 41 MiB, so that lookups take microseconds rather than a 0.2 s scan. A read-only database is scanned instead.

Parameters:

Name Type Description Default
inchikey str

InChIKey (27 characters), standard or not

required

Returns:

Type Description
dict

The get_by_dtxsid record, or None if not found

Examples:

>>> CompToxID().get_by_inchikey("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")["DTXSID"]
'DTXSID5020108'
>>> CompToxID().get_by_inchikey("PGRHXDWITVMQBC-UHFFFAOYSA-N")["INCHIKEY"]
'PGRHXDWITVMQBC-UHFFFAOYNA-N'
Source code in src/provesid/comptox.py
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
def get_by_inchikey(self, inchikey: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by InChIKey.

    About 11% of CompTox's substances are stored under a non-standard
    InChIKey (flag ``N``, as in ``PGRHXDWITVMQBC-UHFFFAOYNA-N``). A key is
    also looked up with its other flag, so a standard key finds those rows
    where only the flag differs, about 98% of them. The key given is
    preferred when both exist. The record returned carries the key as
    CompTox stores it.

    The first call adds an index on ``INCHIKEY`` to the database, about
    1 s and 41 MiB, so that lookups take microseconds rather than a 0.2 s
    scan. A read-only database is scanned instead.

    Args:
        inchikey (str): InChIKey (27 characters), standard or not

    Returns:
        (dict): The
            [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            record, or None if not found

    Examples:
        >>> CompToxID().get_by_inchikey("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")["DTXSID"]
        'DTXSID5020108'
        >>> CompToxID().get_by_inchikey("PGRHXDWITVMQBC-UHFFFAOYSA-N")["INCHIKEY"]
        'PGRHXDWITVMQBC-UHFFFAOYNA-N'
    """
    self._ensure_lookup_index("INCHIKEY")
    spellings = inchikey_flag_variants(inchikey)
    placeholders = ", ".join("?" * len(spellings))
    cursor = self.conn.cursor()
    cursor.execute(
        f"""
        SELECT * FROM chemicals WHERE INCHIKEY IN ({placeholders})
        ORDER BY INCHIKEY = ? DESC
        LIMIT 1
    """,
        (*spellings, inchikey),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
get_by_smiles(smiles)

Get chemical information by SMILES string.

The first call adds an index on SMILES to the database, about 1 s and 57 MiB, so that lookups take well under a millisecond rather than a 0.17 s scan. A read-only database is scanned instead.

Parameters:

Name Type Description Default
smiles str

SMILES string, matched as a string against CompTox's own: another valid SMILES for the same structure finds nothing

required

Returns:

Type Description
dict

The get_by_dtxsid record, or None if not found

Examples:

>>> db = CompToxID()
>>> db.get_by_smiles("CC(=O)OC1=C(C=CC=C1)C(O)=O")["CASRN"]
'50-78-2'
>>> db.get_by_smiles("CC(=O)OC1=CC=CC=C1C(O)=O") is None
True
Source code in src/provesid/comptox.py
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
def get_by_smiles(self, smiles: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by SMILES string.

    The first call adds an index on ``SMILES`` to the database, about
    1 s and 57 MiB, so that lookups take well under a millisecond rather
    than a 0.17 s scan. A read-only database is scanned instead.

    Args:
        smiles (str): SMILES string, matched as a string against CompTox's
            own: another valid SMILES for the same structure finds nothing

    Returns:
        (dict): The
            [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            record, or None if not found

    Examples:
        >>> db = CompToxID()
        >>> db.get_by_smiles("CC(=O)OC1=C(C=CC=C1)C(O)=O")["CASRN"]
        '50-78-2'
        >>> db.get_by_smiles("CC(=O)OC1=CC=CC=C1C(O)=O") is None
        True
    """
    self._ensure_lookup_index("SMILES")
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE SMILES = ?
    """,
        (smiles,),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
get_by_name(name)

Get chemical information by preferred name (exact match).

Parameters:

Name Type Description Default
name str

Preferred name, case included. search_by_name with exact=True matches any name, ignoring case.

required

Returns:

Type Description
dict

The get_by_dtxsid record, or None if not found

Examples:

>>> db = CompToxID()
>>> db.get_by_name("Aspirin")["CASRN"], db.get_by_name("aspirin")
('50-78-2', None)
Source code in src/provesid/comptox.py
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
def get_by_name(self, name: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by preferred name (exact match).

    Args:
        name (str): Preferred name, case included.
            [`search_by_name`][provesid.comptox.CompToxID.search_by_name]
            with ``exact=True`` matches any name, ignoring case.

    Returns:
        (dict): The
            [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            record, or None if not found

    Examples:
        >>> db = CompToxID()
        >>> db.get_by_name("Aspirin")["CASRN"], db.get_by_name("aspirin")
        ('50-78-2', None)
    """
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE PREFERRED_NAME = ?
    """,
        (name,),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
get_by_dtxcid(dtxcid)

Get chemical information by DTXCID.

The first call adds an index on DTXCID to the database, about 0.6 s and 27 MiB, so that lookups take well under a millisecond rather than a 0.15 s scan. A read-only database is scanned instead.

Parameters:

Name Type Description Default
dtxcid str

DSSTox Compound ID (e.g., "DTXCID101")

required

Returns:

Type Description
dict

The get_by_dtxsid record, or None if not found

Examples:

>>> CompToxID().get_by_dtxcid("DTXCID50108")["PREFERRED_NAME"]
'Aspirin'
Source code in src/provesid/comptox.py
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
def get_by_dtxcid(self, dtxcid: str) -> Optional[Dict[str, Any]]:
    """
    Get chemical information by DTXCID.

    The first call adds an index on ``DTXCID`` to the database, about
    0.6 s and 27 MiB, so that lookups take well under a millisecond rather
    than a 0.15 s scan. A read-only database is scanned instead.

    Args:
        dtxcid (str): DSSTox Compound ID (e.g., "DTXCID101")

    Returns:
        (dict): The
            [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            record, or None if not found

    Examples:
        >>> CompToxID().get_by_dtxcid("DTXCID50108")["PREFERRED_NAME"]
        'Aspirin'
    """
    self._ensure_lookup_index("DTXCID")
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE DTXCID = ?
    """,
        (dtxcid,),
    )

    row = cursor.fetchone()
    if not row:
        return None

    result = dict(row)
    result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
    return result
search_by_name(name, exact=False, limit=10)

Search chemicals by name or synonym.

With exact=True the query is compared, case-insensitively, with every name the database holds for a chemical: its preferred name, its IUPAC name and each synonym or identifier in IDENTIFIER. Chemicals called the query come first, then those whose IUPAC name it is, then those that list it as a synonym; ties keep the database's order. This reads the name index, which the first exact call builds if the database predates it (see build_name_index); on a read-only file without one, only preferred names are matched, case-sensitively, as before the index existed.

With exact=False the query is matched as a substring, first of the preferred name and then of IDENTIFIER. That is a full scan, about 3 s a call.

Parameters:

Name Type Description Default
name str

Chemical name or synonym to search for

required
exact bool

If True, exact (case-insensitive) match on any name. If False, partial match (case-insensitive)

False
limit int

Maximum number of results to return

10

Returns:

Type Description
list

List of matching chemicals

Examples:

>>> with CompToxID() as db:
...     [r["PREFERRED_NAME"] for r in db.search_by_name("Acetaldoxime", exact=True)]
['Acetaldehyde oxime']
Source code in src/provesid/comptox.py
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
def search_by_name(
    self, name: str, exact: bool = False, limit: int = 10
) -> List[Dict[str, Any]]:
    """
    Search chemicals by name or synonym.

    With ``exact=True`` the query is compared, case-insensitively, with
    every name the database holds for a chemical: its preferred name, its
    IUPAC name and each synonym or identifier in ``IDENTIFIER``.  Chemicals
    *called* the query come first, then those whose IUPAC name it is, then
    those that list it as a synonym; ties keep the database's order.  This
    reads the name index, which the first exact call builds if the database
    predates it (see
    [`build_name_index`][provesid.comptox.CompToxID.build_name_index]); on
    a read-only file without one, only preferred names are matched,
    case-sensitively, as before the index existed.

    With ``exact=False`` the query is matched as a substring, first of the
    preferred name and then of ``IDENTIFIER``.  That is a full scan, about
    3 s a call.

    Args:
        name (str): Chemical name or synonym to search for
        exact (bool): If True, exact (case-insensitive) match on any name.
            If False, partial match (case-insensitive)
        limit (int): Maximum number of results to return

    Returns:
        (list): List of matching chemicals

    Examples:
        >>> with CompToxID() as db:                     # doctest: +SKIP
        ...     [r["PREFERRED_NAME"] for r in db.search_by_name("Acetaldoxime", exact=True)]
        ['Acetaldehyde oxime']
    """
    cursor = self.conn.cursor()
    results = []

    if exact and self._ensure_name_index():
        cursor.execute(
            f"""
            SELECT c.* FROM {NAME_INDEX_TABLE} n
            JOIN chemicals c ON c.rowid = n.chemical_rowid
            WHERE n.name_key = ?
            ORDER BY n.kind, n.chemical_rowid
            LIMIT ?
        """,
            (name_key(name), limit),
        )
    elif exact:
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE PREFERRED_NAME = ? LIMIT ?
        """,
            (name, limit),
        )
    else:
        # Partial match with LIKE (case-insensitive)
        search_term = f"%{name}%"
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE PREFERRED_NAME LIKE ? LIMIT ?
        """,
            (search_term, limit),
        )

    rows = cursor.fetchall()
    for row in rows:
        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        results.append(result)

    # If not enough results and not exact, also search in identifiers
    if len(results) < limit and not exact:
        search_term = f"%{name}%"
        cursor.execute(
            """
            SELECT * FROM chemicals WHERE IDENTIFIER LIKE ? LIMIT ?
        """,
            (search_term, limit - len(results)),
        )

        # Need to deduplicate by DTXSID
        seen_dtxsids = {r["DTXSID"] for r in results}
        for row in cursor.fetchall():
            if row["DTXSID"] not in seen_dtxsids:
                result = dict(row)
                result["identifiers"] = self._parse_identifiers(
                    result.get("IDENTIFIER")
                )
                results.append(result)
                seen_dtxsids.add(row["DTXSID"])
            if len(results) >= limit:
                break

    return results
search_by_formula(formula, limit=100)

Search chemicals by molecular formula.

The first call adds an index on MOLECULAR_FORMULA to the database, about 0.7 s and 21 MiB, so that a formula no chemical has is answered at once rather than after a 0.16 s scan. A read-only database is scanned instead.

Parameters:

Name Type Description Default
formula str

Molecular formula (e.g., "C9H8O4")

required
limit int

Maximum number of results to return

100

Returns:

Type Description
list

get_by_dtxsid records, in database order

Examples:

>>> [r["PREFERRED_NAME"] for r in CompToxID().search_by_formula("C9H8O4", limit=2)]
['Aspirin', '3,4-Dihydroxycinnamic acid']
Source code in src/provesid/comptox.py
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
def search_by_formula(self, formula: str, limit: int = 100) -> List[Dict[str, Any]]:
    """
    Search chemicals by molecular formula.

    The first call adds an index on ``MOLECULAR_FORMULA`` to the
    database, about 0.7 s and 21 MiB, so that a formula no chemical has
    is answered at once rather than after a 0.16 s scan. A read-only
    database is scanned instead.

    Args:
        formula (str): Molecular formula (e.g., "C9H8O4")
        limit (int): Maximum number of results to return

    Returns:
        (list): [`get_by_dtxsid`][provesid.comptox.CompToxID.get_by_dtxsid]
            records, in database order

    Examples:
        >>> [r["PREFERRED_NAME"] for r in CompToxID().search_by_formula("C9H8O4", limit=2)]
        ['Aspirin', '3,4-Dihydroxycinnamic acid']
    """
    self._ensure_lookup_index("MOLECULAR_FORMULA")
    cursor = self.conn.cursor()
    cursor.execute(
        """
        SELECT * FROM chemicals WHERE MOLECULAR_FORMULA = ? LIMIT ?
    """,
        (formula, limit),
    )

    results = []
    for row in cursor.fetchall():
        result = dict(row)
        result["identifiers"] = self._parse_identifiers(result.get("IDENTIFIER"))
        results.append(result)

    return results
casrn_to_dtxsid(casrn)

Convert CAS Registry Number to DTXSID.

Parameters:

Name Type Description Default
casrn str

CAS Registry Number.

required

Returns:

Type Description
Optional[str]

The DTXSID, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.casrn_to_dtxsid("50-78-2")
'DTXSID5020108'
Source code in src/provesid/comptox.py
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
def casrn_to_dtxsid(self, casrn: str) -> Optional[str]:
    """
    Convert CAS Registry Number to DTXSID.

    Args:
        casrn: CAS Registry Number.

    Returns:
        The DTXSID, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.casrn_to_dtxsid("50-78-2")
        'DTXSID5020108'
    """
    result = self.get_by_casrn(casrn)
    return result["DTXSID"] if result else None
casrn_to_inchikey(casrn)

Convert CAS Registry Number to InChIKey.

Parameters:

Name Type Description Default
casrn str

CAS Registry Number.

required

Returns:

Type Description
Optional[str]

The InChIKey, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.casrn_to_inchikey("50-78-2")
'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
Source code in src/provesid/comptox.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def casrn_to_inchikey(self, casrn: str) -> Optional[str]:
    """
    Convert CAS Registry Number to InChIKey.

    Args:
        casrn: CAS Registry Number.

    Returns:
        The InChIKey, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.casrn_to_inchikey("50-78-2")
        'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
    """
    result = self.get_by_casrn(casrn)
    return result["INCHIKEY"] if result else None
casrn_to_smiles(casrn)

Convert CAS Registry Number to SMILES.

Parameters:

Name Type Description Default
casrn str

CAS Registry Number.

required

Returns:

Type Description
Optional[str]

CompTox's SMILES, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.casrn_to_smiles("50-78-2")
'CC(=O)OC1=C(C=CC=C1)C(O)=O'
Source code in src/provesid/comptox.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
def casrn_to_smiles(self, casrn: str) -> Optional[str]:
    """
    Convert CAS Registry Number to SMILES.

    Args:
        casrn: CAS Registry Number.

    Returns:
        CompTox's SMILES, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.casrn_to_smiles("50-78-2")
        'CC(=O)OC1=C(C=CC=C1)C(O)=O'
    """
    result = self.get_by_casrn(casrn)
    return result["SMILES"] if result else None
inchikey_to_casrn(inchikey)

Convert InChIKey to CAS Registry Number.

Parameters:

Name Type Description Default
inchikey str

Standard InChIKey.

required

Returns:

Type Description
Optional[str]

The CAS number, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.inchikey_to_casrn("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
'50-78-2'
Source code in src/provesid/comptox.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
def inchikey_to_casrn(self, inchikey: str) -> Optional[str]:
    """
    Convert InChIKey to CAS Registry Number.

    Args:
        inchikey: Standard InChIKey.

    Returns:
        The CAS number, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.inchikey_to_casrn("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
        '50-78-2'
    """
    result = self.get_by_inchikey(inchikey)
    return result["CASRN"] if result else None
inchikey_to_dtxsid(inchikey)

Convert InChIKey to DTXSID.

Parameters:

Name Type Description Default
inchikey str

Standard InChIKey.

required

Returns:

Type Description
Optional[str]

The DTXSID, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.inchikey_to_dtxsid("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
'DTXSID5020108'
Source code in src/provesid/comptox.py
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def inchikey_to_dtxsid(self, inchikey: str) -> Optional[str]:
    """
    Convert InChIKey to DTXSID.

    Args:
        inchikey: Standard InChIKey.

    Returns:
        The DTXSID, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.inchikey_to_dtxsid("BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
        'DTXSID5020108'
    """
    result = self.get_by_inchikey(inchikey)
    return result["DTXSID"] if result else None
dtxsid_to_casrn(dtxsid)

Convert DTXSID to CAS Registry Number.

Parameters:

Name Type Description Default
dtxsid str

DSSTox Substance ID.

required

Returns:

Type Description
Optional[str]

The CAS number, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.dtxsid_to_casrn("DTXSID5020108")
'50-78-2'
Source code in src/provesid/comptox.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
def dtxsid_to_casrn(self, dtxsid: str) -> Optional[str]:
    """
    Convert DTXSID to CAS Registry Number.

    Args:
        dtxsid: DSSTox Substance ID.

    Returns:
        The CAS number, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.dtxsid_to_casrn("DTXSID5020108")
        '50-78-2'
    """
    result = self.get_by_dtxsid(dtxsid)
    return result["CASRN"] if result else None
dtxsid_to_inchikey(dtxsid)

Convert DTXSID to InChIKey.

Parameters:

Name Type Description Default
dtxsid str

DSSTox Substance ID.

required

Returns:

Type Description
Optional[str]

The InChIKey, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.dtxsid_to_inchikey("DTXSID5020108")
'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
Source code in src/provesid/comptox.py
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def dtxsid_to_inchikey(self, dtxsid: str) -> Optional[str]:
    """
    Convert DTXSID to InChIKey.

    Args:
        dtxsid: DSSTox Substance ID.

    Returns:
        The InChIKey, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.dtxsid_to_inchikey("DTXSID5020108")
        'BSYNRYMUTXBXSQ-UHFFFAOYSA-N'
    """
    result = self.get_by_dtxsid(dtxsid)
    return result["INCHIKEY"] if result else None
dtxsid_to_smiles(dtxsid)

Convert DTXSID to SMILES.

Parameters:

Name Type Description Default
dtxsid str

DSSTox Substance ID.

required

Returns:

Type Description
Optional[str]

CompTox's SMILES, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.dtxsid_to_smiles("DTXSID5020108")
'CC(=O)OC1=C(C=CC=C1)C(O)=O'
Source code in src/provesid/comptox.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
def dtxsid_to_smiles(self, dtxsid: str) -> Optional[str]:
    """
    Convert DTXSID to SMILES.

    Args:
        dtxsid: DSSTox Substance ID.

    Returns:
        CompTox's SMILES, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.dtxsid_to_smiles("DTXSID5020108")
        'CC(=O)OC1=C(C=CC=C1)C(O)=O'
    """
    result = self.get_by_dtxsid(dtxsid)
    return result["SMILES"] if result else None
smiles_to_casrn(smiles)

Convert SMILES to CAS Registry Number.

Parameters:

Name Type Description Default
smiles str

SMILES, matched as a string; see get_by_smiles.

required

Returns:

Type Description
Optional[str]

The CAS number, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.smiles_to_casrn("CC(=O)OC1=C(C=CC=C1)C(O)=O")
'50-78-2'
Source code in src/provesid/comptox.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
def smiles_to_casrn(self, smiles: str) -> Optional[str]:
    """
    Convert SMILES to CAS Registry Number.

    Args:
        smiles: SMILES, matched as a string; see
            [`get_by_smiles`][provesid.comptox.CompToxID.get_by_smiles].

    Returns:
        The CAS number, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.smiles_to_casrn("CC(=O)OC1=C(C=CC=C1)C(O)=O")
        '50-78-2'
    """
    result = self.get_by_smiles(smiles)
    return result["CASRN"] if result else None
smiles_to_dtxsid(smiles)

Convert SMILES to DTXSID.

Parameters:

Name Type Description Default
smiles str

SMILES, matched as a string; see get_by_smiles.

required

Returns:

Type Description
Optional[str]

The DTXSID, or None if not found.

Examples:

>>> db = CompToxID()
>>> db.smiles_to_dtxsid("CCO")
'DTXSID9020584'
Source code in src/provesid/comptox.py
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def smiles_to_dtxsid(self, smiles: str) -> Optional[str]:
    """
    Convert SMILES to DTXSID.

    Args:
        smiles: SMILES, matched as a string; see
            [`get_by_smiles`][provesid.comptox.CompToxID.get_by_smiles].

    Returns:
        The DTXSID, or None if not found.

    Examples:
        >>> db = CompToxID()
        >>> db.smiles_to_dtxsid("CCO")
        'DTXSID9020584'
    """
    result = self.get_by_smiles(smiles)
    return result["DTXSID"] if result else None
batch_casrn_to_dtxsid(casrn_list)

Convert multiple CAS numbers to DTXSIDs.

Parameters:

Name Type Description Default
casrn_list list

List of CAS numbers

required

Returns:

Type Description
dict

Mapping of CAS -> DTXSID (None if not found)

Examples:

>>> CompToxID().batch_casrn_to_dtxsid(["50-78-2", "0-00-0"])
{'50-78-2': 'DTXSID5020108', '0-00-0': None}
Source code in src/provesid/comptox.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
def batch_casrn_to_dtxsid(self, casrn_list: List[str]) -> Dict[str, Optional[str]]:
    """
    Convert multiple CAS numbers to DTXSIDs.

    Args:
        casrn_list (list): List of CAS numbers

    Returns:
        (dict): Mapping of CAS -> DTXSID (None if not found)

    Examples:
        >>> CompToxID().batch_casrn_to_dtxsid(["50-78-2", "0-00-0"])
        {'50-78-2': 'DTXSID5020108', '0-00-0': None}
    """
    results = {}
    for casrn in casrn_list:
        results[casrn] = self.casrn_to_dtxsid(casrn)
    return results
batch_casrn_to_inchikey(casrn_list)

Convert multiple CAS numbers to InChIKeys.

Parameters:

Name Type Description Default
casrn_list list

List of CAS numbers

required

Returns:

Type Description
dict

Mapping of CAS -> InChIKey (None if not found)

Examples:

>>> CompToxID().batch_casrn_to_inchikey(["50-78-2", "0-00-0"])
{'50-78-2': 'BSYNRYMUTXBXSQ-UHFFFAOYSA-N', '0-00-0': None}
Source code in src/provesid/comptox.py
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def batch_casrn_to_inchikey(
    self, casrn_list: List[str]
) -> Dict[str, Optional[str]]:
    """
    Convert multiple CAS numbers to InChIKeys.

    Args:
        casrn_list (list): List of CAS numbers

    Returns:
        (dict): Mapping of CAS -> InChIKey (None if not found)

    Examples:
        >>> CompToxID().batch_casrn_to_inchikey(["50-78-2", "0-00-0"])
        {'50-78-2': 'BSYNRYMUTXBXSQ-UHFFFAOYSA-N', '0-00-0': None}
    """
    results = {}
    for casrn in casrn_list:
        results[casrn] = self.casrn_to_inchikey(casrn)
    return results
batch_inchikey_to_casrn(inchikey_list)

Convert multiple InChIKeys to CAS numbers.

Parameters:

Name Type Description Default
inchikey_list list

List of InChIKeys

required

Returns:

Type Description
dict

Mapping of InChIKey -> CAS (None if not found)

Examples:

>>> CompToxID().batch_inchikey_to_casrn(
...     ["BSYNRYMUTXBXSQ-UHFFFAOYSA-N", "LFQSCWFLJHTTHZ-UHFFFAOYSA-N"])
{'BSYNRYMUTXBXSQ-UHFFFAOYSA-N': '50-78-2', 'LFQSCWFLJHTTHZ-UHFFFAOYSA-N': '64-17-5'}
Source code in src/provesid/comptox.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
def batch_inchikey_to_casrn(
    self, inchikey_list: List[str]
) -> Dict[str, Optional[str]]:
    """
    Convert multiple InChIKeys to CAS numbers.

    Args:
        inchikey_list (list): List of InChIKeys

    Returns:
        (dict): Mapping of InChIKey -> CAS (None if not found)

    Examples:
        >>> CompToxID().batch_inchikey_to_casrn(
        ...     ["BSYNRYMUTXBXSQ-UHFFFAOYSA-N", "LFQSCWFLJHTTHZ-UHFFFAOYSA-N"])
        {'BSYNRYMUTXBXSQ-UHFFFAOYSA-N': '50-78-2', 'LFQSCWFLJHTTHZ-UHFFFAOYSA-N': '64-17-5'}
    """
    results = {}
    for inchikey in inchikey_list:
        results[inchikey] = self.inchikey_to_casrn(inchikey)
    return results

Functions:

name_key(name)

The form a name is indexed and looked up under: stripped and lower-cased.

Python's str.lower rather than SQLite's lower(), which folds ASCII only; the same function builds the index and reads it, so the two always agree.

Parameters:

Name Type Description Default
name str

A chemical name or other identifier.

required

Returns:

Type Description
str

The lookup key.

Examples:

>>> name_key("  Acetylsalicylic Acid ")
'acetylsalicylic acid'
Source code in src/provesid/comptox.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def name_key(name: str) -> str:
    """The form a name is indexed and looked up under: stripped and lower-cased.

    Python's `str.lower` rather than SQLite's ``lower()``, which folds
    ASCII only; the same function builds the index and reads it, so the two
    always agree.

    Args:
        name: A chemical name or other identifier.

    Returns:
        The lookup key.

    Examples:
        >>> name_key("  Acetylsalicylic Acid ")
        'acetylsalicylic acid'
    """
    return name.strip().lower()