Skip to content

ZeroPM

Offline: the ZeroPM global chemical inventory. Search leaves it out unless its sources names "zeropm". See the ZeroPM tutorial.

provesid.zeropm

The ZeroPM global chemical inventory, offline: ZeroPM.

ZeroPM (https://zeropm.eu) merged 25 national and regional chemical inventories --- TSCA, the EC Inventory, Japan's CSCL, China's IECSC and others --- into one SQLite file, resolved every listed CAS number and name to structures, and scored the structures for persistence and mobility. Version 0.0.4 holds 164 513 CAS numbers, 283 104 names and 359 221 structures.

Its tables, and the names this class uses for them:

api_ready_query Every query string --- a CAS number or a name --- with its query_id. Names are stored as the inventories spelled them, so matching is exact and case-sensitive. api_results The structures (inchi_id) each query resolved to, with a rank. Rank 1 is the resolver's best answer. Lower ranks are often a different compound entirely: the name formaldehyde reaches methane at rank 2. substances One row per structure: inchi_id, InChI and InChIKey. zeropm_chemicals, pm_probabilities The structures ZeroPM assessed (zeropm_id) and their probabilities of being persistent and mobile.

The methods that follow every rank (get_cas_from_name, get_cas_from_inchi and the get_id_table_from_* family) are broad rather than precise; filter a table on rank == 1 for the best answer. This is why Search leaves ZeroPM out of its default vote.

SMILES are not stored. They are written from the InChI with RDKit on demand.

Examples:

>>> from provesid import ZeroPM
>>> with ZeroPM() as zpm:
...     zpm.get_smiles_from_cas("64-17-5")
...     zpm.get_zeropm_id(cas="64-17-5")
'CCO'
1452

Attributes

PM_PROBABILITY_COLUMNS module-attribute

The probability fields every reader returns, in order.

not_p + p_or_vp = 1 and p + vp = p_or_vp, and the same for M.

Classes

ZeroPM

Bases: SQLiteClient

Class to extract data from the ZeroPM SQLite database using SQL queries. This class provides the same functionality as ZeroPM but uses SQL instead of pandas. SMILES are generated on-the-fly from InChI using RDKit.

The database file will be automatically downloaded if not found locally.

Connection handling comes from SQLiteClient: use the class as a context manager, or call close when finished, and query it from as many threads as you like --- each gets its own connection. This is the one client that also writes (create_indexes, create_view); SQLite serialises those against the reading connections.

Example

with ZeroPM() as zpm: ... df = zpm.get_id_table_from_cas("50-00-0") ... df[["cas", "rank", "inchikey", "zeropm_id"]].to_dict("records") [{'cas': '50-00-0', 'rank': 1, 'inchikey': 'WSFSSNUMVMOOMR-UHFFFAOYSA-N', 'zeropm_id': 3224}]

Source code in src/provesid/zeropm.py
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
class ZeroPM(SQLiteClient):
    """
    Class to extract data from the ZeroPM SQLite database using SQL queries.
    This class provides the same functionality as ZeroPM but uses SQL instead of pandas.
    SMILES are generated on-the-fly from InChI using RDKit.

    The database file will be automatically downloaded if not found locally.

    Connection handling comes from
    [`SQLiteClient`][provesid.sqlite_client.SQLiteClient]: use the class 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.  This is the one client that also *writes*
    ([`create_indexes`][provesid.zeropm.ZeroPM.create_indexes],
    [`create_view`][provesid.zeropm.ZeroPM.create_view]); SQLite serialises
    those against the reading connections.

    Example
    -------
    >>> with ZeroPM() as zpm:
    ...     df = zpm.get_id_table_from_cas("50-00-0")
    ...     df[["cas", "rank", "inchikey", "zeropm_id"]].to_dict("records")
    [{'cas': '50-00-0', 'rank': 1, 'inchikey': 'WSFSSNUMVMOOMR-UHFFFAOYSA-N', 'zeropm_id': 3224}]
    """

    # Default download URL for the ZeroPM database
    DEFAULT_DB_URL = "https://github.com/ZeroPM-H2020/global-chemical-inventory-database/raw/refs/heads/main/zeropm-v0-0-4.sqlite"

    def __init__(
        self,
        db_name: str = 'zeropm-v0-0-4.sqlite',
        auto_download: bool = True,
        db_url: Optional[str] = None,
        data_dir: Optional[str] = None,
        db_path: Optional[str] = None,
        redownload: bool = False,
    ):
        """
        Initialize connection to the ZeroPM SQLite database.

        Parameters
        ----------
        db_name : str, optional
            Name of the SQLite database file (default: 'zeropm-v0-0-4.sqlite')
        auto_download : bool, optional
            If True, automatically download the database if not found (default: True)
        db_url : str, optional
            Custom URL to download the database from. If None, uses the default GitHub URL.
        data_dir : str, optional
            Directory to store the database when ``db_path`` is not provided.
        db_path : str, optional
            Full path to a database file. Overrides ``db_name``/``data_dir``.
        redownload : bool, optional
            If True, force re-download when ``auto_download`` is enabled.

        Raises
        ------
        FileNotFoundError
            If the database is not on disk and ``auto_download`` is False.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> os.path.basename(zpm.db_path)
        'zeropm-v0-0-4.sqlite'
        >>> ZeroPM(db_path="/no/such/zeropm.sqlite", auto_download=False)
        Traceback (most recent call last):
        ...
        FileNotFoundError: Database not found at: /no/such/zeropm.sqlite
        ...
        """
        self.logger = logging.getLogger(__name__)
        if db_path is None:
            self.path = data_dir or user_dataset_path()
            self.db_path = os.path.join(self.path, db_name)
        else:
            self.db_path = os.path.abspath(os.path.expanduser(db_path))
            self.path = os.path.dirname(self.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, download if needed
        if needs_download:
            if auto_download:
                if redownload and os.path.exists(self.db_path):
                    self.logger.info(
                        "Forced ZeroPM redownload requested for: %s", self.db_path
                    )
                else:
                    self.logger.info(f"Database not found at: {self.db_path}")
                self.logger.info("Downloading database automatically...")
                self.download_database(url=self.db_url, force=redownload)
            else:
                raise FileNotFoundError(
                    f"Database not found at: {self.db_path}\n"
                    f"Please run ZeroPM.download_database() or set auto_download=True"
                )

        # Create the connection.  One per thread, reused for every query on
        # that thread and released by close() or by leaving a ``with`` block.
        # row_factory stays unset: this module's queries index rows by
        # position, and sqlite3.Row would be a behaviour change.
        self._open_database(self.db_path, row_factory=None)

        # Cache chemical names for fuzzy matching (lazy loading)
        self._chemical_names_cache = None

    def download_database(self, url=None, force=False):
        """
        Download the ZeroPM SQLite database from a remote URL.

        The transfer is resumable: an interrupted download leaves a ``.part``
        file beside the destination and the next call continues from it rather
        than starting the 100 MB again. Nothing replaces an existing database
        until the new file has downloaded in full and opened successfully.

        Parameters
        ----------
        url : str, optional
            URL to download the database from. If None, uses the default GitHub URL.
        force : bool, optional
            If True, download even if the database already exists (default: False)

        Returns
        -------
        str
            Path to the downloaded database file

        Raises
        ------
        FileExistsError
            If the database already exists and force=False
        provesid.datasets.DownloadError
            If the download could not be completed, or the file that arrived is
            not a readable SQLite database

        Example
        -------
        >>> zpm = ZeroPM()
        >>> zpm.download_database(force=True)      # doctest: +SKIP
        '/home/me/.local/share/provesid/zeropm-v0-0-4.sqlite'
        """
        download_url = url or self.db_url

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

        def must_be_a_database(path):
            """Reject a download that is not a readable SQLite file.

            Run on the ``.part`` file, before it is moved into place, so a
            damaged download leaves any existing database untouched.
            """
            connection = sqlite3.connect(path)
            try:
                connection.execute(
                    "SELECT name FROM sqlite_master WHERE type='table' LIMIT 1"
                ).fetchone()
            except sqlite3.Error as exc:
                raise RuntimeError(f"Downloaded database is corrupted: {exc}") from exc
            finally:
                connection.close()

        download_file(
            download_url,
            self.db_path,
            verify=must_be_a_database,
            description="ZeroPM database",
            log=self.logger,
        )
        return self.db_path

    def _get_chemical_names_cache(self):
        """
        Lazy load and cache all chemical names for fuzzy matching.
        Returns a list of (name, query_id) tuples.
        """
        if self._chemical_names_cache is None:
            self.cursor.execute("""
                SELECT query, query_id
                FROM api_ready_query
                WHERE type = 'chemical name'
            """)
            self._chemical_names_cache = self.cursor.fetchall()
        return self._chemical_names_cache

    def _inchi_to_smiles(self, inchi):
        """
        Convert InChI string to SMILES using RDKit.

        Parameters
        ----------
        inchi : str
            InChI string

        Returns
        -------
        str or None
            SMILES string, or None if conversion fails
        """
        try:
            mol = Chem.MolFromInchi(inchi)
            if mol is None:
                return None
            return Chem.MolToSmiles(mol)
        except Exception as e:
            logging.warning(f"Error converting InChI to SMILES: {e}")
            return None

    def _find_substance_by_inchikey(self, inchikey):
        """The ``substances`` row stored under an InChIKey, in either flag spelling.

        About 5% of ZeroPM's substances are stored under a non-standard InChI
        and InChIKey. The key is looked up as given and with its other flag
        (``...SA-N`` / ``...NA-N``, see
        [`inchikey_flag_variants`][provesid.utils.inchikey_flag_variants]),
        preferring the key as given.

        Parameters
        ----------
        inchikey : str
            InChIKey, standard or not

        Returns
        -------
        tuple or None
            ``(inchi_id, inchi, inchikey)`` as stored, or None
        """
        spellings = inchikey_flag_variants(inchikey)
        placeholders = ", ".join("?" * len(spellings))
        self.cursor.execute(f"""
            SELECT inchi_id, inchi, inchikey
            FROM substances
            WHERE inchikey IN ({placeholders})
            ORDER BY inchikey = ? DESC
            LIMIT 1
        """, (*spellings, inchikey))
        return self.cursor.fetchone()

    def _find_substance_by_inchi(self, inchi):
        """The ``substances`` row an InChI names, stored standard or not.

        The InChI is matched as a string first. When that misses, its
        InChIKey is computed with RDKit and looked up in both flag spellings
        (see
        [`_find_substance_by_inchikey`][provesid.zeropm.ZeroPM._find_substance_by_inchikey]).
        That lets a standard InChI (``InChI=1S/...``) find a substance
        stored only under a non-standard one (``InChI=1/...``) whose key
        differs by the flag alone, and the reverse. A non-standard InChI with
        relative stereo (``/s2``) hashes differently from any standard one
        and is still not found.

        Parameters
        ----------
        inchi : str
            InChI string, standard or not

        Returns
        -------
        tuple or None
            ``(inchi_id, inchi, inchikey)`` as stored, or None when neither
            the string nor its key is in the database, or when the string is
            not an InChI
        """
        self.cursor.execute("""
            SELECT inchi_id, inchi, inchikey
            FROM substances
            WHERE inchi = ?
        """, (inchi,))
        row = self.cursor.fetchone()
        if row or not str(inchi).startswith("InChI="):
            return row
        with rdBase.BlockLogs():
            inchikey = Chem.InchiToInchiKey(inchi)
        return self._find_substance_by_inchikey(inchikey) if inchikey else None

    def query_cas(self, cas_rn):
        """
        Returns a query id from the query with the CAS RN to be used with the query_results function.

        Parameters
        ----------
        cas_rn : str
            CAS Registry Number

        Returns
        -------
        int or None
            query_id if found, None otherwise

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.query_cas("50-00-0")
        8671
        >>> zpm.query_cas("0-00-0") is None
        True
        """
        self.cursor.execute("""
            SELECT query_id
            FROM api_ready_query
            WHERE query = ? AND type = 'CAS Registry Number'
        """, (cas_rn,))
        result = self.cursor.fetchone()
        return result[0] if result else None

    def query_name(self, name):
        """
        Returns a query id from the query with the exact chemical name to be used with the query_results function.

        Parameters
        ----------
        name : str
            Exact chemical name, case included: the inventories' spellings
            are separate queries.

        Returns
        -------
        int or None
            query_id if found, None otherwise

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.query_name("Formaldehyde"), zpm.query_name("formaldehyde")
        (8672, 325578)
        """
        self.cursor.execute("""
            SELECT query_id
            FROM api_ready_query
            WHERE query = ? AND type = 'chemical name'
        """, (name,))
        result = self.cursor.fetchone()
        return result[0] if result else None

    def query_similar_name(self, name, number_of_results=5, score_cutoff=80):
        """
        Returns number_of_results query ids from a query with similar chemical names
        using fuzzy string matching.

        Parameters
        ----------
        name : str
            Chemical name to search for
        number_of_results : int, optional
            Maximum number of results to return (default: 5)
        score_cutoff : int, optional
            Minimum similarity score (0-100) (default: 80)

        Returns
        -------
        list or None
            List of query_ids, or None if no matches above cutoff

        Notes
        -----
        Scores with ``rapidfuzz``'s ``WRatio``, which rates a short name
        highly whenever it appears inside the query.
        [`match_similar_name`][provesid.zeropm.ZeroPM.match_similar_name] uses
        a stricter scorer and reports the names and scores.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.query_similar_name("formaldehyd")
        [8672, 8673, 104113, 325578, 367895]
        """
        names_cache = self._get_chemical_names_cache()
        name_list = [n[0] for n in names_cache]

        res = process.extract(
            name,
            name_list,
            scorer=fuzz.WRatio,
            limit=number_of_results,
            processor=utils.default_process,
        )

        if (len(res) < 1) or (res[0][1] < score_cutoff):
            return None
        else:
            # Get query_ids for matching names
            query_ids = []
            for match in res:
                if match[1] >= score_cutoff:
                    matched_name = match[0]
                    # Find the query_id for this name
                    query_id = next((n[1] for n in names_cache if n[0] == matched_name), None)
                    if query_id:
                        query_ids.append(query_id)
            return query_ids if query_ids else None

    def match_similar_name(self, name, number_of_results=5, score_cutoff=80,
                           scorer=None):
        """
        Fuzzy-match a chemical name and return the matches with their scores.

        Same purpose as
        [`query_similar_name`][provesid.zeropm.ZeroPM.query_similar_name], but
        keeps the matched name and the similarity score instead of discarding
        them, so callers can tell *what* matched and *how well*.

        Uses ``rapidfuzz.fuzz.ratio`` rather than the ``WRatio`` used by
        [`query_similar_name`][provesid.zeropm.ZeroPM.query_similar_name].
        ``WRatio`` includes a partial-ratio term that scores a short name
        highly whenever it appears anywhere inside the query, which over a list
        of millions of chemical names is a reliable source of nonsense:
        ``WRatio("caffiene", "ne")`` is 90 and ``WRatio("zzzznotachemical",
        "Mica")`` is also 90, while ``ratio`` puts both at 40 and still scores
        the genuine typo ``ratio("caffiene", "caffeine")`` at 87.5.

        Parameters
        ----------
        name : str
            Chemical name to search for.
        number_of_results : int, optional
            Maximum number of matches to return (default: 5).
        score_cutoff : int, optional
            Minimum similarity score, 0-100 (default: 80).
        scorer : callable, optional
            A ``rapidfuzz.fuzz`` scorer. Defaults to ``fuzz.ratio``. Pass
            ``fuzz.token_sort_ratio`` when word order may differ; avoid
            ``fuzz.WRatio`` for the reason above.

        Returns
        -------
        list of tuple
            ``(matched_name, query_id, score)`` tuples, best first. Empty when
            nothing scores at or above ``score_cutoff``.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> name, query_id, score = zpm.match_similar_name("formaldehyd")[0]
        >>> name, round(score, 1)
        ('Formaldehyde', 95.7)
        >>> zpm.match_similar_name("zzzznotachemical")
        []
        """
        names_cache = self._get_chemical_names_cache()
        query_id_of = {row[0]: row[1] for row in names_cache}

        matches = process.extract(
            name,
            list(query_id_of),
            scorer=scorer or fuzz.ratio,
            limit=number_of_results,
            processor=utils.default_process,
        )

        return [
            (matched_name, query_id_of[matched_name], score)
            for matched_name, score, _ in matches
            if score >= score_cutoff
        ]

    def get_id_table_from_similar_name(self, name, number_of_results=5, score_cutoff=80):
        """
        Returns identifiers for the chemical whose name best fuzzy-matches *name*.

        The fuzzy counterpart of
        [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name]:
        use it when the name may be misspelled or formatted differently from
        the database entry. The table is built for the single best-scoring
        match.

        Parameters
        ----------
        name : str
            Chemical name, possibly misspelled.
        number_of_results : int, optional
            How many fuzzy candidates to consider (default: 5). Only the best
            one is turned into a table.
        score_cutoff : int, optional
            Minimum ``rapidfuzz.fuzz.ratio`` score, 0-100 (default: 80); see
            [`match_similar_name`][provesid.zeropm.ZeroPM.match_similar_name].

        Returns
        -------
        pandas.DataFrame or None
            Same columns as
            [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name],
            with an extra ``matched_name`` column recording what actually
            matched, and ``match_score`` holding its similarity. None when
            nothing scores at or above ``score_cutoff``.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_similar_name("formaldehyd")
        >>> row = df.iloc[0]
        >>> row["name"], row["matched_name"], round(float(row["match_score"]), 1), row["inchikey"]
        ('formaldehyd', 'Formaldehyde', 95.7, 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
        """
        matches = self.match_similar_name(
            name, number_of_results=number_of_results, score_cutoff=score_cutoff
        )
        if not matches:
            self.logger.debug("No fuzzy name match for '%s' at cutoff %s", name, score_cutoff)
            return None

        matched_name, query_id, score = matches[0]
        table = self._id_table_for_query_id(query_id, name)
        if table is None or table.empty:
            return None

        table["matched_name"] = matched_name
        table["match_score"] = score
        return table

    def get_inchi_id(self, query_id):
        """
        Returns all the inchi_id and ranks of a query with a given query_id.

        Parameters
        ----------
        query_id : int
            Query identifier

        Returns
        -------
        tuple of (list, list)
            (inchi_ids, ranks) sorted by rank, with duplicates removed; two
            empty lists when the query has no structures

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_inchi_id(zpm.query_cas("50-00-0"))
        ([32227], [1])
        >>> zpm.get_inchi_id(zpm.query_name("formaldehyde"))
        ([32227, 73275, 27053, 119941], [1, 2, 3, 4])
        """
        self.cursor.execute("""
            SELECT DISTINCT inchi_id, rank
            FROM api_results
            WHERE query_id = ?
            ORDER BY rank
        """, (query_id,))
        results = self.cursor.fetchall()

        if not results:
            return [], []

        # Separate inchi_ids and ranks
        inchi_ids = [r[0] for r in results]
        ranks = [r[1] for r in results]

        return inchi_ids, ranks

    def get_inchi(self, inchi_id):
        """
        Returns the inchi and inchikey string of a given inchi_id.

        Parameters
        ----------
        inchi_id : int
            InChI identifier

        Returns
        -------
        tuple of (str, str) or (None, None)
            (inchi, inchikey) if found, (None, None) otherwise

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_inchi(32227)
        ('InChI=1S/CH2O/c1-2/h1H2', 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
        """
        self.cursor.execute("""
            SELECT inchi, inchikey
            FROM substances
            WHERE inchi_id = ?
        """, (inchi_id,))
        result = self.cursor.fetchone()
        return (result[0], result[1]) if result else (None, None)

    def get_names(self, cas_rn):
        """
        Returns all the names for a CAS number.

        Parameters
        ----------
        cas_rn : str
            CAS Registry Number

        Returns
        -------
        list
            The distinct names the inventories list under this CAS number,
            excluding the CAS number itself, in no particular order. Empty
            when the CAS number is not in the database.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> sorted(zpm.get_names("64-17-5"))[:4]
        ['Alcohol', 'ETHANOL', 'ETHYL ALCOHOL', 'Ethanol']
        """
        query_id = self.query_cas(cas_rn)
        if query_id is None:
            return []

        # Get inventory_ids from inventory_summary
        self.cursor.execute("""
            SELECT inventory_id
            FROM inventory_summary
            WHERE query_id = ?
        """, (query_id,))
        inventory_ids = [row[0] for row in self.cursor.fetchall()]

        if len(inventory_ids) == 0:
            return []

        # Get identifiers from inventories
        names = set()
        for inv_id in inventory_ids:
            self.cursor.execute("""
                SELECT identifier
                FROM inventories
                WHERE inventory_id = ?
            """, (inv_id,))
            result = self.cursor.fetchone()
            if result:
                # Split by semicolon and add to set
                identifier_string = result[0]
                for name in identifier_string.split(';'):
                    name = name.strip()
                    if name and name != cas_rn:
                        names.add(name)

        return list(names)

    def get_smiles_from_cas(self, cas_rn):
        """
        Returns the SMILES from a CAS number.
        SMILES is generated on-the-fly from InChI using RDKit.

        Parameters
        ----------
        cas_rn : str
            CAS Registry Number

        Returns
        -------
        str or None
            SMILES string of the rank-1 structure, or None if not found

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_smiles_from_cas("50-00-0")
        'C=O'
        """
        query_id = self.query_cas(cas_rn)
        if query_id is None:
            return None

        # Get inchi_id from the query_id
        inchi_ids, _ = self.get_inchi_id(query_id)
        if len(inchi_ids) == 0:
            return None

        # Get InChI and convert to SMILES
        inchi, _ = self.get_inchi(inchi_ids[0])
        if inchi is None:
            return None

        return self._inchi_to_smiles(inchi)

    def get_cas_from_inchi(self, inchi):
        """
        Returns the CAS number(s) from an InChI string.

        The InChI is found as in
        [`get_id_table_from_inchi`][provesid.zeropm.ZeroPM.get_id_table_from_inchi]:
        as a string, else by its InChIKey with either flag.

        Parameters
        ----------
        inchi : str
            InChI string, standard or not

        Returns
        -------
        str, list, or None
            CAS number, list of CAS numbers, or None if not found. Every CAS
            number whose query reaches this structure at any rank, so the
            list includes relatives: formaldehyde's includes carbon
            monoxide's ``630-08-0``, which reaches it at rank 2. The order is
            the order ZeroPM stored its results in, which is not a ranking
            but often puts the main number first: ethanol's list starts
            ``64-17-5`` and caffeine's ``58-08-2``.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> cas = zpm.get_cas_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
        >>> "50-00-0" in cas, "630-08-0" in cas
        (True, True)
        >>> zpm.get_cas_from_inchi("InChI=1S/Xx") is None
        True
        """
        # First, find the inchi_id
        result = self._find_substance_by_inchi(inchi)
        if not result:
            return None

        inchi_id = result[0]

        # Find all query_ids for this inchi_id that are CAS numbers, in the
        # order ZeroPM stored its results
        self.cursor.execute("""
            SELECT aq.query
            FROM api_results ar
            JOIN api_ready_query aq ON ar.query_id = aq.query_id
            WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
            GROUP BY aq.query
            ORDER BY MIN(ar.rowid)
        """, (inchi_id,))
        cas_numbers = [row[0] for row in self.cursor.fetchall()]

        if not cas_numbers:
            return None
        elif len(cas_numbers) == 1:
            return cas_numbers[0]
        else:
            return cas_numbers

    def get_cas_from_inchikey(self, inchikey):
        """
        Returns the CAS number(s) from an InChIKey.

        The key is looked up with either flag, as in
        [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].

        Parameters
        ----------
        inchikey : str
            InChIKey string, standard or not

        Returns
        -------
        str, list, or None
            CAS number, list of CAS numbers, or None if not found; as broad
            as [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> "64-17-5" in zpm.get_cas_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
        True
        """
        # First, find the inchi_id, under either flag spelling
        result = self._find_substance_by_inchikey(inchikey)
        if not result:
            return None

        inchi_id = result[0]

        # Find all query_ids for this inchi_id that are CAS numbers, in the
        # order ZeroPM stored its results
        self.cursor.execute("""
            SELECT aq.query
            FROM api_results ar
            JOIN api_ready_query aq ON ar.query_id = aq.query_id
            WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
            GROUP BY aq.query
            ORDER BY MIN(ar.rowid)
        """, (inchi_id,))
        cas_numbers = [row[0] for row in self.cursor.fetchall()]

        if not cas_numbers:
            return None
        elif len(cas_numbers) == 1:
            return cas_numbers[0]
        else:
            return cas_numbers

    def get_smiles_from_inchikey(self, inchikey):
        """
        Returns the SMILES from an InChIKey.
        SMILES is generated on-the-fly from InChI using RDKit. The key is
        looked up with either flag, as in
        [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].

        Parameters
        ----------
        inchikey : str
            InChIKey string, standard or not

        Returns
        -------
        str or None
            SMILES string, or None if not found

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_smiles_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
        'CCO'
        """
        # Get InChI from InChIKey, under either flag spelling
        result = self._find_substance_by_inchikey(inchikey)

        if not result:
            return None

        inchi = result[1]
        return self._inchi_to_smiles(inchi)

    def get_cas_from_smiles(self, smiles):
        """
        Returns the CAS number from a SMILES string.
        This is done by converting the SMILES to InChI and then to CAS number.

        Parameters
        ----------
        smiles : str
            SMILES string

        Returns
        -------
        str, list, or None
            CAS number, list of CAS numbers, or None if not found or the
            SMILES cannot be parsed; as broad as
            [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> "64-17-5" in zpm.get_cas_from_smiles("OCC")
        True
        """
        try:
            mol = Chem.MolFromSmiles(smiles)
            if mol is None:
                logging.warning(f"Invalid SMILES: {smiles}")
                return None
            inchi = Chem.MolToInchi(mol)
        except Exception as e:
            logging.warning(f"Error converting SMILES to InChI for smiles: {smiles}. Error: {e}")
            return None

        return self.get_cas_from_inchi(inchi)

    def get_cas_from_name(self, name):
        """
        Returns the CAS number(s) associated with a chemical name.

        This method performs an exact match search for the chemical name in the database.
        For fuzzy matching, use query_similar_name() first to get query_ids.

        The answer is broad: it is every CAS number that reaches any of the
        structures the name resolved to, at any rank. For
        ``"formaldehyde"`` that is 31 numbers, methane's and carbon's among
        them.
        [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name]
        shows where each came from.

        Parameters
        ----------
        name : str
            Chemical name (exact match)

        Returns
        -------
        str, list, or None
            CAS number, list of CAS numbers, or None if not found

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> cas = zpm.get_cas_from_name("formaldehyde")
        >>> len(cas), "50-00-0" in cas, "74-82-8" in cas
        (31, True, True)
        >>> zpm.get_cas_from_name("acetylsalicylic acid") is None
        True
        """
        # Get query_id for this name
        query_id = self.query_name(name)
        if query_id is None:
            return None

        # Get inchi_ids for this query_id
        inchi_ids, _ = self.get_inchi_id(query_id)
        if not inchi_ids:
            return None

        # Collect all CAS numbers for all inchi_ids
        all_cas = set()
        for inchi_id in inchi_ids:
            # Get InChI for this inchi_id
            inchi, _ = self.get_inchi(inchi_id)
            if inchi:
                cas_result = self.get_cas_from_inchi(inchi)
                if cas_result:
                    if isinstance(cas_result, list):
                        all_cas.update(cas_result)
                    else:
                        all_cas.add(cas_result)

        if not all_cas:
            return None
        elif len(all_cas) == 1:
            return list(all_cas)[0]
        else:
            return sorted(list(all_cas))

    def get_cas_from_formula(self, formula):
        """
        Returns CAS numbers for chemicals matching a molecular formula.

        Note: Molecular formulas are not unique identifiers - many different chemicals
        can have the same formula (isomers). This method returns all CAS numbers
        for chemicals matching the given formula.

        Parameters
        ----------
        formula : str
            Molecular formula (e.g., "H2O", "C6H12O6", "CH2O")

        Returns
        -------
        list or None
            List of CAS numbers matching the formula, or None if not found

        Warning
        -------
        This method can be slow as it needs to parse all InChI strings to extract
        molecular formulas. Consider caching results for frequently used formulas.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_cas_from_formula("CH2O")  # Formaldehyde
        ['108-62-3', '1664-98-8', '30525-89-4', '3228-27-1', '50-00-0', '630-08-0', '63101-50-8']
        """
        # Normalize formula (basic normalization - can be improved)
        formula = formula.replace(" ", "")

        # Query all substances and check their formulas
        # InChI format: InChI=1S/CH2O/c1-2/h1H2
        # Formula is between the first two slashes
        self.cursor.execute("""
            SELECT DISTINCT s.inchi_id, s.inchi
            FROM substances s
            WHERE s.inchi IS NOT NULL
        """)

        matching_inchi_ids = []
        for inchi_id, inchi in self.cursor.fetchall():
            try:
                # Extract formula from InChI
                # Format: InChI=1S/FORMULA/...
                parts = inchi.split('/')
                if len(parts) >= 2:
                    inchi_formula = parts[1]
                    if inchi_formula == formula:
                        matching_inchi_ids.append(inchi_id)
            except Exception:
                continue

        if not matching_inchi_ids:
            return None

        # Get all CAS numbers for matching inchi_ids
        all_cas = set()
        for inchi_id in matching_inchi_ids:
            self.cursor.execute("""
                SELECT DISTINCT aq.query
                FROM api_results ar
                JOIN api_ready_query aq ON ar.query_id = aq.query_id
                WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
            """, (inchi_id,))
            cas_results = [row[0] for row in self.cursor.fetchall()]
            all_cas.update(cas_results)

        return sorted(list(all_cas)) if all_cas else None

    def batch_get_cas_from_smiles(self, smiles_list):
        """
        Get CAS numbers for multiple SMILES strings at once.

        Parameters
        ----------
        smiles_list : list of str
            List of SMILES strings

        Returns
        -------
        dict
            Dictionary mapping SMILES strings to CAS numbers (or None if not found)

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.batch_get_cas_from_smiles(["CC", "not a smiles"])
        {'CC': ['74-84-0', '9002-88-4'], 'not a smiles': None}
        """
        return {smiles: self.get_cas_from_smiles(smiles) for smiles in smiles_list}

    def batch_get_cas_from_name(self, name_list):
        """
        Get CAS numbers for multiple chemical names at once.

        Parameters
        ----------
        name_list : list of str
            List of chemical names (exact match)

        Returns
        -------
        dict
            Dictionary mapping chemical names to CAS numbers (or None if not found)

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> results = zpm.batch_get_cas_from_name(["Formaldehyde", "xyzzy"])
        >>> "50-00-0" in results["Formaldehyde"], results["xyzzy"]
        (True, None)
        """
        return {name: self.get_cas_from_name(name) for name in name_list}

    def batch_get_cas_from_formula(self, formula_list):
        """
        Get CAS numbers for multiple molecular formulas at once.

        Parameters
        ----------
        formula_list : list of str
            List of molecular formulas

        Returns
        -------
        dict
            Dictionary mapping formulas to lists of CAS numbers

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> results = zpm.batch_get_cas_from_formula(["CH2O", "C2H6O"])
        >>> {formula: len(cas) for formula, cas in results.items()}
        {'CH2O': 7, 'C2H6O': 10}
        """
        return {formula: self.get_cas_from_formula(formula) for formula in formula_list}

    def get_id_table_from_cas(self, cas):
        """
        Returns a pandas DataFrame containing all identifiers for a given CAS number.

        This method retrieves all query_ids associated with the CAS number, then for each query_id,
        it retrieves all associated inchi_ids and their corresponding InChI and InChIKey values.
        Synonyms (chemical names) and data sources are also included.

        Parameters
        ----------
        cas : str
            CAS Registry Number

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
            Returns None if the CAS number is not found in the database.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_cas("50-00-0")
        >>> df[["cas", "query_id", "inchi_id", "rank", "inchikey", "zeropm_id"]]
               cas  query_id  inchi_id  rank                     inchikey  zeropm_id
        0  50-00-0      8671     32227     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
        >>> df.loc[0, "sources"]
        'Chemical Data Reporting Inventory, Industrial ...'
        """
        # Get all query_ids for this CAS (using fetchall in case there are multiple)
        self.cursor.execute("""
            SELECT query_id
            FROM api_ready_query
            WHERE query = ? AND type = 'CAS Registry Number'
        """, (cas,))
        query_ids = [row[0] for row in self.cursor.fetchall()]

        if not query_ids:
            self.logger.debug("CAS number %s not found in database", cas)
            return None

        # Get synonyms for this CAS
        synonyms = self.get_names(cas)
        synonyms_str = "; ".join(synonyms) if synonyms else ""

        # Get sources for this CAS
        self.cursor.execute("""
            SELECT DISTINCT s.source_name
            FROM inventory_summary issum
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            WHERE issum.query_id IN ({})
        """.format(','.join('?' * len(query_ids))), query_ids)
        sources = [row[0] for row in self.cursor.fetchall()]
        sources_str = "; ".join(sources) if sources else ""

        # Collect all data
        rows = []
        for query_id in query_ids:
            # Get all inchi_ids for this query_id
            inchi_ids, ranks = self.get_inchi_id(query_id)

            if not inchi_ids:
                # If no inchi_ids found, still add a row with the query_id
                rows.append({
                    'cas': cas,
                    'query_id': query_id,
                    'inchi_id': None,
                    'rank': None,
                    'inchi': None,
                    'inchikey': None,
                    'zeropm_id': None,
                    'synonyms': synonyms_str,
                    'sources': sources_str
                })
            else:
                # For each inchi_id, get the inchi and inchikey
                for inchi_id, rank in zip(inchi_ids, ranks):
                    inchi, inchikey = self.get_inchi(inchi_id)
                    # Get zeropm_id for this inchi_id
                    self.cursor.execute("""
                        SELECT zeropm_id
                        FROM zeropm_chemicals
                        WHERE inchi_id = ?
                    """, (inchi_id,))
                    zeropm_result = self.cursor.fetchone()
                    zeropm_id = zeropm_result[0] if zeropm_result else None

                    rows.append({
                        'cas': cas,
                        'query_id': query_id,
                        'inchi_id': inchi_id,
                        'rank': rank,
                        'inchi': inchi,
                        'inchikey': inchikey,
                        'zeropm_id': zeropm_id,
                        'synonyms': synonyms_str,
                        'sources': sources_str
                    })

        # Create DataFrame
        df = pd.DataFrame(rows)
        # Convert zeropm_id to nullable integer type
        if not df.empty and 'zeropm_id' in df.columns:
            df['zeropm_id'] = df['zeropm_id'].astype('Int64')
        return df

    def get_id_table_from_zeropm_id(self, zeropm_id):
        """
        Returns a pandas DataFrame containing all identifiers for a given zeropm_id.

        This method retrieves the inchi_id associated with the zeropm_id, then finds all
        query_ids (CAS numbers) linked to that inchi_id and builds a comprehensive table
        with InChI, InChIKey, synonyms, and data sources.

        Parameters
        ----------
        zeropm_id : int
            ZeroPM identifier

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
            Returns None if the zeropm_id is not found in the database.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_zeropm_id(3224)   # formaldehyde
        >>> df[["cas", "rank"]].sort_values(["rank", "cas"]).values.tolist()
        [['30525-89-4', 1], ['50-00-0', 1], ['108-62-3', 2], ['1664-98-8', 2], ['630-08-0', 2], ['63101-50-8', 2]]
        """
        # Get inchi_id for this zeropm_id
        self.cursor.execute("""
            SELECT inchi_id
            FROM zeropm_chemicals
            WHERE zeropm_id = ?
        """, (zeropm_id,))
        result = self.cursor.fetchone()

        if not result:
            self.logger.debug("zeropm_id %s not found in database", zeropm_id)
            return None

        inchi_id = result[0]

        # Get InChI and InChIKey
        inchi, inchikey = self.get_inchi(inchi_id)

        # Get all query_ids (CAS numbers) associated with this inchi_id.
        # DISTINCT because api_results can hold the same (query, structure,
        # rank) more than once, differing only in columns not read here.
        self.cursor.execute("""
            SELECT DISTINCT ar.query_id, ar.rank, aq.query
            FROM api_results ar
            JOIN api_ready_query aq ON ar.query_id = aq.query_id
            WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
        """, (inchi_id,))
        query_results = self.cursor.fetchall()

        if not query_results:
            logging.warning(f"No CAS numbers found for zeropm_id {zeropm_id}")
            return None

        # Collect all data
        rows = []
        for query_id, rank, cas in query_results:
            # Get synonyms for this CAS
            synonyms = self.get_names(cas)
            synonyms_str = "; ".join(synonyms) if synonyms else ""

            # Get sources for this query_id
            self.cursor.execute("""
                SELECT DISTINCT s.source_name
                FROM inventory_summary issum
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                WHERE issum.query_id = ?
            """, (query_id,))
            sources = [row[0] for row in self.cursor.fetchall()]
            sources_str = "; ".join(sources) if sources else ""

            rows.append({
                'cas': cas,
                'query_id': query_id,
                'inchi_id': inchi_id,
                'rank': rank,
                'inchi': inchi,
                'inchikey': inchikey,
                'zeropm_id': zeropm_id,
                'synonyms': synonyms_str,
                'sources': sources_str
            })

        # Create DataFrame
        df = pd.DataFrame(rows)
        # Convert zeropm_id to nullable integer type
        if not df.empty and 'zeropm_id' in df.columns:
            df['zeropm_id'] = df['zeropm_id'].astype('Int64')
        return df

    def batch_get_id_table_from_cas(self, cas_list):
        """
        Returns a pandas DataFrame containing all identifiers for a list of CAS numbers.

        This method calls get_id_table_from_cas for each CAS number in the list and
        combines the results into a single DataFrame. CAS numbers not found in the
        database are logged but skipped in the output.

        Parameters
        ----------
        cas_list : list of str
            List of CAS Registry Numbers

        Returns
        -------
        pandas.DataFrame
            Combined DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
            Returns an empty DataFrame if no CAS numbers are found in the database.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]  # formaldehyde, aspirin, ethanol
        >>> df = zpm.batch_get_id_table_from_cas(cas_numbers)
        >>> df[["cas", "rank", "inchikey", "zeropm_id"]]
               cas  rank                     inchikey  zeropm_id
        0  50-00-0     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
        1  50-78-2     1  BSYNRYMUTXBXSQ-UHFFFAOYSA-N       4267
        2  50-78-2     2  BSYNRYMUTXBXSQ-UHFFFAOYSA-M       <NA>
        3  50-78-2     3  XDZMPRGFOOFSBL-UHFFFAOYSA-N       6402
        4  50-78-2     4  BSYNRYMUTXBXSQ-FIBGUPNXSA-N       <NA>
        5  64-17-5     1  LFQSCWFLJHTTHZ-UHFFFAOYSA-N       1452
        """
        if not cas_list:
            logging.warning("Empty CAS list provided")
            return pd.DataFrame(columns=['cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'])

        # Collect DataFrames for each CAS
        dataframes = []
        for cas in cas_list:
            df = self.get_id_table_from_cas(cas)
            if df is not None:
                dataframes.append(df)

        # Combine all DataFrames
        if not dataframes:
            logging.warning("None of the provided CAS numbers were found in the database")
            return pd.DataFrame(columns=['cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'])

        # Concatenate all DataFrames and reset index
        combined_df = pd.concat(dataframes, ignore_index=True)
        return combined_df

    def batch_get_id_table_from_cas_filtered(self, cas_list, rank=None, have_zeropm_id=None):
        """
        Returns a filtered pandas DataFrame containing identifiers for a list of CAS numbers.

        This method calls batch_get_id_table_from_cas and applies optional filters to the results.

        Parameters
        ----------
        cas_list : list of str
            List of CAS Registry Numbers
        rank : int, optional
            If specified, only include rows with this rank value (e.g., rank=1 for top results)
            If None, no rank filtering is applied (default: None)
        have_zeropm_id : bool, optional
            If True, only include rows where zeropm_id is not None
            If False, only include rows where zeropm_id is None
            If None, no zeropm_id filtering is applied (default: None)

        Returns
        -------
        pandas.DataFrame
            Filtered DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
            Returns an empty DataFrame if no CAS numbers match the filters.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]
        >>> # Get only rank=1 results with zeropm_id
        >>> df = zpm.batch_get_id_table_from_cas_filtered(cas_numbers, rank=1, have_zeropm_id=True)
        >>> df[["cas", "rank", "zeropm_id"]]
               cas  rank  zeropm_id
        0  50-00-0     1       3224
        1  50-78-2     1       4267
        2  64-17-5     1       1452

        See Also
        --------
        batch_get_id_table_from_cas : Returns all results without filtering
        """
        # Get the full id table
        df = self.batch_get_id_table_from_cas(cas_list)

        # Return empty if no results
        if df.empty:
            return df

        # Apply rank filter if specified
        if rank is not None:
            df = df[df['rank'] == rank]

        # Apply zeropm_id filter if specified
        if have_zeropm_id is not None:
            if have_zeropm_id:
                df = df[df['zeropm_id'].notna()]
            else:
                df = df[df['zeropm_id'].isna()]

        # Reset index
        df = df.reset_index(drop=True)

        return df

    def get_id_table_from_inchi(self, inchi):
        """
        Returns a pandas DataFrame containing all identifiers for a given InChI.

        This method retrieves the inchi_id for the InChI, then finds all associated
        query_ids and their CAS numbers. It also includes synonyms and sources.

        About 5% of ZeroPM's substances are stored under a non-standard InChI
        (``InChI=1/...``). The InChI is matched as a string first; when that
        misses, its InChIKey is computed and looked up with either flag, as
        in
        [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].
        So a standard InChI finds a substance stored only under a
        non-standard one whose key differs by the flag alone: 536 of the
        816 such substances that no standard InChI matched as a string. The
        other 280 have relative stereo (``/s2``), which a standard InChI
        cannot express.

        Parameters
        ----------
        inchi : str
            InChI string, standard or not

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
            Returns None if the InChI is not found in the database.
            One row per query --- CAS number or name --- that reaches the
            structure, best rank first; ``cas`` is NaN for a name query. The
            synonyms are those of the first CAS number, on every row.
            ``inchi`` and ``inchikey`` are as ZeroPM stores them.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
        >>> df.dropna(subset=["cas"])[["query_id", "rank", "cas"]].head(2)
           query_id  rank         cas
        0      8671     1     50-00-0
        3     35725     1  30525-89-4

        trans-1,4-Cyclohexanediol is stored only under a non-standard InChI:

        >>> df = zpm.get_id_table_from_inchi(
        ...     "InChI=1S/C6H12O2/c7-5-1-2-6(8)4-3-5/h5-8H,1-4H2/t5-,6-")
        >>> df["cas"].dropna().tolist(), df["inchikey"].unique().tolist()
        (['6995-79-5'], ['VKONPUDBRVKQLM-IZLXSQMJNA-N'])
        """
        # Get inchi_id, and the InChI and InChIKey as stored
        result = self._find_substance_by_inchi(inchi)

        if not result:
            self.logger.debug("InChI %s not found in database", inchi)
            return None

        inchi_id, inchi, inchikey = result

        # Get all query_ids and ranks for this inchi_id
        self.cursor.execute("""
            SELECT DISTINCT ar.query_id, ar.rank
            FROM api_results ar
            WHERE ar.inchi_id = ?
            ORDER BY ar.rank
        """, (inchi_id,))
        query_results = self.cursor.fetchall()

        if not query_results:
            # If no query_ids found, still return basic info
            return pd.DataFrame([{
                'inchi': inchi,
                'inchikey': inchikey,
                'inchi_id': inchi_id,
                'query_id': None,
                'rank': None,
                'cas': None,
                'synonyms': '',
                'sources': ''
            }])

        # Get CAS numbers for these query_ids
        rows = []
        primary_cas = None
        query_ids_list = [q[0] for q in query_results]

        # Get sources for all query_ids at once
        if query_ids_list:
            placeholders = ','.join('?' * len(query_ids_list))
            self.cursor.execute(f"""
                SELECT DISTINCT s.source_name
                FROM inventory_summary issum
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                WHERE issum.query_id IN ({placeholders})
            """, query_ids_list)
            sources = [row[0] for row in self.cursor.fetchall()]
            sources_str = "; ".join(sources) if sources else ""
        else:
            sources_str = ""

        for query_id, rank in query_results:
            # Get CAS number for this query_id
            self.cursor.execute("""
                SELECT query
                FROM api_ready_query
                WHERE query_id = ? AND type = 'CAS Registry Number'
            """, (query_id,))
            cas_result = self.cursor.fetchone()
            cas = cas_result[0] if cas_result else None

            # Use first CAS as primary for synonyms
            if cas and primary_cas is None:
                primary_cas = cas

            rows.append({
                'inchi': inchi,
                'inchikey': inchikey,
                'inchi_id': inchi_id,
                'query_id': query_id,
                'rank': rank,
                'cas': cas,
                'sources': sources_str
            })

        # Get synonyms from primary CAS
        synonyms_str = ''
        if primary_cas:
            synonyms = self.get_names(primary_cas)
            synonyms_str = "; ".join(synonyms) if synonyms else ""

        # Add synonyms to all rows
        for row in rows:
            row['synonyms'] = synonyms_str

        return pd.DataFrame(rows)

    def batch_get_id_table_from_inchi(self, inchi_list):
        """
        Returns a pandas DataFrame containing all identifiers for a list of InChI strings.

        Parameters
        ----------
        inchi_list : list of str
            List of InChI strings

        Returns
        -------
        pandas.DataFrame
            Combined DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
            Returns an empty DataFrame if no InChIs are found in the database.
            InChIs not found are left out.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.batch_get_id_table_from_inchi(
        ...     ["InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", "InChI=1S/Xx"])
        >>> df["inchikey"].unique().tolist(), len(df)
        (['LFQSCWFLJHTTHZ-UHFFFAOYSA-N'], 43)
        """
        if not inchi_list:
            logging.warning("Empty InChI list provided")
            return pd.DataFrame(columns=['inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

        dataframes = []
        for inchi in inchi_list:
            df = self.get_id_table_from_inchi(inchi)
            if df is not None:
                dataframes.append(df)

        if not dataframes:
            logging.warning("None of the provided InChIs were found in the database")
            return pd.DataFrame(columns=['inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

        combined_df = pd.concat(dataframes, ignore_index=True)
        return combined_df

    def get_id_table_from_inchikey(self, inchikey):
        """
        Returns a pandas DataFrame containing all identifiers for a given InChIKey.

        This method retrieves the inchi_id for the InChIKey, then finds all associated
        query_ids and their CAS numbers. It also includes synonyms and sources.

        About 5% of ZeroPM's substances are stored under a non-standard InChI
        and InChIKey. A key is also looked up with its other standard flag
        (``...SA-N`` / ``...NA-N``), so a standard key finds those rows where
        only the flag differs; the key given is preferred when both exist.

        Parameters
        ----------
        inchikey : str
            InChIKey string, standard or not

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
            Returns None if the InChIKey is not found in the database.
            Shaped as
            [`get_id_table_from_inchi`][provesid.zeropm.ZeroPM.get_id_table_from_inchi]
            describes.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_inchikey("WSFSSNUMVMOOMR-UHFFFAOYSA-N")
        >>> df.dropna(subset=["cas"])[["rank", "cas"]].head(2)
           rank         cas
        0     1     50-00-0
        3     1  30525-89-4
        """
        # Get inchi_id and inchi from InChIKey, in either flag spelling
        result = self._find_substance_by_inchikey(inchikey)

        if not result:
            self.logger.debug("InChIKey %s not found in database", inchikey)
            return None

        inchi_id, inchi, _ = result

        # Get all query_ids and ranks for this inchi_id
        self.cursor.execute("""
            SELECT DISTINCT ar.query_id, ar.rank
            FROM api_results ar
            WHERE ar.inchi_id = ?
            ORDER BY ar.rank
        """, (inchi_id,))
        query_results = self.cursor.fetchall()

        if not query_results:
            # If no query_ids found, still return basic info
            return pd.DataFrame([{
                'inchikey': inchikey,
                'inchi': inchi,
                'inchi_id': inchi_id,
                'query_id': None,
                'rank': None,
                'cas': None,
                'synonyms': '',
                'sources': ''
            }])

        # Get CAS numbers for these query_ids
        rows = []
        primary_cas = None
        query_ids_list = [q[0] for q in query_results]

        # Get sources for all query_ids at once
        if query_ids_list:
            placeholders = ','.join('?' * len(query_ids_list))
            self.cursor.execute(f"""
                SELECT DISTINCT s.source_name
                FROM inventory_summary issum
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                WHERE issum.query_id IN ({placeholders})
            """, query_ids_list)
            sources = [row[0] for row in self.cursor.fetchall()]
            sources_str = "; ".join(sources) if sources else ""
        else:
            sources_str = ""

        for query_id, rank in query_results:
            # Get CAS number for this query_id
            self.cursor.execute("""
                SELECT query
                FROM api_ready_query
                WHERE query_id = ? AND type = 'CAS Registry Number'
            """, (query_id,))
            cas_result = self.cursor.fetchone()
            cas = cas_result[0] if cas_result else None

            # Use first CAS as primary for synonyms
            if cas and primary_cas is None:
                primary_cas = cas

            rows.append({
                'inchikey': inchikey,
                'inchi': inchi,
                'inchi_id': inchi_id,
                'query_id': query_id,
                'rank': rank,
                'cas': cas,
                'sources': sources_str
            })

        # Get synonyms from primary CAS
        synonyms_str = ''
        if primary_cas:
            synonyms = self.get_names(primary_cas)
            synonyms_str = "; ".join(synonyms) if synonyms else ""

        # Add synonyms to all rows
        for row in rows:
            row['synonyms'] = synonyms_str

        return pd.DataFrame(rows)

    def batch_get_id_table_from_inchikey(self, inchikey_list):
        """
        Returns a pandas DataFrame containing all identifiers for a list of InChIKey strings.

        Parameters
        ----------
        inchikey_list : list of str
            List of InChIKey strings

        Returns
        -------
        pandas.DataFrame
            Combined DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
            Returns an empty DataFrame if no InChIKeys are found in the database.
            InChIKeys not found are left out.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.batch_get_id_table_from_inchikey(
        ...     ["LFQSCWFLJHTTHZ-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
        >>> df["inchikey"].unique().tolist()
        ['LFQSCWFLJHTTHZ-UHFFFAOYSA-N']
        """
        if not inchikey_list:
            logging.warning("Empty InChIKey list provided")
            return pd.DataFrame(columns=['inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

        dataframes = []
        for inchikey in inchikey_list:
            df = self.get_id_table_from_inchikey(inchikey)
            if df is not None:
                dataframes.append(df)

        if not dataframes:
            logging.warning("None of the provided InChIKeys were found in the database")
            return pd.DataFrame(columns=['inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

        combined_df = pd.concat(dataframes, ignore_index=True)
        return combined_df

    def get_id_table_from_name(self, name):
        """
        Returns a pandas DataFrame containing all identifiers for a given chemical name.

        This method searches for an exact match of the chemical name, then retrieves all
        associated inchi_ids and their corresponding InChI, InChIKey, CAS numbers, and sources.

        Parameters
        ----------
        name : str
            Chemical name (exact match)

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'
            Returns None if the name is not found in the database.
            One row per (structure, CAS number): each structure the name
            resolved to, at every rank, with every CAS number that reaches
            that structure.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.get_id_table_from_name("Formaldehyde")
        >>> df.groupby("rank")["inchikey"].first().to_dict()
        {1: 'WSFSSNUMVMOOMR-UHFFFAOYSA-N', 2: 'VNWKTOKETHGBQD-UHFFFAOYSA-N', 3: 'MDYZKJNTKZIUSK-UHFFFAOYSA-N', 4: 'SYCNHFWYTQQMNG-UHFFFAOYSA-N'}
        >>> df[df["rank"] == 1]["cas"].tolist()[:2]
        ['50-00-0', '30525-89-4']
        """
        # Get query_id for this name
        query_id = self.query_name(name)

        if query_id is None:
            self.logger.debug("Chemical name '%s' not found in database", name)
            return None

        return self._id_table_for_query_id(query_id, name)

    def _id_table_for_query_id(self, query_id, name):
        """
        Build the identifier table for one already-resolved query_id.

        This is the shared body of
        [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name]
        and
        [`get_id_table_from_similar_name`][provesid.zeropm.ZeroPM.get_id_table_from_similar_name];
        the only difference between them is how the ``query_id`` was found.

        Parameters
        ----------
        query_id : int
            An ``api_ready_query`` id.
        name : str
            Name to record in the ``name`` column of the result.

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank',
            'inchi', 'inchikey', 'cas', 'sources'.
        """
        # Get sources for this query_id
        self.cursor.execute("""
            SELECT DISTINCT s.source_name
            FROM inventory_summary issum
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            WHERE issum.query_id = ?
        """, (query_id,))
        sources = [row[0] for row in self.cursor.fetchall()]
        sources_str = "; ".join(sources) if sources else ""

        # Get all inchi_ids and ranks for this query_id
        inchi_ids, ranks = self.get_inchi_id(query_id)

        if not inchi_ids:
            # If no inchi_ids found, still return basic info
            return pd.DataFrame([{
                'name': name,
                'query_id': query_id,
                'inchi_id': None,
                'rank': None,
                'inchi': None,
                'inchikey': None,
                'cas': None,
                'sources': sources_str
            }])

        # Collect all data
        rows = []
        for inchi_id, rank in zip(inchi_ids, ranks):
            # Get InChI and InChIKey
            inchi, inchikey = self.get_inchi(inchi_id)

            # Get CAS number(s) for this inchi_id
            self.cursor.execute("""
                SELECT DISTINCT aq.query
                FROM api_results ar
                JOIN api_ready_query aq ON ar.query_id = aq.query_id
                WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
            """, (inchi_id,))
            cas_results = [row[0] for row in self.cursor.fetchall()]

            # If multiple CAS numbers, create a row for each
            if cas_results:
                for cas in cas_results:
                    rows.append({
                        'name': name,
                        'query_id': query_id,
                        'inchi_id': inchi_id,
                        'rank': rank,
                        'inchi': inchi,
                        'inchikey': inchikey,
                        'cas': cas,
                        'sources': sources_str
                    })
            else:
                # No CAS found, still add the row
                rows.append({
                    'name': name,
                    'query_id': query_id,
                    'inchi_id': inchi_id,
                    'rank': rank,
                    'inchi': inchi,
                    'inchikey': inchikey,
                    'cas': None,
                    'sources': sources_str
                })

        return pd.DataFrame(rows)

    def batch_get_id_table_from_name(self, name_list):
        """
        Returns a pandas DataFrame containing all identifiers for a list of chemical names.

        Parameters
        ----------
        name_list : list of str
            List of chemical names (exact match)

        Returns
        -------
        pandas.DataFrame
            Combined DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'
            Returns an empty DataFrame if no names are found in the database.
            Names not found are left out.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> df = zpm.batch_get_id_table_from_name(["Formaldehyde", "ethanol", "xyzzy"])
        >>> df[df["rank"] == 1].groupby("name")["cas"].first().to_dict()
        {'Formaldehyde': '50-00-0', 'ethanol': '64-17-5'}
        """
        if not name_list:
            logging.warning("Empty name list provided")
            return pd.DataFrame(columns=['name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'])

        dataframes = []
        for name in name_list:
            df = self.get_id_table_from_name(name)
            if df is not None:
                dataframes.append(df)

        if not dataframes:
            logging.warning("None of the provided names were found in the database")
            return pd.DataFrame(columns=['name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'])

        combined_df = pd.concat(dataframes, ignore_index=True)
        return combined_df

    # ==================== Performance Enhancement Methods ====================

    def create_indexes(self, force=False):
        """
        Create indexes on frequently queried columns to improve performance.
        Indexes are created on query, type, query_id, inchi_id, inchi, and inchikey.

        Parameters
        ----------
        force : bool, optional
            If True, drop existing indexes before creating new ones (default: False)

        Returns
        -------
        dict
            Dictionary with index names as keys and status ('created', 'exists', 'error') as values.
            Without ``force`` every index reads ``'exists'``, whether or not
            it was just built: ``CREATE INDEX IF NOT EXISTS`` does not say.

        Notes
        -----
        This writes to the database file. An index that already exists under
        its name is left alone, so a second call does nothing.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.create_indexes()["idx_query"]     # doctest: +SKIP
        'exists'
        """
        indexes = {
            'idx_query': 'CREATE INDEX IF NOT EXISTS idx_query ON api_ready_query(query)',
            'idx_type': 'CREATE INDEX IF NOT EXISTS idx_type ON api_ready_query(type)',
            'idx_query_id_results': 'CREATE INDEX IF NOT EXISTS idx_query_id_results ON api_results(query_id)',
            'idx_inchi_id_results': 'CREATE INDEX IF NOT EXISTS idx_inchi_id_results ON api_results(inchi_id)',
            'idx_inchi': 'CREATE INDEX IF NOT EXISTS idx_inchi ON substances(inchi)',
            'idx_inchikey': 'CREATE INDEX IF NOT EXISTS idx_inchikey ON substances(inchikey)',
            'idx_inventory_query': 'CREATE INDEX IF NOT EXISTS idx_inventory_query ON inventory_summary(query_id)',
            'idx_inventory_id': 'CREATE INDEX IF NOT EXISTS idx_inventory_id ON inventories(inventory_id)',
        }

        results = {}

        if force:
            # Drop existing indexes
            for idx_name in indexes.keys():
                try:
                    self.cursor.execute(f"DROP INDEX IF EXISTS {idx_name}")
                except Exception as e:
                    logging.warning(f"Could not drop index {idx_name}: {e}")

        # Create indexes
        for idx_name, sql in indexes.items():
            try:
                self.cursor.execute(sql)
                self.conn.commit()
                results[idx_name] = 'created' if force else 'exists'
            except Exception as e:
                logging.error(f"Error creating index {idx_name}: {e}")
                results[idx_name] = 'error'

        return results

    # ==================== Batch Query Methods ====================

    def batch_query_cas(self, cas_list):
        """
        Query multiple CAS numbers at once.

        Parameters
        ----------
        cas_list : list of str
            List of CAS Registry Numbers

        Returns
        -------
        dict
            Dictionary mapping CAS numbers to query_ids (or None if not found)

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.batch_query_cas(["50-00-0", "64-17-5", "0-00-0"])
        {'50-00-0': 8671, '64-17-5': 3904, '0-00-0': None}
        """
        if not cas_list:
            return {}

        # Use parameterized query with IN clause
        placeholders = ','.join('?' * len(cas_list))
        self.cursor.execute(f"""
            SELECT query, query_id
            FROM api_ready_query
            WHERE query IN ({placeholders}) AND type = 'CAS Registry Number'
        """, cas_list)

        results = {row[0]: row[1] for row in self.cursor.fetchall()}

        # Add None for CAS numbers not found
        return {cas: results.get(cas) for cas in cas_list}

    def batch_get_smiles_from_cas(self, cas_list):
        """
        Get SMILES for multiple CAS numbers at once.

        Parameters
        ----------
        cas_list : list of str
            List of CAS Registry Numbers

        Returns
        -------
        dict
            Dictionary mapping CAS numbers to SMILES strings (or None if not found)

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.batch_get_smiles_from_cas(["50-00-0", "64-17-5", "0-00-0"])
        {'50-00-0': 'C=O', '64-17-5': 'CCO', '0-00-0': None}
        """
        query_ids = self.batch_query_cas(cas_list)
        results = {}

        for cas, query_id in query_ids.items():
            if query_id is None:
                results[cas] = None
            else:
                results[cas] = self.get_smiles_from_cas(cas)

        return results

    def batch_get_names(self, cas_list):
        """
        Get all names for multiple CAS numbers at once.

        Parameters
        ----------
        cas_list : list of str
            List of CAS Registry Numbers

        Returns
        -------
        dict
            Dictionary mapping CAS numbers to lists of names, as
            [`get_names`][provesid.zeropm.ZeroPM.get_names] returns them (empty
            when not found)

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> names = zpm.batch_get_names(["64-17-5", "0-00-0"])
        >>> "Ethanol" in names["64-17-5"], names["0-00-0"]
        (True, [])
        """
        return {cas: self.get_names(cas) for cas in cas_list}

    def batch_get_cas_from_inchikey(self, inchikey_list):
        """
        Get CAS numbers for multiple InChIKeys at once.

        Parameters
        ----------
        inchikey_list : list of str
            List of InChIKey strings

        Returns
        -------
        dict
            Dictionary mapping InChIKeys to CAS numbers (or None if not found);
            one number as a string, several as a list, as broad as
            [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi].
            Each key is looked up with either flag, as in
            [`get_cas_from_inchikey`][provesid.zeropm.ZeroPM.get_cas_from_inchikey].

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> found = zpm.batch_get_cas_from_inchikey(
        ...     ["WSFSSNUMVMOOMR-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
        >>> "50-00-0" in found["WSFSSNUMVMOOMR-UHFFFAOYSA-N"]
        True
        >>> found["XXXXXXXXXXXXXX-XXXXXXXXXX-X"] is None
        True
        """
        if not inchikey_list:
            return {}

        # First, get inchi_ids for all inchikeys, each under either flag
        # spelling as in get_cas_from_inchikey; each lookup is one index probe
        inchikey_to_id = {}
        for inchikey in inchikey_list:
            found = self._find_substance_by_inchikey(inchikey)
            if found:
                inchikey_to_id[inchikey] = found[0]

        # Get all CAS numbers for these inchi_ids
        if not inchikey_to_id:
            return {key: None for key in inchikey_list}

        inchi_ids = list(inchikey_to_id.values())
        placeholders = ','.join('?' * len(inchi_ids))
        self.cursor.execute(f"""
            SELECT DISTINCT ar.inchi_id, aq.query
            FROM api_results ar
            JOIN api_ready_query aq ON ar.query_id = aq.query_id
            WHERE ar.inchi_id IN ({placeholders}) AND aq.type = 'CAS Registry Number'
        """, inchi_ids)

        # Group CAS numbers by inchi_id
        inchi_to_cas = {}
        for inchi_id, cas in self.cursor.fetchall():
            if inchi_id not in inchi_to_cas:
                inchi_to_cas[inchi_id] = []
            inchi_to_cas[inchi_id].append(cas)

        # Map back to inchikeys
        results = {}
        for inchikey in inchikey_list:
            inchi_id = inchikey_to_id.get(inchikey)
            if inchi_id and inchi_id in inchi_to_cas:
                cas_list = inchi_to_cas[inchi_id]
                results[inchikey] = cas_list[0] if len(cas_list) == 1 else cas_list
            else:
                results[inchikey] = None

        return results

    # ==================== Advanced Search Methods ====================

    def query_name_regex(self, pattern, case_sensitive=False, limit=100):
        """
        Search for chemical names with a simple wildcard pattern.

        Not a full regular expression: ``.*`` matches any run of characters
        and ``.`` any single character, and everything else is literal. The
        pattern is translated to SQL ``LIKE`` (case-insensitive) or ``GLOB``
        (case-sensitive), so it must match the whole name.

        Parameters
        ----------
        pattern : str
            Pattern using ``.*`` and ``.`` as wildcards
        case_sensitive : bool, optional
            Whether the search is case-sensitive (default: False)
        limit : int, optional
            Maximum number of results to return (default: 100)

        Returns
        -------
        list of tuple
            List of (query_id, name) tuples matching the pattern, in database
            order

        Note
        ----
        Use '.*pattern.*' for substring matching. A case-insensitive pattern
        may also use ``%`` and ``_``, which ``LIKE`` reads as wildcards.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.query_name_regex("formaldehyde.*", limit=2)
        [(8672, 'Formaldehyde'), (8673, 'formaldehyde ... %')]
        >>> zpm.query_name_regex("formaldehyde.*", case_sensitive=True, limit=2)
        [(8673, 'formaldehyde ... %'), (104113, 'formaldehyde ...%')]
        """
        if case_sensitive:
            # LIKE ignores case for ASCII letters whatever the pattern says;
            # GLOB does not, and takes * and ? as its wildcards.
            pattern = pattern.replace('.*', '*').replace('.', '?')
            self.cursor.execute(f"""
                SELECT query_id, query
                FROM api_ready_query
                WHERE type = 'chemical name' AND query GLOB ?
                LIMIT ?
            """, (pattern, limit))
        else:
            # Case-insensitive search
            pattern = pattern.replace('.*', '%').replace('.', '_')
            self.cursor.execute(f"""
                SELECT query_id, query
                FROM api_ready_query
                WHERE type = 'chemical name' AND LOWER(query) LIKE LOWER(?)
                LIMIT ?
            """, (pattern, limit))

        return self.cursor.fetchall()

    def get_cas_by_substructure(self, smarts_pattern, max_results=100):
        """
        Search for chemicals containing a specific substructure.
        This method converts InChIs to molecules and performs substructure
        matching using RDKit, in database order.

        Parameters
        ----------
        smarts_pattern : str
            SMARTS pattern for substructure search
        max_results : int, optional
            Maximum number of results to return (default: 100)

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'cas', 'inchi', 'inchikey', 'smiles'.
            ``cas`` is as
            [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]
            returns it. Empty for an invalid SMARTS pattern.

        Warning
        -------
        Only the first 10 000 of the database's ~359 000 structures are
        searched, so a structure beyond them is never found. Converting each
        InChI costs time, and RDKit logs a warning for many of them.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> hits = zpm.get_cas_by_substructure("c1ccccc1C(=O)O", max_results=2)
        >>> [hit["smiles"] for hit in hits]
        ['COc1ccc(C(=O)O)cc1', 'O=C(O)c1ccc(C(=O)O)cc1']
        """
        try:
            pattern_mol = Chem.MolFromSmarts(smarts_pattern)
            if pattern_mol is None:
                logging.error(f"Invalid SMARTS pattern: {smarts_pattern}")
                return []
        except Exception as e:
            logging.error(f"Error parsing SMARTS pattern: {e}")
            return []

        # Get all substances (this could be optimized with pagination)
        self.cursor.execute("""
            SELECT s.inchi_id, s.inchi, s.inchikey
            FROM substances s
            LIMIT 10000
        """)

        results = []
        count = 0

        for inchi_id, inchi, inchikey in self.cursor.fetchall():
            if count >= max_results:
                break

            # Convert InChI to mol
            try:
                mol = Chem.MolFromInchi(inchi)
                if mol is None:
                    continue

                # Check for substructure match
                if mol.HasSubstructMatch(pattern_mol):
                    # Get CAS number
                    cas = self.get_cas_from_inchi(inchi)
                    smiles = Chem.MolToSmiles(mol)

                    results.append({
                        'cas': cas,
                        'inchi': inchi,
                        'inchikey': inchikey,
                        'smiles': smiles
                    })
                    count += 1
            except Exception as e:
                continue

        return results

    # ==================== Export Methods ====================

    def export_to_csv(self, query_results, filename, columns=None):
        """
        Export query results to a CSV file.

        Parameters
        ----------
        query_results : list or dict
            Query results to export (list of tuples or dictionary)
        filename : str
            Output CSV filename. A relative name is written into the
            database's directory, beside the database; pass an absolute path
            to write anywhere else.
        columns : list of str, optional
            Column names for the CSV header. A dict gets ``key,value`` when
            none are given; a list gets no header.

        Returns
        -------
        str
            Path to the created CSV file

        Examples
        --------
        >>> import tempfile
        >>> zpm = ZeroPM()
        >>> path = os.path.join(tempfile.mkdtemp(), "smiles.csv")
        >>> zpm.export_to_csv({"50-00-0": "C=O"}, path, columns=["cas", "smiles"]) == path
        True
        >>> print(open(path).read())
        cas,smiles
        50-00-0,C=O
        <BLANKLINE>
        """
        import csv

        output_path = os.path.join(self.path, filename)

        with open(output_path, 'w', newline='', encoding='utf-8') as f:
            if isinstance(query_results, dict):
                # Handle dictionary results
                writer = csv.writer(f)
                if columns:
                    writer.writerow(columns)
                else:
                    writer.writerow(['key', 'value'])

                for key, value in query_results.items():
                    writer.writerow([key, value])
            else:
                # Handle list of tuples/lists
                writer = csv.writer(f)
                if columns:
                    writer.writerow(columns)

                for row in query_results:
                    writer.writerow(row)

        return output_path

    def create_view(self, view_name, sql_query):
        """
        Create a custom view in the database for frequently used queries.

        Parameters
        ----------
        view_name : str
            Name of the view to create
        sql_query : str
            SQL SELECT statement defining the view

        Returns
        -------
        bool
            True if view was created successfully, False otherwise. A view
            of the same name is replaced.

        Notes
        -----
        This writes to the database file.

        Example
        -------
        >>> zpm = ZeroPM()
        >>> sql = '''
        ...     SELECT aq.query AS cas, s.inchi, s.inchikey
        ...     FROM api_ready_query aq
        ...     JOIN api_results ar ON aq.query_id = ar.query_id
        ...     JOIN substances s ON ar.inchi_id = s.inchi_id
        ...     WHERE aq.type = 'CAS Registry Number' AND ar.rank = 1
        ... '''
        >>> zpm.create_view('cas_to_inchi', sql)            # doctest: +SKIP
        True
        """
        try:
            # Drop view if it exists
            self.cursor.execute(f"DROP VIEW IF EXISTS {view_name}")

            # Create new view
            self.cursor.execute(f"CREATE VIEW {view_name} AS {sql_query}")
            self.conn.commit()

            logging.info(f"View '{view_name}' created successfully")
            return True
        except Exception as e:
            logging.error(f"Error creating view '{view_name}': {e}")
            return False

    def export_query_results(self, sql_query, filename, include_headers=True):
        """
        Execute a custom SQL query and export results to CSV.

        Parameters
        ----------
        sql_query : str
            SQL query to execute
        filename : str
            Output CSV filename
        include_headers : bool, optional
            Include column headers in CSV (default: True)

        Returns
        -------
        str
            Path to the created CSV file; see
            [`export_to_csv`][provesid.zeropm.ZeroPM.export_to_csv] for where a
            relative ``filename`` goes

        Examples
        --------
        >>> import tempfile
        >>> zpm = ZeroPM()
        >>> path = os.path.join(tempfile.mkdtemp(), "regions.csv")
        >>> _ = zpm.export_query_results(
        ...     "SELECT region_id, region FROM global_regions ORDER BY region_id", path)
        >>> print(open(path).read().splitlines()[:3])
        ['region_id,region', '1,North America', '2,Europe']
        """
        import csv

        self.cursor.execute(sql_query)
        results = self.cursor.fetchall()

        # Get column names from cursor description
        columns = [desc[0] for desc in self.cursor.description] if include_headers else None

        return self.export_to_csv(results, filename, columns)

    def get_database_stats(self):
        """
        Get statistics about the database contents.

        Returns
        -------
        dict
            Row counts of ``api_ready_query``, ``api_results``,
            ``substances``, ``inventories``, ``inventory_summary``,
            ``cleanventory_chemicals``, ``zeropm_chemicals``, ``components``
            and ``multi_components``, plus ``unique_cas_numbers`` and
            ``unique_chemical_names``. A table that cannot be counted holds
            its error message instead.

        Examples
        --------
        >>> stats = ZeroPM().get_database_stats()
        >>> stats["unique_cas_numbers"], stats["zeropm_chemicals"]
        (164513, 126369)
        """
        tables = [
            'api_ready_query', 'api_results', 'substances',
            'inventories', 'inventory_summary', 'cleanventory_chemicals',
            'zeropm_chemicals', 'components', 'multi_components'
        ]

        stats = {}

        for table in tables:
            try:
                self.cursor.execute(f"SELECT COUNT(*) FROM {table}")
                count = self.cursor.fetchone()[0]
                stats[table] = count
            except Exception as e:
                stats[table] = f"Error: {e}"

        # Additional statistics
        self.cursor.execute("""
            SELECT COUNT(DISTINCT query)
            FROM api_ready_query
            WHERE type = 'CAS Registry Number'
        """)
        stats['unique_cas_numbers'] = self.cursor.fetchone()[0]

        self.cursor.execute("""
            SELECT COUNT(DISTINCT query)
            FROM api_ready_query
            WHERE type = 'chemical name'
        """)
        stats['unique_chemical_names'] = self.cursor.fetchone()[0]

        return stats

    # ==================== Inventory, Country, and Region Query Methods ====================

    def get_all_inventories(self):
        """
        Get all available inventory sources.

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'source_id', 'source_name', 'country_scope', 'link', 'type',
            ordered by name. Some names carry stray spaces, as stored.

        Examples
        --------
        >>> inventories = ZeroPM().get_all_inventories()
        >>> len(inventories)
        25
        >>> [(i["source_id"], i["country_scope"]) for i in inventories if "TSCA" in i["source_name"]]
        [(24, 'United States of America')]
        """
        self.cursor.execute("""
            SELECT source_id, source_name, country_scope, link, type
            FROM sources
            ORDER BY source_name
        """)

        inventories = []
        for row in self.cursor.fetchall():
            inventories.append({
                'source_id': row[0],
                'source_name': row[1],
                'country_scope': row[2],
                'link': row[3],
                'type': row[4]
            })

        return inventories

    def get_all_countries(self):
        """
        Get all countries in the database.

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'country_id', 'country', ordered by name

        Examples
        --------
        >>> countries = ZeroPM().get_all_countries()
        >>> len(countries), countries[0]
        (38, {'country_id': 1, 'country': 'Australia'})
        """
        self.cursor.execute("""
            SELECT country_id, country
            FROM countries
            ORDER BY country
        """)

        countries = []
        for row in self.cursor.fetchall():
            countries.append({
                'country_id': row[0],
                'country': row[1]
            })

        return countries

    def get_all_regions(self):
        """
        Get all global regions in the database.

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'region_id', 'region', ordered by name

        Examples
        --------
        >>> [r["region"] for r in ZeroPM().get_all_regions()]
        ['Asia', 'Europe', 'North America', 'Oceania', 'Scandinavia']
        """
        self.cursor.execute("""
            SELECT region_id, region
            FROM global_regions
            ORDER BY region
        """)

        regions = []
        for row in self.cursor.fetchall():
            regions.append({
                'region_id': row[0],
                'region': row[1]
            })

        return regions

    def query_by_inventory(self, source_name=None, source_id=None):
        """
        Query chemicals by inventory source.

        Parameters
        ----------
        source_name : str, optional
            Name of the inventory source (case-insensitive partial match)
        source_id : int, optional
            Source ID (exact match)

        Returns
        -------
        list of dict
            List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'source_name',
            ordered by CAS number. A CAS number appears once per structure
            it resolves to, at any rank, and once per matching inventory.

        Raises
        ------
        ValueError
            If neither ``source_name`` nor ``source_id`` is given.

        Note
        ----
        Either source_name or source_id must be provided.
        [`count_chemicals_by_inventory`][provesid.zeropm.ZeroPM.count_chemicals_by_inventory]
        counts distinct CAS numbers without building the list.

        Examples
        --------
        >>> rows = ZeroPM().query_by_inventory(source_name="TSCA")
        >>> rows[0]
        {'cas': '100-00-5', 'query_id': 1927, 'inchi_id': 1, 'source_name': 'Toxic Substances Control Act (TSCA) Chemical Substance Inventory'}
        """
        if source_name is None and source_id is None:
            raise ValueError("Either source_name or source_id must be provided")

        if source_id is not None:
            # Query by source_id
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND s.source_id = ?
                ORDER BY aq.query
            """, (source_id,))
        else:
            # Query by source_name (partial, case-insensitive)
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND LOWER(s.source_name) LIKE LOWER(?)
                ORDER BY aq.query
            """, (f'%{source_name}%',))

        results = []
        for row in self.cursor.fetchall():
            results.append({
                'cas': row[0],
                'query_id': row[1],
                'inchi_id': row[2],
                'source_name': row[3]
            })

        return results

    def query_by_country(self, country_name=None, country_id=None):
        """
        Query chemicals by country.

        Parameters
        ----------
        country_name : str, optional
            Name of the country (case-insensitive partial match)
        country_id : int, optional
            Country ID (exact match)

        Returns
        -------
        list of dict
            List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'country', 'source_name',
            ordered by CAS number, repeated as
            [`query_by_inventory`][provesid.zeropm.ZeroPM.query_by_inventory]
            describes

        Raises
        ------
        ValueError
            If neither ``country_name`` nor ``country_id`` is given.

        Note
        ----
        Either country_name or country_id must be provided.

        Examples
        --------
        >>> rows = ZeroPM().query_by_country("Japan")
        >>> rows[0]["cas"], rows[0]["source_name"]
        ('100-00-5', 'NITE')
        """
        if country_name is None and country_id is None:
            raise ValueError("Either country_name or country_id must be provided")

        if country_id is not None:
            # Query by country_id
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, c.country, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND c.country_id = ?
                ORDER BY aq.query
            """, (country_id,))
        else:
            # Query by country_name (partial, case-insensitive)
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, c.country, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND LOWER(c.country) LIKE LOWER(?)
                ORDER BY aq.query
            """, (f'%{country_name}%',))

        results = []
        for row in self.cursor.fetchall():
            results.append({
                'cas': row[0],
                'query_id': row[1],
                'inchi_id': row[2],
                'country': row[3],
                'source_name': row[4]
            })

        return results

    def query_by_region(self, region_name=None, region_id=None):
        """
        Query chemicals by global region.

        Parameters
        ----------
        region_name : str, optional
            Name of the region (case-insensitive partial match)
        region_id : int, optional
            Region ID (exact match)

        Returns
        -------
        list of dict
            List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'region', 'country', 'source_name',
            ordered by CAS number, repeated as
            [`query_by_inventory`][provesid.zeropm.ZeroPM.query_by_inventory]
            describes

        Raises
        ------
        ValueError
            If neither ``region_name`` nor ``region_id`` is given.

        Note
        ----
        Either region_name or region_id must be provided.

        Examples
        --------
        >>> rows = ZeroPM().query_by_region("Oceania")
        >>> rows[0]["cas"], rows[0]["country"]
        ('100-00-5', 'New Zealand')
        """
        if region_name is None and region_id is None:
            raise ValueError("Either region_name or region_id must be provided")

        if region_id is not None:
            # Query by region_id
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, gr.region, c.country, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                JOIN region_country_index rci ON c.country_id = rci.country_id
                JOIN global_regions gr ON rci.region_id = gr.region_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND gr.region_id = ?
                ORDER BY aq.query
            """, (region_id,))
        else:
            # Query by region_name (partial, case-insensitive)
            self.cursor.execute("""
                SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, gr.region, c.country, s.source_name
                FROM api_ready_query aq
                JOIN inventory_summary issum ON aq.query_id = issum.query_id
                JOIN inventories inv ON issum.inventory_id = inv.inventory_id
                JOIN sources s ON inv.source_id = s.source_id
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                JOIN region_country_index rci ON c.country_id = rci.country_id
                JOIN global_regions gr ON rci.region_id = gr.region_id
                JOIN api_results ar ON aq.query_id = ar.query_id
                WHERE aq.type = 'CAS Registry Number' AND LOWER(gr.region) LIKE LOWER(?)
                ORDER BY aq.query
            """, (f'%{region_name}%',))

        results = []
        for row in self.cursor.fetchall():
            results.append({
                'cas': row[0],
                'query_id': row[1],
                'inchi_id': row[2],
                'region': row[3],
                'country': row[4],
                'source_name': row[5]
            })

        return results

    def get_countries_for_region(self, region_name=None, region_id=None):
        """
        Get all countries in a specific region.

        Parameters
        ----------
        region_name : str, optional
            Name of the region (case-insensitive partial match)
        region_id : int, optional
            Region ID (exact match)

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'country_id', 'country', 'region'

        Raises
        ------
        ValueError
            If neither ``region_name`` nor ``region_id`` is given.

        Note
        ----
        Either region_name or region_id must be provided.

        Examples
        --------
        >>> [c["country"] for c in ZeroPM().get_countries_for_region("Scandinavia")]
        ['Denmark', 'Finland', 'Norway', 'Sweden']
        """
        if region_name is None and region_id is None:
            raise ValueError("Either region_name or region_id must be provided")

        if region_id is not None:
            self.cursor.execute("""
                SELECT DISTINCT c.country_id, c.country, gr.region
                FROM countries c
                JOIN region_country_index rci ON c.country_id = rci.country_id
                JOIN global_regions gr ON rci.region_id = gr.region_id
                WHERE gr.region_id = ?
                ORDER BY c.country
            """, (region_id,))
        else:
            self.cursor.execute("""
                SELECT DISTINCT c.country_id, c.country, gr.region
                FROM countries c
                JOIN region_country_index rci ON c.country_id = rci.country_id
                JOIN global_regions gr ON rci.region_id = gr.region_id
                WHERE LOWER(gr.region) LIKE LOWER(?)
                ORDER BY c.country
            """, (f'%{region_name}%',))

        countries = []
        for row in self.cursor.fetchall():
            countries.append({
                'country_id': row[0],
                'country': row[1],
                'region': row[2]
            })

        return countries

    def get_inventories_for_country(self, country_name=None, country_id=None):
        """
        Get all inventory sources for a specific country.

        Parameters
        ----------
        country_name : str, optional
            Name of the country (case-insensitive partial match)
        country_id : int, optional
            Country ID (exact match)

        Returns
        -------
        list of dict
            List of dictionaries with keys: 'source_id', 'source_name', 'country', 'link', 'type'

        Raises
        ------
        ValueError
            If neither ``country_name`` nor ``country_id`` is given.

        Note
        ----
        Either country_name or country_id must be provided.

        Examples
        --------
        >>> [i["source_id"] for i in ZeroPM().get_inventories_for_country("Japan")]
        [8, 9, 10, 11]
        """
        if country_name is None and country_id is None:
            raise ValueError("Either country_name or country_id must be provided")

        if country_id is not None:
            self.cursor.execute("""
                SELECT DISTINCT s.source_id, s.source_name, c.country, s.link, s.type
                FROM sources s
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                WHERE c.country_id = ?
                ORDER BY s.source_name
            """, (country_id,))
        else:
            self.cursor.execute("""
                SELECT DISTINCT s.source_id, s.source_name, c.country, s.link, s.type
                FROM sources s
                JOIN country_sources_index csi ON s.source_id = csi.source_id
                JOIN countries c ON csi.country_id = c.country_id
                WHERE LOWER(c.country) LIKE LOWER(?)
                ORDER BY s.source_name
            """, (f'%{country_name}%',))

        inventories = []
        for row in self.cursor.fetchall():
            inventories.append({
                'source_id': row[0],
                'source_name': row[1],
                'country': row[2],
                'link': row[3],
                'type': row[4]
            })

        return inventories

    def count_chemicals_by_inventory(self, source_id):
        """
        Count the number of chemicals in a specific inventory.

        Parameters
        ----------
        source_id : int
            Source ID

        Returns
        -------
        int
            Number of unique CAS numbers in the inventory

        Examples
        --------
        >>> ZeroPM().count_chemicals_by_inventory(12)   # South Korea's
        21580
        """
        self.cursor.execute("""
            SELECT COUNT(DISTINCT aq.query)
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            WHERE aq.type = 'CAS Registry Number' AND inv.source_id = ?
        """, (source_id,))

        return self.cursor.fetchone()[0]

    def count_chemicals_by_country(self, country_id):
        """
        Count the number of chemicals registered in a specific country.

        Parameters
        ----------
        country_id : int
            Country ID

        Returns
        -------
        int
            Number of unique CAS numbers in the country, over all its
            inventories

        Examples
        --------
        >>> ZeroPM().count_chemicals_by_country(1)      # Australia
        25183
        """
        self.cursor.execute("""
            SELECT COUNT(DISTINCT aq.query)
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            WHERE aq.type = 'CAS Registry Number' AND csi.country_id = ?
        """, (country_id,))

        return self.cursor.fetchone()[0]

    def count_chemicals_by_region(self, region_id):
        """
        Count the number of chemicals registered in a specific region.

        Parameters
        ----------
        region_id : int
            Region ID

        Returns
        -------
        int
            Number of unique CAS numbers in the region

        Examples
        --------
        >>> ZeroPM().count_chemicals_by_region(5)       # Oceania
        34175
        """
        self.cursor.execute("""
            SELECT COUNT(DISTINCT aq.query)
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            JOIN region_country_index rci ON c.country_id = rci.country_id
            WHERE aq.type = 'CAS Registry Number' AND rci.region_id = ?
        """, (region_id,))

        return self.cursor.fetchone()[0]

    # ==================== ZeroPM Specific Methods (v0-0-4) ====================

    def get_zeropm_id(self, cas=None, inchi_id=None):
        """
        Get the zeropm_id for a chemical from CAS number or inchi_id.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier

        Returns
        -------
        int or None
            zeropm_id if found, None otherwise. A CAS number is resolved to
            its rank-1 structure first.

        Raises
        ------
        ValueError
            If neither ``cas`` nor ``inchi_id`` is given.

        Note
        ----
        Either cas or inchi_id must be provided.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.get_zeropm_id(cas="50-00-0"), zpm.get_zeropm_id(inchi_id=32227)
        (3224, 3224)
        """
        if cas is None and inchi_id is None:
            raise ValueError("Either cas or inchi_id must be provided")

        if inchi_id is None:
            inchi_id = self._inchi_id_from_cas(cas)
            if inchi_id is None:
                return None

        # Get zeropm_id from inchi_id
        self.cursor.execute("""
            SELECT zeropm_id
            FROM zeropm_chemicals
            WHERE inchi_id = ?
        """, (inchi_id,))
        result = self.cursor.fetchone()
        return result[0] if result else None

    def zeropm_id_to_inchi_id(self, zeropm_id):
        """
        Get the inchi_id for a zeropm_id — the reverse of
        [`get_zeropm_id`][provesid.zeropm.ZeroPM.get_zeropm_id].

        Parameters
        ----------
        zeropm_id : int
            ZeroPM identifier.

        Returns
        -------
        int or None
            The inchi_id, or None when the zeropm_id is not in the database.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.zeropm_id_to_inchi_id(1)
        6210
        >>> zpm.zeropm_id_to_inchi_id(3224)   # formaldehyde
        32227
        """
        self.cursor.execute("""
            SELECT inchi_id
            FROM zeropm_chemicals
            WHERE zeropm_id = ?
        """, (zeropm_id,))
        result = self.cursor.fetchone()
        return result[0] if result else None

    def _inchi_id_from_cas(self, cas):
        """
        Resolve a CAS number to its first inchi_id.

        Parameters
        ----------
        cas : str
            CAS Registry Number.

        Returns
        -------
        int or None
            The first inchi_id for the CAS, or None when it is not found.
        """
        query_id = self.query_cas(cas)
        if query_id is None:
            return None
        inchi_ids, _ = self.get_inchi_id(query_id)
        return inchi_ids[0] if inchi_ids else None


    def get_pm_probabilities(self, cas=None, inchi_id=None, zeropm_id=None):
        """
        Get P/M (Persistent/Mobile) probability data for a chemical.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier
        zeropm_id : int, optional
            ZeroPM identifier

        Returns
        -------
        dict or None
            Dictionary with probability data:

            - probability_of_not_p: Probability of NOT persistent
            - probability_of_p_or_vp: Probability of persistent OR very persistent
            - probability_of_p: Probability of persistent
            - probability_of_vp: Probability of very persistent
            - probability_of_not_m: Probability of NOT mobile
            - probability_of_m_or_vm: Probability of mobile OR very mobile
            - probability_of_m: Probability of mobile but not very mobile
            - probability_of_vm: Probability of very mobile
            - n: Sample size

            ``probability_of_p`` likewise excludes the very persistent, so
            ``p + vp = p_or_vp`` and ``not_p + p_or_vp = 1``; the same holds
            for M.
            Returns None if not found, or if ZeroPM assessed the chemical
            but published no probabilities for it --- formaldehyde is one.

        Raises
        ------
        ValueError
            If none of ``cas``, ``inchi_id`` or ``zeropm_id`` is provided.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> probs = zpm.get_pm_probabilities(inchi_id=6210)
        >>> round(probs["probability_of_p"], 3)
        0.4
        >>> tfa = zpm.get_pm_probabilities(cas="76-05-1")
        >>> round(tfa["probability_of_vm"], 3), round(tfa["probability_of_m_or_vm"], 3)
        (0.995, 1.0)
        >>> zpm.get_pm_probabilities(cas="50-00-0") is None
        True

        Note
        ----
        Three of the mobility columns in ``zeropm-v0-0-4.sqlite`` hold each
        other's values: the one named ``m_or_vm`` holds ``m``, ``m`` holds
        ``vm``, and ``vm`` holds ``m_or_vm``. The file was loaded positionally
        from a CSV that orders them differently. This method, like
        [`batch_get_pm_probabilities`][provesid.zeropm.ZeroPM.batch_get_pm_probabilities]
        and [`get_all_zeropm_chemicals`][provesid.zeropm.ZeroPM.get_all_zeropm_chemicals],
        returns each value under its true name. A query of the table
        written by hand gets the stored names.

        ``pm_probabilities`` is keyed on ``inchi_id``, so a ``zeropm_id`` is
        translated first via
        [`zeropm_id_to_inchi_id`][provesid.zeropm.ZeroPM.zeropm_id_to_inchi_id].
        """
        if cas is None and inchi_id is None and zeropm_id is None:
            raise ValueError("One of cas, inchi_id or zeropm_id must be provided")

        if inchi_id is None:
            if zeropm_id is not None:
                inchi_id = self.zeropm_id_to_inchi_id(zeropm_id)
            else:
                inchi_id = self._inchi_id_from_cas(cas)
            if inchi_id is None:
                return None

        self.cursor.execute(f"""
            SELECT {_PM_PROBABILITY_SELECT}
            FROM pm_probabilities pm
            WHERE pm.inchi_id = ?
        """, (inchi_id,))
        result = self.cursor.fetchone()

        if not result:
            return None

        return dict(zip(PM_PROBABILITY_COLUMNS, result))

    def is_in_zeropm(self, cas=None, inchi_id=None):
        """
        Check if a chemical is in the ZeroPM database.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier

        Returns
        -------
        bool
            True if the chemical has a ``zeropm_id`` (ZeroPM assessed it),
            False otherwise --- including a CAS number that is in the
            inventories but was not assessed

        Raises
        ------
        ValueError
            If neither ``cas`` nor ``inchi_id`` is given.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.is_in_zeropm(cas="50-00-0"), zpm.is_in_zeropm(cas="0-00-0")
        (True, False)
        """
        return self.get_zeropm_id(cas=cas, inchi_id=inchi_id) is not None

    def is_multicomponent(self, inchi_id):
        """
        Check if a substance is a multi-component substance.

        Parameters
        ----------
        inchi_id : int
            InChI identifier

        Returns
        -------
        bool
            True if substance is multi-component, False otherwise

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.is_multicomponent(5), zpm.is_multicomponent(32227)
        (True, False)
        """
        self.cursor.execute("""
            SELECT mc_id
            FROM multi_components
            WHERE inchi_id = ?
        """, (inchi_id,))
        return self.cursor.fetchone() is not None

    def get_multicomponent_id(self, inchi_id):
        """
        Get the multi-component ID for a substance.

        Parameters
        ----------
        inchi_id : int
            InChI identifier

        Returns
        -------
        int or None
            mc_id if found, None otherwise

        Examples
        --------
        >>> ZeroPM().get_multicomponent_id(5)
        1
        """
        self.cursor.execute("""
            SELECT mc_id
            FROM multi_components
            WHERE inchi_id = ?
        """, (inchi_id,))
        result = self.cursor.fetchone()
        return result[0] if result else None

    def get_components(self, mc_id):
        """
        Get all components of a multi-component substance.

        Parameters
        ----------
        mc_id : int
            Multi-component identifier

        Returns
        -------
        list of dict
            List of component information with keys:

            - component_id: Component identifier
            - component_frequency: How often the component appears
            - inchi_id: InChI identifier of the component
            - inchi: InChI string of the component
            - inchikey: InChIKey of the component
            Most frequent first. Empty for an unknown ``mc_id``.

        Examples
        --------
        >>> [c["inchi"] for c in ZeroPM().get_components(1)]
        ['InChI=1S/ClH/h1H/p-1', 'InChI=1S/C8H10N3/c1-11(2)8-5-3-7(10-9)4-6-8/h3-6H,1-2H3/q+1']
        """
        self.cursor.execute("""
            SELECT ci.component_id, ci.component_frequency, c.inchi_id, s.inchi, s.inchikey
            FROM component_index ci
            JOIN components c ON ci.component_id = c.component_id
            JOIN substances s ON c.inchi_id = s.inchi_id
            WHERE ci.mc_id = ?
            ORDER BY ci.component_frequency DESC
        """, (mc_id,))

        components = []
        for row in self.cursor.fetchall():
            components.append({
                'component_id': row[0],
                'component_frequency': row[1],
                'inchi_id': row[2],
                'inchi': row[3],
                'inchikey': row[4]
            })

        return components

    def get_multicomponent_info(self, cas=None, inchi_id=None):
        """
        Get complete multi-component information for a substance.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier

        Returns
        -------
        dict or None
            Dictionary with:

            - mc_id: Multi-component identifier
            - inchi_id: InChI identifier of the multi-component
            - inchi: InChI of the multi-component
            - inchikey: InChIKey of the multi-component
            - components: List of component dictionaries, as
              [`get_components`][provesid.zeropm.ZeroPM.get_components] returns them
            Returns None if not a multi-component substance. A CAS number is
            resolved to its rank-1 structure first.

        Raises
        ------
        ValueError
            If neither ``cas`` nor ``inchi_id`` is given.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> info = zpm.get_multicomponent_info(inchi_id=5)
        >>> info["mc_id"], info["inchikey"], len(info["components"])
        (1, 'CCIAVEMREXZXAK-UHFFFAOYSA-M', 2)
        >>> zpm.get_multicomponent_info(cas="50-00-0") is None
        True
        """
        if inchi_id is None:
            if cas is None:
                raise ValueError("Either cas or inchi_id must be provided")
            query_id = self.query_cas(cas)
            if query_id is None:
                return None
            inchi_ids, _ = self.get_inchi_id(query_id)
            if not inchi_ids:
                return None
            inchi_id = inchi_ids[0]

        # Check if it's a multi-component
        mc_id = self.get_multicomponent_id(inchi_id)
        if mc_id is None:
            return None

        # Get multi-component info
        self.cursor.execute("""
            SELECT mc.inchi_id, s.inchi, s.inchikey
            FROM multi_components mc
            JOIN substances s ON mc.inchi_id = s.inchi_id
            WHERE mc.mc_id = ?
        """, (mc_id,))
        result = self.cursor.fetchone()

        if not result:
            return None

        # Get components
        components = self.get_components(mc_id)

        return {
            'mc_id': mc_id,
            'inchi_id': result[0],
            'inchi': result[1],
            'inchikey': result[2],
            'components': components
        }

    def is_in_cleanventory(self, cas=None, inchi_id=None):
        """
        Check if a chemical is in the Cleanventory database.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier

        Returns
        -------
        bool
            True if chemical is in Cleanventory, False otherwise. A CAS
            number is resolved to its rank-1 structure first.

        Raises
        ------
        ValueError
            If neither ``cas`` nor ``inchi_id`` is given.

        Examples
        --------
        >>> zpm = ZeroPM()
        >>> zpm.is_in_cleanventory(cas="50-00-0"), zpm.is_in_cleanventory(cas="0-00-0")
        (True, False)
        """
        if inchi_id is None:
            if cas is None:
                raise ValueError("Either cas or inchi_id must be provided")
            query_id = self.query_cas(cas)
            if query_id is None:
                return False
            inchi_ids, _ = self.get_inchi_id(query_id)
            if not inchi_ids:
                return False
            inchi_id = inchi_ids[0]

        self.cursor.execute("""
            SELECT cleanventory_id
            FROM cleanventory_chemicals
            WHERE inchi_id = ?
        """, (inchi_id,))
        return self.cursor.fetchone() is not None

    def get_consensus_score(self, cas=None, inchi_id=None):
        """
        Get consensus scoring information for a chemical.

        Parameters
        ----------
        cas : str, optional
            CAS Registry Number
        inchi_id : int, optional
            InChI identifier

        Returns
        -------
        list of dict or None
            List of consensus scores from different inventories, each with:

            - inventory_id: Inventory identifier
            - consensus_score: Consensus score value
            - consensus_count: Count of consensus
            Returns None if not found. The values are as stored: in v0.0.4
            ``consensus_score`` is a string of a small integer and
            ``consensus_count`` a fraction between 0 and 1.

        Raises
        ------
        ValueError
            If neither ``cas`` nor ``inchi_id`` is given.

        Examples
        --------
        >>> scores = ZeroPM().get_consensus_score(cas="50-00-0")
        >>> scores[0]
        {'inventory_id': 692, 'consensus_score': '2', 'consensus_count': 0.198675496688742}
        """
        if inchi_id is None:
            if cas is None:
                raise ValueError("Either cas or inchi_id must be provided")
            query_id = self.query_cas(cas)
            if query_id is None:
                return None
            inchi_ids, _ = self.get_inchi_id(query_id)
            if not inchi_ids:
                return None
            inchi_id = inchi_ids[0]

        self.cursor.execute("""
            SELECT inventory_id, consensus_score, consensus_count
            FROM consensus_index
            WHERE inchi_id = ?
        """, (inchi_id,))

        results = self.cursor.fetchall()
        if not results:
            return None

        consensus_data = []
        for row in results:
            consensus_data.append({
                'inventory_id': row[0],
                'consensus_score': row[1],
                'consensus_count': row[2]
            })

        return consensus_data

    def get_all_zeropm_chemicals(self, limit=None, include_pm_probs=False):
        """
        Get all chemicals in the ZeroPM database.

        Parameters
        ----------
        limit : int, optional
            Maximum number of results to return
        include_pm_probs : bool, optional
            If True, include P/M probability data (default: False)

        Returns
        -------
        pandas.DataFrame
            DataFrame with zeropm_id, inchi_id, inchi, inchikey
            If include_pm_probs=True, also includes all probability columns,
            NaN where none were published

        Examples
        --------
        >>> df = ZeroPM().get_all_zeropm_chemicals(limit=2, include_pm_probs=True)
        >>> df[["zeropm_id", "inchi_id", "probability_of_p", "n"]].round(3)
           zeropm_id  inchi_id  probability_of_p  n
        0          1      6210             0.400  1
        1          2    101901             0.438  1
        """
        if include_pm_probs:
            query = f"""
                SELECT zc.zeropm_id, zc.inchi_id, s.inchi, s.inchikey,
                       {_PM_PROBABILITY_SELECT}
                FROM zeropm_chemicals zc
                JOIN substances s ON zc.inchi_id = s.inchi_id
                LEFT JOIN pm_probabilities pm ON zc.inchi_id = pm.inchi_id
            """
            columns = ['zeropm_id', 'inchi_id', 'inchi', 'inchikey',
                       *PM_PROBABILITY_COLUMNS]
        else:
            query = """
                SELECT zc.zeropm_id, zc.inchi_id, s.inchi, s.inchikey
                FROM zeropm_chemicals zc
                JOIN substances s ON zc.inchi_id = s.inchi_id
            """
            columns = ['zeropm_id', 'inchi_id', 'inchi', 'inchikey']

        if limit:
            query += f" LIMIT {limit}"

        self.cursor.execute(query)
        results = self.cursor.fetchall()

        return pd.DataFrame(results, columns=columns)

    def get_all_multicomponent_substances(self, limit=None):
        """
        Get all multi-component substances.

        Parameters
        ----------
        limit : int, optional
            Maximum number of results to return

        Returns
        -------
        pandas.DataFrame
            DataFrame with mc_id, inchi_id, inchi, inchikey, component_count

        Examples
        --------
        >>> ZeroPM().get_all_multicomponent_substances(limit=2)[["mc_id", "inchi_id", "component_count"]]
           mc_id  inchi_id  component_count
        0      1         5                2
        1      2         6                2
        """
        query = """
            SELECT mc.mc_id, mc.inchi_id, s.inchi, s.inchikey,
                   COUNT(ci.component_id) as component_count
            FROM multi_components mc
            JOIN substances s ON mc.inchi_id = s.inchi_id
            LEFT JOIN component_index ci ON mc.mc_id = ci.mc_id
            GROUP BY mc.mc_id, mc.inchi_id, s.inchi, s.inchikey
        """

        if limit:
            query += f" LIMIT {limit}"

        self.cursor.execute(query)
        results = self.cursor.fetchall()

        return pd.DataFrame(results, columns=['mc_id', 'inchi_id', 'inchi', 'inchikey', 'component_count'])

    def batch_get_pm_probabilities(self, cas_list=None, inchi_id_list=None):
        """
        Get P/M probabilities for multiple chemicals at once.

        Parameters
        ----------
        cas_list : list of str, optional
            List of CAS Registry Numbers
        inchi_id_list : list of int, optional
            List of InChI identifiers

        Returns
        -------
        pandas.DataFrame
            DataFrame with columns for identifiers and all probability values:
            one row per chemical ZeroPM assessed, with ``cas`` first when
            ``cas_list`` was given. Chemicals it did not assess, and CAS
            numbers not in the database, have no row; one assessed without
            published probabilities has NaN. Empty when nothing is found.

        Examples
        --------
        >>> df = ZeroPM().batch_get_pm_probabilities(cas_list=["50-00-0", "64-17-5", "0-00-0"])
        >>> df[["cas", "probability_of_p", "probability_of_vm"]].round(3)
               cas  probability_of_p  probability_of_vm
        0  50-00-0               NaN                NaN
        1  64-17-5             0.307              0.682
        """
        if cas_list is not None:
            # Convert CAS to inchi_ids
            inchi_id_list = []
            cas_to_inchi_id = {}
            for cas in cas_list:
                query_id = self.query_cas(cas)
                if query_id:
                    inchi_ids, _ = self.get_inchi_id(query_id)
                    if inchi_ids:
                        inchi_id = inchi_ids[0]
                        inchi_id_list.append(inchi_id)
                        cas_to_inchi_id[inchi_id] = cas

        if not inchi_id_list:
            return pd.DataFrame()

        # Query all at once
        placeholders = ','.join('?' * len(inchi_id_list))
        query = f"""
            SELECT zc.inchi_id, s.inchi, s.inchikey,
                   {_PM_PROBABILITY_SELECT}
            FROM zeropm_chemicals zc
            JOIN substances s ON zc.inchi_id = s.inchi_id
            LEFT JOIN pm_probabilities pm ON zc.inchi_id = pm.inchi_id
            WHERE zc.inchi_id IN ({placeholders})
        """

        self.cursor.execute(query, inchi_id_list)
        results = self.cursor.fetchall()

        df = pd.DataFrame(results, columns=[
            'inchi_id', 'inchi', 'inchikey', *PM_PROBABILITY_COLUMNS
        ])

        # Add CAS if available
        if cas_list is not None:
            df['cas'] = df['inchi_id'].map(cas_to_inchi_id)
            # Reorder columns to put cas first
            cols = ['cas'] + [col for col in df.columns if col != 'cas']
            df = df[cols]

        return df
Methods:
__init__(db_name='zeropm-v0-0-4.sqlite', auto_download=True, db_url=None, data_dir=None, db_path=None, redownload=False)

Initialize connection to the ZeroPM SQLite database.

Parameters:

Name Type Description Default
db_name str

Name of the SQLite database file (default: 'zeropm-v0-0-4.sqlite')

'zeropm-v0-0-4.sqlite'
auto_download bool

If True, automatically download the database if not found (default: True)

True
db_url str

Custom URL to download the database from. If None, uses the default GitHub URL.

None
data_dir str

Directory to store the database when db_path is not provided.

None
db_path str

Full path to a database file. Overrides db_name/data_dir.

None
redownload bool

If True, force re-download when auto_download is enabled.

False

Raises:

Type Description
FileNotFoundError

If the database is not on disk and auto_download is False.

Examples:

>>> zpm = ZeroPM()
>>> os.path.basename(zpm.db_path)
'zeropm-v0-0-4.sqlite'
>>> ZeroPM(db_path="/no/such/zeropm.sqlite", auto_download=False)
Traceback (most recent call last):
...
FileNotFoundError: Database not found at: /no/such/zeropm.sqlite
...
Source code in src/provesid/zeropm.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def __init__(
    self,
    db_name: str = 'zeropm-v0-0-4.sqlite',
    auto_download: bool = True,
    db_url: Optional[str] = None,
    data_dir: Optional[str] = None,
    db_path: Optional[str] = None,
    redownload: bool = False,
):
    """
    Initialize connection to the ZeroPM SQLite database.

    Parameters
    ----------
    db_name : str, optional
        Name of the SQLite database file (default: 'zeropm-v0-0-4.sqlite')
    auto_download : bool, optional
        If True, automatically download the database if not found (default: True)
    db_url : str, optional
        Custom URL to download the database from. If None, uses the default GitHub URL.
    data_dir : str, optional
        Directory to store the database when ``db_path`` is not provided.
    db_path : str, optional
        Full path to a database file. Overrides ``db_name``/``data_dir``.
    redownload : bool, optional
        If True, force re-download when ``auto_download`` is enabled.

    Raises
    ------
    FileNotFoundError
        If the database is not on disk and ``auto_download`` is False.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> os.path.basename(zpm.db_path)
    'zeropm-v0-0-4.sqlite'
    >>> ZeroPM(db_path="/no/such/zeropm.sqlite", auto_download=False)
    Traceback (most recent call last):
    ...
    FileNotFoundError: Database not found at: /no/such/zeropm.sqlite
    ...
    """
    self.logger = logging.getLogger(__name__)
    if db_path is None:
        self.path = data_dir or user_dataset_path()
        self.db_path = os.path.join(self.path, db_name)
    else:
        self.db_path = os.path.abspath(os.path.expanduser(db_path))
        self.path = os.path.dirname(self.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, download if needed
    if needs_download:
        if auto_download:
            if redownload and os.path.exists(self.db_path):
                self.logger.info(
                    "Forced ZeroPM redownload requested for: %s", self.db_path
                )
            else:
                self.logger.info(f"Database not found at: {self.db_path}")
            self.logger.info("Downloading database automatically...")
            self.download_database(url=self.db_url, force=redownload)
        else:
            raise FileNotFoundError(
                f"Database not found at: {self.db_path}\n"
                f"Please run ZeroPM.download_database() or set auto_download=True"
            )

    # Create the connection.  One per thread, reused for every query on
    # that thread and released by close() or by leaving a ``with`` block.
    # row_factory stays unset: this module's queries index rows by
    # position, and sqlite3.Row would be a behaviour change.
    self._open_database(self.db_path, row_factory=None)

    # Cache chemical names for fuzzy matching (lazy loading)
    self._chemical_names_cache = None
download_database(url=None, force=False)

Download the ZeroPM SQLite database from a remote URL.

The transfer is resumable: an interrupted download leaves a .part file beside the destination and the next call continues from it rather than starting the 100 MB again. Nothing replaces an existing database until the new file has downloaded in full and opened successfully.

Parameters:

Name Type Description Default
url str

URL to download the database from. If None, uses the default GitHub URL.

None
force bool

If True, download even if the database already exists (default: False)

False

Returns:

Type Description
str

Path to the downloaded database file

Raises:

Type Description
FileExistsError

If the database already exists and force=False

DownloadError

If the download could not be completed, or the file that arrived is not a readable SQLite database

Example

zpm = ZeroPM() zpm.download_database(force=True) # doctest: +SKIP '/home/me/.local/share/provesid/zeropm-v0-0-4.sqlite'

Source code in src/provesid/zeropm.py
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
def download_database(self, url=None, force=False):
    """
    Download the ZeroPM SQLite database from a remote URL.

    The transfer is resumable: an interrupted download leaves a ``.part``
    file beside the destination and the next call continues from it rather
    than starting the 100 MB again. Nothing replaces an existing database
    until the new file has downloaded in full and opened successfully.

    Parameters
    ----------
    url : str, optional
        URL to download the database from. If None, uses the default GitHub URL.
    force : bool, optional
        If True, download even if the database already exists (default: False)

    Returns
    -------
    str
        Path to the downloaded database file

    Raises
    ------
    FileExistsError
        If the database already exists and force=False
    provesid.datasets.DownloadError
        If the download could not be completed, or the file that arrived is
        not a readable SQLite database

    Example
    -------
    >>> zpm = ZeroPM()
    >>> zpm.download_database(force=True)      # doctest: +SKIP
    '/home/me/.local/share/provesid/zeropm-v0-0-4.sqlite'
    """
    download_url = url or self.db_url

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

    def must_be_a_database(path):
        """Reject a download that is not a readable SQLite file.

        Run on the ``.part`` file, before it is moved into place, so a
        damaged download leaves any existing database untouched.
        """
        connection = sqlite3.connect(path)
        try:
            connection.execute(
                "SELECT name FROM sqlite_master WHERE type='table' LIMIT 1"
            ).fetchone()
        except sqlite3.Error as exc:
            raise RuntimeError(f"Downloaded database is corrupted: {exc}") from exc
        finally:
            connection.close()

    download_file(
        download_url,
        self.db_path,
        verify=must_be_a_database,
        description="ZeroPM database",
        log=self.logger,
    )
    return self.db_path
query_cas(cas_rn)

Returns a query id from the query with the CAS RN to be used with the query_results function.

Parameters:

Name Type Description Default
cas_rn str

CAS Registry Number

required

Returns:

Type Description
int or None

query_id if found, None otherwise

Examples:

>>> zpm = ZeroPM()
>>> zpm.query_cas("50-00-0")
8671
>>> zpm.query_cas("0-00-0") is None
True
Source code in src/provesid/zeropm.py
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
def query_cas(self, cas_rn):
    """
    Returns a query id from the query with the CAS RN to be used with the query_results function.

    Parameters
    ----------
    cas_rn : str
        CAS Registry Number

    Returns
    -------
    int or None
        query_id if found, None otherwise

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.query_cas("50-00-0")
    8671
    >>> zpm.query_cas("0-00-0") is None
    True
    """
    self.cursor.execute("""
        SELECT query_id
        FROM api_ready_query
        WHERE query = ? AND type = 'CAS Registry Number'
    """, (cas_rn,))
    result = self.cursor.fetchone()
    return result[0] if result else None
query_name(name)

Returns a query id from the query with the exact chemical name to be used with the query_results function.

Parameters:

Name Type Description Default
name str

Exact chemical name, case included: the inventories' spellings are separate queries.

required

Returns:

Type Description
int or None

query_id if found, None otherwise

Examples:

>>> zpm = ZeroPM()
>>> zpm.query_name("Formaldehyde"), zpm.query_name("formaldehyde")
(8672, 325578)
Source code in src/provesid/zeropm.py
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
def query_name(self, name):
    """
    Returns a query id from the query with the exact chemical name to be used with the query_results function.

    Parameters
    ----------
    name : str
        Exact chemical name, case included: the inventories' spellings
        are separate queries.

    Returns
    -------
    int or None
        query_id if found, None otherwise

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.query_name("Formaldehyde"), zpm.query_name("formaldehyde")
    (8672, 325578)
    """
    self.cursor.execute("""
        SELECT query_id
        FROM api_ready_query
        WHERE query = ? AND type = 'chemical name'
    """, (name,))
    result = self.cursor.fetchone()
    return result[0] if result else None
query_similar_name(name, number_of_results=5, score_cutoff=80)

Returns number_of_results query ids from a query with similar chemical names using fuzzy string matching.

Parameters:

Name Type Description Default
name str

Chemical name to search for

required
number_of_results int

Maximum number of results to return (default: 5)

5
score_cutoff int

Minimum similarity score (0-100) (default: 80)

80

Returns:

Type Description
list or None

List of query_ids, or None if no matches above cutoff

Notes

Scores with rapidfuzz's WRatio, which rates a short name highly whenever it appears inside the query. match_similar_name uses a stricter scorer and reports the names and scores.

Examples:

>>> zpm = ZeroPM()
>>> zpm.query_similar_name("formaldehyd")
[8672, 8673, 104113, 325578, 367895]
Source code in src/provesid/zeropm.py
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
def query_similar_name(self, name, number_of_results=5, score_cutoff=80):
    """
    Returns number_of_results query ids from a query with similar chemical names
    using fuzzy string matching.

    Parameters
    ----------
    name : str
        Chemical name to search for
    number_of_results : int, optional
        Maximum number of results to return (default: 5)
    score_cutoff : int, optional
        Minimum similarity score (0-100) (default: 80)

    Returns
    -------
    list or None
        List of query_ids, or None if no matches above cutoff

    Notes
    -----
    Scores with ``rapidfuzz``'s ``WRatio``, which rates a short name
    highly whenever it appears inside the query.
    [`match_similar_name`][provesid.zeropm.ZeroPM.match_similar_name] uses
    a stricter scorer and reports the names and scores.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.query_similar_name("formaldehyd")
    [8672, 8673, 104113, 325578, 367895]
    """
    names_cache = self._get_chemical_names_cache()
    name_list = [n[0] for n in names_cache]

    res = process.extract(
        name,
        name_list,
        scorer=fuzz.WRatio,
        limit=number_of_results,
        processor=utils.default_process,
    )

    if (len(res) < 1) or (res[0][1] < score_cutoff):
        return None
    else:
        # Get query_ids for matching names
        query_ids = []
        for match in res:
            if match[1] >= score_cutoff:
                matched_name = match[0]
                # Find the query_id for this name
                query_id = next((n[1] for n in names_cache if n[0] == matched_name), None)
                if query_id:
                    query_ids.append(query_id)
        return query_ids if query_ids else None
match_similar_name(name, number_of_results=5, score_cutoff=80, scorer=None)

Fuzzy-match a chemical name and return the matches with their scores.

Same purpose as query_similar_name, but keeps the matched name and the similarity score instead of discarding them, so callers can tell what matched and how well.

Uses rapidfuzz.fuzz.ratio rather than the WRatio used by query_similar_name. WRatio includes a partial-ratio term that scores a short name highly whenever it appears anywhere inside the query, which over a list of millions of chemical names is a reliable source of nonsense: WRatio("caffiene", "ne") is 90 and WRatio("zzzznotachemical", "Mica") is also 90, while ratio puts both at 40 and still scores the genuine typo ratio("caffiene", "caffeine") at 87.5.

Parameters:

Name Type Description Default
name str

Chemical name to search for.

required
number_of_results int

Maximum number of matches to return (default: 5).

5
score_cutoff int

Minimum similarity score, 0-100 (default: 80).

80
scorer callable

A rapidfuzz.fuzz scorer. Defaults to fuzz.ratio. Pass fuzz.token_sort_ratio when word order may differ; avoid fuzz.WRatio for the reason above.

None

Returns:

Type Description
list of tuple

(matched_name, query_id, score) tuples, best first. Empty when nothing scores at or above score_cutoff.

Examples:

>>> zpm = ZeroPM()
>>> name, query_id, score = zpm.match_similar_name("formaldehyd")[0]
>>> name, round(score, 1)
('Formaldehyde', 95.7)
>>> zpm.match_similar_name("zzzznotachemical")
[]
Source code in src/provesid/zeropm.py
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
def match_similar_name(self, name, number_of_results=5, score_cutoff=80,
                       scorer=None):
    """
    Fuzzy-match a chemical name and return the matches with their scores.

    Same purpose as
    [`query_similar_name`][provesid.zeropm.ZeroPM.query_similar_name], but
    keeps the matched name and the similarity score instead of discarding
    them, so callers can tell *what* matched and *how well*.

    Uses ``rapidfuzz.fuzz.ratio`` rather than the ``WRatio`` used by
    [`query_similar_name`][provesid.zeropm.ZeroPM.query_similar_name].
    ``WRatio`` includes a partial-ratio term that scores a short name
    highly whenever it appears anywhere inside the query, which over a list
    of millions of chemical names is a reliable source of nonsense:
    ``WRatio("caffiene", "ne")`` is 90 and ``WRatio("zzzznotachemical",
    "Mica")`` is also 90, while ``ratio`` puts both at 40 and still scores
    the genuine typo ``ratio("caffiene", "caffeine")`` at 87.5.

    Parameters
    ----------
    name : str
        Chemical name to search for.
    number_of_results : int, optional
        Maximum number of matches to return (default: 5).
    score_cutoff : int, optional
        Minimum similarity score, 0-100 (default: 80).
    scorer : callable, optional
        A ``rapidfuzz.fuzz`` scorer. Defaults to ``fuzz.ratio``. Pass
        ``fuzz.token_sort_ratio`` when word order may differ; avoid
        ``fuzz.WRatio`` for the reason above.

    Returns
    -------
    list of tuple
        ``(matched_name, query_id, score)`` tuples, best first. Empty when
        nothing scores at or above ``score_cutoff``.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> name, query_id, score = zpm.match_similar_name("formaldehyd")[0]
    >>> name, round(score, 1)
    ('Formaldehyde', 95.7)
    >>> zpm.match_similar_name("zzzznotachemical")
    []
    """
    names_cache = self._get_chemical_names_cache()
    query_id_of = {row[0]: row[1] for row in names_cache}

    matches = process.extract(
        name,
        list(query_id_of),
        scorer=scorer or fuzz.ratio,
        limit=number_of_results,
        processor=utils.default_process,
    )

    return [
        (matched_name, query_id_of[matched_name], score)
        for matched_name, score, _ in matches
        if score >= score_cutoff
    ]
get_id_table_from_similar_name(name, number_of_results=5, score_cutoff=80)

Returns identifiers for the chemical whose name best fuzzy-matches name.

The fuzzy counterpart of get_id_table_from_name: use it when the name may be misspelled or formatted differently from the database entry. The table is built for the single best-scoring match.

Parameters:

Name Type Description Default
name str

Chemical name, possibly misspelled.

required
number_of_results int

How many fuzzy candidates to consider (default: 5). Only the best one is turned into a table.

5
score_cutoff int

Minimum rapidfuzz.fuzz.ratio score, 0-100 (default: 80); see match_similar_name.

80

Returns:

Type Description
DataFrame or None

Same columns as get_id_table_from_name, with an extra matched_name column recording what actually matched, and match_score holding its similarity. None when nothing scores at or above score_cutoff.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_similar_name("formaldehyd")
>>> row = df.iloc[0]
>>> row["name"], row["matched_name"], round(float(row["match_score"]), 1), row["inchikey"]
('formaldehyd', 'Formaldehyde', 95.7, 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
Source code in src/provesid/zeropm.py
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
def get_id_table_from_similar_name(self, name, number_of_results=5, score_cutoff=80):
    """
    Returns identifiers for the chemical whose name best fuzzy-matches *name*.

    The fuzzy counterpart of
    [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name]:
    use it when the name may be misspelled or formatted differently from
    the database entry. The table is built for the single best-scoring
    match.

    Parameters
    ----------
    name : str
        Chemical name, possibly misspelled.
    number_of_results : int, optional
        How many fuzzy candidates to consider (default: 5). Only the best
        one is turned into a table.
    score_cutoff : int, optional
        Minimum ``rapidfuzz.fuzz.ratio`` score, 0-100 (default: 80); see
        [`match_similar_name`][provesid.zeropm.ZeroPM.match_similar_name].

    Returns
    -------
    pandas.DataFrame or None
        Same columns as
        [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name],
        with an extra ``matched_name`` column recording what actually
        matched, and ``match_score`` holding its similarity. None when
        nothing scores at or above ``score_cutoff``.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_similar_name("formaldehyd")
    >>> row = df.iloc[0]
    >>> row["name"], row["matched_name"], round(float(row["match_score"]), 1), row["inchikey"]
    ('formaldehyd', 'Formaldehyde', 95.7, 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
    """
    matches = self.match_similar_name(
        name, number_of_results=number_of_results, score_cutoff=score_cutoff
    )
    if not matches:
        self.logger.debug("No fuzzy name match for '%s' at cutoff %s", name, score_cutoff)
        return None

    matched_name, query_id, score = matches[0]
    table = self._id_table_for_query_id(query_id, name)
    if table is None or table.empty:
        return None

    table["matched_name"] = matched_name
    table["match_score"] = score
    return table
get_inchi_id(query_id)

Returns all the inchi_id and ranks of a query with a given query_id.

Parameters:

Name Type Description Default
query_id int

Query identifier

required

Returns:

Type Description
tuple of (list, list)

(inchi_ids, ranks) sorted by rank, with duplicates removed; two empty lists when the query has no structures

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_inchi_id(zpm.query_cas("50-00-0"))
([32227], [1])
>>> zpm.get_inchi_id(zpm.query_name("formaldehyde"))
([32227, 73275, 27053, 119941], [1, 2, 3, 4])
Source code in src/provesid/zeropm.py
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
def get_inchi_id(self, query_id):
    """
    Returns all the inchi_id and ranks of a query with a given query_id.

    Parameters
    ----------
    query_id : int
        Query identifier

    Returns
    -------
    tuple of (list, list)
        (inchi_ids, ranks) sorted by rank, with duplicates removed; two
        empty lists when the query has no structures

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_inchi_id(zpm.query_cas("50-00-0"))
    ([32227], [1])
    >>> zpm.get_inchi_id(zpm.query_name("formaldehyde"))
    ([32227, 73275, 27053, 119941], [1, 2, 3, 4])
    """
    self.cursor.execute("""
        SELECT DISTINCT inchi_id, rank
        FROM api_results
        WHERE query_id = ?
        ORDER BY rank
    """, (query_id,))
    results = self.cursor.fetchall()

    if not results:
        return [], []

    # Separate inchi_ids and ranks
    inchi_ids = [r[0] for r in results]
    ranks = [r[1] for r in results]

    return inchi_ids, ranks
get_inchi(inchi_id)

Returns the inchi and inchikey string of a given inchi_id.

Parameters:

Name Type Description Default
inchi_id int

InChI identifier

required

Returns:

Type Description
tuple of (str, str) or (None, None)

(inchi, inchikey) if found, (None, None) otherwise

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_inchi(32227)
('InChI=1S/CH2O/c1-2/h1H2', 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
Source code in src/provesid/zeropm.py
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
def get_inchi(self, inchi_id):
    """
    Returns the inchi and inchikey string of a given inchi_id.

    Parameters
    ----------
    inchi_id : int
        InChI identifier

    Returns
    -------
    tuple of (str, str) or (None, None)
        (inchi, inchikey) if found, (None, None) otherwise

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_inchi(32227)
    ('InChI=1S/CH2O/c1-2/h1H2', 'WSFSSNUMVMOOMR-UHFFFAOYSA-N')
    """
    self.cursor.execute("""
        SELECT inchi, inchikey
        FROM substances
        WHERE inchi_id = ?
    """, (inchi_id,))
    result = self.cursor.fetchone()
    return (result[0], result[1]) if result else (None, None)
get_names(cas_rn)

Returns all the names for a CAS number.

Parameters:

Name Type Description Default
cas_rn str

CAS Registry Number

required

Returns:

Type Description
list

The distinct names the inventories list under this CAS number, excluding the CAS number itself, in no particular order. Empty when the CAS number is not in the database.

Examples:

>>> zpm = ZeroPM()
>>> sorted(zpm.get_names("64-17-5"))[:4]
['Alcohol', 'ETHANOL', 'ETHYL ALCOHOL', 'Ethanol']
Source code in src/provesid/zeropm.py
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
def get_names(self, cas_rn):
    """
    Returns all the names for a CAS number.

    Parameters
    ----------
    cas_rn : str
        CAS Registry Number

    Returns
    -------
    list
        The distinct names the inventories list under this CAS number,
        excluding the CAS number itself, in no particular order. Empty
        when the CAS number is not in the database.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> sorted(zpm.get_names("64-17-5"))[:4]
    ['Alcohol', 'ETHANOL', 'ETHYL ALCOHOL', 'Ethanol']
    """
    query_id = self.query_cas(cas_rn)
    if query_id is None:
        return []

    # Get inventory_ids from inventory_summary
    self.cursor.execute("""
        SELECT inventory_id
        FROM inventory_summary
        WHERE query_id = ?
    """, (query_id,))
    inventory_ids = [row[0] for row in self.cursor.fetchall()]

    if len(inventory_ids) == 0:
        return []

    # Get identifiers from inventories
    names = set()
    for inv_id in inventory_ids:
        self.cursor.execute("""
            SELECT identifier
            FROM inventories
            WHERE inventory_id = ?
        """, (inv_id,))
        result = self.cursor.fetchone()
        if result:
            # Split by semicolon and add to set
            identifier_string = result[0]
            for name in identifier_string.split(';'):
                name = name.strip()
                if name and name != cas_rn:
                    names.add(name)

    return list(names)
get_smiles_from_cas(cas_rn)

Returns the SMILES from a CAS number. SMILES is generated on-the-fly from InChI using RDKit.

Parameters:

Name Type Description Default
cas_rn str

CAS Registry Number

required

Returns:

Type Description
str or None

SMILES string of the rank-1 structure, or None if not found

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_smiles_from_cas("50-00-0")
'C=O'
Source code in src/provesid/zeropm.py
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
def get_smiles_from_cas(self, cas_rn):
    """
    Returns the SMILES from a CAS number.
    SMILES is generated on-the-fly from InChI using RDKit.

    Parameters
    ----------
    cas_rn : str
        CAS Registry Number

    Returns
    -------
    str or None
        SMILES string of the rank-1 structure, or None if not found

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_smiles_from_cas("50-00-0")
    'C=O'
    """
    query_id = self.query_cas(cas_rn)
    if query_id is None:
        return None

    # Get inchi_id from the query_id
    inchi_ids, _ = self.get_inchi_id(query_id)
    if len(inchi_ids) == 0:
        return None

    # Get InChI and convert to SMILES
    inchi, _ = self.get_inchi(inchi_ids[0])
    if inchi is None:
        return None

    return self._inchi_to_smiles(inchi)
get_cas_from_inchi(inchi)

Returns the CAS number(s) from an InChI string.

The InChI is found as in get_id_table_from_inchi: as a string, else by its InChIKey with either flag.

Parameters:

Name Type Description Default
inchi str

InChI string, standard or not

required

Returns:

Type Description
str, list, or None

CAS number, list of CAS numbers, or None if not found. Every CAS number whose query reaches this structure at any rank, so the list includes relatives: formaldehyde's includes carbon monoxide's 630-08-0, which reaches it at rank 2. The order is the order ZeroPM stored its results in, which is not a ranking but often puts the main number first: ethanol's list starts 64-17-5 and caffeine's 58-08-2.

Examples:

>>> zpm = ZeroPM()
>>> cas = zpm.get_cas_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
>>> "50-00-0" in cas, "630-08-0" in cas
(True, True)
>>> zpm.get_cas_from_inchi("InChI=1S/Xx") is None
True
Source code in src/provesid/zeropm.py
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
def get_cas_from_inchi(self, inchi):
    """
    Returns the CAS number(s) from an InChI string.

    The InChI is found as in
    [`get_id_table_from_inchi`][provesid.zeropm.ZeroPM.get_id_table_from_inchi]:
    as a string, else by its InChIKey with either flag.

    Parameters
    ----------
    inchi : str
        InChI string, standard or not

    Returns
    -------
    str, list, or None
        CAS number, list of CAS numbers, or None if not found. Every CAS
        number whose query reaches this structure at any rank, so the
        list includes relatives: formaldehyde's includes carbon
        monoxide's ``630-08-0``, which reaches it at rank 2. The order is
        the order ZeroPM stored its results in, which is not a ranking
        but often puts the main number first: ethanol's list starts
        ``64-17-5`` and caffeine's ``58-08-2``.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> cas = zpm.get_cas_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
    >>> "50-00-0" in cas, "630-08-0" in cas
    (True, True)
    >>> zpm.get_cas_from_inchi("InChI=1S/Xx") is None
    True
    """
    # First, find the inchi_id
    result = self._find_substance_by_inchi(inchi)
    if not result:
        return None

    inchi_id = result[0]

    # Find all query_ids for this inchi_id that are CAS numbers, in the
    # order ZeroPM stored its results
    self.cursor.execute("""
        SELECT aq.query
        FROM api_results ar
        JOIN api_ready_query aq ON ar.query_id = aq.query_id
        WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
        GROUP BY aq.query
        ORDER BY MIN(ar.rowid)
    """, (inchi_id,))
    cas_numbers = [row[0] for row in self.cursor.fetchall()]

    if not cas_numbers:
        return None
    elif len(cas_numbers) == 1:
        return cas_numbers[0]
    else:
        return cas_numbers
get_cas_from_inchikey(inchikey)

Returns the CAS number(s) from an InChIKey.

The key is looked up with either flag, as in get_id_table_from_inchikey.

Parameters:

Name Type Description Default
inchikey str

InChIKey string, standard or not

required

Returns:

Type Description
str, list, or None

CAS number, list of CAS numbers, or None if not found; as broad as get_cas_from_inchi

Examples:

>>> zpm = ZeroPM()
>>> "64-17-5" in zpm.get_cas_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
True
Source code in src/provesid/zeropm.py
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
def get_cas_from_inchikey(self, inchikey):
    """
    Returns the CAS number(s) from an InChIKey.

    The key is looked up with either flag, as in
    [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].

    Parameters
    ----------
    inchikey : str
        InChIKey string, standard or not

    Returns
    -------
    str, list, or None
        CAS number, list of CAS numbers, or None if not found; as broad
        as [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> "64-17-5" in zpm.get_cas_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
    True
    """
    # First, find the inchi_id, under either flag spelling
    result = self._find_substance_by_inchikey(inchikey)
    if not result:
        return None

    inchi_id = result[0]

    # Find all query_ids for this inchi_id that are CAS numbers, in the
    # order ZeroPM stored its results
    self.cursor.execute("""
        SELECT aq.query
        FROM api_results ar
        JOIN api_ready_query aq ON ar.query_id = aq.query_id
        WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
        GROUP BY aq.query
        ORDER BY MIN(ar.rowid)
    """, (inchi_id,))
    cas_numbers = [row[0] for row in self.cursor.fetchall()]

    if not cas_numbers:
        return None
    elif len(cas_numbers) == 1:
        return cas_numbers[0]
    else:
        return cas_numbers
get_smiles_from_inchikey(inchikey)

Returns the SMILES from an InChIKey. SMILES is generated on-the-fly from InChI using RDKit. The key is looked up with either flag, as in get_id_table_from_inchikey.

Parameters:

Name Type Description Default
inchikey str

InChIKey string, standard or not

required

Returns:

Type Description
str or None

SMILES string, or None if not found

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_smiles_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
'CCO'
Source code in src/provesid/zeropm.py
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
def get_smiles_from_inchikey(self, inchikey):
    """
    Returns the SMILES from an InChIKey.
    SMILES is generated on-the-fly from InChI using RDKit. The key is
    looked up with either flag, as in
    [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].

    Parameters
    ----------
    inchikey : str
        InChIKey string, standard or not

    Returns
    -------
    str or None
        SMILES string, or None if not found

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_smiles_from_inchikey("LFQSCWFLJHTTHZ-UHFFFAOYSA-N")
    'CCO'
    """
    # Get InChI from InChIKey, under either flag spelling
    result = self._find_substance_by_inchikey(inchikey)

    if not result:
        return None

    inchi = result[1]
    return self._inchi_to_smiles(inchi)
get_cas_from_smiles(smiles)

Returns the CAS number from a SMILES string. This is done by converting the SMILES to InChI and then to CAS number.

Parameters:

Name Type Description Default
smiles str

SMILES string

required

Returns:

Type Description
str, list, or None

CAS number, list of CAS numbers, or None if not found or the SMILES cannot be parsed; as broad as get_cas_from_inchi

Examples:

>>> zpm = ZeroPM()
>>> "64-17-5" in zpm.get_cas_from_smiles("OCC")
True
Source code in src/provesid/zeropm.py
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
def get_cas_from_smiles(self, smiles):
    """
    Returns the CAS number from a SMILES string.
    This is done by converting the SMILES to InChI and then to CAS number.

    Parameters
    ----------
    smiles : str
        SMILES string

    Returns
    -------
    str, list, or None
        CAS number, list of CAS numbers, or None if not found or the
        SMILES cannot be parsed; as broad as
        [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> "64-17-5" in zpm.get_cas_from_smiles("OCC")
    True
    """
    try:
        mol = Chem.MolFromSmiles(smiles)
        if mol is None:
            logging.warning(f"Invalid SMILES: {smiles}")
            return None
        inchi = Chem.MolToInchi(mol)
    except Exception as e:
        logging.warning(f"Error converting SMILES to InChI for smiles: {smiles}. Error: {e}")
        return None

    return self.get_cas_from_inchi(inchi)
get_cas_from_name(name)

Returns the CAS number(s) associated with a chemical name.

This method performs an exact match search for the chemical name in the database. For fuzzy matching, use query_similar_name() first to get query_ids.

The answer is broad: it is every CAS number that reaches any of the structures the name resolved to, at any rank. For "formaldehyde" that is 31 numbers, methane's and carbon's among them. get_id_table_from_name shows where each came from.

Parameters:

Name Type Description Default
name str

Chemical name (exact match)

required

Returns:

Type Description
str, list, or None

CAS number, list of CAS numbers, or None if not found

Examples:

>>> zpm = ZeroPM()
>>> cas = zpm.get_cas_from_name("formaldehyde")
>>> len(cas), "50-00-0" in cas, "74-82-8" in cas
(31, True, True)
>>> zpm.get_cas_from_name("acetylsalicylic acid") is None
True
Source code in src/provesid/zeropm.py
 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
def get_cas_from_name(self, name):
    """
    Returns the CAS number(s) associated with a chemical name.

    This method performs an exact match search for the chemical name in the database.
    For fuzzy matching, use query_similar_name() first to get query_ids.

    The answer is broad: it is every CAS number that reaches any of the
    structures the name resolved to, at any rank. For
    ``"formaldehyde"`` that is 31 numbers, methane's and carbon's among
    them.
    [`get_id_table_from_name`][provesid.zeropm.ZeroPM.get_id_table_from_name]
    shows where each came from.

    Parameters
    ----------
    name : str
        Chemical name (exact match)

    Returns
    -------
    str, list, or None
        CAS number, list of CAS numbers, or None if not found

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> cas = zpm.get_cas_from_name("formaldehyde")
    >>> len(cas), "50-00-0" in cas, "74-82-8" in cas
    (31, True, True)
    >>> zpm.get_cas_from_name("acetylsalicylic acid") is None
    True
    """
    # Get query_id for this name
    query_id = self.query_name(name)
    if query_id is None:
        return None

    # Get inchi_ids for this query_id
    inchi_ids, _ = self.get_inchi_id(query_id)
    if not inchi_ids:
        return None

    # Collect all CAS numbers for all inchi_ids
    all_cas = set()
    for inchi_id in inchi_ids:
        # Get InChI for this inchi_id
        inchi, _ = self.get_inchi(inchi_id)
        if inchi:
            cas_result = self.get_cas_from_inchi(inchi)
            if cas_result:
                if isinstance(cas_result, list):
                    all_cas.update(cas_result)
                else:
                    all_cas.add(cas_result)

    if not all_cas:
        return None
    elif len(all_cas) == 1:
        return list(all_cas)[0]
    else:
        return sorted(list(all_cas))
get_cas_from_formula(formula)

Returns CAS numbers for chemicals matching a molecular formula.

Note: Molecular formulas are not unique identifiers - many different chemicals can have the same formula (isomers). This method returns all CAS numbers for chemicals matching the given formula.

Parameters:

Name Type Description Default
formula str

Molecular formula (e.g., "H2O", "C6H12O6", "CH2O")

required

Returns:

Type Description
list or None

List of CAS numbers matching the formula, or None if not found

Warning

This method can be slow as it needs to parse all InChI strings to extract molecular formulas. Consider caching results for frequently used formulas.

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_cas_from_formula("CH2O")  # Formaldehyde
['108-62-3', '1664-98-8', '30525-89-4', '3228-27-1', '50-00-0', '630-08-0', '63101-50-8']
Source code in src/provesid/zeropm.py
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
def get_cas_from_formula(self, formula):
    """
    Returns CAS numbers for chemicals matching a molecular formula.

    Note: Molecular formulas are not unique identifiers - many different chemicals
    can have the same formula (isomers). This method returns all CAS numbers
    for chemicals matching the given formula.

    Parameters
    ----------
    formula : str
        Molecular formula (e.g., "H2O", "C6H12O6", "CH2O")

    Returns
    -------
    list or None
        List of CAS numbers matching the formula, or None if not found

    Warning
    -------
    This method can be slow as it needs to parse all InChI strings to extract
    molecular formulas. Consider caching results for frequently used formulas.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_cas_from_formula("CH2O")  # Formaldehyde
    ['108-62-3', '1664-98-8', '30525-89-4', '3228-27-1', '50-00-0', '630-08-0', '63101-50-8']
    """
    # Normalize formula (basic normalization - can be improved)
    formula = formula.replace(" ", "")

    # Query all substances and check their formulas
    # InChI format: InChI=1S/CH2O/c1-2/h1H2
    # Formula is between the first two slashes
    self.cursor.execute("""
        SELECT DISTINCT s.inchi_id, s.inchi
        FROM substances s
        WHERE s.inchi IS NOT NULL
    """)

    matching_inchi_ids = []
    for inchi_id, inchi in self.cursor.fetchall():
        try:
            # Extract formula from InChI
            # Format: InChI=1S/FORMULA/...
            parts = inchi.split('/')
            if len(parts) >= 2:
                inchi_formula = parts[1]
                if inchi_formula == formula:
                    matching_inchi_ids.append(inchi_id)
        except Exception:
            continue

    if not matching_inchi_ids:
        return None

    # Get all CAS numbers for matching inchi_ids
    all_cas = set()
    for inchi_id in matching_inchi_ids:
        self.cursor.execute("""
            SELECT DISTINCT aq.query
            FROM api_results ar
            JOIN api_ready_query aq ON ar.query_id = aq.query_id
            WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
        """, (inchi_id,))
        cas_results = [row[0] for row in self.cursor.fetchall()]
        all_cas.update(cas_results)

    return sorted(list(all_cas)) if all_cas else None
batch_get_cas_from_smiles(smiles_list)

Get CAS numbers for multiple SMILES strings at once.

Parameters:

Name Type Description Default
smiles_list list of str

List of SMILES strings

required

Returns:

Type Description
dict

Dictionary mapping SMILES strings to CAS numbers (or None if not found)

Examples:

>>> zpm = ZeroPM()
>>> zpm.batch_get_cas_from_smiles(["CC", "not a smiles"])
{'CC': ['74-84-0', '9002-88-4'], 'not a smiles': None}
Source code in src/provesid/zeropm.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
def batch_get_cas_from_smiles(self, smiles_list):
    """
    Get CAS numbers for multiple SMILES strings at once.

    Parameters
    ----------
    smiles_list : list of str
        List of SMILES strings

    Returns
    -------
    dict
        Dictionary mapping SMILES strings to CAS numbers (or None if not found)

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.batch_get_cas_from_smiles(["CC", "not a smiles"])
    {'CC': ['74-84-0', '9002-88-4'], 'not a smiles': None}
    """
    return {smiles: self.get_cas_from_smiles(smiles) for smiles in smiles_list}
batch_get_cas_from_name(name_list)

Get CAS numbers for multiple chemical names at once.

Parameters:

Name Type Description Default
name_list list of str

List of chemical names (exact match)

required

Returns:

Type Description
dict

Dictionary mapping chemical names to CAS numbers (or None if not found)

Examples:

>>> zpm = ZeroPM()
>>> results = zpm.batch_get_cas_from_name(["Formaldehyde", "xyzzy"])
>>> "50-00-0" in results["Formaldehyde"], results["xyzzy"]
(True, None)
Source code in src/provesid/zeropm.py
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
def batch_get_cas_from_name(self, name_list):
    """
    Get CAS numbers for multiple chemical names at once.

    Parameters
    ----------
    name_list : list of str
        List of chemical names (exact match)

    Returns
    -------
    dict
        Dictionary mapping chemical names to CAS numbers (or None if not found)

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> results = zpm.batch_get_cas_from_name(["Formaldehyde", "xyzzy"])
    >>> "50-00-0" in results["Formaldehyde"], results["xyzzy"]
    (True, None)
    """
    return {name: self.get_cas_from_name(name) for name in name_list}
batch_get_cas_from_formula(formula_list)

Get CAS numbers for multiple molecular formulas at once.

Parameters:

Name Type Description Default
formula_list list of str

List of molecular formulas

required

Returns:

Type Description
dict

Dictionary mapping formulas to lists of CAS numbers

Examples:

>>> zpm = ZeroPM()
>>> results = zpm.batch_get_cas_from_formula(["CH2O", "C2H6O"])
>>> {formula: len(cas) for formula, cas in results.items()}
{'CH2O': 7, 'C2H6O': 10}
Source code in src/provesid/zeropm.py
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def batch_get_cas_from_formula(self, formula_list):
    """
    Get CAS numbers for multiple molecular formulas at once.

    Parameters
    ----------
    formula_list : list of str
        List of molecular formulas

    Returns
    -------
    dict
        Dictionary mapping formulas to lists of CAS numbers

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> results = zpm.batch_get_cas_from_formula(["CH2O", "C2H6O"])
    >>> {formula: len(cas) for formula, cas in results.items()}
    {'CH2O': 7, 'C2H6O': 10}
    """
    return {formula: self.get_cas_from_formula(formula) for formula in formula_list}
get_id_table_from_cas(cas)

Returns a pandas DataFrame containing all identifiers for a given CAS number.

This method retrieves all query_ids associated with the CAS number, then for each query_id, it retrieves all associated inchi_ids and their corresponding InChI and InChIKey values. Synonyms (chemical names) and data sources are also included.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

required

Returns:

Type Description
DataFrame

DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources' Returns None if the CAS number is not found in the database.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_cas("50-00-0")
>>> df[["cas", "query_id", "inchi_id", "rank", "inchikey", "zeropm_id"]]
       cas  query_id  inchi_id  rank                     inchikey  zeropm_id
0  50-00-0      8671     32227     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
>>> df.loc[0, "sources"]
'Chemical Data Reporting Inventory, Industrial ...'
Source code in src/provesid/zeropm.py
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
def get_id_table_from_cas(self, cas):
    """
    Returns a pandas DataFrame containing all identifiers for a given CAS number.

    This method retrieves all query_ids associated with the CAS number, then for each query_id,
    it retrieves all associated inchi_ids and their corresponding InChI and InChIKey values.
    Synonyms (chemical names) and data sources are also included.

    Parameters
    ----------
    cas : str
        CAS Registry Number

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
        Returns None if the CAS number is not found in the database.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_cas("50-00-0")
    >>> df[["cas", "query_id", "inchi_id", "rank", "inchikey", "zeropm_id"]]
           cas  query_id  inchi_id  rank                     inchikey  zeropm_id
    0  50-00-0      8671     32227     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
    >>> df.loc[0, "sources"]
    'Chemical Data Reporting Inventory, Industrial ...'
    """
    # Get all query_ids for this CAS (using fetchall in case there are multiple)
    self.cursor.execute("""
        SELECT query_id
        FROM api_ready_query
        WHERE query = ? AND type = 'CAS Registry Number'
    """, (cas,))
    query_ids = [row[0] for row in self.cursor.fetchall()]

    if not query_ids:
        self.logger.debug("CAS number %s not found in database", cas)
        return None

    # Get synonyms for this CAS
    synonyms = self.get_names(cas)
    synonyms_str = "; ".join(synonyms) if synonyms else ""

    # Get sources for this CAS
    self.cursor.execute("""
        SELECT DISTINCT s.source_name
        FROM inventory_summary issum
        JOIN inventories inv ON issum.inventory_id = inv.inventory_id
        JOIN sources s ON inv.source_id = s.source_id
        WHERE issum.query_id IN ({})
    """.format(','.join('?' * len(query_ids))), query_ids)
    sources = [row[0] for row in self.cursor.fetchall()]
    sources_str = "; ".join(sources) if sources else ""

    # Collect all data
    rows = []
    for query_id in query_ids:
        # Get all inchi_ids for this query_id
        inchi_ids, ranks = self.get_inchi_id(query_id)

        if not inchi_ids:
            # If no inchi_ids found, still add a row with the query_id
            rows.append({
                'cas': cas,
                'query_id': query_id,
                'inchi_id': None,
                'rank': None,
                'inchi': None,
                'inchikey': None,
                'zeropm_id': None,
                'synonyms': synonyms_str,
                'sources': sources_str
            })
        else:
            # For each inchi_id, get the inchi and inchikey
            for inchi_id, rank in zip(inchi_ids, ranks):
                inchi, inchikey = self.get_inchi(inchi_id)
                # Get zeropm_id for this inchi_id
                self.cursor.execute("""
                    SELECT zeropm_id
                    FROM zeropm_chemicals
                    WHERE inchi_id = ?
                """, (inchi_id,))
                zeropm_result = self.cursor.fetchone()
                zeropm_id = zeropm_result[0] if zeropm_result else None

                rows.append({
                    'cas': cas,
                    'query_id': query_id,
                    'inchi_id': inchi_id,
                    'rank': rank,
                    'inchi': inchi,
                    'inchikey': inchikey,
                    'zeropm_id': zeropm_id,
                    'synonyms': synonyms_str,
                    'sources': sources_str
                })

    # Create DataFrame
    df = pd.DataFrame(rows)
    # Convert zeropm_id to nullable integer type
    if not df.empty and 'zeropm_id' in df.columns:
        df['zeropm_id'] = df['zeropm_id'].astype('Int64')
    return df
get_id_table_from_zeropm_id(zeropm_id)

Returns a pandas DataFrame containing all identifiers for a given zeropm_id.

This method retrieves the inchi_id associated with the zeropm_id, then finds all query_ids (CAS numbers) linked to that inchi_id and builds a comprehensive table with InChI, InChIKey, synonyms, and data sources.

Parameters:

Name Type Description Default
zeropm_id int

ZeroPM identifier

required

Returns:

Type Description
DataFrame

DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources' Returns None if the zeropm_id is not found in the database.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_zeropm_id(3224)   # formaldehyde
>>> df[["cas", "rank"]].sort_values(["rank", "cas"]).values.tolist()
[['30525-89-4', 1], ['50-00-0', 1], ['108-62-3', 2], ['1664-98-8', 2], ['630-08-0', 2], ['63101-50-8', 2]]
Source code in src/provesid/zeropm.py
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
def get_id_table_from_zeropm_id(self, zeropm_id):
    """
    Returns a pandas DataFrame containing all identifiers for a given zeropm_id.

    This method retrieves the inchi_id associated with the zeropm_id, then finds all
    query_ids (CAS numbers) linked to that inchi_id and builds a comprehensive table
    with InChI, InChIKey, synonyms, and data sources.

    Parameters
    ----------
    zeropm_id : int
        ZeroPM identifier

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
        Returns None if the zeropm_id is not found in the database.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_zeropm_id(3224)   # formaldehyde
    >>> df[["cas", "rank"]].sort_values(["rank", "cas"]).values.tolist()
    [['30525-89-4', 1], ['50-00-0', 1], ['108-62-3', 2], ['1664-98-8', 2], ['630-08-0', 2], ['63101-50-8', 2]]
    """
    # Get inchi_id for this zeropm_id
    self.cursor.execute("""
        SELECT inchi_id
        FROM zeropm_chemicals
        WHERE zeropm_id = ?
    """, (zeropm_id,))
    result = self.cursor.fetchone()

    if not result:
        self.logger.debug("zeropm_id %s not found in database", zeropm_id)
        return None

    inchi_id = result[0]

    # Get InChI and InChIKey
    inchi, inchikey = self.get_inchi(inchi_id)

    # Get all query_ids (CAS numbers) associated with this inchi_id.
    # DISTINCT because api_results can hold the same (query, structure,
    # rank) more than once, differing only in columns not read here.
    self.cursor.execute("""
        SELECT DISTINCT ar.query_id, ar.rank, aq.query
        FROM api_results ar
        JOIN api_ready_query aq ON ar.query_id = aq.query_id
        WHERE ar.inchi_id = ? AND aq.type = 'CAS Registry Number'
    """, (inchi_id,))
    query_results = self.cursor.fetchall()

    if not query_results:
        logging.warning(f"No CAS numbers found for zeropm_id {zeropm_id}")
        return None

    # Collect all data
    rows = []
    for query_id, rank, cas in query_results:
        # Get synonyms for this CAS
        synonyms = self.get_names(cas)
        synonyms_str = "; ".join(synonyms) if synonyms else ""

        # Get sources for this query_id
        self.cursor.execute("""
            SELECT DISTINCT s.source_name
            FROM inventory_summary issum
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            WHERE issum.query_id = ?
        """, (query_id,))
        sources = [row[0] for row in self.cursor.fetchall()]
        sources_str = "; ".join(sources) if sources else ""

        rows.append({
            'cas': cas,
            'query_id': query_id,
            'inchi_id': inchi_id,
            'rank': rank,
            'inchi': inchi,
            'inchikey': inchikey,
            'zeropm_id': zeropm_id,
            'synonyms': synonyms_str,
            'sources': sources_str
        })

    # Create DataFrame
    df = pd.DataFrame(rows)
    # Convert zeropm_id to nullable integer type
    if not df.empty and 'zeropm_id' in df.columns:
        df['zeropm_id'] = df['zeropm_id'].astype('Int64')
    return df
batch_get_id_table_from_cas(cas_list)

Returns a pandas DataFrame containing all identifiers for a list of CAS numbers.

This method calls get_id_table_from_cas for each CAS number in the list and combines the results into a single DataFrame. CAS numbers not found in the database are logged but skipped in the output.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

required

Returns:

Type Description
DataFrame

Combined DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources' Returns an empty DataFrame if no CAS numbers are found in the database.

Examples:

>>> zpm = ZeroPM()
>>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]  # formaldehyde, aspirin, ethanol
>>> df = zpm.batch_get_id_table_from_cas(cas_numbers)
>>> df[["cas", "rank", "inchikey", "zeropm_id"]]
       cas  rank                     inchikey  zeropm_id
0  50-00-0     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
1  50-78-2     1  BSYNRYMUTXBXSQ-UHFFFAOYSA-N       4267
2  50-78-2     2  BSYNRYMUTXBXSQ-UHFFFAOYSA-M       <NA>
3  50-78-2     3  XDZMPRGFOOFSBL-UHFFFAOYSA-N       6402
4  50-78-2     4  BSYNRYMUTXBXSQ-FIBGUPNXSA-N       <NA>
5  64-17-5     1  LFQSCWFLJHTTHZ-UHFFFAOYSA-N       1452
Source code in src/provesid/zeropm.py
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
def batch_get_id_table_from_cas(self, cas_list):
    """
    Returns a pandas DataFrame containing all identifiers for a list of CAS numbers.

    This method calls get_id_table_from_cas for each CAS number in the list and
    combines the results into a single DataFrame. CAS numbers not found in the
    database are logged but skipped in the output.

    Parameters
    ----------
    cas_list : list of str
        List of CAS Registry Numbers

    Returns
    -------
    pandas.DataFrame
        Combined DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
        Returns an empty DataFrame if no CAS numbers are found in the database.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]  # formaldehyde, aspirin, ethanol
    >>> df = zpm.batch_get_id_table_from_cas(cas_numbers)
    >>> df[["cas", "rank", "inchikey", "zeropm_id"]]
           cas  rank                     inchikey  zeropm_id
    0  50-00-0     1  WSFSSNUMVMOOMR-UHFFFAOYSA-N       3224
    1  50-78-2     1  BSYNRYMUTXBXSQ-UHFFFAOYSA-N       4267
    2  50-78-2     2  BSYNRYMUTXBXSQ-UHFFFAOYSA-M       <NA>
    3  50-78-2     3  XDZMPRGFOOFSBL-UHFFFAOYSA-N       6402
    4  50-78-2     4  BSYNRYMUTXBXSQ-FIBGUPNXSA-N       <NA>
    5  64-17-5     1  LFQSCWFLJHTTHZ-UHFFFAOYSA-N       1452
    """
    if not cas_list:
        logging.warning("Empty CAS list provided")
        return pd.DataFrame(columns=['cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'])

    # Collect DataFrames for each CAS
    dataframes = []
    for cas in cas_list:
        df = self.get_id_table_from_cas(cas)
        if df is not None:
            dataframes.append(df)

    # Combine all DataFrames
    if not dataframes:
        logging.warning("None of the provided CAS numbers were found in the database")
        return pd.DataFrame(columns=['cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'])

    # Concatenate all DataFrames and reset index
    combined_df = pd.concat(dataframes, ignore_index=True)
    return combined_df
batch_get_id_table_from_cas_filtered(cas_list, rank=None, have_zeropm_id=None)

Returns a filtered pandas DataFrame containing identifiers for a list of CAS numbers.

This method calls batch_get_id_table_from_cas and applies optional filters to the results.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

required
rank int

If specified, only include rows with this rank value (e.g., rank=1 for top results) If None, no rank filtering is applied (default: None)

None
have_zeropm_id bool

If True, only include rows where zeropm_id is not None If False, only include rows where zeropm_id is None If None, no zeropm_id filtering is applied (default: None)

None

Returns:

Type Description
DataFrame

Filtered DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources' Returns an empty DataFrame if no CAS numbers match the filters.

Examples:

>>> zpm = ZeroPM()
>>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]
>>> # Get only rank=1 results with zeropm_id
>>> df = zpm.batch_get_id_table_from_cas_filtered(cas_numbers, rank=1, have_zeropm_id=True)
>>> df[["cas", "rank", "zeropm_id"]]
       cas  rank  zeropm_id
0  50-00-0     1       3224
1  50-78-2     1       4267
2  64-17-5     1       1452
See Also

batch_get_id_table_from_cas : Returns all results without filtering

Source code in src/provesid/zeropm.py
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
def batch_get_id_table_from_cas_filtered(self, cas_list, rank=None, have_zeropm_id=None):
    """
    Returns a filtered pandas DataFrame containing identifiers for a list of CAS numbers.

    This method calls batch_get_id_table_from_cas and applies optional filters to the results.

    Parameters
    ----------
    cas_list : list of str
        List of CAS Registry Numbers
    rank : int, optional
        If specified, only include rows with this rank value (e.g., rank=1 for top results)
        If None, no rank filtering is applied (default: None)
    have_zeropm_id : bool, optional
        If True, only include rows where zeropm_id is not None
        If False, only include rows where zeropm_id is None
        If None, no zeropm_id filtering is applied (default: None)

    Returns
    -------
    pandas.DataFrame
        Filtered DataFrame with columns: 'cas', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'zeropm_id', 'synonyms', 'sources'
        Returns an empty DataFrame if no CAS numbers match the filters.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> cas_numbers = ["50-00-0", "50-78-2", "64-17-5"]
    >>> # Get only rank=1 results with zeropm_id
    >>> df = zpm.batch_get_id_table_from_cas_filtered(cas_numbers, rank=1, have_zeropm_id=True)
    >>> df[["cas", "rank", "zeropm_id"]]
           cas  rank  zeropm_id
    0  50-00-0     1       3224
    1  50-78-2     1       4267
    2  64-17-5     1       1452

    See Also
    --------
    batch_get_id_table_from_cas : Returns all results without filtering
    """
    # Get the full id table
    df = self.batch_get_id_table_from_cas(cas_list)

    # Return empty if no results
    if df.empty:
        return df

    # Apply rank filter if specified
    if rank is not None:
        df = df[df['rank'] == rank]

    # Apply zeropm_id filter if specified
    if have_zeropm_id is not None:
        if have_zeropm_id:
            df = df[df['zeropm_id'].notna()]
        else:
            df = df[df['zeropm_id'].isna()]

    # Reset index
    df = df.reset_index(drop=True)

    return df
get_id_table_from_inchi(inchi)

Returns a pandas DataFrame containing all identifiers for a given InChI.

This method retrieves the inchi_id for the InChI, then finds all associated query_ids and their CAS numbers. It also includes synonyms and sources.

About 5% of ZeroPM's substances are stored under a non-standard InChI (InChI=1/...). The InChI is matched as a string first; when that misses, its InChIKey is computed and looked up with either flag, as in get_id_table_from_inchikey. So a standard InChI finds a substance stored only under a non-standard one whose key differs by the flag alone: 536 of the 816 such substances that no standard InChI matched as a string. The other 280 have relative stereo (/s2), which a standard InChI cannot express.

Parameters:

Name Type Description Default
inchi str

InChI string, standard or not

required

Returns:

Type Description
DataFrame

DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms' Returns None if the InChI is not found in the database. One row per query --- CAS number or name --- that reaches the structure, best rank first; cas is NaN for a name query. The synonyms are those of the first CAS number, on every row. inchi and inchikey are as ZeroPM stores them.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
>>> df.dropna(subset=["cas"])[["query_id", "rank", "cas"]].head(2)
   query_id  rank         cas
0      8671     1     50-00-0
3     35725     1  30525-89-4

trans-1,4-Cyclohexanediol is stored only under a non-standard InChI:

>>> df = zpm.get_id_table_from_inchi(
...     "InChI=1S/C6H12O2/c7-5-1-2-6(8)4-3-5/h5-8H,1-4H2/t5-,6-")
>>> df["cas"].dropna().tolist(), df["inchikey"].unique().tolist()
(['6995-79-5'], ['VKONPUDBRVKQLM-IZLXSQMJNA-N'])
Source code in src/provesid/zeropm.py
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def get_id_table_from_inchi(self, inchi):
    """
    Returns a pandas DataFrame containing all identifiers for a given InChI.

    This method retrieves the inchi_id for the InChI, then finds all associated
    query_ids and their CAS numbers. It also includes synonyms and sources.

    About 5% of ZeroPM's substances are stored under a non-standard InChI
    (``InChI=1/...``). The InChI is matched as a string first; when that
    misses, its InChIKey is computed and looked up with either flag, as
    in
    [`get_id_table_from_inchikey`][provesid.zeropm.ZeroPM.get_id_table_from_inchikey].
    So a standard InChI finds a substance stored only under a
    non-standard one whose key differs by the flag alone: 536 of the
    816 such substances that no standard InChI matched as a string. The
    other 280 have relative stereo (``/s2``), which a standard InChI
    cannot express.

    Parameters
    ----------
    inchi : str
        InChI string, standard or not

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
        Returns None if the InChI is not found in the database.
        One row per query --- CAS number or name --- that reaches the
        structure, best rank first; ``cas`` is NaN for a name query. The
        synonyms are those of the first CAS number, on every row.
        ``inchi`` and ``inchikey`` are as ZeroPM stores them.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_inchi("InChI=1S/CH2O/c1-2/h1H2")
    >>> df.dropna(subset=["cas"])[["query_id", "rank", "cas"]].head(2)
       query_id  rank         cas
    0      8671     1     50-00-0
    3     35725     1  30525-89-4

    trans-1,4-Cyclohexanediol is stored only under a non-standard InChI:

    >>> df = zpm.get_id_table_from_inchi(
    ...     "InChI=1S/C6H12O2/c7-5-1-2-6(8)4-3-5/h5-8H,1-4H2/t5-,6-")
    >>> df["cas"].dropna().tolist(), df["inchikey"].unique().tolist()
    (['6995-79-5'], ['VKONPUDBRVKQLM-IZLXSQMJNA-N'])
    """
    # Get inchi_id, and the InChI and InChIKey as stored
    result = self._find_substance_by_inchi(inchi)

    if not result:
        self.logger.debug("InChI %s not found in database", inchi)
        return None

    inchi_id, inchi, inchikey = result

    # Get all query_ids and ranks for this inchi_id
    self.cursor.execute("""
        SELECT DISTINCT ar.query_id, ar.rank
        FROM api_results ar
        WHERE ar.inchi_id = ?
        ORDER BY ar.rank
    """, (inchi_id,))
    query_results = self.cursor.fetchall()

    if not query_results:
        # If no query_ids found, still return basic info
        return pd.DataFrame([{
            'inchi': inchi,
            'inchikey': inchikey,
            'inchi_id': inchi_id,
            'query_id': None,
            'rank': None,
            'cas': None,
            'synonyms': '',
            'sources': ''
        }])

    # Get CAS numbers for these query_ids
    rows = []
    primary_cas = None
    query_ids_list = [q[0] for q in query_results]

    # Get sources for all query_ids at once
    if query_ids_list:
        placeholders = ','.join('?' * len(query_ids_list))
        self.cursor.execute(f"""
            SELECT DISTINCT s.source_name
            FROM inventory_summary issum
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            WHERE issum.query_id IN ({placeholders})
        """, query_ids_list)
        sources = [row[0] for row in self.cursor.fetchall()]
        sources_str = "; ".join(sources) if sources else ""
    else:
        sources_str = ""

    for query_id, rank in query_results:
        # Get CAS number for this query_id
        self.cursor.execute("""
            SELECT query
            FROM api_ready_query
            WHERE query_id = ? AND type = 'CAS Registry Number'
        """, (query_id,))
        cas_result = self.cursor.fetchone()
        cas = cas_result[0] if cas_result else None

        # Use first CAS as primary for synonyms
        if cas and primary_cas is None:
            primary_cas = cas

        rows.append({
            'inchi': inchi,
            'inchikey': inchikey,
            'inchi_id': inchi_id,
            'query_id': query_id,
            'rank': rank,
            'cas': cas,
            'sources': sources_str
        })

    # Get synonyms from primary CAS
    synonyms_str = ''
    if primary_cas:
        synonyms = self.get_names(primary_cas)
        synonyms_str = "; ".join(synonyms) if synonyms else ""

    # Add synonyms to all rows
    for row in rows:
        row['synonyms'] = synonyms_str

    return pd.DataFrame(rows)
batch_get_id_table_from_inchi(inchi_list)

Returns a pandas DataFrame containing all identifiers for a list of InChI strings.

Parameters:

Name Type Description Default
inchi_list list of str

List of InChI strings

required

Returns:

Type Description
DataFrame

Combined DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms' Returns an empty DataFrame if no InChIs are found in the database. InChIs not found are left out.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.batch_get_id_table_from_inchi(
...     ["InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", "InChI=1S/Xx"])
>>> df["inchikey"].unique().tolist(), len(df)
(['LFQSCWFLJHTTHZ-UHFFFAOYSA-N'], 43)
Source code in src/provesid/zeropm.py
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
def batch_get_id_table_from_inchi(self, inchi_list):
    """
    Returns a pandas DataFrame containing all identifiers for a list of InChI strings.

    Parameters
    ----------
    inchi_list : list of str
        List of InChI strings

    Returns
    -------
    pandas.DataFrame
        Combined DataFrame with columns: 'inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
        Returns an empty DataFrame if no InChIs are found in the database.
        InChIs not found are left out.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.batch_get_id_table_from_inchi(
    ...     ["InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", "InChI=1S/Xx"])
    >>> df["inchikey"].unique().tolist(), len(df)
    (['LFQSCWFLJHTTHZ-UHFFFAOYSA-N'], 43)
    """
    if not inchi_list:
        logging.warning("Empty InChI list provided")
        return pd.DataFrame(columns=['inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

    dataframes = []
    for inchi in inchi_list:
        df = self.get_id_table_from_inchi(inchi)
        if df is not None:
            dataframes.append(df)

    if not dataframes:
        logging.warning("None of the provided InChIs were found in the database")
        return pd.DataFrame(columns=['inchi', 'inchikey', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

    combined_df = pd.concat(dataframes, ignore_index=True)
    return combined_df
get_id_table_from_inchikey(inchikey)

Returns a pandas DataFrame containing all identifiers for a given InChIKey.

This method retrieves the inchi_id for the InChIKey, then finds all associated query_ids and their CAS numbers. It also includes synonyms and sources.

About 5% of ZeroPM's substances are stored under a non-standard InChI and InChIKey. A key is also looked up with its other standard flag (...SA-N / ...NA-N), so a standard key finds those rows where only the flag differs; the key given is preferred when both exist.

Parameters:

Name Type Description Default
inchikey str

InChIKey string, standard or not

required

Returns:

Type Description
DataFrame

DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms' Returns None if the InChIKey is not found in the database. Shaped as get_id_table_from_inchi describes.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_inchikey("WSFSSNUMVMOOMR-UHFFFAOYSA-N")
>>> df.dropna(subset=["cas"])[["rank", "cas"]].head(2)
   rank         cas
0     1     50-00-0
3     1  30525-89-4
Source code in src/provesid/zeropm.py
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
def get_id_table_from_inchikey(self, inchikey):
    """
    Returns a pandas DataFrame containing all identifiers for a given InChIKey.

    This method retrieves the inchi_id for the InChIKey, then finds all associated
    query_ids and their CAS numbers. It also includes synonyms and sources.

    About 5% of ZeroPM's substances are stored under a non-standard InChI
    and InChIKey. A key is also looked up with its other standard flag
    (``...SA-N`` / ``...NA-N``), so a standard key finds those rows where
    only the flag differs; the key given is preferred when both exist.

    Parameters
    ----------
    inchikey : str
        InChIKey string, standard or not

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
        Returns None if the InChIKey is not found in the database.
        Shaped as
        [`get_id_table_from_inchi`][provesid.zeropm.ZeroPM.get_id_table_from_inchi]
        describes.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_inchikey("WSFSSNUMVMOOMR-UHFFFAOYSA-N")
    >>> df.dropna(subset=["cas"])[["rank", "cas"]].head(2)
       rank         cas
    0     1     50-00-0
    3     1  30525-89-4
    """
    # Get inchi_id and inchi from InChIKey, in either flag spelling
    result = self._find_substance_by_inchikey(inchikey)

    if not result:
        self.logger.debug("InChIKey %s not found in database", inchikey)
        return None

    inchi_id, inchi, _ = result

    # Get all query_ids and ranks for this inchi_id
    self.cursor.execute("""
        SELECT DISTINCT ar.query_id, ar.rank
        FROM api_results ar
        WHERE ar.inchi_id = ?
        ORDER BY ar.rank
    """, (inchi_id,))
    query_results = self.cursor.fetchall()

    if not query_results:
        # If no query_ids found, still return basic info
        return pd.DataFrame([{
            'inchikey': inchikey,
            'inchi': inchi,
            'inchi_id': inchi_id,
            'query_id': None,
            'rank': None,
            'cas': None,
            'synonyms': '',
            'sources': ''
        }])

    # Get CAS numbers for these query_ids
    rows = []
    primary_cas = None
    query_ids_list = [q[0] for q in query_results]

    # Get sources for all query_ids at once
    if query_ids_list:
        placeholders = ','.join('?' * len(query_ids_list))
        self.cursor.execute(f"""
            SELECT DISTINCT s.source_name
            FROM inventory_summary issum
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            WHERE issum.query_id IN ({placeholders})
        """, query_ids_list)
        sources = [row[0] for row in self.cursor.fetchall()]
        sources_str = "; ".join(sources) if sources else ""
    else:
        sources_str = ""

    for query_id, rank in query_results:
        # Get CAS number for this query_id
        self.cursor.execute("""
            SELECT query
            FROM api_ready_query
            WHERE query_id = ? AND type = 'CAS Registry Number'
        """, (query_id,))
        cas_result = self.cursor.fetchone()
        cas = cas_result[0] if cas_result else None

        # Use first CAS as primary for synonyms
        if cas and primary_cas is None:
            primary_cas = cas

        rows.append({
            'inchikey': inchikey,
            'inchi': inchi,
            'inchi_id': inchi_id,
            'query_id': query_id,
            'rank': rank,
            'cas': cas,
            'sources': sources_str
        })

    # Get synonyms from primary CAS
    synonyms_str = ''
    if primary_cas:
        synonyms = self.get_names(primary_cas)
        synonyms_str = "; ".join(synonyms) if synonyms else ""

    # Add synonyms to all rows
    for row in rows:
        row['synonyms'] = synonyms_str

    return pd.DataFrame(rows)
batch_get_id_table_from_inchikey(inchikey_list)

Returns a pandas DataFrame containing all identifiers for a list of InChIKey strings.

Parameters:

Name Type Description Default
inchikey_list list of str

List of InChIKey strings

required

Returns:

Type Description
DataFrame

Combined DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms' Returns an empty DataFrame if no InChIKeys are found in the database. InChIKeys not found are left out.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.batch_get_id_table_from_inchikey(
...     ["LFQSCWFLJHTTHZ-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
>>> df["inchikey"].unique().tolist()
['LFQSCWFLJHTTHZ-UHFFFAOYSA-N']
Source code in src/provesid/zeropm.py
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
def batch_get_id_table_from_inchikey(self, inchikey_list):
    """
    Returns a pandas DataFrame containing all identifiers for a list of InChIKey strings.

    Parameters
    ----------
    inchikey_list : list of str
        List of InChIKey strings

    Returns
    -------
    pandas.DataFrame
        Combined DataFrame with columns: 'inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'sources', 'synonyms'
        Returns an empty DataFrame if no InChIKeys are found in the database.
        InChIKeys not found are left out.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.batch_get_id_table_from_inchikey(
    ...     ["LFQSCWFLJHTTHZ-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
    >>> df["inchikey"].unique().tolist()
    ['LFQSCWFLJHTTHZ-UHFFFAOYSA-N']
    """
    if not inchikey_list:
        logging.warning("Empty InChIKey list provided")
        return pd.DataFrame(columns=['inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

    dataframes = []
    for inchikey in inchikey_list:
        df = self.get_id_table_from_inchikey(inchikey)
        if df is not None:
            dataframes.append(df)

    if not dataframes:
        logging.warning("None of the provided InChIKeys were found in the database")
        return pd.DataFrame(columns=['inchikey', 'inchi', 'inchi_id', 'query_id', 'rank', 'cas', 'synonyms', 'sources'])

    combined_df = pd.concat(dataframes, ignore_index=True)
    return combined_df
get_id_table_from_name(name)

Returns a pandas DataFrame containing all identifiers for a given chemical name.

This method searches for an exact match of the chemical name, then retrieves all associated inchi_ids and their corresponding InChI, InChIKey, CAS numbers, and sources.

Parameters:

Name Type Description Default
name str

Chemical name (exact match)

required

Returns:

Type Description
DataFrame

DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources' Returns None if the name is not found in the database. One row per (structure, CAS number): each structure the name resolved to, at every rank, with every CAS number that reaches that structure.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.get_id_table_from_name("Formaldehyde")
>>> df.groupby("rank")["inchikey"].first().to_dict()
{1: 'WSFSSNUMVMOOMR-UHFFFAOYSA-N', 2: 'VNWKTOKETHGBQD-UHFFFAOYSA-N', 3: 'MDYZKJNTKZIUSK-UHFFFAOYSA-N', 4: 'SYCNHFWYTQQMNG-UHFFFAOYSA-N'}
>>> df[df["rank"] == 1]["cas"].tolist()[:2]
['50-00-0', '30525-89-4']
Source code in src/provesid/zeropm.py
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
def get_id_table_from_name(self, name):
    """
    Returns a pandas DataFrame containing all identifiers for a given chemical name.

    This method searches for an exact match of the chemical name, then retrieves all
    associated inchi_ids and their corresponding InChI, InChIKey, CAS numbers, and sources.

    Parameters
    ----------
    name : str
        Chemical name (exact match)

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'
        Returns None if the name is not found in the database.
        One row per (structure, CAS number): each structure the name
        resolved to, at every rank, with every CAS number that reaches
        that structure.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.get_id_table_from_name("Formaldehyde")
    >>> df.groupby("rank")["inchikey"].first().to_dict()
    {1: 'WSFSSNUMVMOOMR-UHFFFAOYSA-N', 2: 'VNWKTOKETHGBQD-UHFFFAOYSA-N', 3: 'MDYZKJNTKZIUSK-UHFFFAOYSA-N', 4: 'SYCNHFWYTQQMNG-UHFFFAOYSA-N'}
    >>> df[df["rank"] == 1]["cas"].tolist()[:2]
    ['50-00-0', '30525-89-4']
    """
    # Get query_id for this name
    query_id = self.query_name(name)

    if query_id is None:
        self.logger.debug("Chemical name '%s' not found in database", name)
        return None

    return self._id_table_for_query_id(query_id, name)
batch_get_id_table_from_name(name_list)

Returns a pandas DataFrame containing all identifiers for a list of chemical names.

Parameters:

Name Type Description Default
name_list list of str

List of chemical names (exact match)

required

Returns:

Type Description
DataFrame

Combined DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources' Returns an empty DataFrame if no names are found in the database. Names not found are left out.

Examples:

>>> zpm = ZeroPM()
>>> df = zpm.batch_get_id_table_from_name(["Formaldehyde", "ethanol", "xyzzy"])
>>> df[df["rank"] == 1].groupby("name")["cas"].first().to_dict()
{'Formaldehyde': '50-00-0', 'ethanol': '64-17-5'}
Source code in src/provesid/zeropm.py
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
def batch_get_id_table_from_name(self, name_list):
    """
    Returns a pandas DataFrame containing all identifiers for a list of chemical names.

    Parameters
    ----------
    name_list : list of str
        List of chemical names (exact match)

    Returns
    -------
    pandas.DataFrame
        Combined DataFrame with columns: 'name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'
        Returns an empty DataFrame if no names are found in the database.
        Names not found are left out.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> df = zpm.batch_get_id_table_from_name(["Formaldehyde", "ethanol", "xyzzy"])
    >>> df[df["rank"] == 1].groupby("name")["cas"].first().to_dict()
    {'Formaldehyde': '50-00-0', 'ethanol': '64-17-5'}
    """
    if not name_list:
        logging.warning("Empty name list provided")
        return pd.DataFrame(columns=['name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'])

    dataframes = []
    for name in name_list:
        df = self.get_id_table_from_name(name)
        if df is not None:
            dataframes.append(df)

    if not dataframes:
        logging.warning("None of the provided names were found in the database")
        return pd.DataFrame(columns=['name', 'query_id', 'inchi_id', 'rank', 'inchi', 'inchikey', 'cas', 'sources'])

    combined_df = pd.concat(dataframes, ignore_index=True)
    return combined_df
create_indexes(force=False)

Create indexes on frequently queried columns to improve performance. Indexes are created on query, type, query_id, inchi_id, inchi, and inchikey.

Parameters:

Name Type Description Default
force bool

If True, drop existing indexes before creating new ones (default: False)

False

Returns:

Type Description
dict

Dictionary with index names as keys and status ('created', 'exists', 'error') as values. Without force every index reads 'exists', whether or not it was just built: CREATE INDEX IF NOT EXISTS does not say.

Notes

This writes to the database file. An index that already exists under its name is left alone, so a second call does nothing.

Examples:

>>> zpm = ZeroPM()
>>> zpm.create_indexes()["idx_query"]
'exists'
Source code in src/provesid/zeropm.py
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
def create_indexes(self, force=False):
    """
    Create indexes on frequently queried columns to improve performance.
    Indexes are created on query, type, query_id, inchi_id, inchi, and inchikey.

    Parameters
    ----------
    force : bool, optional
        If True, drop existing indexes before creating new ones (default: False)

    Returns
    -------
    dict
        Dictionary with index names as keys and status ('created', 'exists', 'error') as values.
        Without ``force`` every index reads ``'exists'``, whether or not
        it was just built: ``CREATE INDEX IF NOT EXISTS`` does not say.

    Notes
    -----
    This writes to the database file. An index that already exists under
    its name is left alone, so a second call does nothing.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.create_indexes()["idx_query"]     # doctest: +SKIP
    'exists'
    """
    indexes = {
        'idx_query': 'CREATE INDEX IF NOT EXISTS idx_query ON api_ready_query(query)',
        'idx_type': 'CREATE INDEX IF NOT EXISTS idx_type ON api_ready_query(type)',
        'idx_query_id_results': 'CREATE INDEX IF NOT EXISTS idx_query_id_results ON api_results(query_id)',
        'idx_inchi_id_results': 'CREATE INDEX IF NOT EXISTS idx_inchi_id_results ON api_results(inchi_id)',
        'idx_inchi': 'CREATE INDEX IF NOT EXISTS idx_inchi ON substances(inchi)',
        'idx_inchikey': 'CREATE INDEX IF NOT EXISTS idx_inchikey ON substances(inchikey)',
        'idx_inventory_query': 'CREATE INDEX IF NOT EXISTS idx_inventory_query ON inventory_summary(query_id)',
        'idx_inventory_id': 'CREATE INDEX IF NOT EXISTS idx_inventory_id ON inventories(inventory_id)',
    }

    results = {}

    if force:
        # Drop existing indexes
        for idx_name in indexes.keys():
            try:
                self.cursor.execute(f"DROP INDEX IF EXISTS {idx_name}")
            except Exception as e:
                logging.warning(f"Could not drop index {idx_name}: {e}")

    # Create indexes
    for idx_name, sql in indexes.items():
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            results[idx_name] = 'created' if force else 'exists'
        except Exception as e:
            logging.error(f"Error creating index {idx_name}: {e}")
            results[idx_name] = 'error'

    return results
batch_query_cas(cas_list)

Query multiple CAS numbers at once.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

required

Returns:

Type Description
dict

Dictionary mapping CAS numbers to query_ids (or None if not found)

Examples:

>>> zpm = ZeroPM()
>>> zpm.batch_query_cas(["50-00-0", "64-17-5", "0-00-0"])
{'50-00-0': 8671, '64-17-5': 3904, '0-00-0': None}
Source code in src/provesid/zeropm.py
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
def batch_query_cas(self, cas_list):
    """
    Query multiple CAS numbers at once.

    Parameters
    ----------
    cas_list : list of str
        List of CAS Registry Numbers

    Returns
    -------
    dict
        Dictionary mapping CAS numbers to query_ids (or None if not found)

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.batch_query_cas(["50-00-0", "64-17-5", "0-00-0"])
    {'50-00-0': 8671, '64-17-5': 3904, '0-00-0': None}
    """
    if not cas_list:
        return {}

    # Use parameterized query with IN clause
    placeholders = ','.join('?' * len(cas_list))
    self.cursor.execute(f"""
        SELECT query, query_id
        FROM api_ready_query
        WHERE query IN ({placeholders}) AND type = 'CAS Registry Number'
    """, cas_list)

    results = {row[0]: row[1] for row in self.cursor.fetchall()}

    # Add None for CAS numbers not found
    return {cas: results.get(cas) for cas in cas_list}
batch_get_smiles_from_cas(cas_list)

Get SMILES for multiple CAS numbers at once.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

required

Returns:

Type Description
dict

Dictionary mapping CAS numbers to SMILES strings (or None if not found)

Examples:

>>> zpm = ZeroPM()
>>> zpm.batch_get_smiles_from_cas(["50-00-0", "64-17-5", "0-00-0"])
{'50-00-0': 'C=O', '64-17-5': 'CCO', '0-00-0': None}
Source code in src/provesid/zeropm.py
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
def batch_get_smiles_from_cas(self, cas_list):
    """
    Get SMILES for multiple CAS numbers at once.

    Parameters
    ----------
    cas_list : list of str
        List of CAS Registry Numbers

    Returns
    -------
    dict
        Dictionary mapping CAS numbers to SMILES strings (or None if not found)

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.batch_get_smiles_from_cas(["50-00-0", "64-17-5", "0-00-0"])
    {'50-00-0': 'C=O', '64-17-5': 'CCO', '0-00-0': None}
    """
    query_ids = self.batch_query_cas(cas_list)
    results = {}

    for cas, query_id in query_ids.items():
        if query_id is None:
            results[cas] = None
        else:
            results[cas] = self.get_smiles_from_cas(cas)

    return results
batch_get_names(cas_list)

Get all names for multiple CAS numbers at once.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

required

Returns:

Type Description
dict

Dictionary mapping CAS numbers to lists of names, as get_names returns them (empty when not found)

Examples:

>>> zpm = ZeroPM()
>>> names = zpm.batch_get_names(["64-17-5", "0-00-0"])
>>> "Ethanol" in names["64-17-5"], names["0-00-0"]
(True, [])
Source code in src/provesid/zeropm.py
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
def batch_get_names(self, cas_list):
    """
    Get all names for multiple CAS numbers at once.

    Parameters
    ----------
    cas_list : list of str
        List of CAS Registry Numbers

    Returns
    -------
    dict
        Dictionary mapping CAS numbers to lists of names, as
        [`get_names`][provesid.zeropm.ZeroPM.get_names] returns them (empty
        when not found)

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> names = zpm.batch_get_names(["64-17-5", "0-00-0"])
    >>> "Ethanol" in names["64-17-5"], names["0-00-0"]
    (True, [])
    """
    return {cas: self.get_names(cas) for cas in cas_list}
batch_get_cas_from_inchikey(inchikey_list)

Get CAS numbers for multiple InChIKeys at once.

Parameters:

Name Type Description Default
inchikey_list list of str

List of InChIKey strings

required

Returns:

Type Description
dict

Dictionary mapping InChIKeys to CAS numbers (or None if not found); one number as a string, several as a list, as broad as get_cas_from_inchi. Each key is looked up with either flag, as in get_cas_from_inchikey.

Examples:

>>> zpm = ZeroPM()
>>> found = zpm.batch_get_cas_from_inchikey(
...     ["WSFSSNUMVMOOMR-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
>>> "50-00-0" in found["WSFSSNUMVMOOMR-UHFFFAOYSA-N"]
True
>>> found["XXXXXXXXXXXXXX-XXXXXXXXXX-X"] is None
True
Source code in src/provesid/zeropm.py
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
def batch_get_cas_from_inchikey(self, inchikey_list):
    """
    Get CAS numbers for multiple InChIKeys at once.

    Parameters
    ----------
    inchikey_list : list of str
        List of InChIKey strings

    Returns
    -------
    dict
        Dictionary mapping InChIKeys to CAS numbers (or None if not found);
        one number as a string, several as a list, as broad as
        [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi].
        Each key is looked up with either flag, as in
        [`get_cas_from_inchikey`][provesid.zeropm.ZeroPM.get_cas_from_inchikey].

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> found = zpm.batch_get_cas_from_inchikey(
    ...     ["WSFSSNUMVMOOMR-UHFFFAOYSA-N", "XXXXXXXXXXXXXX-XXXXXXXXXX-X"])
    >>> "50-00-0" in found["WSFSSNUMVMOOMR-UHFFFAOYSA-N"]
    True
    >>> found["XXXXXXXXXXXXXX-XXXXXXXXXX-X"] is None
    True
    """
    if not inchikey_list:
        return {}

    # First, get inchi_ids for all inchikeys, each under either flag
    # spelling as in get_cas_from_inchikey; each lookup is one index probe
    inchikey_to_id = {}
    for inchikey in inchikey_list:
        found = self._find_substance_by_inchikey(inchikey)
        if found:
            inchikey_to_id[inchikey] = found[0]

    # Get all CAS numbers for these inchi_ids
    if not inchikey_to_id:
        return {key: None for key in inchikey_list}

    inchi_ids = list(inchikey_to_id.values())
    placeholders = ','.join('?' * len(inchi_ids))
    self.cursor.execute(f"""
        SELECT DISTINCT ar.inchi_id, aq.query
        FROM api_results ar
        JOIN api_ready_query aq ON ar.query_id = aq.query_id
        WHERE ar.inchi_id IN ({placeholders}) AND aq.type = 'CAS Registry Number'
    """, inchi_ids)

    # Group CAS numbers by inchi_id
    inchi_to_cas = {}
    for inchi_id, cas in self.cursor.fetchall():
        if inchi_id not in inchi_to_cas:
            inchi_to_cas[inchi_id] = []
        inchi_to_cas[inchi_id].append(cas)

    # Map back to inchikeys
    results = {}
    for inchikey in inchikey_list:
        inchi_id = inchikey_to_id.get(inchikey)
        if inchi_id and inchi_id in inchi_to_cas:
            cas_list = inchi_to_cas[inchi_id]
            results[inchikey] = cas_list[0] if len(cas_list) == 1 else cas_list
        else:
            results[inchikey] = None

    return results
query_name_regex(pattern, case_sensitive=False, limit=100)

Search for chemical names with a simple wildcard pattern.

Not a full regular expression: .* matches any run of characters and . any single character, and everything else is literal. The pattern is translated to SQL LIKE (case-insensitive) or GLOB (case-sensitive), so it must match the whole name.

Parameters:

Name Type Description Default
pattern str

Pattern using .* and . as wildcards

required
case_sensitive bool

Whether the search is case-sensitive (default: False)

False
limit int

Maximum number of results to return (default: 100)

100

Returns:

Type Description
list of tuple

List of (query_id, name) tuples matching the pattern, in database order

Note

Use '.pattern.' for substring matching. A case-insensitive pattern may also use % and _, which LIKE reads as wildcards.

Examples:

>>> zpm = ZeroPM()
>>> zpm.query_name_regex("formaldehyde.*", limit=2)
[(8672, 'Formaldehyde'), (8673, 'formaldehyde ... %')]
>>> zpm.query_name_regex("formaldehyde.*", case_sensitive=True, limit=2)
[(8673, 'formaldehyde ... %'), (104113, 'formaldehyde ...%')]
Source code in src/provesid/zeropm.py
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
def query_name_regex(self, pattern, case_sensitive=False, limit=100):
    """
    Search for chemical names with a simple wildcard pattern.

    Not a full regular expression: ``.*`` matches any run of characters
    and ``.`` any single character, and everything else is literal. The
    pattern is translated to SQL ``LIKE`` (case-insensitive) or ``GLOB``
    (case-sensitive), so it must match the whole name.

    Parameters
    ----------
    pattern : str
        Pattern using ``.*`` and ``.`` as wildcards
    case_sensitive : bool, optional
        Whether the search is case-sensitive (default: False)
    limit : int, optional
        Maximum number of results to return (default: 100)

    Returns
    -------
    list of tuple
        List of (query_id, name) tuples matching the pattern, in database
        order

    Note
    ----
    Use '.*pattern.*' for substring matching. A case-insensitive pattern
    may also use ``%`` and ``_``, which ``LIKE`` reads as wildcards.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.query_name_regex("formaldehyde.*", limit=2)
    [(8672, 'Formaldehyde'), (8673, 'formaldehyde ... %')]
    >>> zpm.query_name_regex("formaldehyde.*", case_sensitive=True, limit=2)
    [(8673, 'formaldehyde ... %'), (104113, 'formaldehyde ...%')]
    """
    if case_sensitive:
        # LIKE ignores case for ASCII letters whatever the pattern says;
        # GLOB does not, and takes * and ? as its wildcards.
        pattern = pattern.replace('.*', '*').replace('.', '?')
        self.cursor.execute(f"""
            SELECT query_id, query
            FROM api_ready_query
            WHERE type = 'chemical name' AND query GLOB ?
            LIMIT ?
        """, (pattern, limit))
    else:
        # Case-insensitive search
        pattern = pattern.replace('.*', '%').replace('.', '_')
        self.cursor.execute(f"""
            SELECT query_id, query
            FROM api_ready_query
            WHERE type = 'chemical name' AND LOWER(query) LIKE LOWER(?)
            LIMIT ?
        """, (pattern, limit))

    return self.cursor.fetchall()
get_cas_by_substructure(smarts_pattern, max_results=100)

Search for chemicals containing a specific substructure. This method converts InChIs to molecules and performs substructure matching using RDKit, in database order.

Parameters:

Name Type Description Default
smarts_pattern str

SMARTS pattern for substructure search

required
max_results int

Maximum number of results to return (default: 100)

100

Returns:

Type Description
list of dict

List of dictionaries with keys: 'cas', 'inchi', 'inchikey', 'smiles'. cas is as get_cas_from_inchi returns it. Empty for an invalid SMARTS pattern.

Warning

Only the first 10 000 of the database's ~359 000 structures are searched, so a structure beyond them is never found. Converting each InChI costs time, and RDKit logs a warning for many of them.

Examples:

>>> zpm = ZeroPM()
>>> hits = zpm.get_cas_by_substructure("c1ccccc1C(=O)O", max_results=2)
>>> [hit["smiles"] for hit in hits]
['COc1ccc(C(=O)O)cc1', 'O=C(O)c1ccc(C(=O)O)cc1']
Source code in src/provesid/zeropm.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
def get_cas_by_substructure(self, smarts_pattern, max_results=100):
    """
    Search for chemicals containing a specific substructure.
    This method converts InChIs to molecules and performs substructure
    matching using RDKit, in database order.

    Parameters
    ----------
    smarts_pattern : str
        SMARTS pattern for substructure search
    max_results : int, optional
        Maximum number of results to return (default: 100)

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'cas', 'inchi', 'inchikey', 'smiles'.
        ``cas`` is as
        [`get_cas_from_inchi`][provesid.zeropm.ZeroPM.get_cas_from_inchi]
        returns it. Empty for an invalid SMARTS pattern.

    Warning
    -------
    Only the first 10 000 of the database's ~359 000 structures are
    searched, so a structure beyond them is never found. Converting each
    InChI costs time, and RDKit logs a warning for many of them.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> hits = zpm.get_cas_by_substructure("c1ccccc1C(=O)O", max_results=2)
    >>> [hit["smiles"] for hit in hits]
    ['COc1ccc(C(=O)O)cc1', 'O=C(O)c1ccc(C(=O)O)cc1']
    """
    try:
        pattern_mol = Chem.MolFromSmarts(smarts_pattern)
        if pattern_mol is None:
            logging.error(f"Invalid SMARTS pattern: {smarts_pattern}")
            return []
    except Exception as e:
        logging.error(f"Error parsing SMARTS pattern: {e}")
        return []

    # Get all substances (this could be optimized with pagination)
    self.cursor.execute("""
        SELECT s.inchi_id, s.inchi, s.inchikey
        FROM substances s
        LIMIT 10000
    """)

    results = []
    count = 0

    for inchi_id, inchi, inchikey in self.cursor.fetchall():
        if count >= max_results:
            break

        # Convert InChI to mol
        try:
            mol = Chem.MolFromInchi(inchi)
            if mol is None:
                continue

            # Check for substructure match
            if mol.HasSubstructMatch(pattern_mol):
                # Get CAS number
                cas = self.get_cas_from_inchi(inchi)
                smiles = Chem.MolToSmiles(mol)

                results.append({
                    'cas': cas,
                    'inchi': inchi,
                    'inchikey': inchikey,
                    'smiles': smiles
                })
                count += 1
        except Exception as e:
            continue

    return results
export_to_csv(query_results, filename, columns=None)

Export query results to a CSV file.

Parameters:

Name Type Description Default
query_results list or dict

Query results to export (list of tuples or dictionary)

required
filename str

Output CSV filename. A relative name is written into the database's directory, beside the database; pass an absolute path to write anywhere else.

required
columns list of str

Column names for the CSV header. A dict gets key,value when none are given; a list gets no header.

None

Returns:

Type Description
str

Path to the created CSV file

Examples:

>>> import tempfile
>>> zpm = ZeroPM()
>>> path = os.path.join(tempfile.mkdtemp(), "smiles.csv")
>>> zpm.export_to_csv({"50-00-0": "C=O"}, path, columns=["cas", "smiles"]) == path
True
>>> print(open(path).read())
cas,smiles
50-00-0,C=O
Source code in src/provesid/zeropm.py
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
def export_to_csv(self, query_results, filename, columns=None):
    """
    Export query results to a CSV file.

    Parameters
    ----------
    query_results : list or dict
        Query results to export (list of tuples or dictionary)
    filename : str
        Output CSV filename. A relative name is written into the
        database's directory, beside the database; pass an absolute path
        to write anywhere else.
    columns : list of str, optional
        Column names for the CSV header. A dict gets ``key,value`` when
        none are given; a list gets no header.

    Returns
    -------
    str
        Path to the created CSV file

    Examples
    --------
    >>> import tempfile
    >>> zpm = ZeroPM()
    >>> path = os.path.join(tempfile.mkdtemp(), "smiles.csv")
    >>> zpm.export_to_csv({"50-00-0": "C=O"}, path, columns=["cas", "smiles"]) == path
    True
    >>> print(open(path).read())
    cas,smiles
    50-00-0,C=O
    <BLANKLINE>
    """
    import csv

    output_path = os.path.join(self.path, filename)

    with open(output_path, 'w', newline='', encoding='utf-8') as f:
        if isinstance(query_results, dict):
            # Handle dictionary results
            writer = csv.writer(f)
            if columns:
                writer.writerow(columns)
            else:
                writer.writerow(['key', 'value'])

            for key, value in query_results.items():
                writer.writerow([key, value])
        else:
            # Handle list of tuples/lists
            writer = csv.writer(f)
            if columns:
                writer.writerow(columns)

            for row in query_results:
                writer.writerow(row)

    return output_path
create_view(view_name, sql_query)

Create a custom view in the database for frequently used queries.

Parameters:

Name Type Description Default
view_name str

Name of the view to create

required
sql_query str

SQL SELECT statement defining the view

required

Returns:

Type Description
bool

True if view was created successfully, False otherwise. A view of the same name is replaced.

Notes

This writes to the database file.

Example

zpm = ZeroPM() sql = ''' ... SELECT aq.query AS cas, s.inchi, s.inchikey ... FROM api_ready_query aq ... JOIN api_results ar ON aq.query_id = ar.query_id ... JOIN substances s ON ar.inchi_id = s.inchi_id ... WHERE aq.type = 'CAS Registry Number' AND ar.rank = 1 ... ''' zpm.create_view('cas_to_inchi', sql) # doctest: +SKIP True

Source code in src/provesid/zeropm.py
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
def create_view(self, view_name, sql_query):
    """
    Create a custom view in the database for frequently used queries.

    Parameters
    ----------
    view_name : str
        Name of the view to create
    sql_query : str
        SQL SELECT statement defining the view

    Returns
    -------
    bool
        True if view was created successfully, False otherwise. A view
        of the same name is replaced.

    Notes
    -----
    This writes to the database file.

    Example
    -------
    >>> zpm = ZeroPM()
    >>> sql = '''
    ...     SELECT aq.query AS cas, s.inchi, s.inchikey
    ...     FROM api_ready_query aq
    ...     JOIN api_results ar ON aq.query_id = ar.query_id
    ...     JOIN substances s ON ar.inchi_id = s.inchi_id
    ...     WHERE aq.type = 'CAS Registry Number' AND ar.rank = 1
    ... '''
    >>> zpm.create_view('cas_to_inchi', sql)            # doctest: +SKIP
    True
    """
    try:
        # Drop view if it exists
        self.cursor.execute(f"DROP VIEW IF EXISTS {view_name}")

        # Create new view
        self.cursor.execute(f"CREATE VIEW {view_name} AS {sql_query}")
        self.conn.commit()

        logging.info(f"View '{view_name}' created successfully")
        return True
    except Exception as e:
        logging.error(f"Error creating view '{view_name}': {e}")
        return False
export_query_results(sql_query, filename, include_headers=True)

Execute a custom SQL query and export results to CSV.

Parameters:

Name Type Description Default
sql_query str

SQL query to execute

required
filename str

Output CSV filename

required
include_headers bool

Include column headers in CSV (default: True)

True

Returns:

Type Description
str

Path to the created CSV file; see export_to_csv for where a relative filename goes

Examples:

>>> import tempfile
>>> zpm = ZeroPM()
>>> path = os.path.join(tempfile.mkdtemp(), "regions.csv")
>>> _ = zpm.export_query_results(
...     "SELECT region_id, region FROM global_regions ORDER BY region_id", path)
>>> print(open(path).read().splitlines()[:3])
['region_id,region', '1,North America', '2,Europe']
Source code in src/provesid/zeropm.py
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
def export_query_results(self, sql_query, filename, include_headers=True):
    """
    Execute a custom SQL query and export results to CSV.

    Parameters
    ----------
    sql_query : str
        SQL query to execute
    filename : str
        Output CSV filename
    include_headers : bool, optional
        Include column headers in CSV (default: True)

    Returns
    -------
    str
        Path to the created CSV file; see
        [`export_to_csv`][provesid.zeropm.ZeroPM.export_to_csv] for where a
        relative ``filename`` goes

    Examples
    --------
    >>> import tempfile
    >>> zpm = ZeroPM()
    >>> path = os.path.join(tempfile.mkdtemp(), "regions.csv")
    >>> _ = zpm.export_query_results(
    ...     "SELECT region_id, region FROM global_regions ORDER BY region_id", path)
    >>> print(open(path).read().splitlines()[:3])
    ['region_id,region', '1,North America', '2,Europe']
    """
    import csv

    self.cursor.execute(sql_query)
    results = self.cursor.fetchall()

    # Get column names from cursor description
    columns = [desc[0] for desc in self.cursor.description] if include_headers else None

    return self.export_to_csv(results, filename, columns)
get_database_stats()

Get statistics about the database contents.

Returns:

Type Description
dict

Row counts of api_ready_query, api_results, substances, inventories, inventory_summary, cleanventory_chemicals, zeropm_chemicals, components and multi_components, plus unique_cas_numbers and unique_chemical_names. A table that cannot be counted holds its error message instead.

Examples:

>>> stats = ZeroPM().get_database_stats()
>>> stats["unique_cas_numbers"], stats["zeropm_chemicals"]
(164513, 126369)
Source code in src/provesid/zeropm.py
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
def get_database_stats(self):
    """
    Get statistics about the database contents.

    Returns
    -------
    dict
        Row counts of ``api_ready_query``, ``api_results``,
        ``substances``, ``inventories``, ``inventory_summary``,
        ``cleanventory_chemicals``, ``zeropm_chemicals``, ``components``
        and ``multi_components``, plus ``unique_cas_numbers`` and
        ``unique_chemical_names``. A table that cannot be counted holds
        its error message instead.

    Examples
    --------
    >>> stats = ZeroPM().get_database_stats()
    >>> stats["unique_cas_numbers"], stats["zeropm_chemicals"]
    (164513, 126369)
    """
    tables = [
        'api_ready_query', 'api_results', 'substances',
        'inventories', 'inventory_summary', 'cleanventory_chemicals',
        'zeropm_chemicals', 'components', 'multi_components'
    ]

    stats = {}

    for table in tables:
        try:
            self.cursor.execute(f"SELECT COUNT(*) FROM {table}")
            count = self.cursor.fetchone()[0]
            stats[table] = count
        except Exception as e:
            stats[table] = f"Error: {e}"

    # Additional statistics
    self.cursor.execute("""
        SELECT COUNT(DISTINCT query)
        FROM api_ready_query
        WHERE type = 'CAS Registry Number'
    """)
    stats['unique_cas_numbers'] = self.cursor.fetchone()[0]

    self.cursor.execute("""
        SELECT COUNT(DISTINCT query)
        FROM api_ready_query
        WHERE type = 'chemical name'
    """)
    stats['unique_chemical_names'] = self.cursor.fetchone()[0]

    return stats
get_all_inventories()

Get all available inventory sources.

Returns:

Type Description
list of dict

List of dictionaries with keys: 'source_id', 'source_name', 'country_scope', 'link', 'type', ordered by name. Some names carry stray spaces, as stored.

Examples:

>>> inventories = ZeroPM().get_all_inventories()
>>> len(inventories)
25
>>> [(i["source_id"], i["country_scope"]) for i in inventories if "TSCA" in i["source_name"]]
[(24, 'United States of America')]
Source code in src/provesid/zeropm.py
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
def get_all_inventories(self):
    """
    Get all available inventory sources.

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'source_id', 'source_name', 'country_scope', 'link', 'type',
        ordered by name. Some names carry stray spaces, as stored.

    Examples
    --------
    >>> inventories = ZeroPM().get_all_inventories()
    >>> len(inventories)
    25
    >>> [(i["source_id"], i["country_scope"]) for i in inventories if "TSCA" in i["source_name"]]
    [(24, 'United States of America')]
    """
    self.cursor.execute("""
        SELECT source_id, source_name, country_scope, link, type
        FROM sources
        ORDER BY source_name
    """)

    inventories = []
    for row in self.cursor.fetchall():
        inventories.append({
            'source_id': row[0],
            'source_name': row[1],
            'country_scope': row[2],
            'link': row[3],
            'type': row[4]
        })

    return inventories
get_all_countries()

Get all countries in the database.

Returns:

Type Description
list of dict

List of dictionaries with keys: 'country_id', 'country', ordered by name

Examples:

>>> countries = ZeroPM().get_all_countries()
>>> len(countries), countries[0]
(38, {'country_id': 1, 'country': 'Australia'})
Source code in src/provesid/zeropm.py
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
def get_all_countries(self):
    """
    Get all countries in the database.

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'country_id', 'country', ordered by name

    Examples
    --------
    >>> countries = ZeroPM().get_all_countries()
    >>> len(countries), countries[0]
    (38, {'country_id': 1, 'country': 'Australia'})
    """
    self.cursor.execute("""
        SELECT country_id, country
        FROM countries
        ORDER BY country
    """)

    countries = []
    for row in self.cursor.fetchall():
        countries.append({
            'country_id': row[0],
            'country': row[1]
        })

    return countries
get_all_regions()

Get all global regions in the database.

Returns:

Type Description
list of dict

List of dictionaries with keys: 'region_id', 'region', ordered by name

Examples:

>>> [r["region"] for r in ZeroPM().get_all_regions()]
['Asia', 'Europe', 'North America', 'Oceania', 'Scandinavia']
Source code in src/provesid/zeropm.py
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
def get_all_regions(self):
    """
    Get all global regions in the database.

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'region_id', 'region', ordered by name

    Examples
    --------
    >>> [r["region"] for r in ZeroPM().get_all_regions()]
    ['Asia', 'Europe', 'North America', 'Oceania', 'Scandinavia']
    """
    self.cursor.execute("""
        SELECT region_id, region
        FROM global_regions
        ORDER BY region
    """)

    regions = []
    for row in self.cursor.fetchall():
        regions.append({
            'region_id': row[0],
            'region': row[1]
        })

    return regions
query_by_inventory(source_name=None, source_id=None)

Query chemicals by inventory source.

Parameters:

Name Type Description Default
source_name str

Name of the inventory source (case-insensitive partial match)

None
source_id int

Source ID (exact match)

None

Returns:

Type Description
list of dict

List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'source_name', ordered by CAS number. A CAS number appears once per structure it resolves to, at any rank, and once per matching inventory.

Raises:

Type Description
ValueError

If neither source_name nor source_id is given.

Note

Either source_name or source_id must be provided. count_chemicals_by_inventory counts distinct CAS numbers without building the list.

Examples:

>>> rows = ZeroPM().query_by_inventory(source_name="TSCA")
>>> rows[0]
{'cas': '100-00-5', 'query_id': 1927, 'inchi_id': 1, 'source_name': 'Toxic Substances Control Act (TSCA) Chemical Substance Inventory'}
Source code in src/provesid/zeropm.py
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
def query_by_inventory(self, source_name=None, source_id=None):
    """
    Query chemicals by inventory source.

    Parameters
    ----------
    source_name : str, optional
        Name of the inventory source (case-insensitive partial match)
    source_id : int, optional
        Source ID (exact match)

    Returns
    -------
    list of dict
        List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'source_name',
        ordered by CAS number. A CAS number appears once per structure
        it resolves to, at any rank, and once per matching inventory.

    Raises
    ------
    ValueError
        If neither ``source_name`` nor ``source_id`` is given.

    Note
    ----
    Either source_name or source_id must be provided.
    [`count_chemicals_by_inventory`][provesid.zeropm.ZeroPM.count_chemicals_by_inventory]
    counts distinct CAS numbers without building the list.

    Examples
    --------
    >>> rows = ZeroPM().query_by_inventory(source_name="TSCA")
    >>> rows[0]
    {'cas': '100-00-5', 'query_id': 1927, 'inchi_id': 1, 'source_name': 'Toxic Substances Control Act (TSCA) Chemical Substance Inventory'}
    """
    if source_name is None and source_id is None:
        raise ValueError("Either source_name or source_id must be provided")

    if source_id is not None:
        # Query by source_id
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND s.source_id = ?
            ORDER BY aq.query
        """, (source_id,))
    else:
        # Query by source_name (partial, case-insensitive)
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND LOWER(s.source_name) LIKE LOWER(?)
            ORDER BY aq.query
        """, (f'%{source_name}%',))

    results = []
    for row in self.cursor.fetchall():
        results.append({
            'cas': row[0],
            'query_id': row[1],
            'inchi_id': row[2],
            'source_name': row[3]
        })

    return results
query_by_country(country_name=None, country_id=None)

Query chemicals by country.

Parameters:

Name Type Description Default
country_name str

Name of the country (case-insensitive partial match)

None
country_id int

Country ID (exact match)

None

Returns:

Type Description
list of dict

List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'country', 'source_name', ordered by CAS number, repeated as query_by_inventory describes

Raises:

Type Description
ValueError

If neither country_name nor country_id is given.

Note

Either country_name or country_id must be provided.

Examples:

>>> rows = ZeroPM().query_by_country("Japan")
>>> rows[0]["cas"], rows[0]["source_name"]
('100-00-5', 'NITE')
Source code in src/provesid/zeropm.py
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
def query_by_country(self, country_name=None, country_id=None):
    """
    Query chemicals by country.

    Parameters
    ----------
    country_name : str, optional
        Name of the country (case-insensitive partial match)
    country_id : int, optional
        Country ID (exact match)

    Returns
    -------
    list of dict
        List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'country', 'source_name',
        ordered by CAS number, repeated as
        [`query_by_inventory`][provesid.zeropm.ZeroPM.query_by_inventory]
        describes

    Raises
    ------
    ValueError
        If neither ``country_name`` nor ``country_id`` is given.

    Note
    ----
    Either country_name or country_id must be provided.

    Examples
    --------
    >>> rows = ZeroPM().query_by_country("Japan")
    >>> rows[0]["cas"], rows[0]["source_name"]
    ('100-00-5', 'NITE')
    """
    if country_name is None and country_id is None:
        raise ValueError("Either country_name or country_id must be provided")

    if country_id is not None:
        # Query by country_id
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, c.country, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND c.country_id = ?
            ORDER BY aq.query
        """, (country_id,))
    else:
        # Query by country_name (partial, case-insensitive)
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, c.country, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND LOWER(c.country) LIKE LOWER(?)
            ORDER BY aq.query
        """, (f'%{country_name}%',))

    results = []
    for row in self.cursor.fetchall():
        results.append({
            'cas': row[0],
            'query_id': row[1],
            'inchi_id': row[2],
            'country': row[3],
            'source_name': row[4]
        })

    return results
query_by_region(region_name=None, region_id=None)

Query chemicals by global region.

Parameters:

Name Type Description Default
region_name str

Name of the region (case-insensitive partial match)

None
region_id int

Region ID (exact match)

None

Returns:

Type Description
list of dict

List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'region', 'country', 'source_name', ordered by CAS number, repeated as query_by_inventory describes

Raises:

Type Description
ValueError

If neither region_name nor region_id is given.

Note

Either region_name or region_id must be provided.

Examples:

>>> rows = ZeroPM().query_by_region("Oceania")
>>> rows[0]["cas"], rows[0]["country"]
('100-00-5', 'New Zealand')
Source code in src/provesid/zeropm.py
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
def query_by_region(self, region_name=None, region_id=None):
    """
    Query chemicals by global region.

    Parameters
    ----------
    region_name : str, optional
        Name of the region (case-insensitive partial match)
    region_id : int, optional
        Region ID (exact match)

    Returns
    -------
    list of dict
        List of chemicals with keys: 'cas', 'query_id', 'inchi_id', 'region', 'country', 'source_name',
        ordered by CAS number, repeated as
        [`query_by_inventory`][provesid.zeropm.ZeroPM.query_by_inventory]
        describes

    Raises
    ------
    ValueError
        If neither ``region_name`` nor ``region_id`` is given.

    Note
    ----
    Either region_name or region_id must be provided.

    Examples
    --------
    >>> rows = ZeroPM().query_by_region("Oceania")
    >>> rows[0]["cas"], rows[0]["country"]
    ('100-00-5', 'New Zealand')
    """
    if region_name is None and region_id is None:
        raise ValueError("Either region_name or region_id must be provided")

    if region_id is not None:
        # Query by region_id
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, gr.region, c.country, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            JOIN region_country_index rci ON c.country_id = rci.country_id
            JOIN global_regions gr ON rci.region_id = gr.region_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND gr.region_id = ?
            ORDER BY aq.query
        """, (region_id,))
    else:
        # Query by region_name (partial, case-insensitive)
        self.cursor.execute("""
            SELECT DISTINCT aq.query, aq.query_id, ar.inchi_id, gr.region, c.country, s.source_name
            FROM api_ready_query aq
            JOIN inventory_summary issum ON aq.query_id = issum.query_id
            JOIN inventories inv ON issum.inventory_id = inv.inventory_id
            JOIN sources s ON inv.source_id = s.source_id
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            JOIN region_country_index rci ON c.country_id = rci.country_id
            JOIN global_regions gr ON rci.region_id = gr.region_id
            JOIN api_results ar ON aq.query_id = ar.query_id
            WHERE aq.type = 'CAS Registry Number' AND LOWER(gr.region) LIKE LOWER(?)
            ORDER BY aq.query
        """, (f'%{region_name}%',))

    results = []
    for row in self.cursor.fetchall():
        results.append({
            'cas': row[0],
            'query_id': row[1],
            'inchi_id': row[2],
            'region': row[3],
            'country': row[4],
            'source_name': row[5]
        })

    return results
get_countries_for_region(region_name=None, region_id=None)

Get all countries in a specific region.

Parameters:

Name Type Description Default
region_name str

Name of the region (case-insensitive partial match)

None
region_id int

Region ID (exact match)

None

Returns:

Type Description
list of dict

List of dictionaries with keys: 'country_id', 'country', 'region'

Raises:

Type Description
ValueError

If neither region_name nor region_id is given.

Note

Either region_name or region_id must be provided.

Examples:

>>> [c["country"] for c in ZeroPM().get_countries_for_region("Scandinavia")]
['Denmark', 'Finland', 'Norway', 'Sweden']
Source code in src/provesid/zeropm.py
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
def get_countries_for_region(self, region_name=None, region_id=None):
    """
    Get all countries in a specific region.

    Parameters
    ----------
    region_name : str, optional
        Name of the region (case-insensitive partial match)
    region_id : int, optional
        Region ID (exact match)

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'country_id', 'country', 'region'

    Raises
    ------
    ValueError
        If neither ``region_name`` nor ``region_id`` is given.

    Note
    ----
    Either region_name or region_id must be provided.

    Examples
    --------
    >>> [c["country"] for c in ZeroPM().get_countries_for_region("Scandinavia")]
    ['Denmark', 'Finland', 'Norway', 'Sweden']
    """
    if region_name is None and region_id is None:
        raise ValueError("Either region_name or region_id must be provided")

    if region_id is not None:
        self.cursor.execute("""
            SELECT DISTINCT c.country_id, c.country, gr.region
            FROM countries c
            JOIN region_country_index rci ON c.country_id = rci.country_id
            JOIN global_regions gr ON rci.region_id = gr.region_id
            WHERE gr.region_id = ?
            ORDER BY c.country
        """, (region_id,))
    else:
        self.cursor.execute("""
            SELECT DISTINCT c.country_id, c.country, gr.region
            FROM countries c
            JOIN region_country_index rci ON c.country_id = rci.country_id
            JOIN global_regions gr ON rci.region_id = gr.region_id
            WHERE LOWER(gr.region) LIKE LOWER(?)
            ORDER BY c.country
        """, (f'%{region_name}%',))

    countries = []
    for row in self.cursor.fetchall():
        countries.append({
            'country_id': row[0],
            'country': row[1],
            'region': row[2]
        })

    return countries
get_inventories_for_country(country_name=None, country_id=None)

Get all inventory sources for a specific country.

Parameters:

Name Type Description Default
country_name str

Name of the country (case-insensitive partial match)

None
country_id int

Country ID (exact match)

None

Returns:

Type Description
list of dict

List of dictionaries with keys: 'source_id', 'source_name', 'country', 'link', 'type'

Raises:

Type Description
ValueError

If neither country_name nor country_id is given.

Note

Either country_name or country_id must be provided.

Examples:

>>> [i["source_id"] for i in ZeroPM().get_inventories_for_country("Japan")]
[8, 9, 10, 11]
Source code in src/provesid/zeropm.py
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
def get_inventories_for_country(self, country_name=None, country_id=None):
    """
    Get all inventory sources for a specific country.

    Parameters
    ----------
    country_name : str, optional
        Name of the country (case-insensitive partial match)
    country_id : int, optional
        Country ID (exact match)

    Returns
    -------
    list of dict
        List of dictionaries with keys: 'source_id', 'source_name', 'country', 'link', 'type'

    Raises
    ------
    ValueError
        If neither ``country_name`` nor ``country_id`` is given.

    Note
    ----
    Either country_name or country_id must be provided.

    Examples
    --------
    >>> [i["source_id"] for i in ZeroPM().get_inventories_for_country("Japan")]
    [8, 9, 10, 11]
    """
    if country_name is None and country_id is None:
        raise ValueError("Either country_name or country_id must be provided")

    if country_id is not None:
        self.cursor.execute("""
            SELECT DISTINCT s.source_id, s.source_name, c.country, s.link, s.type
            FROM sources s
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            WHERE c.country_id = ?
            ORDER BY s.source_name
        """, (country_id,))
    else:
        self.cursor.execute("""
            SELECT DISTINCT s.source_id, s.source_name, c.country, s.link, s.type
            FROM sources s
            JOIN country_sources_index csi ON s.source_id = csi.source_id
            JOIN countries c ON csi.country_id = c.country_id
            WHERE LOWER(c.country) LIKE LOWER(?)
            ORDER BY s.source_name
        """, (f'%{country_name}%',))

    inventories = []
    for row in self.cursor.fetchall():
        inventories.append({
            'source_id': row[0],
            'source_name': row[1],
            'country': row[2],
            'link': row[3],
            'type': row[4]
        })

    return inventories
count_chemicals_by_inventory(source_id)

Count the number of chemicals in a specific inventory.

Parameters:

Name Type Description Default
source_id int

Source ID

required

Returns:

Type Description
int

Number of unique CAS numbers in the inventory

Examples:

>>> ZeroPM().count_chemicals_by_inventory(12)   # South Korea's
21580
Source code in src/provesid/zeropm.py
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
def count_chemicals_by_inventory(self, source_id):
    """
    Count the number of chemicals in a specific inventory.

    Parameters
    ----------
    source_id : int
        Source ID

    Returns
    -------
    int
        Number of unique CAS numbers in the inventory

    Examples
    --------
    >>> ZeroPM().count_chemicals_by_inventory(12)   # South Korea's
    21580
    """
    self.cursor.execute("""
        SELECT COUNT(DISTINCT aq.query)
        FROM api_ready_query aq
        JOIN inventory_summary issum ON aq.query_id = issum.query_id
        JOIN inventories inv ON issum.inventory_id = inv.inventory_id
        WHERE aq.type = 'CAS Registry Number' AND inv.source_id = ?
    """, (source_id,))

    return self.cursor.fetchone()[0]
count_chemicals_by_country(country_id)

Count the number of chemicals registered in a specific country.

Parameters:

Name Type Description Default
country_id int

Country ID

required

Returns:

Type Description
int

Number of unique CAS numbers in the country, over all its inventories

Examples:

>>> ZeroPM().count_chemicals_by_country(1)      # Australia
25183
Source code in src/provesid/zeropm.py
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
def count_chemicals_by_country(self, country_id):
    """
    Count the number of chemicals registered in a specific country.

    Parameters
    ----------
    country_id : int
        Country ID

    Returns
    -------
    int
        Number of unique CAS numbers in the country, over all its
        inventories

    Examples
    --------
    >>> ZeroPM().count_chemicals_by_country(1)      # Australia
    25183
    """
    self.cursor.execute("""
        SELECT COUNT(DISTINCT aq.query)
        FROM api_ready_query aq
        JOIN inventory_summary issum ON aq.query_id = issum.query_id
        JOIN inventories inv ON issum.inventory_id = inv.inventory_id
        JOIN sources s ON inv.source_id = s.source_id
        JOIN country_sources_index csi ON s.source_id = csi.source_id
        WHERE aq.type = 'CAS Registry Number' AND csi.country_id = ?
    """, (country_id,))

    return self.cursor.fetchone()[0]
count_chemicals_by_region(region_id)

Count the number of chemicals registered in a specific region.

Parameters:

Name Type Description Default
region_id int

Region ID

required

Returns:

Type Description
int

Number of unique CAS numbers in the region

Examples:

>>> ZeroPM().count_chemicals_by_region(5)       # Oceania
34175
Source code in src/provesid/zeropm.py
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
def count_chemicals_by_region(self, region_id):
    """
    Count the number of chemicals registered in a specific region.

    Parameters
    ----------
    region_id : int
        Region ID

    Returns
    -------
    int
        Number of unique CAS numbers in the region

    Examples
    --------
    >>> ZeroPM().count_chemicals_by_region(5)       # Oceania
    34175
    """
    self.cursor.execute("""
        SELECT COUNT(DISTINCT aq.query)
        FROM api_ready_query aq
        JOIN inventory_summary issum ON aq.query_id = issum.query_id
        JOIN inventories inv ON issum.inventory_id = inv.inventory_id
        JOIN sources s ON inv.source_id = s.source_id
        JOIN country_sources_index csi ON s.source_id = csi.source_id
        JOIN countries c ON csi.country_id = c.country_id
        JOIN region_country_index rci ON c.country_id = rci.country_id
        WHERE aq.type = 'CAS Registry Number' AND rci.region_id = ?
    """, (region_id,))

    return self.cursor.fetchone()[0]
get_zeropm_id(cas=None, inchi_id=None)

Get the zeropm_id for a chemical from CAS number or inchi_id.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None

Returns:

Type Description
int or None

zeropm_id if found, None otherwise. A CAS number is resolved to its rank-1 structure first.

Raises:

Type Description
ValueError

If neither cas nor inchi_id is given.

Note

Either cas or inchi_id must be provided.

Examples:

>>> zpm = ZeroPM()
>>> zpm.get_zeropm_id(cas="50-00-0"), zpm.get_zeropm_id(inchi_id=32227)
(3224, 3224)
Source code in src/provesid/zeropm.py
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
def get_zeropm_id(self, cas=None, inchi_id=None):
    """
    Get the zeropm_id for a chemical from CAS number or inchi_id.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier

    Returns
    -------
    int or None
        zeropm_id if found, None otherwise. A CAS number is resolved to
        its rank-1 structure first.

    Raises
    ------
    ValueError
        If neither ``cas`` nor ``inchi_id`` is given.

    Note
    ----
    Either cas or inchi_id must be provided.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.get_zeropm_id(cas="50-00-0"), zpm.get_zeropm_id(inchi_id=32227)
    (3224, 3224)
    """
    if cas is None and inchi_id is None:
        raise ValueError("Either cas or inchi_id must be provided")

    if inchi_id is None:
        inchi_id = self._inchi_id_from_cas(cas)
        if inchi_id is None:
            return None

    # Get zeropm_id from inchi_id
    self.cursor.execute("""
        SELECT zeropm_id
        FROM zeropm_chemicals
        WHERE inchi_id = ?
    """, (inchi_id,))
    result = self.cursor.fetchone()
    return result[0] if result else None
zeropm_id_to_inchi_id(zeropm_id)

Get the inchi_id for a zeropm_id — the reverse of get_zeropm_id.

Parameters:

Name Type Description Default
zeropm_id int

ZeroPM identifier.

required

Returns:

Type Description
int or None

The inchi_id, or None when the zeropm_id is not in the database.

Examples:

>>> zpm = ZeroPM()
>>> zpm.zeropm_id_to_inchi_id(1)
6210
>>> zpm.zeropm_id_to_inchi_id(3224)   # formaldehyde
32227
Source code in src/provesid/zeropm.py
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
def zeropm_id_to_inchi_id(self, zeropm_id):
    """
    Get the inchi_id for a zeropm_id — the reverse of
    [`get_zeropm_id`][provesid.zeropm.ZeroPM.get_zeropm_id].

    Parameters
    ----------
    zeropm_id : int
        ZeroPM identifier.

    Returns
    -------
    int or None
        The inchi_id, or None when the zeropm_id is not in the database.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.zeropm_id_to_inchi_id(1)
    6210
    >>> zpm.zeropm_id_to_inchi_id(3224)   # formaldehyde
    32227
    """
    self.cursor.execute("""
        SELECT inchi_id
        FROM zeropm_chemicals
        WHERE zeropm_id = ?
    """, (zeropm_id,))
    result = self.cursor.fetchone()
    return result[0] if result else None
get_pm_probabilities(cas=None, inchi_id=None, zeropm_id=None)

Get P/M (Persistent/Mobile) probability data for a chemical.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None
zeropm_id int

ZeroPM identifier

None

Returns:

Type Description
dict or None

Dictionary with probability data:

  • probability_of_not_p: Probability of NOT persistent
  • probability_of_p_or_vp: Probability of persistent OR very persistent
  • probability_of_p: Probability of persistent
  • probability_of_vp: Probability of very persistent
  • probability_of_not_m: Probability of NOT mobile
  • probability_of_m_or_vm: Probability of mobile OR very mobile
  • probability_of_m: Probability of mobile but not very mobile
  • probability_of_vm: Probability of very mobile
  • n: Sample size

probability_of_p likewise excludes the very persistent, so p + vp = p_or_vp and not_p + p_or_vp = 1; the same holds for M. Returns None if not found, or if ZeroPM assessed the chemical but published no probabilities for it --- formaldehyde is one.

Raises:

Type Description
ValueError

If none of cas, inchi_id or zeropm_id is provided.

Examples:

>>> zpm = ZeroPM()
>>> probs = zpm.get_pm_probabilities(inchi_id=6210)
>>> round(probs["probability_of_p"], 3)
0.4
>>> tfa = zpm.get_pm_probabilities(cas="76-05-1")
>>> round(tfa["probability_of_vm"], 3), round(tfa["probability_of_m_or_vm"], 3)
(0.995, 1.0)
>>> zpm.get_pm_probabilities(cas="50-00-0") is None
True
Note

Three of the mobility columns in zeropm-v0-0-4.sqlite hold each other's values: the one named m_or_vm holds m, m holds vm, and vm holds m_or_vm. The file was loaded positionally from a CSV that orders them differently. This method, like batch_get_pm_probabilities and get_all_zeropm_chemicals, returns each value under its true name. A query of the table written by hand gets the stored names.

pm_probabilities is keyed on inchi_id, so a zeropm_id is translated first via zeropm_id_to_inchi_id.

Source code in src/provesid/zeropm.py
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
def get_pm_probabilities(self, cas=None, inchi_id=None, zeropm_id=None):
    """
    Get P/M (Persistent/Mobile) probability data for a chemical.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier
    zeropm_id : int, optional
        ZeroPM identifier

    Returns
    -------
    dict or None
        Dictionary with probability data:

        - probability_of_not_p: Probability of NOT persistent
        - probability_of_p_or_vp: Probability of persistent OR very persistent
        - probability_of_p: Probability of persistent
        - probability_of_vp: Probability of very persistent
        - probability_of_not_m: Probability of NOT mobile
        - probability_of_m_or_vm: Probability of mobile OR very mobile
        - probability_of_m: Probability of mobile but not very mobile
        - probability_of_vm: Probability of very mobile
        - n: Sample size

        ``probability_of_p`` likewise excludes the very persistent, so
        ``p + vp = p_or_vp`` and ``not_p + p_or_vp = 1``; the same holds
        for M.
        Returns None if not found, or if ZeroPM assessed the chemical
        but published no probabilities for it --- formaldehyde is one.

    Raises
    ------
    ValueError
        If none of ``cas``, ``inchi_id`` or ``zeropm_id`` is provided.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> probs = zpm.get_pm_probabilities(inchi_id=6210)
    >>> round(probs["probability_of_p"], 3)
    0.4
    >>> tfa = zpm.get_pm_probabilities(cas="76-05-1")
    >>> round(tfa["probability_of_vm"], 3), round(tfa["probability_of_m_or_vm"], 3)
    (0.995, 1.0)
    >>> zpm.get_pm_probabilities(cas="50-00-0") is None
    True

    Note
    ----
    Three of the mobility columns in ``zeropm-v0-0-4.sqlite`` hold each
    other's values: the one named ``m_or_vm`` holds ``m``, ``m`` holds
    ``vm``, and ``vm`` holds ``m_or_vm``. The file was loaded positionally
    from a CSV that orders them differently. This method, like
    [`batch_get_pm_probabilities`][provesid.zeropm.ZeroPM.batch_get_pm_probabilities]
    and [`get_all_zeropm_chemicals`][provesid.zeropm.ZeroPM.get_all_zeropm_chemicals],
    returns each value under its true name. A query of the table
    written by hand gets the stored names.

    ``pm_probabilities`` is keyed on ``inchi_id``, so a ``zeropm_id`` is
    translated first via
    [`zeropm_id_to_inchi_id`][provesid.zeropm.ZeroPM.zeropm_id_to_inchi_id].
    """
    if cas is None and inchi_id is None and zeropm_id is None:
        raise ValueError("One of cas, inchi_id or zeropm_id must be provided")

    if inchi_id is None:
        if zeropm_id is not None:
            inchi_id = self.zeropm_id_to_inchi_id(zeropm_id)
        else:
            inchi_id = self._inchi_id_from_cas(cas)
        if inchi_id is None:
            return None

    self.cursor.execute(f"""
        SELECT {_PM_PROBABILITY_SELECT}
        FROM pm_probabilities pm
        WHERE pm.inchi_id = ?
    """, (inchi_id,))
    result = self.cursor.fetchone()

    if not result:
        return None

    return dict(zip(PM_PROBABILITY_COLUMNS, result))
is_in_zeropm(cas=None, inchi_id=None)

Check if a chemical is in the ZeroPM database.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None

Returns:

Type Description
bool

True if the chemical has a zeropm_id (ZeroPM assessed it), False otherwise --- including a CAS number that is in the inventories but was not assessed

Raises:

Type Description
ValueError

If neither cas nor inchi_id is given.

Examples:

>>> zpm = ZeroPM()
>>> zpm.is_in_zeropm(cas="50-00-0"), zpm.is_in_zeropm(cas="0-00-0")
(True, False)
Source code in src/provesid/zeropm.py
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
def is_in_zeropm(self, cas=None, inchi_id=None):
    """
    Check if a chemical is in the ZeroPM database.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier

    Returns
    -------
    bool
        True if the chemical has a ``zeropm_id`` (ZeroPM assessed it),
        False otherwise --- including a CAS number that is in the
        inventories but was not assessed

    Raises
    ------
    ValueError
        If neither ``cas`` nor ``inchi_id`` is given.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.is_in_zeropm(cas="50-00-0"), zpm.is_in_zeropm(cas="0-00-0")
    (True, False)
    """
    return self.get_zeropm_id(cas=cas, inchi_id=inchi_id) is not None
is_multicomponent(inchi_id)

Check if a substance is a multi-component substance.

Parameters:

Name Type Description Default
inchi_id int

InChI identifier

required

Returns:

Type Description
bool

True if substance is multi-component, False otherwise

Examples:

>>> zpm = ZeroPM()
>>> zpm.is_multicomponent(5), zpm.is_multicomponent(32227)
(True, False)
Source code in src/provesid/zeropm.py
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
def is_multicomponent(self, inchi_id):
    """
    Check if a substance is a multi-component substance.

    Parameters
    ----------
    inchi_id : int
        InChI identifier

    Returns
    -------
    bool
        True if substance is multi-component, False otherwise

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.is_multicomponent(5), zpm.is_multicomponent(32227)
    (True, False)
    """
    self.cursor.execute("""
        SELECT mc_id
        FROM multi_components
        WHERE inchi_id = ?
    """, (inchi_id,))
    return self.cursor.fetchone() is not None
get_multicomponent_id(inchi_id)

Get the multi-component ID for a substance.

Parameters:

Name Type Description Default
inchi_id int

InChI identifier

required

Returns:

Type Description
int or None

mc_id if found, None otherwise

Examples:

>>> ZeroPM().get_multicomponent_id(5)
1
Source code in src/provesid/zeropm.py
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
def get_multicomponent_id(self, inchi_id):
    """
    Get the multi-component ID for a substance.

    Parameters
    ----------
    inchi_id : int
        InChI identifier

    Returns
    -------
    int or None
        mc_id if found, None otherwise

    Examples
    --------
    >>> ZeroPM().get_multicomponent_id(5)
    1
    """
    self.cursor.execute("""
        SELECT mc_id
        FROM multi_components
        WHERE inchi_id = ?
    """, (inchi_id,))
    result = self.cursor.fetchone()
    return result[0] if result else None
get_components(mc_id)

Get all components of a multi-component substance.

Parameters:

Name Type Description Default
mc_id int

Multi-component identifier

required

Returns:

Type Description
list of dict

List of component information with keys:

  • component_id: Component identifier
  • component_frequency: How often the component appears
  • inchi_id: InChI identifier of the component
  • inchi: InChI string of the component
  • inchikey: InChIKey of the component Most frequent first. Empty for an unknown mc_id.

Examples:

>>> [c["inchi"] for c in ZeroPM().get_components(1)]
['InChI=1S/ClH/h1H/p-1', 'InChI=1S/C8H10N3/c1-11(2)8-5-3-7(10-9)4-6-8/h3-6H,1-2H3/q+1']
Source code in src/provesid/zeropm.py
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
def get_components(self, mc_id):
    """
    Get all components of a multi-component substance.

    Parameters
    ----------
    mc_id : int
        Multi-component identifier

    Returns
    -------
    list of dict
        List of component information with keys:

        - component_id: Component identifier
        - component_frequency: How often the component appears
        - inchi_id: InChI identifier of the component
        - inchi: InChI string of the component
        - inchikey: InChIKey of the component
        Most frequent first. Empty for an unknown ``mc_id``.

    Examples
    --------
    >>> [c["inchi"] for c in ZeroPM().get_components(1)]
    ['InChI=1S/ClH/h1H/p-1', 'InChI=1S/C8H10N3/c1-11(2)8-5-3-7(10-9)4-6-8/h3-6H,1-2H3/q+1']
    """
    self.cursor.execute("""
        SELECT ci.component_id, ci.component_frequency, c.inchi_id, s.inchi, s.inchikey
        FROM component_index ci
        JOIN components c ON ci.component_id = c.component_id
        JOIN substances s ON c.inchi_id = s.inchi_id
        WHERE ci.mc_id = ?
        ORDER BY ci.component_frequency DESC
    """, (mc_id,))

    components = []
    for row in self.cursor.fetchall():
        components.append({
            'component_id': row[0],
            'component_frequency': row[1],
            'inchi_id': row[2],
            'inchi': row[3],
            'inchikey': row[4]
        })

    return components
get_multicomponent_info(cas=None, inchi_id=None)

Get complete multi-component information for a substance.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None

Returns:

Type Description
dict or None

Dictionary with:

  • mc_id: Multi-component identifier
  • inchi_id: InChI identifier of the multi-component
  • inchi: InChI of the multi-component
  • inchikey: InChIKey of the multi-component
  • components: List of component dictionaries, as get_components returns them Returns None if not a multi-component substance. A CAS number is resolved to its rank-1 structure first.

Raises:

Type Description
ValueError

If neither cas nor inchi_id is given.

Examples:

>>> zpm = ZeroPM()
>>> info = zpm.get_multicomponent_info(inchi_id=5)
>>> info["mc_id"], info["inchikey"], len(info["components"])
(1, 'CCIAVEMREXZXAK-UHFFFAOYSA-M', 2)
>>> zpm.get_multicomponent_info(cas="50-00-0") is None
True
Source code in src/provesid/zeropm.py
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
def get_multicomponent_info(self, cas=None, inchi_id=None):
    """
    Get complete multi-component information for a substance.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier

    Returns
    -------
    dict or None
        Dictionary with:

        - mc_id: Multi-component identifier
        - inchi_id: InChI identifier of the multi-component
        - inchi: InChI of the multi-component
        - inchikey: InChIKey of the multi-component
        - components: List of component dictionaries, as
          [`get_components`][provesid.zeropm.ZeroPM.get_components] returns them
        Returns None if not a multi-component substance. A CAS number is
        resolved to its rank-1 structure first.

    Raises
    ------
    ValueError
        If neither ``cas`` nor ``inchi_id`` is given.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> info = zpm.get_multicomponent_info(inchi_id=5)
    >>> info["mc_id"], info["inchikey"], len(info["components"])
    (1, 'CCIAVEMREXZXAK-UHFFFAOYSA-M', 2)
    >>> zpm.get_multicomponent_info(cas="50-00-0") is None
    True
    """
    if inchi_id is None:
        if cas is None:
            raise ValueError("Either cas or inchi_id must be provided")
        query_id = self.query_cas(cas)
        if query_id is None:
            return None
        inchi_ids, _ = self.get_inchi_id(query_id)
        if not inchi_ids:
            return None
        inchi_id = inchi_ids[0]

    # Check if it's a multi-component
    mc_id = self.get_multicomponent_id(inchi_id)
    if mc_id is None:
        return None

    # Get multi-component info
    self.cursor.execute("""
        SELECT mc.inchi_id, s.inchi, s.inchikey
        FROM multi_components mc
        JOIN substances s ON mc.inchi_id = s.inchi_id
        WHERE mc.mc_id = ?
    """, (mc_id,))
    result = self.cursor.fetchone()

    if not result:
        return None

    # Get components
    components = self.get_components(mc_id)

    return {
        'mc_id': mc_id,
        'inchi_id': result[0],
        'inchi': result[1],
        'inchikey': result[2],
        'components': components
    }
is_in_cleanventory(cas=None, inchi_id=None)

Check if a chemical is in the Cleanventory database.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None

Returns:

Type Description
bool

True if chemical is in Cleanventory, False otherwise. A CAS number is resolved to its rank-1 structure first.

Raises:

Type Description
ValueError

If neither cas nor inchi_id is given.

Examples:

>>> zpm = ZeroPM()
>>> zpm.is_in_cleanventory(cas="50-00-0"), zpm.is_in_cleanventory(cas="0-00-0")
(True, False)
Source code in src/provesid/zeropm.py
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
def is_in_cleanventory(self, cas=None, inchi_id=None):
    """
    Check if a chemical is in the Cleanventory database.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier

    Returns
    -------
    bool
        True if chemical is in Cleanventory, False otherwise. A CAS
        number is resolved to its rank-1 structure first.

    Raises
    ------
    ValueError
        If neither ``cas`` nor ``inchi_id`` is given.

    Examples
    --------
    >>> zpm = ZeroPM()
    >>> zpm.is_in_cleanventory(cas="50-00-0"), zpm.is_in_cleanventory(cas="0-00-0")
    (True, False)
    """
    if inchi_id is None:
        if cas is None:
            raise ValueError("Either cas or inchi_id must be provided")
        query_id = self.query_cas(cas)
        if query_id is None:
            return False
        inchi_ids, _ = self.get_inchi_id(query_id)
        if not inchi_ids:
            return False
        inchi_id = inchi_ids[0]

    self.cursor.execute("""
        SELECT cleanventory_id
        FROM cleanventory_chemicals
        WHERE inchi_id = ?
    """, (inchi_id,))
    return self.cursor.fetchone() is not None
get_consensus_score(cas=None, inchi_id=None)

Get consensus scoring information for a chemical.

Parameters:

Name Type Description Default
cas str

CAS Registry Number

None
inchi_id int

InChI identifier

None

Returns:

Type Description
list of dict or None

List of consensus scores from different inventories, each with:

  • inventory_id: Inventory identifier
  • consensus_score: Consensus score value
  • consensus_count: Count of consensus Returns None if not found. The values are as stored: in v0.0.4 consensus_score is a string of a small integer and consensus_count a fraction between 0 and 1.

Raises:

Type Description
ValueError

If neither cas nor inchi_id is given.

Examples:

>>> scores = ZeroPM().get_consensus_score(cas="50-00-0")
>>> scores[0]
{'inventory_id': 692, 'consensus_score': '2', 'consensus_count': 0.198675496688742}
Source code in src/provesid/zeropm.py
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
def get_consensus_score(self, cas=None, inchi_id=None):
    """
    Get consensus scoring information for a chemical.

    Parameters
    ----------
    cas : str, optional
        CAS Registry Number
    inchi_id : int, optional
        InChI identifier

    Returns
    -------
    list of dict or None
        List of consensus scores from different inventories, each with:

        - inventory_id: Inventory identifier
        - consensus_score: Consensus score value
        - consensus_count: Count of consensus
        Returns None if not found. The values are as stored: in v0.0.4
        ``consensus_score`` is a string of a small integer and
        ``consensus_count`` a fraction between 0 and 1.

    Raises
    ------
    ValueError
        If neither ``cas`` nor ``inchi_id`` is given.

    Examples
    --------
    >>> scores = ZeroPM().get_consensus_score(cas="50-00-0")
    >>> scores[0]
    {'inventory_id': 692, 'consensus_score': '2', 'consensus_count': 0.198675496688742}
    """
    if inchi_id is None:
        if cas is None:
            raise ValueError("Either cas or inchi_id must be provided")
        query_id = self.query_cas(cas)
        if query_id is None:
            return None
        inchi_ids, _ = self.get_inchi_id(query_id)
        if not inchi_ids:
            return None
        inchi_id = inchi_ids[0]

    self.cursor.execute("""
        SELECT inventory_id, consensus_score, consensus_count
        FROM consensus_index
        WHERE inchi_id = ?
    """, (inchi_id,))

    results = self.cursor.fetchall()
    if not results:
        return None

    consensus_data = []
    for row in results:
        consensus_data.append({
            'inventory_id': row[0],
            'consensus_score': row[1],
            'consensus_count': row[2]
        })

    return consensus_data
get_all_zeropm_chemicals(limit=None, include_pm_probs=False)

Get all chemicals in the ZeroPM database.

Parameters:

Name Type Description Default
limit int

Maximum number of results to return

None
include_pm_probs bool

If True, include P/M probability data (default: False)

False

Returns:

Type Description
DataFrame

DataFrame with zeropm_id, inchi_id, inchi, inchikey If include_pm_probs=True, also includes all probability columns, NaN where none were published

Examples:

>>> df = ZeroPM().get_all_zeropm_chemicals(limit=2, include_pm_probs=True)
>>> df[["zeropm_id", "inchi_id", "probability_of_p", "n"]].round(3)
   zeropm_id  inchi_id  probability_of_p  n
0          1      6210             0.400  1
1          2    101901             0.438  1
Source code in src/provesid/zeropm.py
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
def get_all_zeropm_chemicals(self, limit=None, include_pm_probs=False):
    """
    Get all chemicals in the ZeroPM database.

    Parameters
    ----------
    limit : int, optional
        Maximum number of results to return
    include_pm_probs : bool, optional
        If True, include P/M probability data (default: False)

    Returns
    -------
    pandas.DataFrame
        DataFrame with zeropm_id, inchi_id, inchi, inchikey
        If include_pm_probs=True, also includes all probability columns,
        NaN where none were published

    Examples
    --------
    >>> df = ZeroPM().get_all_zeropm_chemicals(limit=2, include_pm_probs=True)
    >>> df[["zeropm_id", "inchi_id", "probability_of_p", "n"]].round(3)
       zeropm_id  inchi_id  probability_of_p  n
    0          1      6210             0.400  1
    1          2    101901             0.438  1
    """
    if include_pm_probs:
        query = f"""
            SELECT zc.zeropm_id, zc.inchi_id, s.inchi, s.inchikey,
                   {_PM_PROBABILITY_SELECT}
            FROM zeropm_chemicals zc
            JOIN substances s ON zc.inchi_id = s.inchi_id
            LEFT JOIN pm_probabilities pm ON zc.inchi_id = pm.inchi_id
        """
        columns = ['zeropm_id', 'inchi_id', 'inchi', 'inchikey',
                   *PM_PROBABILITY_COLUMNS]
    else:
        query = """
            SELECT zc.zeropm_id, zc.inchi_id, s.inchi, s.inchikey
            FROM zeropm_chemicals zc
            JOIN substances s ON zc.inchi_id = s.inchi_id
        """
        columns = ['zeropm_id', 'inchi_id', 'inchi', 'inchikey']

    if limit:
        query += f" LIMIT {limit}"

    self.cursor.execute(query)
    results = self.cursor.fetchall()

    return pd.DataFrame(results, columns=columns)
get_all_multicomponent_substances(limit=None)

Get all multi-component substances.

Parameters:

Name Type Description Default
limit int

Maximum number of results to return

None

Returns:

Type Description
DataFrame

DataFrame with mc_id, inchi_id, inchi, inchikey, component_count

Examples:

>>> ZeroPM().get_all_multicomponent_substances(limit=2)[["mc_id", "inchi_id", "component_count"]]
   mc_id  inchi_id  component_count
0      1         5                2
1      2         6                2
Source code in src/provesid/zeropm.py
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
def get_all_multicomponent_substances(self, limit=None):
    """
    Get all multi-component substances.

    Parameters
    ----------
    limit : int, optional
        Maximum number of results to return

    Returns
    -------
    pandas.DataFrame
        DataFrame with mc_id, inchi_id, inchi, inchikey, component_count

    Examples
    --------
    >>> ZeroPM().get_all_multicomponent_substances(limit=2)[["mc_id", "inchi_id", "component_count"]]
       mc_id  inchi_id  component_count
    0      1         5                2
    1      2         6                2
    """
    query = """
        SELECT mc.mc_id, mc.inchi_id, s.inchi, s.inchikey,
               COUNT(ci.component_id) as component_count
        FROM multi_components mc
        JOIN substances s ON mc.inchi_id = s.inchi_id
        LEFT JOIN component_index ci ON mc.mc_id = ci.mc_id
        GROUP BY mc.mc_id, mc.inchi_id, s.inchi, s.inchikey
    """

    if limit:
        query += f" LIMIT {limit}"

    self.cursor.execute(query)
    results = self.cursor.fetchall()

    return pd.DataFrame(results, columns=['mc_id', 'inchi_id', 'inchi', 'inchikey', 'component_count'])
batch_get_pm_probabilities(cas_list=None, inchi_id_list=None)

Get P/M probabilities for multiple chemicals at once.

Parameters:

Name Type Description Default
cas_list list of str

List of CAS Registry Numbers

None
inchi_id_list list of int

List of InChI identifiers

None

Returns:

Type Description
DataFrame

DataFrame with columns for identifiers and all probability values: one row per chemical ZeroPM assessed, with cas first when cas_list was given. Chemicals it did not assess, and CAS numbers not in the database, have no row; one assessed without published probabilities has NaN. Empty when nothing is found.

Examples:

>>> df = ZeroPM().batch_get_pm_probabilities(cas_list=["50-00-0", "64-17-5", "0-00-0"])
>>> df[["cas", "probability_of_p", "probability_of_vm"]].round(3)
       cas  probability_of_p  probability_of_vm
0  50-00-0               NaN                NaN
1  64-17-5             0.307              0.682
Source code in src/provesid/zeropm.py
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
def batch_get_pm_probabilities(self, cas_list=None, inchi_id_list=None):
    """
    Get P/M probabilities for multiple chemicals at once.

    Parameters
    ----------
    cas_list : list of str, optional
        List of CAS Registry Numbers
    inchi_id_list : list of int, optional
        List of InChI identifiers

    Returns
    -------
    pandas.DataFrame
        DataFrame with columns for identifiers and all probability values:
        one row per chemical ZeroPM assessed, with ``cas`` first when
        ``cas_list`` was given. Chemicals it did not assess, and CAS
        numbers not in the database, have no row; one assessed without
        published probabilities has NaN. Empty when nothing is found.

    Examples
    --------
    >>> df = ZeroPM().batch_get_pm_probabilities(cas_list=["50-00-0", "64-17-5", "0-00-0"])
    >>> df[["cas", "probability_of_p", "probability_of_vm"]].round(3)
           cas  probability_of_p  probability_of_vm
    0  50-00-0               NaN                NaN
    1  64-17-5             0.307              0.682
    """
    if cas_list is not None:
        # Convert CAS to inchi_ids
        inchi_id_list = []
        cas_to_inchi_id = {}
        for cas in cas_list:
            query_id = self.query_cas(cas)
            if query_id:
                inchi_ids, _ = self.get_inchi_id(query_id)
                if inchi_ids:
                    inchi_id = inchi_ids[0]
                    inchi_id_list.append(inchi_id)
                    cas_to_inchi_id[inchi_id] = cas

    if not inchi_id_list:
        return pd.DataFrame()

    # Query all at once
    placeholders = ','.join('?' * len(inchi_id_list))
    query = f"""
        SELECT zc.inchi_id, s.inchi, s.inchikey,
               {_PM_PROBABILITY_SELECT}
        FROM zeropm_chemicals zc
        JOIN substances s ON zc.inchi_id = s.inchi_id
        LEFT JOIN pm_probabilities pm ON zc.inchi_id = pm.inchi_id
        WHERE zc.inchi_id IN ({placeholders})
    """

    self.cursor.execute(query, inchi_id_list)
    results = self.cursor.fetchall()

    df = pd.DataFrame(results, columns=[
        'inchi_id', 'inchi', 'inchikey', *PM_PROBABILITY_COLUMNS
    ])

    # Add CAS if available
    if cas_list is not None:
        df['cas'] = df['inchi_id'].map(cas_to_inchi_id)
        # Reorder columns to put cas first
        cols = ['cas'] + [col for col in df.columns if col != 'cas']
        df = df[cols]

    return df

Functions: