comparative_analysis.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. from cProfile import label
  2. import numpy as np
  3. import pandas as pd
  4. from scipy.stats import entropy
  5. import ot
  6. from sklearn.linear_model import LinearRegression
  7. from matplotlib import pyplot as plt
  8. import matplotlib
  9. matplotlib.use("pgf")
  10. matplotlib.rcParams.update(
  11. {
  12. "pgf.texsystem": "xelatex",
  13. "font.family": "serif",
  14. "font.serif": "Times New Roman",
  15. "text.usetex": True,
  16. "pgf.rcfonts": False,
  17. }
  18. )
  19. plt.rcParams["text.latex.preamble"].join([
  20. r"\usepackage{amsmath}",
  21. r"\setmainfont{amssymb}",
  22. ])
  23. from textwrap import wrap
  24. import argparse
  25. from os.path import join as opj, exists
  26. import pickle
  27. from cmdstanpy import CmdStanModel
  28. parser = argparse.ArgumentParser()
  29. parser.add_argument("--input")
  30. parser.add_argument("--dataset", default="inspire-harvest/database")
  31. parser.add_argument("--suffix", default=None)
  32. parser.add_argument("--metric", default="change", choices=["change", "disruption", "diversification", "diversification_stirling", "entered", "exited", "exited_total_power_effect"])
  33. parser.add_argument("--diversity", default="entropy", choices=["entropy", "stirling"])
  34. parser.add_argument("--power", choices=["magnitude", "brokerage"], default="magnitude")
  35. parser.add_argument("--model", default="", choices=["", "bare"])
  36. parser.add_argument("--compact", action="store_true", default=False)
  37. parser.add_argument("--fla", action="store_true", default=False)
  38. args = parser.parse_args()
  39. fla = "_fla" if args.fla else ""
  40. def age():
  41. if not exists(opj(args.input, "age.csv")):
  42. articles = pd.read_parquet(opj(args.dataset, "articles.parquet"))[["article_id", "date_created", "pacs_codes", "curated", "accelerators"]]
  43. articles["article_id"] = articles.article_id.astype(int)
  44. articles = articles[articles["date_created"].str.len() >= 4]
  45. articles["year"] = articles["date_created"].str[:4].astype(int)
  46. articles["age"] = 2015-articles["date_created"].str[:4].astype(int)
  47. age = articles[["article_id", "age"]].copy()
  48. articles = articles[(articles["year"]>=2000)&(articles["year"]<2010)]
  49. _articles = pd.read_csv(opj(args.input, "articles.csv"))
  50. articles = _articles.merge(articles, how="inner")
  51. authors = pd.read_parquet(opj(args.dataset, "articles_authors.parquet"))
  52. authors["article_id"] = authors.article_id.astype(int)
  53. n_authors = authors.groupby("article_id").agg(n_authors=("bai", "count")).reset_index()
  54. articles = articles.merge(n_authors, how="left", left_on="article_id", right_on="article_id")
  55. # exclude large collaborations (experiments, software, etc.)
  56. articles = articles[articles.accelerators.map(len)==0]
  57. articles = articles[articles["n_authors"]<10]
  58. references = pd.read_parquet(opj(args.dataset, "articles_references.parquet"))
  59. references = references[references["cites"]!=references["cited"]]
  60. references = references.groupby("cited").agg(citations=("cites", "count")).reset_index()
  61. references["cited"] = references.cited.astype(int)
  62. references = references[references["cited"].isin(articles.article_id)]
  63. articles = articles.merge(references, how="outer", left_on="article_id", right_on="cited")
  64. articles.dropna(subset=["year"], inplace=True)
  65. articles.fillna({"citations": 0}, inplace=True)
  66. articles["citations_per_author"] = articles["citations"]/articles["n_authors"]
  67. del references
  68. age = age.merge(authors, how="inner", left_on="article_id", right_on="article_id")
  69. age = age.groupby("bai").agg(age=("age", "max")).reset_index()
  70. age.to_csv(opj(args.input, "age.csv"))
  71. else:
  72. age = pd.read_csv(opj(args.input, "age.csv"))
  73. return age
  74. def institution_stability():
  75. if exists(opj(args.input, "institutional_stability.csv")):
  76. return pd.read_csv(opj(args.input, "institutional_stability.csv"), index_col="bai")
  77. affiliations = pd.read_parquet(opj(args.dataset, "affiliations.parquet"))
  78. affiliations["article_id"] = affiliations.article_id.astype(int)
  79. articles = pd.read_parquet(opj(args.dataset, "articles.parquet"))[["article_id", "date_created"]]
  80. articles = articles[articles["date_created"].str.len() >= 4]
  81. articles["year"] = articles["date_created"].str[:4].astype(int) - 2000
  82. articles["article_id"] = articles.article_id.astype(int)
  83. articles = articles[articles["year"] <= 2019 - 2000]
  84. articles = articles[articles["year"] >= 0]
  85. affiliations["article_id"] = affiliations.article_id.astype(int)
  86. affiliations = affiliations.merge(articles, how="inner", left_on="article_id", right_on="article_id")
  87. affiliations = affiliations[affiliations["bai"].isin(df["bai"])]
  88. authors_last = affiliations.groupby("bai").agg(last_article=("year", "max"))
  89. hosts = affiliations.sort_values(["bai", "institution_id", "year"]).groupby(["bai", "institution_id"]).agg(
  90. first=("year", "min"),
  91. last=("year", "max")
  92. )
  93. hosts["duration"] = hosts["last"]-hosts["first"]
  94. stability = hosts.groupby("bai").agg(stability=("duration", "max"), last=("last", "max"), first=("first", "min"))
  95. stability = stability.merge(authors_last, left_index=True, right_index=True)
  96. stability["stable"] = stability["stability"]>=(stability["last"]-stability["first"]-1)
  97. stability.to_csv(opj(args.input, "institutional_stability.csv"))
  98. return stability
  99. def productivity():
  100. if exists(opj(args.input, "productivity.csv")):
  101. return pd.read_csv(opj(args.input, "productivity.csv"), index_col="bai")
  102. articles = pd.read_parquet(opj(args.dataset, "articles.parquet"))[["article_id", "date_created", "categories"]]
  103. articles["article_id"] = articles.article_id.astype(int)
  104. articles = articles[articles["date_created"].str.len() >= 4]
  105. articles["year"] = articles["date_created"].str[:4].astype(int)
  106. articles = articles[articles["categories"].map(lambda x: "Phenomenology-HEP" in x or "Theory-HEP" in x or "Gravitation and Cosmology" in x)]
  107. articles = articles[(articles["year"]>=2000)&(articles["year"]<2010)]
  108. _articles = pd.read_csv(opj(args.input, "articles.csv"))
  109. articles = _articles.merge(articles, how="inner")
  110. authors = pd.read_parquet(opj(args.dataset, "articles_authors.parquet"))
  111. authors["article_id"] = authors.article_id.astype(int)
  112. n_authors = authors.groupby("article_id").agg(n_authors=("bai", "count")).reset_index()
  113. articles = articles.merge(n_authors, how="inner", left_on="article_id", right_on="article_id")
  114. articles["solo"] = articles["n_authors"]==1
  115. articles = articles.merge(authors, how="left", left_on="article_id", right_on="article_id")
  116. productivity = articles.groupby("bai").agg(
  117. productivity=("solo", lambda x: (~x).sum()),
  118. productivity_solo=("solo", "sum")
  119. )
  120. productivity.to_csv(opj(args.input, "productivity.csv"))
  121. return productivity
  122. suffix = f"_{args.suffix}" if args.suffix is not None else ""
  123. topics = pd.read_csv(opj(args.input, "topics.csv"))
  124. junk = topics["label"].str.contains("Junk")
  125. topics = topics[~junk]["label"].tolist()
  126. fig, ax = plt.subplots()
  127. n_topics = len(pd.read_csv(opj(args.input, "topics.csv")))
  128. df = pd.read_csv(opj(args.input, f"aggregate{fla}.csv"))
  129. resources = pd.read_parquet(opj(args.input, "pooled_resources.parquet"))
  130. df = df.merge(resources, left_on="bai", right_on="bai")
  131. print(df)
  132. NR = np.stack(df[[f"start_{k+1}" for k in range(n_topics)]].values).astype(int)
  133. NC = np.stack(df[[f"end_{k+1}" for k in range(n_topics)]].values).astype(int)
  134. expertise = np.stack(df[[f"expertise_{k+1}" for k in range(n_topics)]].values)
  135. S = np.stack(df["pooled_resources"])
  136. brokerage = pd.read_csv("output/authors_brokerage.csv")
  137. df = df.merge(brokerage, how="left", left_on="bai", right_on="bai")
  138. print(df)
  139. NR = NR[:,~junk]
  140. NC = NC[:,~junk]
  141. expertise = expertise[:,~junk]
  142. S = S[:,~junk]
  143. x = NR/NR.sum(axis=1)[:,np.newaxis]
  144. y = NC/NC.sum(axis=1)[:,np.newaxis]
  145. S_distrib = S/S.sum(axis=1)[:,np.newaxis]
  146. R = np.array([
  147. [((expertise[:,i]>expertise[:,i].mean())&(expertise[:,j]>expertise[:,j].mean())).mean()/(expertise[:,i]>expertise[:,i].mean()).mean() for j in range(len(topics))]
  148. for i in range(len(topics))
  149. ])
  150. change = np.abs(y-x).sum(axis=1)/2
  151. diversification = (np.exp(entropy(y, axis=1))-np.exp(entropy(x, axis=1)))/x.shape[1]
  152. x_matrix = np.einsum("ki,kj->kij", x, x)
  153. y_matrix = np.einsum("ki,kj->kij", y, y)
  154. x_stirling = 1-np.einsum("ij,kij->k", R, x_matrix)
  155. y_stirling = 1-np.einsum("ij,kij->k", R, y_matrix)
  156. if exists(opj(args.input, f"cost_knowledge_bounded.npz")):
  157. cost_matrix = np.load(opj(args.input, f"cost_knowledge_bounded.npz"))["C"].mean(axis=0)
  158. print(cost_matrix.sum())
  159. cost_matrix = cost_matrix*(1-np.eye(x.shape[1])).sum()/cost_matrix.sum()
  160. else:
  161. cost_matrix = np.eye(x.shape[1])
  162. disruption = np.zeros(len(change))
  163. for a in range(len(change)):
  164. # disruption[a] = ot.emd2(x[a,:].copy(order='C'), y[a,:].copy(order='C'), 1-R, processes=4)
  165. disruption[a] = ot.emd2(x[a,:].copy(order='C'), y[a,:].copy(order='C'), cost_matrix, processes=4)
  166. alpha = 1
  167. exited = ((x>alpha*x.mean(axis=0))&(y<alpha*y.mean(axis=0))).sum(axis=1)
  168. entered = ((x<alpha*x.mean(axis=0))&(y>alpha*y.mean(axis=0))).sum(axis=1)
  169. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  170. ax.hist(change, bins=np.linspace(0,1,50), histtype="step", color = '#377eb8', label="Change score $c_a$")
  171. ax.hist(disruption, bins=np.linspace(0,1,50), histtype="step", color = '#ff7f00', label="Cognitive distance $d_a$")
  172. ax.set_xlabel(f"Change score $c_a$ and cognitive distance $d_a$")
  173. ax.set_ylabel("\\# of scientists")
  174. ax.legend()
  175. fig.savefig(opj(args.input, f"change_disruption_score{fla}.eps"), bbox_inches="tight")
  176. print("change 50%% interval: ", np.quantile(change,q=0.25), np.quantile(change,q=1-0.25))
  177. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  178. ax.hist(diversification, bins=np.linspace(-0.5,0.5,50), histtype="step")
  179. ax.set_xlabel(f"Diversification score $\\Delta_a$")
  180. ax.set_ylabel("\\# of scientists")
  181. fig.savefig(opj(args.input, f"diversification_score{fla}.eps"), bbox_inches="tight")
  182. fig, ax = plt.subplots()
  183. ax.hist(disruption, bins=np.linspace(0,1,50), histtype="step")
  184. ax.set_xlabel(f"Disruption score $d_a$")
  185. ax.set_ylabel("\\# of scientists")
  186. fig.savefig(opj(args.input, f"disruption_score{fla}.eps"), bbox_inches="tight")
  187. df["change_score"] = change
  188. df["disruption_score"] = disruption
  189. df["diversification_score"] = diversification
  190. df["diversification_stirling_score"] = y_stirling-x_stirling
  191. df["entered_score"] = (entered>0).astype(int)
  192. df["exited_score"] = (exited>0).astype(int)
  193. df["exited_total_power_effect_score"] = (exited>0).astype(int)
  194. df["origin"] = np.argmax(x, axis=1)
  195. df["target"] = np.argmax(y, axis=1)
  196. df["origin_value"] = x.max(axis=1)
  197. df["target_value"] = y.max(axis=1)
  198. df["origin_final_value"] = np.array(y[a,df.loc[a, "origin"]] for a in range(x.shape[0]))
  199. df["target_initial_value"] = np.array(x[a,df.loc[a, "target"]] for a in range(x.shape[0]))
  200. df["origin_label"] = df["origin"].apply(lambda k: topics[k])
  201. df["target_label"] = df["target"].apply(lambda k: topics[k])
  202. df["origin_label"] = df.apply(lambda row: row["origin_label"] + (f" ({row['origin_value']:.2f})" if row["origin"]==row["target"] else f" ({row['origin_value']:.2f}$\\to${row['origin_final_value']:.2f})"), axis=1)
  203. df["target_label"] = df.apply(lambda row: row["target_label"] + (f" ({row['target_value']:.2f})" if row["origin"]==row["target"] else f" ({row['target_initial_value']:.2f}$\\to${row['target_value']:.2f})"), axis=1)
  204. df["social_entropy"] = np.exp(entropy(S,axis=1))
  205. df["intellectual_entropy"] = np.exp(entropy(expertise,axis=1))
  206. expertise_matrix = np.einsum("ki,kj->kij", expertise, expertise)
  207. social_expertise_matrix = np.einsum("ki,kj->kij", S_distrib, S_distrib)
  208. df["intellectual_stirling"] = 1-np.einsum("ij,kij->k", R, expertise_matrix)
  209. df["social_stirling"] = 1-np.einsum("ij,kij->k", R, social_expertise_matrix)
  210. stability = institution_stability()
  211. df = df.merge(stability, left_on="bai", right_index=True)
  212. df = df.merge(age(), left_on="bai", right_on="bai")
  213. df = df.merge(productivity(), left_on="bai", right_on="bai")
  214. df["productivity"] /= np.maximum(df["age"]-5, 10)
  215. df["productivity_solo"] /= np.maximum(df["age"]-5, 10)
  216. print(df["productivity_solo"])
  217. df["primary_research_area"] = x.argmax(axis=1)
  218. df["social_diversity"] = df[f"social_{args.diversity}"].fillna(0)
  219. df["intellectual_diversity"] = df[f"intellectual_{args.diversity}"].fillna(0)
  220. df["res_social_diversity"] = df["social_diversity"]-LinearRegression().fit(df[["intellectual_diversity"]], df["social_diversity"]).predict(df[["intellectual_diversity"]])
  221. data = {
  222. "N": len(df),
  223. "K": x.shape[1],
  224. "m": df[f"{args.metric}_score"],
  225. "soc_cap": np.log(1+S.sum(axis=1)) if args.power == "magnitude" else np.log(1+df["brokerage"].values),
  226. # "soc_cap": S.sum(axis=1) if args.power == "magnitude" else df["brokerage"].values,
  227. "soc_div": df["social_diversity"],
  228. "int_div": df["intellectual_diversity"],
  229. "res_soc_div": df["res_social_diversity"],
  230. "productivity": df["productivity"],
  231. "productivity_solo": df["productivity_solo"],
  232. "x": x,
  233. "initial_div": np.exp(entropy(x, axis=1)),
  234. "primary_research_area": df["primary_research_area"],
  235. "stable": df["stable"].astype(float).values,
  236. "age": df["age"].values
  237. }
  238. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  239. ax.hist(change[df["primary_research_area"] != 4], bins=np.linspace(0,1,25), histtype="step", label=f"Others ($\\mu={change[df['primary_research_area'] != 4].mean():.2f}$)", density=True)
  240. ax.hist(change[df["primary_research_area"] == 4], bins=np.linspace(0,1,25), histtype="step", label=f"Collider physics ($\\mu={change[df['primary_research_area'] == 4].mean():.2f}$)", density=True)
  241. ax.set_xlabel(f"Change score $c_a = \\frac{{1}}{{2}}\\sum_k |y_{{ak}}-x_{{ak}}|$")
  242. ax.set_ylabel("\\# of scientists")
  243. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  244. fig.savefig(opj(args.input, f"change_score_collider_physics{fla}.eps"), bbox_inches="tight")
  245. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  246. ax.hist(disruption[df["primary_research_area"] != 4], bins=np.linspace(0,1,25), histtype="step", label=f"Others ($\\mu={disruption[df['primary_research_area'] != 4].mean():.2f}$)", density=True)
  247. ax.hist(disruption[df["primary_research_area"] == 4], bins=np.linspace(0,1,25), histtype="step", label=f"Collider physics ($\\mu={disruption[df['primary_research_area'] == 4].mean():.2f}$)", density=True)
  248. ax.set_xlabel(f"Cognitive distance $d_a$")
  249. ax.set_ylabel("\\# of scientists")
  250. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  251. fig.savefig(opj(args.input, f"disruption_score_collider_physics{fla}.eps"), bbox_inches="tight")
  252. if not exists(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz")):
  253. model = CmdStanModel(
  254. stan_file=f"code/{args.metric}.stan" if args.model==""
  255. else f"code/{args.metric}_{args.model}_{args.power}.stan",
  256. )
  257. fit = model.sample(
  258. data=data,
  259. chains=4,
  260. iter_sampling=10000,
  261. iter_warmup=1000,
  262. show_console=True
  263. )
  264. vars = fit.stan_variables()
  265. samples = {}
  266. for (k, v) in vars.items():
  267. samples[k] = v
  268. np.savez_compressed(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz"), **samples)
  269. samples = np.load(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz"))
  270. labels = [
  271. "Intellectual capital (diversity)",
  272. "Social capital (diversity)",
  273. "Social capital (power)",
  274. "Stable affiliation",
  275. "Academic age",
  276. "Productivity (co-authored)",
  277. "Productivity (solo-authored)",
  278. ]
  279. labels = [f"\\textbf{{{label}}}" for label in labels]
  280. labels += topics
  281. names = [
  282. "beta_int_div", "beta_soc_div", "beta_soc_cap", "beta_stable", "beta_age", "beta_productivity", "beta_productivity_solo"
  283. ]
  284. if args.metric not in ["entered", "exited"] and args.metric not in ["change", "disruption"]:
  285. mu = np.array([samples[name].mean() for name in names] + [(samples["beta_x"][:,i]*samples["tau"]).mean() for i in range(x.shape[1])])
  286. low = np.array([np.quantile(samples[name], q=0.05/2) for name in names] + [np.quantile(samples["beta_x"][:,i]*samples["tau"], q=0.05/2) for i in range(x.shape[1])])
  287. up = np.array([np.quantile(samples[name], q=1-0.05/2) for name in names] + [np.quantile(samples["beta_x"][:,i]*samples["tau"], q=1-0.05/2) for i in range(x.shape[1])])
  288. sig = up*low>0
  289. prob = np.array([(samples[name]*np.sign(samples[name].mean())<0).mean() for name in names] + [((samples["beta_x"][:,i]*np.sign(samples["beta_x"][:,i].mean()))<0).mean() for i in range(x.shape[1])])
  290. keep = sig | (np.arange(len(sig))<len(names))
  291. mu = mu[keep]
  292. low = low[keep]
  293. up = up[keep]
  294. prob = prob[keep]
  295. sign = ["<" if _mu>0 else ">" for i, _mu in enumerate(mu)]
  296. labels = [label for i, label in enumerate(labels) if keep[i]]
  297. n_vars = len(labels)
  298. # effect of capital and controls
  299. fig, ax = plt.subplots(figsize=[6.4, 0.4*(1+n_vars)])
  300. ax.scatter(mu, np.arange(len(labels))[::-1])
  301. ax.errorbar(mu, np.arange(len(labels))[::-1], xerr=(mu-low,up-mu), ls="none", capsize=4, elinewidth=1)
  302. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  303. for i, p in enumerate(prob):
  304. if p>1e-4 and np.abs(p-0.5)>0.4:
  305. ax.text(
  306. -0.02 if mu[i]>0 else 0.02,
  307. np.arange(len(labels))[::-1][i],
  308. f"\\scriptsize $\\mu(\\beta)={mu[i]:.2g}, P(\\beta{sign[i]}0)={p:.2g}$",
  309. ha="right" if mu[i]>0 else "left",
  310. va="center"
  311. )
  312. elif p<0.05/2 or p>1-0.05/2:
  313. ax.text(
  314. -0.02 if mu[i]>0 else 0.02,
  315. np.arange(len(labels))[::-1][i],
  316. f"\\scriptsize $\\mu(\\beta)={mu[i]:.2g}$",
  317. ha="right" if mu[i]>0 else "left",
  318. va="center"
  319. )
  320. ax.set_xlabel(f"Effect on {args.metric}")
  321. ax.axvline(0, color="black")
  322. low, high = ax.get_xlim()
  323. bound = max(abs(low), abs(high))
  324. ax.set_xlim(-bound, bound)
  325. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{fla}.eps"), bbox_inches="tight")
  326. # average change score per research area
  327. ratio = args.metric != "diversification"
  328. labels = topics
  329. if ratio:
  330. mu = np.array([(samples["mu_x"][:,i]/samples["mu_pop"]).mean() for i in range(x.shape[1])])
  331. low = np.array([np.quantile(samples["mu_x"][:,i]/samples["mu_pop"], q=0.05/2) for i in range(x.shape[1])])
  332. up = np.array([np.quantile(samples["mu_x"][:,i]/samples["mu_pop"], q=1-0.05/2) for i in range(x.shape[1])])
  333. sig = (up-1)*(low-1)>0
  334. else:
  335. mu = np.array([(samples["mu_x"][:,i]-samples["mu_pop"]).mean() for i in range(x.shape[1])])
  336. low = np.array([np.quantile(samples["mu_x"][:,i]-samples["mu_pop"], q=0.05/2) for i in range(x.shape[1])])
  337. up = np.array([np.quantile(samples["mu_x"][:,i]-samples["mu_pop"], q=1-0.05/2) for i in range(x.shape[1])])
  338. sig = (up)*(low)>0
  339. keep = sig
  340. mu = mu[keep]
  341. low = low[keep]
  342. up = up[keep]
  343. labels = [label for i, label in enumerate(labels) if keep[i]]
  344. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  345. ax.scatter(mu, np.arange(len(labels))[::-1])
  346. ax.errorbar(mu, np.arange(len(labels))[::-1], xerr=(mu-low,up-mu), ls="none", capsize=4, elinewidth=1)
  347. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  348. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  349. df["m_ratio"] = df[f"{args.metric}_score"]/df[f"{args.metric}_score"].mean()
  350. research_areas = df.groupby("primary_research_area").agg(
  351. mu=("m_ratio", "mean"),
  352. low=("m_ratio", lambda x: np.quantile(x, q=0.05/2)),
  353. up=("m_ratio", lambda x: np.quantile(x, q=1-0.05/2)),
  354. label=("origin_label", lambda x: x.iloc[0])
  355. ).reset_index()
  356. low, high = ax.get_xlim()
  357. bound = max(abs(low), abs(high))
  358. ax.set_xlim(-bound, bound)
  359. ax.scatter(research_areas["mu"], research_areas.index)
  360. ax.errorbar(research_areas["mu"], research_areas.index, xerr=(research_areas["mu"]-research_areas["low"],research_areas["up"]-research_areas["low"]), ls="none", capsize=4, elinewidth=1)
  361. ax.set_yticks(research_areas.index, research_areas["label"])
  362. ax.set_xlabel(f"Ratio to average {args.metric} score" if ratio else f"Difference with average {args.metric} score")
  363. ax.axvline(1 if ratio else 0, color="black")
  364. fig.savefig(opj(args.input, f"{args.metric}_research_area{fla}.eps"), bbox_inches="tight")
  365. elif args.metric in ["change", "disruption"]:
  366. labels = [
  367. "Intellectual capital (diversity)",
  368. "Social capital (diversity)",
  369. "Social capital (power)",
  370. "Stable affiliation",
  371. "Academic age",
  372. "Productivity (co-authored)",
  373. "Productivity (solo-authored)",
  374. ]
  375. names = [
  376. "beta_int_div", "beta_soc_div", "beta_soc_cap", "beta_stable", "beta_age", "beta_productivity", "beta_productivity_solo"
  377. ]
  378. if not args.compact:
  379. labels = [f"\\textbf{{{label}}}" for label in labels]
  380. labels += topics
  381. samples = [
  382. np.load(opj(args.input, f"samples_change_{args.diversity}_{args.power}{fla}.npz")),
  383. np.load(opj(args.input, f"samples_disruption_{args.diversity}_{args.power}{fla}.npz"))
  384. ]
  385. mu = [None, None]
  386. low = [None, None]
  387. up = [None, None]
  388. sig = [None, None]
  389. prob = [None, None]
  390. for i in range(2):
  391. mu[i] = np.array([samples[i][name].mean() for name in names] + [(samples[i]["beta_x"][:,j]*samples[i]["tau"]).mean() for j in range(x.shape[1])])
  392. low[i] = np.array([np.quantile(samples[i][name], q=0.05/2) for name in names] + [np.quantile(samples[i]["beta_x"][:,j]*samples[i]["tau"], q=0.05/2) for j in range(x.shape[1])])
  393. up[i] = np.array([np.quantile(samples[i][name], q=1-0.05/2) for name in names] + [np.quantile(samples[i]["beta_x"][:,j]*samples[i]["tau"], q=1-0.05/2) for j in range(x.shape[1])])
  394. sig[i] = up[i]*low[i]>0
  395. prob[i] = np.array([(samples[i][name]*np.sign(samples[i][name].mean())<0).mean() for name in names] + [((samples[i]["beta_x"][:,j]*np.sign(samples[i]["beta_x"][:,j].mean()))<0).mean() for j in range(x.shape[1])])
  396. if args.compact:
  397. keep = (np.arange(len(sig[0]))<len(names))
  398. else:
  399. keep = sig[0] | sig[1] | (np.arange(len(sig[0]))<len(names))
  400. for i in range(2):
  401. mu[i] = mu[i][keep]
  402. low[i] = low[i][keep]
  403. up[i] = up[i][keep]
  404. prob[i] = prob[i][keep]
  405. sign = [["<" if _mu>0 else ">" for j, _mu in enumerate(mu[i])] for i in range(2)]
  406. labels = [label for i, label in enumerate(labels) if keep[i]]
  407. n_vars = len(labels)
  408. if args.compact:
  409. labels = [
  410. '\n'.join(map(lambda x: f"\\textbf{{{x}}}", wrap(label, width=15))) if i < 4
  411. else
  412. '\n'.join(wrap(label, width=15))
  413. for i, label in enumerate(labels)
  414. ]
  415. print(labels)
  416. # effect of capital and controls
  417. fig, ax = plt.subplots(figsize=[4.8 if args.compact else 6.4, 0.52*(1+n_vars)])
  418. colors = ['#377eb8', '#ff7f00']
  419. legend = ["change ($c_a$)", "cognitive distance ($d_a$)"]
  420. for j in range(2):
  421. R2 = samples[j]["R2"].mean()
  422. dy = -0.125 if j else +0.125
  423. ax.scatter(mu[j], np.arange(len(labels))[::-1]+dy, color=colors[j])
  424. ax.errorbar(mu[j], np.arange(len(labels))[::-1]+dy, xerr=(mu[j]-low[j],up[j]-mu[j]), ls="none", capsize=4, elinewidth=1, color=colors[j], label=f"{legend[j]}, $R^2={R2:.2f}$")
  425. for i, p in enumerate(prob[j]):
  426. significant = p<0.05/2
  427. if p>1e-4 and np.abs(p-0.5)>0.4 and significant:
  428. ax.text(
  429. -0.02 if mu[j][i]>0 else 0.02,
  430. np.arange(len(labels))[::-1][i]+dy,
  431. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g},P(\\beta{sign[j][i]}0)={p:.2g}$",
  432. ha="right" if mu[j][i]>0 else "left",
  433. va="center"
  434. )
  435. elif p>1e-4 and np.abs(p-0.5)>0.4 and (not significant):
  436. ax.text(
  437. -0.02 if mu[j][i]>0 else 0.02,
  438. np.arange(len(labels))[::-1][i]+dy,
  439. f"\\scriptsize $P(\\beta{sign[j][i]}0)={p:.2g}$",
  440. ha="right" if mu[j][i]>0 else "left",
  441. va="center"
  442. )
  443. elif significant:
  444. ax.text(
  445. -0.02 if mu[j][i]>0 else 0.02,
  446. np.arange(len(labels))[::-1][i]+dy,
  447. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g}$",
  448. ha="right" if mu[j][i]>0 else "left",
  449. va="center"
  450. )
  451. low, high = ax.get_xlim()
  452. bound = max(abs(low), abs(high))
  453. ax.set_xlim(-bound, bound)
  454. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  455. ax.set_xlabel(f"Effect size (standard deviations)")
  456. ax.axvline(0, color="black")
  457. if args.compact:
  458. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.3))
  459. else:
  460. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  461. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.eps"), bbox_inches="tight")
  462. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.pdf"), bbox_inches="tight")
  463. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.png"), bbox_inches="tight", dpi=300)
  464. else:
  465. labels = [
  466. "Intellectual capital (diversity)",
  467. "Social capital (diversity)",
  468. "Social capital (power)",
  469. "Stable affiliation",
  470. "Academic age",
  471. "Productivity (co-authored)",
  472. "Productivity (solo-authored)",
  473. ]
  474. if not args.compact:
  475. labels = [f"\\textbf{{{label}}}" for label in labels]
  476. labels += topics
  477. samples = [
  478. np.load(opj(args.input, f"samples_entered_{args.diversity}_{args.power}{fla}.npz")),
  479. np.load(opj(args.input, f"samples_exited_{args.diversity}_{args.power}{fla}.npz"))
  480. ]
  481. mu = [None, None]
  482. low = [None, None]
  483. up = [None, None]
  484. sig = [None, None]
  485. prob = [None, None]
  486. for i in range(2):
  487. mu[i] = np.array([samples[i][name].mean() for name in names] + [(samples[i]["beta_x"][:,j]*samples[i]["tau"]).mean() for j in range(x.shape[1])])
  488. low[i] = np.array([np.quantile(samples[i][name], q=0.05/2) for name in names] + [np.quantile(samples[i]["beta_x"][:,j]*samples[i]["tau"], q=0.05/2) for j in range(x.shape[1])])
  489. up[i] = np.array([np.quantile(samples[i][name], q=1-0.05/2) for name in names] + [np.quantile(samples[i]["beta_x"][:,j]*samples[i]["tau"], q=1-0.05/2) for j in range(x.shape[1])])
  490. sig[i] = up[i]*low[i]>0
  491. prob[i] = np.array([(samples[i][name]*np.sign(samples[i][name].mean())<0).mean() for name in names] + [((samples[i]["beta_x"][:,j]*np.sign(samples[i]["beta_x"][:,j].mean()))<0).mean() for j in range(x.shape[1])])
  492. if args.compact:
  493. keep = (np.arange(len(sig[0]))<len(names))
  494. else:
  495. keep = sig[0] | sig[1] | (np.arange(len(sig[0]))<len(names))
  496. for i in range(2):
  497. mu[i] = mu[i][keep]
  498. low[i] = low[i][keep]
  499. up[i] = up[i][keep]
  500. prob[i] = prob[i][keep]
  501. sign = [["<" if _mu>0 else ">" for j, _mu in enumerate(mu[i])] for i in range(2)]
  502. labels = [label for i, label in enumerate(labels) if keep[i]]
  503. n_vars = len(labels)
  504. if args.compact:
  505. labels = [
  506. '\n'.join(map(lambda x: f"\\textbf{{{x}}}", wrap(label, width=15))) if i < 4
  507. else
  508. '\n'.join(wrap(label, width=15))
  509. for i, label in enumerate(labels)
  510. ]
  511. print(labels)
  512. # effect of capital and controls
  513. fig, ax = plt.subplots(figsize=[4.8 if args.compact else 6.4, 0.52*(1+n_vars)])
  514. colors = ['#377eb8', '#ff7f00']
  515. legend = ["entered new research area", "exited research area"]
  516. if args.compact:
  517. ax.set_xlim(-0.9, 1.25)
  518. for j in range(2):
  519. dy = -0.125 if j else +0.125
  520. ax.scatter(mu[j], np.arange(len(labels))[::-1]+dy, color=colors[j])
  521. ax.errorbar(mu[j], np.arange(len(labels))[::-1]+dy, xerr=(mu[j]-low[j],up[j]-mu[j]), ls="none", capsize=4, elinewidth=1, color=colors[j], label=legend[j])
  522. for i, p in enumerate(prob[j]):
  523. significant = p<0.05/2
  524. if p>1e-4 and np.abs(p-0.5)>0.4 and significant:
  525. ax.text(
  526. -0.02 if mu[j][i]>0 else 0.02,
  527. np.arange(len(labels))[::-1][i]+dy,
  528. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g},P(\\beta{sign[j][i]}0)={p:.2g}$",
  529. ha="right" if mu[j][i]>0 else "left",
  530. va="center"
  531. )
  532. elif p>1e-4 and np.abs(p-0.5)>0.4 and (not significant):
  533. ax.text(
  534. -0.02 if mu[j][i]>0 else 0.02,
  535. np.arange(len(labels))[::-1][i]+dy,
  536. f"\\scriptsize $P(\\beta{sign[j][i]}0)={p:.2g}$",
  537. ha="right" if mu[j][i]>0 else "left",
  538. va="center"
  539. )
  540. elif significant:
  541. ax.text(
  542. -0.02 if mu[j][i]>0 else 0.02,
  543. np.arange(len(labels))[::-1][i]+dy,
  544. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g}$",
  545. ha="right" if mu[j][i]>0 else "left",
  546. va="center"
  547. )
  548. low, high = ax.get_xlim()
  549. bound = max(abs(low), abs(high))
  550. ax.set_xlim(-bound, bound)
  551. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  552. ax.set_xlabel(f"Effect size (log odds ratio)")
  553. ax.axvline(0, color="black")
  554. if args.compact:
  555. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.3))
  556. else:
  557. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  558. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.eps"), bbox_inches="tight")
  559. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.pdf"), bbox_inches="tight")
  560. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.png"), bbox_inches="tight", dpi=300)
  561. table = df[["bai", "stable", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"]].sort_values(f"{args.metric}_score", ascending=False)
  562. table.to_csv(opj(args.input, f"{args.metric}_scores.csv"))
  563. table["bai"] = table["bai"].str.replace(".1", "")
  564. table["bai"] = table["bai"].str.replace(r"^([A-Z])\.", r"\1.~")
  565. table["bai"] = table["bai"].str.replace(r"\.\~([A-Z])\.", r".~\1.~")
  566. table["bai"] = table["bai"].str.replace(r"([a-zA-Z]{2,})\.", r"\1 ")
  567. table["bai"] = table.apply(lambda r: r["bai"] if not r["stable"] else f"{r['bai']} ($\\ast$)", axis=1)
  568. table["target_label"] += "EOL"
  569. latex = table.head(20).to_latex(
  570. columns=["bai", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"],
  571. header=["Physicist", "$c_a$", "$D(\\bm{I_a})$", "$D(\\bm{S_a})$", "Previous main area", "Current main area"],
  572. index=False,
  573. multirow=True,
  574. multicolumn=True,
  575. column_format='p{0.15\\textwidth}|c|c|c|b{0.25\\textwidth}|b{0.25\\textwidth}',
  576. escape=False,
  577. float_format=lambda x: f"{x:.2f}",
  578. caption="Physicists with the highest change scores $c_a$. $D(\\bm{I_a})$ and $D(\\bm{S_a})$ measure the diversity of intellectual and social capital. Numbers in parentheses indicate the share of attention dedicated to each research area during each time-period. Asterisks ($\\ast$) indicate physicists with a permanent position.",
  579. label=f"table:top_{args.metric}",
  580. position="H"
  581. )
  582. latex = latex.replace('EOL \\\\\n', '\\\\ \\hline\n')
  583. with open(opj(args.input, f"top_{args.metric}.tex"), "w+") as fp:
  584. fp.write(latex)
  585. latex = table.sort_values(f"{args.metric}_score", ascending=True).head(20).to_latex(
  586. columns=["bai", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"],
  587. header=["Physicist", "$c_a$", "$D(\\bm{I_a})$", "$D(\\bm{S_a})$", "Previous main area", "Current main area"],
  588. index=False,
  589. multirow=True,
  590. multicolumn=True,
  591. column_format='p{0.15\\textwidth}|c|c|c|b{0.25\\textwidth}|b{0.25\\textwidth}',
  592. escape=False,
  593. float_format=lambda x: f"{x:.2f}",
  594. caption="Physicists with the lowest change scores $c_a$. $D(\\bm{I_a})$ and $D(\\bm{S_a})$ measure the diversity of intellectual and social capital. Numbers in parentheses indicate the share of attention dedicated to each research area. Asterisks ($\\ast$) indicate physicists with a permanent position.",
  595. label=f"table:low_{args.metric}",
  596. position="H"
  597. )
  598. latex = latex.replace('EOL \\\\\n', '\\\\ \\hline\n')
  599. with open(opj(args.input, f"low_{args.metric}.tex"), "w+") as fp:
  600. fp.write(latex)