scigantic-comptox 0.1.0__py3-none-any.whl
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.
- scigantic_comptox/__init__.py +62 -0
- scigantic_comptox/_constants.py +16 -0
- scigantic_comptox/bioactivity.py +90 -0
- scigantic_comptox/cache.py +146 -0
- scigantic_comptox/cli.py +56 -0
- scigantic_comptox/connection.py +176 -0
- scigantic_comptox/ctx_cache.py +97 -0
- scigantic_comptox/ctx_client.py +157 -0
- scigantic_comptox/pubchem_bridge.py +54 -0
- scigantic_comptox/py.typed +0 -0
- scigantic_comptox/releases.py +99 -0
- scigantic_comptox-0.1.0.dist-info/METADATA +152 -0
- scigantic_comptox-0.1.0.dist-info/RECORD +17 -0
- scigantic_comptox-0.1.0.dist-info/WHEEL +5 -0
- scigantic_comptox-0.1.0.dist-info/entry_points.txt +2 -0
- scigantic_comptox-0.1.0.dist-info/licenses/LICENSE +16 -0
- scigantic_comptox-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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)
|
scigantic_comptox/cli.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Command-line interface: `scigantic-comptox info` and `scigantic-comptox query`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Sequence, cast
|
|
8
|
+
|
|
9
|
+
from .connection import query as run_query
|
|
10
|
+
from .releases import releases
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _cmd_info(_args: argparse.Namespace) -> int:
|
|
14
|
+
for info in releases():
|
|
15
|
+
derived = [
|
|
16
|
+
name
|
|
17
|
+
for name, present in (
|
|
18
|
+
("bioactivity", info.bioactivity),
|
|
19
|
+
("pubchem_bridge", info.pubchem_bridge),
|
|
20
|
+
("structures", info.structures),
|
|
21
|
+
)
|
|
22
|
+
if present
|
|
23
|
+
]
|
|
24
|
+
suffix = f" + {', '.join(derived)}" if derived else " (nothing mirrored yet)"
|
|
25
|
+
print(f"{info.release}{suffix}")
|
|
26
|
+
return 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _cmd_query(args: argparse.Namespace) -> int:
|
|
30
|
+
df = run_query(args.sql, release=args.release)
|
|
31
|
+
print(df.to_csv(sep="\t", index=False), end="")
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
36
|
+
parser = argparse.ArgumentParser(prog="scigantic-comptox")
|
|
37
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
38
|
+
|
|
39
|
+
info_parser = subparsers.add_parser(
|
|
40
|
+
"info", help="list mirrored releases and what each one supports"
|
|
41
|
+
)
|
|
42
|
+
info_parser.set_defaults(func=_cmd_info)
|
|
43
|
+
|
|
44
|
+
query_parser = subparsers.add_parser(
|
|
45
|
+
"query", help="run SQL against a release and print tab-separated output"
|
|
46
|
+
)
|
|
47
|
+
query_parser.add_argument("sql")
|
|
48
|
+
query_parser.add_argument("--release", default=None, help="defaults to the current release")
|
|
49
|
+
query_parser.set_defaults(func=_cmd_query)
|
|
50
|
+
|
|
51
|
+
args = parser.parse_args(argv)
|
|
52
|
+
return cast(int, args.func(args))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if __name__ == "__main__":
|
|
56
|
+
sys.exit(main())
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""DuckDB connection helpers for the mirror half. Queries run against the
|
|
2
|
+
public S3 mirror over httpfs, no download, no API key.
|
|
3
|
+
|
|
4
|
+
connect() hands out a cursor() on a lazily-created, shared base connection
|
|
5
|
+
per release rather than a brand new duckdb.connect() on every call: setup
|
|
6
|
+
(INSTALL/LOAD httpfs, the anonymous S3 secret, registering the two views
|
|
7
|
+
below) happens once per (release, process), matching scigantic-bindingdb's
|
|
8
|
+
connection.py, which measured this as a real cost when a caller loops a
|
|
9
|
+
query-returning function.
|
|
10
|
+
|
|
11
|
+
The `bioactivity` view normalizes two known data-quality issues in the
|
|
12
|
+
source file rather than leaving them for every caller to rediscover:
|
|
13
|
+
|
|
14
|
+
- `dsstox_substance_id` (and several other identifier columns) use the
|
|
15
|
+
literal string "NA" for a small fraction of rows (~0.3%), not a real SQL
|
|
16
|
+
NULL -- confirmed against the real mirrored data. `IS NOT NULL` silently
|
|
17
|
+
misses these; the view applies NULLIF(..., 'NA') so a real NULL check
|
|
18
|
+
works as expected.
|
|
19
|
+
- Several genuinely numeric columns (ac50, bmd, top, bmdl, bmdu, rmse, and
|
|
20
|
+
others -- EPA's own CSV export ships these as text because "NA" rows
|
|
21
|
+
forced the column to infer as a string) are TRY_CAST to DOUBLE here, with
|
|
22
|
+
"NA" treated as NULL first. A value that still fails to parse becomes
|
|
23
|
+
NULL rather than raising, since a handful of non-numeric outliers in a
|
|
24
|
+
~3.5M-row export are expected, not a reason to fail every query.
|
|
25
|
+
|
|
26
|
+
`bioactivity_raw` (in bioactivity.py) reads the file directly with no
|
|
27
|
+
normalization, for anyone who wants the exact upstream types.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import threading
|
|
33
|
+
from typing import TYPE_CHECKING
|
|
34
|
+
|
|
35
|
+
from ._constants import BUCKET, REGION
|
|
36
|
+
from .releases import _validate_release, latest
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
import duckdb
|
|
40
|
+
import pandas as pd
|
|
41
|
+
|
|
42
|
+
# Text columns known to carry the literal string "NA" in place of a real
|
|
43
|
+
# NULL, confirmed against the live mirror.
|
|
44
|
+
_NA_STRING_COLUMNS = (
|
|
45
|
+
"spid",
|
|
46
|
+
"chid",
|
|
47
|
+
"casn",
|
|
48
|
+
"chnm",
|
|
49
|
+
"dsstox_substance_id",
|
|
50
|
+
"code",
|
|
51
|
+
"aenm",
|
|
52
|
+
"modl",
|
|
53
|
+
"fitc",
|
|
54
|
+
"mc6_flags",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Columns that are genuinely numeric but shipped as VARCHAR in EPA's export
|
|
58
|
+
# (see module docstring). TRY_CAST after NULLIF('NA', ...) turns each into a
|
|
59
|
+
# real DOUBLE, NULL on anything that still doesn't parse.
|
|
60
|
+
_NUMERIC_TEXT_COLUMNS = (
|
|
61
|
+
"top_over_cutoff",
|
|
62
|
+
"rmse",
|
|
63
|
+
"a",
|
|
64
|
+
"p",
|
|
65
|
+
"er",
|
|
66
|
+
"bmdl",
|
|
67
|
+
"bmdu",
|
|
68
|
+
"caikwt",
|
|
69
|
+
"mll",
|
|
70
|
+
"ac50",
|
|
71
|
+
"top",
|
|
72
|
+
"ac5",
|
|
73
|
+
"ac10",
|
|
74
|
+
"ac20",
|
|
75
|
+
"ac1sd",
|
|
76
|
+
"bmd",
|
|
77
|
+
"tp",
|
|
78
|
+
"q",
|
|
79
|
+
"ga",
|
|
80
|
+
"la",
|
|
81
|
+
"ac50_loss",
|
|
82
|
+
"b",
|
|
83
|
+
"acc",
|
|
84
|
+
"loec",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _bioactivity_select_list() -> str:
|
|
89
|
+
parts = []
|
|
90
|
+
for col in _NA_STRING_COLUMNS:
|
|
91
|
+
parts.append(f"NULLIF({col}, 'NA') AS {col}")
|
|
92
|
+
for col in _NUMERIC_TEXT_COLUMNS:
|
|
93
|
+
parts.append(f"TRY_CAST(NULLIF({col}, 'NA') AS DOUBLE) AS {col}")
|
|
94
|
+
# Everything else (aeid, m4id, bmad, hitc, hitcall, and the other
|
|
95
|
+
# already-numeric columns, plus the odd "flag.length" name) passes
|
|
96
|
+
# through unchanged via EXCLUDE.
|
|
97
|
+
already_handled = ", ".join(_NA_STRING_COLUMNS + _NUMERIC_TEXT_COLUMNS)
|
|
98
|
+
return f"* EXCLUDE ({already_handled}), " + ", ".join(parts)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_base_cons: dict[str, "duckdb.DuckDBPyConnection"] = {}
|
|
102
|
+
_base_cons_lock = threading.Lock()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _get_base_connection(release: str) -> "duckdb.DuckDBPyConnection":
|
|
106
|
+
con = _base_cons.get(release)
|
|
107
|
+
if con is not None:
|
|
108
|
+
return con
|
|
109
|
+
with _base_cons_lock:
|
|
110
|
+
con = _base_cons.get(release)
|
|
111
|
+
if con is None: # re-check: another thread may have won the race
|
|
112
|
+
import duckdb
|
|
113
|
+
|
|
114
|
+
new_con = duckdb.connect()
|
|
115
|
+
new_con.execute("SET enable_progress_bar=false")
|
|
116
|
+
new_con.execute("INSTALL httpfs")
|
|
117
|
+
new_con.execute("LOAD httpfs")
|
|
118
|
+
new_con.execute(f"SET s3_region='{REGION}'")
|
|
119
|
+
# The mirror is public-read. Without this, DuckDB looks for AWS
|
|
120
|
+
# credentials and fails on a machine that has none configured.
|
|
121
|
+
new_con.execute(
|
|
122
|
+
"CREATE OR REPLACE SECRET scigantic_comptox "
|
|
123
|
+
"(TYPE s3, PROVIDER config, KEY_ID '', SECRET '')"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
base = f"s3://{BUCKET}/{release}"
|
|
127
|
+
bioactivity_path = f"{base}/bioactivity/mc5_6_winning_model_fits.parquet"
|
|
128
|
+
new_con.execute(
|
|
129
|
+
f"CREATE OR REPLACE VIEW bioactivity_raw AS "
|
|
130
|
+
f"SELECT * FROM read_parquet('{bioactivity_path}')"
|
|
131
|
+
)
|
|
132
|
+
new_con.execute(
|
|
133
|
+
f"CREATE OR REPLACE VIEW bioactivity AS "
|
|
134
|
+
f"SELECT {_bioactivity_select_list()} "
|
|
135
|
+
f"FROM read_parquet('{bioactivity_path}')"
|
|
136
|
+
)
|
|
137
|
+
pubchem_bridge_path = f"{base}/derived/pubchem_bridge.parquet"
|
|
138
|
+
new_con.execute(
|
|
139
|
+
f"CREATE OR REPLACE VIEW pubchem_bridge AS "
|
|
140
|
+
f"SELECT * FROM read_parquet('{pubchem_bridge_path}')"
|
|
141
|
+
)
|
|
142
|
+
_base_cons[release] = new_con
|
|
143
|
+
con = new_con
|
|
144
|
+
return con
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def connect(release: str | None = None) -> "duckdb.DuckDBPyConnection":
|
|
148
|
+
"""A DuckDB connection against s3://scigantic-comptox.
|
|
149
|
+
|
|
150
|
+
`SELECT * FROM bioactivity` gives the normalized winning-model table
|
|
151
|
+
(see module docstring); `bioactivity_raw` and `pubchem_bridge` are also
|
|
152
|
+
registered as views. release defaults to the manifest's latest().
|
|
153
|
+
|
|
154
|
+
Returns an independent cursor() on a shared base connection for this
|
|
155
|
+
release, safe to use and close() on its own without affecting other
|
|
156
|
+
callers or re-paying the view-registration setup cost.
|
|
157
|
+
"""
|
|
158
|
+
release = release or latest()
|
|
159
|
+
_validate_release(release)
|
|
160
|
+
return _get_base_connection(release).cursor()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def query(sql: str, release: str | None = None) -> "pd.DataFrame":
|
|
164
|
+
"""Run SQL against a release and return a pandas DataFrame.
|
|
165
|
+
|
|
166
|
+
For several queries against the same release, call connect() once and
|
|
167
|
+
reuse it instead, to avoid opening and closing a cursor per query.
|
|
168
|
+
"""
|
|
169
|
+
resolved_release = release or latest()
|
|
170
|
+
con = connect(resolved_release)
|
|
171
|
+
try:
|
|
172
|
+
df = con.execute(sql).df()
|
|
173
|
+
df.attrs["comptox_release"] = resolved_release
|
|
174
|
+
return df
|
|
175
|
+
finally:
|
|
176
|
+
con.close()
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Local response cache for the live REST half, ON by default -- the
|
|
2
|
+
opposite default from cache.py (the mirror half), and deliberately so: this
|
|
3
|
+
side calls EPA's rate-limited CCTE API for every lookup, while the mirror
|
|
4
|
+
half reads an unlimited public S3 mirror. Re-fetching the same DTXSID
|
|
5
|
+
repeatedly in a notebook loop is both slow and the kind of load a live
|
|
6
|
+
government API shouldn't take unnecessarily. Matches scigantic-pubchem's
|
|
7
|
+
identical reasoning for its own default-on cache.
|
|
8
|
+
|
|
9
|
+
Entries expire after ttl_days (30 by default, same as scigantic-pubchem).
|
|
10
|
+
Pass ttl_days=None to disable expiry.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
_enabled = True
|
|
25
|
+
_cache_dir: Path | None = None
|
|
26
|
+
_ttl_seconds: float | None = 30 * 86400
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _default_cache_dir() -> Path:
|
|
30
|
+
if sys.platform == "win32":
|
|
31
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
32
|
+
elif sys.platform == "darwin":
|
|
33
|
+
base = str(Path.home() / "Library" / "Caches")
|
|
34
|
+
else:
|
|
35
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
36
|
+
return Path(base) / "scigantic-comptox" / "ctx-api"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _resolve_dir() -> Path:
|
|
40
|
+
global _cache_dir
|
|
41
|
+
if _cache_dir is None:
|
|
42
|
+
env = os.environ.get("SCIGANTIC_COMPTOX_CTX_CACHE")
|
|
43
|
+
_cache_dir = Path(env) if env else _default_cache_dir()
|
|
44
|
+
_cache_dir.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
return _cache_dir
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def enable_ctx_cache(cache_dir: str | None = None, ttl_days: float | None = 30) -> Path:
|
|
49
|
+
"""Turn caching on for the live REST half (it already is, by default)."""
|
|
50
|
+
global _enabled, _cache_dir, _ttl_seconds
|
|
51
|
+
if cache_dir is not None:
|
|
52
|
+
_cache_dir = Path(cache_dir)
|
|
53
|
+
_cache_dir.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
else:
|
|
55
|
+
_resolve_dir()
|
|
56
|
+
_ttl_seconds = ttl_days * 86400 if ttl_days is not None else None
|
|
57
|
+
_enabled = True
|
|
58
|
+
return _cache_dir # type: ignore[return-value]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def disable_ctx_cache() -> None:
|
|
62
|
+
global _enabled
|
|
63
|
+
_enabled = False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_ctx_cache_enabled() -> bool:
|
|
67
|
+
return _enabled
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _key_path(key: str) -> Path:
|
|
71
|
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()
|
|
72
|
+
return _resolve_dir() / f"{digest}.json"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def get(key: str) -> Any | None:
|
|
76
|
+
"""A cached JSON value for `key`, or None on a miss or expired entry."""
|
|
77
|
+
if not _enabled:
|
|
78
|
+
return None
|
|
79
|
+
path = _key_path(key)
|
|
80
|
+
if not path.exists():
|
|
81
|
+
return None
|
|
82
|
+
if _ttl_seconds is not None and (time.time() - path.stat().st_mtime) > _ttl_seconds:
|
|
83
|
+
return None
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(path.read_text())
|
|
86
|
+
except (json.JSONDecodeError, OSError):
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def put(key: str, value: Any) -> None:
|
|
91
|
+
"""Cache `value` (must be JSON-serializable) under `key`."""
|
|
92
|
+
if not _enabled:
|
|
93
|
+
return
|
|
94
|
+
path = _key_path(key)
|
|
95
|
+
tmp_path = path.with_name(path.name + f".{uuid.uuid4().hex}.part")
|
|
96
|
+
tmp_path.write_text(json.dumps(value))
|
|
97
|
+
os.replace(tmp_path, path)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Live wrapper over EPA's CCTE API (Chemical/Hazard/Exposure microservices),
|
|
2
|
+
the optional half of this package -- the mirror half (bioactivity.py,
|
|
3
|
+
pubchem_bridge.py) needs no API key at all.
|
|
4
|
+
|
|
5
|
+
Requires the caller's OWN EPA API key, deliberately. EPA's own docs describe
|
|
6
|
+
it as "an individual API key" that "uniquely identifies the user", and
|
|
7
|
+
issuance is manually gated through ccte_api@epa.gov rather than self-serve
|
|
8
|
+
-- a real signal against a shared/pooled key. EPA's own reference client
|
|
9
|
+
(github.com/USEPA/ctx-python, read directly to confirm real endpoint paths
|
|
10
|
+
and conventions used here) never embeds a key and always requires the
|
|
11
|
+
caller to supply their own; this package does the same. Get a key by
|
|
12
|
+
emailing ccte_api@epa.gov (see CTX_API_INFO_URL).
|
|
13
|
+
|
|
14
|
+
Endpoint coverage here is intentionally a starting set (one representative,
|
|
15
|
+
real, verified-path endpoint per microservice: chemical detail, a ToxValDB
|
|
16
|
+
hazard search, and HTTK exposure data), not a full reimplementation of
|
|
17
|
+
ctx-python -- ctx-python already covers Chemical/Exposure/Hazard
|
|
18
|
+
comprehensively; this package's real differentiator is the bioactivity
|
|
19
|
+
mirror, not REST-endpoint parity with EPA's own client. Point users at
|
|
20
|
+
ctx-python directly if they need broader REST coverage than what's here.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import requests
|
|
31
|
+
|
|
32
|
+
from . import ctx_cache
|
|
33
|
+
from ._constants import CTX_API_BASE, CTX_API_INFO_URL, CTX_API_KEY_CONTACT, CTX_API_KEY_ENV
|
|
34
|
+
|
|
35
|
+
_USER_AGENT = "scigantic-comptox (+https://scigantic.com; mailto:support@scigantic.com)"
|
|
36
|
+
_MAX_RETRIES = 5
|
|
37
|
+
_RETRY_STATUS_CODES = {429, 500, 502, 503, 504}
|
|
38
|
+
_BACKOFF_BASE_SECONDS = 1.0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class CtxApiError(Exception):
|
|
42
|
+
"""Raised for a CCTE API error response after retries are exhausted."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class MissingApiKeyError(CtxApiError):
|
|
46
|
+
"""Raised when no EPA CCTE API key is configured.
|
|
47
|
+
|
|
48
|
+
This package never embeds or shares a key -- see module docstring.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
super().__init__(
|
|
53
|
+
f"No EPA CCTE API key found. Set the {CTX_API_KEY_ENV} environment "
|
|
54
|
+
f"variable, or pass api_key= directly. Get a free key by emailing "
|
|
55
|
+
f"{CTX_API_KEY_CONTACT} -- see {CTX_API_INFO_URL}."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_session: requests.Session | None = None
|
|
60
|
+
_session_lock = threading.Lock()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _get_session() -> requests.Session:
|
|
64
|
+
global _session
|
|
65
|
+
if _session is None:
|
|
66
|
+
with _session_lock:
|
|
67
|
+
if _session is None: # re-check: another thread may have won the race
|
|
68
|
+
_session = requests.Session()
|
|
69
|
+
_session.headers["User-Agent"] = _USER_AGENT
|
|
70
|
+
_session.headers["Accept"] = "application/json"
|
|
71
|
+
return _session
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _resolve_api_key(api_key: str | None) -> str:
|
|
75
|
+
key = api_key or os.environ.get(CTX_API_KEY_ENV)
|
|
76
|
+
if not key:
|
|
77
|
+
raise MissingApiKeyError()
|
|
78
|
+
return key
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def ctx_get(
|
|
82
|
+
endpoint: str,
|
|
83
|
+
api_key: str | None = None,
|
|
84
|
+
params: dict[str, Any] | None = None,
|
|
85
|
+
use_cache: bool = True,
|
|
86
|
+
) -> Any:
|
|
87
|
+
"""A GET against `{CTX_API_BASE}/{endpoint}`, JSON-decoded.
|
|
88
|
+
|
|
89
|
+
Retries 429/5xx with exponential backoff. Results are cached (see
|
|
90
|
+
ctx_cache.py, ON by default) keyed on the exact endpoint + params, so
|
|
91
|
+
a repeated identical lookup makes no network call while the cache
|
|
92
|
+
entry is still fresh.
|
|
93
|
+
"""
|
|
94
|
+
resolve_key = _resolve_api_key(api_key)
|
|
95
|
+
cache_key = f"GET {endpoint} {params!r}"
|
|
96
|
+
if use_cache:
|
|
97
|
+
cached = ctx_cache.get(cache_key)
|
|
98
|
+
if cached is not None:
|
|
99
|
+
return cached
|
|
100
|
+
|
|
101
|
+
session = _get_session()
|
|
102
|
+
url = f"{CTX_API_BASE}/{endpoint.lstrip('/')}"
|
|
103
|
+
last_exc: Exception | None = None
|
|
104
|
+
|
|
105
|
+
for attempt in range(_MAX_RETRIES):
|
|
106
|
+
try:
|
|
107
|
+
response = session.get(
|
|
108
|
+
url, headers={"x-api-key": resolve_key}, params=params, timeout=30
|
|
109
|
+
)
|
|
110
|
+
except requests.RequestException as exc:
|
|
111
|
+
last_exc = exc
|
|
112
|
+
time.sleep(_BACKOFF_BASE_SECONDS * (2**attempt))
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
if response.status_code == 200:
|
|
116
|
+
data = response.json()
|
|
117
|
+
if use_cache:
|
|
118
|
+
ctx_cache.put(cache_key, data)
|
|
119
|
+
return data
|
|
120
|
+
if response.status_code in _RETRY_STATUS_CODES and attempt < _MAX_RETRIES - 1:
|
|
121
|
+
time.sleep(_BACKOFF_BASE_SECONDS * (2**attempt))
|
|
122
|
+
continue
|
|
123
|
+
raise CtxApiError(
|
|
124
|
+
f"CCTE API request failed: {response.status_code} {response.reason} "
|
|
125
|
+
f"for {url}"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
raise CtxApiError(f"CCTE API request failed after {_MAX_RETRIES} attempts: {last_exc!r}")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def chemical_detail(
|
|
132
|
+
dtxsid: str, api_key: str | None = None, projection: str = "chemicaldetailall"
|
|
133
|
+
) -> Any:
|
|
134
|
+
"""Chemical details for a single DTXSID (structure, identifiers,
|
|
135
|
+
physicochemical properties). Real endpoint path confirmed against EPA's
|
|
136
|
+
own ctx-python client source: `chemical/detail/search/by-dtxsid/{dtxsid}`.
|
|
137
|
+
"""
|
|
138
|
+
return ctx_get(
|
|
139
|
+
f"chemical/detail/search/by-dtxsid/{dtxsid}",
|
|
140
|
+
api_key=api_key,
|
|
141
|
+
params={"projection": projection},
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def hazard_toxval(dtxsid: str, api_key: str | None = None) -> Any:
|
|
146
|
+
"""ToxValDB hazard records for a single DTXSID. Real endpoint path
|
|
147
|
+
confirmed against ctx-python: `hazard/toxval/search/by-dtxsid/{dtxsid}`.
|
|
148
|
+
"""
|
|
149
|
+
return ctx_get(f"hazard/toxval/search/by-dtxsid/{dtxsid}", api_key=api_key)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def exposure_httk(dtxsid: str, api_key: str | None = None) -> Any:
|
|
153
|
+
"""High-Throughput Toxicokinetics (HTTK) exposure data for a single
|
|
154
|
+
DTXSID. Real endpoint path confirmed against ctx-python:
|
|
155
|
+
`exposure/httk/search/by-dtxsid/{dtxsid}`.
|
|
156
|
+
"""
|
|
157
|
+
return ctx_get(f"exposure/httk/search/by-dtxsid/{dtxsid}", api_key=api_key)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Cross-reference ToxCast bioactivity to PubChem, through EPA's own
|
|
2
|
+
precomputed bridge file rather than re-deriving the join yourself.
|
|
3
|
+
|
|
4
|
+
EPA publishes a per-assay-endpoint PubChem CID cross-reference alongside
|
|
5
|
+
each invitrodb release (`pubchem_invitrodb_v4_3_*.zip`, 1,536 files, one per
|
|
6
|
+
assay endpoint). This module wraps the consolidated single-table version of
|
|
7
|
+
that file. Combined with scigantic-pubchem's own bioassay/gene/protein
|
|
8
|
+
coverage, this is a real bridge into the rest of the scigantic-* family, the
|
|
9
|
+
same shape as scigantic-bindingdb's chembl_bridge().
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
from .connection import connect
|
|
17
|
+
from .releases import _require, latest
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def pubchem_bridge(
|
|
24
|
+
dtxsid: str | None = None,
|
|
25
|
+
aeid: int | None = None,
|
|
26
|
+
release: str | None = None,
|
|
27
|
+
limit: int | None = None,
|
|
28
|
+
) -> "pd.DataFrame":
|
|
29
|
+
"""EPA's ToxCast-to-PubChem cross-reference: (aeid, tx_sample_id,
|
|
30
|
+
dtxsid, activity_outcome, ac50_um, hitc, bmd_um) rows, one per assay
|
|
31
|
+
endpoint's tested samples.
|
|
32
|
+
|
|
33
|
+
release defaults to the manifest's current latest().
|
|
34
|
+
"""
|
|
35
|
+
release = release or latest()
|
|
36
|
+
_require(release, "pubchem_bridge")
|
|
37
|
+
con = connect(release)
|
|
38
|
+
try:
|
|
39
|
+
where: list[str] = []
|
|
40
|
+
params: list[str | int] = []
|
|
41
|
+
if dtxsid is not None:
|
|
42
|
+
where.append("dtxsid = ?")
|
|
43
|
+
params.append(dtxsid)
|
|
44
|
+
if aeid is not None:
|
|
45
|
+
where.append("aeid = ?")
|
|
46
|
+
params.append(aeid)
|
|
47
|
+
clause = f"WHERE {' AND '.join(where)}" if where else ""
|
|
48
|
+
sql = f"SELECT * FROM pubchem_bridge {clause}"
|
|
49
|
+
if limit is not None:
|
|
50
|
+
sql += " LIMIT ?"
|
|
51
|
+
params.append(int(limit))
|
|
52
|
+
return con.execute(sql, params).df()
|
|
53
|
+
finally:
|
|
54
|
+
con.close()
|
|
File without changes
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Release metadata: what's mirrored, and what each release supports.
|
|
2
|
+
|
|
3
|
+
Reads a small manifest at s3://scigantic-comptox/_MANIFEST.json, the same
|
|
4
|
+
mechanism scigantic-chembl and scigantic-bindingdb use. The v4_3 release
|
|
5
|
+
carries `bioactivity` and `pubchem_bridge`; `structures` is False because
|
|
6
|
+
DSSTox bulk chemical structures aren't mirrored yet (EPA's bulk distribution
|
|
7
|
+
for that turned out to be a messy institutional drive, not a clean single
|
|
8
|
+
file) -- a future release can add a structures.parquet without breaking
|
|
9
|
+
anything that calls releases() to check what's available first.
|
|
10
|
+
|
|
11
|
+
The manifest is fetched once per process and cached. If it can't be fetched,
|
|
12
|
+
calls fall back to the snapshot below rather than failing outright.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.request
|
|
20
|
+
import warnings
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any, cast
|
|
23
|
+
|
|
24
|
+
from ._constants import BUCKET, REGION
|
|
25
|
+
|
|
26
|
+
_MANIFEST_URL = f"https://{BUCKET}.s3.{REGION}.amazonaws.com/_MANIFEST.json"
|
|
27
|
+
_TIMEOUT_SECONDS = 5
|
|
28
|
+
|
|
29
|
+
# Last-known-good snapshot, shipped with this package version.
|
|
30
|
+
_FALLBACK_LATEST = "v4_3"
|
|
31
|
+
_FALLBACK_RELEASES = {
|
|
32
|
+
"v4_3": {"structures": False, "bioactivity": True, "pubchem_bridge": True},
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class UnknownReleaseError(LookupError):
|
|
37
|
+
"""Raised when a release isn't mirrored at all."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ReleaseCapabilityError(LookupError):
|
|
41
|
+
"""Raised when a release doesn't carry the artifact a call asked for."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class ReleaseInfo:
|
|
46
|
+
release: str
|
|
47
|
+
structures: bool
|
|
48
|
+
bioactivity: bool
|
|
49
|
+
pubchem_bridge: bool
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_cache: dict[str, Any] | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _manifest() -> dict[str, Any]:
|
|
56
|
+
global _cache
|
|
57
|
+
if _cache is not None:
|
|
58
|
+
return _cache
|
|
59
|
+
try:
|
|
60
|
+
with urllib.request.urlopen(_MANIFEST_URL, timeout=_TIMEOUT_SECONDS) as response:
|
|
61
|
+
_cache = json.loads(response.read())
|
|
62
|
+
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
63
|
+
if isinstance(exc, urllib.error.HTTPError):
|
|
64
|
+
exc.close()
|
|
65
|
+
warnings.warn(
|
|
66
|
+
f"could not fetch the live release manifest ({exc!r}); falling back "
|
|
67
|
+
"to the snapshot shipped with this package version, which may be stale",
|
|
68
|
+
stacklevel=3,
|
|
69
|
+
)
|
|
70
|
+
_cache = {"latest": _FALLBACK_LATEST, "releases": _FALLBACK_RELEASES}
|
|
71
|
+
return _cache
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def releases() -> list[ReleaseInfo]:
|
|
75
|
+
"""List every release the mirror carries, and what each one supports."""
|
|
76
|
+
data = _manifest()
|
|
77
|
+
return [ReleaseInfo(release=name, **caps) for name, caps in data["releases"].items()]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def latest() -> str:
|
|
81
|
+
"""The release the archive treats as its current default."""
|
|
82
|
+
return cast(str, _manifest()["latest"])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _validate_release(release: str) -> None:
|
|
86
|
+
data = _manifest()
|
|
87
|
+
if release not in data["releases"]:
|
|
88
|
+
known = ", ".join(data["releases"])
|
|
89
|
+
raise UnknownReleaseError(f"{release!r} is not mirrored. Known releases: {known}.")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _require(release: str, capability: str) -> None:
|
|
93
|
+
_validate_release(release)
|
|
94
|
+
data = _manifest()
|
|
95
|
+
if not data["releases"][release][capability]:
|
|
96
|
+
raise ReleaseCapabilityError(
|
|
97
|
+
f"{release!r} has no {capability.replace('_', ' ')}. Call releases() to "
|
|
98
|
+
"see what each release supports."
|
|
99
|
+
)
|
|
@@ -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,17 @@
|
|
|
1
|
+
scigantic_comptox/__init__.py,sha256=JMS9dcv6TlpBQYav8-gFcTP7m6dzNExC0i0J3iBc5xk,1602
|
|
2
|
+
scigantic_comptox/_constants.py,sha256=VGW-8DdKwu8t5waw-IgppBFVVouz3oPuOIb7iNMXB5k,871
|
|
3
|
+
scigantic_comptox/bioactivity.py,sha256=6VSWRjRMXVJNmnAioz9OvHpyGJve04b1EKVs85Vugjg,3202
|
|
4
|
+
scigantic_comptox/cache.py,sha256=V96xBby7ujEKQ8d9K5bWLDpc65KC0FntRUzg4rx5NII,5237
|
|
5
|
+
scigantic_comptox/cli.py,sha256=fiZ81kfcqy9VS3VHalOJQRcd5EIMxEFIEsQJyMYf348,1709
|
|
6
|
+
scigantic_comptox/connection.py,sha256=QGTsr9iV_QbrwFldda073_CTZFVPrTzhidRiiuSF6Dw,6197
|
|
7
|
+
scigantic_comptox/ctx_cache.py,sha256=DLwFfKvlnfxAv9tXuNK64f6XPdglXbTE8VYAU1vdE3Y,3065
|
|
8
|
+
scigantic_comptox/ctx_client.py,sha256=bM1CBgDt5g9YdngghEzRFHxYWEbaVvE3MZNwYeqeAT8,5738
|
|
9
|
+
scigantic_comptox/pubchem_bridge.py,sha256=mU5qYi7Ytz0MEfu56q1ZcX7uPNUzwEGPWJDTjggjs7I,1833
|
|
10
|
+
scigantic_comptox/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
scigantic_comptox/releases.py,sha256=IPskpRxbZlhoUlMPfwqFlwZjWrTY1K3mUXSHDdaGRos,3286
|
|
12
|
+
scigantic_comptox-0.1.0.dist-info/licenses/LICENSE,sha256=RiBhEtE0qZ65CeSf05VqMHWAhMh0ETETZAj4TEtscWE,904
|
|
13
|
+
scigantic_comptox-0.1.0.dist-info/METADATA,sha256=Y9hQE4a9kWsyLIHTuAj7HaMhoSaIf-zvLYwi3axx9oo,8619
|
|
14
|
+
scigantic_comptox-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
15
|
+
scigantic_comptox-0.1.0.dist-info/entry_points.txt,sha256=gIxrQURBAJU1MI73KbzIasY_d3oAYUb5jqvQg-6c_Dk,65
|
|
16
|
+
scigantic_comptox-0.1.0.dist-info/top_level.txt,sha256=FNS1PjNb52OT2OLihoyH_I7QbTwkOqHqbObXLzjmuGg,18
|
|
17
|
+
scigantic_comptox-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
scigantic_comptox
|