scigantic-comptox 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. scigantic_comptox-0.1.0/LICENSE +16 -0
  2. scigantic_comptox-0.1.0/PKG-INFO +152 -0
  3. scigantic_comptox-0.1.0/README.md +115 -0
  4. scigantic_comptox-0.1.0/pyproject.toml +63 -0
  5. scigantic_comptox-0.1.0/setup.cfg +4 -0
  6. scigantic_comptox-0.1.0/src/scigantic_comptox/__init__.py +62 -0
  7. scigantic_comptox-0.1.0/src/scigantic_comptox/_constants.py +16 -0
  8. scigantic_comptox-0.1.0/src/scigantic_comptox/bioactivity.py +90 -0
  9. scigantic_comptox-0.1.0/src/scigantic_comptox/cache.py +146 -0
  10. scigantic_comptox-0.1.0/src/scigantic_comptox/cli.py +56 -0
  11. scigantic_comptox-0.1.0/src/scigantic_comptox/connection.py +176 -0
  12. scigantic_comptox-0.1.0/src/scigantic_comptox/ctx_cache.py +97 -0
  13. scigantic_comptox-0.1.0/src/scigantic_comptox/ctx_client.py +157 -0
  14. scigantic_comptox-0.1.0/src/scigantic_comptox/pubchem_bridge.py +54 -0
  15. scigantic_comptox-0.1.0/src/scigantic_comptox/py.typed +0 -0
  16. scigantic_comptox-0.1.0/src/scigantic_comptox/releases.py +99 -0
  17. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/PKG-INFO +152 -0
  18. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/SOURCES.txt +27 -0
  19. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/dependency_links.txt +1 -0
  20. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/entry_points.txt +2 -0
  21. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/requires.txt +10 -0
  22. scigantic_comptox-0.1.0/src/scigantic_comptox.egg-info/top_level.txt +1 -0
  23. scigantic_comptox-0.1.0/tests/test_bioactivity.py +64 -0
  24. scigantic_comptox-0.1.0/tests/test_cache.py +58 -0
  25. scigantic_comptox-0.1.0/tests/test_cli.py +16 -0
  26. scigantic_comptox-0.1.0/tests/test_connection.py +30 -0
  27. scigantic_comptox-0.1.0/tests/test_ctx_client.py +93 -0
  28. scigantic_comptox-0.1.0/tests/test_pubchem_bridge.py +21 -0
  29. scigantic_comptox-0.1.0/tests/test_releases.py +54 -0
@@ -0,0 +1,16 @@
1
+ MIT No Attribution
2
+
3
+ Copyright 2026 Scigantic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
6
+ software and associated documentation files (the "Software"), to deal in the Software
7
+ without restriction, including without limitation the rights to use, copy, modify,
8
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
12
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
13
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
14
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
15
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
16
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.4
2
+ Name: scigantic-comptox
3
+ Version: 0.1.0
4
+ Summary: Query EPA's CompTox Chemicals Dashboard: ToxCast bioactivity (winning dose-response model + hit-call per chemical/assay-endpoint) from a public S3 mirror, plus live Chemical/Hazard/Exposure lookups via EPA's CCTE API.
5
+ Author-email: Scigantic <support@scigantic.com>
6
+ License: MIT-0
7
+ Project-URL: Homepage, https://scigantic.com
8
+ Project-URL: Repository, https://github.com/Scigantic/scigantic-comptox
9
+ Project-URL: Issues, https://github.com/Scigantic/scigantic-comptox/issues
10
+ Project-URL: CompTox, https://comptox.epa.gov/dashboard/
11
+ Keywords: epa,comptox,toxcast,toxicology,cheminformatics,bioinformatics,duckdb
12
+ Classifier: License :: OSI Approved :: MIT No Attribution License (MIT-0)
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Typing :: Typed
20
+ Classifier: Development Status :: 4 - Beta
21
+ Classifier: Intended Audience :: Science/Research
22
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
23
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: duckdb<2,>=0.10
28
+ Requires-Dist: pandas<4,>=1.5
29
+ Requires-Dist: requests<3,>=2.28
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5; extra == "dev"
33
+ Requires-Dist: mypy>=1.10; extra == "dev"
34
+ Requires-Dist: pandas-stubs; extra == "dev"
35
+ Requires-Dist: types-requests; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ <h1 align="center">scigantic-comptox</h1>
39
+
40
+ <p align="center">
41
+ <a href="https://github.com/Scigantic/scigantic-comptox/actions/workflows/ci.yml">
42
+ <img alt="CI" src="https://github.com/Scigantic/scigantic-comptox/actions/workflows/ci.yml/badge.svg" /></a>
43
+ <a href="https://pypi.org/project/scigantic-comptox/">
44
+ <img alt="PyPI" src="https://img.shields.io/pypi/v/scigantic-comptox" /></a>
45
+ <a href="https://pypi.org/project/scigantic-comptox/">
46
+ <img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/scigantic-comptox" /></a>
47
+ <a href="https://github.com/Scigantic/scigantic-comptox/blob/main/LICENSE">
48
+ <img alt="License" src="https://img.shields.io/github/license/Scigantic/scigantic-comptox" /></a>
49
+ </p>
50
+
51
+ Query EPA's [CompTox Chemicals Dashboard](https://comptox.epa.gov/dashboard/) from Python. Two halves, and only one of them needs anything from you:
52
+
53
+ - **ToxCast bioactivity**, from a public S3 mirror over DuckDB. No API key, no download, no local database.
54
+ - **Live Chemical/Hazard/Exposure lookups**, over EPA's own CCTE REST API. Optional, and requires your own EPA API key.
55
+
56
+ ```python
57
+ import scigantic_comptox as comptox
58
+
59
+ df = comptox.bioactivity(dtxsid="DTXSID7020182", hitc=1.0)
60
+ ```
61
+
62
+ That query runs against `s3://scigantic-comptox` over DuckDB's httpfs extension.
63
+
64
+ ## Installation
65
+
66
+ ```console
67
+ $ pip install scigantic-comptox
68
+ ```
69
+
70
+ ## What's in the bioactivity mirror
71
+
72
+ Every row is the **winning dose-response model plus hit-call** for one (chemical, ToxCast assay endpoint) pair, from EPA's `invitrodb` v4.3 `mc5-6_winning_model_fits` summary tier: AC50, potency, top, confidence bounds, and `hitc`/`hitcall` (active/inactive/ambiguous). This is the same level of detail as PubChem's own `concise` BioAssay tables, deliberately not the raw well-level plate reads or the full set of *losing* candidate curve models EPA also publishes (`mc4_all_model_fits`) -- that table is what makes EPA's own "summary" download 7GB instead of the ~600MB actually mirrored here; almost nobody needs the losing models, they need the winner.
73
+
74
+ ```python
75
+ comptox.bioactivity(aeid=1114, limit=5)
76
+ ```
77
+
78
+ **A real data-quality issue is handled for you.** EPA's export uses the literal string `"NA"` for missing values in several columns (including `dsstox_substance_id`), not a real SQL `NULL` -- filtering with `IS NOT NULL` silently misses these. `bioactivity()` normalizes this (`NULLIF(..., 'NA')`) so a real `NULL` check works as expected; it also casts columns EPA ships as text purely because of those `"NA"` strings (`ac50`, `bmd`, `top`, and others) to real `DOUBLE`s. Use `bioactivity_raw()` if you want EPA's exact upstream types instead.
79
+
80
+ ## PubChem cross-reference
81
+
82
+ EPA publishes a per-assay-endpoint PubChem CID cross-reference alongside each `invitrodb` release. This wraps the consolidated version of that file:
83
+
84
+ ```python
85
+ comptox.pubchem_bridge(dtxsid="DTXSID7020182")
86
+ ```
87
+
88
+ Pairs naturally with [scigantic-pubchem](https://github.com/Scigantic/scigantic-pubchem)'s own BioAssay/gene/protein coverage.
89
+
90
+ ## What's not mirrored (yet)
91
+
92
+ DSSTox bulk chemical structures aren't mirrored -- EPA's bulk distribution for that turned out to be a large, unstructured institutional drive rather than a clean single file. `comptox.releases()` reports this plainly (`structures: False`) rather than silently missing the data. For now, chemical structure lookup by DTXSID goes through the live REST half below, the same place EPA's own client gets it from.
93
+
94
+ ## The live REST half: bring your own EPA API key
95
+
96
+ EPA's CCTE API needs one, and deliberately doesn't hand out a shared one: their own docs describe it as "an individual API key" that "uniquely identifies the user," issued by emailing `ccte_api@epa.gov` rather than self-serve signup. EPA's own reference client, [`ctx-python`](https://github.com/USEPA/ctx-python), never embeds a key either. This package follows the same rule -- no key ships with it, and none is proxied on your behalf.
97
+
98
+ ```console
99
+ $ export COMPTOX_API_KEY=your-key-here
100
+ ```
101
+
102
+ ```python
103
+ comptox.chemical_detail("DTXSID7020182")
104
+ comptox.hazard_toxval("DTXSID7020182")
105
+ comptox.exposure_httk("DTXSID7020182")
106
+ ```
107
+
108
+ Calling any of these without a key raises `MissingApiKeyError` with a link to how to get one, not a bare 401. Requests are retried with backoff on 429/5xx, and responses are cached for 30 days by default (the opposite default from the mirror half's caching, see below) -- EPA's API has no documented rate limit, but it's still a live government service, not an unlimited public mirror, so repeatedly re-fetching the same lookup in a loop is worth avoiding by default.
109
+
110
+ Endpoint coverage here is intentionally a starting set (one real, verified path per microservice), not a full reimplementation of `ctx-python` -- that package already covers Chemical/Exposure/Hazard comprehensively. This package's actual differentiator is the bioactivity mirror above, which `ctx-python` doesn't cover at all.
111
+
112
+ ## Working offline (mirror half)
113
+
114
+ Off by default, since zero setup is the whole point of the mirror:
115
+
116
+ ```python
117
+ comptox.enable_cache()
118
+ df = comptox.pubchem_bridge() # downloads the file once, then reads from disk
119
+ ```
120
+
121
+ Downloads to `~/.cache/scigantic-comptox` (override with `enable_cache(cache_dir=...)` or the `SCIGANTIC_COMPTOX_CACHE` environment variable). Concurrent callers racing the first download of the same file wait for it rather than each downloading their own copy.
122
+
123
+ `connect()`, `query()`, and `bioactivity()` don't participate in this (registering the underlying views eagerly would mean the first call for any release downloads the full ~600MB regardless of what the query actually touches); use `comptox.cache_resolve("v4_3/derived/pubchem_bridge.parquet")` to cache a specific file yourself.
124
+
125
+ The live REST half has its own separate cache, ON by default (`comptox.disable_ctx_cache()` to turn it off) -- see above for why the two halves use opposite defaults.
126
+
127
+ ## What's mirrored
128
+
129
+ ```python
130
+ comptox.releases()
131
+ ```
132
+
133
+ | release | bioactivity | pubchem bridge | structures |
134
+ |---|---|---|---|
135
+ | v4_3 | yes | yes | no |
136
+
137
+ This table isn't hardcoded. `releases()` reads a small manifest published alongside each mirror run.
138
+
139
+ ## Command line
140
+
141
+ ```console
142
+ $ scigantic-comptox info
143
+ $ scigantic-comptox query "SELECT count(*) FROM bioactivity" --release v4_3
144
+ ```
145
+
146
+ ## License
147
+
148
+ MIT-0. See [LICENSE](LICENSE). This covers the code in this package only.
149
+
150
+ ## Data license
151
+
152
+ EPA's `invitrodb` v4.3 (ToxCast bioactivity data) is [CC0](https://creativecommons.org/publicdomain/zero/1.0/) -- public domain, no attribution or share-alike terms to track. A courtesy citation is appreciated, not required: Filer, D.L. et al. (2017), *tcpl: the ToxCast pipeline for high-throughput screening data*, Bioinformatics, [doi:10.1093/bioinformatics/btw680](https://doi.org/10.1093/bioinformatics/btw680).
@@ -0,0 +1,115 @@
1
+ <h1 align="center">scigantic-comptox</h1>
2
+
3
+ <p align="center">
4
+ <a href="https://github.com/Scigantic/scigantic-comptox/actions/workflows/ci.yml">
5
+ <img alt="CI" src="https://github.com/Scigantic/scigantic-comptox/actions/workflows/ci.yml/badge.svg" /></a>
6
+ <a href="https://pypi.org/project/scigantic-comptox/">
7
+ <img alt="PyPI" src="https://img.shields.io/pypi/v/scigantic-comptox" /></a>
8
+ <a href="https://pypi.org/project/scigantic-comptox/">
9
+ <img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/scigantic-comptox" /></a>
10
+ <a href="https://github.com/Scigantic/scigantic-comptox/blob/main/LICENSE">
11
+ <img alt="License" src="https://img.shields.io/github/license/Scigantic/scigantic-comptox" /></a>
12
+ </p>
13
+
14
+ Query EPA's [CompTox Chemicals Dashboard](https://comptox.epa.gov/dashboard/) from Python. Two halves, and only one of them needs anything from you:
15
+
16
+ - **ToxCast bioactivity**, from a public S3 mirror over DuckDB. No API key, no download, no local database.
17
+ - **Live Chemical/Hazard/Exposure lookups**, over EPA's own CCTE REST API. Optional, and requires your own EPA API key.
18
+
19
+ ```python
20
+ import scigantic_comptox as comptox
21
+
22
+ df = comptox.bioactivity(dtxsid="DTXSID7020182", hitc=1.0)
23
+ ```
24
+
25
+ That query runs against `s3://scigantic-comptox` over DuckDB's httpfs extension.
26
+
27
+ ## Installation
28
+
29
+ ```console
30
+ $ pip install scigantic-comptox
31
+ ```
32
+
33
+ ## What's in the bioactivity mirror
34
+
35
+ Every row is the **winning dose-response model plus hit-call** for one (chemical, ToxCast assay endpoint) pair, from EPA's `invitrodb` v4.3 `mc5-6_winning_model_fits` summary tier: AC50, potency, top, confidence bounds, and `hitc`/`hitcall` (active/inactive/ambiguous). This is the same level of detail as PubChem's own `concise` BioAssay tables, deliberately not the raw well-level plate reads or the full set of *losing* candidate curve models EPA also publishes (`mc4_all_model_fits`) -- that table is what makes EPA's own "summary" download 7GB instead of the ~600MB actually mirrored here; almost nobody needs the losing models, they need the winner.
36
+
37
+ ```python
38
+ comptox.bioactivity(aeid=1114, limit=5)
39
+ ```
40
+
41
+ **A real data-quality issue is handled for you.** EPA's export uses the literal string `"NA"` for missing values in several columns (including `dsstox_substance_id`), not a real SQL `NULL` -- filtering with `IS NOT NULL` silently misses these. `bioactivity()` normalizes this (`NULLIF(..., 'NA')`) so a real `NULL` check works as expected; it also casts columns EPA ships as text purely because of those `"NA"` strings (`ac50`, `bmd`, `top`, and others) to real `DOUBLE`s. Use `bioactivity_raw()` if you want EPA's exact upstream types instead.
42
+
43
+ ## PubChem cross-reference
44
+
45
+ EPA publishes a per-assay-endpoint PubChem CID cross-reference alongside each `invitrodb` release. This wraps the consolidated version of that file:
46
+
47
+ ```python
48
+ comptox.pubchem_bridge(dtxsid="DTXSID7020182")
49
+ ```
50
+
51
+ Pairs naturally with [scigantic-pubchem](https://github.com/Scigantic/scigantic-pubchem)'s own BioAssay/gene/protein coverage.
52
+
53
+ ## What's not mirrored (yet)
54
+
55
+ DSSTox bulk chemical structures aren't mirrored -- EPA's bulk distribution for that turned out to be a large, unstructured institutional drive rather than a clean single file. `comptox.releases()` reports this plainly (`structures: False`) rather than silently missing the data. For now, chemical structure lookup by DTXSID goes through the live REST half below, the same place EPA's own client gets it from.
56
+
57
+ ## The live REST half: bring your own EPA API key
58
+
59
+ EPA's CCTE API needs one, and deliberately doesn't hand out a shared one: their own docs describe it as "an individual API key" that "uniquely identifies the user," issued by emailing `ccte_api@epa.gov` rather than self-serve signup. EPA's own reference client, [`ctx-python`](https://github.com/USEPA/ctx-python), never embeds a key either. This package follows the same rule -- no key ships with it, and none is proxied on your behalf.
60
+
61
+ ```console
62
+ $ export COMPTOX_API_KEY=your-key-here
63
+ ```
64
+
65
+ ```python
66
+ comptox.chemical_detail("DTXSID7020182")
67
+ comptox.hazard_toxval("DTXSID7020182")
68
+ comptox.exposure_httk("DTXSID7020182")
69
+ ```
70
+
71
+ Calling any of these without a key raises `MissingApiKeyError` with a link to how to get one, not a bare 401. Requests are retried with backoff on 429/5xx, and responses are cached for 30 days by default (the opposite default from the mirror half's caching, see below) -- EPA's API has no documented rate limit, but it's still a live government service, not an unlimited public mirror, so repeatedly re-fetching the same lookup in a loop is worth avoiding by default.
72
+
73
+ Endpoint coverage here is intentionally a starting set (one real, verified path per microservice), not a full reimplementation of `ctx-python` -- that package already covers Chemical/Exposure/Hazard comprehensively. This package's actual differentiator is the bioactivity mirror above, which `ctx-python` doesn't cover at all.
74
+
75
+ ## Working offline (mirror half)
76
+
77
+ Off by default, since zero setup is the whole point of the mirror:
78
+
79
+ ```python
80
+ comptox.enable_cache()
81
+ df = comptox.pubchem_bridge() # downloads the file once, then reads from disk
82
+ ```
83
+
84
+ Downloads to `~/.cache/scigantic-comptox` (override with `enable_cache(cache_dir=...)` or the `SCIGANTIC_COMPTOX_CACHE` environment variable). Concurrent callers racing the first download of the same file wait for it rather than each downloading their own copy.
85
+
86
+ `connect()`, `query()`, and `bioactivity()` don't participate in this (registering the underlying views eagerly would mean the first call for any release downloads the full ~600MB regardless of what the query actually touches); use `comptox.cache_resolve("v4_3/derived/pubchem_bridge.parquet")` to cache a specific file yourself.
87
+
88
+ The live REST half has its own separate cache, ON by default (`comptox.disable_ctx_cache()` to turn it off) -- see above for why the two halves use opposite defaults.
89
+
90
+ ## What's mirrored
91
+
92
+ ```python
93
+ comptox.releases()
94
+ ```
95
+
96
+ | release | bioactivity | pubchem bridge | structures |
97
+ |---|---|---|---|
98
+ | v4_3 | yes | yes | no |
99
+
100
+ This table isn't hardcoded. `releases()` reads a small manifest published alongside each mirror run.
101
+
102
+ ## Command line
103
+
104
+ ```console
105
+ $ scigantic-comptox info
106
+ $ scigantic-comptox query "SELECT count(*) FROM bioactivity" --release v4_3
107
+ ```
108
+
109
+ ## License
110
+
111
+ MIT-0. See [LICENSE](LICENSE). This covers the code in this package only.
112
+
113
+ ## Data license
114
+
115
+ EPA's `invitrodb` v4.3 (ToxCast bioactivity data) is [CC0](https://creativecommons.org/publicdomain/zero/1.0/) -- public domain, no attribution or share-alike terms to track. A courtesy citation is appreciated, not required: Filer, D.L. et al. (2017), *tcpl: the ToxCast pipeline for high-throughput screening data*, Bioinformatics, [doi:10.1093/bioinformatics/btw680](https://doi.org/10.1093/bioinformatics/btw680).
@@ -0,0 +1,63 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scigantic-comptox"
7
+ version = "0.1.0"
8
+ description = "Query EPA's CompTox Chemicals Dashboard: ToxCast bioactivity (winning dose-response model + hit-call per chemical/assay-endpoint) from a public S3 mirror, plus live Chemical/Hazard/Exposure lookups via EPA's CCTE API."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT-0" }
12
+ authors = [{ name = "Scigantic", email = "support@scigantic.com" }]
13
+ keywords = ["epa", "comptox", "toxcast", "toxicology", "cheminformatics", "bioinformatics", "duckdb"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: MIT No Attribution License (MIT-0)",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Typing :: Typed",
23
+ "Development Status :: 4 - Beta",
24
+ "Intended Audience :: Science/Research",
25
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
26
+ "Topic :: Scientific/Engineering :: Chemistry",
27
+ ]
28
+
29
+ dependencies = [
30
+ "duckdb>=0.10,<2",
31
+ "pandas>=1.5,<4",
32
+ "requests>=2.28,<3",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest>=7", "pytest-cov>=5", "mypy>=1.10", "pandas-stubs", "types-requests"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://scigantic.com"
40
+ Repository = "https://github.com/Scigantic/scigantic-comptox"
41
+ Issues = "https://github.com/Scigantic/scigantic-comptox/issues"
42
+ CompTox = "https://comptox.epa.gov/dashboard/"
43
+
44
+ [project.scripts]
45
+ scigantic-comptox = "scigantic_comptox.cli:main"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["src"]
49
+
50
+ [tool.setuptools.package-data]
51
+ scigantic_comptox = ["py.typed"]
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
55
+
56
+ [tool.coverage.run]
57
+ source = ["scigantic_comptox"]
58
+ # Not wired into CI as a gate: the mirror-half suite runs real queries
59
+ # against the live S3 mirror, so a coverage threshold would be one more
60
+ # thing that can fail for reasons unrelated to a change.
61
+
62
+ [tool.mypy]
63
+ strict = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,62 @@
1
+ """Query EPA's CompTox Chemicals Dashboard: ToxCast bioactivity from a
2
+ public S3 mirror (no API key), plus live Chemical/Hazard/Exposure lookups
3
+ via EPA's CCTE API (bring your own key)."""
4
+
5
+ from importlib.metadata import PackageNotFoundError, version as _version
6
+
7
+ from .bioactivity import bioactivity, bioactivity_raw
8
+ from .cache import cache_dir, disable_cache, enable_cache, is_cache_enabled
9
+ from .cache import resolve as cache_resolve
10
+ from .connection import connect, query
11
+ from .ctx_cache import disable_ctx_cache, enable_ctx_cache, is_ctx_cache_enabled
12
+ from .ctx_client import (
13
+ CtxApiError,
14
+ MissingApiKeyError,
15
+ chemical_detail,
16
+ ctx_get,
17
+ exposure_httk,
18
+ hazard_toxval,
19
+ )
20
+ from .pubchem_bridge import pubchem_bridge
21
+ from .releases import (
22
+ ReleaseCapabilityError,
23
+ ReleaseInfo,
24
+ UnknownReleaseError,
25
+ latest,
26
+ releases,
27
+ )
28
+
29
+ try:
30
+ __version__ = _version("scigantic-comptox")
31
+ except PackageNotFoundError:
32
+ # Running from a source checkout with no install (editable or not).
33
+ __version__ = "0.0.0"
34
+
35
+ __all__ = [
36
+ # mirror half
37
+ "connect",
38
+ "query",
39
+ "bioactivity",
40
+ "bioactivity_raw",
41
+ "pubchem_bridge",
42
+ "releases",
43
+ "latest",
44
+ "enable_cache",
45
+ "disable_cache",
46
+ "is_cache_enabled",
47
+ "cache_dir",
48
+ "cache_resolve",
49
+ "ReleaseInfo",
50
+ "ReleaseCapabilityError",
51
+ "UnknownReleaseError",
52
+ # live REST half
53
+ "ctx_get",
54
+ "chemical_detail",
55
+ "hazard_toxval",
56
+ "exposure_httk",
57
+ "CtxApiError",
58
+ "MissingApiKeyError",
59
+ "enable_ctx_cache",
60
+ "disable_ctx_cache",
61
+ "is_ctx_cache_enabled",
62
+ ]
@@ -0,0 +1,16 @@
1
+ """Shared constants: where the mirror lives, and the live CCTE API base."""
2
+
3
+ BUCKET = "scigantic-comptox"
4
+ REGION = "us-east-1"
5
+
6
+ # EPA's Computational Toxicology and Exposure (CCTE) REST API. Requires an
7
+ # individual API key (see ctx_client.py) -- EPA's own docs describe it as
8
+ # "an individual API key" that "uniquely identifies the user", and issuance
9
+ # is manually gated through ccte_api@epa.gov rather than self-serve. EPA's
10
+ # own reference client (github.com/USEPA/ctx-python) never embeds a key and
11
+ # always requires the caller to supply their own; this package does the
12
+ # same, deliberately, rather than proxying a shared Scigantic-side key.
13
+ CTX_API_BASE = "https://api-ccte.epa.gov"
14
+ CTX_API_KEY_ENV = "COMPTOX_API_KEY"
15
+ CTX_API_INFO_URL = "https://www.epa.gov/comptox-tools/computational-toxicology-and-exposure-apis-about"
16
+ CTX_API_KEY_CONTACT = "ccte_api@epa.gov"
@@ -0,0 +1,90 @@
1
+ """ToxCast bioactivity: the winning dose-response model and hit-call for
2
+ each (chemical, assay endpoint) pair, from EPA's `invitrodb` v4.3 summary
3
+ tier (`mc5-6_winning_model_fits`), the same level of detail as PubChem's
4
+ own `concise` BioAssay tables. This is the real, verified gap versus EPA's
5
+ own `ctx-python` client, which covers Chemical/Exposure/Hazard but not
6
+ Bioactivity/ToxCast at all.
7
+
8
+ Deliberately NOT mirrored: `mc4_all_model_fits` (every losing candidate
9
+ curve model alongside the winner) -- that's what made EPA's "summary"
10
+ bundle grow from 1.5GB at v3.3 to 7.0GB at v4.3, for detail almost no
11
+ caller needs (the winning model plus hit-call is what a bioactivity lookup
12
+ actually wants).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING
18
+
19
+ from .connection import connect
20
+ from .releases import _require, latest
21
+
22
+ if TYPE_CHECKING:
23
+ import pandas as pd
24
+
25
+
26
+ def bioactivity(
27
+ dtxsid: str | None = None,
28
+ aeid: int | None = None,
29
+ hitc: float | None = None,
30
+ release: str | None = None,
31
+ limit: int | None = None,
32
+ ) -> "pd.DataFrame":
33
+ """Winning-model bioactivity results, optionally filtered.
34
+
35
+ dtxsid: a single DSSTox substance id (e.g. "DTXSID7020182"), matched
36
+ against the normalized dsstox_substance_id column (the raw "NA" string
37
+ EPA's export uses for missing values is already excluded, see
38
+ connection.py).
39
+ aeid: a single ToxCast assay endpoint id.
40
+ hitc: filter to an exact hit-call value (1.0 = active, 0.0 = inactive,
41
+ other fractional values represent ambiguous/borderline calls per EPA's
42
+ own tcpl methodology).
43
+ release defaults to the manifest's current latest().
44
+ """
45
+ release = release or latest()
46
+ _require(release, "bioactivity")
47
+ con = connect(release)
48
+ try:
49
+ where: list[str] = []
50
+ params: list[str | int | float] = []
51
+ if dtxsid is not None:
52
+ where.append("dsstox_substance_id = ?")
53
+ params.append(dtxsid)
54
+ if aeid is not None:
55
+ where.append("aeid = ?")
56
+ params.append(aeid)
57
+ if hitc is not None:
58
+ where.append("hitc = ?")
59
+ params.append(hitc)
60
+ clause = f"WHERE {' AND '.join(where)}" if where else ""
61
+ sql = f"SELECT * FROM bioactivity {clause}"
62
+ if limit is not None:
63
+ sql += " LIMIT ?"
64
+ params.append(int(limit))
65
+ return con.execute(sql, params).df()
66
+ finally:
67
+ con.close()
68
+
69
+
70
+ def bioactivity_raw(
71
+ release: str | None = None,
72
+ limit: int | None = None,
73
+ ) -> "pd.DataFrame":
74
+ """The winning-model table exactly as EPA ships it, with no
75
+ normalization: the literal "NA" strings and text-typed numeric columns
76
+ (ac50, bmd, top, and others -- see connection.py's module docstring)
77
+ are left as-is. Use bioactivity() for a cleaned version.
78
+ """
79
+ release = release or latest()
80
+ _require(release, "bioactivity")
81
+ con = connect(release)
82
+ try:
83
+ sql = "SELECT * FROM bioactivity_raw"
84
+ params: list[int] = []
85
+ if limit is not None:
86
+ sql += " LIMIT ?"
87
+ params.append(int(limit))
88
+ return con.execute(sql, params).df()
89
+ finally:
90
+ con.close()
@@ -0,0 +1,146 @@
1
+ """Optional local caching for the mirror half: download once, then work
2
+ with no network.
3
+
4
+ Off by default, matching scigantic-chembl/scigantic-bindingdb's convention
5
+ for a public S3 mirror with no meaningful rate limit -- caching is a pure
6
+ convenience here, opt-in rather than a default that changes behavior:
7
+
8
+ import scigantic_comptox as comptox
9
+ comptox.enable_cache()
10
+
11
+ This is the mirror half's cache only. The live REST half (ctx_client.py)
12
+ has its own separate cache, default ON with a TTL, since that side calls a
13
+ real government API per lookup rather than reading an unlimited public
14
+ mirror -- see ctx_cache.py for why that default is the opposite of this
15
+ one.
16
+
17
+ connect() / query() / bioactivity() / pubchem_bridge() do not use this:
18
+ connect() registers views on every call to the shared base connection, so
19
+ caching would mean eagerly downloading a 600+ MB file regardless of what a
20
+ query actually touches. Use cache_resolve("<release>/<path>.parquet") to
21
+ pull a specific file locally and read it directly with read_parquet(...).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ import sys
28
+ import threading
29
+ import urllib.request
30
+ import uuid
31
+ from pathlib import Path
32
+
33
+ from ._constants import BUCKET, REGION
34
+
35
+ _enabled = False
36
+ _cache_dir: Path | None = None
37
+
38
+ _CHUNK_BYTES = 1024 * 1024
39
+
40
+ # One lock per key, guarding resolve()'s check-then-download against
41
+ # concurrent callers asking for the same key at once. Ported from
42
+ # scigantic-bindingdb's cache.py, which measured this as a real bug: 16
43
+ # threads racing an empty cache each triggered a full separate download
44
+ # before this fix.
45
+ _resolve_locks: dict[str, threading.Lock] = {}
46
+ _resolve_locks_guard = threading.Lock()
47
+
48
+
49
+ def _lock_for(key: str) -> threading.Lock:
50
+ lock = _resolve_locks.get(key)
51
+ if lock is not None:
52
+ return lock
53
+ with _resolve_locks_guard:
54
+ return _resolve_locks.setdefault(key, threading.Lock())
55
+
56
+
57
+ def _default_cache_dir() -> Path:
58
+ if sys.platform == "win32":
59
+ base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
60
+ elif sys.platform == "darwin":
61
+ base = str(Path.home() / "Library" / "Caches")
62
+ else:
63
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
64
+ return Path(base) / "scigantic-comptox"
65
+
66
+
67
+ def enable_cache(cache_dir: str | None = None) -> Path:
68
+ """Turn on local caching for the mirror half.
69
+
70
+ Cache location: `cache_dir` if given, else the SCIGANTIC_COMPTOX_CACHE
71
+ environment variable, else a platform-appropriate user cache directory.
72
+ Returns the resolved directory.
73
+ """
74
+ global _enabled, _cache_dir
75
+ if cache_dir is not None:
76
+ resolved = Path(cache_dir)
77
+ elif os.environ.get("SCIGANTIC_COMPTOX_CACHE"):
78
+ resolved = Path(os.environ["SCIGANTIC_COMPTOX_CACHE"])
79
+ else:
80
+ resolved = _default_cache_dir()
81
+ resolved.mkdir(parents=True, exist_ok=True)
82
+ _cache_dir = resolved
83
+ _enabled = True
84
+ return resolved
85
+
86
+
87
+ def disable_cache() -> None:
88
+ """Turn caching back off. Later calls go straight to S3 again.
89
+
90
+ Anything already downloaded stays on disk; this only stops using it.
91
+ """
92
+ global _enabled
93
+ _enabled = False
94
+
95
+
96
+ def is_cache_enabled() -> bool:
97
+ return _enabled
98
+
99
+
100
+ def cache_dir() -> Path | None:
101
+ """The resolved cache directory, or None if caching has never been enabled."""
102
+ return _cache_dir
103
+
104
+
105
+ def _atomic_download(url: str, local_path: Path) -> None:
106
+ """Stream `url` to a sibling temp file, then rename it into place.
107
+
108
+ The temp filename is unique per call (UUID-suffixed), not shared per
109
+ `local_path`: two threads racing to fill the same key must not share a
110
+ temp path, or the second os.replace() raises FileNotFoundError once the
111
+ first has already consumed it -- the exact bug scigantic-chembl's
112
+ original cache.py had and scigantic-bindingdb fixed; this package
113
+ starts from the fixed version.
114
+ """
115
+ tmp_path = local_path.with_name(local_path.name + f".{uuid.uuid4().hex}.part")
116
+ with urllib.request.urlopen(url) as response, open(tmp_path, "wb") as fh:
117
+ while chunk := response.read(_CHUNK_BYTES):
118
+ fh.write(chunk)
119
+ os.replace(tmp_path, local_path)
120
+
121
+
122
+ def resolve(key: str) -> str:
123
+ """An S3 URL, or a local cached file path if caching is on.
124
+
125
+ `key` is a path relative to the bucket root, e.g.
126
+ "v4_3/derived/pubchem_bridge.parquet". Downloads to the cache on first
127
+ access; later calls for the same key reuse the local file. Concurrent
128
+ callers asking for the same key while it's still downloading wait for
129
+ that download rather than each starting their own.
130
+ """
131
+ if not _enabled:
132
+ return f"s3://{BUCKET}/{key}"
133
+
134
+ assert _cache_dir is not None
135
+ local_path = _cache_dir / key
136
+ if local_path.exists():
137
+ return str(local_path)
138
+
139
+ with _lock_for(key):
140
+ if local_path.exists(): # another thread finished it while we waited
141
+ return str(local_path)
142
+ local_path.parent.mkdir(parents=True, exist_ok=True)
143
+ url = f"https://{BUCKET}.s3.{REGION}.amazonaws.com/{key}"
144
+ print(f"scigantic-comptox: caching {key} ...", file=sys.stderr, flush=True)
145
+ _atomic_download(url, local_path)
146
+ return str(local_path)