import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sece_stats import metrics, periods, small_groups as sg
pubs = data.load_publications()
meta = data.load_metadata()
cites = pubs["cited_by"]
AS_OF_TEXT = f"{AS_OF.day} {AS_OF:%B %Y}" # the export date as text: day, month name and year
LAST_FULL = periods.LAST_FULL # the latest full year (PARTIAL - 1)
P_RECENT = periods.period_of(LAST_FULL) # the latest five full years
P_PREV = periods.period_of(LAST_FULL - 5) # the five years before them
RECENT_FROM = periods.bounds(P_RECENT)[0]
TEN_FROM = periods.bounds(P_PREV)[0] # the latest ten full years are TEN_FROM..LAST_FULL
TEN_YEARS = f"{TEN_FROM}–{LAST_FULL}"
MATURE_TO = LAST_FULL - 2 # papers with at least two full calendar years of citations
# Age-controlled statistics (within publication years, normalised scores) cover NCS_FROM..MATURE_TO. NCS_FROM is
# the first year from which every year has at least NCS_MIN articles (reviews included, see below) and NCS_MIN
# conference papers, so that each year and type has an average of its own.
CITABLE = ["Article", "Review", "Conference paper"]
NCS_TYPE = {"Review": "Article"} # the normalisation type of a document type
NCS_MIN = 10
citable = pubs[pubs["doc_type"].isin(CITABLE)]
type_year = (pd.crosstab(citable["year"], citable["doc_type"].replace(NCS_TYPE))
.reindex(index=range(int(pubs["year"].min()), MATURE_TO + 1), columns=["Article", "Conference paper"],
fill_value=0))
thin = type_year.min(axis=1) < NCS_MIN # a year with fewer than NCS_MIN papers of a type
NCS_FROM = int(thin[thin].index.max()) + 1 if thin.any() else int(type_year.index.min())
NCS_TO = MATURE_TO
COHORT_FROM = NCS_FROM # the same years for the statistics within publication years
def fmt_count(value: float) -> str:
"""Citation count or median: no decimals unless it has a fraction (5.5)."""
return dp.fmt_int(value) if float(value).is_integer() else dp.fmt_num(value, 1)
def join_and(items: list[str]) -> str:
"""'a', 'a and b', 'a, b and c' ('' for no items)."""
return " and ".join(items) if len(items) <= 2 else ", ".join(items[:-1]) + " and " + items[-1]
# --- Headline indicators: all records, Scopus "Cited by" counts at the export date
n_pubs = len(pubs)
n_partial = int((pubs["year"] == PARTIAL).sum())
total_cites = int(cites.sum())
mean_cites = cites.mean()
median_cites = cites.median()
mean_to_median = mean_cites / median_cites
n_uncited = int((cites == 0).sum())
share_uncited = n_uncited / n_pubs
share_uncited_mature = (pubs.loc[pubs["year"] <= MATURE_TO, "cited_by"] == 0).mean()
h_all = metrics.h_index(cites)
h_next = h_all + 1
n_h, n_h_next = int((cites >= h_all).sum()), int((cites >= h_next).sum()) # papers cited >= h, >= h + 1 times
h_ten = metrics.h_index(pubs.loc[pubs["year"].between(TEN_FROM, LAST_FULL), "cited_by"])
h_recent = metrics.h_index(pubs.loc[pubs["year"].between(*periods.bounds(P_RECENT)), "cited_by"])
n_100 = int((cites >= 100).sum())
share_100 = n_100 / n_pubs
share_cites_100 = cites[cites >= 100].sum() / total_cites
# --- Distribution over citation classes
BIN_EDGES = [0, 1, 5, 10, 25, 50, 100, 250, np.inf]
BIN_LABELS = ["0", "1–4", "5–9", "10–24", "25–49", "50–99", "100–249", "≥250"]
cite_class = pd.cut(cites, bins=BIN_EDGES, labels=BIN_LABELS, right=False)
dist = (pubs.groupby(cite_class, observed=False)["cited_by"]
.agg(papers="size", citations="sum")
.rename_axis("cite_class").reset_index())
dist["share_papers"] = dist["papers"] / n_pubs
dist["share_citations"] = dist["citations"] / total_cites
under_10 = dist["cite_class"].isin(["0", "1–4", "5–9"])
share_papers_lt10 = dist.loc[under_10, "share_papers"].sum()
share_cites_lt10 = dist.loc[under_10, "share_citations"].sum()
# --- Concentration: papers ranked from most to least cited
top1_n, top10_n, half_n = (int(np.ceil(f * n_pubs)) for f in (0.01, 0.10, 0.50))
top1_share = metrics.top_share(cites, frac=0.01)
top10_share = metrics.top_share(cites, frac=0.10)
half_share = metrics.top_share(cites, frac=0.50)
gini = metrics.gini(cites)
ranked = np.sort(cites.to_numpy())[::-1]
cum_share = np.concatenate([[0.0], np.cumsum(ranked) / ranked.sum()]) # share held by the top k papers
n_half_cites = int(np.searchsorted(cum_share, 0.5)) # fewest papers holding >= 50%
share_half_cites = n_half_cites / n_pubs
# The all-records figures mix papers of very different ages. Within one publication year all papers
# have had the same time to be cited: the top-10% share of each year COHORT_FROM..MATURE_TO.
cohort_top10 = pd.Series({y: metrics.top_share(pubs.loc[pubs["year"] == y, "cited_by"], frac=0.10)
for y in range(COHORT_FROM, MATURE_TO + 1)})
cohort_top10_median, cohort_top10_min, cohort_top10_max = cohort_top10.agg(["median", "min", "max"])
# --- Citations by publication year (the citation-window effect)
by_year = (pubs.groupby("year")["cited_by"]
.agg(papers="size", mean="mean", median="median", uncited=lambda s: (s == 0).mean())
.reindex(range(int(pubs["year"].min()), LAST_FULL + 1)))
by_year["papers"] = by_year["papers"].fillna(0).astype(int)
enough = (by_year["papers"] >= 10)[::-1].cummin()[::-1] # this and every later year have >= 10 papers
FIRST_YEAR = int(enough.idxmax())
n_before_first = int((pubs["year"] < FIRST_YEAR).sum())
max_before_first = int(by_year.loc[:FIRST_YEAR - 1, "papers"].max())
by_year = by_year.loc[FIRST_YEAR:].rename_axis("year").reset_index()
year_stats = by_year.set_index("year")
median_min, median_max = year_stats.loc[COHORT_FROM:MATURE_TO, "median"].agg(["min", "max"])
def period(label: str) -> pd.Series:
"""Citation statistics of the papers published in a period ("first–last" year)."""
c = pubs.loc[pubs["year"].between(*periods.bounds(label)), "cited_by"]
return pd.Series({"papers": len(c), "mean": c.mean(), "median": c.median(), "uncited": (c == 0).mean()})
p_prev, p_recent = period(P_PREV), period(P_RECENT)
y_before_last, y_last = year_stats.loc[LAST_FULL - 1], year_stats.loc[LAST_FULL]
# the median of the last two full years, below the range of COHORT_FROM..MATURE_TO (checked below)
median_a, median_b = fmt_count(y_before_last["median"]), fmt_count(y_last["median"])
if y_before_last["median"] < median_min:
median_drop_text = f"The median falls to {median_a} for {LAST_FULL - 1} and {median_b} for {LAST_FULL}"
else:
median_drop_text = f"The median is {median_a} for {LAST_FULL - 1} and falls to {median_b} for {LAST_FULL}"
peak = pubs.loc[cites.idxmax()] # the most-cited paper
peak_year = int(peak["year"])
peak_year_share = peak["cited_by"] / cites[pubs["year"] == peak_year].sum()
# --- The most-cited publications
top = pubs.sort_values(["cited_by", "year", "eid"], ascending=[False, True, True]).head(15).copy()
top["doi_url"] = "https://doi.org/" + top["doi"]
top_cites = int(top["cited_by"].sum())
top_share = top_cites / total_cites
top_before_recent = int((top["year"] < RECENT_FROM).sum())
share_before_recent = (pubs["year"] < RECENT_FROM).mean() # of all records
top_single = int((top["collab_type"] == "single-institution").sum())
top_intl = int((top["collab_type"] == "international").sum())
top_led = int((top["sece_first_author"] | top["sece_last_author"]).sum()) # an SECE first or last author
# --- Normalised citation score (NCS) by paper characteristics
in_window = pubs["year"].between(NCS_FROM, NCS_TO)
ncs = pubs[in_window & pubs["doc_type"].isin(CITABLE)].copy()
# Reviews are normalised together with articles: most years have too few reviews for an average of their
# own (a year with a single review would give it a score of 1 by construction).
ncs["ncs_type"] = ncs["doc_type"].replace(NCS_TYPE)
ncs["score"] = metrics.normalized_citation_score(ncs, by=["year", "ncs_type"])
ncs["score_year"] = metrics.normalized_citation_score(ncs, by="year") # journal vs conference
n_ncs = len(ncs)
other_types = pubs.loc[in_window & ~pubs["doc_type"].isin(CITABLE), "doc_type"].value_counts()
n_ncs_other = int(other_types.sum())
n_reviews = int(ncs["doc_type"].eq("Review").sum())
reviews_year = ncs.loc[ncs["doc_type"].eq("Review"), "year"].value_counts().reindex(range(NCS_FROM, NCS_TO + 1),
fill_value=0)
intl = ncs["collab_type"] == "international"
led = ncs["sece_first_author"] | ncs["sece_last_author"] # an SECE author is first or last author
# External-partner basis: counting only affiliations of co-authors who are not SECE authors, so that an SECE
# author's own second affiliation abroad (one that only SECE authors hold) does not make a paper international
intl_ext = ncs["is_international_external"]
def boot_mean_ci(values: pd.Series, n_boot: int = 2000, seed: int = 0) -> tuple[float, float, float]:
"""Mean with a 95% percentile-bootstrap interval (papers resampled with replacement)."""
x = values.dropna().to_numpy(dtype=float)
idx = np.random.default_rng(seed).integers(0, len(x), size=(n_boot, len(x)))
lo, hi = np.quantile(x[idx].mean(axis=1), [0.025, 0.975])
return float(x.mean()), float(lo), float(hi)
GROUPS = [ # (dimension, group, chart row label, mask of the group's papers, score column)
("Collaboration", "Single-institution", "Single-institution",
ncs["collab_type"] == "single-institution", "score"),
("Collaboration", "National", "National", ncs["collab_type"] == "national", "score"),
("Collaboration", "International", "International", intl, "score"),
# who leads the international papers: an SECE first or last author, or neither (partner-led)
("International papers", "International, SECE-led", "SECE-led", intl & led, "score"),
("International papers", "International, partner-led", "Partner-led", intl & ~led, "score"),
# the international papers again on the external-partner basis (‡ in the caption)
("International, external‡", "International, external", "All", intl_ext, "score"),
("International, external‡", "International, external, SECE-led", "SECE-led", intl_ext & led, "score"),
("International, external‡", "International, external, partner-led", "Partner-led", intl_ext & ~led, "score"),
("SECE first or last author", "SECE first or last author", "Yes", led, "score"),
("SECE first or last author", "No SECE first or last author", "No", ~led, "score"),
("Open access", "Open access (all types)", "All types", ncs["oa_any"], "score"),
("Open access", "Gold", "Gold", ncs["oa_status"] == "gold", "score"),
("Open access", "Hybrid", "Hybrid", ncs["oa_status"] == "hybrid", "score"),
("Open access", "Bronze", "Bronze", ncs["oa_status"] == "bronze", "score"),
# oa_status counts a paper once, in the order gold > hybrid > bronze > green: "Green" = repository copy only
("Open access", "Green", "Green only", ncs["oa_status"] == "green", "score"),
("Open access", "Closed", "Closed", ~ncs["oa_any"], "score"),
("Funding acknowledged", "Funding acknowledged", "Yes", ncs["has_funding"], "score"),
("Funding acknowledged", "No funding acknowledged", "No", ~ncs["has_funding"], "score"),
("Industry partner", "Industry partner", "Yes", ncs["has_industry_partner"], "score"),
("Industry partner", "No industry partner", "No", ~ncs["has_industry_partner"], "score"),
("Source type†", "Journal", "Journal", ncs["source_kind"] == "journal", "score_year"),
("Source type†", "Conference", "Conference", ncs["source_kind"] == "conference", "score_year"),
]
rows = []
for dim, group, row_label, mask, col in GROUPS:
mean, lo, hi = boot_mean_ci(ncs.loc[mask, col])
rows.append({"dimension": dim, "group": group, "row_label": row_label, "papers": int(mask.sum()),
"mean": mean, "lo": lo, "hi": hi, "median_score": ncs.loc[mask, col].median(),
"median_cites": ncs.loc[mask, "cited_by"].median()})
ncs_groups = pd.DataFrame(rows)
G = ncs_groups.set_index("group")
ncs_journal, ncs_conference = G.loc["Journal", "mean"], G.loc["Conference", "mean"]
journal_ratio = ncs_journal / ncs_conference
def ci_text(group: str, label: bool = True) -> str:
"""Mean score with its interval: '1.20 (95% CI 1.08–1.35)', or '1.20 (1.08–1.35)'."""
r = G.loc[group]
ci = f"{dp.fmt_num(r['lo'], 2)}–{dp.fmt_num(r['hi'], 2)}"
return f"{dp.fmt_num(r['mean'], 2)} ({'95% CI ' if label else ''}{ci})"
def vs_average(group: str) -> str:
"""Mean score relative to the School average (1), e.g. '20% above'."""
diff = G.loc[group, "mean"] - 1
return f"{dp.fmt_pct(abs(diff), 0)} {'above' if diff >= 0 else 'below'}"
def vs_interval(group: str) -> str:
"""Position of the 95% interval relative to the School average."""
r = G.loc[group]
if r["lo"] > 1:
return "above the average"
if r["hi"] < 1:
return "below the average"
return "an interval that includes the average, so there is no clear difference"
# International papers: the advantage sits in the papers that partners lead
intl_led_median = G.loc["International, SECE-led", "median_score"]
intl_partner_median = G.loc["International, partner-led", "median_score"]
n_intl_partner = int(G.loc["International, partner-led", "papers"])
share_intl_partner = n_intl_partner / int(G.loc["International", "papers"])
mean_gap = G.loc["International, partner-led", "mean"] - G.loc["International, SECE-led", "mean"]
# share of the international papers' score above the average (score - 1, summed) that partner-led papers hold;
# the tail: the partner-led share of the highest-scoring 5% of the international papers, and the gap between
# the two groups without the highest-scoring 5% of each
intl_score, intl_partner = ncs.loc[intl, "score"], ~led[intl]
partner_excess_share = (intl_score - 1)[intl_partner].sum() / (intl_score - 1).sum()
partner_share_top5 = intl_partner[intl_score >= intl_score.quantile(0.95)].mean()
trimmed = {partner: s[s <= s.quantile(0.95)].mean() for partner, s in intl_score.groupby(intl_partner)}
gap_trimmed = trimmed[True] - trimmed[False]
# International papers on the external-partner basis: does the association hold without the papers that are
# international only through an SECE author's own second affiliation abroad?
n_intl, n_intl_ext = int(G.loc["International", "papers"]), int(G.loc["International, external", "papers"])
intl_sece_only = intl & ~intl_ext # international only through such second affiliations
n_intl_sece_only = int(intl_sece_only.sum())
ext_holds_text = ("so the association holds" if G.loc["International, external", "lo"] > 1
else "so the association is no longer clear")
# how many of the international papers remain international on that basis, in words (the numbers are not given,
# see below)
share_remain = n_intl_ext / n_intl
ext_remain_text = "almost all" if share_remain >= 0.95 else "most" if share_remain > 0.5 else "at most half"
# Small groups (no per-person metrics): a number of papers that are international only through SECE authors' own
# second affiliations abroad, or the score of such papers, is shown only when it is zero or rests on at least
# config.MIN_SECE_HOLDERS distinct SECE authors who hold these affiliations; with fewer it would in practice be one
# or two people's paper count or citation score. This covers the numbers a reader can derive as well: an
# external-partner group next to its address-based counterpart gives the number of its papers that are
# international only through such affiliations (its cell), and two cells give their difference. Other pages give
# the number of such papers for all countries together (by year, by period and for spans of years, papers of every
# type), and readers can combine the values of several pages, so the site gives these numbers only where
# sece_stats.small_groups publishes them. The papers compared here (three document types, NCS_FROM..NCS_TO) are
# not among them, so neither the figure nor the text gives the number of papers of an external-partner group or
# of a cell; the cells still decide which scores are shown. Author ids are only counted.
MIN_HOLDERS = config.MIN_SECE_HOLDERS
pub_aff = data.load_publication_affiliations()
authors = data.load_publication_authors()
own_abroad = pub_aff[pub_aff["eid"].isin(ncs.loc[intl_sece_only, "eid"]) & pub_aff["match_method"].ne("ignored")
& ~pub_aff["is_auth"] & pub_aff["held_only_by_sece"].fillna(False).astype(bool)
& pub_aff["country_code"].notna() & pub_aff["country_code"].ne(config.HOME_COUNTRY)]
own_abroad_holders = (own_abroad[["eid", "holder_author_pos"]]
.assign(author_pos=lambda d: d["holder_author_pos"].str.split(";")).explode("author_pos")
.astype({"author_pos": "int64"})
.merge(authors[["eid", "author_pos", "author_id", "is_sece"]], on=["eid", "author_pos"],
how="left", validate="many_to_one"))
assert own_abroad_holders["is_sece"].eq(True).all() and own_abroad_holders["author_id"].notna().all(), \
"every holder of an own second affiliation is an SECE author with an author id"
assert own_abroad["eid"].nunique() == n_intl_sece_only, "each such paper has an own second affiliation abroad"
held_by = own_abroad_holders.groupby("eid")["author_id"].agg(set) # each such paper: the SECE authors behind it
def rests_on(eids: frozenset) -> int:
"""Distinct SECE authors whose own second affiliations abroad make these papers international."""
return len(set().union(*held_by.reindex(sorted(eids)).dropna()))
def remainders_safe(cells: list[frozenset]) -> bool:
"""Does every number a reader can form from these cells rest on no or at least MIN_HOLDERS SECE authors? The
cells must be nested or disjoint; then each such number is a sum of remainders (a cell minus the cells inside
it), and it is enough to check the remainders."""
assert all(a <= b or b <= a or not a & b for a in cells for b in cells), "cells must be nested or disjoint"
rests = [rests_on(c.difference(*[o for o in cells if o < c])) for c in cells]
return all(n == 0 or n >= MIN_HOLDERS for n in rests)
# The external-partner groups of the figure (in order of importance), each with its address-based counterpart. The
# difference of their paper counts is the number of the group's papers that are international only through own
# affiliations abroad: the group's cell. A group (its score) is shown when its cell, with the cells of the groups
# shown before it, passes remainders_safe. A group that is not shown loses its score too: next to the score of its
# address-based counterpart, it would describe the papers of its cell (a weighted mean). Leadership splits the
# international papers, so both leadership groups are shown or neither (with one of them, the cell of the other
# follows from the total).
EXT_PAIRS = {"International, external": "International",
"International, external, SECE-led": "International, SECE-led",
"International, external, partner-led": "International, partner-led"}
EXT_SPLIT = ["International, external, SECE-led", "International, external, partner-led"]
MASKS = {group: mask for _, group, _, mask, _ in GROUPS}
assert all((MASKS[g] & ~MASKS[a]).sum() == 0 for g, a in EXT_PAIRS.items()), "external groups within their counterparts"
ext_cells = {g: frozenset(ncs.loc[MASKS[a] & ~MASKS[g], "eid"]) for g, a in EXT_PAIRS.items()}
assert set().union(*ext_cells.values()) <= set(held_by.index), "every paper of a cell has an own affiliation abroad"
ext_shown, kept = {}, []
for g, cell in ext_cells.items():
ext_shown[g] = remainders_safe([*kept, cell])
if ext_shown[g]:
kept.append(cell)
assert ext_shown["International, external"], \
"small groups: the text gives the scores of the international papers on the external-partner basis and of those " \
"that are international only through own affiliations"
ext_split_shown = all(ext_shown[g] for g in EXT_SPLIT)
ext_hidden = [g for g in EXT_PAIRS if not ext_shown[g] or (g in EXT_SPLIT and not ext_split_shown)]
ncs_shown = ncs_groups[~ncs_groups["group"].isin(ext_hidden)].copy() # the groups of the figure
# their number of papers (hover), except for the external-partner groups (see above)
ncs_shown["papers_text"] = [("not shown" if g in EXT_PAIRS else dp.fmt_int(n))
for g, n in zip(ncs_shown["group"], ncs_shown["papers"])]
only_mean, only_lo, only_hi = boot_mean_ci(ncs.loc[intl_sece_only, "score"])
sece_only_text = (f"score {dp.fmt_num(only_mean, 2)} ({dp.fmt_num(only_lo, 2)}–{dp.fmt_num(only_hi, 2)}), "
+ ("an interval that includes the average" if only_lo <= 1 <= only_hi
else "above the average" if only_lo > 1 else "below the average"))
# The scores still bound the number of these papers (a weighted mean): n_intl * m_intl = (n_intl - n) * m_ext +
# n * m_only, where readers know n_intl (the hover) and each mean to the two decimals shown. counts_open: the
# numbers n that fit. They tell readers nothing new when the values the site publishes already place the papers of
# these years that are international only through own affiliations, of every type (n plus at most the n_ncs_other
# items of other types), between known[0] and known[1] (sece_stats.small_groups: the site's values for all
# countries together, with what readers know of those left out).
def shown_range(value: float) -> tuple[float, float]:
"""The values that round to the two decimals shown."""
return round(value, 2) - 0.005, round(value, 2) + 0.005
(i_lo, i_hi), (e_lo, e_hi), (o_lo, o_hi) = (shown_range(m) for m in (G.loc["International", "mean"],
G.loc["International, external", "mean"],
only_mean))
counts_open = [n for n in range(n_intl + 1)
if n_intl * i_lo - (n_intl - n) * e_hi - n * o_hi <= 0 <= n_intl * i_hi - (n_intl - n) * e_lo - n * o_lo]
rule = sg.site()
ALL_YEARS = range(int(pubs["year"].min()), PARTIAL + 1)
audit = sg.Audit(rule.moved, ALL_YEARS,
pd.crosstab(pubs["year"], pubs["collab_type"]).reindex(index=ALL_YEARS, columns=sg.COLLAB,
fill_value=0),
rule.windows, sg.ranking_bounds(pubs, LAST_FULL)[1])
known = audit.range(audit.system(rule.split_shown, rule.cell_shown),
audit.vector(sg.INTL, range(NCS_FROM, NCS_TO + 1)))
if ext_split_shown:
ext_lead_text = (f"On the external-partner basis, partner-led international papers again score higher: "
f"{ci_text('International, external, partner-led')} against "
f"{ci_text('International, external, SECE-led', False)} for SECE-led ones.")
else:
ext_lead_text = ("On the external-partner basis, partner-led international papers again score higher than "
"SECE-led ones; these two scores are not shown, because with the other values they would "
"reveal a small group of papers (see the notes).")
# Overlap of the characteristics: international papers vs the others
intl_funded, other_funded = ncs.loc[intl, "has_funding"].mean(), ncs.loc[~intl, "has_funding"].mean()
intl_oa, other_oa = ncs.loc[intl, "oa_any"].mean(), ncs.loc[~intl, "oa_any"].mean()
# Mutually adjusted differences: least squares of the score on all characteristics at once
# (reference: single-institution, closed, no funding acknowledged, no industry partner); both models use
# the same bootstrap resamples of the papers
y = ncs["score"].to_numpy(dtype=float)
idx = np.random.default_rng(0).integers(0, n_ncs, size=(1000, n_ncs))
def adjusted(terms: dict[str, pd.Series]) -> pd.DataFrame:
"""Least-squares differences in mean score for indicator terms, with 95% bootstrap intervals."""
X = np.column_stack([np.ones(n_ncs)] + [m.to_numpy(dtype=float) for m in terms.values()])
coef = np.linalg.lstsq(X, y, rcond=None)[0]
boot = np.array([np.linalg.lstsq(X[i], y[i], rcond=None)[0] for i in idx])
return pd.DataFrame({"diff": coef[1:], "lo": np.quantile(boot[:, 1:], 0.025, axis=0),
"hi": np.quantile(boot[:, 1:], 0.975, axis=0)}, index=list(terms))
TERMS = {"International": intl, "National": ncs["collab_type"] == "national",
"Open access": ncs["oa_any"], "Funding acknowledged": ncs["has_funding"],
"Industry partner": ncs["has_industry_partner"], "SECE first or last author": led}
adj = adjusted(TERMS)
# the same model with the partner indicators on the external-partner basis
adj_ext = adjusted({**TERMS, "International": intl_ext, "National": ncs["collab_type_external"] == "national",
"Industry partner": ncs["has_industry_partner_external"]})
def adj_text(term: str, table: pd.DataFrame | None = None) -> str:
"""Adjusted difference in mean score with its interval, e.g. '+0.22 (95% CI +0.06 to +0.40)'
(from `adj`, or from `table`)."""
r = (adj if table is None else table).loc[term]
f = lambda v: ("+" if v >= 0 else "−") + dp.fmt_num(abs(v), 2)
return f"{f(r['diff'])} (95% CI {f(r['lo'])} to {f(r['hi'])})"
def adj_word(term: str, table: pd.DataFrame | None = None) -> str:
"""'positive' / 'negative' / 'uncertain' from the adjusted 95% interval (of `adj`, or of `table`)."""
r = (adj if table is None else table).loc[term]
return "positive" if r["lo"] > 0 else "negative" if r["hi"] < 0 else "uncertain"
adj_summary = (f"With the other characteristics held fixed, the international difference is "
f"{adj_word('International')}, the funding difference {adj_word('Funding acknowledged')}, "
f"the open-access difference {adj_word('Open access')} and the difference for an SECE first or "
f"last author {adj_word('SECE first or last author')}.")
ext_word = adj_word("International", adj_ext)
adj_ext_text = (f"With the international, national and industry-partner indicators on the external-partner basis, "
f"the international difference is {adj_text('International', adj_ext)}, "
f"{'also ' if ext_word == adj_word('International') else ''}{ext_word}.")
both_persist = all(adj_word(t) == "positive" for t in ("International", "Funding acknowledged"))
persist_text = ("both differences remain when these characteristics and SECE leadership are considered together"
if both_persist else
"not all of these differences remain clear when these characteristics and SECE leadership are "
"considered together")
# Robustness: do the group medians order each comparison like the means?
ORDER_DIMS = {"collaboration type": ["Single-institution", "National", "International"],
"open access vs closed": ["Open access (all types)", "Closed"],
"funding": ["Funding acknowledged", "No funding acknowledged"],
"industry partner": ["Industry partner", "No industry partner"],
"source type": ["Journal", "Conference"],
"SECE first or last author": ["SECE first or last author", "No SECE first or last author"],
"leadership of the international papers": ["International, SECE-led", "International, partner-led"]}
same_order = [name for name, grp in ORDER_DIMS.items()
if list(G.loc[grp, "mean"].sort_values().index)
== list(G.loc[grp, "median_score"].sort_values().index)]
other_order = [name for name in ORDER_DIMS if name not in same_order]
if same_order and other_order:
robust_text = (f"the group medians rank the groups as the means do for {join_and(same_order)}, "
f"but not for {join_and(other_order)}")
elif same_order:
robust_text = "the group medians rank the groups as the means do for every comparison"
else:
robust_text = "the group medians rank the groups differently from the means in every comparison"
# Matching coverage: industry partners rely on affiliations matched to ROR
cov_partner = meta["matching"]["excluding_auth"]["occurrence_matched_share"]
# Funding acknowledgements: papers before the latest ten full years against the latest five
funded_old = pubs.loc[pubs["year"] < TEN_FROM, "has_funding"].mean()
funded_recent = pubs.loc[pubs["year"].between(*periods.bounds(P_RECENT)), "has_funding"].mean()
# The text states these patterns of the current data: stop if new data change them.
checks = {
"text: the windowed h-indices are lower than the h-index over all years": h_recent < h_ten < h_all,
"text: n_h (>= h) papers are cited at least h times, but only n_h_next (< h + 1) at least h + 1 times":
n_h >= h_all and n_h_next < h_next,
"text: most papers have fewer than 10 citations": share_papers_lt10 > 0.5,
"text: citations are concentrated (the most-cited 10% of the papers hold most of them)": top10_share > 0.5,
"text: concentration is lower within publication years": cohort_top10_median < top10_share,
"text: some years before NCS_FROM have fewer than NCS_MIN articles and reviews or conference papers": thin.any(),
"text: recent papers average fewer citations than those of the period before": p_recent["mean"] < p_prev["mean"],
"text: the median falls in the latest full year, below that of every year COHORT_FROM..MATURE_TO":
y_last["median"] < median_min and y_last["median"] <= y_before_last["median"],
"text: the mean jumps in the year of the most-cited paper (shown in the chart, above both neighbours)":
FIRST_YEAR < peak_year < LAST_FULL
and year_stats.loc[peak_year, "mean"] > year_stats.loc[[peak_year - 1, peak_year + 1], "mean"].max(),
"text: most of the top papers are older than the latest period, more than among all papers":
top_before_recent / len(top) > max(0.5, share_before_recent),
"caption: every title in the top-papers table links to its DOI": top["doi"].notna().all(),
"text: the other items in the window are mostly book chapters, also editorials, errata and other types":
other_types.index[0] == "Book chapter" and {"Editorial", "Erratum"} <= set(other_types.index)
and len(other_types) > 3,
"text: most years have too few reviews for an average of their own": (reviews_year < NCS_MIN).mean() > 0.5,
"text: international papers are cited above the average": G.loc["International", "lo"] > 1,
"text: mainly those led by partners (most of the international papers' excess citations)":
partner_excess_share > 0.5,
"text: papers with a funding acknowledgement are cited above the average": G.loc["Funding acknowledged", "lo"] > 1,
"text: partner-led international papers score higher than SECE-led ones": mean_gap > 0,
"text: on the external-partner basis too, partner-led international papers score higher":
G.loc["International, external, partner-led", "mean"] > G.loc["International, external, SECE-led", "mean"],
"small groups: every external-partner value of the figure and the text, and every number a reader can form "
"from them and the address-based values, rests on no or at least MIN_HOLDERS SECE authors":
remainders_safe([ext_cells[g] for g in EXT_PAIRS
if g in set(ncs_shown["group"]) or g == "International, external"
or (g in EXT_SPLIT and ext_split_shown)]),
"small groups: no external-partner group comes with its number of papers (next to the address-based number it "
"would give how many papers of NCS_FROM..NCS_TO are international only through own affiliations, which is not "
"a value the site publishes)":
ncs_shown.loc[ncs_shown["group"].isin(EXT_PAIRS), "papers_text"].eq("not shown").all(),
"small groups: the scores shown do not narrow that number beyond what the values the site publishes give":
bool(counts_open) and min(counts_open) <= known[0] and max(counts_open) + n_ncs_other >= known[1],
"small groups: the site's rule for the values for all countries together holds": all(rule.checks().values()),
"text: the medians of SECE-led and partner-led international papers differ much less than their means":
abs(intl_partner_median - intl_led_median) < mean_gap / 3,
"text: most of the difference comes from a tail of highly cited partner-led papers (over-represented in the "
"top 5% of the international papers; without the top 5% of each group, less than half of the gap remains)":
partner_share_top5 > share_intl_partner and gap_trimmed < mean_gap / 2,
"text: the open-access routes differ, green-only above gold": G.loc["Green", "lo"] > G.loc["Gold", "hi"],
"text: journal papers are cited far more than conference papers":
journal_ratio > 2 and G.loc["Journal", "lo"] > G.loc["Conference", "hi"],
"text: international papers more often acknowledge funding and are more often open access":
intl_funded > other_funded and intl_oa > other_oa,
"notes: funding acknowledgements are missing especially for older papers": funded_old < funded_recent,
}
failed = [claim for claim, ok in checks.items() if not ok]
assert not failed, f"the text no longer matches the data: {failed}"