import re
import textwrap
from functools import partial
from itertools import combinations
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sece_stats import periods
from sece_stats import small_groups as sg
pubs = data.load_publications()
pub_aff = data.load_publication_affiliations()
orgs = data.load_organizations().set_index("ror_id")
countries = data.load_countries().set_index("country_code")
authors = data.load_publication_authors() # only to count the SECE authors behind small counts
HOME = config.HOME_COUNTRY # "GR"
FIRST_YEAR = int(pubs["year"].min())
LAST_FULL = periods.LAST_FULL # the latest full year, PARTIAL - 1
# Five-year periods that end with the latest full year (sece_stats.periods), named by their role.
# period_of labels a year: the first period starts no earlier than FIRST_YEAR, and the partial year
# has a label of its own, so it never falls in a period.
period_of = partial(periods.period_of, first_year=FIRST_YEAR)
P_RECENT = period_of(LAST_FULL) # the latest five full years
P_PREV = period_of(LAST_FULL - 5) # the five years before them
P_EARLIER = period_of(LAST_FULL - 10) # the five years before those
P_BASE = period_of(LAST_FULL - 20) # the baseline, twenty years before the latest period
RECENT_START = periods.bounds(P_RECENT)[0] # first year of the latest period
EARLY = f"{FIRST_YEAR}–{RECENT_START - 1}" # the years before the latest period
MIN_INTL = 30 # periods with fewer international papers are not shown as shares
AS_OF_TEXT = f"{AS_OF.day} {AS_OF:%B %Y}" # the export date as text: day, month name, year
REGIONS = ["EU-27", "Other Europe", "North America", "Western Asia", "Rest of Asia", "Rest of world"]
EXT = "external-partner basis" # label of the values without SECE authors' own second affiliations
def region_of(c: pd.Series) -> str:
"""World region of a country: EU-27 membership first, then continent / UN subregion."""
if c["is_eu27"]:
return "EU-27"
if c["continent"] == "Europe":
return "Other Europe"
if c["continent"] == "North America":
return "North America"
if c["subregion"] == "Western Asia":
return "Western Asia"
if c["continent"] == "Asia":
return "Rest of Asia"
return "Rest of world"
def prose(code: str, start: bool = False) -> str:
"""Country name for running text ("the United Kingdom"), capitalised at a sentence start."""
name = countries.at[code, "country_name"]
if name.startswith("United ") or name in {"Netherlands", "Philippines"}:
name = f"the {name}"
return name[:1].upper() + name[1:] if start else name
def and_join(names: list[str]) -> str:
"""'a', 'a and b', 'a, b and c'."""
return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
def and_list(codes: list[str]) -> str:
"""'India and South Korea' from country codes."""
return and_join([prose(c) for c in codes])
def ordinal(rank: int) -> str:
"""'second' for rank 2 (ranks past 10 as 'number 11')."""
words = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"]
return words[rank - 1] if 1 <= rank <= len(words) else f"number {rank}"
def sole_max(s: pd.Series):
"""The index of the largest value of *s*, or None where several share it (for the guards of rankings)."""
top = s.index[s.eq(s.max())]
return top[0] if len(top) == 1 else None
def nth(n: int) -> str:
"""'20th', '21st', '22nd', '23rd'."""
return f"{n}{'th' if 10 <= n % 100 <= 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')}"
NEEDS_THE = re.compile(r"(?:University|National|Technical|International|Foundation|Centre|Center|Lebanese"
r"|Institute)\b")
def inst_prose(ror_id: str, start: bool = False) -> str:
"""Institution name for running text ("the University of Huddersfield"), capitalised at a
sentence start."""
name = orgs.at[ror_id, "name"]
name = f"the {name}" if NEEDS_THE.match(name) else name
return name[:1].upper() + name[1:] if start else name
countries["region"] = countries.apply(region_of, axis=1)
# ---- papers and their countries abroad ------------------------------------------------------
# Country of each affiliation: society memberships (match_method "ignored") are left out and
# AUTH affiliations count as Greece. This is the rule behind publications.is_international.
usable = pub_aff[pub_aff["match_method"].ne("ignored")].copy()
usable["country"] = usable["country_code"].where(~usable["is_auth"], HOME)
# An SECE author's own second affiliation (a joint, adjunct or visiting position): an affiliation
# outside AUTH whose holders are all SECE authors of the paper. The external-partner values, counting
# only affiliations of co-authors who are not SECE authors, leave these out (an affiliation that no
# author holds would still count); this is the rule behind publications.is_international_external.
usable["sece_only"] = ~usable["is_auth"] & usable["held_only_by_sece"].fillna(False).astype(bool)
# one row per (paper, country abroad); external: at least one of the paper's affiliations in that
# country is held by a co-author who is not an SECE author
links = (usable[usable["country"].notna() & usable["country"].ne(HOME)]
.assign(external=lambda d: ~d["sece_only"])
.groupby(["eid", "country"], as_index=False)
.agg(year=("year", "first"), external=("external", "any")))
links["region"] = links["country"].map(countries["region"])
links["period"] = links["year"].map(period_of)
links_x = links[links["external"]] # suffix _x: on the external-partner basis
assert set(links["eid"]) == set(pubs.loc[pubs["is_international"], "eid"]), "country rule out of sync"
assert set(links_x["eid"]) == set(pubs.loc[pubs["is_international_external"], "eid"]), "external rule out of sync"
# (paper, region) links; external: at least one of them is
region_links = (links.groupby(["eid", "region"], as_index=False)
.agg(year=("year", "first"), period=("period", "first"), external=("external", "any")))
# ---- small groups ----------------------------------------------------------------------------
# The page gives the number of papers that involve a country, a region, an institution or any country abroad
# at all only through SECE authors' own second affiliations (or an external-partner count from which it
# follows, alone or together with other values shown, on this page or on other pages) only when it is zero or
# at least config.MIN_SECE_HOLDERS distinct SECE authors hold these affiliations. With fewer it would in practice
# be one or two people's paper count, which the site does not publish: the text then describes it in words and
# the figures leave the external-partner value out. The values of all countries together (the papers
# international only through such affiliations, by year, period or window of years) are given by several pages:
# the site's rule (sece_stats.small_groups, the same for every page; rule below) decides which of them the pages
# give, from the values of all pages together and what a reader knows of those left out. For the places, two passes
# decide what is shown: shown_cells, for the values of one place in different years, then an audit of all values
# together, with those that other pages give (all countries together, institutions abroad), for the combinations
# across places ("small groups across places", before the checks). own_holders: one row per SECE-only affiliation abroad and SECE author who
# holds it, as the rule counts them (author ids are only counted, never shown).
MIN_HOLDERS = config.MIN_SECE_HOLDERS
rule = sg.site()
# Hover text of a value left out. It states no reason of its own: some values rest on fewer than MIN_HOLDERS SECE
# authors, others are left out only because, with the values shown, they would reveal such a number (or because
# their period's international papers on that basis are left out); the notes explain the rule.
NOT_SHOWN = "not shown (see the notes on small groups)"
own_holders = sg.own_holders(pub_aff, authors) # every holder is an SECE author (checked there)
own_holders = (own_holders[sg.places(own_holders)["abroad"]].reset_index(drop=True)
.rename(columns={"country_code": "country", "org": "ror_id_top"}))
own_holders["region"] = own_holders["country"].map(countries["region"])
own_abroad = usable[usable["sece_only"] & usable["country"].notna() & usable["country"].ne(HOME)]
assert set(zip(own_holders["eid"], own_holders["country"])) == set(zip(own_abroad["eid"], own_abroad["country"])), \
"the rule's own affiliations abroad are the page's SECE-only affiliations abroad"
def held_by_year(sece_only: pd.DataFrame, key: str) -> dict:
"""For each *key* value (a country, region or ror_id_top) of *sece_only*, the (paper, key) pairs
linked only through SECE authors' own second affiliations: {year: the SECE authors who hold them}."""
held = own_holders.merge(sece_only[["eid", key, "year"]].drop_duplicates(), on=["eid", key])
return {k: g.groupby("year")["author_id"].agg(set).to_dict() for k, g in held.groupby(key)}
def rests_on(held: dict, years: frozenset) -> int:
"""Distinct SECE authors behind a place's links of these years (held: the place's held_by_year)."""
return len(set().union(*(held.get(year, set()) for year in years)))
def shown_cells(held: dict, cells: dict[str, frozenset]) -> dict[str, bool]:
"""Which external-partner values of a place may be shown. *cells* maps each value that the page gives
for the place (all years, a period, ...) to its years, in order of importance; *held* is the place's
held_by_year. Next to the count of all affiliations, an external-partner value gives the number of
papers linked to the place only through SECE authors' own second affiliations, and two values give
the difference of these numbers (all years minus a period, say). A value is shown when, with the
values shown before it, every number that follows rests on no SECE author or on at least MIN_HOLDERS.
The cells are nested or disjoint, so these numbers are sums of remainders (a cell minus the cells
shown inside it), and it is enough to check the remainders."""
shown, out = [], {}
for name, years in cells.items():
trial = [*shown, years]
assert all(a <= b or b <= a or not a & b for a in trial for b in trial), "cells must be nested or disjoint"
rests = [rests_on(held, cell.difference(*[c for c in trial if c < cell])) for cell in trial]
out[name] = all(n == 0 or n >= MIN_HOLDERS for n in rests)
if out[name]:
shown.append(years)
return out
def sece_part(m: int, n: int, ok: bool) -> str:
"""'m of the n': m of n papers involve a place only through SECE authors' own second affiliations;
in words ('most of the n', 'half of the n', 'part of the n') when m may not be shown (*ok* False)."""
if ok:
return f"{dp.fmt_int(m)} of the {dp.fmt_int(n)}"
return f"{'most' if 2 * m > n else 'half' if 2 * m == n else 'part'} of the {dp.fmt_int(n)}"
pubs["period"] = pubs["year"].map(period_of)
full = pubs[pubs["year"] < PARTIAL] # full calendar years only
intl, intl_x = pubs[pubs["is_international"]], pubs[pubs["is_international_external"]]
n_pubs, n_intl, n_intl_x = len(pubs), len(intl), len(intl_x)
share_intl, share_intl_x = n_intl / n_pubs, n_intl_x / n_pubs
intl_period = full[full["is_international"]].groupby("period").size()
intl_period_x = full[full["is_international_external"]].groupby("period").size()
n_intl_early, n_intl_early_x = int((intl["year"] < RECENT_START).sum()), int((intl_x["year"] < RECENT_START).sum())
n_intl_recent, n_intl_recent_x = int(intl_period[P_RECENT]), int(intl_period_x[P_RECENT])
n_intl_last, n_intl_last_x = int(intl["year"].eq(LAST_FULL).sum()), int(intl_x["year"].eq(LAST_FULL).sum())
no_country = usable[~usable["is_auth"] & usable["country"].isna()]
n_aff_no_country, n_pubs_no_country = len(no_country), no_country["eid"].nunique()
def papers_by_country(mask: pd.Series | None = None, external: bool = False) -> pd.Series:
"""Distinct papers per partner country (optionally for a subset of the links); with
``external``, only links through an affiliation of a co-author who is not an SECE author."""
sub = links if mask is None else links[mask]
return (sub[sub["external"]] if external else sub).groupby("country")["eid"].nunique()
# ---- partner institutions abroad ------------------------------------------------------------
# A partner institution abroad is the top-level ROR organisation, located outside Greece, of an
# affiliation abroad (a Greek branch of a foreign organisation does not count).
abroad = usable[~usable["is_auth"] & usable["country"].notna() & usable["country"].ne(HOME)]
share_abroad_matched = abroad["ror_id"].notna().mean()
inst_links = abroad[abroad["ror_id_top"].notna()
& abroad["ror_id_top"].map(orgs["country_code"]).ne(HOME)].copy()
# one row per (institution, paper); sece_only: the paper names the institution only in SECE authors'
# own second affiliations
inst_papers = (inst_links.groupby(["ror_id_top", "eid"], as_index=False)
.agg(year=("year", "first"), sece_only=("sece_only", "all")))
inst = (inst_papers.groupby("ror_id_top").agg(papers=("eid", "size"), sece_only=("sece_only", "sum"))
.join(orgs[["name", "country_name", "primary_type"]])
.sort_values(["papers", "name"], ascending=[False, True]))
inst["papers_x"] = inst["papers"] - inst["sece_only"]
inst["mostly_sece"] = inst["sece_only"] >= 0.5 * inst["papers"] # counted in the text
inst_held = held_by_year(inst_papers[inst_papers["sece_only"]], "ror_id_top") # small groups
n_inst, n_inst_x, n_inst_mostly = len(inst), int(inst["papers_x"].gt(0).sum()), int(inst["mostly_sece"].sum())
# foreign institutions named only in affiliations located in Greece (a Greek campus or branch)
top_country = usable["ror_id_top"].map(orgs["country_code"])
foreign_tops = set(usable.loc[~usable["is_auth"] & top_country.notna() & top_country.ne(HOME), "ror_id_top"])
n_branch_only = len(foreign_tops - set(inst.index))
share_intl_with_inst = inst_links["eid"].nunique() / n_intl
inst_by_country = (inst_links.groupby(["country", "ror_id_top"])["eid"].nunique().rename("n").reset_index()
.assign(name=lambda d: d["ror_id_top"].map(orgs["name"]))
.sort_values(["country", "n", "name"], ascending=[True, False, True]))
inst_country = inst_by_country.drop_duplicates("country").set_index("country") # most frequent institution per country
inst_tied = inst_by_country[inst_by_country["n"].eq(inst_by_country["country"].map(inst_country["n"]))] # and ties
inst_hidden = set() # (ror_id, cell) left out across places (small groups, below)
def inst_shown(ror_id: str) -> dict[str, bool]:
"""shown_cells for an institution: the text gives its value of all years and, for the two leading
Western Asian institutions, also that of P_RECENT, which comes first; less those left out across places."""
cells = ({"recent": years_of(P_RECENT)} if ror_id in wa_top2 else {}) | {"papers": ALL_YEARS}
return {cell: ok and (ror_id, cell) not in inst_hidden
for cell, ok in shown_cells(inst_held.get(ror_id, {}), cells).items()}
def inst_counts(ror_id: str, recent: bool = False) -> tuple[int, int, bool]:
"""Papers naming an institution abroad (all years, or P_RECENT with *recent*), how many of them name
it only in SECE authors' own second affiliations, and whether that number may be shown (small groups)."""
sub = inst_papers[inst_papers["ror_id_top"].eq(ror_id)]
if recent:
sub = sub[sub["year"].map(period_of).eq(P_RECENT)]
return len(sub), int(sub["sece_only"].sum()), inst_shown(ror_id).get("recent" if recent else "papers", False)
# ---- SECE authors' own second affiliations abroad (the note on dual affiliations) --------------
n_aff_usable, n_no_holder = len(usable), int(usable["held_only_by_sece"].isna().sum())
n_aff_abroad, n_aff_abroad_sece = len(abroad), int(abroad["sece_only"].sum())
n_pubs_abroad_sece = abroad.loc[abroad["sece_only"], "eid"].nunique()
n_only_sece = n_intl - n_intl_x # international only through SECE authors' own second affiliations
only_sece_period = intl_period.sub(intl_period_x, fill_value=0).astype("int64")
n_only_sece_last = n_intl_last - n_intl_last_x
# ---- papers per partner country -------------------------------------------------------------
by_country = pd.DataFrame({
"papers": papers_by_country(),
"early": papers_by_country(links["year"] < RECENT_START),
"recent": papers_by_country(links["period"].eq(P_RECENT)),
"papers_x": papers_by_country(external=True),
"early_x": papers_by_country(links["year"] < RECENT_START, external=True),
"recent_x": papers_by_country(links["period"].eq(P_RECENT), external=True),
"first_year": links.groupby("country")["year"].min(),
}).fillna(0).astype("int64")
by_country = by_country.join(countries[["country_name", "iso3", "continent", "region"]])
for sfx, total, early, recent in (("", n_intl, n_intl_early, n_intl_recent),
("_x", n_intl_x, n_intl_early_x, n_intl_recent_x)):
by_country["share" + sfx] = by_country["papers" + sfx] / total
by_country["sh_early" + sfx] = by_country["early" + sfx] / early
by_country["sh_recent" + sfx] = by_country["recent" + sfx] / recent
by_country["delta" + sfx] = by_country["sh_recent" + sfx] - by_country["sh_early" + sfx]
own_links = links[~links["external"]] # the (paper, country) links only through SECE-only affiliations
def main_inst(code: str) -> str:
"""Map hover: a country's most frequent partner institution and its papers; where several tie, all of them
(the first three and how many more), wrapped onto lines of about 60 characters."""
if code not in inst_country.index:
return "–"
names, n = inst_tied.loc[inst_tied["country"].eq(code), "name"].tolist(), dp.fmt_int(inst_country.at[code, "n"])
if len(names) == 1:
return f"{names[0]} ({n})"
names = names if len(names) <= 3 else [*names[:3], f"{len(names) - 3} more"]
tied = f"(tied, {n} each)".replace(" ", "\u00a0") # no-break spaces: kept on one line
return "<br>".join(textwrap.wrap(f"{and_join(names)} {tied}", 60, break_on_hyphens=False, break_long_words=False))
by_country["main_inst"] = [main_inst(c) for c in by_country.index]
by_country = by_country.sort_values(["papers", "country_name"], ascending=[False, True])
n_countries = len(by_country)
n_countries_x = int(by_country["papers_x"].gt(0).sum()) # countries with an external partner
n_countries_10 = int((by_country["papers"] >= 10).sum())
n_countries_100 = int((by_country["papers"] >= 100).sum())
n_countries_1 = int((by_country["papers"] == 1).sum())
# share of all (paper, country abroad) links that fall on the countries with 100 or more papers
share_links_100 = by_country.loc[by_country["papers"] >= 100, "papers"].sum() / by_country["papers"].sum()
n_continents = by_country["continent"].nunique()
eu_other = sorted(config.EU27 - {HOME})
n_eu_partners = int(by_country.index.isin(eu_other).sum())
eu_partners_txt = (f"all {len(eu_other)}" if n_eu_partners == len(eu_other)
else f"{n_eu_partners} of the {len(eu_other)}")
lead = list(by_country.index[:3])
lead_cap, lead_n = prose(lead[0], start=True), by_country.loc[lead, "papers"].tolist()
lead_n_x = by_country.loc[lead, "papers_x"].tolist()
lead_txt = [prose(c) for c in lead]
# countries after the first two with more papers than the third, on the external-partner basis
ahead_x = [c for c in by_country.index[3:] if by_country.at[c, "papers_x"] > by_country.at[lead[2], "papers_x"]]
def pct(code: str, col: str) -> str:
"""A country's share in column ``col`` of by_country, as text."""
return dp.fmt_pct(by_country.at[code, col])
def num(code: str, col: str) -> str:
"""A country's number of papers in column ``col`` of by_country, as text."""
return dp.fmt_int(by_country.at[code, col])
SHOWN_COL = {"papers": "shown", "early": "shown_early", "recent": "shown_recent"}
def country_part(code: str, col: str = "papers") -> str:
"""sece_part for a country: of its papers in column ``col`` ("papers", "early", "recent"), those
with an affiliation there only through SECE authors' own second affiliations."""
n, n_x = by_country.at[code, col], by_country.at[code, col + "_x"]
return sece_part(n - n_x, n, bool(by_country.at[code, SHOWN_COL[col]]))
def change_text(code: str, sfx: str = "") -> str:
"""'France (from a% to b%)': a country's share of the international papers of EARLY (the years
before the latest period) and of P_RECENT; on the external-partner basis (sfx "_x") the shares only
where both may be shown."""
if sfx and not (by_country.at[code, "shown_early"] and by_country.at[code, "shown_recent"]):
return prose(code)
return f"{prose(code)} (from {pct(code, 'sh_early' + sfx)} to {pct(code, 'sh_recent' + sfx)})"
# ---- countries by region (table) -------------------------------------------------------------
region_tbl = pd.DataFrame({
"countries": by_country.groupby("region").size(),
"papers": links.groupby("region")["eid"].nunique(),
"papers_x": links_x.groupby("region")["eid"].nunique(),
"list": by_country.groupby("region", sort=False)[["country_name", "papers"]].apply(
lambda d: ", ".join(f"{n} ({dp.fmt_int(p)})" for n, p in zip(d["country_name"], d["papers"]))),
}).reindex(REGIONS)
region_tbl["papers_x"] = region_tbl["papers_x"].fillna(0).astype("int64")
region_tbl["share"] = region_tbl["papers"] / n_intl
region_tbl["share_x"] = region_tbl["papers_x"] / n_intl_x
reg_all, reg_all_x, reg_n_x = region_tbl["share"], region_tbl["share_x"], region_tbl["papers_x"]
reg_order, reg_order_x = (list(s.sort_values(ascending=False).index) for s in (reg_all, reg_all_x))
wa_place, wa_place_x = (ordinal(order.index("Western Asia") + 1) for order in (reg_order, reg_order_x))
region_tbl = region_tbl.rename_axis("region").reset_index()
region_lists = dict(zip(region_tbl["region"], region_tbl["list"])) # listed below the table
# The text lists the regions by their share: the EU-27 first and the rest of the world last (checked
# below), the others in between in the order of the data.
REGION_TEXT = {"EU-27": "the EU-27", "Other Europe": "the rest of Europe", "North America": "North America",
"Western Asia": "Western Asia", "Rest of Asia": "the rest of Asia", "Rest of world": "the rest of the world"}
def region_item(region: str) -> str:
"""'Western Asia (x%)': a region and its share of the international papers; for the rest of
Europe also the United Kingdom's share."""
uk = f"; {prose('GB')} alone {pct('GB', 'share')}" if region == "Other Europe" else ""
return f"{REGION_TEXT[region]} ({dp.fmt_pct(reg_all[region])}{uk})"
regions_txt = and_join([region_item(r) for r in reg_order if r not in ("EU-27", "Rest of world")])
# on the external-partner basis: the regions that move ahead of Western Asia, in their order on that basis
wa_passed = [r for r in reg_order_x[:reg_order_x.index("Western Asia")]
if reg_order.index(r) > reg_order.index("Western Asia")]
wa_passed_txt = and_join([REGION_TEXT[r] for r in wa_passed]) if wa_passed else ""
# ---- leading countries: EARLY (the years before the latest period) vs P_RECENT --------------------
top20_all = by_country.nlargest(20, "papers", keep="all").index
top20_recent = by_country.nlargest(20, "recent", keep="all").index
top_countries = by_country[by_country.index.isin(top20_all.union(top20_recent))] # all-years order
n_top = len(top_countries)
newcomers = [c for c in top_countries.index if c not in top20_all]
dropouts = [c for c in top_countries.index if c not in top20_recent]
top20_all_x = by_country.nlargest(20, "papers_x", keep="all").index
top20_recent_x = by_country.nlargest(20, "recent_x", keep="all").index
newcomers_x = [c for c in by_country.index if c in top20_recent_x and c not in top20_all_x]
dropouts_x = [c for c in by_country.index if c in top20_all_x and c not in top20_recent_x]
moves, moves_x = top_countries.sort_values("delta"), top_countries.sort_values("delta_x")
gainers, losers = list(moves.index[::-1][:2]), list(moves.index[:2])
gainers_x, losers_x = list(moves_x.index[::-1][:2]), list(moves_x.index[:2])
def tie_note(top: pd.Index, col: str, k: int = 20) -> str:
"""' (21, as A and B tie for 20th place)' when countries that tie at the cut make the k
leading partners by column ``col`` more than k; otherwise ''."""
if len(top) <= k:
return ""
cut = by_country.loc[top, col].min()
tied = [c for c in by_country.index if c in top and by_country.at[c, col] == cut]
rank = int(by_country[col].gt(cut).sum()) + 1
return f" ({len(top)}, as {and_list(tied)} tie for {ordinal(rank) if rank <= 10 else nth(rank)} place)"
top20_ties = tie_note(top20_all, "papers"), tie_note(top20_recent, "recent") # for the caption and text
# the latest period's top 20 against the all-years top 20, as text; on the external-partner basis in full
# only where its newcomers differ
top20_swap_txt = f"{and_list(newcomers)} instead of {and_list(dropouts)}" if newcomers and dropouts else ""
top20_swap_x_txt = ("" if not (newcomers_x and dropouts_x)
else f" (instead of {and_list(dropouts_x)} on the external-partner basis)"
if newcomers_x == newcomers
else f"; on the external-partner basis, {and_list(newcomers_x)} instead of {and_list(dropouts_x)}")
# ---- the eight leading countries and the world regions by 5-year period -------------------------
assert set(intl_period.index) <= set(rule.periods), "the page's periods are those of the site's rule"
SHOWN = [p for p in rule.periods if intl_period.get(p, 0) >= MIN_INTL] # the periods shown, ... P_RECENT
first_shown = SHOWN[0]
# the eight leading countries (heatmap), with all those that tie for eighth place (by_country is in order of papers)
top8 = list(by_country.index[by_country["papers"].ge(by_country["papers"].iloc[7])])
top8_ties = tie_note(pd.Index(top8), "papers", 8) # for the caption
# ---- small groups: which external-partner values may be shown --------------------------------------
# The values the page gives for a place, as sets of years, in order of importance for shown_cells: the
# latest period (text, ticks, the last period of the heatmap and of the regions chart), all years (map,
# table, text), EARLY (ticks), then the earlier periods of the heatmap and the regions chart, newest first.
def years_of(period: str) -> frozenset:
"""The years of a period label."""
return frozenset(sg.years_of(period))
# All countries together: the international papers on both bases of all years (text, KPI), of EARLY and P_RECENT
# (captions), of P_BASE, P_RECENT and LAST_FULL (notes) and of each period shown (the n of the period labels). Their
# difference is the number of papers international only through SECE authors' own second affiliations abroad, which
# Collaboration and the Overview also give, by year and period. The page gives only values that the site's rule
# publishes (rule.is_published, checked below), over the rule's windows of years (rule.windows), and no
# external-partner value of a period whose value the rule leaves out (a share would give it).
WINDOW = {"papers": "all years", "early": "before the latest period", "recent": "latest period",
"last": "latest full year"} # the page's names for the windows of the site's rule
CELL_YEARS = {name: rule.windows[window].years for name, window in WINDOW.items()}
ALL_YEARS, EARLY_YEARS = CELL_YEARS["papers"], CELL_YEARS["early"]
assert (min(ALL_YEARS), max(ALL_YEARS), min(EARLY_YEARS), max(EARLY_YEARS)) == (FIRST_YEAR, PARTIAL, FIRST_YEAR,
RECENT_START - 1) \
and CELL_YEARS["recent"] == years_of(P_RECENT) and CELL_YEARS["last"] == {LAST_FULL} \
and rule.windows["base period"].years == years_of(P_BASE), "the page's windows are those of the site's rule"
only_sece_eids = set(intl["eid"]) - set(intl_x["eid"])
SHOWN_X = [p for p in SHOWN if rule.is_published(years_of(p))] # periods with external-partner values
period_ticks = [f"{p}<br>n = {dp.fmt_int(intl_period[p])} / "
f"{dp.fmt_int(intl_period_x[p]) if p in SHOWN_X else '–'}" for p in SHOWN]
OLDER = {p: years_of(p) for p in reversed(SHOWN_X) if p != P_RECENT}
def country_cells(code: str) -> dict[str, frozenset]:
"""The values the page gives for a country: all years (map) and, for the countries of the top-countries
chart, also EARLY and P_RECENT (ticks; the text names some), and for the eight leading countries the
periods of the heatmap."""
if code not in top_countries.index:
return {"papers": ALL_YEARS}
return {"recent": years_of(P_RECENT), "papers": ALL_YEARS, "early": EARLY_YEARS} | (OLDER if code in top8 else {})
country_held = held_by_year(own_links, "country")
country_ok = pd.DataFrame.from_dict(
{c: shown_cells(country_held.get(c, {}), country_cells(c)) for c in by_country.index}, orient="index")
for col, cell in (("shown", "papers"), ("shown_early", "early"), ("shown_recent", "recent")):
by_country[col] = country_ok[cell].eq(True) # False where the page gives no such value
cs_shown = pd.DataFrame({c: [bool(p in SHOWN_X and country_ok.at[c, "recent" if p == P_RECENT else p])
for p in SHOWN] for c in top8}, index=SHOWN) # the heatmap: periods (rows), countries
region_held = held_by_year(region_links[~region_links["external"]], "region")
region_ok = pd.DataFrame.from_dict(
{r: shown_cells(region_held.get(r, {}), {"recent": years_of(P_RECENT), "papers": ALL_YEARS} | OLDER)
for r in REGIONS}, orient="index")
region_shown = pd.DataFrame({r: [bool(p in SHOWN_X and region_ok.at[r, "recent" if p == P_RECENT else p])
for p in SHOWN] for r in REGIONS}, index=SHOWN) # the regions chart
def by_period(lk: pd.DataFrame, key: str) -> pd.DataFrame:
"""Distinct full-year papers per period shown (rows) and country or region (columns)."""
return (lk[lk["year"] < PARTIAL].groupby(["period", key])["eid"].nunique()
.unstack(fill_value=0).reindex(SHOWN, fill_value=0))
country_period = by_period(links, "country")
country_period_x = by_period(links_x, "country").reindex(columns=country_period.columns, fill_value=0)
country_share = country_period.div(intl_period[SHOWN], axis=0)
country_share_x = country_period_x.div(intl_period_x[SHOWN], axis=0)
cs, cs_x = country_share[top8], country_share_x[top8]
US, AE, CN, FR, FI, LB = "US", "AE", "CN", "FR", "FI", "LB" # countries named in the text (checked below)
FRAUNHOFER = "https://ror.org/05hkkdn48" # institution named in the text
# the US's rank in the latest period, counting all affiliations and on the external-partner basis
us_ranks = [int(s.loc[P_RECENT].rank(ascending=False, method="min")[US]) for s in (country_share, country_share_x)]
us_rank_txt = ordinal(us_ranks[0])
us_rank_x_txt = f"also {us_rank_txt}" if us_ranks[1] == us_ranks[0] else ordinal(us_ranks[1])
fi_peak = cs[FI].idxmax()
fi_main = inst_country.at[FI, "ror_id_top"]
fi_peak_eids = set(links.loc[links["country"].eq(FI) & links["period"].eq(fi_peak), "eid"])
n_fi_peak = len(fi_peak_eids)
n_fi_peak_main = len(fi_peak_eids & set(inst_links.loc[inst_links["ror_id_top"].eq(fi_main), "eid"]))
region_period = by_period(links, "region").reindex(columns=REGIONS, fill_value=0)
region_period_x = by_period(links_x, "region").reindex(columns=REGIONS, fill_value=0)
region_share = region_period.div(intl_period[SHOWN], axis=0)
region_share_x = region_period_x.div(intl_period_x[SHOWN], axis=0)
eu, na, wa, ra = (region_share[r] for r in ("EU-27", "North America", "Western Asia", "Rest of Asia"))
eu_x, na_x, wa_x, ra_x = (region_share_x[r] for r in ("EU-27", "North America", "Western Asia", "Rest of Asia"))
na_n, na_n_x = region_period["North America"], region_period_x["North America"]
wa_n, wa_n_x = region_period["Western Asia"], region_period_x["Western Asia"]
eu_min, eu_max = eu.loc[P_BASE:].min(), eu.loc[P_BASE:].max()
# P_RECENT: largest difference between the two counts for the regions other than Western Asia,
# rounded up to whole percentage points for the text ("less than N points")
other_gap = (region_share_x - region_share).loc[P_RECENT].drop("Western Asia").abs().max()
other_gap_max = int(np.floor(100 * other_gap)) + 1
recent_intl = set(intl.loc[intl["period"].eq(P_RECENT), "eid"])
share_no_eu_recent = 1 - len(set(links.loc[links["region"].eq("EU-27"), "eid"]) & recent_intl) / len(recent_intl)
wa_names = and_list(list(by_country.index[by_country["region"].eq("Western Asia")]))
ra_recent = links[links["region"].eq("Rest of Asia") & links["period"].eq(P_RECENT)].groupby("country")["eid"].nunique()
ra_lead = ra_recent.idxmax()
# Western Asia: how much of it comes from its two most frequent partner institutions, and how much
# from SECE authors' own second affiliations
wa_inst = (inst_links[inst_links["country"].map(countries["region"]).eq("Western Asia")]
.groupby("ror_id_top")["eid"].nunique().sort_values(ascending=False))
wa_top2 = list(wa_inst.index[:2])
KHALIFA, LAU = wa_top2 # Khalifa University (UAE), Lebanese American University (checked below)
wa_top2_txt = [inst_prose(r) for r in wa_top2]
wa_top2_eids = set(inst_links.loc[inst_links["ror_id_top"].isin(wa_top2), "eid"])
wa_recent = set(links.loc[links["region"].eq("Western Asia"), "eid"]) & recent_intl
n_wa_recent, n_wa_recent_top2 = len(wa_recent), len(wa_recent & wa_top2_eids)
others_recent = recent_intl - wa_top2_eids
share_wa_others = len(wa_recent & others_recent) / len(others_recent)
n_wa_recent_sece = n_wa_recent - int(wa_n_x[P_RECENT]) # Western Asia only through such affiliations
# ---- breadth: partner countries per year ---------------------------------------------------------
first_year = by_country["first_year"]
per_year = pd.DataFrame({
"total": links.groupby("year")["country"].nunique(),
"new": first_year.value_counts(),
}).reindex(range(int(links["year"].min()), PARTIAL + 1)).fillna(0).astype("int64").rename_axis("year")
per_year["returning"] = per_year["total"] - per_year["new"]
full_years = per_year.loc[:LAST_FULL, "total"]
full_years_x = links_x.groupby("year")["country"].nunique().reindex(full_years.index, fill_value=0)
avg_c_base, avg_c_recent = (full_years.loc[slice(*periods.bounds(p))].mean() for p in (P_BASE, P_RECENT))
c_last, c_last_x = int(full_years[LAST_FULL]), int(full_years_x[LAST_FULL])
def year_x_ok(year: int) -> bool:
"""May a year's number of partner countries be given on the external-partner basis (small groups)? The
countries that the year's papers involve only through SECE authors' own second affiliations, the difference
from the count of all affiliations, must rest on no SECE author or on at least MIN_HOLDERS."""
lk = links[links["year"].eq(year)]
own = lk[~lk["country"].isin(lk.loc[lk["external"], "country"])]
n = own_holders.merge(own[["eid", "country"]], on=["eid", "country"])["author_id"].nunique()
return n == 0 or n >= MIN_HOLDERS
def record_txt(counts: pd.Series, numbers=lambda year: True) -> str:
"""The latest full year against the earlier years of a yearly count: 'more than any earlier year',
'as many as in <year>' or 'fewer than the <n> of <year>' ('fewer than in <year>' where numbers(year) is
False: that count may not be shown)."""
earlier = counts[counts.index < LAST_FULL]
top, last = int(earlier.max()), int(counts[LAST_FULL])
tops = list(earlier.index[earlier.eq(top)])
years = and_join([str(y) for y in tops])
if last > top:
return "more than any earlier year"
if last == top:
return f"as many as in {years}"
return f"fewer than the {dp.fmt_int(top)} of {years}" if all(numbers(y) for y in tops) else f"fewer than in {years}"
c_last_txt, c_last_x_txt = record_txt(full_years), record_txt(full_years_x, numbers=year_x_ok)
if c_last_txt == c_last_x_txt == "more than any earlier year":
c_last_x_txt = "also more than any earlier year"
# LAST_FULL on the external-partner basis, with its number where it may be shown (small groups)
if year_x_ok(LAST_FULL):
c_last_x_note = f"{dp.fmt_int(c_last_x)} on the external-partner basis, {c_last_x_txt}"
elif c_last_x_txt == "also more than any earlier year":
c_last_x_note = "also on the external-partner basis"
else:
c_last_x_note = f"{c_last_x_txt} on the external-partner basis"
# the partial year, named when its papers already involve more partner countries than those of LAST_FULL
c_part = int(per_year.at[PARTIAL, "total"])
c_part_x = links_x.loc[links_x["year"].eq(PARTIAL), "country"].nunique()
part_txt = (f"; those of {PARTIAL} so far already involve {dp.fmt_int(c_part)}"
+ (f" ({dp.fmt_int(c_part_x)} on the external-partner basis)" if year_x_ok(PARTIAL) else "")
if c_part > c_last else "")
# The step up of the yearly count: the latest year from which every full year (at least five of them) has
# had more partner countries than any year before it; the text gives the range since then.
step_years = [int(y) for y in full_years.index[1:] if y <= LAST_FULL - periods.WIDTH + 1
and full_years.loc[y:].min() > full_years.loc[:y - 1].max()]
step_year = step_years[-1] if step_years else LAST_FULL - periods.WIDTH + 1 # no step: a check below fails
c_low, c_high = int(full_years.loc[step_year:].min()), int(full_years.loc[step_year:].max())
def years_in(period: str) -> int:
"""Number of years in a period label."""
first, last = periods.bounds(period)
return last - first + 1
avg_i_base, avg_i_recent = (intl_period[p] / years_in(p) for p in (P_BASE, P_RECENT))
n_first_early = int((first_year < RECENT_START).sum())
n_first_recent = int(first_year.between(RECENT_START, LAST_FULL).sum())
n_first_partial = int((first_year >= PARTIAL).sum())
new_recent = sorted(first_year.index[first_year.between(RECENT_START, LAST_FULL)],
key=lambda c: countries.at[c, "country_name"])
new_recent_txt = f" ({and_list(new_recent)})" if new_recent else "" # the countries, in parentheses
# papers with two or more countries abroad ("multinational"), on both counts
pubs["n_abroad"] = pubs["eid"].map(links.groupby("eid")["country"].nunique()).fillna(0).astype(int)
pubs["n_abroad_x"] = pubs["eid"].map(links_x.groupby("eid")["country"].nunique()).fillna(0).astype(int)
intl_full = pubs[pubs["is_international"] & (pubs["year"] < PARTIAL)].copy()
intl_full_x = pubs[pubs["is_international_external"] & (pubs["year"] < PARTIAL)]
multi = intl_full.groupby("period")["n_abroad"].apply(lambda s: (s >= 2).mean())
multi_x = intl_full_x.groupby("period")["n_abroad_x"].apply(lambda s: (s >= 2).mean())
# the latest period against the one before it, on both counts ("slightly": less than 3 points on both)
multi_rise = (multi[P_RECENT] - multi[P_PREV], multi_x[P_RECENT] - multi_x[P_PREV])
MULTI = [P_RECENT, P_BASE, P_PREV] # the periods whose shares the text gives, in its order
multi_prev_txt = (f"and slightly more than in {P_PREV}" if 0 < min(multi_rise) and max(multi_rise) < 0.03
else f"and more than in {P_PREV}" if 0 < min(multi_rise)
else f"though not more than in {P_PREV}" if max(multi_rise) <= 0
else f"though about as multinational as in {P_PREV}")
# ---- partner institutions abroad: leaders, sectors, map ---------------------------------------
top3 = list(inst.index[:3])
top3_txt = [inst_prose(r) for r in top3]
top3_n, top3_n_x = inst["papers"].iloc[:3].tolist(), inst["papers_x"].iloc[:3].tolist()
top3_ctry = inst["country_name"].iloc[:3].tolist()
top3_other = [r for r in top3 if r not in wa_top2]
intl_full["top3"] = intl_full["eid"].isin(set(inst_links.loc[inst_links["ror_id_top"].isin(top3), "eid"]))
top3_share = intl_full.groupby("period")["top3"].mean()
top3_eids_x = set(inst_papers.loc[inst_papers["ror_id_top"].isin(top3) & ~inst_papers["sece_only"], "eid"])
top3_share_x = intl_full_x["eid"].isin(top3_eids_x).groupby(intl_full_x["period"]).mean()
# the papers of P_RECENT that name the three only in SECE authors' own second affiliations: may the two
# shares of that period be given together (small groups)? (P_PREV is described in words)
top3_own = (inst_papers[inst_papers["ror_id_top"].isin(top3) & inst_papers["year"].map(period_of).eq(P_RECENT)]
.groupby("eid")["sece_only"].all().loc[lambda s: s])
top3_recent_shown = top3_own.empty or (own_holders[own_holders["ror_id_top"].isin(top3)
& own_holders["eid"].isin(top3_own.index)]
["author_id"].nunique() >= MIN_HOLDERS)
next_x = inst.drop(index=top3).sort_values(["papers_x", "name"], ascending=[False, True]).index[0]
def ext_part(ror_id: str) -> str:
"""'m of its n': an institution's papers on the external-partner basis, of all its papers; in words
('almost all of its n', 'most of', 'fewer than half of') when the number may not be shown."""
n_x, n = int(inst.at[ror_id, "papers_x"]), int(inst.at[ror_id, "papers"])
if inst_shown(ror_id)["papers"]:
return f"{dp.fmt_int(n_x)} of its {dp.fmt_int(n)}"
word = ("almost all" if n_x >= 0.9 * n else "most" if 2 * n_x > n else "half" if 2 * n_x == n
else "fewer than half")
return f"{word} of its {dp.fmt_int(n)}"
recent_rest = intl_full[intl_full["period"].eq(P_RECENT) & ~intl_full["top3"]]
multi_rest_recent = (recent_rest["n_abroad"] >= 2).mean()
# Same sectors and order as on the Collaboration page: dp.color_map assigns colours in list order,
# so every sector gets the same colour on both pages.
SECTORS = ["education", "facility", "nonprofit", "government", "company", "healthcare"]
SECTOR_LABEL = {"education": "Education", "facility": "Research facility", "nonprofit": "Nonprofit",
"government": "Government", "company": "Company", "healthcare": "Healthcare",
"other": "Other"}
SECTOR_COLORS = dp.color_map(SECTOR_LABEL.values())
org_sector = orgs["primary_type"].where(orgs["primary_type"].isin(SECTORS), "other").map(SECTOR_LABEL)
inst["sector"] = inst.index.map(org_sector)
n_edu = int(inst["sector"].eq("Education").sum())
n_company = int(inst["sector"].eq("Company").sum())
# Each matched unit is placed in its own city, as ROR locates it, so a research institute appears in its
# own city rather than at its parent's headquarters.
placed = inst_links.assign(
lat=inst_links["ror_id"].map(orgs["lat"]), lng=inst_links["ror_id"].map(orgs["lng"]),
city=inst_links["ror_id"].map(orgs["city"]).fillna(""), place=inst_links["ror_id"].map(orgs["country_name"]),
sector=inst_links["ror_id_top"].map(org_sector), name=inst_links["ror_id_top"].map(orgs["name"]))
placed = placed[placed["lat"].notna() & placed["lng"].notna()]
# ROR gives a city the coordinates of a GeoNames record, but not always the same ones: a few cities appear
# at two points a kilometre or two apart, and a city name can belong to two cities (such as Newark,
# Delaware and Newark, New Jersey). A city is a city name in one country; a location of that name more
# than CITY_KM from the city's location with the most papers is another city of the same name. Each unit
# is drawn at its city's location with the most papers, so that the institutions of one city and sector
# share a bubble.
CITY_KM = 25
def km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
"""Great-circle distance in kilometres between two points given in degrees."""
lat1, lng1, lat2, lng2 = np.radians([lat1, lng1, lat2, lng2])
cos = np.sin(lat1) * np.sin(lat2) + np.cos(lat1) * np.cos(lat2) * np.cos(lng2 - lng1)
return float(6371 * np.arccos(min(1.0, cos)))
locs = (placed.groupby(["place", "city", "lat", "lng"])["eid"].nunique().rename("n").reset_index()
.sort_values(["n", "lat", "lng"], ascending=[False, True, True], ignore_index=True))
city_at = {} # (place, city, lat, lng) -> (place, city, lat, lng) of its city
for (place, city), group in locs.groupby(["place", "city"], sort=False):
centres = [] # the cities of this name, by their location with most papers
for lat, lng in zip(group["lat"], group["lng"]):
centre = next((c for c in centres if km(lat, lng, *c) <= CITY_KM), None)
if centre is None:
centres.append(centre := (lat, lng))
city_at[place, city, lat, lng] = (place, city, *centre)
xy = [city_at[k][2:] for k in zip(placed["place"], placed["city"], placed["lat"], placed["lng"])]
placed = placed.assign(lat=[x for x, _ in xy], lng=[y for _, y in xy])
n_cities = len(set(city_at.values()))
n_inst_countries = placed["place"].nunique()
def describe(g: pd.DataFrame, k: int = 4) -> str:
"""Hover text: the k institutions with most papers at a location, then how many more."""
counts = (g.groupby(["ror_id_top", "name"])["eid"].nunique().rename("n").reset_index()
.sort_values(["n", "name"], ascending=[False, True], ignore_index=True))
lines = [f"{dp.wrap_label(name, 44, 2)} ({dp.fmt_int(n)})" for name, n in zip(counts["name"].head(k),
counts["n"].head(k))]
more = len(counts) - len(lines)
return "<br>".join(lines) + (f"<br>and {more} more" if more else "")
keys = ["lat", "lng", "sector"]
bubbles = (placed.groupby(keys).agg(papers=("eid", "nunique"), city=("city", "first"), place=("place", "first"))
.join(placed.groupby(keys)[["ror_id_top", "name", "eid"]].apply(describe).rename("institutions"))
.reset_index().sort_values(["papers", "city"], ascending=[False, True], ignore_index=True))
bubbles["where"] = bubbles["city"].fillna("") + ", " + bubbles["place"]
# ---- small groups across places ------------------------------------------------------------------
# Each external-partner value shown gives, next to its count of all affiliations, the number of papers of a set
# that count there only through SECE authors' own second affiliations: a place's papers of some years, the
# international or the multinational papers of a period, an institution's papers. A reader can also combine
# such numbers across places: the international papers of a period minus a country's, a region minus its
# countries, a country minus its institution. A paper counts in a set through the second affiliations of some
# of its SECE authors (those in the place, ...), so every combination of the values shown is a sum over units:
# a paper and the SECE authors it counts through. The values that shown_cells allows are taken in order of
# importance, and a value is left out when some combination of it and the values kept before it (any integer
# combination, found with linear algebra over the units) is a number of papers, not zero, that only depends on
# units of fewer than MIN_HOLDERS SECE authors. The values of other pages come first, as they are given: those of all
# countries together that the site's rule publishes (Collaboration and the Overview give them by year and period),
# and the counts of institutions abroad that Collaboration may give (any of all years or of P_RECENT that rests on
# enough SECE authors on its own: those its charts and text give are among them).
year_of = pubs.set_index("eid")["year"]
held = own_holders.assign(region=own_holders["country"].map(countries["region"]))
held_in = {key: held.dropna(subset=[key]).groupby(["eid", key])["author_id"].agg(frozenset)
for key in ("country", "region", "ror_id_top")} # a paper's holders in a place
held_any = held.groupby("eid")["author_id"].agg(frozenset) # in all its SECE-only affiliations abroad
held_own = (held.merge(own_links[["eid", "country"]], on=["eid", "country"]) # in the countries it involves
.groupby("eid")["author_id"].agg(frozenset)) # only through them
held_top3 = held[held["ror_id_top"].isin(top3)].groupby("eid")["author_id"].agg(frozenset)
# the years of a value: periods by their label, the other values by name (CELL_YEARS, the rule's windows; an
# institution's latest period is "recent")
sece_abroad = abroad[abroad["sece_only"]]
# the papers of a period with two or more countries abroad only through SECE authors' own second affiliations
multi_own = {p: set(intl_full.loc[intl_full["period"].eq(p) & intl_full["n_abroad"].ge(2), "eid"])
- set(intl_full_x.loc[intl_full_x["period"].eq(p) & intl_full_x["n_abroad_x"].ge(2), "eid"])
for p in MULTI}
# a share on the external-partner basis needs the period's international papers on that basis (the site's rule)
multi_shown = {p: rule.is_published(years_of(p)) for p in MULTI}
def units(eids, years: frozenset, who) -> dict:
"""A value as units {(paper, the SECE authors it counts through): 1}, for the papers of *years*."""
return {(e, who(e)): 1 for e in eids if year_of[e] in years}
def only_own(key: str, value: str) -> set:
"""The papers whose links to a place (links[key] == value) all go through SECE-only affiliations."""
ext = links[links[key].eq(value)].groupby("eid")["external"].any()
return set(ext.index[~ext])
def shown_values() -> dict:
"""Every external-partner value the page shows, as units, in order of importance: all countries together
(every value of the site's rule, given on this page or on others: years, periods, windows), the notes and the
institutions abroad as other pages may give them (partner: Collaboration gives the counts of all years and of
P_RECENT that rest on enough SECE authors on their own, so that the pages together reveal no more than each
alone); the values the text needs (checked below); the institutions the text names; the multinational papers;
the three leading countries; the regions; the other countries by their papers. For each place: P_RECENT, all
years, EARLY, then the older periods, newest first."""
v = {("intl", name): units(only_sece_eids, years, held_any.get) for name, years in rule.published().items()}
v["notes", "papers"] = units(set(sece_abroad["eid"]), ALL_YEARS, held_any.get)
v["notes", "affiliations"] = {(e, held_any[e]): int(n) for e, n in sece_abroad.groupby("eid").size().items()}
for r in inst.index[inst["sece_only"].gt(0)]:
own = set(inst_papers.loc[inst_papers["ror_id_top"].eq(r) & inst_papers["sece_only"], "eid"])
v |= {("partner", r, cell): units(own, years, lambda e, r=r: held_in["ror_id_top"][e, r])
for cell, years in (("papers", ALL_YEARS), ("recent", years_of(P_RECENT)))
if rests_on(inst_held.get(r, {}), years) >= MIN_HOLDERS}
v |= {("multi", p): units(multi_own[p], years_of(p), held_own.get) for p in MULTI if multi_shown[p]}
for c in by_country.index:
top = c in top_countries.index
cells = ({P_RECENT: top and by_country.at[c, "shown_recent"], "papers": by_country.at[c, "shown"],
"early": top and by_country.at[c, "shown_early"]}
| {p: c in top8 and cs_shown.at[p, c] for p in reversed(SHOWN) if p != P_RECENT})
own = only_own("country", c)
v |= {("country", c, cell): units(own, CELL_YEARS.get(cell) or years_of(cell),
lambda e, c=c: held_in["country"][e, c]) for cell, ok in cells.items() if ok}
for r in REGIONS:
cells = ({P_RECENT: region_shown.at[P_RECENT, r], "papers": region_ok.at[r, "papers"]}
| {p: region_shown.at[p, r] for p in reversed(SHOWN) if p != P_RECENT})
own = only_own("region", r)
v |= {("region", r, cell): units(own, CELL_YEARS.get(cell) or years_of(cell),
lambda e, r=r: held_in["region"][e, r]) for cell, ok in cells.items() if ok}
for r in dict.fromkeys([KHALIFA, LAU, *top3]):
own = set(inst_papers.loc[inst_papers["ror_id_top"].eq(r) & inst_papers["sece_only"], "eid"])
v |= {("inst", r, cell): units(own, CELL_YEARS[cell], lambda e, r=r: held_in["ror_id_top"][e, r])
for cell, ok in inst_shown(r).items() if ok}
if top3_recent_shown:
v["top3", P_RECENT] = units(set(top3_own.index), years_of(P_RECENT), held_top3.get)
text = [("region", "Western Asia", P_RECENT), ("region", "Rest of Asia", P_RECENT), ("country", CN, P_RECENT),
("top3", P_RECENT)]
order = ([k for k in v if k[0] in ("intl", "notes", "partner")] + [k for k in text if k in v]
+ [k for k in v if k[0] == "inst"] + [k for k in v if k[0] == "multi"]
+ [k for k in v if k[0] == "country" and k[1] in lead] + [k for k in v if k[0] == "region"])
return {k: v[k] for k in dict.fromkeys([*order, *v])}
def unit_space(values: dict) -> tuple:
"""The values as a matrix over the units (merged where no value tells them apart), the papers of the units
(papers x units) and the sets of units that rest on fewer than MIN_HOLDERS SECE authors, one for each
group of such authors."""
unit = sorted(set().union(*values.values()), key=lambda u: (u[0], sorted(u[1])))
if not unit: # no paper counts through SECE authors' own affiliations
return np.zeros((len(values), 0)), np.zeros((0, 0)), []
F = np.array([[val.get(u, 0) for u in unit] for val in values.values()], dtype=float)
_, first, cls = np.unique(F.T, axis=0, return_index=True, return_inverse=True)
cls = np.ravel(cls)
who = [frozenset().union(*(unit[i][1] for i in np.flatnonzero(cls == k))) for k in range(len(first))]
row_of = {e: i for i, e in enumerate(sorted({u[0] for u in unit}))}
paper_of = np.zeros((len(row_of), len(first)))
for i, u in enumerate(unit):
paper_of[row_of[u[0]], cls[i]] += 1
people = sorted(set().union(*who))
small = {tuple(k for k, w in enumerate(who) if w <= set(g))
for n in range(1, MIN_HOLDERS) for g in combinations(people, n)} - {()}
return F[:, first], paper_of, sorted(small)
def revealed(Q: np.ndarray, paper_of: np.ndarray, small: list) -> tuple | None:
"""A set of *small* on which some combination of the values (Q: orthonormal basis of the combinations) is a
number of papers other than zero, or None."""
P = Q.T @ Q
for g in small:
ev, vec = np.linalg.eigh(P[np.ix_(g, g)])
on_g = vec[:, ev > 1 - 1e-8] # the combinations that are zero outside g
if on_g.size and np.abs(paper_of[:, g] @ on_g).max() > 1e-7:
return g
return None
candidates = shown_values()
F, paper_of, small = unit_space(candidates)
Q, left_out = np.zeros((0, F.shape[1])), []
for key, row in zip(candidates, F):
rest = row - Q.T @ (Q @ row) # what the value adds to those kept
if np.linalg.norm(rest) < 1e-9:
continue
trial = np.vstack([Q, rest / np.linalg.norm(rest)])
if revealed(trial, paper_of, small) is None:
Q = trial
else:
left_out.append(key)
for kind, *key in left_out: # leave these values out
if kind == "country":
c, cell = key
if cell in ("papers", "early"):
by_country.at[c, {"papers": "shown", "early": "shown_early"}[cell]] = False
else:
if cell == P_RECENT:
by_country.at[c, "shown_recent"] = False
if c in top8:
cs_shown.at[cell, c] = False
elif kind == "region":
r, cell = key
if cell == "papers":
region_ok.at[r, "papers"] = False
else:
region_shown.at[cell, r] = False
elif kind == "inst":
inst_hidden.add(tuple(key))
elif kind == "multi":
multi_shown[key[0]] = False
elif kind == "top3":
top3_recent_shown = False
else: # they come first (all countries, partners: given on other pages)
raise AssertionError(f"small groups: the value {kind, *key} would have to be left out")
# the audit of the values now shown, as a reader sees them
F, paper_of, small = unit_space(shown_values())
_, sv, vt = np.linalg.svd(F, full_matrices=False) if F.size else (None, np.zeros(0), np.zeros((0, 0)))
small_combination = revealed(vt[sv > 1e-9], paper_of, small)
region_tbl["shown_x"] = region_tbl["region"].map(region_ok["papers"]).eq(True)
top_countries = by_country.loc[top_countries.index] # with the columns shown, shown_early, shown_recent
n_not_shown = int((~by_country["shown"]).sum()) # countries whose external-partner count is not shown
map_x_note = (f" (not shown for {dp.fmt_int(n_not_shown)} of the {dp.fmt_int(n_countries)} countries, see the notes)"
if n_not_shown else "") # for the map caption
# texts with values that may be left out (small groups)
# the third country on the external-partner basis: its count where it may be shown, and the countries ahead of it
lead3_x_txt = (f", or {dp.fmt_int(lead_n_x[2])} on the external-partner basis" if by_country.at[lead[2], "shown"]
else "; on the external-partner basis") + f", fewer than {and_list(ahead_x)}"
# what moves Western Asia down on that basis: the UAE's count where it may be shown, otherwise in words
wa_drop_txt = (f"{prose(AE)} drops from {num(AE, 'papers')} papers to {num(AE, 'papers_x')}, and {country_part(LB)} "
f"papers with an affiliation in {prose(LB)} have it" if by_country.at[AE, "shown"] else
f"{country_part(AE)} papers with an affiliation in {prose(AE)} and {country_part(LB)} with one in "
f"{prose(LB)} have it")
# Western Asia over all years on the external-partner basis, for the text where it may be shown
wa_all_x_txt = (f", with {dp.fmt_int(reg_n_x['Western Asia'])} papers ({dp.fmt_pct(reg_all_x['Western Asia'])} of "
f"the {dp.fmt_int(n_intl_x)} international papers on that basis)"
if region_ok.at["Western Asia", "papers"] else "")
# (papers, of them SECE-only, may that be shown), then "m of the n" or "most of the n" for the text
khalifa_all, khalifa_recent = inst_counts(KHALIFA), inst_counts(KHALIFA, recent=True)
lau_all, lau_recent = inst_counts(LAU), inst_counts(LAU, recent=True)
khalifa_all_txt, khalifa_recent_txt, lau_all_txt, lau_recent_txt = (
sece_part(m, n, ok) for n, m, ok in (khalifa_all, khalifa_recent, lau_all, lau_recent))
# the multinational shares on the external-partner basis that may be shown, in the order of the text (with
# their periods when some are left out)
multi_x_items = [dp.fmt_pct(multi_x[p]) if all(multi_shown.values()) else f"{dp.fmt_pct(multi_x[p])} in {p}"
for p in MULTI if multi_shown[p]]
multi_x_txt = f" (on the external-partner basis, {and_join(multi_x_items)})" if multi_x_items else ""
# the notes: the papers international only through SECE authors' own second affiliations, in P_BASE, P_RECENT and
# LAST_FULL where the site's rule publishes them (P_RECENT always: checked below)
only_sece_txt = and_join([f"{dp.fmt_int(m)} of the {dp.fmt_int(n)} of {when}" for m, n, when, years in (
(only_sece_period[P_BASE], intl_period[P_BASE], P_BASE, years_of(P_BASE)),
(only_sece_period[P_RECENT], n_intl_recent, P_RECENT, years_of(P_RECENT)),
(n_only_sece_last, n_intl_last, str(LAST_FULL), frozenset({LAST_FULL}))) if rule.is_published(years)] or ["–"])
# institutions counted in the text by how they appear (counts of institutions): the SECE authors behind those
# named only, or at least half of the time, through SECE authors' own second affiliations
inst_only_own = set(inst.index[inst["papers_x"].eq(0)])
n_held_inst_only = own_holders.loc[own_holders["ror_id_top"].isin(inst_only_own), "author_id"].nunique()
n_held_inst_mostly = own_holders.merge(
inst_papers.loc[inst_papers["ror_id_top"].isin(inst.index[inst["mostly_sece"]]) & inst_papers["sece_only"],
["eid", "ror_id_top"]], on=["eid", "ror_id_top"])["author_id"].nunique()
# ---- the text states these directions: stop if the data no longer agree ------------------------
checks = {
"the three leading countries are named in order, without ties (they and the next one have different counts)":
bool((by_country["papers"].to_numpy()[:3] > by_country["papers"].to_numpy()[1:4]).all()),
"the leading country leads in EARLY and in P_RECENT (on both counts)":
all(sole_max(by_country[col]) == lead[0] for col in ("sh_early", "sh_recent", "sh_early_x", "sh_recent_x")),
"every partner country has an external partner": n_countries_x == n_countries,
"joint papers are concentrated in a few countries: the countries with 100 or more papers are few and hold "
"most of the (paper, country) links": n_countries_100 <= 0.2 * n_countries and share_links_100 > 0.5,
"on the external-partner basis, the third country falls behind others, the first two do not":
len(ahead_x) > 0 and bool((by_country.loc[lead[:2], "papers_x"] > by_country.loc[ahead_x, "papers_x"].max()).all()),
"gainers gained and losers lost": bool((by_country.loc[gainers, "delta"] > 0).all()
and (by_country.loc[losers, "delta"] < 0).all()),
"Lebanon and the UAE are the largest gains, Lebanon mostly and the UAE in part through SECE authors' own "
"second affiliations":
gainers == [LB, AE] and by_country.at[LB, "recent_x"] < 0.5 * by_country.at[LB, "recent"]
and 0.5 * by_country.at[AE, "recent"] < by_country.at[AE, "recent_x"] < by_country.at[AE, "recent"],
"on the external-partner basis, gainers gained, Lebanon is not among them and the two largest losses are "
"those of the same two countries": bool((by_country.loc[gainers_x, "delta_x"] > 0).all()) and LB not in gainers_x
and set(losers_x) == set(losers),
"the P_RECENT top 20 has newcomers and dropouts on both counts (the text names them)":
bool(top20_swap_txt and top20_swap_x_txt),
"the US led in first_shown and P_BASE, the first two periods shown":
SHOWN[:2] == [first_shown, P_BASE] and all(sole_max(country_share.loc[p]) == US for p in SHOWN[:2]),
"the US is not the leading partner in P_RECENT (on both counts)": min(us_ranks) > 1,
"UAE and China rose, France fell, Finland peaked in the same period (on both counts)": all(
s.at[P_RECENT, AE] > s.at[P_BASE, AE] and s.at[P_RECENT, CN] > s.at[P_BASE, CN]
and s.at[P_RECENT, FR] < s.at[P_BASE, FR] and sole_max(s[FI]) == fi_peak for s in (cs, cs_x)),
"the UAE shares of P_PREV and P_RECENT are lower on the external-partner basis":
cs_x.at[P_PREV, AE] < cs.at[P_PREV, AE] and cs_x.at[P_RECENT, AE] < cs.at[P_RECENT, AE],
"North America fell in share but grew in papers (on both counts)": na[P_RECENT] < na[P_BASE]
and na_n[P_RECENT] > na_n[P_BASE] and na_x[P_RECENT] < na_x[P_BASE] and na_n_x[P_RECENT] > na_n_x[P_BASE],
"the change came from outside the EU: from P_BASE to P_RECENT the EU-27 share changed less than those of "
"North America, Western Asia and the rest of Asia (on both counts)": all(
abs(e[P_RECENT] - e[P_BASE]) < min(abs(s[P_RECENT] - s[P_BASE]) for s in others)
for e, others in ((eu, (na, wa, ra)), (eu_x, (na_x, wa_x, ra_x)))),
"a region has a higher share in P_RECENT on the external-partner basis (the smaller denominator)":
bool((region_share_x.loc[P_RECENT] > region_share.loc[P_RECENT]).any()),
"Western Asia and the rest of Asia rose (on both counts)": wa[P_RECENT] > wa[P_BASE] and ra[P_RECENT] > ra[P_BASE]
and wa_x[P_RECENT] > wa_x[P_BASE]
and ra_x[P_RECENT] > ra_x[P_BASE],
"one country leads the rest of Asia in P_RECENT": int(ra_recent.eq(ra_recent.max()).sum()) == 1,
"Western Asia: much of it in P_RECENT (a third or more) and most of its growth since P_PREV come from SECE "
"authors' own second affiliations, and on the external-partner basis it is below the rest of Asia in P_RECENT":
3 * n_wa_recent_sece >= n_wa_recent
and wa_n[P_RECENT] > wa_n[P_PREV] and wa_n_x[P_RECENT] - wa_n_x[P_PREV] < 0.5 * (wa_n[P_RECENT] - wa_n[P_PREV])
and ra_x[P_RECENT] > wa_x[P_RECENT],
"in P_RECENT the other regions differ by less than other_gap_max points": 100 * other_gap < other_gap_max,
"the EU-27 range is about the same on the external-partner basis":
abs(eu_x.loc[P_BASE:].min() - eu_min) < 0.02 and abs(eu_x.loc[P_BASE:].max() - eu_max) < 0.02,
"regions: the EU-27 comes first and the rest of the world last on both counts (the text lists the others "
"in the order of the data, and gives Western Asia's place on both: no two regions tie)":
reg_order[0] == reg_order_x[0] == "EU-27" and reg_order[-1] == reg_order_x[-1] == "Rest of world"
and reg_all.is_unique and reg_all_x.is_unique,
"on the external-partner basis, Western Asia falls behind other regions": len(wa_passed) > 0,
"the rest of the world is Africa, South America and Oceania":
set(by_country.loc[by_country["region"].eq("Rest of world"), "continent"])
<= {"Africa", "South America", "Oceania"},
"SECE authors' own second affiliations weigh most on Western Asia (the largest difference between the two "
"counts of a region)": sole_max(region_tbl.set_index("region").eval("papers - papers_x")) == "Western Asia",
"Khalifa University is in the UAE and the Lebanese American University in Lebanon":
orgs.at[KHALIFA, "country_code"] == AE and orgs.at[LAU, "country_code"] == LB,
"the yearly count of partner countries stepped up in step_year and stayed above every earlier year since":
bool(step_years),
"more partner countries a year in P_RECENT than in P_BASE": avg_c_recent > avg_c_base,
"more international papers a year in P_RECENT than in P_BASE": avg_i_recent > avg_i_base,
"few partner countries are new: most of them first appeared before P_RECENT": n_first_early >= 0.8 * n_countries,
"more multinational than in P_BASE (on both counts)":
multi[P_RECENT] > multi[P_BASE] and multi_x[P_RECENT] > multi_x[P_BASE],
"more multinational papers, also without the top 3, but fewer": multi[P_RECENT] > multi[P_BASE]
and multi[P_BASE] < multi_rest_recent < multi[P_RECENT],
"the United Kingdom is the leading country of Other Europe": by_country.loc[
by_country["region"].eq("Other Europe"), "papers"].pipe(sole_max) == "GB",
"universities dominate: most partner institutions abroad are in the education sector": n_edu > 0.5 * n_inst,
"the Fraunhofer-Gesellschaft is a public-body partner abroad":
FRAUNHOFER in inst.index and inst.at[FRAUNHOFER, "sector"] == "Government",
"the other sectors are mostly facilities, public bodies, hospitals and nonprofits":
inst["sector"].isin(["Research facility", "Government", "Healthcare", "Nonprofit"]).sum()
> 0.5 * (~inst["sector"].isin(["Education", "Company"])).sum(),
"three institutions appear most often (no tie for third place)": inst["papers"].iloc[2] > inst["papers"].iloc[3],
"each city is drawn at a point of its own, so the institutions of one city and sector share a bubble (the "
"notes say so)": len({c[2:] for c in city_at.values()}) == n_cities,
"the top-3 share grew (on both counts)": top3_share[P_RECENT] > top3_share[P_PREV] > top3_share[P_EARLIER]
and top3_share_x[P_RECENT] > top3_share_x[P_PREV],
"the top 3 are Khalifa University, one institution outside Western Asia and the Lebanese American "
"University; on the external-partner basis, the first two stay ahead and next_x is third":
top3[0] == KHALIFA and top3[2] == LAU and len(top3_other) == 1
and list(inst.sort_values(["papers_x", "name"], ascending=[False, True]).index[:3]) == [*top3[:2], next_x]
and inst.at[next_x, "papers_x"] > inst["papers_x"].drop(index=[*top3[:2], next_x]).max(),
"the two leading Western Asian institutions are on most Western Asian papers of P_RECENT":
n_wa_recent_top2 > 0.5 * n_wa_recent,
"the periods compared start in the 1990s (the page description says so)":
1990 <= periods.bounds(first_shown)[0] <= 1999,
"every affiliation occurrence has a holder (the note says so)": n_no_holder == 0,
"small groups: the external-partner counts that the text gives as numbers may be shown (Western Asia, the "
"rest of Asia and China in P_RECENT; the top 3 in P_RECENT; the others adapt)":
bool(region_shown.at[P_RECENT, "Western Asia"] and region_shown.at[P_RECENT, "Rest of Asia"]
and cs_shown.at[P_RECENT, CN] and top3_recent_shown),
"small groups: the site's rule publishes the international papers on both bases of all years, EARLY and P_RECENT "
"(text, KPI, captions, the top-countries chart), and every other value of all countries together that the page "
"gives on both bases (the periods with an n on that basis, those of the multinational shares, the notes)":
all(rule.is_published(years) for years in [ALL_YEARS, EARLY_YEARS, years_of(P_RECENT)]
+ [years_of(p) for p in SHOWN_X] + [years_of(p) for p in MULTI if multi_shown[p]])
and P_RECENT in only_sece_txt,
"small groups: a period without values on the external-partner basis here has none in the Collaboration "
"page's table either (the notes say so)": all(rule.cell_shown.at[p, sg.INTL] == (p in SHOWN_X) for p in SHOWN),
"small groups: the papers international only through SECE authors' own second affiliations are those of the "
"site's rule, in every value of all countries together that it publishes":
all(int(year_of[list(only_sece_eids)].isin(years).sum()) == rule.value(years)
for years in rule.published().values()),
"small groups: the site's rule passes its own checks, and its audit of the values of all pages together":
all(rule.checks().values()),
"small groups: the institutions that the text counts as named only, or at least half of the time, through "
"SECE authors' own second affiliations rest on no SECE author or on at least MIN_HOLDERS":
all(n == 0 or n >= MIN_HOLDERS for n in (n_held_inst_only, n_held_inst_mostly)),
"small groups: no combination of the external-partner values shown, of the values of all countries together "
"that other pages give and of the counts of institutions abroad that they may give (differences, sums, across "
"years and places), gives a number of papers that rests on fewer than MIN_HOLDERS SECE authors":
small_combination is None,
}
failed = [name for name, ok in checks.items() if not ok]
assert not failed, f"the page text no longer matches the data: {failed}"