skyleee's picture
Upload diversa-biomedical-v1 package
7bcd860 verified
Raw History Blame Contribute Delete
25.9 kB
"""Generate the human-facing documentation bundle from live pipeline results."""
from __future__ import annotations
from datetime import datetime, timezone
from common import human_bytes
WORKS_COLUMNS = [
("work_id", "string", "OpenAlex work ID (short form, e.g. W2146512944). Primary key."),
("doi", "string", "Normalized DOI (lowercase, no https://doi.org/ prefix). Null if absent."),
("title", "string", "Work title. Rows with empty titles are removed during cleaning."),
("publication_date", "string", "ISO date (YYYY-MM-DD). Null when OpenAlex has no exact date."),
("publication_year", "int16", "Publication year (2015-2025)."),
("publication_month", "int8", "Month extracted from publication_date."),
("type", "string", "OpenAlex work type (article, review, book-chapter, ...)."),
("primary_topic_id", "string", "OpenAlex topic ID of the work's primary topic."),
("primary_topic_name", "string", "Display name of the primary topic."),
("primary_topic_score", "float32", "OpenAlex confidence score for the primary topic."),
("field_id", "string", "OpenAlex field ID (top-level discipline) of the primary topic."),
("field_name", "string", "Field name, e.g. Medicine, Neuroscience."),
("subfield_id", "string", "OpenAlex subfield ID of the primary topic."),
("subfield_name", "string", "Subfield name, e.g. Oncology, Cardiology."),
("domain_id", "string", "OpenAlex domain ID (Life Sciences=1, Health Sciences=4)."),
("domain_name", "string", "Domain name."),
("topic_ids", "list<string>", "All OpenAlex topic IDs assigned to the work (max 3)."),
("topic_names", "list<string>", "Names aligned positionally with topic_ids."),
("topic_count", "int16", "Number of topics on the work."),
("author_count", "int32", "Number of authorships."),
("author_names", "list<string>", "Author display names in authorship order."),
("author_ids", "list<string>", "OpenAlex author IDs aligned with author_names."),
("author_orcids", "list<string>", "ORCIDs aligned with author_names (null where absent)."),
("institution_count", "int32", "Number of distinct institutions on the work."),
("institution_ids", "list<string>", "Distinct OpenAlex institution IDs."),
("institution_names", "list<string>", "Institution display names."),
("institution_countries", "list<string>", "Distinct ISO-3166 alpha-2 codes of institutions."),
("country_codes", "list<string>", "All countries involved (authors + institutions)."),
("country_count", "int16", "Number of distinct countries."),
("source_id", "string", "OpenAlex source (journal/venue) ID."),
("source_name", "string", "Source display name."),
("source_type", "string", "Source type (journal, conference, repository, ...)."),
("issn_l", "string", "Linking ISSN of the source."),
("issns", "list<string>", "All ISSNs of the source."),
("publisher", "string", "Host organisation / publisher name."),
("cited_by_count", "int32", "OpenAlex citation count at retrieval time."),
("recent_citations_3y", "int32", "Citations accrued in the last 3 years (2023-2025)."),
("referenced_works_count", "int32", "Number of references (per OpenAlex)."),
("referenced_work_ids", "list<string>", "OpenAlex IDs of referenced works (short form)."),
("is_oa", "bool", "Open-access flag."),
("oa_status", "string", "OA status: gold, green, hybrid, bronze, diamond, closed."),
("oa_url", "string", "Best OA location URL."),
("license", "string", "License string of the primary/best OA location (e.g. cc-by)."),
("license_id", "string", "License identifier where provided."),
("language", "string", "Language code of the work."),
("abstract", "string", "Abstract reconstructed from OpenAlex's inverted index (null if none)."),
("has_abstract", "bool", "Whether an abstract could be reconstructed."),
("is_retracted", "bool", "Retraction flag."),
("is_paratext", "bool", "Paratext flag (front matter, editorials) - excluded by default."),
("fwci", "float32", "Field-Weighted Citation Impact (OpenAlex supplied)."),
("openalex_citation_percentile", "float32", "OpenAlex-supplied normalized citation percentile."),
("created_date", "string", "Date the record was created in OpenAlex."),
("updated_date", "string", "Date the record was last updated in OpenAlex."),
("mesh_terms", "list<string>", "MeSH descriptor/qualifier terms where OpenAlex supplies them."),
("keywords", "list<string>", "OpenAlex keyword tags."),
("paper_age_years", "float32", "DERIVED: reference_year - publication_year."),
("citations_per_year", "float32", "DERIVED: cited_by_count / max(paper_age_years, 1)."),
("citation_velocity", "float32", "DERIVED: recent_citations_3y / 3."),
("international_collaboration", "bool", "DERIVED: country_count >= 2."),
("multi_institutional", "bool", "DERIVED: institution_count >= 2."),
("publication_recency_score", "float32", "DERIVED: exp(-paper_age_years / halflife)."),
("citation_percentile", "float32", "DERIVED: percentile of cited_by_count within publication_year x field."),
("high_impact_flag", "bool", "DERIVED: citation_percentile >= configured threshold (default 90)."),
("research_growth_score", "float32", "DERIVED: late/early publication ratio of the work's field."),
("topic_growth_score", "float32", "DERIVED: late/early publication ratio of the primary topic."),
("emerging_topic_flag", "bool", "DERIVED: primary topic is emerging (growth ratio >= threshold, sufficient volume)."),
]
RELATION_COLUMNS = {
"work_authors.parquet": [
("work_id", "FK to works.work_id"), ("author_id", "OpenAlex author ID"),
("author_name", "author display name"), ("orcid", "ORCID if available"),
("author_position", "first / middle / last"), ("is_corresponding", "corresponding-author flag"),
("institution_ids", "institutions for this authorship"),
("country_codes", "countries for this authorship"),
],
"work_institutions.parquet": [
("work_id", "FK to works"), ("institution_id", "OpenAlex institution ID"),
("institution_name", "name"), ("country_code", "ISO alpha-2"),
("institution_type", "education / company / government / facility / other"),
],
"work_topics.parquet": [
("work_id", "FK to works"), ("topic_id", "OpenAlex topic ID"), ("topic_name", "topic name"),
("score", "relevance score"), ("is_primary", "primary-topic flag"),
("subfield_id", "subfield"), ("subfield_name", "subfield name"),
("field_id", "field"), ("field_name", "field name"),
("domain_id", "domain"), ("domain_name", "domain name"),
],
"citation_edges.parquet": [
("citing_work_id", "work that cites"), ("cited_work_id", "work that is cited"),
("cited_in_dataset", "always true: edges are restricted to pairs inside this dataset"),
],
"authors.parquet": [
("author_id", "PK"), ("author_name", "name"), ("orcid", "ORCID"),
("works_count", "works in dataset"), ("first_year", "earliest year"), ("last_year", "latest year"),
("total_citations", "sum of citations"), ("mean_citations", "mean citations per work"),
("institution_ids", "affiliations seen"), ("country_codes", "countries seen"),
("primary_field_id", "most frequent field"), ("primary_field_name", "field name"),
],
"institutions.parquet": [
("institution_id", "PK"), ("institution_name", "name"), ("country_code", "ISO alpha-2"),
("works_count", "works in dataset"), ("first_year", "earliest year"), ("last_year", "latest year"),
("total_citations", "sum of citations"), ("mean_citations", "mean citations"),
("primary_field_id", "most frequent field"), ("primary_field_name", "field name"),
],
"topics.parquet": [
("topic_id", "PK"), ("topic_name", "name"), ("subfield_id", "subfield"), ("subfield_name", "subfield name"),
("field_id", "field"), ("field_name", "field name"), ("domain_id", "domain"), ("domain_name", "domain name"),
("works_count", "works in dataset"), ("first_year", "earliest year"), ("last_year", "latest year"),
("total_citations", "sum of citations"), ("mean_citations", "mean citations"),
],
"sources.parquet": [
("source_id", "PK"), ("source_name", "venue name"), ("source_type", "journal/conference/..."),
("issn_l", "linking ISSN"), ("issns", "all ISSNs"), ("publisher", "publisher"),
("is_oa", "venue OA flag"), ("works_count", "works in dataset"),
("total_citations", "sum of citations"), ("mean_citations", "mean citations"),
],
}
ANALYTICS_COLUMNS = {
"topic_year_counts.parquet": [("topic_id", ""), ("topic_name", ""), ("publication_year", ""), ("works_count", "")],
"topic_growth.parquet": [("topic_id", ""), ("topic_name", ""), ("first_year", ""), ("last_year", ""),
("early_count", "sum in first half of range"), ("late_count", "sum in second half"),
("growth_ratio", "(late+1)/(early+1)"), ("cagr", "compound annual growth of averages"),
("trend_slope", "OLS slope of yearly counts"), ("emerging_topic_flag", "growth and volume threshold")],
"country_year_counts.parquet": [("country_code", ""), ("publication_year", ""), ("works_count", "")],
"country_collaboration.parquet": [("country_a", ""), ("country_b", ""), ("collaboration_count", "co-authored works")],
"institution_activity.parquet": [("institution_id", ""), ("institution_name", ""), ("country_code", ""),
("publication_year", ""), ("works_count", ""), ("total_citations", "")],
}
def _now():
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
def readme(cfg, stats, manifest) -> str:
t = stats.get("totals", {})
yrs = stats.get("year_range") or [None, None]
size = manifest.get("package_size_bytes", 0)
cit = stats.get("citation_statistics", {})
return f"""# {cfg['project']['title']}
A curated, normalized, enriched and packaged **biomedical research intelligence
dataset** derived from OpenAlex metadata, provided in AI-ready formats
(Parquet + JSONL) with full provenance and reproducible build tooling.
This is a **derivative dataset**: it is not a re-upload of OpenAlex. The value
added here is biomedical filtering by taxonomy, cleaning, normalization,
relational restructuring, quality control and derived analytical features.
## What it is
- **Source:** OpenAlex work metadata, retrieved through the OpenAlex REST API.
- **Scope:** biomedical and health-related research only, selected by OpenAlex
**taxonomy IDs** (fields 13, 24, 27, 28, 29, 30, 35, 36), not keyword search.
- **Coverage:** publication years {yrs[0]}-{yrs[1]}.
- **Selection:** stratified random sample drawn per (year x field) shard with a
fixed random seed, so every year and every biomedical field is represented
proportionally and the result is reproducible.
- **Records:** {t.get('total_records', 0):,} works, {t.get('unique_works', 0):,} unique
OpenAlex IDs, {t.get('unique_dois', 0):,} unique DOIs.
- **Languages / OA:** see `metadata/dataset_statistics.json`.
- **Package size (uncompressed):** {human_bytes(size)}.
## Intended uses
Machine-learning and analytical research on the biomedical literature:
trend and growth analysis, collaboration-network analysis, bibliometric
modeling, topic classification, retrieval/ranking experiments, and as a
ready-to-load table for LLM and data-science tooling.
## Formats and layout
```
data/ works + dimensions + relations (Parquet), JSONL exports, splits
analytics/ pre-aggregated time-series and collaboration tables (Parquet)
metadata/ manifest, statistics, schema, source queries, build info
```
Parquet is the primary format. JSONL exports (gzip) are provided for
streaming/LLM use. See `DATA_DICTIONARY.md` for every column.
## Key derived features
`paper_age_years`, `citations_per_year`, `citation_velocity`,
`citation_percentile` (within year x field), `high_impact_flag`,
`publication_recency_score`, `international_collaboration`,
`multi_institutional`, `research_growth_score`, `topic_growth_score`,
`emerging_topic_flag`. Definitions are in `METHODOLOGY.md`.
## Train / validation / test splits
Chronological to avoid leakage:
train <= {cfg['splits']['train_max_year']},
validation {cfg['splits']['validation_years']},
test >= {cfg['splits']['test_min_year']}.
The complete unsplit dataset is retained separately.
## Limitations
See `QUALITY_REPORT.md`. In short: metadata-only (no full text), citation
counts are OpenAlex's at retrieval time, institutional/author disambiguation
is inherited from OpenAlex, and derived growth signals are estimates that scale
with sample size.
## Rights
Base metadata originates from OpenAlex (CC0). Derived fields and packaging are
original. No copyrighted full text, figures or supplementary files are included.
See `LICENSE_AND_RIGHTS.md`.
## Reproduce
```bash
pip install -r requirements.txt
python run-all.py
```
Retrieval dates and exact filters are recorded in `PROVENANCE.md` and
`metadata/source_queries.json`.
_Generated {_now()} by pipeline v{cfg['project']['version']}._
"""
def data_dictionary(cfg, stats) -> str:
out = [f"# Data Dictionary - {cfg['project']['title']}", "",
"All columns of every delivered table. Types are Arrow/Parquet types.", ""]
out += ["## data/works.parquet", "", "| Column | Type | Description |", "|---|---|---|"]
for name, typ, desc in WORKS_COLUMNS:
out.append(f"| `{name}` | {typ} | {desc} |")
out.append("")
for fname, cols in RELATION_COLUMNS.items():
out += [f"## data/{fname}", "", "| Column | Description |", "|---|---|"]
for name, desc in cols:
out.append(f"| `{name}` | {desc} |")
out.append("")
for fname, cols in ANALYTICS_COLUMNS.items():
out += [f"## analytics/{fname}", "", "| Column | Description |", "|---|---|"]
for name, desc in cols:
out.append(f"| `{name}` | {desc} |")
out.append("")
out += ["## Splits", "",
"`data/biomedical_works_train.jsonl.gz`, `..._validation.jsonl.gz`, "
"`..._test.jsonl.gz` contain the same columns as `data/works.parquet`, "
"split chronologically by publication year.", ""]
return "\n".join(out)
def methodology(cfg) -> str:
f = cfg["features"]
return f"""# Methodology
## 1. Collection
Metadata is retrieved from the OpenAlex REST API (`/works`) using OAuth-free
polite-pool access with a `mailto` identifier. Retrieval is resumable: each
(year, field) shard keeps its own checkpoint, requests are retried with
exponential backoff and jitter, and 429/5xx responses honour `Retry-After`.
## 2. Taxonomy filtering (no keyword search)
The biomedical scope is defined by OpenAlex **field IDs**:
| Field ID | Field |
|---|---|
| 13 | Biochemistry, Genetics and Molecular Biology |
| 24 | Immunology and Microbiology |
| 27 | Medicine |
| 28 | Neuroscience |
| 29 | Nursing |
| 30 | Pharmacology, Toxicology and Pharmaceutics |
| 35 | Dentistry |
| 36 | Health Professions |
These cover the requested areas (oncology, cardiology, public health,
epidemiology, infectious disease, genetics, surgery, psychiatry, pediatrics,
obstetrics & gynecology, radiology, anesthesiology, health policy, global
health, and more) through their subfields and topics. The taxonomy snapshot is
frozen under `metadata/taxonomy/` so normalization is deterministic.
## 3. Selection / sampling
The scope is partitioned into (publication_year x field) shards. A global target
row count is distributed across shards **in proportion to each shard's true
size**, and works are drawn with OpenAlex's **seeded random `sample`** operator.
Seeded sampling is essential: the default listing order returns the most-cited
works first (median ~1,300 citations), whereas the seeded sample reproduces the
true citation distribution (median 0-1). Each shard uses a deterministic seed,
so re-running reproduces the identical set. No record is duplicated to inflate
size.
## 4. Cleaning and normalization
- **Deduplication** by OpenAlex work ID and by normalized DOI.
- **DOI normalization**: lowercase, scheme/prefix stripped.
- **Date normalization** to ISO `YYYY-MM-DD`; invalid dates dropped.
- **Abstract reconstruction** from OpenAlex's inverted index into text.
- **Author normalization**: names, OpenAlex IDs, ORCIDs (bare form), positions,
corresponding flags; affiliations flattened.
- **Institution normalization**: IDs, names, ISO-3166 alpha-2 country codes.
- **Country normalization**: union of authorship and institution countries.
- **Topic normalization** to a frozen topic index (topic/subfield/field/domain).
- **Malformed removal**: rows without an ID or with empty titles are dropped.
- **Missing values** represented consistently as null.
## 5. Derived metrics (deterministic, reproducible)
Let `ref_year = max(publication_year)`, halflife = {f['recency_halflife_years']}y.
- `paper_age_years = ref_year - publication_year`
- `citations_per_year = cited_by_count / max(paper_age_years, 1)`
- `citation_velocity = recent_citations_3y / 3`
- `publication_recency_score = exp(-paper_age_years / halflife)`
- `citation_percentile` = percentile rank of `cited_by_count` **within
publication_year x field** (groups: {f['citation_percentile_group']}).
- `high_impact_flag = citation_percentile >= {f['high_impact_percentile']}`
- `international_collaboration = country_count >= 2`
- `multi_institutional = institution_count >= 2`
- Growth: each topic/field's yearly counts are split into an early and a late
half of the year range; `growth_ratio = (late+1)/(early+1)`, `cagr` from the
half-averages, `trend_slope` = OLS slope of yearly counts.
- `emerging_topic_flag = growth_ratio >= {f['emerging_growth_threshold']} and
late_count >= 50 and late > early`.
No derived field is generated by a language model; all values are computed from
OpenAlex metadata by the versioned code in `src/`.
## 6. Train / validation / test splitting
Chronological, to prevent leakage: a work appears in exactly one split
(works are unique and DOIs are deduplicated, so the same paper or DOI cannot
cross splits). Train <= {cfg['splits']['train_max_year']}, validation
{cfg['splits']['validation_years']}, test >= {cfg['splits']['test_min_year']}.
The complete unsplit dataset is retained as `data/works.parquet`.
## 7. Validation and packaging
Every Parquet table is validated against its canonical Arrow schema (column
names, types, required-column nulls, primary-key uniqueness). SHA-256 checksums
are written for all delivered files in `checksums.sha256`.
"""
def provenance(cfg, source_queries, stats, manifest) -> str:
queries = source_queries or []
rows = []
for q in queries:
rows.append(f"- retrieval started **{q.get('retrieval_started')}**, finished "
f"**{q.get('retrieval_finished')}**, {q.get('rows_collected'):,} rows, "
f"filters field IDs {q.get('field_ids')}, years {q.get('year_range')}, "
f"endpoint `{q.get('endpoint')}`")
qtext = "\n".join(rows) if rows else "- see metadata/source_queries.json"
return f"""# Provenance
## Source
The base metadata in this package originates from **OpenAlex**
(https://openalex.org), an open scholarly-metadata catalogue. OpenAlex data is
dedicated to the public domain under **CC0 1.0** (see `LICENSE_AND_RIGHTS.md`).
- API base: `{cfg['source']['base_url']}`
- Endpoint: `/works` (plus `/domains`, `/fields`, `/subfields`, `/topics` for taxonomy)
- Access: polite pool via `mailto`
- Selection operator: seeded random `sample` per (year x field) shard
## Retrieval records
{qtext}
## Transformations
1. Raw JSON pages are streamed to gzip-JSONL shards per (year, field).
2. `normalize.py` flattens nested objects, reconstructs abstracts, normalizes
identifiers and writes Parquet parts.
3. `derive_features.py` attaches derived metrics.
4. `build_relations.py` builds dimension tables and the internal citation graph.
5. `analyze.py` builds the analytics aggregates and statistics.
6. `validate.py` checks schemas; `package.py` writes the manifest, checksums
and archive.
Every stage is checkpointed and deterministic given the same config and seeds.
## Build
- Pipeline version: {cfg['project']['version']}
- Build timestamp: {manifest.get('build_timestamp')}
- Config file: `config.yaml` (frozen values in `metadata/build_info.json`)
## Reproducibility
Because sampling uses fixed seeds derived from shard keys, re-running the
collection reproduces the same works (subject to OpenAlex's own record
additions/updates between runs). Citation counts reflect OpenAlex at the
retrieval date above.
"""
def license_and_rights(cfg) -> str:
return f"""# License and Rights
This document separates three layers of rights so that nothing is misrepresented.
## 1. Original OpenAlex metadata (source layer)
The base bibliographic metadata is sourced from **OpenAlex**, which is made
available under **CC0 1.0 Universal (Public Domain Dedication)**.
OpenAlex aggregates metadata from Crossref, PubMed, MAG, institutional
repositories and others; it publishes the aggregated metadata openly.
- No exclusive ownership of OpenAlex source data is claimed.
- The underlying public metadata is **not** proprietary.
- Attribution to OpenAlex is given as a courtesy and is recorded in
`PROVENANCE.md`.
## 2. Derived content (this package's contribution)
The following are original to this project: the biomedical taxonomy-based
selection and stratification, cleaning and normalization, relational
restructuring, derived analytical features, quality control, documentation and
packaging.
This package is offered as a **curated, normalized, enriched and packaged
derivative dataset**. It does not claim exclusive rights over the source data.
## 3. Content intentionally excluded
The following are **not** included, because their redistribution rights are
unclear or restricted:
- Full-text articles, PDFs, HTML and publisher landing pages.
- Figures, tables, images and supplementary files.
- Any content flagged non-commercial or otherwise restricted.
- Any dataset with unclear commercial reuse rights.
Only OpenAlex metadata fields and abstracts that OpenAlex itself distributes
through its API are included. Abstracts are reconstructed from OpenAlex's
inverted-index metadata representation, which OpenAlex provides as part of its
open API; no publisher scraping or access-control circumvention was performed.
## Practical guidance for downstream users
- Cite OpenAlex as the metadata source.
- Verify the licence of any individual work before redistributing its abstract,
where a specific licence is required.
- `works.license` / `works.license_id` record the OpenAlex-reported licence of
the article's OA location where available.
_This document is not legal advice._
"""
def quality_report(cfg, validation, stats, norm_stats, derive_stats, files) -> str:
t = stats.get("totals", {})
missing = stats.get("missing_value_percent", {})
worst = sorted(missing.items(), key=lambda kv: -kv[1])[:15]
missing_rows = "\n".join(f"| `{k}` | {v}% |" for k, v in worst)
tables = []
for rel, info in (validation.get("tables") or {}).items():
tables.append(f"| `{rel}` | {info.get('rows', 'n/a')} | {info.get('status')} |")
tables_txt = "\n".join(tables)
return f"""# Quality Report
_Generated {_now()} by pipeline v{cfg['project']['version']}._
## Schema validation
Status: **{validation.get('status', 'unknown')}**
({len(validation.get('errors', []))} errors, {len(validation.get('warnings', []))} warnings)
| Table | Rows | Status |
|---|---|---|
{tables_txt}
## Malformed records
| Category | Count |
|---|---|
| Raw rows read | {norm_stats.get('raw_rows', 'n/a')} |
| Malformed / dropped (no ID or empty title) | {norm_stats.get('malformed', 'n/a')} |
| Duplicate work IDs removed | {norm_stats.get('dup_id', 'n/a')} |
| Duplicate DOIs removed | {norm_stats.get('dup_doi', 'n/a')} |
| Records kept | {norm_stats.get('kept', 'n/a')} |
## Missingness (top columns, by percent null)
| Column | % null |
|---|---|
{missing_rows}
## Citation statistics
`{stats.get('citation_statistics', {})}`
## International collaboration rate
{stats.get('international_collaboration_rate')}
## Suspicious / notable values
- Citation counts are OpenAlex's at retrieval time and can be 0 for recent works.
- `citation_velocity` is null where OpenAlex supplies no `counts_by_year`.
- `citation_percentile` is computed within (year x field); small shards in the
least-populated (year, field) cells have coarser percentiles.
- `emerging_topic_flag` requires >= 50 late-period works; small samples flag few
topics.
- OpenAlex primary-topic assignment is model-predicted and inherits its error.
## Coverage
- Year range: {stats.get('year_range')}
- Fields covered: {len(stats.get('works_per_field', {}))}
- Subfields covered: {len(stats.get('works_per_subfield', {}))}
- Countries covered: {len(stats.get('works_per_country', {}))}
- OpenAlex-supplied citation percentile and FWCI retained for cross-checks.
## Known limitations
1. Metadata-only: abstracts where OpenAlex provides them; no full text.
2. Sampling: this is a proportional stratified sample, not the full corpus;
rare cells are represented with fewer rows.
3. Author/institution identity is inherited from OpenAlex disambiguation.
4. Citation-based features are time-sensitive (snapshot at retrieval date).
5. Derived growth scores are estimates and scale with the sample size.
## Files validated
{len(files)} delivered files hashed in `checksums.sha256`.
"""