raxtik-source-faers 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.
- raxtik_source_faers/__init__.py +75 -0
- raxtik_source_faers/_version.py +1 -0
- raxtik_source_faers/adapter.py +443 -0
- raxtik_source_faers/builder.py +51 -0
- raxtik_source_faers/client.py +152 -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.dist-info/METADATA +227 -0
- raxtik_source_faers-0.1.0.dist-info/RECORD +35 -0
- raxtik_source_faers-0.1.0.dist-info/WHEEL +4 -0
- raxtik_source_faers-0.1.0.dist-info/entry_points.txt +5 -0
- raxtik_source_faers-0.1.0.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"
|
|
@@ -0,0 +1,443 @@
|
|
|
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.indexing.models import ResolutionPolicy
|
|
17
|
+
from raxtik_etl.packaging.builder import compute_sha256
|
|
18
|
+
from raxtik_etl.sources import (
|
|
19
|
+
BaseSourceAdapter,
|
|
20
|
+
SourceArtifact,
|
|
21
|
+
SourceLoadResult,
|
|
22
|
+
normalize_quarter,
|
|
23
|
+
)
|
|
24
|
+
from rich.console import Console
|
|
25
|
+
|
|
26
|
+
from raxtik_source_faers._version import __version__ as __source_version__
|
|
27
|
+
from raxtik_source_faers.constants import (
|
|
28
|
+
CANONICAL_SCHEMA_VERSION,
|
|
29
|
+
CANONICAL_TABLES,
|
|
30
|
+
DEFAULT_RAW_CACHE_DIR,
|
|
31
|
+
PROTOCOL_VERSION,
|
|
32
|
+
SOURCE_NAME,
|
|
33
|
+
)
|
|
34
|
+
from raxtik_source_faers.fetcher import (
|
|
35
|
+
download_quarterly_archive,
|
|
36
|
+
find_local_faers_files,
|
|
37
|
+
)
|
|
38
|
+
from raxtik_source_faers.mappings.s1_legacy import (
|
|
39
|
+
load_s1_demo,
|
|
40
|
+
load_s1_drug,
|
|
41
|
+
load_s1_indi,
|
|
42
|
+
load_s1_outc,
|
|
43
|
+
load_s1_reac,
|
|
44
|
+
load_s1_rpsr,
|
|
45
|
+
load_s1_ther,
|
|
46
|
+
)
|
|
47
|
+
from raxtik_source_faers.mappings.s2_migration import (
|
|
48
|
+
load_s2_demo,
|
|
49
|
+
load_s2_drug,
|
|
50
|
+
load_s2_indi,
|
|
51
|
+
load_s2_outc,
|
|
52
|
+
load_s2_reac,
|
|
53
|
+
load_s2_rpsr,
|
|
54
|
+
load_s2_ther,
|
|
55
|
+
)
|
|
56
|
+
from raxtik_source_faers.mappings.s3_modern import (
|
|
57
|
+
load_s3_demo,
|
|
58
|
+
load_s3_drug,
|
|
59
|
+
load_s3_indi,
|
|
60
|
+
load_s3_outc,
|
|
61
|
+
load_s3_reac,
|
|
62
|
+
load_s3_rpsr,
|
|
63
|
+
load_s3_ther,
|
|
64
|
+
)
|
|
65
|
+
from raxtik_source_faers.reference import (
|
|
66
|
+
FDA_AGE_GROUPS_REFERENCE,
|
|
67
|
+
FDA_AGE_UNITS_REFERENCE,
|
|
68
|
+
FDA_CUMULATIVE_DOSE_UNITS_REFERENCE,
|
|
69
|
+
FDA_DECHALLENGE_REFERENCE,
|
|
70
|
+
FDA_DOSE_FREQUENCIES_REFERENCE,
|
|
71
|
+
FDA_DRUG_NAME_SOURCES_REFERENCE,
|
|
72
|
+
FDA_DURATION_UNITS_REFERENCE,
|
|
73
|
+
FDA_OCCUPATIONS_REFERENCE,
|
|
74
|
+
FDA_OUTCOMES_REFERENCE,
|
|
75
|
+
FDA_RECHALLENGE_REFERENCE,
|
|
76
|
+
FDA_REPORT_SOURCES_REFERENCE,
|
|
77
|
+
FDA_REPORT_TYPES_REFERENCE,
|
|
78
|
+
FDA_ROLES_REFERENCE,
|
|
79
|
+
FDA_SEX_REFERENCE,
|
|
80
|
+
FDA_WEIGHT_UNITS_REFERENCE,
|
|
81
|
+
ICH_ISO_COUNTRIES_REFERENCE,
|
|
82
|
+
)
|
|
83
|
+
from raxtik_source_faers.signatures.resolver import detect_archive_signature
|
|
84
|
+
|
|
85
|
+
console = Console()
|
|
86
|
+
|
|
87
|
+
REQUIRED_TABLE_COLUMNS: Final[Dict[str, Dict[str, Set[str]]]] = {
|
|
88
|
+
"S1": {
|
|
89
|
+
"demo": {"isr", "case"},
|
|
90
|
+
"drug": {"isr", "drugname"},
|
|
91
|
+
"reac": {"isr", "pt"},
|
|
92
|
+
"outc": {"isr", "outc_cod|outc_code"},
|
|
93
|
+
"rpsr": {"isr"},
|
|
94
|
+
"ther": {"isr"},
|
|
95
|
+
"indi": {"isr"},
|
|
96
|
+
},
|
|
97
|
+
"S2": {
|
|
98
|
+
"demo": {"primaryid", "caseid"},
|
|
99
|
+
"drug": {"primaryid", "drugname"},
|
|
100
|
+
"reac": {"primaryid", "pt"},
|
|
101
|
+
"outc": {"primaryid", "outc_cod|outc_code"},
|
|
102
|
+
"rpsr": {"primaryid"},
|
|
103
|
+
"ther": {"primaryid"},
|
|
104
|
+
"indi": {"primaryid"},
|
|
105
|
+
},
|
|
106
|
+
"S3": {
|
|
107
|
+
"demo": {"primaryid", "caseid"},
|
|
108
|
+
"drug": {"primaryid", "drugname"},
|
|
109
|
+
"reac": {"primaryid", "pt"},
|
|
110
|
+
"outc": {"primaryid", "outc_cod|outc_code"},
|
|
111
|
+
"rpsr": {"primaryid"},
|
|
112
|
+
"ther": {"primaryid"},
|
|
113
|
+
"indi": {"primaryid"},
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
# Mandatory tables required in every valid FDA FAERS/AERS quarterly archive.
|
|
118
|
+
# Other canonical tables (outc, indi, ther, rpsr) are optional if absent from an archive.
|
|
119
|
+
MANDATORY_TABLES: tuple[str, ...] = ("demo", "drug", "reac")
|
|
120
|
+
|
|
121
|
+
SIGNATURE_LOADERS = {
|
|
122
|
+
"S1": {
|
|
123
|
+
"demo": load_s1_demo,
|
|
124
|
+
"drug": load_s1_drug,
|
|
125
|
+
"reac": load_s1_reac,
|
|
126
|
+
"outc": load_s1_outc,
|
|
127
|
+
"indi": load_s1_indi,
|
|
128
|
+
"ther": load_s1_ther,
|
|
129
|
+
"rpsr": load_s1_rpsr,
|
|
130
|
+
},
|
|
131
|
+
"S2": {
|
|
132
|
+
"demo": load_s2_demo,
|
|
133
|
+
"drug": load_s2_drug,
|
|
134
|
+
"reac": load_s2_reac,
|
|
135
|
+
"outc": load_s2_outc,
|
|
136
|
+
"indi": load_s2_indi,
|
|
137
|
+
"ther": load_s2_ther,
|
|
138
|
+
"rpsr": load_s2_rpsr,
|
|
139
|
+
},
|
|
140
|
+
"S3": {
|
|
141
|
+
"demo": load_s3_demo,
|
|
142
|
+
"drug": load_s3_drug,
|
|
143
|
+
"reac": load_s3_reac,
|
|
144
|
+
"outc": load_s3_outc,
|
|
145
|
+
"indi": load_s3_indi,
|
|
146
|
+
"ther": load_s3_ther,
|
|
147
|
+
"rpsr": load_s3_rpsr,
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class FAERSAdapter(BaseSourceAdapter):
|
|
153
|
+
"""Source adapter for FDA FAERS quarterly ASCII extracts."""
|
|
154
|
+
|
|
155
|
+
source_name: str = SOURCE_NAME
|
|
156
|
+
source_version: str = __source_version__
|
|
157
|
+
etl_version: str = __source_version__
|
|
158
|
+
supported_schema_versions: List[str] = [CANONICAL_SCHEMA_VERSION]
|
|
159
|
+
protocol_version: str = PROTOCOL_VERSION
|
|
160
|
+
|
|
161
|
+
def fetch_archive(
|
|
162
|
+
self,
|
|
163
|
+
data_period: str,
|
|
164
|
+
dest_dir: Path,
|
|
165
|
+
) -> Path:
|
|
166
|
+
"""Downloads official FDA FAERS/AERS ASCII zip archive for data_period.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
data_period: Quarterly period identifier (e.g. '2004Q1').
|
|
170
|
+
dest_dir: Destination folder to download archive into.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
Path to downloaded raw .zip archive.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
ValueError: If data_period format is invalid.
|
|
177
|
+
"""
|
|
178
|
+
if not data_period:
|
|
179
|
+
raise ValueError("Must provide data_period (e.g. '2004Q1')")
|
|
180
|
+
if dest_dir is None:
|
|
181
|
+
raise ValueError("Must provide dest_dir")
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
canonical_period = normalize_quarter(data_period)
|
|
185
|
+
except ValueError:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
f"Invalid data_period format for FAERS: '{data_period}'. Expected format like '2004Q1'."
|
|
188
|
+
)
|
|
189
|
+
return download_quarterly_archive(data_period=canonical_period, dest_dir=dest_dir)
|
|
190
|
+
|
|
191
|
+
def extract_and_load(
|
|
192
|
+
self, con: duckdb.DuckDBPyConnection, artifact: SourceArtifact
|
|
193
|
+
) -> SourceLoadResult:
|
|
194
|
+
"""Extracts text files from ZIP into DuckDB staging tables and normalizes to canonical schemas.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
con: Active DuckDB database connection.
|
|
198
|
+
artifact: SourceArtifact describing path and data period.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
SourceLoadResult containing row counts, reference tables, and metadata.
|
|
202
|
+
|
|
203
|
+
Raises:
|
|
204
|
+
FileNotFoundError: If source zip does not exist.
|
|
205
|
+
"""
|
|
206
|
+
zip_path = artifact.path
|
|
207
|
+
# Derive data_period from artifact or archive filename
|
|
208
|
+
raw_period = getattr(artifact, "data_period", None) or zip_path.name
|
|
209
|
+
try:
|
|
210
|
+
data_period = normalize_quarter(raw_period)
|
|
211
|
+
except ValueError as err:
|
|
212
|
+
raise ValueError(
|
|
213
|
+
f"Cannot determine valid FAERS quarterly data_period from artifact or archive '{zip_path.name}'. "
|
|
214
|
+
"A quarterly format like '2004Q1' is required."
|
|
215
|
+
) from err
|
|
216
|
+
|
|
217
|
+
zip_sha256 = compute_sha256(zip_path)
|
|
218
|
+
|
|
219
|
+
staging_dir = DEFAULT_RAW_CACHE_DIR.parent / "tmp"
|
|
220
|
+
staging_dir.mkdir(parents=True, exist_ok=True)
|
|
221
|
+
|
|
222
|
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
|
223
|
+
signature_id = detect_archive_signature(zf, data_period)
|
|
224
|
+
console.print(
|
|
225
|
+
f"[cyan]Detected Schema Signature for {data_period}:[/cyan] [bold]{signature_id}[/bold]"
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
with tempfile.TemporaryDirectory(dir=staging_dir) as tmpdir:
|
|
229
|
+
tmp_path = Path(tmpdir)
|
|
230
|
+
zf.extractall(tmp_path)
|
|
231
|
+
|
|
232
|
+
local_tables = find_local_faers_files(tmp_path)
|
|
233
|
+
table_files: Dict[str, Path] = {
|
|
234
|
+
tbl: paths[0] for tbl, paths in local_tables.items() if paths
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
missing_mandatory = [t for t in MANDATORY_TABLES if t not in table_files]
|
|
238
|
+
if missing_mandatory:
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"Incomplete FAERS archive '{zip_path.name}' for {data_period}: "
|
|
241
|
+
f"missing mandatory table(s) {missing_mandatory}. "
|
|
242
|
+
f"Found: {sorted(table_files.keys())}"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
loaders = SIGNATURE_LOADERS.get(signature_id, {})
|
|
246
|
+
sig_required = REQUIRED_TABLE_COLUMNS.get(str(signature_id), {})
|
|
247
|
+
for tbl_name, file_path in table_files.items():
|
|
248
|
+
req_cols = sig_required.get(tbl_name)
|
|
249
|
+
self.validate_extract_file(file_path, required_columns=req_cols, delimiter="$")
|
|
250
|
+
|
|
251
|
+
loader_fn = loaders.get(tbl_name)
|
|
252
|
+
if loader_fn:
|
|
253
|
+
loader_fn(con, file_path, data_period)
|
|
254
|
+
|
|
255
|
+
row_counts = {}
|
|
256
|
+
for tbl in CANONICAL_TABLES:
|
|
257
|
+
try:
|
|
258
|
+
res = con.execute(f"SELECT COUNT(*) FROM {tbl}").fetchone()
|
|
259
|
+
cnt = int(res[0]) if res is not None else 0
|
|
260
|
+
row_counts[tbl] = cnt
|
|
261
|
+
except duckdb.CatalogException:
|
|
262
|
+
console.print(
|
|
263
|
+
f"[dim yellow]Table '{tbl}' not present in DuckDB schema for {data_period}. Defaulting row count to 0.[/dim yellow]"
|
|
264
|
+
)
|
|
265
|
+
row_counts[tbl] = 0
|
|
266
|
+
except Exception as err:
|
|
267
|
+
raise RuntimeError(
|
|
268
|
+
f"Unexpected error reading row count for table '{tbl}' ({data_period}): {err}"
|
|
269
|
+
) from err
|
|
270
|
+
|
|
271
|
+
source_files = [
|
|
272
|
+
{
|
|
273
|
+
"filename": zip_path.name,
|
|
274
|
+
"byte_size": zip_path.stat().st_size,
|
|
275
|
+
"sha256": zip_sha256,
|
|
276
|
+
"table_type": "RAW_ARCHIVE_ZIP",
|
|
277
|
+
"row_count": row_counts.get("demo", 0),
|
|
278
|
+
}
|
|
279
|
+
]
|
|
280
|
+
|
|
281
|
+
reference_tables = {
|
|
282
|
+
"_code_outcomes": FDA_OUTCOMES_REFERENCE,
|
|
283
|
+
"_code_roles": FDA_ROLES_REFERENCE,
|
|
284
|
+
"_code_occupations": FDA_OCCUPATIONS_REFERENCE,
|
|
285
|
+
"_code_report_sources": FDA_REPORT_SOURCES_REFERENCE,
|
|
286
|
+
"_code_dechallenge": FDA_DECHALLENGE_REFERENCE,
|
|
287
|
+
"_code_rechallenge": FDA_RECHALLENGE_REFERENCE,
|
|
288
|
+
"_code_report_types": FDA_REPORT_TYPES_REFERENCE,
|
|
289
|
+
"_code_age_groups": FDA_AGE_GROUPS_REFERENCE,
|
|
290
|
+
"_code_age_units": FDA_AGE_UNITS_REFERENCE,
|
|
291
|
+
"_code_weight_units": FDA_WEIGHT_UNITS_REFERENCE,
|
|
292
|
+
"_code_sex": FDA_SEX_REFERENCE,
|
|
293
|
+
"_code_countries": ICH_ISO_COUNTRIES_REFERENCE,
|
|
294
|
+
"_code_drug_name_sources": FDA_DRUG_NAME_SOURCES_REFERENCE,
|
|
295
|
+
"_code_dose_frequencies": FDA_DOSE_FREQUENCIES_REFERENCE,
|
|
296
|
+
"_code_duration_units": FDA_DURATION_UNITS_REFERENCE,
|
|
297
|
+
"_code_cumulative_dose_units": FDA_CUMULATIVE_DOSE_UNITS_REFERENCE,
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return SourceLoadResult(
|
|
301
|
+
source_name=self.source_name,
|
|
302
|
+
data_period=data_period,
|
|
303
|
+
signature_id=signature_id,
|
|
304
|
+
source_files=source_files,
|
|
305
|
+
reference_tables=reference_tables,
|
|
306
|
+
row_counts=row_counts,
|
|
307
|
+
metadata={
|
|
308
|
+
"source_data_license": "US Government Work / Public Domain (17 U.S.C. § 105)"
|
|
309
|
+
},
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
def get_case_resolution_sql(self) -> str:
|
|
313
|
+
"""Returns SQL creating the deterministic deduplicated 'cases' view for FAERS.
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
CREATE OR REPLACE VIEW SQL statement string.
|
|
317
|
+
"""
|
|
318
|
+
return """
|
|
319
|
+
CREATE OR REPLACE VIEW cases AS
|
|
320
|
+
WITH ranked_reports AS (
|
|
321
|
+
SELECT
|
|
322
|
+
*,
|
|
323
|
+
ROW_NUMBER() OVER (
|
|
324
|
+
PARTITION BY case_id
|
|
325
|
+
ORDER BY
|
|
326
|
+
canonical_case_version DESC,
|
|
327
|
+
TRY_CAST(latest_regulatory_date AS BIGINT) DESC NULLS LAST,
|
|
328
|
+
TRY_CAST(manufacturer_date AS BIGINT) DESC NULLS LAST,
|
|
329
|
+
TRY_CAST(primary_id AS BIGINT) DESC
|
|
330
|
+
) AS _rn
|
|
331
|
+
FROM demo
|
|
332
|
+
)
|
|
333
|
+
SELECT * EXCLUDE (_rn)
|
|
334
|
+
FROM ranked_reports
|
|
335
|
+
WHERE _rn = 1;
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
def get_case_lineage_sql(self) -> str:
|
|
339
|
+
"""Returns SQL creating the 'case_lineage' table tracking cross-quarter submission history for FAERS.
|
|
340
|
+
|
|
341
|
+
Returns:
|
|
342
|
+
CREATE OR REPLACE TABLE SQL statement string.
|
|
343
|
+
"""
|
|
344
|
+
return """
|
|
345
|
+
CREATE OR REPLACE TABLE case_lineage AS
|
|
346
|
+
SELECT
|
|
347
|
+
case_id,
|
|
348
|
+
COUNT(DISTINCT primary_id) AS total_submissions_count,
|
|
349
|
+
COUNT(DISTINCT _data_period) AS quarters_count,
|
|
350
|
+
MIN(_data_period) AS first_data_period,
|
|
351
|
+
MAX(_data_period) AS latest_data_period,
|
|
352
|
+
MIN(TRY_CAST(latest_regulatory_date AS BIGINT)) AS first_regulatory_date,
|
|
353
|
+
MAX(TRY_CAST(latest_regulatory_date AS BIGINT)) AS latest_regulatory_date,
|
|
354
|
+
MIN(canonical_case_version) AS min_case_version,
|
|
355
|
+
MAX(canonical_case_version) AS max_case_version,
|
|
356
|
+
BOOL_OR(initial_or_followup_code = 'F') AS has_followup,
|
|
357
|
+
(COUNT(DISTINCT _data_period) > 1) AS is_cross_quarter_case,
|
|
358
|
+
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,
|
|
359
|
+
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
|
|
360
|
+
FROM demo
|
|
361
|
+
GROUP BY case_id;
|
|
362
|
+
"""
|
|
363
|
+
|
|
364
|
+
def get_summary_views_sql(self) -> Dict[str, str]:
|
|
365
|
+
"""Returns analytical summary views for FAERS with pre-aggregated non-fanout arrays.
|
|
366
|
+
|
|
367
|
+
Returns:
|
|
368
|
+
Mapping of view name to SQL CREATE OR REPLACE VIEW statement.
|
|
369
|
+
"""
|
|
370
|
+
return {
|
|
371
|
+
"case_adverse_events_summary": """
|
|
372
|
+
CREATE OR REPLACE VIEW case_adverse_events_summary AS
|
|
373
|
+
WITH drug_agg AS (
|
|
374
|
+
SELECT
|
|
375
|
+
primary_id,
|
|
376
|
+
LIST(reported_drug_name ORDER BY TRY_CAST(drug_seq AS INTEGER) NULLS LAST, drug_seq) AS primary_suspect_drugs,
|
|
377
|
+
FIRST(reported_drug_name ORDER BY TRY_CAST(drug_seq AS INTEGER) NULLS LAST, drug_seq) AS primary_suspect_drug
|
|
378
|
+
FROM drug
|
|
379
|
+
WHERE role_code = 'PS'
|
|
380
|
+
GROUP BY primary_id
|
|
381
|
+
),
|
|
382
|
+
reac_agg AS (
|
|
383
|
+
SELECT
|
|
384
|
+
primary_id,
|
|
385
|
+
LIST(reported_reaction_term ORDER BY reported_reaction_term) AS reaction_terms,
|
|
386
|
+
COUNT(DISTINCT reported_reaction_term) AS reaction_count
|
|
387
|
+
FROM reac
|
|
388
|
+
GROUP BY primary_id
|
|
389
|
+
),
|
|
390
|
+
outc_agg AS (
|
|
391
|
+
SELECT
|
|
392
|
+
o.primary_id,
|
|
393
|
+
LIST(o.outcome_code ORDER BY o.outcome_code) AS outcome_codes,
|
|
394
|
+
LIST(co.label ORDER BY o.outcome_code) AS outcome_labels,
|
|
395
|
+
BOOL_OR(o.outcome_code = 'DE') AS has_death,
|
|
396
|
+
BOOL_OR(o.outcome_code = 'LT') AS has_life_threatening,
|
|
397
|
+
BOOL_OR(o.outcome_code = 'HO') AS has_hospitalization
|
|
398
|
+
FROM outc o
|
|
399
|
+
LEFT JOIN _code_outcomes co ON o.outcome_code = co.code
|
|
400
|
+
GROUP BY o.primary_id
|
|
401
|
+
)
|
|
402
|
+
SELECT
|
|
403
|
+
c.case_id,
|
|
404
|
+
c.primary_id,
|
|
405
|
+
c.canonical_case_version,
|
|
406
|
+
c.event_date,
|
|
407
|
+
c.standard_age_years,
|
|
408
|
+
c.standard_sex_label,
|
|
409
|
+
c._data_period,
|
|
410
|
+
COALESCE(d.primary_suspect_drugs, []) AS primary_suspect_drugs,
|
|
411
|
+
d.primary_suspect_drug,
|
|
412
|
+
COALESCE(r.reaction_terms, []) AS reaction_terms,
|
|
413
|
+
COALESCE(r.reaction_count, 0) AS reaction_count,
|
|
414
|
+
COALESCE(o.outcome_codes, []) AS outcome_codes,
|
|
415
|
+
COALESCE(o.outcome_labels, []) AS outcome_labels,
|
|
416
|
+
COALESCE(o.has_death, FALSE) AS has_death,
|
|
417
|
+
COALESCE(o.has_life_threatening, FALSE) AS has_life_threatening,
|
|
418
|
+
COALESCE(o.has_hospitalization, FALSE) AS has_hospitalization
|
|
419
|
+
FROM cases c
|
|
420
|
+
LEFT JOIN drug_agg d ON c.primary_id = d.primary_id
|
|
421
|
+
LEFT JOIN reac_agg r ON c.primary_id = r.primary_id
|
|
422
|
+
LEFT JOIN outc_agg o ON c.primary_id = o.primary_id;
|
|
423
|
+
"""
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
def get_resolution_policy(self) -> ResolutionPolicy:
|
|
427
|
+
"""Returns the FAERS-specific deterministic resolution policy for derived tier indexing.
|
|
428
|
+
|
|
429
|
+
Explicitly declares FAERS canonical entity/record keys (`case_id`, `primary_id`),
|
|
430
|
+
precedence columns (`canonical_case_version`, `latest_regulatory_date`,
|
|
431
|
+
`manufacturer_date`), numeric `primary_id` tie-breaker, and all 6 FAERS child tables.
|
|
432
|
+
"""
|
|
433
|
+
return ResolutionPolicy(
|
|
434
|
+
entity_key="case_id",
|
|
435
|
+
record_key="primary_id",
|
|
436
|
+
version_column="canonical_case_version",
|
|
437
|
+
regulatory_date_column="latest_regulatory_date",
|
|
438
|
+
manufacturer_date_column="manufacturer_date",
|
|
439
|
+
source_table="demo",
|
|
440
|
+
child_tables=("drug", "reac", "outc", "indi", "ther", "rpsr"),
|
|
441
|
+
numeric_record_key_tiebreaker=True,
|
|
442
|
+
policy_version="faers-1.0.0",
|
|
443
|
+
)
|
|
@@ -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
|
+
)
|