import re
from functools import partial
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sece_stats import metrics, 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")
meta = data.load_metadata()
HOME, AUTH = config.HOME_COUNTRY, config.AUTH_ROR
n_pubs = len(pubs)
FIRST_YEAR = int(pubs["year"].min())
LAST_FULL = periods.LAST_FULL # latest full year (PARTIAL - 1)
START = 1995 # first year of the annual charts (earlier years have few papers)
AS_OF_TEXT = f"{AS_OF.day} {AS_OF:%B %Y}"
# The site's five-year periods (sece_stats.periods): they end with the latest full year, the first one is
# clipped to the data, and the partial year has a label of its own.
period_of = partial(periods.period_of, first_year=FIRST_YEAR)
def and_join(items: list[str]) -> str:
"""'a', 'a and b', 'a, b and c'."""
items = list(items)
return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
def fold_text(ratio: float) -> str:
"""A growth by a factor of about two to four in words: 'doubled', 'more than doubled', 'nearly tripled'..."""
words = {2: "doubled", 3: "tripled", 4: "quadrupled"}
assert 1.9 <= ratio < 4.1, f"text: no wording for a growth by {ratio:.2f} times"
k = round(ratio)
if abs(ratio - k) <= 0.1:
return words[k]
if ratio < k <= ratio + 0.25:
return f"nearly {words[k]}"
return f"more than {words[int(ratio)]}"
def latest_text(share: pd.Series) -> str:
"""The latest full year against the other full years: 'reached <share> in <LAST_FULL>, its highest of any
full year', or 'was <share> in <LAST_FULL>, after a high of <share> in <year>' when an earlier full year
has the highest share."""
best = share.loc[:LAST_FULL].idxmax()
if best == LAST_FULL:
return f"reached {dp.fmt_pct(share[LAST_FULL])} in {LAST_FULL}, its highest of any full year"
return f"was {dp.fmt_pct(share[LAST_FULL])} in {LAST_FULL}, after a high of {dp.fmt_pct(share[best])} in {best}"
def top_rows(ranking: pd.DataFrame, col: str, n: int) -> pd.DataFrame:
"""The first n rows of a ranking sorted by *col* (largest first) and any further rows tied with the n-th,
so that the selection does not depend on how ties are broken."""
return ranking[ranking[col].ge(ranking[col].iloc[n - 1])] if len(ranking) > n else ranking
def separated(ranking: pd.DataFrame, col: str, k: int) -> bool:
"""True when the first k rows of a ranking sorted by *col* (largest first) rank above all the others, so
that the k named first do not depend on how ties are broken."""
return len(ranking) <= k or ranking[col].iloc[k - 1] > ranking[col].iloc[k]
P_RECENT = period_of(LAST_FULL) # the latest five full years
P_PREV = period_of(LAST_FULL - 5) # the five years before them
P_EARLY = period_of(LAST_FULL - 20) # twenty years earlier: the baseline of the comparisons
EARLY_FIRST = periods.bounds(P_EARLY)[0] # first year of P_EARLY
P_PRE = period_of(EARLY_FIRST - 1) # the period before the baseline
pubs["period"] = pubs["year"].map(period_of)
full = pubs[pubs["year"] < PARTIAL].copy() # full calendar years only
PERIODS = periods.periods(FIRST_YEAR) # full-year periods, oldest first
assert set(full["period"]) == set(PERIODS), "every period has papers"
CHART_PERIODS = [p for p in PERIODS if periods.bounds(p)[0] >= START]
DECADE_2000S = [p for p in PERIODS if 2000 <= periods.bounds(p)[0] <= 2009] # periods that start in the 2000s
period_n = full.groupby("period").size()
# ------------------------------------------------------------------ small groups
usable = pub_aff[pub_aff["match_method"].ne("ignored")]
# own: an SECE author's own second affiliation, i.e. outside AUTH and listed only by SECE authors of the
# paper (an affiliation that no author lists counts as external, as in the pipeline)
usable = usable.assign(own=~usable["is_auth"] & usable["held_only_by_sece"].fillna(False).astype(bool))
# Small groups: no number of papers that link to something (an institution, a sector, a collaboration type, in any
# year or period) only through such affiliations is shown, or can be worked out from the numbers shown (as the
# difference between the two bases, or a total minus its shown parts, also with the numbers of other pages), unless
# it is zero or at least config.MIN_SECE_HOLDERS distinct SECE authors hold the affiliations it rests on. With fewer it
# would in practice be one or two people's paper count (no per-person metrics): the page then leaves it out or
# describes it in words, and leaves out enough other values that it cannot be worked out (the checks at the end of
# this cell).
MIN_HOLDERS = config.MIN_SECE_HOLDERS
authors = data.load_publication_authors()
# own_holders: one row per own affiliation and SECE author who holds it (author ids are only counted).
own_holders = sg.own_holders(pub_aff, authors)
safe = sg.safe # safe(papers, holders): the number may be shown or be derivable (zero, or MIN_HOLDERS SECE authors)
def count_holders(pairs: pd.DataFrame) -> int:
"""Distinct SECE authors who hold the own second affiliations behind the given (eid, org) links."""
return own_holders.merge(pairs[["eid", "org"]].drop_duplicates(), on=["eid", "org"])["author_id"].nunique()
def links_safe(pairs: pd.DataFrame) -> bool:
"""The papers of the given (eid, org) links that are only through own affiliations may be counted."""
return safe(pairs["eid"].nunique(), count_holders(pairs))
# ------------------------------------------------------------------ collaboration types
COLLAB = data.COLLAB_TYPE_ORDER
COLLAB_LABEL = {"single-institution": "Single-institution", "national": "National",
"international": "International"}
COLLAB_COLORS = {COLLAB_LABEL[k]: c for k, c in dp.CATEGORY_COLORS["collab_type"].items()}
type_year = pd.crosstab(pubs["year"], pubs["collab_type"]).reindex(columns=COLLAB, fill_value=0)
type_year_share = type_year.div(type_year.sum(axis=1), axis=0)
type_period = pd.crosstab(full["period"], full["collab_type"]).reindex(columns=COLLAB, fill_value=0)
type_period_share = type_period.div(period_n, axis=0)
single, national, intl = (type_period_share[c] for c in COLLAB)
multi = 1 - single
intl_year = type_year_share.loc[:LAST_FULL, "international"]
intl_last = intl_year[LAST_FULL]
since_early = PERIODS[PERIODS.index(P_EARLY):] # P_EARLY to P_RECENT
nat_min, nat_max = national[since_early].min(), national[since_early].max()
intl_fold = fold_text(intl[P_RECENT] / intl[P_EARLY]) # 'doubled', 'more than doubled', ... (key findings)
intl_gain_pp = 100 * (intl[P_RECENT] - intl[P_EARLY])
nat_gain_pp = 100 * (national[P_RECENT] - national[P_EARLY])
nat_verb = "gained" if nat_gain_pp >= 0 else "lost" # the national share from P_EARLY to P_RECENT
greek_any = full.groupby("period")["has_national_partner"].mean() # any Greek partner affiliation
max_pre_start = int(type_year.sum(axis=1).loc[:START - 1].max())
# The same types counting only affiliations of co-authors who are not SECE authors (the pipeline's
# *_external fields; the page calls them external-partner values): an affiliation outside AUTH that only
# SECE authors of the paper list, i.e. an SECE author's own second affiliation (a joint, adjunct or
# visiting position), no longer makes a paper national or international.
OWN_TEXT = "only through SECE authors’ own second affiliations"
OWN_LABEL = "Only through SECE authors’ own second affiliations"
OWN_INTL = f"International {OWN_TEXT}" # the hatched part of the international bars
OWN_PATTERN = dict(shape="x", fgcolor="#ffffff", size=6, solidity=0.3, fillmode="overlay")
type_period_ext = (pd.crosstab(full["period"], full["collab_type_external"])
.reindex(index=PERIODS, columns=COLLAB, fill_value=0))
type_period_ext_share = type_period_ext.div(period_n, axis=0)
single_ext, national_ext, intl_ext = (type_period_ext_share[c] for c in COLLAB)
intl_year_ext = full.groupby("year")["is_international_external"].mean()
intl_last_ext = intl_year_ext[LAST_FULL]
intl_gain_ext_pp = 100 * (intl_ext[P_RECENT] - intl_ext[P_EARLY])
nat_gain_ext_pp = 100 * (national_ext[P_RECENT] - national_ext[P_EARLY])
# the move away from single-institution papers went entirely to international ones when the national share
# did not grow on either basis (the three shares add up to one)
shift_word = "mostly" if max(nat_gain_pp, nat_gain_ext_pp) > 0 else "entirely"
gap_pp = 100 * (intl - intl_ext) # percentage points between the two bases, by period
gap_last_pp = 100 * (intl_last - intl_last_ext)
# papers that are international only through SECE authors' own second affiliations abroad
own_intl = pubs["is_international"] & ~pubs["is_international_external"]
n_intl, n_own_intl = (s.groupby(pubs["period"]).sum() for s in (pubs["is_international"], own_intl))
n_intl_year, own_intl_year = (s.groupby(pubs["year"]).sum() for s in (pubs["is_international"], own_intl))
# all years: address-based type (rows) against the external-partner type (columns)
moves = (pd.crosstab(pubs["collab_type"], pubs["collab_type_external"])
.reindex(index=COLLAB, columns=COLLAB, fill_value=0))
type_all, type_all_ext = moves.sum(axis=1), moves.sum(axis=0)
intl_to_single, intl_to_nat, nat_to_single = (int(moves.at[a, b]) for a, b in (
("international", "single-institution"), ("international", "national"), ("national", "single-institution")))
n_own_intl_all = intl_to_single + intl_to_nat
share_own_intl_all = n_own_intl_all / type_all["international"]
share_nat_to_single = nat_to_single / type_all["national"]
# Small groups in the collaboration types. A paper changes type between the two bases through the SECE authors who
# hold its own second affiliations: those abroad for a paper that is international only through them (it becomes
# single-institution or national), those in Greece for a national paper that becomes single-institution (the
# matched ones, or all of them where none is matched: an unmatched string may name only a laboratory). The site's
# rule (sece_stats.small_groups, the same for every page) holds these definitions: moved, one row per changed paper,
# change (address-based > external-partner type), place and SECE author; CAUSE, what each change rests on; CELL,
# what the difference of each type (address-based minus external-partner count) rests on.
rule = sg.site()
moved, CAUSE, CELL = rule.moved, sg.CAUSE, sg.CELL
TO_SINGLE, TO_NAT, NAT_SINGLE = sg.TO_SINGLE, sg.TO_NAT, sg.NAT_SINGLE
in_greece = own_holders["country_code"].eq(HOME)
PLACE = sg.places(own_holders) # own affiliations abroad, and those in Greece that a national paper rests on
changed = partial(sg.changed, moved) # changed(years, parts): (papers, SECE authors) of these (change, place) parts
years_of = sg.years_of
ALL_YEARS = range(FIRST_YEAR, PARTIAL + 1)
assert [changed(ALL_YEARS, CAUSE[c])[0] for c in CAUSE] == [intl_to_single, intl_to_nat, nat_to_single], \
"every type change rests on own affiliations of its place"
# Where the page gives these differences: the annual chart splits the international bars (CHART_YEARS), the table
# gives the external-partner share of each type and period, and the text gives all years (the partial year
# included; every type and change) and P_EARLY, P_RECENT and LAST_FULL. Other pages give some of them too, and other
# windows of years (Global reach: the years before P_RECENT). The site's rule shows a split or a share only where its
# difference may be shown, hides enough others that what is hidden does not follow from what is shown (complementary
# cells), and checks the values of all pages together, with what a reader knows of the values left out (at least one
# paper, at most the international papers), hiding further cells until no small group follows from them.
CHART_YEARS = range(START, LAST_FULL + 1)
assert rule.chart_years == list(CHART_YEARS) and rule.periods == PERIODS, "the chart and the table follow the rule"
split_shown, cell_shown = rule.split_shown, rule.cell_shown
def unshown_years(t: str) -> list[int]:
"""The years whose difference for type t follows only together, from all years minus the parts shown: those
of the periods that hide it and the partial year, without (international) the years the chart splits."""
years = [y for p in PERIODS if not cell_shown.at[p, t] for y in years_of(p)] + [PARTIAL]
return [y for y in years if t != "international" or not split_shown.get(y, False)]
def tint(color: str, amount: float = 0.35) -> str:
"""Hex colour mixed with white (0: unchanged, 1: white)."""
rgb = (int(color[i:i + 2], 16) for i in (1, 3, 5))
return "#" + "".join(f"{round(c + (255 - c) * amount):02x}" for c in rgb)
def both_pct(addr: pd.Series, ext: pd.Series, shown: pd.Series) -> list[str]:
"""'48.3% (44.7%)': the share counting every affiliation, with the external-partner share in
brackets where the two differ after rounding, or '48.3% (–)' where it is not shown (small groups)."""
return [a if ok and a == e else f"{a} ({e if ok else '–'})"
for a, e, ok in zip(addr.map(dp.fmt_pct), ext.map(dp.fmt_pct), shown)]
# ------------------------------------------------------------------ partner institutions
# A partner institution is the top-level ROR organisation of an affiliation outside AUTH (society
# memberships are ignored), as in the pipeline's n_partner_orgs.
ITI, CERTH = "https://ror.org/0069akp70", "https://ror.org/03bndpq63"
KHALIFA = "https://ror.org/05hffr360" # Khalifa University of Science and Technology: "Khalifa University" in prose
ATEI, IHU = "https://ror.org/04h36ea57", "https://ror.org/00708jp83" # Alexander TEI and its successor, IHU
ROR_VERSION = meta["ror_version"]
# the notes on ITI below rest on ROR listing it without a parent
assert pd.isna(orgs.at[ITI, "parent_id"]), f"ROR {ROR_VERSION} lists a parent for ITI: revise the ITI notes"
partner_rows = usable[~usable["is_auth"] & usable["ror_id_top"].notna() & usable["ror_id_top"].ne(AUTH)]
links = (partner_rows[["eid", "year", "ror_id_top"]].rename(columns={"ror_id_top": "org"})
.drop_duplicates(ignore_index=True))
links["period"] = links["year"].map(period_of)
# external link: at least one affiliation of the institution on the paper is not an SECE author's own
external = (partner_rows.assign(external=~partner_rows["own"]).rename(columns={"ror_id_top": "org"})
.groupby(["eid", "org"], as_index=False)["external"].any())
links = links.merge(external, on=["eid", "org"], how="left", validate="one_to_one")
assert (links.groupby("eid")["org"].nunique().reindex(pubs["eid"], fill_value=0).to_numpy()
== pubs["n_partner_orgs"].to_numpy()).all(), "partner links must reproduce n_partner_orgs"
assert (links[links["external"]].groupby("eid")["org"].nunique().reindex(pubs["eid"], fill_value=0).to_numpy()
== pubs["n_partner_orgs_external"].to_numpy()).all(), "external links must reproduce n_partner_orgs_external"
# Sector = primary ROR type of the partner institution (Methodology & data, "Definitions").
SECTOR_LABEL = {"education": "Education", "facility": "Research facility", "nonprofit": "Nonprofit",
"government": "Government", "company": "Company", "healthcare": "Healthcare"}
SECTORS = list(SECTOR_LABEL)
# Fixed sector colours, pinned rather than derived from the order above: a sector must have the same
# colour on every page that shows sectors (also the partner bubble map in Global reach).
SECTOR_COLORS = {"Education": dp.CATEGORICAL[0], "Research facility": dp.CATEGORICAL[1],
"Nonprofit": dp.CATEGORICAL[2], "Government": dp.CATEGORICAL[3],
"Company": dp.CATEGORICAL[4], "Healthcare": dp.CATEGORICAL[5], "Other": dp.OTHER_COLOR}
assert list(SECTOR_COLORS) == [*SECTOR_LABEL.values(), "Other"], "one colour per sector, legend order"
org_sector = orgs["primary_type"].where(orgs["primary_type"].isin(SECTORS), "other")
links["sector"] = links["org"].map(org_sector)
# ITI is an institute of CERTH that ROR lists without a parent: it stays a separate
# organisation (as everywhere on this site) but is labelled with CERTH.
DISPLAY_NAME = {ITI: "Information Technologies Institute (CERTH)"}
partners = links.groupby("org").agg(papers=("eid", "nunique"), first_year=("year", "min"))
partners["recent"] = (links[links["period"].eq(P_RECENT)].groupby("org")["eid"].nunique()
.reindex(partners.index, fill_value=0))
# papers that link to the institution only through SECE authors' own second affiliations (all years,
# recent); *_shown: the count may be shown (none, or at least MIN_HOLDERS SECE authors hold them, and it gives
# away no smaller count: below)
own_links = links[~links["external"]]
partners["only"] = own_links.groupby("org")["eid"].nunique().reindex(partners.index, fill_value=0)
partners["recent_only"] = (own_links[own_links["period"].eq(P_RECENT)].groupby("org")["eid"].nunique()
.reindex(partners.index, fill_value=0))
own_link_holders = own_holders.merge(own_links[["eid", "org", "period"]], on=["eid", "org"])
recent_link_holders = own_link_holders[own_link_holders["period"].eq(P_RECENT)]
for col, sub in (("only", own_link_holders), ("recent_only", recent_link_holders)):
n_held = sub.groupby("org")["author_id"].nunique().reindex(partners.index, fill_value=0)
partners[f"{col}_shown"] = partners[col].eq(0) | n_held.ge(MIN_HOLDERS)
# The hovers give both counts of an institution, so their difference (its papers of the other years) must rest on
# enough SECE authors too; where it does not, the count of P_RECENT is not shown either (the all-years count also
# follows from the external-partner ranking in the text).
other_only = (own_links[own_links["period"].ne(P_RECENT)].groupby("org")["eid"].nunique()
.reindex(partners.index, fill_value=0))
other_held = (own_link_holders[own_link_holders["period"].ne(P_RECENT)].groupby("org")["author_id"].nunique()
.reindex(partners.index, fill_value=0))
partners["recent_only_shown"] &= ~(partners["only_shown"] & other_only.gt(0) & other_held.lt(MIN_HOLDERS))
partners["papers_ext"] = partners["papers"] - partners["only"]
partners["recent_ext"] = partners["recent"] - partners["recent_only"]
partners = partners.join(orgs[["name", "acronym", "country_code", "country_name", "city"]])
partners["name"] = [DISPLAY_NAME.get(org, name) for org, name in zip(partners.index, partners["name"])]
partners["sector"] = org_sector.reindex(partners.index).map({**SECTOR_LABEL, "other": "Other"})
partners = partners.rename_axis("ror_id").reset_index()
by_all = partners.sort_values(["papers", "name"], ascending=[False, True], ignore_index=True)
by_recent = (partners[partners["recent"] > 0]
.sort_values(["recent", "name"], ascending=[False, True], ignore_index=True))
# the figures: the 25 most frequent partners of all years and the 15 of P_RECENT, with any tied with the last
top_all, top_recent = top_rows(by_all, "papers", 25), top_rows(by_recent, "recent", 15)
top_all_min, top_recent_min = int(top_all["papers"].min()), int(top_recent["recent"].min())
# the same rankings counting only affiliations of co-authors who are not SECE authors
by_ext = partners.sort_values(["papers_ext", "name"], ascending=[False, True], ignore_index=True)
by_recent_ext = partners.sort_values(["recent_ext", "name"], ascending=[False, True], ignore_index=True)
# the most papers only through SECE authors' own second affiliations, among the counts that may be shown,
# and the partners of the all-years figure whose count is not shown although it is at least half of their papers
most_own = (partners[partners["only"].gt(0) & partners["only_shown"]]
.sort_values(["only", "name"], ascending=[False, True], ignore_index=True))
mostly_hidden = (top_all[top_all["only"].mul(2).ge(top_all["papers"]) & ~top_all["only_shown"]]
.reset_index(drop=True))
lead_ext = by_ext.iloc[0]
by_id = partners.set_index("ror_id")
n_partners = len(partners)
n_partners_ext = int(partners["papers_ext"].gt(0).sum())
n_partners_own_only = n_partners - n_partners_ext
# In Greece / abroad as on Global reach: a foreign institution counts as abroad when an affiliation
# located outside Greece names it; one seen only through a campus or branch in Greece is counted apart.
abroad_ids = set(partner_rows.loc[partner_rows["country_code"].notna()
& partner_rows["country_code"].ne(HOME), "ror_id_top"])
is_gr = partners["country_code"].eq(HOME)
is_abroad = partners["ror_id"].isin(abroad_ids) & partners["country_code"].notna() & ~is_gr
n_partners_gr, n_partners_abroad = int(is_gr.sum()), int(is_abroad.sum())
n_partners_branch = int((partners["country_code"].notna() & ~is_gr & ~is_abroad).sum())
assert n_partners_gr + n_partners_abroad + n_partners_branch + int(partners["country_code"].isna().sum()) \
== n_partners, "every partner institution is in Greece, abroad, or a foreign one seen only in Greece"
branch_text = ("" if n_partners_branch == 0 else
f"; {dp.fmt_int(n_partners_branch)} foreign institution"
+ (" appears" if n_partners_branch == 1 else "s appear") + " only through a campus or branch in Greece")
# the same rule over the affiliations that are not SECE authors' own (external-partner basis)
ext_rows = partner_rows[~partner_rows["own"]]
abroad_ids_ext = set(ext_rows.loc[ext_rows["country_code"].notna() & ext_rows["country_code"].ne(HOME),
"ror_id_top"])
n_partners_abroad_ext = int((partners["ror_id"].isin(abroad_ids_ext) & partners["country_code"].notna()
& ~is_gr).sum())
greek = by_all[by_all["country_code"].eq(HOME)].reset_index(drop=True)
abroad = by_all[by_all["ror_id"].isin(set(partners.loc[is_abroad, "ror_id"]))].reset_index(drop=True)
n_gr_top = int(top_all["country_code"].eq(HOME).sum())
n_abroad_top_recent = int(top_recent["country_code"].ne(HOME).sum())
certh_iti_papers = links.loc[links["org"].isin([ITI, CERTH]), "eid"].nunique()
best_other = by_all.loc[~by_all["ror_id"].isin([ITI, CERTH]), "papers"].iloc[0]
share_oneoff = partners["papers"].eq(1).mean()
n_10plus = int(partners["papers"].ge(10).sum())
papers_with_partner = links["eid"].nunique()
leading = top_rows(by_all, "papers", 10) # the ten most frequent partners, with any tied with the tenth
leading_min = int(leading["papers"].min())
leading_share = links.loc[links["org"].isin(leading["ror_id"]), "eid"].nunique() / papers_with_partner
_THE = re.compile(r"(?:National|International|Technical|Hellenic|Greek|Lebanese|European|Information"
r"|Centre|Center|Foundation|Institute|Royal)\b")
PROSE_NAME = {ITI: "CERTH's Information Technologies Institute", KHALIFA: "Khalifa University"} # as on other pages
def prose(org: str) -> str:
"""Partner name for running text: no "(Country)" suffix, "the" where English needs it."""
if org in PROSE_NAME:
return PROSE_NAME[org]
row = by_id.loc[org]
name = row["name"].removesuffix(f" ({row['country_name']})")
return f"the {name}" if " of " in name or _THE.match(name) else name
def most_or_half(m: int, n: int) -> str:
"""'most' or 'half': a count m of at least half of n, in words (for counts that are not shown)."""
return "most" if 2 * m > n else "half"
def top_text(df: pd.DataFrame, col: str, k: int, unit: str = " papers", own: str | None = None) -> str:
"""'A (n papers), B (n) and C (n)' for the first k rows of a ranking. With *own* (the column of
papers only through SECE authors' own second affiliations), an institution where these are at least
half of its papers reads 'A (n, m of them only through ...)', or 'A (n, most of them only through
...)' when m may not be shown (column *own*_shown)."""
parts = []
for i, row in enumerate(df.head(k).to_dict("records")):
text = f"{dp.fmt_int(row[col])}{unit if i == 0 else ''}"
if own is not None and 2 * row[own] >= row[col] > 0:
m = dp.fmt_int(row[own]) if row[f"{own}_shown"] else most_or_half(row[own], row[col])
text += f", {m} of them {OWN_TEXT}"
parts.append(f"{prose(row['ror_id'])} ({text})")
return and_join(parts)
def own_examples(k: int) -> str:
"""'m of the n papers with A and m of the n with B link to the institution only through ...': the k
partners with the most such papers among the counts that may be shown, then ', and so do most of
the n papers with C' for the partners of the all-years figure whose count is not shown (mostly_hidden)."""
shown = [f"{dp.fmt_int(m)} of the {dp.fmt_int(n)}{' papers' if i == 0 else ''} with {prose(org)}"
for i, (org, m, n) in enumerate(zip(most_own["ror_id"].head(k), most_own["only"].head(k),
most_own["papers"].head(k)))]
hidden = [f"{most_or_half(m, n)} of the {dp.fmt_int(n)} papers with {prose(org)}"
for org, m, n in zip(mostly_hidden["ror_id"], mostly_hidden["only"], mostly_hidden["papers"])]
return (f"{and_join(shown)} link to the institution {OWN_TEXT}"
+ (f", and so do {and_join(hidden)}" if hidden else ""))
# partners of P_RECENT counting only affiliations of co-authors who are not SECE authors: names only,
# since these counts minus the address-based ones would give counts that may not be shown
recent_ext_names = and_join([prose(org) for org in by_recent_ext["ror_id"].head(4)])
# ------------------------------------------------------------------ sectors and industry
sec_full = links[(links["year"] < PARTIAL) & links["sector"].isin(SECTORS)]
sec_period = (sec_full.groupby(["period", "sector"])["eid"].nunique().unstack(fill_value=0)
.reindex(index=PERIODS, columns=SECTORS, fill_value=0))
sec_share = sec_period.div(period_n, axis=0)
sec_year = (sec_full.groupby(["year", "sector"])["eid"].nunique().unstack(fill_value=0)
.reindex(columns=SECTORS, fill_value=0))
paper_year = full.groupby("year").size()
nonprofit_links = sec_full[sec_full["sector"].eq("nonprofit")]
np_iti = nonprofit_links[nonprofit_links["org"].eq(ITI)].groupby("period")["eid"].nunique()
np_all = nonprofit_links.groupby("period")["eid"].nunique()
n_other_sector = links.loc[links["sector"].eq("other"), "eid"].nunique()
# Companies: ROR lists few, so unmatched affiliations outside AUTH that name a company by its legal form
# also count (a sensitivity check; the site-wide industry flag uses ROR only). Common forms count in any
# address (SA and AB not in Australian or Canadian ones, where they are states); short national forms only in
# addresses of their own country, where they mean nothing else, and there as they are written: with or without
# dots and spaces, in any case ("S.A.", "S. A.", "SA", "Sa"; "P.C.", "PC"; "I.K.E.", "Ike").
LEGAL_FORM = re.compile(
r"(?<![\w.&])(?:Ltd|LTD|Limited|LIMITED|GmbH|Gmbh|GMBH|Inc|INC|Corporation|CORPORATION|Corp|CORP|LLC|PLC|Plc|plc"
r"|S\.A\.?U?|S\.p\.A|S\.P\.A|SpA|S\.r\.l|S\.R\.L|Srl|SRL|srl|B\.V\.?|BV|Bv|N\.V\.|A/S|ApS|Oyj?|OÜ"
r"|O\.E\.|A\.E\.)(?![\w&])")
BARE_FORM = re.compile(r"(?<![\w.&])(?:SA|AB)(?![\w&])") # also state codes in AU / CA addresses
NATIONAL_FORM = { # S.A., S.M.S.A., P.C., S.M.P.C., I.K.E., A.E., O.E., E.P.E.; OÜ; AB; JSC, AD, EAD, OOD, EOOD
HOME: re.compile(r"(?<![\w.&])(?:S\.?\s?A|S\.?\s?M\.?\s?S\.?\s?A|P\.?\s?C|S\.?\s?M\.?\s?P\.?\s?C"
r"|I\.?\s?K\.?\s?E|A\.?\s?E|O\.?\s?E|E\.?\s?P\.?\s?E)\.?(?![\w&])", re.IGNORECASE),
"EE": re.compile(r"(?<![\w.&])O[UÜ](?![\w&])", re.IGNORECASE),
"SE": re.compile(r"(?<![\w.&])AB(?![\w&])", re.IGNORECASE),
"BG": re.compile(r"(?<![\w.&])(?:JSC|E?AD|E?OOD)(?![\w&])"),
}
unmatched = usable[usable["match_method"].eq("none") & ~usable["is_auth"]]
names_company = (unmatched["affiliation"].str.contains(LEGAL_FORM)
| (unmatched["affiliation"].str.contains(BARE_FORM) & ~unmatched["country_code"].isin(["AU", "CA"])))
for country, form in NATIONAL_FORM.items():
names_company |= unmatched["affiliation"].str.contains(form) & unmatched["country_code"].eq(country)
company_rows = unmatched[names_company]
for frame in (pubs, full):
frame["company_ror"] = frame["has_industry_partner"]
frame["company_any"] = frame["has_industry_partner"] | frame["eid"].isin(company_rows["eid"])
frame["company_text_only"] = frame["company_any"] & ~frame["company_ror"]
ind = full.groupby("period")[["company_ror", "company_any", "company_text_only"]].mean()
ind_n = full.groupby("period")[["company_ror", "company_any", "company_text_only"]].sum()
ror_listed = ind_n["company_ror"] / ind_n["company_any"] # papers with a company: one listed in ROR
n_company_strings = company_rows["affiliation"].nunique()
n_unmatched_strings = unmatched["affiliation"].nunique()
# with an address in Greece (a string that names no country counts as not in Greece)
company_strings_gr = company_rows.drop_duplicates("affiliation")["country_code"].eq(HOME).mean()
top_companies = by_all[by_all["sector"].eq(SECTOR_LABEL["company"])].reset_index(drop=True)
# ------------------------------------------------------------------ Greek partners
gr_links = links[links["org"].map(orgs["country_code"]).eq(HOME)]
GR_COLS = [f"{FIRST_YEAR}–{EARLY_FIRST - 1}", *since_early] # the years before P_EARLY together
# Short row labels for the heatmap (full names in the hover), so that it stays readable on phones.
SHORT_NAME = [(r"^Information Technologies Institute \(CERTH\)$", "CERTH-ITI"),
(r"^Centre for Research and Technology Hellas$", "CERTH"),
(r"^Foundation for Research and Technology Hellas$", "FORTH"),
(r'^National Centre of Scientific Research "?Demokritos"?$', 'NCSR "Demokritos"'),
(r"^National Technical University of Athens$", "NTUA (Athens)"),
(r"^National and Kapodistrian University of Athens$", "Univ. of Athens (NKUA)"),
(r"Technological Educational Institute", "TEI"), (r"\bUniversity\b", "Univ."),
(r"\bInternational\b", "Int."), (r"\bTechnical\b", "Tech.")]
def short_name(name: str) -> str:
for rx, short in SHORT_NAME:
name = re.sub(rx, short, name)
return name.replace(" of Thessaloniki", " Thessaloniki") if name.startswith("Alexander") else name
def gr_column(year: int) -> str:
return GR_COLS[0] if year < EARLY_FIRST else period_of(year)
gr_full = gr_links[gr_links["year"] < PARTIAL]
gr_tab = (gr_full.assign(col=gr_full["year"].map(gr_column)).groupby(["org", "col"])["eid"].nunique()
.unstack(fill_value=0).reindex(columns=GR_COLS, fill_value=0))
gr_tab["total"] = gr_full.groupby("org")["eid"].nunique()
gr_tab["name"] = by_id["name"].reindex(gr_tab.index)
gr_top = top_rows(gr_tab.sort_values(["total", "name"], ascending=[False, True]), "total", 15) # the figure
gr_recent = gr_tab.sort_values([P_RECENT, "name"], ascending=[False, True])
gr_lead = list(gr_recent.index[:2]) # most frequent Greek partners in P_RECENT
P_CMP = period_of(LAST_FULL - 10) # ten years before P_RECENT: their growth since
certh_iti = (links[links["org"].isin([ITI, CERTH]) & (links["year"] < PARTIAL)]
.groupby("period")["eid"].nunique())
certh_iti_peak = certh_iti.idxmax()
certh_iti_ext = (links[links["org"].isin([ITI, CERTH]) & (links["year"] < PARTIAL) & links["external"]]
.groupby("period")["eid"].nunique())
# CERTH with ITI only through SECE authors' own second affiliations, by period: may the counts be shown?
ci_links = links[links["org"].isin([ITI, CERTH]) & (links["year"] < PARTIAL)]
ci_own = ci_links[~ci_links["eid"].isin(set(ci_links.loc[ci_links["external"], "eid"]))]
assert ci_own.groupby("period")["eid"].nunique().equals(
certh_iti.sub(certh_iti_ext, fill_value=0).astype("int64").loc[lambda s: s > 0]), "CERTH with ITI, own links"
certh_iti_shown = {p: count_holders(g) >= MIN_HOLDERS for p, g in ci_own.groupby("period")}
def ext_words(m: int, n: int) -> str:
"""How many of n papers also count on the external-partner basis, in words, when the number m of those
that link only through SECE authors' own second affiliations may not be shown."""
return "nearly all" if 10 * m <= n else "most" if 2 * m < n else "at most half"
# CERTH with ITI in P_RECENT on the external-partner basis: the count, or in words where it may not be shown
ci_recent_own = int(certh_iti.get(P_RECENT, 0) - certh_iti_ext.get(P_RECENT, 0))
ci_recent_tail = (f" ({dp.fmt_int(certh_iti_ext.get(P_RECENT, 0))} on that basis)"
if certh_iti_shown.get(P_RECENT, True) else
f", {ext_words(ci_recent_own, certh_iti[P_RECENT])} of them with co-authors from CERTH or ITI"
" who are not SECE authors")
# the most papers of any other Greek partner, by period (both bases)
other_gr_rows = gr_full[~gr_full["org"].isin([ITI, CERTH])]
other_gr = other_gr_rows.groupby(["period", "org"])["eid"].nunique().groupby(level="period").max()
other_gr_ext = (other_gr_rows[other_gr_rows["external"]]
.groupby(["period", "org"])["eid"].nunique().groupby(level="period").max())
papers_gr_partner = gr_links["eid"].nunique()
n_thess = gr_links.loc[gr_links["org"].map(orgs["city"]).eq("Thessaloniki"), "eid"].nunique()
share_thess = n_thess / papers_gr_partner
# ------------------------------------------------------------------ breadth
first_seen = links.groupby("org")["year"].min()
breadth = (pd.DataFrame({"partners": links.groupby("year")["org"].nunique(),
"first_time": first_seen.value_counts()})
.reindex(range(FIRST_YEAR, PARTIAL + 1)).fillna(0).astype(int))
breadth["returning"] = breadth["partners"] - breadth["first_time"]
breadth["papers"] = pubs.groupby("year").size().reindex(breadth.index, fill_value=0)
breadth["partner_papers"] = links.groupby("year")["eid"].nunique().reindex(breadth.index, fill_value=0)
breadth_period = breadth.loc[:LAST_FULL].groupby(period_of).mean()
avg_partners, avg_first, avg_papers, avg_pp = (breadth_period[c] for c in
("partners", "first_time", "papers", "partner_papers"))
partners_x = avg_partners[P_RECENT] / avg_partners[P_EARLY]
papers_x = avg_papers[P_RECENT] / avg_papers[P_EARLY]
pp_x = avg_pp[P_RECENT] / avg_pp[P_EARLY] # papers with a matched partner institution
per_pp = avg_partners / avg_pp # distinct partners a year per paper with a partner
pace = partners_x / pp_x # equals per_pp[P_RECENT] / per_pp[P_EARLY]
pace_word = "in line with" if abs(pace - 1) < 0.1 else "ahead of" if pace > 1 else "behind"
ratio_text = "changed little, from" if pace_word == "in line with" else "rose from" if pace > 1 else "fell from"
first_change = avg_first[P_RECENT] / avg_first[P_PREV] - 1
first_verb = "grew" if first_change > 0 else "eased" if first_change > -0.1 else "slowed"
first_best_year = int(breadth.loc[:LAST_FULL, "first_time"].idxmax()) # most first-time partners, full years
first_best = int(breadth.at[first_best_year, "first_time"])
# ------------------------------------------------------------------ partners per paper
BINS = ["None", "1", "2", "3", "4 or more"]
n_org = full["n_partner_orgs"]
dist = (pd.crosstab(full["period"], n_org.clip(upper=4).map(dict(enumerate(BINS))))
.reindex(index=CHART_PERIODS, columns=BINS, fill_value=0))
dist_share = dist.div(dist.sum(axis=1), axis=0)
multi_partner = n_org.ge(2).groupby(full["period"]).mean()
no_partner = n_org.eq(0).groupby(full["period"]).mean()
mean_partners = n_org.groupby(full["period"]).mean()
max_partners = int(pubs["n_partner_orgs"].max()) # all years, the partial one too: the text names the year
max_years = pubs.loc[pubs["n_partner_orgs"].eq(max_partners), "year"]
max_partners_on = (f"a paper of {max_years.iloc[0]}" if len(max_years) == 1 else
f"{len(max_years)} papers of " + and_join([str(y) for y in sorted(max_years.unique())]))
collab = pubs["collab_type"].ne("single-institution")
n_collab = int(collab.sum())
n_collab_nomatch = int((collab & pubs["n_partner_orgs"].eq(0)).sum())
# ------------------------------------------------------------------ caveats
coverage = meta["matching"]
cov_all = coverage["all"]["occurrence_matched_share"]
cov_ext = coverage["excluding_auth"]["occurrence_matched_share"]
cov_ext_unique = coverage["excluding_auth"]["unique_matched_share"]
outside_auth = usable[~usable["is_auth"]] # affiliation occurrences outside AUTH
cov_period = outside_auth["ror_id"].notna().groupby(outside_auth["year"].map(period_of)).mean()
# SECE authors' own second affiliations, measured (metadata.json holds the same counts)
own_rows = usable[usable["own"]]
own_cc = own_rows["country_code"]
n_own_occ, n_own_papers = len(own_rows), own_rows["eid"].nunique()
n_own_abroad, n_own_gr, n_own_nocc = (int(m.sum()) for m in (own_cc.notna() & own_cc.ne(HOME), own_cc.eq(HOME),
own_cc.isna()))
n_no_holder = int(usable["held_only_by_sece"].isna().sum()) # listed by no author: counted as external
holders = meta["affiliation_holders"]
assert (holders["sece_only_occurrences"], holders["papers_with_sece_only"], holders["occurrences_no_holder"]) \
== (n_own_occ, n_own_papers, n_no_holder), "SECE authors' own second affiliations differ from metadata.json"
assert holders["collab_type_external"] == type_all_ext.to_dict(), "external-partner types differ from metadata.json"
holder_text = ("every affiliation on the records is listed by at least one of their authors" if n_no_holder == 0
else f"the {dp.fmt_int(n_no_holder)} affiliations that no author lists count as external")
edu_recent_ext = (links.loc[links["period"].eq(P_RECENT) & links["external"] & links["sector"].eq("education"),
"eid"].nunique() / period_n[P_RECENT])
mean_partners_ext = full["n_partner_orgs_external"].groupby(full["period"]).mean()
def partner_bars(df: pd.DataFrame, value: str, own: str, value_title: str,
other: str, other_own: str, other_title: str) -> go.Figure:
"""Horizontal bars of partner institutions (largest on top), coloured by sector.
The hatched end of a bar counts the papers that link to the institution only through SECE
authors' own second affiliations (column *own*), drawn only where that count may be shown
(column *own*_shown); an asterisk marks the institutions where these are at least half of the
papers. *other* / *other_own*: the same counts for the other period (hover).
"""
rows = df.iloc[::-1].reset_index(drop=True) # plotly draws the first category at the bottom
star = np.where(2 * rows[own] >= rows[value], "*", "")
rows["label"] = [dp.wrap_label(f"{n}{s} · {c}", 46) for n, s, c in zip(rows["name"], star, rows["country_name"])]
rows["place"] = [f"{city}, {country}" if isinstance(city, str) else country
for city, country in zip(rows["city"], rows["country_name"])]
# hover values as text, so that a count that may not be shown reads "not shown"
for col in (value, other):
rows[f"{col}_text"] = rows[col].map(dp.fmt_int)
not_shown = "not shown (small groups)"
for col in (own, other_own):
rows[f"{col}_text"] = [dp.fmt_int(n) if ok else not_shown for n, ok in zip(rows[col], rows[f"{col}_shown"])]
custom = rows[["name", "place", "sector", f"{value}_text", f"{own}_text", f"{other}_text", f"{other_own}_text",
"first_year"]].to_numpy()
hover = ("<b>%{customdata[0]}</b><br>%{customdata[1]}<br>%{customdata[2]}"
f"<br>{value_title}: %{{customdata[3]}}<br>of which {OWN_TEXT}: %{{customdata[4]}}"
f"<br>{other_title}: %{{customdata[5]}}<br>of which {OWN_TEXT}: %{{customdata[6]}}"
"<br>First joint paper: %{customdata[7]}<extra></extra>")
fig = go.Figure()
for sector, color in SECTOR_COLORS.items():
part = rows["sector"].eq(sector).to_numpy()
if not part.any():
continue
fig.add_bar(x=rows.loc[part, value], y=rows.loc[part, "label"], orientation="h", name=sector,
marker_color=color, customdata=custom[part], hovertemplate=hover,
texttemplate="%{x:,}", textposition="outside")
# papers only through SECE authors' own second affiliations: a lighter, hatched end drawn over the
# bar, where the count may be shown
part = (rows[own].gt(0) & rows[f"{own}_shown"]).to_numpy()
fig.add_bar(x=rows.loc[part, own], base=(rows[value] - rows[own])[part], y=rows.loc[part, "label"],
orientation="h", name=OWN_LABEL, legendgroup="own", showlegend=False,
marker=dict(color="rgba(255,255,255,0.35)", pattern=OWN_PATTERN),
customdata=custom[part], hovertemplate=hover)
fig.add_bar(x=[None], y=[None], orientation="h", name=OWN_LABEL, legendgroup="own", hoverinfo="skip",
marker=dict(color=dp.OTHER_COLOR, pattern=OWN_PATTERN)) # legend key only
fig.update_layout(height=dp.fig_height(len(rows), per_row=30), barmode="overlay", bargap=0.3)
fig.update_xaxes(title_text=value_title, showgrid=True, showline=False, zeroline=False,
range=[0, float(rows[value].max()) * 1.15])
fig.update_yaxes(categoryorder="array", categoryarray=list(rows["label"]), showgrid=False,
showline=True)
return fig
# The text describes these patterns of the current data: fail loudly if new data change them.
assert periods.bounds(P_RECENT)[0] - EARLY_FIRST == 20, "text: P_EARLY to P_RECENT are twenty years"
assert multi[P_RECENT] > 0.5, "text: working with other institutions has become the norm"
assert intl[P_RECENT] > intl[P_EARLY] and single[P_RECENT] < single[P_EARLY], "text: intl up, single down"
assert fold_text(intl_ext[P_RECENT] / intl_ext[P_EARLY]) == intl_fold, \
"text: the external-partner share grew by the same factor in words (key findings)"
assert DECADE_2000S and all(certh_iti[p] > other_gr[p] and certh_iti_ext[p] > other_gr_ext[p] for p in DECADE_2000S), \
"text: CERTH with ITI was the main Greek partner in the 2000s, also counting only co-authors who are not SECE authors"
assert certh_iti_ext.idxmax() == certh_iti_peak, "text: the CERTH with ITI peak is the same on both bases"
assert (certh_iti - certh_iti_ext)[certh_iti_peak] > (certh_iti - certh_iti_ext)[P_RECENT] \
and certh_iti_ext[P_RECENT] < certh_iti_ext[certh_iti_peak], \
"text: part of the CERTH decline comes from fewer papers linked only through SECE authors' own second " \
"affiliations"
# Small groups: the text quotes these counts, or counts from which they follow (P_RECENT: ci_recent_tail)
assert certh_iti_shown.get(certh_iti_peak, True), \
"text: the CERTH with ITI counts of both bases in the peak period rest on enough SECE authors to be shown"
assert by_ext["only_shown"].head(3).all(), "text: the external-partner ranking gives counts that may be shown"
assert len(most_own) >= 3, "text: three partners with a count that may be shown"
assert abs(cov_period[P_RECENT] - cov_period[P_EARLY]) < 0.03 \
and cov_period.reindex(PERIODS[:PERIODS.index(P_EARLY)]).max() < min(cov_period[P_EARLY], cov_period[P_RECENT]), \
"text: similar matching coverage in the compared periods, lower in every period before them"
assert (nat_gain_pp >= 0) == (nat_gain_ext_pp >= 0), "text: the national share moved the same way on both bases"
assert intl_gain_pp > 2 * abs(nat_gain_pp) and intl_gain_ext_pp > 2 * abs(nat_gain_ext_pp), \
"text: the shift went mostly (or entirely) to international papers, on both bases"
assert gap_pp[P_RECENT] > gap_pp[P_EARLY] > 0, "text: the gap between the two shares grew"
assert abs(sec_share.loc[P_RECENT, "education"] - edu_recent_ext) < 0.05 \
and abs(mean_partners[P_RECENT] - mean_partners_ext[P_RECENT]) < 0.2, "text: other figures change little"
assert greek_any[P_RECENT] > greek_any[P_EARLY], "text: the share with a Greek partner rose"
assert certh_iti_papers > best_other, "text: CERTH with ITI on more papers than any other partner"
assert by_all.loc[0, "ror_id"] not in (ITI, CERTH) and by_all.loc[1, "ror_id"] == ITI \
and by_all.loc[0, "papers"] > by_all.loc[1, "papers"], "text: the list is led by another institution, ahead of ITI"
assert sec_share.loc[P_RECENT].idxmax() == "education", "text: universities are the main partner sector"
assert (sec_share.loc[P_RECENT, "education"] - sec_share.loc[P_EARLY, "education"]
> multi[P_RECENT] - multi[P_EARLY]), "text: universities account for the growth in collaboration"
assert sec_share.loc[P_RECENT].drop("education").max() < 0.1, "text: other sectors on small shares"
assert np_iti[P_EARLY] / np_all[P_EARLY] > 0.5 > np_iti[P_RECENT] / np_all[P_RECENT], \
"text: ITI is on most papers with a nonprofit partner in P_EARLY, but not in P_RECENT"
assert ind.loc[P_RECENT, "company_ror"] < 0.05 and ind.loc[P_RECENT, "company_any"] < 0.15, \
"text: industry co-authorship is small; few papers with a company listed in ROR"
assert ind.loc[P_RECENT, "company_text_only"] > ind.loc[P_RECENT, "company_ror"] \
and ind.loc[P_RECENT, "company_any"] > ind.loc[P_EARLY, "company_any"] \
and (ind.loc[P_RECENT, "company_text_only"] - ind.loc[P_EARLY, "company_text_only"]
> ind.loc[P_RECENT, "company_ror"] - ind.loc[P_EARLY, "company_ror"]), \
"text: industry co-authorship rose, mostly with companies outside ROR"
assert ror_listed[P_RECENT] < ror_listed[P_EARLY] - 0.1, \
"text: ROR covers a clearly smaller part of the company partners in the recent period"
assert certh_iti_peak != P_RECENT and certh_iti[P_RECENT] < certh_iti[certh_iti_peak], "text: CERTH+ITI fell"
assert all(gr_tab.loc[o, P_RECENT] > gr_tab.loc[o, P_CMP] for o in gr_lead), "text: Greek leaders grew"
assert share_thess > 0.3, "text: local partners weigh heavily"
assert gr_tab.loc[IHU, P_RECENT] > gr_tab.loc[ATEI, P_RECENT] and gr_tab.loc[ATEI, P_RECENT] < gr_tab.loc[ATEI, P_PREV], \
"text: papers with the Alexander TEI give way to papers with the International Hellenic University"
assert partners_x > 1 and papers_x > 1, "text: the partner network widened; total output grew"
assert share_oneoff > 0.3, "text: the partner network has a long tail"
assert multi_partner[P_RECENT] > multi_partner[P_EARLY] and no_partner[P_RECENT] < no_partner[P_EARLY], \
"text: more papers with several partners, fewer without a matched partner"
assert all(full.loc[n_org.eq(0) & full["period"].eq(p), "collab_type"].eq("single-institution").mean() > 0.5
for p in CHART_PERIODS), "caption: papers without a matched partner are mostly single-institution papers"
assert top_all["name"].is_unique and top_recent["name"].is_unique, "partner labels must be unique"
assert all(separated(df, col, k) for df, col, k in (
(by_all, "papers", 3), (abroad, "papers", 3), (by_ext, "papers_ext", 1), (by_ext, "papers_ext", 3),
(by_recent, "recent", 4), (by_recent_ext, "recent_ext", 4), (top_companies, "papers", 3),
(gr_recent, P_RECENT, 2))), "text: the partners named first in a ranking rank above the next one"
assert certh_iti.eq(certh_iti.max()).sum() == 1 and breadth.loc[:LAST_FULL, "first_time"].eq(first_best).sum() == 1, \
"text: one period with the most CERTH with ITI papers and one full year with the most first-time partners"
# Small groups, recomputed: every number of papers only through SECE authors' own second affiliations that the
# page shows, and every one a reader can work out from those shown (the difference between the two bases of the
# same group, a total minus its shown parts), is zero or rests on at least MIN_HOLDERS distinct SECE authors; a
# count that is not shown but described in words ('most', an asterisk) leaves at least two values open.
INTL = CELL["international"]
own_link_rows = links[~links["external"]] # (paper, institution) links only through own ones
org_checks = []
for org, rows in own_link_rows.groupby("org"): # the hovers and the text, all years and P_RECENT
only_ok, recent_ok = by_id.at[org, "only_shown"], by_id.at[org, "recent_only_shown"]
recent = rows["period"].eq(P_RECENT)
org_checks.append((not only_ok or links_safe(rows)) and (not recent_ok or links_safe(rows[recent]))
and (not (only_ok and recent_ok) or links_safe(rows[~recent])))
edu_recent = links[links["period"].eq(P_RECENT) & links["sector"].eq("education")]
own_only_orgs = set(partners.loc[partners["papers_ext"].eq(0), "ror_id"])
abroad_own_only = set(partners.loc[is_abroad, "ror_id"]) - abroad_ids_ext
own_place = pd.Series(np.select([PLACE["abroad"], in_greece], ["abroad", "greece"], "none"), index=own_holders.index)
place_held = own_holders.groupby(own_place)["author_id"].nunique()
ext_best = int(intl_year_ext.loc[:LAST_FULL].idxmax()) # the year latest_text(intl_year_ext) names
# the values the text gives on both bases (the chart and the table follow split_shown and cell_shown): all years for
# every type and change, the three types of P_EARLY and P_RECENT, LAST_FULL and the year of the highest
# external-partner share
quoted = ([(ALL_YEARS, k) for k in (*COLLAB, *CAUSE)] + [(years_of(p), t) for p in (P_EARLY, P_RECENT) for t in COLLAB]
+ [([LAST_FULL], "international"), ([ext_best], "international")])
def vague(rows: pd.DataFrame, col: str, own: str, text: bool = True) -> bool:
"""Counts not shown that the text calls 'most' (never 'half', which would give the number) or that an
asterisk marks as at least half leave at least two values open."""
words = rows[rows[own].mul(2).ge(rows[col]) & rows[col].gt(0) & ~rows[f"{own}_shown"]]
return bool((words[own].mul(2).gt(words[col]) & words[col].ge(3)).all() if text else words[col].ge(2).all())
def ext_words_vague(m: int, n: int) -> bool:
"""The words of ext_words for m (at least 1) of n papers leave at least two values of m open."""
lo, hi = {"nearly all": (1, n // 10), "most": (n // 10 + 1, (n - 1) // 2),
"at most half": ((n + 1) // 2, n)}[ext_words(m, n)]
return hi > lo
small_groups = {
"annual chart: each split year": all(safe(*changed([y], INTL)) for y in CHART_YEARS if split_shown[y]),
"annual chart: a period's difference minus its split years": all(
safe(*changed([y for y in years_of(p) if not split_shown.get(y, False)], INTL))
for p in PERIODS if cell_shown.at[p, "international"]),
"table: each external-partner share shown": all(
safe(*changed(years_of(p), CELL[t])) for p in PERIODS for t in COLLAB if cell_shown.at[p, t]),
"table: no period hides only one of its three shares": bool((~cell_shown).sum(axis=1).ne(1).all()),
"text: all years minus the periods and years shown": all(
safe(*changed(unshown_years(t), CELL[t])) for t in COLLAB),
"text: the same without the partial year (in case other pages show it)": all(
safe(*changed([y for y in unshown_years(t) if y != PARTIAL], CELL[t])) for t in COLLAB),
"text: the type changes of all years": all(
safe(*changed(ALL_YEARS, parts)) for parts in [*CAUSE.values(), *CELL.values()]),
"text: the periods and years quoted on both bases": bool(
cell_shown.loc[[P_EARLY, P_RECENT]].to_numpy().all() and split_shown[LAST_FULL] and split_shown.get(ext_best)),
"partners: each count shown, and all years minus P_RECENT": all(org_checks),
"partners: the external-partner counts quoted": bool(by_ext["only_shown"].head(3).all()),
"partners: counts described in words": all(vague(*args) for args in (
(abroad.head(3), "papers", "only"), (top_recent.head(4), "recent", "recent_only"),
(top_companies.head(3), "papers", "only"), (mostly_hidden, "papers", "only"),
(top_all, "papers", "only", False), (top_recent, "recent", "recent_only", False))),
"CERTH with ITI: the counts of both bases quoted": links_safe(ci_own[ci_own["period"].eq(certh_iti_peak)]) and (
links_safe(ci_own[ci_own["period"].eq(P_RECENT)]) if certh_iti_shown.get(P_RECENT, True)
else ext_words_vague(ci_recent_own, int(certh_iti[P_RECENT]))),
"notes: university partners in P_RECENT on both bases": links_safe(
edu_recent[~edu_recent["eid"].isin(set(edu_recent.loc[edu_recent["external"], "eid"]))]),
"notes: partner institutions per paper in P_RECENT on both bases": links_safe(
own_link_rows[own_link_rows["period"].eq(P_RECENT)]),
"text: institutions only through own affiliations": safe(
len(own_only_orgs), count_holders(own_link_rows[own_link_rows["org"].isin(own_only_orgs)])) and safe(
len(abroad_own_only), own_holders.loc[PLACE["abroad"] & own_holders["org"].isin(abroad_own_only),
"author_id"].nunique()),
"notes: own affiliations by place": safe(n_own_occ, own_holders["author_id"].nunique()) and all(
safe(n, place_held.get(k, 0)) for k, n in (("abroad", n_own_abroad), ("greece", n_own_gr),
("none", n_own_nocc))),
"site: the values the text gives on both bases are values the site's rule publishes": all(
rule.is_published(years, kind) for years, kind in quoted),
"site: the rule's own checks, and its audit of the values of all pages together": all(rule.checks().values()),
}
assert all(small_groups.values()), f"small groups: {[k for k, ok in small_groups.items() if not ok]}"