import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from sece_stats import metrics, periods
pubs = data.load_publications()
pub_aff = data.load_publication_affiliations()
FIRST_YEAR = int(pubs["year"].min())
LAST_FULL = periods.LAST_FULL # latest full year (PARTIAL - 1)
START = 1995 # first year of the per-year share and team-size charts (small counts before)
AS_OF_TEXT = f"{AS_OF.day} {AS_OF:%B %Y}"
NUMBER_WORDS = ("zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen "
"fifteen sixteen seventeen eighteen nineteen twenty").split()
def join_and(items: list[str]) -> str:
"""'a', 'a and b', 'a, b and c'."""
return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
# Five-year periods end with the latest full year (sece_stats.periods) and move with every export;
# the partial year has a label of its own. The names say what each period is in the text.
PERIODS = periods.periods(FIRST_YEAR) # the full-year periods, oldest first
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
P_LONG = periods.period_of(LAST_FULL - 15) # fifteen years earlier: full and fractional counts compared
P_BASE = periods.period_of(LAST_FULL - 20) # twenty years earlier: baseline of team size and SECE share
P_EARLY = next(p for p in PERIODS if periods.bounds(p)[0] >= START) # the early output: first period of the charts
# the SECE share in single-institution publications is compared over the periods from 1990 on (few before)
P_SI_FROM = next(p for p in PERIODS if periods.bounds(p)[0] >= 1990)
# Derived columns ------------------------------------------------------------------
type_counts = pubs["doc_type"].value_counts()
MAIN_TYPES = type_counts.index[:4].tolist() # the four largest Scopus document types
TYPE_ORDER = MAIN_TYPES + ["Other"]
pubs["type_group"] = pubs["doc_type"].where(pubs["doc_type"].isin(MAIN_TYPES), "Other")
pubs["period"] = pubs["year"].map(lambda y: periods.period_of(y, first_year=FIRST_YEAR))
pubs["sece_share"] = metrics.safe_share(pubs["n_sece_authors"], pubs["n_authors"])
full = pubs[pubs["year"] < PARTIAL] # full years only: trends, shares, averages
SK = dp.CATEGORY_COLORS["source_kind"]
TYPE_COLORS = dp.color_map(
TYPE_ORDER,
fixed={"Article": SK["journal"], "Conference paper": SK["conference"], "Book chapter": SK["book"]},
)
other_types = sorted(type_counts.iloc[4:].items(), key=lambda kv: (-kv[1], kv[0]))
other_types_text = join_and([f"{t} ({n})" for t, n in other_types])
# document types of each source type, as listed in the caption of the source-type chart
KIND_TYPES = {"journal": {"Article", "Review", "Letter", "Editorial", "Note", "Erratum", "Data paper"},
"conference": {"Conference paper"}, "book": {"Book", "Book chapter"}}
# Annual output ----------------------------------------------------------------------
years = pd.RangeIndex(FIRST_YEAR, PARTIAL + 1, name="year")
per_year = pubs.groupby("year").size().reindex(years, fill_value=0) # years without records = 0
per_year_full = per_year.loc[:LAST_FULL]
ma5 = per_year_full.rolling(5, min_periods=5).mean().dropna() # trailing 5-year mean
n_pubs = len(pubs)
n_partial = int(per_year.loc[PARTIAL])
zero_years = [int(y) for y in per_year_full.index[per_year_full.eq(0)]]
ranked = per_year_full.sort_values(ascending=False, kind="mergesort")
best_year, second_year, third_year = (int(y) for y in ranked.index[:3])
best_n, second_n, third_n = (int(v) for v in ranked.iloc[:3])
last_n = int(per_year_full.loc[LAST_FULL])
n_2000 = int(per_year.loc[2000])
max_80s = int(per_year.loc[:1989].max())
max_pre_start = int(per_year.loc[:START - 1].max())
share_since_2010 = pubs["year"].ge(2010).mean() # all records, the partial year included
ma_last = ma5.loc[LAST_FULL] # the mean of P_RECENT
decade_rows = []
for d in range(FIRST_YEAR // 10 * 10, LAST_FULL + 1, 10):
y0, y1 = max(d, FIRST_YEAR), min(d + 9, LAST_FULL)
n = int(per_year_full.loc[y0:y1].sum())
decade_rows.append({"decade": f"{d}s", "years": f"{y0}–{y1}" if y1 > y0 else str(y0),
"n_years": y1 - y0 + 1, "papers": n, "per_year": n / (y1 - y0 + 1)})
decades = pd.DataFrame(decade_rows)
decades["change"] = decades["per_year"].pct_change()
dec = decades.set_index("decade")
DEC_PREV, DEC_LAST = decades["decade"].iloc[-2:] # the decade before and the latest decade
# Growth -----------------------------------------------------------------------------
def trend_growth(series: pd.Series) -> tuple[float, float, float]:
"""Annual growth implied by a least-squares fit of ln(count) on year, with its 95% confidence
interval (t distribution with n - 2 degrees of freedom on the slope's standard error)."""
x = series.index.to_numpy(dtype=float)
coef, cov = np.polyfit(x, np.log(series.to_numpy(dtype=float)), 1, cov=True)
half = stats.t.ppf(0.975, len(x) - 2) * np.sqrt(cov[0, 0])
return tuple(float(np.expm1(v)) for v in (coef[0], coef[0] - half, coef[0] + half))
# Growth since three fixed calendar years (an analysis choice: since 2000, 2010 and 2015), each span
# ending with the latest full year, so the spans grow by a year with every export.
GROWTH_STARTS = (2000, 2010, 2015)
growth = pd.DataFrame([
{"span": f"{s}–{LAST_FULL}", "start_n": int(per_year_full.loc[s]), "end_n": last_n,
"cagr": metrics.cagr_between(per_year_full, s, LAST_FULL),
**dict(zip(("trend", "trend_lo", "trend_hi"), trend_growth(per_year_full.loc[s:LAST_FULL])))}
for s in GROWTH_STARTS
])
growth["trend_ci"] = [f"{dp.fmt_pct(lo)[:-1]}–{dp.fmt_pct(hi)}"
for lo, hi in zip(growth["trend_lo"], growth["trend_hi"])]
span = dict(zip(GROWTH_STARTS, growth["span"]))
cagr = dict(zip(GROWTH_STARTS, growth["cagr"]))
trend = dict(zip(GROWTH_STARTS, growth["trend"]))
trend_ci = dict(zip(GROWTH_STARTS, growth["trend_ci"])) # interval text, 'lo–hi%'
trend_lo = dict(zip(GROWTH_STARTS, growth["trend_lo"]))
trend_hi = dict(zip(GROWTH_STARTS, growth["trend_hi"]))
# the shortest span: its length in words, and how clearly its trend differs from no growth
G_SHORT = GROWTH_STARTS[-1]
n_short_text = NUMBER_WORDS[LAST_FULL - G_SHORT + 1].capitalize()
if trend_lo[G_SHORT] <= 0:
trend_short_zero, trend_short_link = "includes zero growth", "and"
elif trend_lo[G_SHORT] < 0.01:
trend_short_zero, trend_short_link = "only just excludes zero growth", "and"
else: # clearly above zero: a contrast with the wide interval, not one more caveat
trend_short_zero, trend_short_link = "excludes zero growth", "but still"
trend_short_note = f"an interval that {trend_short_zero}"
trend_short_clause = f"{trend_short_link} {trend_short_zero}" # follows "the interval is wide"
period_n = full.groupby("period").size().reindex(PERIODS)
period_change = period_n.pct_change() # vs the previous five-year period
recent_n, prev_n = int(period_n[P_RECENT]), int(period_n[P_PREV])
growth_recent = recent_n / prev_n - 1
# the period of the slowest growth since the baseline, and the periods either side of it
P_SLOW = period_change.loc[P_BASE:].idxmin()
assert P_SLOW != P_RECENT, "text: growth picked up again after its slowest period"
P_BEFORE_SLOW, P_AFTER_SLOW = (PERIODS[PERIODS.index(P_SLOW) + k] for k in (-1, 1))
# Document types and source types -------------------------------------------------------
type_n = pd.crosstab(full["period"], full["type_group"])
type_share = pd.crosstab(full["period"], full["type_group"], normalize="index")
art = type_share["Article"]
confp = type_share["Conference paper"]
is_review = full["doc_type"].eq("Review")
review_n = is_review.groupby(full["period"]).sum()
review_share = is_review.groupby(full["period"]).mean()
KINDS = [k for k in data.SOURCE_KIND_ORDER if pubs["source_kind"].eq(k).any()]
kind_year = pd.crosstab(full["year"], full["source_kind"]).reindex(columns=KINDS, fill_value=0)
kind_year_share = kind_year.div(kind_year.sum(axis=1), axis=0)
jour = pd.crosstab(full["period"], full["source_kind"], normalize="index")["journal"]
P_LOW = jour.loc[P_EARLY:].idxmin() # the lowest journal share since the early output
jour_year = kind_year_share["journal"]
conf_year = kind_year["conference"]
conf_best_year, conf_best_n = int(conf_year.idxmax()), int(conf_year.max()) # record year of conference papers
book_share = pubs["source_kind"].eq("book").mean()
n_book = int(pubs["source_kind"].eq("book").sum())
# Team size --------------------------------------------------------------------------
team_period = full.groupby("period")["n_authors"].agg(
mean="mean", median="median",
six_plus=lambda s: s.ge(6).mean(), single=lambda s: s.eq(1).mean())
team_kind = full.groupby(["period", "source_kind"])["n_authors"].mean().unstack()
team_year = (full[full["year"] >= START].groupby("year")["n_authors"]
.agg(n="size", mean="mean", median="median",
q1=lambda s: s.quantile(0.25), q3=lambda s: s.quantile(0.75)))
mean_base, mean_recent = team_period.loc[P_BASE, "mean"], team_period.loc[P_RECENT, "mean"]
# Full and fractional counts ------------------------------------------------------------
counts_period = full.groupby("period").agg(
full_n=("eid", "size"), frac_n=("sece_share", "sum"), sece_share=("sece_share", "mean"))
frac_recent, frac_prev, frac_long = (counts_period.loc[p, "frac_n"] for p in (P_RECENT, P_PREV, P_LONG))
frac_growth = frac_recent / frac_prev - 1
full_growth_long = recent_n / period_n[P_LONG] - 1
frac_growth_long = frac_recent / frac_long - 1
is_single = full["collab_type"].eq("single-institution")
single_inst_share = full[is_single].groupby("period")["sece_share"].mean().loc[P_SI_FROM:]
single_inst_weight = is_single.groupby(full["period"]).mean() # share of single-institution publications
# Notes ------------------------------------------------------------------------------
n_explicit = int(pubs["has_sece_affiliation"].sum())
# SECE strings that name another AUTH unit (Physics, Journalism, the medical school) and no electrical
# or computer engineering department: the same keyword check as on Methodology & data.
OTHER_UNIT = r"physic|journalism|dermatolog|school of medicine|medical school"
ECE_DEPT = (r"electrical|electr\.?\s*,?\s*eng|elec\.?\s*comp\.?\s*eng"
r"|(?:electronics?|electrical)\s+(?:and|&)\s+comp\w*\.?\s*eng|computer\s+eng|\bECE\b")
sece_occ = pub_aff[pub_aff["is_sece"]].assign(
other_unit=lambda d: d["affiliation"].str.contains(OTHER_UNIT, case=False)
& ~d["affiliation"].str.contains(ECE_DEPT, case=False))
other_unit_rec = sece_occ.groupby("eid")["other_unit"].all() # records with only such strings
n_other_unit = int(other_unit_rec.sum())
n_confirmed = int(sece_occ.loc[~sece_occ["other_unit"], "eid"].nunique())
assert n_confirmed == n_explicit - n_other_unit, "SECE records: explicit = confirmed + other AUTH units"
other_unit_physics = (sece_occ.loc[sece_occ["eid"].isin(other_unit_rec.index[other_unit_rec]), "affiliation"]
.str.contains("physic", case=False).any())
in_press = (pubs.loc[pubs["pub_stage"].eq("Article in press"), "year"].value_counts()
.sort_index(ascending=False))
n_in_press = int(in_press.sum())
in_press_text = join_and([f"{dp.fmt_int(n)} dated {y}" for y, n in in_press.items()])
share_english = pubs["language"].eq("English").mean()
other_languages = pubs.loc[pubs["language"].ne("English"), "language"].value_counts()
other_languages_text = join_and([f"{lang} ({n})" for lang, n in other_languages.items()])
partial_types = pubs.loc[pubs["year"].eq(PARTIAL), "doc_type"].value_counts()
# Short names for the numbers quoted in the text ------------------------------------------
pyr_dec_prev, pyr_dec_last = dec.loc[DEC_PREV, "per_year"], dec.loc[DEC_LAST, "per_year"]
chg_dec_last, n_dec_last = dec.loc[DEC_LAST, "change"], int(dec.loc[DEC_LAST, "papers"])
years_dec_last = dec.loc[DEC_LAST, "years"]
art_early, art_low, art_recent = art[P_EARLY], art[P_LOW], art[P_RECENT]
conf_early, conf_low, conf_recent = confp[P_EARLY], confp[P_LOW], confp[P_RECENT]
jour_early, jour_low, jour_recent = jour[P_EARLY], jour[P_LOW], jour[P_RECENT]
# the COVID-19 pandemic (historical years): conference papers dipped in 2020 and 2021
jour_2020, jour_last = jour_year[2020], jour_year[LAST_FULL]
conf_2019, conf_2020, conf_2021, conf_last = (int(conf_year[y]) for y in (2019, 2020, 2021, LAST_FULL))
rev_recent_n, rev_prev_n = int(review_n[P_RECENT]), int(review_n[P_PREV])
rev_recent = review_share[P_RECENT]
med_base, med_recent = team_period.loc[P_BASE, "median"], team_period.loc[P_RECENT, "median"]
med_last = team_year.loc[LAST_FULL, "median"]
six_base, six_recent = team_period.loc[P_BASE, "six_plus"], team_period.loc[P_RECENT, "six_plus"]
single_base, single_recent = team_period.loc[P_BASE, "single"], team_period.loc[P_RECENT, "single"]
jmean_base, jmean_recent = team_kind.loc[P_BASE, "journal"], team_kind.loc[P_RECENT, "journal"]
cmean_base, cmean_recent = team_kind.loc[P_BASE, "conference"], team_kind.loc[P_RECENT, "conference"]
dshare_base = counts_period.loc[P_BASE, "sece_share"]
dshare_recent = counts_period.loc[P_RECENT, "sece_share"]
si_min, si_max = single_inst_share.min(), single_inst_share.max()
n_partial_art = int(partial_types.get("Article", 0))
n_partial_conf = int(partial_types.get("Conference paper", 0))
zero_years_text = join_and([str(y) for y in zero_years]) if zero_years else ""
# The text describes these patterns of the current snapshot: fail loudly if new data changes them.
assert FIRST_YEAR == 1981, "description: records since 1981"
assert zero_years, "text: some early years have no records"
assert max_80s < n_2000 < best_n, "text: annual output grew from the 1980s to 2000 and to the record"
assert best_year == LAST_FULL, "text: the latest full year is the record year"
assert ma5.idxmax() == LAST_FULL, "text: the five-year average reached its highest in the latest period"
assert decades["change"].iloc[1:].gt(0).all(), "text: mean annual output rose in every decade"
assert dec.loc[DEC_LAST, "n_years"] < 10, "text: the latest decade is not complete yet ('so far')"
assert all(cagr[s] > 0 and trend[s] > 0 for s in GROWTH_STARTS), "text: output grew over every span"
assert all(trend[s] < cagr[s] for s in (2010, 2015)), "text: trend growth below end-point CAGR"
assert (growth["trend_lo"] < growth["trend"]).all() and (growth["trend"] < growth["trend_hi"]).all(), \
"the interval brackets the trend"
assert trend_hi[G_SHORT] - trend_lo[G_SHORT] > trend[G_SHORT], "text: the shortest span's interval is wide"
assert period_change[P_BEFORE_SLOW] > period_change[P_SLOW] > 0 \
and period_change[P_AFTER_SLOW] > period_change[P_SLOW], "text: growth rose, slowed, then picked up again"
assert growth_recent > 0 and 0 < frac_growth < growth_recent, "text: fractional counts grew more slowly"
assert 0 < frac_growth_long < full_growth_long, "text: fractional counts grew more slowly over fifteen years"
assert art_early > 0.5, "text: articles dominated the early output"
assert confp.loc[P_EARLY:].idxmax() == P_LOW and conf_low > conf_early, \
"text: conference share rose to its peak in the period of the lowest journal share"
assert type_n.loc[P_LOW, "Conference paper"] > type_n.loc[P_LOW, "Article"], \
"text: conference papers outnumbered articles"
assert art_recent > art_low and conf_recent < conf_low and jour_recent > jour_low, \
"text: journals have since regained ground"
assert rev_recent_n > rev_prev_n and rev_recent < 0.05, "text: reviews are a small type but more common"
assert jour_year.loc[2020:LAST_FULL].idxmax() == 2020 and jour_last < jour_2020, \
"text: the journal share has eased since 2020"
assert max(conf_2020, conf_2021) < conf_2019 < conf_year.loc[2022:LAST_FULL].min(), \
"text: conference papers dipped in 2020 and 2021 and recovered"
assert conf_best_year > 2021, "text: conference papers reached their record after the pandemic"
assert all(set(pubs.loc[pubs["source_kind"].eq(k), "doc_type"]) <= KIND_TYPES[k] for k in KINDS), \
"caption: document types of each source type"
assert book_share < 0.05, "text: books and book chapters remain marginal"
assert team_period.loc[P_EARLY:, "mean"].is_monotonic_increasing, "text: teams have grown steadily"
assert med_recent > med_base and six_recent > six_base and single_recent < single_base, \
"text: larger teams, fewer single-author publications"
assert jmean_recent > jmean_base and cmean_recent > cmean_base, "text: teams grew in both kinds"
assert dshare_recent < dshare_base and si_max - si_min < dshare_base - dshare_recent, \
"text: the SECE share fell overall but stayed level in single-institution publications"
assert single_inst_weight[P_RECENT] < single_inst_weight[P_BASE], \
"text: growing weight of publications with external co-authors"
assert other_unit_physics, "text: the other AUTH units include the Department of Physics"
assert n_partial_conf < conf_last / 2, "text: the partial year's conference papers are mostly not indexed yet"
assert n_in_press > 0, "text: some records are articles in press"