raxtik-source-faers 0.1.0.dev1__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.
- raxtik_source_faers/__init__.py +75 -0
- raxtik_source_faers/_version.py +1 -0
- raxtik_source_faers/adapter.py +412 -0
- raxtik_source_faers/builder.py +51 -0
- raxtik_source_faers/client.py +134 -0
- raxtik_source_faers/constants.py +67 -0
- raxtik_source_faers/fetcher.py +141 -0
- raxtik_source_faers/mappings/common.py +99 -0
- raxtik_source_faers/mappings/s1_legacy.py +292 -0
- raxtik_source_faers/mappings/s2_migration.py +255 -0
- raxtik_source_faers/mappings/s3_modern.py +256 -0
- raxtik_source_faers/parser.py +69 -0
- raxtik_source_faers/reference/__init__.py +43 -0
- raxtik_source_faers/reference/age_groups.py +76 -0
- raxtik_source_faers/reference/age_units.py +76 -0
- raxtik_source_faers/reference/countries.py +2828 -0
- raxtik_source_faers/reference/cumulative_dose_units.py +716 -0
- raxtik_source_faers/reference/dechallenge.py +54 -0
- raxtik_source_faers/reference/dose_frequencies.py +263 -0
- raxtik_source_faers/reference/drug_name_sources.py +32 -0
- raxtik_source_faers/reference/duration_units.py +98 -0
- raxtik_source_faers/reference/occupations.py +65 -0
- raxtik_source_faers/reference/outcomes.py +87 -0
- raxtik_source_faers/reference/rechallenge.py +54 -0
- raxtik_source_faers/reference/report_sources.py +87 -0
- raxtik_source_faers/reference/report_types.py +65 -0
- raxtik_source_faers/reference/roles.py +99 -0
- raxtik_source_faers/reference/sex.py +46 -0
- raxtik_source_faers/reference/weight_units.py +43 -0
- raxtik_source_faers/signatures/resolver.py +101 -0
- raxtik_source_faers-0.1.0.dev1.dist-info/METADATA +214 -0
- raxtik_source_faers-0.1.0.dev1.dist-info/RECORD +35 -0
- raxtik_source_faers-0.1.0.dev1.dist-info/WHEEL +4 -0
- raxtik_source_faers-0.1.0.dev1.dist-info/entry_points.txt +5 -0
- raxtik_source_faers-0.1.0.dev1.dist-info/licenses/LICENSE +661 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Official FDA FAERS/AEMS data connector, parser, and extractor for raxtik-etl."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from raxtik_etl.packaging.builder import PackageFormat, compute_sha256
|
|
6
|
+
from raxtik_etl.sources import (
|
|
7
|
+
clean_field_name,
|
|
8
|
+
download_file,
|
|
9
|
+
find_files_by_entity,
|
|
10
|
+
format_quarter,
|
|
11
|
+
is_valid_quarter,
|
|
12
|
+
normalize_quarter,
|
|
13
|
+
parse_delimited_file,
|
|
14
|
+
parse_quarter,
|
|
15
|
+
stream_download,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from raxtik_source_faers._version import __version__
|
|
19
|
+
from raxtik_source_faers.adapter import FAERSAdapter
|
|
20
|
+
from raxtik_source_faers.builder import build_package
|
|
21
|
+
from raxtik_source_faers.client import FAERS
|
|
22
|
+
from raxtik_source_faers.constants import (
|
|
23
|
+
CANONICAL_SCHEMA_VERSION,
|
|
24
|
+
CANONICAL_TABLES,
|
|
25
|
+
DEFAULT_HF_REPO,
|
|
26
|
+
DEFAULT_RAW_CACHE_DIR,
|
|
27
|
+
FAERS_BASE_URL,
|
|
28
|
+
PROTOCOL_VERSION,
|
|
29
|
+
SOURCE_NAME,
|
|
30
|
+
TABLE_PREFIXES,
|
|
31
|
+
)
|
|
32
|
+
from raxtik_source_faers.fetcher import (
|
|
33
|
+
download_quarterly_archive,
|
|
34
|
+
find_local_faers_files,
|
|
35
|
+
)
|
|
36
|
+
from raxtik_source_faers.parser import (
|
|
37
|
+
detect_table_type,
|
|
38
|
+
parse_faers_ascii_file,
|
|
39
|
+
)
|
|
40
|
+
from raxtik_source_faers.signatures.resolver import (
|
|
41
|
+
ArchiveSignature,
|
|
42
|
+
detect_archive_signature,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"ArchiveSignature",
|
|
47
|
+
"FAERS",
|
|
48
|
+
"FAERSAdapter",
|
|
49
|
+
"PackageFormat",
|
|
50
|
+
"build_package",
|
|
51
|
+
"clean_field_name",
|
|
52
|
+
"compute_sha256",
|
|
53
|
+
"detect_archive_signature",
|
|
54
|
+
"detect_table_type",
|
|
55
|
+
"download_file",
|
|
56
|
+
"download_quarterly_archive",
|
|
57
|
+
"find_files_by_entity",
|
|
58
|
+
"find_local_faers_files",
|
|
59
|
+
"format_quarter",
|
|
60
|
+
"is_valid_quarter",
|
|
61
|
+
"normalize_quarter",
|
|
62
|
+
"parse_delimited_file",
|
|
63
|
+
"parse_faers_ascii_file",
|
|
64
|
+
"parse_quarter",
|
|
65
|
+
"stream_download",
|
|
66
|
+
"CANONICAL_SCHEMA_VERSION",
|
|
67
|
+
"CANONICAL_TABLES",
|
|
68
|
+
"DEFAULT_HF_REPO",
|
|
69
|
+
"DEFAULT_RAW_CACHE_DIR",
|
|
70
|
+
"FAERS_BASE_URL",
|
|
71
|
+
"PROTOCOL_VERSION",
|
|
72
|
+
"SOURCE_NAME",
|
|
73
|
+
"TABLE_PREFIXES",
|
|
74
|
+
"__version__",
|
|
75
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0.dev1"
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""FDA FAERS Source Adapter.
|
|
2
|
+
|
|
3
|
+
Extracts quarterly FDA FAERS ASCII zip archives into ephemeral staging files and loads
|
|
4
|
+
them into DuckDB canonical tables via signature-specific mappings (S1, S2, S3).
|
|
5
|
+
Implements the raxtik_etl.sources.protocol.SourceAdapter protocol.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import tempfile
|
|
11
|
+
import zipfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict, Final, List, Set
|
|
14
|
+
|
|
15
|
+
import duckdb
|
|
16
|
+
from raxtik_etl.packaging.builder import compute_sha256
|
|
17
|
+
from raxtik_etl.sources import (
|
|
18
|
+
BaseSourceAdapter,
|
|
19
|
+
SourceArtifact,
|
|
20
|
+
SourceLoadResult,
|
|
21
|
+
normalize_quarter,
|
|
22
|
+
)
|
|
23
|
+
from rich.console import Console
|
|
24
|
+
|
|
25
|
+
from raxtik_source_faers._version import __version__ as __source_version__
|
|
26
|
+
from raxtik_source_faers.constants import (
|
|
27
|
+
CANONICAL_SCHEMA_VERSION,
|
|
28
|
+
CANONICAL_TABLES,
|
|
29
|
+
DEFAULT_RAW_CACHE_DIR,
|
|
30
|
+
PROTOCOL_VERSION,
|
|
31
|
+
SOURCE_NAME,
|
|
32
|
+
)
|
|
33
|
+
from raxtik_source_faers.fetcher import (
|
|
34
|
+
download_quarterly_archive,
|
|
35
|
+
find_local_faers_files,
|
|
36
|
+
)
|
|
37
|
+
from raxtik_source_faers.mappings.s1_legacy import (
|
|
38
|
+
load_s1_demo,
|
|
39
|
+
load_s1_drug,
|
|
40
|
+
load_s1_indi,
|
|
41
|
+
load_s1_outc,
|
|
42
|
+
load_s1_reac,
|
|
43
|
+
load_s1_rpsr,
|
|
44
|
+
load_s1_ther,
|
|
45
|
+
)
|
|
46
|
+
from raxtik_source_faers.mappings.s2_migration import (
|
|
47
|
+
load_s2_demo,
|
|
48
|
+
load_s2_drug,
|
|
49
|
+
load_s2_indi,
|
|
50
|
+
load_s2_outc,
|
|
51
|
+
load_s2_reac,
|
|
52
|
+
load_s2_rpsr,
|
|
53
|
+
load_s2_ther,
|
|
54
|
+
)
|
|
55
|
+
from raxtik_source_faers.mappings.s3_modern import (
|
|
56
|
+
load_s3_demo,
|
|
57
|
+
load_s3_drug,
|
|
58
|
+
load_s3_indi,
|
|
59
|
+
load_s3_outc,
|
|
60
|
+
load_s3_reac,
|
|
61
|
+
load_s3_rpsr,
|
|
62
|
+
load_s3_ther,
|
|
63
|
+
)
|
|
64
|
+
from raxtik_source_faers.reference import (
|
|
65
|
+
FDA_AGE_GROUPS_REFERENCE,
|
|
66
|
+
FDA_AGE_UNITS_REFERENCE,
|
|
67
|
+
FDA_CUMULATIVE_DOSE_UNITS_REFERENCE,
|
|
68
|
+
FDA_DECHALLENGE_REFERENCE,
|
|
69
|
+
FDA_DOSE_FREQUENCIES_REFERENCE,
|
|
70
|
+
FDA_DRUG_NAME_SOURCES_REFERENCE,
|
|
71
|
+
FDA_DURATION_UNITS_REFERENCE,
|
|
72
|
+
FDA_OCCUPATIONS_REFERENCE,
|
|
73
|
+
FDA_OUTCOMES_REFERENCE,
|
|
74
|
+
FDA_RECHALLENGE_REFERENCE,
|
|
75
|
+
FDA_REPORT_SOURCES_REFERENCE,
|
|
76
|
+
FDA_REPORT_TYPES_REFERENCE,
|
|
77
|
+
FDA_ROLES_REFERENCE,
|
|
78
|
+
FDA_SEX_REFERENCE,
|
|
79
|
+
FDA_WEIGHT_UNITS_REFERENCE,
|
|
80
|
+
ICH_ISO_COUNTRIES_REFERENCE,
|
|
81
|
+
)
|
|
82
|
+
from raxtik_source_faers.signatures.resolver import detect_archive_signature
|
|
83
|
+
|
|
84
|
+
console = Console()
|
|
85
|
+
|
|
86
|
+
REQUIRED_TABLE_COLUMNS: Final[Dict[str, Dict[str, Set[str]]]] = {
|
|
87
|
+
"S1": {
|
|
88
|
+
"demo": {"isr", "case"},
|
|
89
|
+
"drug": {"isr", "drugname"},
|
|
90
|
+
"reac": {"isr", "pt"},
|
|
91
|
+
"outc": {"isr", "outc_cod|outc_code"},
|
|
92
|
+
"rpsr": {"isr"},
|
|
93
|
+
"ther": {"isr"},
|
|
94
|
+
"indi": {"isr"},
|
|
95
|
+
},
|
|
96
|
+
"S2": {
|
|
97
|
+
"demo": {"primaryid", "caseid"},
|
|
98
|
+
"drug": {"primaryid", "drugname"},
|
|
99
|
+
"reac": {"primaryid", "pt"},
|
|
100
|
+
"outc": {"primaryid", "outc_cod|outc_code"},
|
|
101
|
+
"rpsr": {"primaryid"},
|
|
102
|
+
"ther": {"primaryid"},
|
|
103
|
+
"indi": {"primaryid"},
|
|
104
|
+
},
|
|
105
|
+
"S3": {
|
|
106
|
+
"demo": {"primaryid", "caseid"},
|
|
107
|
+
"drug": {"primaryid", "drugname"},
|
|
108
|
+
"reac": {"primaryid", "pt"},
|
|
109
|
+
"outc": {"primaryid", "outc_cod|outc_code"},
|
|
110
|
+
"rpsr": {"primaryid"},
|
|
111
|
+
"ther": {"primaryid"},
|
|
112
|
+
"indi": {"primaryid"},
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
SIGNATURE_LOADERS = {
|
|
117
|
+
"S1": {
|
|
118
|
+
"demo": load_s1_demo,
|
|
119
|
+
"drug": load_s1_drug,
|
|
120
|
+
"reac": load_s1_reac,
|
|
121
|
+
"outc": load_s1_outc,
|
|
122
|
+
"indi": load_s1_indi,
|
|
123
|
+
"ther": load_s1_ther,
|
|
124
|
+
"rpsr": load_s1_rpsr,
|
|
125
|
+
},
|
|
126
|
+
"S2": {
|
|
127
|
+
"demo": load_s2_demo,
|
|
128
|
+
"drug": load_s2_drug,
|
|
129
|
+
"reac": load_s2_reac,
|
|
130
|
+
"outc": load_s2_outc,
|
|
131
|
+
"indi": load_s2_indi,
|
|
132
|
+
"ther": load_s2_ther,
|
|
133
|
+
"rpsr": load_s2_rpsr,
|
|
134
|
+
},
|
|
135
|
+
"S3": {
|
|
136
|
+
"demo": load_s3_demo,
|
|
137
|
+
"drug": load_s3_drug,
|
|
138
|
+
"reac": load_s3_reac,
|
|
139
|
+
"outc": load_s3_outc,
|
|
140
|
+
"indi": load_s3_indi,
|
|
141
|
+
"ther": load_s3_ther,
|
|
142
|
+
"rpsr": load_s3_rpsr,
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class FAERSAdapter(BaseSourceAdapter):
|
|
148
|
+
"""Source adapter for FDA FAERS quarterly ASCII extracts."""
|
|
149
|
+
|
|
150
|
+
source_name: str = SOURCE_NAME
|
|
151
|
+
source_version: str = __source_version__
|
|
152
|
+
etl_version: str = __source_version__
|
|
153
|
+
supported_schema_versions: List[str] = [CANONICAL_SCHEMA_VERSION]
|
|
154
|
+
protocol_version: str = PROTOCOL_VERSION
|
|
155
|
+
|
|
156
|
+
def fetch_archive(
|
|
157
|
+
self,
|
|
158
|
+
data_period: str,
|
|
159
|
+
dest_dir: Path,
|
|
160
|
+
) -> Path:
|
|
161
|
+
"""Downloads official FDA FAERS/AERS ASCII zip archive for data_period.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
data_period: Quarterly period identifier (e.g. '2004Q1').
|
|
165
|
+
dest_dir: Destination folder to download archive into.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
Path to downloaded raw .zip archive.
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
ValueError: If data_period format is invalid.
|
|
172
|
+
"""
|
|
173
|
+
if not data_period:
|
|
174
|
+
raise ValueError("Must provide data_period (e.g. '2004Q1')")
|
|
175
|
+
if dest_dir is None:
|
|
176
|
+
raise ValueError("Must provide dest_dir")
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
canonical_period = normalize_quarter(data_period)
|
|
180
|
+
except ValueError:
|
|
181
|
+
raise ValueError(
|
|
182
|
+
f"Invalid data_period format for FAERS: '{data_period}'. Expected format like '2004Q1'."
|
|
183
|
+
)
|
|
184
|
+
return download_quarterly_archive(data_period=canonical_period, dest_dir=dest_dir)
|
|
185
|
+
|
|
186
|
+
def extract_and_load(
|
|
187
|
+
self, con: duckdb.DuckDBPyConnection, artifact: SourceArtifact
|
|
188
|
+
) -> SourceLoadResult:
|
|
189
|
+
"""Extracts text files from ZIP into DuckDB staging tables and normalizes to canonical schemas.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
con: Active DuckDB database connection.
|
|
193
|
+
artifact: SourceArtifact describing path and data period.
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
SourceLoadResult containing row counts, reference tables, and metadata.
|
|
197
|
+
|
|
198
|
+
Raises:
|
|
199
|
+
FileNotFoundError: If source zip does not exist.
|
|
200
|
+
"""
|
|
201
|
+
zip_path = artifact.path
|
|
202
|
+
# Derive data_period from artifact or archive filename
|
|
203
|
+
raw_period = getattr(artifact, "data_period", None) or zip_path.name
|
|
204
|
+
try:
|
|
205
|
+
data_period = normalize_quarter(raw_period)
|
|
206
|
+
except ValueError as err:
|
|
207
|
+
raise ValueError(
|
|
208
|
+
f"Cannot determine valid FAERS quarterly data_period from artifact or archive '{zip_path.name}'. "
|
|
209
|
+
"A quarterly format like '2004Q1' is required."
|
|
210
|
+
) from err
|
|
211
|
+
|
|
212
|
+
zip_sha256 = compute_sha256(zip_path)
|
|
213
|
+
|
|
214
|
+
staging_dir = DEFAULT_RAW_CACHE_DIR.parent / "tmp"
|
|
215
|
+
staging_dir.mkdir(parents=True, exist_ok=True)
|
|
216
|
+
|
|
217
|
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
|
218
|
+
signature_id = detect_archive_signature(zf, data_period)
|
|
219
|
+
console.print(
|
|
220
|
+
f"[cyan]Detected Schema Signature for {data_period}:[/cyan] [bold]{signature_id}[/bold]"
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
with tempfile.TemporaryDirectory(dir=staging_dir) as tmpdir:
|
|
224
|
+
tmp_path = Path(tmpdir)
|
|
225
|
+
zf.extractall(tmp_path)
|
|
226
|
+
|
|
227
|
+
local_tables = find_local_faers_files(tmp_path)
|
|
228
|
+
table_files: Dict[str, Path] = {
|
|
229
|
+
tbl: paths[0] for tbl, paths in local_tables.items() if paths
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
loaders = SIGNATURE_LOADERS.get(signature_id, {})
|
|
233
|
+
sig_required = REQUIRED_TABLE_COLUMNS.get(str(signature_id), {})
|
|
234
|
+
for tbl_name, file_path in table_files.items():
|
|
235
|
+
req_cols = sig_required.get(tbl_name)
|
|
236
|
+
self.validate_extract_file(file_path, required_columns=req_cols, delimiter="$")
|
|
237
|
+
|
|
238
|
+
loader_fn = loaders.get(tbl_name)
|
|
239
|
+
if loader_fn:
|
|
240
|
+
loader_fn(con, file_path, data_period)
|
|
241
|
+
|
|
242
|
+
row_counts = {}
|
|
243
|
+
for tbl in CANONICAL_TABLES:
|
|
244
|
+
try:
|
|
245
|
+
res = con.execute(f"SELECT COUNT(*) FROM {tbl}").fetchone()
|
|
246
|
+
cnt = int(res[0]) if res is not None else 0
|
|
247
|
+
row_counts[tbl] = cnt
|
|
248
|
+
except duckdb.CatalogException:
|
|
249
|
+
console.print(
|
|
250
|
+
f"[dim yellow]Table '{tbl}' not present in DuckDB schema for {data_period}. Defaulting row count to 0.[/dim yellow]"
|
|
251
|
+
)
|
|
252
|
+
row_counts[tbl] = 0
|
|
253
|
+
except Exception as err:
|
|
254
|
+
console.print(
|
|
255
|
+
f"[bold red]Unexpected error reading count for table '{tbl}':[/bold red] {err}"
|
|
256
|
+
)
|
|
257
|
+
row_counts[tbl] = 0
|
|
258
|
+
|
|
259
|
+
source_files = [
|
|
260
|
+
{
|
|
261
|
+
"filename": zip_path.name,
|
|
262
|
+
"byte_size": zip_path.stat().st_size,
|
|
263
|
+
"sha256": zip_sha256,
|
|
264
|
+
"table_type": "RAW_ARCHIVE_ZIP",
|
|
265
|
+
"row_count": row_counts.get("demo", 0),
|
|
266
|
+
}
|
|
267
|
+
]
|
|
268
|
+
|
|
269
|
+
reference_tables = {
|
|
270
|
+
"_code_outcomes": FDA_OUTCOMES_REFERENCE,
|
|
271
|
+
"_code_roles": FDA_ROLES_REFERENCE,
|
|
272
|
+
"_code_occupations": FDA_OCCUPATIONS_REFERENCE,
|
|
273
|
+
"_code_report_sources": FDA_REPORT_SOURCES_REFERENCE,
|
|
274
|
+
"_code_dechallenge": FDA_DECHALLENGE_REFERENCE,
|
|
275
|
+
"_code_rechallenge": FDA_RECHALLENGE_REFERENCE,
|
|
276
|
+
"_code_report_types": FDA_REPORT_TYPES_REFERENCE,
|
|
277
|
+
"_code_age_groups": FDA_AGE_GROUPS_REFERENCE,
|
|
278
|
+
"_code_age_units": FDA_AGE_UNITS_REFERENCE,
|
|
279
|
+
"_code_weight_units": FDA_WEIGHT_UNITS_REFERENCE,
|
|
280
|
+
"_code_sex": FDA_SEX_REFERENCE,
|
|
281
|
+
"_code_countries": ICH_ISO_COUNTRIES_REFERENCE,
|
|
282
|
+
"_code_drug_name_sources": FDA_DRUG_NAME_SOURCES_REFERENCE,
|
|
283
|
+
"_code_dose_frequencies": FDA_DOSE_FREQUENCIES_REFERENCE,
|
|
284
|
+
"_code_duration_units": FDA_DURATION_UNITS_REFERENCE,
|
|
285
|
+
"_code_cumulative_dose_units": FDA_CUMULATIVE_DOSE_UNITS_REFERENCE,
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return SourceLoadResult(
|
|
289
|
+
source_name=self.source_name,
|
|
290
|
+
data_period=data_period,
|
|
291
|
+
signature_id=signature_id,
|
|
292
|
+
source_files=source_files,
|
|
293
|
+
reference_tables=reference_tables,
|
|
294
|
+
row_counts=row_counts,
|
|
295
|
+
metadata={
|
|
296
|
+
"source_data_license": "US Government Work / Public Domain (17 U.S.C. § 105)"
|
|
297
|
+
},
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
def get_case_resolution_sql(self) -> str:
|
|
301
|
+
"""Returns SQL creating the deterministic deduplicated 'cases' view for FAERS.
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
CREATE OR REPLACE VIEW SQL statement string.
|
|
305
|
+
"""
|
|
306
|
+
return """
|
|
307
|
+
CREATE OR REPLACE VIEW cases AS
|
|
308
|
+
WITH ranked_reports AS (
|
|
309
|
+
SELECT
|
|
310
|
+
*,
|
|
311
|
+
ROW_NUMBER() OVER (
|
|
312
|
+
PARTITION BY case_id
|
|
313
|
+
ORDER BY
|
|
314
|
+
canonical_case_version DESC,
|
|
315
|
+
TRY_CAST(latest_regulatory_date AS BIGINT) DESC NULLS LAST,
|
|
316
|
+
TRY_CAST(manufacturer_date AS BIGINT) DESC NULLS LAST,
|
|
317
|
+
TRY_CAST(primary_id AS BIGINT) DESC
|
|
318
|
+
) AS _rn
|
|
319
|
+
FROM demo
|
|
320
|
+
)
|
|
321
|
+
SELECT * EXCLUDE (_rn)
|
|
322
|
+
FROM ranked_reports
|
|
323
|
+
WHERE _rn = 1;
|
|
324
|
+
"""
|
|
325
|
+
|
|
326
|
+
def get_case_lineage_sql(self) -> str:
|
|
327
|
+
"""Returns SQL creating the 'case_lineage' table tracking cross-quarter submission history for FAERS.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
CREATE OR REPLACE TABLE SQL statement string.
|
|
331
|
+
"""
|
|
332
|
+
return """
|
|
333
|
+
CREATE OR REPLACE TABLE case_lineage AS
|
|
334
|
+
SELECT
|
|
335
|
+
case_id,
|
|
336
|
+
COUNT(DISTINCT primary_id) AS total_submissions_count,
|
|
337
|
+
COUNT(DISTINCT _data_period) AS quarters_count,
|
|
338
|
+
MIN(_data_period) AS first_data_period,
|
|
339
|
+
MAX(_data_period) AS latest_data_period,
|
|
340
|
+
MIN(TRY_CAST(latest_regulatory_date AS BIGINT)) AS first_regulatory_date,
|
|
341
|
+
MAX(TRY_CAST(latest_regulatory_date AS BIGINT)) AS latest_regulatory_date,
|
|
342
|
+
MIN(canonical_case_version) AS min_case_version,
|
|
343
|
+
MAX(canonical_case_version) AS max_case_version,
|
|
344
|
+
BOOL_OR(initial_or_followup_code = 'F') AS has_followup,
|
|
345
|
+
(COUNT(DISTINCT _data_period) > 1) AS is_cross_quarter_case,
|
|
346
|
+
FIRST(primary_id ORDER BY canonical_case_version ASC, TRY_CAST(latest_regulatory_date AS BIGINT) ASC, TRY_CAST(primary_id AS BIGINT) ASC) AS initial_primary_id,
|
|
347
|
+
FIRST(primary_id ORDER BY canonical_case_version DESC, TRY_CAST(latest_regulatory_date AS BIGINT) DESC, TRY_CAST(primary_id AS BIGINT) DESC) AS latest_primary_id
|
|
348
|
+
FROM demo
|
|
349
|
+
GROUP BY case_id;
|
|
350
|
+
"""
|
|
351
|
+
|
|
352
|
+
def get_summary_views_sql(self) -> Dict[str, str]:
|
|
353
|
+
"""Returns analytical summary views for FAERS with pre-aggregated non-fanout arrays.
|
|
354
|
+
|
|
355
|
+
Returns:
|
|
356
|
+
Mapping of view name to SQL CREATE OR REPLACE VIEW statement.
|
|
357
|
+
"""
|
|
358
|
+
return {
|
|
359
|
+
"case_adverse_events_summary": """
|
|
360
|
+
CREATE OR REPLACE VIEW case_adverse_events_summary AS
|
|
361
|
+
WITH drug_agg AS (
|
|
362
|
+
SELECT
|
|
363
|
+
primary_id,
|
|
364
|
+
LIST(reported_drug_name) AS primary_suspect_drugs,
|
|
365
|
+
FIRST(reported_drug_name) AS primary_suspect_drug
|
|
366
|
+
FROM drug
|
|
367
|
+
WHERE role_code = 'PS'
|
|
368
|
+
GROUP BY primary_id
|
|
369
|
+
),
|
|
370
|
+
reac_agg AS (
|
|
371
|
+
SELECT
|
|
372
|
+
primary_id,
|
|
373
|
+
LIST(reported_reaction_term) AS reaction_terms,
|
|
374
|
+
COUNT(DISTINCT reported_reaction_term) AS reaction_count
|
|
375
|
+
FROM reac
|
|
376
|
+
GROUP BY primary_id
|
|
377
|
+
),
|
|
378
|
+
outc_agg AS (
|
|
379
|
+
SELECT
|
|
380
|
+
o.primary_id,
|
|
381
|
+
LIST(o.outcome_code) AS outcome_codes,
|
|
382
|
+
LIST(co.label) AS outcome_labels,
|
|
383
|
+
BOOL_OR(o.outcome_code = 'DE') AS has_death,
|
|
384
|
+
BOOL_OR(o.outcome_code = 'LT') AS has_life_threatening,
|
|
385
|
+
BOOL_OR(o.outcome_code = 'HO') AS has_hospitalization
|
|
386
|
+
FROM outc o
|
|
387
|
+
LEFT JOIN _code_outcomes co ON o.outcome_code = co.code
|
|
388
|
+
GROUP BY o.primary_id
|
|
389
|
+
)
|
|
390
|
+
SELECT
|
|
391
|
+
c.case_id,
|
|
392
|
+
c.primary_id,
|
|
393
|
+
c.canonical_case_version,
|
|
394
|
+
c.event_date,
|
|
395
|
+
c.standard_age_years,
|
|
396
|
+
c.standard_sex_label,
|
|
397
|
+
c._data_period,
|
|
398
|
+
COALESCE(d.primary_suspect_drugs, []) AS primary_suspect_drugs,
|
|
399
|
+
d.primary_suspect_drug,
|
|
400
|
+
COALESCE(r.reaction_terms, []) AS reaction_terms,
|
|
401
|
+
COALESCE(r.reaction_count, 0) AS reaction_count,
|
|
402
|
+
COALESCE(o.outcome_codes, []) AS outcome_codes,
|
|
403
|
+
COALESCE(o.outcome_labels, []) AS outcome_labels,
|
|
404
|
+
COALESCE(o.has_death, FALSE) AS has_death,
|
|
405
|
+
COALESCE(o.has_life_threatening, FALSE) AS has_life_threatening,
|
|
406
|
+
COALESCE(o.has_hospitalization, FALSE) AS has_hospitalization
|
|
407
|
+
FROM cases c
|
|
408
|
+
LEFT JOIN drug_agg d ON c.primary_id = d.primary_id
|
|
409
|
+
LEFT JOIN reac_agg r ON c.primary_id = r.primary_id
|
|
410
|
+
LEFT JOIN outc_agg o ON c.primary_id = o.primary_id;
|
|
411
|
+
"""
|
|
412
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Package builder utilities for FDA FAERS datasets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict, Optional, Union
|
|
7
|
+
|
|
8
|
+
from raxtik_etl.packaging.builder import PackageFormat, build_quarterly_package
|
|
9
|
+
from raxtik_etl.sources import normalize_quarter
|
|
10
|
+
|
|
11
|
+
from raxtik_source_faers.adapter import FAERSAdapter
|
|
12
|
+
from raxtik_source_faers.constants import DEFAULT_RAW_CACHE_DIR, SOURCE_NAME
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_package(
|
|
16
|
+
data_period: str,
|
|
17
|
+
output_dir: Optional[Union[str, Path]] = None,
|
|
18
|
+
format: Union[PackageFormat, str] = PackageFormat.BOTH,
|
|
19
|
+
delete_ascii: bool = True,
|
|
20
|
+
download_dir: Optional[Union[str, Path]] = None,
|
|
21
|
+
) -> Dict[str, Any]:
|
|
22
|
+
"""Downloads FDA FAERS quarterly archive, extracts ASCII files, builds DuckDB/Parquet package, and cleans up raw files.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
data_period: Quarter identifier, e.g. '2004Q1' or '2024Q1'
|
|
26
|
+
output_dir: Destination folder for DuckDB/Parquet packages (defaults to ~/.cache/raxtik/packages)
|
|
27
|
+
format: Export format: PackageFormat or 'both', 'duckdb', 'parquet' (defaults to PackageFormat.BOTH)
|
|
28
|
+
delete_ascii: Whether to delete downloaded raw ASCII archive after packaging (defaults to True)
|
|
29
|
+
download_dir: Directory for temporary raw download (defaults to ~/.cache/raxtik/raw_archives)
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
Dict with package metadata, paths, and quality metrics.
|
|
33
|
+
|
|
34
|
+
Raises:
|
|
35
|
+
ValueError: If data_period format is invalid.
|
|
36
|
+
"""
|
|
37
|
+
canonical_period = normalize_quarter(data_period)
|
|
38
|
+
|
|
39
|
+
adapter = FAERSAdapter()
|
|
40
|
+
dest_path = Path(download_dir) if download_dir else DEFAULT_RAW_CACHE_DIR
|
|
41
|
+
downloaded_zip = adapter.fetch_archive(data_period=canonical_period, dest_dir=dest_path)
|
|
42
|
+
|
|
43
|
+
return build_quarterly_package(
|
|
44
|
+
data_period=canonical_period,
|
|
45
|
+
zip_path=downloaded_zip,
|
|
46
|
+
source_name=SOURCE_NAME,
|
|
47
|
+
adapter=adapter,
|
|
48
|
+
output_dir=Path(output_dir) if output_dir else None,
|
|
49
|
+
format=format,
|
|
50
|
+
delete_ascii=delete_ascii,
|
|
51
|
+
)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""FAERS specialized dataset client for raxtik-source-faers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING, Optional, Union
|
|
7
|
+
|
|
8
|
+
from raxtik_etl.sdk import BaseDataset
|
|
9
|
+
|
|
10
|
+
from raxtik_source_faers.constants import SOURCE_NAME
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from raxtik_etl.packaging.builder import PackageFormat
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FAERS(BaseDataset):
|
|
17
|
+
"""Specialized client for inspecting and querying FDA FAERS datasets."""
|
|
18
|
+
|
|
19
|
+
source_name: str = SOURCE_NAME
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
data_period: str,
|
|
24
|
+
source: Optional[str] = "faers",
|
|
25
|
+
package_dir: Optional[Union[str, Path]] = None,
|
|
26
|
+
download_if_missing: bool = False,
|
|
27
|
+
hf_repo: Optional[str] = None,
|
|
28
|
+
timeout: int = 120,
|
|
29
|
+
revision: Optional[str] = None,
|
|
30
|
+
tier: str = "bronze",
|
|
31
|
+
remote: bool = False,
|
|
32
|
+
):
|
|
33
|
+
"""Initializes a FAERS dataset client for a specific quarterly period.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
data_period: Temporal coverage period (e.g. '2004Q1').
|
|
37
|
+
source: Source identifier (defaults to 'faers').
|
|
38
|
+
package_dir: Local directory containing compiled packages.
|
|
39
|
+
download_if_missing: If True, downloads package from Hugging Face if not found locally.
|
|
40
|
+
hf_repo: Optional custom Hugging Face repo identifier.
|
|
41
|
+
timeout: HTTP request timeout in seconds.
|
|
42
|
+
revision: Hugging Face Git revision or branch name.
|
|
43
|
+
tier: Dataset release tier ('bronze' or 'silver'). Defaults to 'bronze'.
|
|
44
|
+
remote: If True, streams directly from Hugging Face Hub over HTTPS with zero local disk footprint.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
ValueError: If data_period is not provided.
|
|
48
|
+
"""
|
|
49
|
+
if not data_period:
|
|
50
|
+
raise ValueError("Must provide data_period (e.g. '2004Q1')")
|
|
51
|
+
super().__init__(
|
|
52
|
+
data_period=data_period,
|
|
53
|
+
source=source,
|
|
54
|
+
package_dir=package_dir,
|
|
55
|
+
download_if_missing=download_if_missing,
|
|
56
|
+
hf_repo=hf_repo,
|
|
57
|
+
timeout=timeout,
|
|
58
|
+
revision=revision,
|
|
59
|
+
tier=tier,
|
|
60
|
+
remote=remote,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_hf(
|
|
65
|
+
cls,
|
|
66
|
+
data_period: str,
|
|
67
|
+
source: Optional[str] = "faers",
|
|
68
|
+
package_dir: Optional[Union[str, Path]] = None,
|
|
69
|
+
hf_repo: Optional[str] = None,
|
|
70
|
+
timeout: int = 120,
|
|
71
|
+
revision: Optional[str] = None,
|
|
72
|
+
tier: str = "bronze",
|
|
73
|
+
remote: bool = False,
|
|
74
|
+
) -> FAERS:
|
|
75
|
+
"""Loads a FAERS package, automatically downloading from Hugging Face Hub if missing locally.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
data_period: Temporal coverage period (e.g. '2004Q1').
|
|
79
|
+
source: Source identifier (defaults to 'faers').
|
|
80
|
+
package_dir: Local directory containing compiled packages.
|
|
81
|
+
hf_repo: Optional custom Hugging Face repo identifier.
|
|
82
|
+
timeout: HTTP request timeout in seconds.
|
|
83
|
+
revision: Hugging Face Git revision or branch name.
|
|
84
|
+
tier: Dataset release tier ('bronze' or 'silver'). Defaults to 'bronze'.
|
|
85
|
+
remote: If True, streams directly from Hugging Face Hub over HTTPS with zero local disk footprint.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
Connected FAERS client instance.
|
|
89
|
+
"""
|
|
90
|
+
return cls(
|
|
91
|
+
data_period=data_period,
|
|
92
|
+
source=source,
|
|
93
|
+
package_dir=package_dir,
|
|
94
|
+
download_if_missing=not remote,
|
|
95
|
+
hf_repo=hf_repo,
|
|
96
|
+
timeout=timeout,
|
|
97
|
+
revision=revision,
|
|
98
|
+
tier=tier,
|
|
99
|
+
remote=remote,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def from_source(
|
|
104
|
+
cls,
|
|
105
|
+
data_period: str,
|
|
106
|
+
source: Optional[str] = "faers",
|
|
107
|
+
package_dir: Optional[Union[str, Path]] = None,
|
|
108
|
+
format: Union[PackageFormat, str] = "both",
|
|
109
|
+
delete_ascii: bool = True,
|
|
110
|
+
download_dir: Optional[Union[str, Path]] = None,
|
|
111
|
+
) -> FAERS:
|
|
112
|
+
"""Downloads FDA FAERS raw files, builds local package, and loads dataset.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
data_period: Temporal coverage period (e.g. '2004Q1').
|
|
116
|
+
source: Source identifier (defaults to 'faers').
|
|
117
|
+
package_dir: Destination folder for built package.
|
|
118
|
+
format: Package format to build ('both', 'duckdb', or 'parquet').
|
|
119
|
+
delete_ascii: Whether to remove raw ASCII files after packaging.
|
|
120
|
+
download_dir: Temporary download directory for raw archives.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
Connected FAERS client instance.
|
|
124
|
+
"""
|
|
125
|
+
from raxtik_source_faers.builder import build_package
|
|
126
|
+
|
|
127
|
+
build_package(
|
|
128
|
+
data_period=data_period,
|
|
129
|
+
output_dir=package_dir,
|
|
130
|
+
format=format,
|
|
131
|
+
delete_ascii=delete_ascii,
|
|
132
|
+
download_dir=download_dir,
|
|
133
|
+
)
|
|
134
|
+
return cls(data_period=data_period, source=source, package_dir=package_dir)
|