File size: 14,366 Bytes
cf08d94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | # science_face.py - World Science face: every OpenAlex work counted by subfield x country x year x type.
# usage: python science_face.py BASE_DIR [--upload] (needs: pip install duckdb pyarrow requests huggingface_hub)
# -*- coding: utf-8 -*-
import sys, os, io, time, datetime, requests
BASE = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith('--') else '.'
PART = os.path.join(BASE, 'part'); O = os.path.join(BASE, 'hf_world-science')
os.makedirs(PART, exist_ok=True); os.makedirs(O, exist_ok=True)
S3 = 'https://openalex.s3.amazonaws.com/'
S = requests.Session()
if os.environ.get('REQUESTS_CA_BUNDLE'): S.verify = os.environ['REQUESTS_CA_BUNDLE']
def U(s3url): return s3url.replace('s3://openalex/', S3)
def fw(p): return p.replace('\\', '/')
class RF(io.RawIOBase):
"""HTTP range-read file, so pyarrow fetches only the needed column chunks."""
def __init__(s, u):
s.u = u; s.p = 0; s.got = 0
s.n = int(S.head(u, timeout=60).headers['Content-Length'])
def readable(s): return True
def seekable(s): return True
def seek(s, o, w=0):
s.p = o if w == 0 else (s.p + o if w == 1 else s.n + o); return s.p
def tell(s): return s.p
def read(s, k=-1):
if k < 0: k = s.n - s.p
if k == 0 or s.p >= s.n: return b''
e = min(s.n, s.p + k) - 1
for t in range(5):
try:
r = S.get(s.u, headers={'Range': f'bytes={s.p}-{e}'}, timeout=120); r.raise_for_status(); b = r.content; break
except Exception:
if t == 4: raise
time.sleep(3 * (t + 1))
s.p += len(b); s.got += len(b); return b
def readinto(s, b):
d = s.read(len(b)); b[:len(d)] = d; return len(d)
COLS = ['publication_year', 'type', 'primary_topic.subfield.id', 'authorships.list.element.countries',
'open_access.is_oa', 'is_retracted', 'created_date', 'cited_by_count']
AGG = """
with w as (select publication_year y, type ty, primary_topic.subfield.id sf,
list_distinct(flatten(list_transform(authorships, lambda x: x.countries))) cc,
open_access.is_oa oa, is_retracted rt, cited_by_count cb, strftime(created_date,'%Y-%m') cm from t),
e as (select *, case when len(list_filter(cc, lambda x: x is not null))=0 then ['XX'] else list_filter(cc, lambda x: x is not null) end c2 from w),
u as (select y,ty,sf,oa,rt,cb,cm,unnest(c2) c, 1.0/len(c2) fr from e)
select coalesce(y,0) y,
case when ty in ('article','review','preprint','dataset','dissertation','letter','editorial') then ty
when ty in ('book','book-chapter','monograph','reference-entry') then 'book'
when ty in ('paratext','erratum','retraction','supplementary-materials','peer-review') then 'paratext' else 'other' end tc,
coalesce(replace(sf,'https://openalex.org/subfields/',''),'none') sf, c,
count(*) n, sum(fr) nf, sum(case when oa then 1 else 0 end) n_oa, sum(case when rt then 1 else 0 end) n_retracted,
sum(coalesce(cb,0)) cites, cm
from u group by all"""
def one(a):
import pyarrow.parquet as pq, duckdb
i, url = a
o = os.path.join(PART, f'{i:05d}.parquet')
if os.path.exists(o): return i, 0
for t in range(4):
try:
f = RF(U(url)); tb = pq.ParquetFile(f).read(columns=COLS); break
except Exception as ex:
if t == 3: return i, 'ERR ' + str(ex)[:200]
time.sleep(5 * (t + 1))
c = duckdb.connect(); c.register('t', tb)
pq.write_table(c.sql(AGG).to_arrow_table(), o + '.tmp'); os.replace(o + '.tmp', o)
return i, f.got
def lookups(m):
import pyarrow as pa, pyarrow.parquet as pq, duckdb
for ent, fn, q in [
('subfields', 'subfields.csv', "select replace(id,'https://openalex.org/subfields/','') subfield_id, display_name subfield, replace(field.id,'https://openalex.org/fields/','') field_id, field.display_name field, replace(domain.id,'https://openalex.org/domains/','') domain_id, domain.display_name AS \"domain\" from t order by 1"),
('countries', 'countries.csv', "select country_code, display_name country, continent.display_name continent, is_global_south, alpha_3 from t order by 1")]:
e = [x for x in m['entities'] if x['entity'] == ent][0]
t = pa.concat_tables([pq.read_table(RF(U(f['url']))) for f in e['files']], promote_options='default')
c = duckdb.connect(); c.register('t', t)
c.sql(f"copy ({q}) to '{fw(O)}/{fn}' (header)")
def build(SNAP):
import duckdb
P = fw(PART) + '/*.parquet'; OO = fw(O)
FET = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%MZ')
SRC = 'OpenAlex works snapshot ' + SNAP + ' (CC0), s3://openalex/data/parquet/works/'
c = duckdb.connect()
c.sql(f"create table a as select y,tc,sf,c,sum(n) n,sum(nf) nf,sum(n_oa) n_oa,sum(n_retracted) n_rt,sum(cites) cites from '{P}' group by all")
c.sql(f"create table m as select cm,tc,sf,c,sum(n) n,sum(nf) nf from '{P}' where cm>='2025-11' group by all")
c.sql(f"create table sfl as select * from read_csv('{OO}/subfields.csv')")
c.sql(f"create table cl as select * from read_csv('{OO}/countries.csv')")
tail = f", '{SRC}' AS source, '{SNAP}' AS snapshot_date, '{FET}' AS fetched_at"
J = "left join sfl on try_cast(a.sf as int)=sfl.subfield_id left join cl on a.c=cl.country_code"
PAP = "('article','review','book','letter','editorial','dissertation')"
def out(name, q, csv=True):
c.sql(f"copy ({q}) to '{OO}/{name}.parquet' (format parquet)")
if csv: c.sql(f"copy ({q}) to '{OO}/{name}.csv' (header)")
print(name, c.sql(f"select count(*) from '{OO}/{name}.parquet'").fetchall()[0], flush=True)
out('works_by_subfield_country_year_type', f"""select a.y AS "year", a.tc AS work_type, a.sf AS subfield_id, sfl.subfield, sfl.field, sfl.domain, a.c AS country_code, cl.country,
a.n AS works, round(a.nf,3) AS works_fractional, a.n_oa AS works_oa, a.n_rt AS retracted, a.cites AS citations{tail}
from a {J} where a.y between 1900 and 2026 order by 1,2,3,7""", csv=False)
out('papers_by_field_year', f"""select a.y AS "year", sfl.field_id, sfl.field, sfl.domain,
round(sum(case when tc in {PAP} then nf end)) AS papers, round(sum(case when tc='preprint' then nf end)) AS preprints,
round(sum(case when tc='dataset' then nf end)) AS datasets, round(sum(case when tc not in {PAP} and tc not in ('preprint','dataset') then nf end)) AS other_records,
round(log10(nullif(sum(case when tc in {PAP} then nf end),0)),2) AS log10_papers{tail}
from a {J} where a.y between 1900 and 2026 group by all order by 1,2""")
out('papers_by_country_year', f"""select a.y AS "year", a.c AS country_code, cl.country, cl.continent, cl.is_global_south,
sum(case when tc in {PAP} then n end) AS papers, round(sum(case when tc in {PAP} then nf end),1) AS papers_fractional,
sum(case when tc='preprint' then n end) AS preprints, sum(case when tc='dataset' then n end) AS datasets,
sum(case when tc in {PAP} then n_oa end) AS papers_oa, sum(case when tc in {PAP} then cites end) AS citations_of_papers{tail}
from a {J} where a.y between 1900 and 2026 group by all order by 1,2""")
out('new_records_by_month', f"""select a.cm AS month_added, a.tc AS work_type, sfl.field, a.c AS country_code, cl.country, sum(a.n) AS works, round(sum(a.nf),2) AS works_fractional{tail}
from m a {J} group by all order by 1,2,3,4""")
out('rising_subfield_country_2025', f"""with b as (select sf,c, sum(case when y=2025 and tc in {PAP} then n end) n25, sum(case when y between 2020 and 2024 and tc in {PAP} then n end)/5.0 base from a group by all)
select b.sf AS subfield_id, sfl.subfield, sfl.field, b.c AS country_code, cl.country, b.n25 AS papers_2025, round(b.base,1) AS mean_papers_2020_2024,
round(100.0*b.n25/nullif(b.base,0)) AS index_2025_vs_base100, round(log10(b.n25),2) AS log10_papers_2025{tail}
from b left join sfl on try_cast(b.sf as int)=sfl.subfield_id left join cl on b.c=cl.country_code
where b.n25>=100 and b.base>=20 and b.c<>'XX' and b.sf<>'none' order by index_2025_vs_base100 desc""")
README = r'''---
license: cc0-1.0
pretty_name: World Science (papers by field x country x year, from OpenAlex)
language:
- en
- ja
tags:
- science
- bibliometrics
- openalex
- research
- countries
- monthly
size_categories:
- 1M<n<10M
configs:
- config_name: papers_by_field_year
data_files: papers_by_field_year.csv
- config_name: papers_by_country_year
data_files: papers_by_country_year.csv
- config_name: rising_subfield_country_2025
data_files: rising_subfield_country_2025.csv
- config_name: new_records_by_month
data_files: new_records_by_month.parquet
- config_name: works_by_subfield_country_year_type
data_files: works_by_subfield_country_year_type.parquet
- config_name: subfields
data_files: subfields.csv
- config_name: countries
data_files: countries.csv
---
# World Science — every OpenAlex work counted by field x country x year x type
**All 464,765,485 works** in the OpenAlex snapshot of 2026-10-14, counted once each (the fractional totals add back to the snapshot record count). No sampling, no model, no API ranking: the whole snapshot was read column by column from the public OpenAlex S3 bucket and grouped.
Part of the [World Signals](https://huggingface.co/datasets/Lilambd/world-signals) family: one flat table per way of looking at the world. This one is the science face: where research is written, in which of 252 subfields, and what is rising.
Every row carries `source`, `snapshot_date` and `fetched_at`.
Quick start:
```python
from datasets import load_dataset
fy = load_dataset("Lilambd/world-science", "papers_by_field_year", split="train")
rising = load_dataset("Lilambd/world-science", "rising_subfield_country_2025", split="train")
```
| file | rows | what |
|---|---|---|
| `works_by_subfield_country_year_type.parquet` | 3.43M | year (1900-2026) x work type x subfield (252 + none) x author country. `works` = full counting (a work with authors in JP and US counts once for each), `works_fractional` = 1/k per country so totals do not double count. Also open-access count, retracted count, citations. |
| `papers_by_field_year.csv` | 3,429 | world total per field and year: papers, preprints, datasets, other records, log10 of papers |
| `papers_by_country_year.csv` | 18,007 | per country and year: papers (full and fractional), preprints, datasets, open-access papers, citations |
| `rising_subfield_country_2025.csv` | 8,716 | subfield x country cells where 2025 papers are compared with the 2020-2024 mean (index, base = 100). Only cells with at least 100 papers in 2025 and a mean of at least 20 |
| `new_records_by_month.parquet` | 204k | records that entered OpenAlex each month from 2025-11 to 2026-10, by type, field and country |
| `subfields.csv`, `countries.csv` | | lookups (subfield -> field -> domain; country -> continent, Global South flag) |
"papers" = article, review, book / chapter, letter, editorial, dissertation. Preprints and datasets are counted separately on purpose.
## Read before using (measured, not assumed)
- **Datasets swamp the totals from 2024.** OpenAlex type `dataset` was 24.9M records for publication year 2025, against 8.4M articles. About 18.1M of those 2025 datasets carry a Japanese affiliation, almost all in Nuclear and High Energy Physics and Aerospace Engineering. Count papers, not works, when comparing countries.
- **No country for many works.** `country_code = XX` means no author affiliation country is recorded. For 2025 that is 4.3M fractional papers, more than any single country.
- **Recent years are still filling.** 2026 is a partial year, and OpenAlex keeps adding records for past years.
- **Month added starts 2025-11.** OpenAlex rebuilt its index in 2025-10 and gave about 356M records that creation month, so earlier months are not a real flow and are left out.
- About 17.7M works with no publication year, or a year before 1900 or after 2026, are left out of the year tables.
- Country = country of the author's affiliation as OpenAlex records it, not nationality.
## Refresh
Rebuilt from each new OpenAlex snapshot (about monthly). The script that made it is `scripts/science_face.py` (it reads only the needed columns over HTTP range requests, about 2.4MB per 750MB file, 4.6GB for the whole snapshot, then builds the tables).
## Attribution
Data from [OpenAlex](https://openalex.org) (Priem, Piwowar and Orr, 2022), released CC0. Grouping and tables by [Lilambd](https://huggingface.co/Lilambd), also CC0. Questions or a slice you need: hello@lilambd.com
---
日本語: OpenAlex の論文など 4.65億件 (2026-10-14 時点) を全部、分野252 × 国 × 年 × 種類 で数えた台帳。2024年からは「データセット」の登録が論文より多く、2025年は日本の所属で約1,810万件 (ほぼ物理と航空宇宙) あるため、国を比べる時は papers を使う。
'''
if __name__ == '__main__':
from multiprocessing import Pool
m = S.get(S3 + 'data/parquet/manifest.json', timeout=120).json(); SNAP = m['date']
works = [e for e in m['entities'] if e['entity'] == 'works'][0]
fs = [(i, f['url']) for i, f in enumerate(works['files'])]
print('snapshot', SNAP, 'files', len(fs), 'records', works['record_count'], flush=True)
t0 = time.time(); n = 0; bad = 0
with Pool(int(os.environ.get('NP', '8'))) as P:
for i, g in P.imap_unordered(one, fs):
n += 1
if isinstance(g, str): bad += 1; print(i, g, flush=True)
if n % 100 == 0: print(n, '/', len(fs), round(time.time() - t0), 's', flush=True)
if bad: print('FAILED files:', bad, '- run again to retry only those'); sys.exit(1)
lookups(m); build(SNAP)
open(os.path.join(O, 'README.md'), 'w', encoding='utf-8', newline='\n').write(README)
os.makedirs(os.path.join(O, 'scripts'), exist_ok=True)
import shutil; shutil.copy(os.path.abspath(__file__), os.path.join(O, 'scripts', 'science_face.py'))
if '--upload' in sys.argv:
from huggingface_hub import HfApi
a = HfApi(); r = 'Lilambd/world-science'
a.create_repo(r, repo_type='dataset', exist_ok=True)
a.upload_folder(repo_id=r, repo_type='dataset', folder_path=O, ignore_patterns=['part/*'])
print('OK https://huggingface.co/datasets/' + r)
print('Done')
|