# Research topics from publication titles: every record has one, so the method is the same for all
# years (the processed data carry no abstracts or keywords).
import re
import unicodedata
from collections import Counter
from scipy.optimize import linear_sum_assignment
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS, TfidfVectorizer
from sece_stats import metrics, periods
LAST_FULL = periods.LAST_FULL # latest full year (the year before PARTIAL)
P_RECENT = periods.period_of(LAST_FULL) # latest five full years
P_BASE = periods.period_of(LAST_FULL - 10) # the five years a decade earlier: comparison period
RECENT, BASE = periods.bounds(P_RECENT), periods.bounds(P_BASE)
NCS_MIN = 10 # citation window (NCS_YEARS, below): fewest papers of a type in a year
K_TOPICS = 12 # number of NMF topics, chosen among K_RANGE (see the notes)
K_RANGE = range(10, 16)
MIN_DF = 5 # a term must occur in at least 5 titles to enter the topic model
MIN_PERIOD_TITLES = 100 # periods with fewer titles are not shown in the topic heatmap
TREND_FROM = 1995 # first year shown in the term trend lines (earlier years have few titles)
MIN_MENTIONS = 20 # curated terms need at least this many titles (all full years)
N_BOOT = 2000 # bootstrap resamples for the confidence intervals
N_TOP = 15 # terms per list (most frequent; rising and declining)
N_TOPIC_TERMS = 8 # top terms listed per topic (hover of the citation chart, notes)
N_TABLE_TERMS = 5 # top terms shown in the topic table
MIN_CHANGE = 0.01 # topic share changes under one percentage point count as small (guarded)
# ------------------------------------------------------------------ text preparation
# Research-generic words: dropped everywhere.
GENERIC = set("""
using use used uses based approach approaches analysis analyses novel new study studies method
methods methodology methodologies application applications applied toward via technique techniques
case paper proposed propose improved improving improve efficient efficiently effective effect
evaluation evaluating investigation investigating performance framework problem result issue
aspect overview review survey introduction comparison comparative comparing assessment development
developing implementation implementing editorial guest special preface reply author discussion part
erratum corrigendum multi non co self semi sub inter intra ultra anti pre post re bi tri de vs et al
generalized simple simplified considering consideration role impact way type various art prospect
challenge trend perspective opportunity insight lesson tutorial
""".split())
# scikit-learn's English stop list also holds words that are terms in engineering titles.
UNSTOP = set("""back bill bottom call describe detail empty fill fire front full interest mill move
serious side system thick thin third top""".split())
UNITS = set("kv ghz mhz khz thz hz gbps mbps kbps db dbm nm km cm mm kw mw gw kwh mwh".split())
STOP = (set(ENGLISH_STOP_WORDS) - UNSTOP) | GENERIC | UNITS
# Generic modifiers: not a term on their own, only inside two-word terms (real time, power system).
WEAK = set("""
model modeling modelling design time high higher low lower order multiple dynamic rate scheme
structure finite domain term level mode state line field current process optimal integrated active
large small scale short long real single dual parameter function condition characteristic property
network algorithm system data power future recent advance advanced emerging
back bill bottom call describe detail empty fill front full interest mill move side thick thin third top
""".split())
# Phrases folded into one token, so that spelled-out and abbreviated forms count together.
PHRASES = [(re.compile(rx), f" {tok} ") for rx, tok in [
(r"finite[- ]difference[- ]time[- ]domain", "fdtd"),
(r"internet[- ]of[- ]things", "iot"),
(r"non[- ]?orthogonal[- ]multiple[- ]access", "noma"),
(r"multiple[- ]input[- ]multiple[- ]output", "mimo"),
(r"reconfigurable[- ]intelligent[- ]surfaces?", "ris"),
(r"unmanned[- ]aerial[- ]vehicles?", "uav"),
(r"orthogonal[- ]frequency[- ]division[- ]multiplexing", "ofdm"),
(r"electroencephalogra(?:m|ms|phy|phic)", "eeg"),
(r"covid[- ]?19|sars[- ]cov[- ]2|coronavirus", "covid"),
(r"field[- ]programmable[- ]gate[- ]arrays?", "fpga"),
(r"amplify[- ]and[- ]forward", "af"),
(r"decode[- ]and[- ]forward", "df"),
(r"millimeter[- ]wave|\bmm[- ]?waves?\b", "mmwave"),
(r"\bpvs?\b", "photovoltaic"),
(r"\bevs?\b", "electric vehicle"),
(r"\bai\b", "artificial intelligence"),
]]
KEEP_S = set("""bias gas canvas atlas alias lens chaos cmos mos dos qos gps mems hems ems bms dms
series species news always thus versus plus status corpus focus stimulus campus virus consensus
apparatus nexus modulus radius locus bus mass class less loss process access stress glass cross pass
wireless lossless seamless ris res""".split())
IRREGULAR = {"indices": "index", "matrices": "matrix", "vertices": "vertex", "analyses": "analysis",
"criteria": "criterion", "phenomena": "phenomenon"}
DASHES = dict.fromkeys(map(ord, "‐‑‒–—―−"), "-")
BRACKETS = re.compile(r"\s*;?\s*\[[^\]]*\]") # translated titles "; [...]", "[letter]"
WORD = re.compile(r"[^\W_]+(?:'[^\W_]+)?")
def normalize_title(title: str) -> str:
"""NFKC, plain hyphens, no bracketed translations, lower case."""
text = unicodedata.normalize("NFKC", title).translate(DASHES)
return BRACKETS.sub(" ", text).replace("’", "'").lower()
def singular(word: str) -> str:
"""Conservative English singular (networks -> network, technologies -> technology)."""
if word in IRREGULAR:
return IRREGULAR[word]
if len(word) <= 3 or word in KEEP_S or not word.endswith("s") or word.endswith(("ss", "us", "is", "ics")):
return word
if word.endswith("ies") and len(word) > 4:
return word[:-3] + "y"
if word.endswith(("sses", "ches", "shes", "xes")):
return word[:-2]
return word[:-1]
def tokenize(title: str) -> tuple[list[str], list[str]]:
"""(normalised tokens, surface forms) of a title; hyphenated words are split."""
text = normalize_title(title)
for rx, tok in PHRASES:
text = rx.sub(tok, text)
raw = [m.group(0).replace("'s", "").replace("'", "") for m in WORD.finditer(text)]
return [singular(w) for w in raw], raw
def is_content(word: str) -> bool:
return len(word) > 1 and word not in STOP and not re.fullmatch(r"\d+(?:\.\d+)?", word)
def title_terms(title: str) -> set[str]:
"""Unigrams (content words that are not generic modifiers) and bigrams of adjacent content words."""
toks, _ = tokenize(title)
keep = [is_content(w) for w in toks]
uni = {w for w, k in zip(toks, keep) if k and w not in WEAK}
bi = {f"{a} {b}" for a, ka, b, kb in zip(toks, keep, toks[1:], keep[1:]) if ka and kb and a != b}
return uni | bi
# ------------------------------------------------------------------ corpus and term frequencies
pubs = data.load_publications()
# normalised citation score as on Citation impact: by publication year and type, reviews with articles
pubs["ncs_type"] = pubs["doc_type"].replace({"Review": "Article"})
pubs["ncs"] = metrics.normalized_citation_score(pubs, by=["year", "ncs_type"])
# Citation window as on Citation impact: papers with at least two full calendar years of citations
# (to LAST_FULL - 2), from the first year after the last one with fewer than NCS_MIN articles (reviews
# included) or conference papers, so that each year and type has an average of its own.
type_year = (pd.crosstab(pubs.year, pubs.ncs_type)
.reindex(index=range(int(pubs.year.min()), LAST_FULL - 1), columns=["Article", "Conference paper"],
fill_value=0))
thin = type_year.min(axis=1) < NCS_MIN
NCS_YEARS = (int(thin[thin].index.max()) + 1 if thin.any() else int(type_year.index.min()), LAST_FULL - 2)
is_erratum = pubs.doc_type.eq("Erratum")
n_errata = int(is_erratum.sum())
other_titles = pubs.loc[~is_erratum, "title"].str.lower()
def corrected_in_data(title: str) -> bool:
"""Whether the paper an erratum corrects ("Erratum: <title> (<journal>)") is also a record."""
core = re.sub(r"^\s*(?:erratum|corrigendum|correction)(?:\s+to)?\s*:?\s*[“\"']?", "", title, flags=re.I)
core = re.split(r"\s*\(|[”\"]", core)[0].strip().lower()[:40]
return bool(core) and bool(other_titles.str.startswith(core).any())
n_errata_in_data = int(pubs.loc[is_erratum, "title"].map(corrected_in_data).sum())
corpus = pubs[~is_erratum].reset_index(drop=True) # errata repeat the title of the corrected paper
corpus["terms"] = [sorted(title_terms(t)) for t in corpus.title]
n_titles = len(corpus)
FIRST_YEAR = int(corpus.year.min())
is_recent = corpus.year.between(*RECENT)
is_base = corpus.year.between(*BASE)
in_full = corpus.year < PARTIAL
n_recent, n_base = int(is_recent.sum()), int(is_base.sum())
def doc_freq(mask) -> pd.Series:
"""Number of titles (rows selected by ``mask``) containing each term, ties in alphabetical order."""
counts = Counter(t for ts in corpus.loc[mask, "terms"] for t in ts)
return pd.Series(counts, dtype="int64").sort_index()
df_all = doc_freq(slice(None))
# A word that occurs mostly (in >= 50% of its titles) inside one two-word term is shown as that term.
best_bigram: dict[str, tuple[float, str]] = {} # word: (largest share of its titles in one pair, that pair)
for term, n in df_all.items():
if " " in term:
for w in term.split():
if w in df_all.index and n / df_all[w] > best_bigram.get(w, (0.0, ""))[0]:
best_bigram[w] = (n / df_all[w], term)
SHOWN_AS = {w: pair for w, (s, pair) in best_bigram.items() if s >= 0.5}
SUBSUMED = set(SHOWN_AS)
# display forms: the most common written form, with acronyms and names restored
surface: Counter = Counter()
for t in corpus.title:
toks, raw = tokenize(t)
surface.update(zip(toks, raw))
surface.update((f"{a} {b}", f"{ra} {rb}") for a, b, ra, rb in zip(toks, toks[1:], raw, raw[1:]))
best_form: dict[str, str] = {}
for (term, form), _ in surface.most_common():
best_form.setdefault(term, form)
CASED = {w.lower(): w for w in """FDTD IoT NOMA MIMO RIS UAV OFDM EEG ECG FPGA 5G 6G 4G 3D 2D RFID mmWave AF
DF AI DC AC PID VLSI CMOS WiMAX LTE QoS MEC HV MV LV EMC EMTP ATP FEM PMSM UWB FSO SNR BER MRI TMS GIS
GPS WSN WLAN STBC MISO RES BESS HVDC CNN SVM LMS SIP ICT ICU Greek European Greece Europe Nakagami
Rayleigh Lyapunov Kalman Fourier Markov Gaussian Maxwell Bayesian Monte Carlo Lorentz""".split()}
CASED["parkinson"] = "Parkinson's"
def show(term: str) -> str:
"""Display form of a term."""
return " ".join(CASED.get(w, w) for w in best_form.get(term, term).split())
def top_terms(mask, total: int, n: int = N_TOP) -> pd.DataFrame:
"""The ``n`` most frequent terms plus any terms tied with the n-th (ties in alphabetical order)."""
counts = doc_freq(mask)
counts = counts[~counts.index.isin(SUBSUMED)].sort_values(ascending=False, kind="stable")
out = counts[counts >= counts.iloc[n - 1]].rename("titles").rename_axis("term").reset_index()
out["share"] = out.titles / total
out["label"] = out.term.map(show)
return out
top_all = top_terms(slice(None), n_titles)
top_recent = top_terms(is_recent, n_recent)
# ------------------------------------------------------------------ topic model: TF-IDF + NMF
tfidf = TfidfVectorizer(analyzer=lambda terms: terms, min_df=MIN_DF, sublinear_tf=True)
X = tfidf.fit_transform(corpus.terms)
vocab = tfidf.get_feature_names_out()
n_vocab = len(vocab)
models = {k: NMF(n_components=k, init="nndsvda", random_state=0, max_iter=2000).fit(X) for k in K_RANGE}
# topic coherence: mean NPMI of the 10 top terms of each topic (co-occurrence within titles)
B = (X > 0).astype("float64").tocsc()
p_term = np.asarray(B.sum(axis=0)).ravel() / n_titles
def npmi(top: np.ndarray) -> float:
vals = []
for i, a in enumerate(top):
for b in top[i + 1:]:
p_ab = B[:, a].multiply(B[:, b]).sum() / n_titles
vals.append(-1.0 if p_ab == 0 else np.log(p_ab / (p_term[a] * p_term[b])) / -np.log(p_ab))
return float(np.mean(vals))
coherence = pd.Series({k: np.mean([npmi(np.argsort(h)[::-1][:10]) for h in m.components_])
for k, m in models.items()})
nmf = models[K_TOPICS]
W = nmf.transform(X)
H = nmf.components_
# Human labels, given after reading each topic's top terms and titles. They are matched to the
# model's topics through anchor terms (optimal one-to-one assignment), so a change in topic order
# cannot mislabel a topic; a topic whose 10 top terms hold fewer than 2 anchors of its match is
# shown by its own top terms instead.
AREAS = ["Energy & power", "Communications & electromagnetics", "Computing, signals & control"]
TOPICS = { # label: (broad area, anchor terms)
"Electricity markets": (0, ["market", "electricity market", "day ahead", "clearing"]),
"Distribution grids & renewables": (0, ["distribution network", "active distribution", "ancillary service", "photovoltaic"]),
"Energy management & storage": (0, ["energy storage", "storage", "battery", "building", "zero energy"]),
"Lightning & high voltage": (0, ["lightning", "overhead", "transmission line", "impulse"]),
"Wireless & optical communications": (1, ["wireless", "wireless communication", "optical wireless", "sensor network"]),
"Fading channels & diversity": (1, ["fading", "fading channel", "diversity", "nakagami"]),
"Antennas & metamaterials": (1, ["antenna", "antenna array", "metamaterial", "array"]),
"Computational EM & photonics": (1, ["fdtd", "wave", "propagation", "waveguide", "graphene"]),
"Machine learning": (2, ["learning", "machine learning", "deep learning", "federated learning"]),
"Neural networks & forecasting": (2, ["neural network", "neural", "recurrent", "forecasting"]),
"Image & signal analysis": (2, ["image", "segmentation", "detection", "classification", "fuzzy"]),
"Control & robotics": (2, ["control", "robot", "prescribed", "tracking"]),
}
labels = list(TOPICS)
pos = {t: i for i, t in enumerate(vocab)}
Hn = H / H.max(axis=1, keepdims=True)
score = np.array([[sum(Hn[c, pos[a]] for a in anchors if a in pos) for c in range(K_TOPICS)]
for _, anchors in TOPICS.values()])
lab_idx, comp_idx = linear_sum_assignment(-score)
match = dict(zip(comp_idx, lab_idx))
comp_label = {}
for c in range(K_TOPICS):
ranked_c = vocab[np.argsort(H[c])[::-1]]
li = match.get(c)
if li is not None and len(set(ranked_c[:10]) & set(TOPICS[labels[li]][1])) >= 2:
comp_label[c] = labels[li]
else:
comp_label[c] = "Topic: " + ", ".join(show(t) for t in ranked_c[:3])
n_fallback = sum(lab not in TOPICS for lab in comp_label.values())
TOPIC_ORDER = sorted(comp_label.values(), key=lambda t: labels.index(t) if t in TOPICS else len(labels))
TOPIC_AREA = {t: AREAS[TOPICS[t][0]] if t in TOPICS else "Other" for t in TOPIC_ORDER}
# each title goes to its dominant topic (largest NMF weight); titles without model terms: Unassigned
has_terms = W.max(axis=1) > 0
corpus["topic"] = np.where(has_terms, [comp_label[c] for c in W.argmax(axis=1)], "Unassigned")
theta = W / np.where(has_terms, W.sum(axis=1), 1.0)[:, None] # topic proportions per title
n_unassigned = int((~has_terms).sum())
share_weak = float((theta.max(axis=1)[has_terms] < 0.5).mean()) # dominant topic < half the weight
topic_top, topic_terms, table_terms = {}, {}, {}
for c, lab in comp_label.items():
# terms by weight; a word that occurs mostly inside one two-word term is shown as that term (once)
ranked = list(dict.fromkeys(SHOWN_AS.get(str(t), str(t)) for t in vocab[np.argsort(H[c])[::-1]]))
topic_top[lab] = set(ranked[:N_TOPIC_TERMS])
topic_terms[lab] = ", ".join(show(t) for t in ranked[:N_TOPIC_TERMS])
table_terms[lab] = ", ".join(show(t) for t in ranked[:N_TABLE_TERMS])
# share of each topic's titles that contain at least one of its listed top terms
topic_cover = pd.Series({lab: corpus.terms[corpus.topic == lab].map(lambda ts: bool(top & set(ts))).mean()
for lab, top in topic_top.items()})
# Stability: refit the model on random 80% samples of the titles and count how many of each topic's
# ten top terms reappear among the ten top terms of the matching topic (topics paired optimally).
N_SUBSAMPLES = 10
rng_sub = np.random.default_rng(1)
ref_sets = [set(vocab[np.argsort(h)[::-1][:10]]) for h in H]
shared = []
for _ in range(N_SUBSAMPLES):
rows = rng_sub.choice(n_titles, size=int(0.8 * n_titles), replace=False)
vec_s = TfidfVectorizer(analyzer=lambda terms: terms, min_df=MIN_DF, sublinear_tf=True)
X_s = vec_s.fit_transform(corpus.terms.iloc[rows])
H_s = NMF(n_components=K_TOPICS, init="nndsvda", random_state=0, max_iter=2000).fit(X_s).components_
voc_s = vec_s.get_feature_names_out()
sets_s = [set(voc_s[np.argsort(h)[::-1][:10]]) for h in H_s]
common = np.array([[len(a & b) for b in sets_s] for a in ref_sets])
r_idx, c_idx = linear_sum_assignment(-common)
shared.append(common[r_idx, c_idx])
topic_stability = pd.Series(np.mean(shared, axis=0), index=[comp_label[c] for c in range(K_TOPICS)])
# topic shares by 5-year period (full years only; shares of all titles of the period)
full = corpus[in_full].assign(period=lambda d: d.year.map(lambda y: periods.period_of(y, first_year=FIRST_YEAR)))
period_n = full.groupby("period").size().reindex(periods.periods(FIRST_YEAR), fill_value=0)
tp = pd.crosstab(full.topic, full.period, normalize="columns")
SHOW_PERIODS = [p for p in period_n.index if period_n[p] >= MIN_PERIOD_TITLES]
topic_change = (tp[P_RECENT] - tp[P_BASE]).drop("Unassigned", errors="ignore").sort_values()
# robustness: the same change computed from fractional topic proportions instead of dominant topics
frac = pd.DataFrame(theta[in_full.to_numpy()], columns=[comp_label[c] for c in range(K_TOPICS)])
frac["period"] = full.period.to_numpy()
frac = frac.groupby("period").mean().T
frac_change = (frac[P_RECENT] - frac[P_BASE])[topic_change.index]
frac_corr = float(np.corrcoef(topic_change, frac_change)[0, 1])
is_paper = corpus.doc_type.isin(["Article", "Conference paper"]).to_numpy()
topic_summary = pd.DataFrame({"topic": TOPIC_ORDER, "area": [TOPIC_AREA[t] for t in TOPIC_ORDER]})
topic_summary["terms"] = topic_summary.topic.map(table_terms)
topic_summary["titles"] = topic_summary.topic.map(corpus.topic.value_counts()).fillna(0).astype(int)
topic_summary["share_all"] = topic_summary.titles / n_titles
topic_summary["share_base"] = topic_summary.topic.map(tp[P_BASE]).fillna(0.0)
topic_summary["share_recent"] = topic_summary.topic.map(tp[P_RECENT]).fillna(0.0)
example = {}
for c, lab in comp_label.items(): # most representative article/paper title: largest topic weight
members = np.flatnonzero((corpus.topic == lab).to_numpy() & is_paper)
example[lab] = corpus.title.iloc[members[np.argmax(W[members, c])]] if len(members) else ""
topic_summary["example"] = topic_summary.topic.map(example)
# ------------------------------------------------------------------ citation impact per topic
# articles, reviews and conference papers of NCS_YEARS, as on the Citation impact page
rng = np.random.default_rng(0)
cit_all = corpus[corpus.year.between(*NCS_YEARS) & corpus.doc_type.isin(["Article", "Review", "Conference paper"])
& corpus.ncs.notna()]
cit = cit_all[cit_all.topic != "Unassigned"] # titles without any model term have no topic
ncs_rows = []
for t in TOPIC_ORDER:
vals = cit.loc[cit.topic == t, "ncs"].to_numpy()
boots = vals[rng.integers(0, len(vals), size=(N_BOOT, len(vals)))].mean(axis=1)
ncs_rows.append(dict(topic=t, area=TOPIC_AREA[t], papers=len(vals), mean=vals.mean(),
median=float(np.median(vals)), lo=np.percentile(boots, 2.5),
hi=np.percentile(boots, 97.5)))
ncs_topic = pd.DataFrame(ncs_rows).sort_values("mean").reset_index(drop=True)
n_cit, n_cit_all = len(cit), len(cit_all)
n_cit_unassigned = n_cit_all - n_cit
# ------------------------------------------------------------------ rising and declining terms
# Weighted log-odds ratio with an informative Dirichlet prior (Monroe, Colaresi & Quinn 2008):
# counts = titles containing the term in P_RECENT vs P_BASE; prior = counts in all titles of the full years.
y_r, y_b, prior = doc_freq(is_recent), doc_freq(is_base), doc_freq(in_full)
lo = pd.DataFrame({"recent": y_r, "base": y_b}).fillna(0).astype("int64")
n_r, n_b = lo.recent.sum(), lo.base.sum() # term occurrences (one per title and term) per period
def log_odds_z(scale: float = 1.0) -> pd.Series:
"""z-score of the log-odds difference, prior = ``scale`` x the term counts of all full years."""
alpha = scale * prior.reindex(lo.index).astype("float64")
a0 = scale * float(prior.sum())
delta = (np.log((lo.recent + alpha) / (n_r + a0 - lo.recent - alpha))
- np.log((lo.base + alpha) / (n_b + a0 - lo.base - alpha)))
return delta / np.sqrt(1 / (lo.recent + alpha) + 1 / (lo.base + alpha))
lo["z"] = log_odds_z(1.0)
lo = lo[~lo.index.isin(SUBSUMED)].copy()
lo["share_recent"], lo["share_base"] = lo.recent / n_recent, lo.base / n_base
lo["label"] = lo.index.map(show)
rising = lo.nlargest(N_TOP, "z").copy()
declining = lo.nsmallest(N_TOP, "z").copy()
# robustness: the same lists with a prior of a quarter of the strength
PRIOR_CHECK = 0.25
z_check = log_odds_z(PRIOR_CHECK).loc[lo.index]
n_same_rising = len(set(rising.index) & set(z_check.nlargest(N_TOP).index))
n_same_declining = len(set(declining.index) & set(z_check.nsmallest(N_TOP).index))
def most_cited_title(term: str, mask: pd.Series) -> str:
"""Most-cited title containing ``term`` among the rows in ``mask`` (shown in the hover)."""
rows = corpus[mask & corpus.terms.map(lambda ts: term in ts)]
return rows.sort_values(["cited_by", "year"], ascending=False).title.iloc[0] if len(rows) else ""
rising["example"] = [most_cited_title(t, is_recent) for t in rising.index]
declining["example"] = [most_cited_title(t, is_base) for t in declining.index]
# ------------------------------------------------------------------ selected technologies over time
CURATED = { # label: regular expression on the normalised title
"neural network": r"\bneural[- ]?networks?\b",
"machine learning": r"\bmachine[- ]learning\b",
"deep learning": r"\bdeep[- ]learning\b",
"EEG": r"\beeg\b|electroencephalogra",
"5G": r"\b5g\b",
"IoT": r"\biot\b|internet[- ]of[- ]things",
"blockchain": r"blockchain",
"smart grid": r"\bsmart[- ]grids?\b",
"photovoltaic": r"photovoltaic|\bpvs?\b",
"electric vehicle": r"\belectric(?:al)?[- ]vehicles?\b|\bevs?\b",
"antenna": r"antenna",
"metamaterial": r"metamaterial",
"metasurface": r"metasurface", # added: one of the strongest rising terms (guarded below)
"graphene": r"graphene",
"FPGA": r"\bfpgas?\b|field[- ]programmable",
"COVID": r"covid|sars[- ]cov[- ]2|coronavirus",
}
norm = corpus.title.map(normalize_title)
titles_per_year = corpus[in_full].groupby("year").size()
mentions = {name: int((norm.str.contains(rx) & in_full).sum()) for name, rx in CURATED.items()}
kept_terms = [name for name in CURATED if mentions[name] >= MIN_MENTIONS]
dropped_terms = [name for name in CURATED if mentions[name] < MIN_MENTIONS]
trend_rows = []
for name in kept_terms:
hits = corpus[norm.str.contains(CURATED[name]) & in_full].groupby("year").size()
share = metrics.rolling_share(hits, titles_per_year, window=3)
num = hits.reindex(share.index, fill_value=0).rolling(3).sum()
den = titles_per_year.reindex(share.index, fill_value=0).rolling(3).sum()
trend_rows.append(pd.DataFrame({"term": name, "year": share.index, "share": share.to_numpy(),
"hits": num.to_numpy(), "titles": den.to_numpy()}))
trends = pd.concat(trend_rows, ignore_index=True)
trends = trends[trends.year >= TREND_FROM].reset_index(drop=True)
trend = trends.pivot(index="year", columns="term", values="share")
def window(year: int) -> str:
"""Label of the 3-year window ending in ``year``."""
return f"{year - 2}–{year}"
# ------------------------------------------------------------------ numbers quoted in the text
pct = dp.fmt_pct
AS_OF_TEXT = f"{AS_OF.day} {AS_OF:%B %Y}" # the export date, day without a leading zero
ref_year = BASE[1] # last year of P_BASE: the 3-year window ending then
def join_and(items) -> str:
"""'a', 'a and b', 'a, b and c'."""
items = [str(i) for i in items]
return " and ".join(items) if len(items) <= 2 else ", ".join(items[:-1]) + " and " + items[-1]
def ordinal(n: int) -> str:
return f"{n}{'th' if 11 <= n % 100 <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')}"
def from_to(topic: str, start: str = None, end: str = None) -> str:
"""'x% to y%': share of a topic's titles in two periods (default: base and recent)."""
return f"{pct(tp.loc[topic, start or P_BASE])} to {pct(tp.loc[topic, end or P_RECENT])}"
median_words = int(corpus.title.str.split().str.len().median()) # words separated by spaces
errata_text = ("their titles repeat those of the corrected papers, which are also in the data"
if n_errata_in_data == n_errata else
f"their titles repeat those of the corrected papers ({n_errata_in_data} of which are in the data)")
entering = ~top_recent.term.isin(top_all.term) # in the recent top list, not in the all-years one
new_terms_text = join_and(top_recent.label[entering])
term1_all, term1_recent = top_all.iloc[0], top_recent.iloc[0]
top3_all_text = join_and(f"“{l}”" for l in top_all.label[:3])
rank_all = df_all[~df_all.index.isin(SUBSUMED)].rank(ascending=False, method="min").astype(int)
term1_recent_rank_all = ordinal(int(rank_all[term1_recent.term]))
term1_recent_share_all = df_all[term1_recent.term] / n_titles
best_k = int(coherence.idxmax())
fallback_text = (f"; all {K_TOPICS} topics received a name" if n_fallback == 0 else
f"; {n_fallback} topic{'s' if n_fallback > 1 else ''} without a matching name "
f"{'are' if n_fallback > 1 else 'is'} shown by {'their' if n_fallback > 1 else 'its'} top terms")
areas_text = "; ".join(AREAS)
# how coherence varies with the number of topics (notes): one peak inside K_RANGE, or a plain range
k_lo, k_hi = min(K_RANGE), max(K_RANGE)
single_peak = (k_lo < best_k < k_hi and coherence.loc[:best_k].is_monotonic_increasing
and coherence.loc[best_k:].is_monotonic_decreasing)
coherence_text = (
f"Coherence was highest with {best_k} topics ({dp.fmt_num(coherence[best_k], 3)}) and decreased with fewer or "
f"more topics, to {dp.fmt_num(coherence[k_lo], 3)} with {k_lo} and {dp.fmt_num(coherence[k_hi], 3)} with {k_hi}"
if single_peak else
f"Coherence ranged from {dp.fmt_num(coherence.min(), 3)} ({coherence.idxmin()} topics) to "
f"{dp.fmt_num(coherence.max(), 3)} ({best_k} topics)")
k_note = ("the most coherent choice" if best_k == K_TOPICS
else f"with a coherence of {dp.fmt_num(coherence[K_TOPICS], 3)}")
stab_lo, stab_hi = topic_stability.idxmin(), topic_stability.idxmax()
cover_lo, cover_hi = topic_cover.idxmin(), topic_cover.idxmax()
n_unassigned_shown = int(((full.topic == "Unassigned") & full.period.isin(SHOW_PERIODS)).sum())
largest_all = topic_summary.loc[topic_summary.titles.idxmax()]
largest_recent = topic_summary.loc[topic_summary.share_recent.idxmax()]
top5_recent = topic_summary.share_recent.nlargest(5)
gain1, gain2 = topic_change.index[-1], topic_change.index[-2]
loss1, loss2, loss3 = topic_change.index[:3]
n_gainers = int((topic_change >= MIN_CHANGE).sum())
n_losers = int((topic_change <= -MIN_CHANGE).sum())
flat = topic_change.index[topic_change.abs() < MIN_CHANGE]
flat_text = (f"; the share{'s' if len(flat) > 1 else ''} of {join_and(f'{t} ({from_to(t)})' for t in flat)} "
"changed by less" if len(flat) else "")
cut_pp = MIN_CHANGE * 100
cut_text = f"{dp.fmt_num(cut_pp, 0 if cut_pp == round(cut_pp) else 1)} percentage point{'' if cut_pp == 1 else 's'}"
def fmt_pp(change: float) -> str:
"""Size of a change in share, in percentage points: -0.0481 -> '4.8'."""
return dp.fmt_num(abs(change) * 100, 1)
# the gains and losses quoted on the page, recomputed with fractional topic weights (notes)
frac_up, frac_down = frac_change.sort_values(ascending=False), frac_change.sort_values()
if frac_up.index[0] != gain1:
frac_text = f", but the largest gain is then in {frac_up.index[0]}"
elif frac_up.index[1] != gain2:
frac_text = (f", but the second-largest gain is then in {frac_up.index[1]}, while {gain2} gains "
f"{fmt_pp(frac_change[gain2])} instead of {fmt_pp(topic_change[gain2])} percentage points")
else:
frac_text = ""
if list(frac_down.index[:3]) == [loss1, loss2, loss3]:
frac_loss_text = ""
elif set(frac_down.index[:3]) == {loss1, loss2, loss3}:
frac_loss_text = (f"The three largest losses are in the same topics, the largest in {frac_down.index[0]} "
f"({fmt_pp(frac_down.iloc[0])} percentage points).")
else:
frac_loss_text = f"The three largest losses are then in {join_and(frac_down.index[:3])}."
first_p = SHOW_PERIODS[0]
long_change = (tp[P_RECENT] - tp[first_p]).drop("Unassigned", errors="ignore").sort_values()
long_gain, long_loss = long_change.index[-1], long_change.index[0]
# broad areas: shares of all titles of the period (titles without model terms count in the totals)
area_share = pd.crosstab(full.topic.map(TOPIC_AREA).fillna("Unassigned"), full.period, normalize="columns")
area_change = (area_share[P_RECENT] - area_share[first_p]).drop("Unassigned", errors="ignore").sort_values()
area_down, area_up = area_change.index[0], area_change.index[-1]
area_recent = area_share[P_RECENT].reindex(AREAS, fill_value=0.0) # the named broad areas only
def area_from_to(area: str) -> str:
"""'x% to y%': share of a broad area's titles in the first shown and the recent period."""
return f"{pct(area_share.loc[area, first_p])} to {pct(area_share.loc[area, P_RECENT])}"
ncs_hi, ncs_lo = ncs_topic.iloc[-1], ncs_topic.iloc[0]
is_above, is_below = ncs_topic.lo > 1, ncs_topic.hi < 1
n_ncs_above, n_ncs_below = int(is_above.sum()), int(is_below.sum())
def ci_clause(mask: pd.Series, side: str, first: bool) -> str:
"""'The intervals of 2 topics (A, B) lie entirely above 1' or, after it, 'those of 2 (C, D) entirely below'."""
names = ncs_topic.topic[mask]
names = join_and(names.iloc[::-1] if side == "above" else names) # the most extreme score first
n = int(mask.sum())
if first:
return (f"The interval of one topic ({names}) lies entirely {side} 1" if n == 1 else
f"The intervals of {n} topics ({names}) lie entirely {side} 1")
return f"that of one ({names}) entirely {side}" if n == 1 else f"those of {n} ({names}) entirely {side}"
ci_sides = [(m, side) for m, side in ((is_above, "above"), (is_below, "below")) if m.any()]
ci_text = (" and ".join(ci_clause(m, side, i == 0) for i, (m, side) in enumerate(ci_sides))
+ "; the others include the average." if ci_sides else "The interval of every topic includes the average.")
def ncs_ci(row) -> str:
"""'1.61 (95% CI 1.24–2.06)'."""
return f"{dp.fmt_num(row['mean'], 2)} (95% CI {dp.fmt_num(row.lo, 2)}–{dp.fmt_num(row.hi, 2)})"
EXPAND = { # acronyms spelled out in the prose (checked against the titles that contain them)
"ris": "reconfigurable intelligent surfaces (RIS)", "uav": "unmanned aerial vehicles (UAV)",
"iot": "Internet of Things (IoT)", "noma": "non-orthogonal multiple access (NOMA)",
"af": "amplify-and-forward (AF) relaying",
}
def prose_list(terms, labels) -> str:
"""Terms joined for the prose, with acronyms spelled out."""
return join_and(EXPAND.get(t, lab) for t, lab in zip(terms, labels))
top_rising_text = prose_list(rising.index[:6], rising.label[:6])
top_declining_text = prose_list(declining.index[:6], declining.label[:6])
r1, d1 = rising.iloc[0], declining.iloc[0]
is_new = rising.base == 0
new_rising_text = prose_list(rising.index[is_new], rising.label[is_new])
n_new_rising = int((rising.base == 0).sum())
# the same fact in the key findings and under the log-odds chart, also when no riser is new
new_risers_short = (f"{n_new_rising} of the {N_TOP} strongest risers occur in no title of {P_BASE}" if n_new_rising
else f"each of the {N_TOP} strongest risers already occurs in titles of {P_BASE}")
new_risers_long = (f"Of the {N_TOP} strongest risers, {n_new_rising} occur in no title of {P_BASE}: {new_rising_text}."
if n_new_rising else f"Each of the {N_TOP} strongest risers already occurs in titles of {P_BASE}.")
# Lines of work named in the prose for the terms of the lists (read from the titles that hold them).
# The guards at the end of this cell fail when a list holds a term that the prose does not account for.
ENTERING_FIELDS = { # terms new in the recent top list -> where the prose places them
"lightning and high-voltage engineering": ["lightning", "overhead"],
"voltage control and surge protection in power networks": ["voltage"],
"metasurfaces and reconfigurable intelligent surfaces": ["metasurface", "ris"],
"machine learning": ["machine learning"],
"general words": ["optimization"],
}
RISING_FIELDS = {
"machine learning and artificial intelligence": ["learning", "deep learning", "machine learning", "artificial intelligence"],
"5G and 6G wireless networks": ["ris", "6g", "uav", "5g", "iot", "edge"],
"metasurfaces": ["metasurface"],
"lightning and surge protection, overhead lines, ancillary services": ["lightning", "surge", "overhead line", "provision"],
}
DECLINING_FIELDS = {
"fuzzy classifiers": ["fuzzy", "genetic fuzzy"],
"silicon plasmonics": ["plasmonic", "silicon", "dielectric loaded", "silicon plasmonic", "plasmonic waveguide"],
"cooperative relaying over fading channels": ["channel", "af", "relaying"],
"tuning of PID controllers": ["pid", "tuning", "optimum criterion"],
"wind energy conversion": ["wind"],
"electricity markets": ["market"],
}
PLASMONIC_TERMS = DECLINING_FIELDS["silicon plasmonics"] # notes: one line of work
plasmonic_text = join_and(show(t) for t in PLASMONIC_TERMS)
first_mention = {name: int(corpus.year[norm.str.contains(rx)].min())
for name, rx in CURATED.items() if mentions[name] > 0}
nn = trend["neural network"]
nn_peak_year = int(nn.idxmax())
nn_low_year = int(nn.loc[nn_peak_year:].idxmin())
ml, dl = trend["machine learning"], trend["deep learning"]
ms, mm = trend["metasurface"], trend["metamaterial"]
ahead = ms > mm
ms_ahead_since = int(ahead[::-1].cummin()[::-1].idxmax()) if ahead.iloc[-1] else None
ms_ahead_text = window(ms_ahead_since) if ms_ahead_since else "–"
mm_peak_year = int(mm.idxmax())
gr = trend["graphene"]
gr_peak_year = int(gr.idxmax())
pv, ev, eeg = trend["photovoltaic"], trend["electric vehicle"], trend["EEG"]
pv_peak_year, eeg_peak_year = int(pv.idxmax()), int(eeg.idxmax())
dropped_text = (f"are not plotted: {join_and(f'{name} ({mentions[name]})' for name in dropped_terms)} titles"
if dropped_terms else "would not be plotted; every term of the list has more")
first_5g, first_iot = str(first_mention.get("5G", "–")), str(first_mention.get("IoT", "–"))
first_dl = str(first_mention.get("deep learning", "–"))
early_titles = int(titles_per_year.reindex(range(TREND_FROM - 2, TREND_FROM + 1), fill_value=0).sum())
# ------------------------------------------------------------------ guards: the prose must match the data
assert pubs.title.notna().all() and pubs.title.str.strip().ne("").all(), "text: every record has a title"
assert n_fallback == 0, "text: every topic of the model has a name (anchor terms of TOPICS match each component)"
i_first = list(period_n.index).index(first_p)
assert (period_n.iloc[:i_first] < MIN_PERIOD_TITLES).all() and SHOW_PERIODS == list(period_n.index[i_first:]), \
"text: the heatmap shows every period from the first with enough titles; the earlier ones have fewer"
assert term1_recent.term != term1_all.term, "text: the recent leader ranks lower over all years"
assert SHOWN_AS.get("neural") == "neural network", "text: neural is shown as neural network"
assert topic_change[gain1] > 0 and topic_change[gain2] > 0, "text: the two largest changes are gains"
assert (topic_change[[loss1, loss2, loss3]] < 0).all(), "text: the three largest losses are losses"
# The heatmap rounds the shares to 0.1 percentage points, so a difference of two shown shares is off by at
# most 0.1 points: no change within 0.1 points of the cut, and the counts of gains, losses and smaller
# changes are the same in the shares as shown.
assert ((topic_change.abs() - MIN_CHANGE).abs() > 0.001).all(), \
"text: every topic's change is clearly above or below the cut, also in the rounded shares of the heatmap"
assert long_change[long_loss] < 0 < long_change[long_gain], "text: long-run fall and rise"
assert area_change[area_down] < 0 < area_change[area_up], "text: one broad area fell, another rose"
assert top5_recent.iloc[0] < 2 * top5_recent.iloc[-1], "text: no topic dominates the recent period"
assert frac_corr >= 0.8, "text: fractional topic weights give similar changes"
assert (ncs_topic["median"] < ncs_topic["mean"]).all(), "text: means depend on a few highly cited papers"
assert ncs_topic.assign(width=ncs_topic.hi - ncs_topic.lo)[["papers", "width"]].corr("spearman").iloc[0, 1] < 0, \
"text: small topics tend to have wide intervals"
# the topics differ in venues, collaboration and open access (citation set, by at least 10 points each)
topic_mix = cit.groupby("topic").agg(journal=("source_kind", lambda s: s.eq("journal").mean()),
intl=("collab_type", lambda s: s.eq("international").mean()),
oa=("oa_any", "mean"))
assert (topic_mix.max() - topic_mix.min()).ge(0.10).all(), "text: topics differ in venues, collaboration and OA"
def topics_of(terms) -> pd.Series:
"""Number of titles per dominant topic among the titles that contain any of ``terms``."""
return corpus.topic[corpus.terms.map(lambda ts: bool(set(ts) & set(terms)))].value_counts()
# examples of topics that are broader than their names (notes)
HEALTH_TERMS = ["patient", "disease", "health", "healthcare", "clinical", "medical", "parkinson"]
ai_topics = topics_of(["artificial intelligence"])
assert topics_of(HEALTH_TERMS).index[0] == "Machine learning", "text: health titles most often under Machine learning"
assert topics_of(["edge computing"]).index[0] == "Wireless & optical communications", \
"text: edge-computing titles under Wireless & optical communications"
assert "artificial intelligence" in pos and ai_topics.index[0] == "Antennas & metamaterials" \
and ai_topics.iloc[0] > ai_topics.sum() / 2 \
and comp_label[int(np.argmax(H[:, pos["artificial intelligence"]]))] == "Antennas & metamaterials", \
"text: most AI titles under Antennas & metamaterials, where the term has its largest weight"
# interpretations of the term lists (fields above)
assert set(top_recent.term[entering]) == {t for ts in ENTERING_FIELDS.values() for t in ts}, \
"text: the fields named for the terms new in the recent top list"
assert set(rising.index) == {t for ts in RISING_FIELDS.values() for t in ts}, "text: fields of the rising terms"
assert set(declining.index) == {t for ts in DECLINING_FIELDS.values() for t in ts}, "text: fields of the declining terms"
assert "metasurface" in rising.index, "text: metasurface is one of the strongest rising terms"
# selected technologies
assert 1990 <= nn_peak_year - 2 and nn_peak_year <= 1999, "text: neural networks peaked in a window of the 1990s"
assert nn_low_year < LAST_FULL and nn[LAST_FULL] >= 2 * nn[nn_low_year], "text: neural networks fell, then recovered"
assert ml[LAST_FULL] > ml[ref_year] and dl[LAST_FULL] > dl[ref_year], "text: machine and deep learning rose over the decade"
assert ms_ahead_since is not None and mm_peak_year < ms_ahead_since, \
"text: metasurfaces ahead of metamaterials in every window since, after the metamaterial peak"
assert gr_peak_year < LAST_FULL and pv_peak_year < LAST_FULL and pv[LAST_FULL] < pv[pv_peak_year], \
"text: graphene and photovoltaic peaked earlier; photovoltaic fell"