# 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 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')