comparative_analysis.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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)]
  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. NR = np.stack(df[[f"start_{k+1}" for k in range(n_topics)]].values).astype(int)
  132. NC = np.stack(df[[f"end_{k+1}" for k in range(n_topics)]].values).astype(int)
  133. expertise = np.stack(df[[f"expertise_{k+1}" for k in range(n_topics)]].values)
  134. S = np.stack(df["pooled_resources"])
  135. brokerage = pd.read_csv("output/authors_brokerage.csv")
  136. df = df.merge(brokerage, left_on="bai", right_on="bai")
  137. NR = NR[:,~junk]
  138. NC = NC[:,~junk]
  139. expertise = expertise[:,~junk]
  140. S = S[:,~junk]
  141. x = NR/NR.sum(axis=1)[:,np.newaxis]
  142. y = NC/NC.sum(axis=1)[:,np.newaxis]
  143. S_distrib = S/S.sum(axis=1)[:,np.newaxis]
  144. R = np.array([
  145. [((expertise[:,i]>expertise[:,i].mean())&(expertise[:,j]>expertise[:,j].mean())).mean()/(expertise[:,i]>expertise[:,i].mean()).mean() for j in range(len(topics))]
  146. for i in range(len(topics))
  147. ])
  148. change = np.abs(y-x).sum(axis=1)/2
  149. diversification = (np.exp(entropy(y, axis=1))-np.exp(entropy(x, axis=1)))/x.shape[1]
  150. x_matrix = np.einsum("ki,kj->kij", x, x)
  151. y_matrix = np.einsum("ki,kj->kij", y, y)
  152. x_stirling = 1-np.einsum("ij,kij->k", R, x_matrix)
  153. y_stirling = 1-np.einsum("ij,kij->k", R, y_matrix)
  154. cost_matrix = np.load(opj(args.input, f"cost_knowledge_bounded.npz"))["C"].mean(axis=0)
  155. print(cost_matrix.sum())
  156. cost_matrix = cost_matrix*(1-np.eye(x.shape[1])).sum()/cost_matrix.sum()
  157. disruption = np.zeros(len(change))
  158. for a in range(len(change)):
  159. # disruption[a] = ot.emd2(x[a,:].copy(order='C'), y[a,:].copy(order='C'), 1-R, processes=4)
  160. disruption[a] = ot.emd2(x[a,:].copy(order='C'), y[a,:].copy(order='C'), cost_matrix, processes=4)
  161. alpha = 1
  162. exited = ((x>alpha*x.mean(axis=0))&(y<alpha*y.mean(axis=0))).sum(axis=1)
  163. entered = ((x<alpha*x.mean(axis=0))&(y>alpha*y.mean(axis=0))).sum(axis=1)
  164. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  165. ax.hist(change, bins=np.linspace(0,1,50), histtype="step", color = '#377eb8', label="Change score $c_a$")
  166. ax.hist(disruption, bins=np.linspace(0,1,50), histtype="step", color = '#ff7f00', label="Cognitive distance $d_a$")
  167. ax.set_xlabel(f"Change score $c_a$ and cognitive distance $d_a$")
  168. ax.set_ylabel("\\# of scientists")
  169. ax.legend()
  170. fig.savefig(opj(args.input, f"change_disruption_score{fla}.eps"), bbox_inches="tight")
  171. print("change 50%% interval: ", np.quantile(change,q=0.25), np.quantile(change,q=1-0.25))
  172. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  173. ax.hist(diversification, bins=np.linspace(-0.5,0.5,50), histtype="step")
  174. ax.set_xlabel(f"Diversification score $\\Delta_a$")
  175. ax.set_ylabel("\\# of scientists")
  176. fig.savefig(opj(args.input, f"diversification_score{fla}.eps"), bbox_inches="tight")
  177. fig, ax = plt.subplots()
  178. ax.hist(disruption, bins=np.linspace(0,1,50), histtype="step")
  179. ax.set_xlabel(f"Disruption score $d_a$")
  180. ax.set_ylabel("\\# of scientists")
  181. fig.savefig(opj(args.input, f"disruption_score{fla}.eps"), bbox_inches="tight")
  182. df["change_score"] = change
  183. df["disruption_score"] = disruption
  184. df["diversification_score"] = diversification
  185. df["diversification_stirling_score"] = y_stirling-x_stirling
  186. df["entered_score"] = (entered>0).astype(int)
  187. df["exited_score"] = (exited>0).astype(int)
  188. df["exited_total_power_effect_score"] = (exited>0).astype(int)
  189. df["origin"] = np.argmax(x, axis=1)
  190. df["target"] = np.argmax(y, axis=1)
  191. df["origin_value"] = x.max(axis=1)
  192. df["target_value"] = y.max(axis=1)
  193. df["origin_final_value"] = np.array(y[a,df.loc[a, "origin"]] for a in range(x.shape[0]))
  194. df["target_initial_value"] = np.array(x[a,df.loc[a, "target"]] for a in range(x.shape[0]))
  195. df["origin_label"] = df["origin"].apply(lambda k: topics[k])
  196. df["target_label"] = df["target"].apply(lambda k: topics[k])
  197. 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)
  198. 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)
  199. df["social_entropy"] = np.exp(entropy(S,axis=1))
  200. df["intellectual_entropy"] = np.exp(entropy(expertise,axis=1))
  201. expertise_matrix = np.einsum("ki,kj->kij", expertise, expertise)
  202. social_expertise_matrix = np.einsum("ki,kj->kij", S_distrib, S_distrib)
  203. df["intellectual_stirling"] = 1-np.einsum("ij,kij->k", R, expertise_matrix)
  204. df["social_stirling"] = 1-np.einsum("ij,kij->k", R, social_expertise_matrix)
  205. stability = institution_stability()
  206. df = df.merge(stability, left_on="bai", right_index=True)
  207. df = df.merge(age(), left_on="bai", right_on="bai")
  208. df = df.merge(productivity(), left_on="bai", right_on="bai")
  209. df["productivity"] /= np.maximum(df["age"]-5, 10)
  210. df["productivity_solo"] /= np.maximum(df["age"]-5, 10)
  211. print(df["productivity_solo"])
  212. df["primary_research_area"] = x.argmax(axis=1)
  213. df["social_diversity"] = df[f"social_{args.diversity}"].fillna(0)
  214. df["intellectual_diversity"] = df[f"intellectual_{args.diversity}"].fillna(0)
  215. df["res_social_diversity"] = df["social_diversity"]-LinearRegression().fit(df[["intellectual_diversity"]], df["social_diversity"]).predict(df[["intellectual_diversity"]])
  216. data = {
  217. "N": len(df),
  218. "K": x.shape[1],
  219. "m": df[f"{args.metric}_score"],
  220. "soc_cap": np.log(1+S.sum(axis=1)) if args.power == "magnitude" else np.log(1+df["brokerage"].values),
  221. # "soc_cap": S.sum(axis=1) if args.power == "magnitude" else df["brokerage"].values,
  222. "soc_div": df["social_diversity"],
  223. "int_div": df["intellectual_diversity"],
  224. "res_soc_div": df["res_social_diversity"],
  225. "productivity": df["productivity"],
  226. "productivity_solo": df["productivity_solo"],
  227. "x": x,
  228. "initial_div": np.exp(entropy(x, axis=1)),
  229. "primary_research_area": df["primary_research_area"],
  230. "stable": df["stable"].astype(float).values,
  231. "age": df["age"].values
  232. }
  233. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  234. 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)
  235. 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)
  236. ax.set_xlabel(f"Change score $c_a = \\frac{{1}}{{2}}\\sum_k |y_{{ak}}-x_{{ak}}|$")
  237. ax.set_ylabel("\\# of scientists")
  238. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  239. fig.savefig(opj(args.input, f"change_score_collider_physics{fla}.eps"), bbox_inches="tight")
  240. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  241. 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)
  242. 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)
  243. ax.set_xlabel(f"Cognitive distance $d_a$")
  244. ax.set_ylabel("\\# of scientists")
  245. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  246. fig.savefig(opj(args.input, f"disruption_score_collider_physics{fla}.eps"), bbox_inches="tight")
  247. if not exists(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz")):
  248. model = CmdStanModel(
  249. stan_file=f"code/{args.metric}.stan" if args.model==""
  250. else f"code/{args.metric}_{args.model}_{args.power}.stan",
  251. )
  252. fit = model.sample(
  253. data=data,
  254. chains=4,
  255. iter_sampling=10000,
  256. iter_warmup=1000,
  257. show_console=True
  258. )
  259. vars = fit.stan_variables()
  260. samples = {}
  261. for (k, v) in vars.items():
  262. samples[k] = v
  263. np.savez_compressed(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz"), **samples)
  264. samples = np.load(opj(args.input, f"samples_{args.metric}_{args.diversity}_{args.power}{fla}.npz"))
  265. labels = [
  266. "Intellectual capital (diversity)",
  267. "Social capital (diversity)",
  268. "Social capital (power)",
  269. "Stable affiliation",
  270. "Academic age",
  271. "Productivity (co-authored)",
  272. "Productivity (solo-authored)",
  273. ]
  274. labels = [f"\\textbf{{{label}}}" for label in labels]
  275. labels += topics
  276. names = [
  277. "beta_int_div", "beta_soc_div", "beta_soc_cap", "beta_stable", "beta_age", "beta_productivity", "beta_productivity_solo"
  278. ]
  279. if args.metric not in ["entered", "exited"] and args.metric not in ["change", "disruption"]:
  280. mu = np.array([samples[name].mean() for name in names] + [(samples["beta_x"][:,i]*samples["tau"]).mean() for i in range(x.shape[1])])
  281. 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])])
  282. 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])])
  283. sig = up*low>0
  284. 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])])
  285. keep = sig | (np.arange(len(sig))<len(names))
  286. mu = mu[keep]
  287. low = low[keep]
  288. up = up[keep]
  289. prob = prob[keep]
  290. sign = ["<" if _mu>0 else ">" for i, _mu in enumerate(mu)]
  291. labels = [label for i, label in enumerate(labels) if keep[i]]
  292. n_vars = len(labels)
  293. # effect of capital and controls
  294. fig, ax = plt.subplots(figsize=[6.4, 0.4*(1+n_vars)])
  295. ax.scatter(mu, np.arange(len(labels))[::-1])
  296. ax.errorbar(mu, np.arange(len(labels))[::-1], xerr=(mu-low,up-mu), ls="none", capsize=4, elinewidth=1)
  297. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  298. for i, p in enumerate(prob):
  299. if p>1e-4 and np.abs(p-0.5)>0.4:
  300. ax.text(
  301. -0.02 if mu[i]>0 else 0.02,
  302. np.arange(len(labels))[::-1][i],
  303. f"\\scriptsize $\\mu(\\beta)={mu[i]:.2g}, P(\\beta{sign[i]}0)={p:.2g}$",
  304. ha="right" if mu[i]>0 else "left",
  305. va="center"
  306. )
  307. elif p<0.05/2 or p>1-0.05/2:
  308. ax.text(
  309. -0.02 if mu[i]>0 else 0.02,
  310. np.arange(len(labels))[::-1][i],
  311. f"\\scriptsize $\\mu(\\beta)={mu[i]:.2g}$",
  312. ha="right" if mu[i]>0 else "left",
  313. va="center"
  314. )
  315. ax.set_xlabel(f"Effect on {args.metric}")
  316. ax.axvline(0, color="black")
  317. low, high = ax.get_xlim()
  318. bound = max(abs(low), abs(high))
  319. ax.set_xlim(-bound, bound)
  320. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{fla}.eps"), bbox_inches="tight")
  321. # average change score per research area
  322. ratio = args.metric != "diversification"
  323. labels = topics
  324. if ratio:
  325. mu = np.array([(samples["mu_x"][:,i]/samples["mu_pop"]).mean() for i in range(x.shape[1])])
  326. low = np.array([np.quantile(samples["mu_x"][:,i]/samples["mu_pop"], q=0.05/2) for i in range(x.shape[1])])
  327. up = np.array([np.quantile(samples["mu_x"][:,i]/samples["mu_pop"], q=1-0.05/2) for i in range(x.shape[1])])
  328. sig = (up-1)*(low-1)>0
  329. else:
  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)*(low)>0
  334. keep = sig
  335. mu = mu[keep]
  336. low = low[keep]
  337. up = up[keep]
  338. labels = [label for i, label in enumerate(labels) if keep[i]]
  339. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  340. ax.scatter(mu, np.arange(len(labels))[::-1])
  341. ax.errorbar(mu, np.arange(len(labels))[::-1], xerr=(mu-low,up-mu), ls="none", capsize=4, elinewidth=1)
  342. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  343. fig, ax = plt.subplots(figsize=[6.4, 3.2])
  344. df["m_ratio"] = df[f"{args.metric}_score"]/df[f"{args.metric}_score"].mean()
  345. research_areas = df.groupby("primary_research_area").agg(
  346. mu=("m_ratio", "mean"),
  347. low=("m_ratio", lambda x: np.quantile(x, q=0.05/2)),
  348. up=("m_ratio", lambda x: np.quantile(x, q=1-0.05/2)),
  349. label=("origin_label", lambda x: x.iloc[0])
  350. ).reset_index()
  351. low, high = ax.get_xlim()
  352. bound = max(abs(low), abs(high))
  353. ax.set_xlim(-bound, bound)
  354. ax.scatter(research_areas["mu"], research_areas.index)
  355. 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)
  356. ax.set_yticks(research_areas.index, research_areas["label"])
  357. ax.set_xlabel(f"Ratio to average {args.metric} score" if ratio else f"Difference with average {args.metric} score")
  358. ax.axvline(1 if ratio else 0, color="black")
  359. fig.savefig(opj(args.input, f"{args.metric}_research_area{fla}.eps"), bbox_inches="tight")
  360. elif args.metric in ["change", "disruption"]:
  361. labels = [
  362. "Intellectual capital (diversity)",
  363. "Social capital (diversity)",
  364. "Social capital (power)",
  365. "Stable affiliation",
  366. "Academic age",
  367. "Productivity (co-authored)",
  368. "Productivity (solo-authored)",
  369. ]
  370. names = [
  371. "beta_int_div", "beta_soc_div", "beta_soc_cap", "beta_stable", "beta_age", "beta_productivity", "beta_productivity_solo"
  372. ]
  373. if not args.compact:
  374. labels = [f"\\textbf{{{label}}}" for label in labels]
  375. labels += topics
  376. samples = [
  377. np.load(opj(args.input, f"samples_change_{args.diversity}_{args.power}{fla}.npz")),
  378. np.load(opj(args.input, f"samples_disruption_{args.diversity}_{args.power}{fla}.npz"))
  379. ]
  380. mu = [None, None]
  381. low = [None, None]
  382. up = [None, None]
  383. sig = [None, None]
  384. prob = [None, None]
  385. for i in range(2):
  386. 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])])
  387. 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])])
  388. 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])])
  389. sig[i] = up[i]*low[i]>0
  390. 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])])
  391. if args.compact:
  392. keep = (np.arange(len(sig[0]))<len(names))
  393. else:
  394. keep = sig[0] | sig[1] | (np.arange(len(sig[0]))<len(names))
  395. for i in range(2):
  396. mu[i] = mu[i][keep]
  397. low[i] = low[i][keep]
  398. up[i] = up[i][keep]
  399. prob[i] = prob[i][keep]
  400. sign = [["<" if _mu>0 else ">" for j, _mu in enumerate(mu[i])] for i in range(2)]
  401. labels = [label for i, label in enumerate(labels) if keep[i]]
  402. n_vars = len(labels)
  403. if args.compact:
  404. labels = [
  405. '\n'.join(map(lambda x: f"\\textbf{{{x}}}", wrap(label, width=15))) if i < 4
  406. else
  407. '\n'.join(wrap(label, width=15))
  408. for i, label in enumerate(labels)
  409. ]
  410. print(labels)
  411. # effect of capital and controls
  412. fig, ax = plt.subplots(figsize=[4.8 if args.compact else 6.4, 0.52*(1+n_vars)])
  413. colors = ['#377eb8', '#ff7f00']
  414. legend = ["change ($c_a$)", "cognitive distance ($d_a$)"]
  415. if args.compact:
  416. ax.set_xlim(-0.9, 1.25)
  417. for j in range(2):
  418. R2 = samples[j]["R2"].mean()
  419. dy = -0.125 if j else +0.125
  420. ax.scatter(mu[j], np.arange(len(labels))[::-1]+dy, color=colors[j])
  421. 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}$")
  422. for i, p in enumerate(prob[j]):
  423. significant = p<0.05/2
  424. if p>1e-4 and np.abs(p-0.5)>0.4 and significant:
  425. ax.text(
  426. -0.02 if mu[j][i]>0 else 0.02,
  427. np.arange(len(labels))[::-1][i]+dy,
  428. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g},P(\\beta{sign[j][i]}0)={p:.2g}$",
  429. ha="right" if mu[j][i]>0 else "left",
  430. va="center"
  431. )
  432. elif p>1e-4 and np.abs(p-0.5)>0.4 and (not significant):
  433. ax.text(
  434. -0.02 if mu[j][i]>0 else 0.02,
  435. np.arange(len(labels))[::-1][i]+dy,
  436. f"\\scriptsize $P(\\beta{sign[j][i]}0)={p:.2g}$",
  437. ha="right" if mu[j][i]>0 else "left",
  438. va="center"
  439. )
  440. elif significant:
  441. ax.text(
  442. -0.02 if mu[j][i]>0 else 0.02,
  443. np.arange(len(labels))[::-1][i]+dy,
  444. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g}$",
  445. ha="right" if mu[j][i]>0 else "left",
  446. va="center"
  447. )
  448. low, high = ax.get_xlim()
  449. bound = max(abs(low), abs(high))
  450. ax.set_xlim(-bound, bound)
  451. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  452. ax.set_xlabel(f"Effect size (standard deviations)")
  453. ax.axvline(0, color="black")
  454. if args.compact:
  455. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.3))
  456. else:
  457. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  458. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.eps"), bbox_inches="tight")
  459. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.pdf"), bbox_inches="tight")
  460. 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)
  461. else:
  462. labels = [
  463. "Intellectual capital (diversity)",
  464. "Social capital (diversity)",
  465. "Social capital (power)",
  466. "Stable affiliation",
  467. "Academic age",
  468. "Productivity (co-authored)",
  469. "Productivity (solo-authored)",
  470. ]
  471. if not args.compact:
  472. labels = [f"\\textbf{{{label}}}" for label in labels]
  473. labels += topics
  474. samples = [
  475. np.load(opj(args.input, f"samples_entered_{args.diversity}_{args.power}{fla}.npz")),
  476. np.load(opj(args.input, f"samples_exited_{args.diversity}_{args.power}{fla}.npz"))
  477. ]
  478. mu = [None, None]
  479. low = [None, None]
  480. up = [None, None]
  481. sig = [None, None]
  482. prob = [None, None]
  483. for i in range(2):
  484. 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])])
  485. 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])])
  486. 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])])
  487. sig[i] = up[i]*low[i]>0
  488. 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])])
  489. if args.compact:
  490. keep = (np.arange(len(sig[0]))<len(names))
  491. else:
  492. keep = sig[0] | sig[1] | (np.arange(len(sig[0]))<len(names))
  493. for i in range(2):
  494. mu[i] = mu[i][keep]
  495. low[i] = low[i][keep]
  496. up[i] = up[i][keep]
  497. prob[i] = prob[i][keep]
  498. sign = [["<" if _mu>0 else ">" for j, _mu in enumerate(mu[i])] for i in range(2)]
  499. labels = [label for i, label in enumerate(labels) if keep[i]]
  500. n_vars = len(labels)
  501. if args.compact:
  502. labels = [
  503. '\n'.join(map(lambda x: f"\\textbf{{{x}}}", wrap(label, width=15))) if i < 4
  504. else
  505. '\n'.join(wrap(label, width=15))
  506. for i, label in enumerate(labels)
  507. ]
  508. print(labels)
  509. # effect of capital and controls
  510. fig, ax = plt.subplots(figsize=[4.8 if args.compact else 6.4, 0.52*(1+n_vars)])
  511. colors = ['#377eb8', '#ff7f00']
  512. legend = ["entered new research area", "exited research area"]
  513. if args.compact:
  514. ax.set_xlim(-0.9, 1.25)
  515. for j in range(2):
  516. dy = -0.125 if j else +0.125
  517. ax.scatter(mu[j], np.arange(len(labels))[::-1]+dy, color=colors[j])
  518. 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])
  519. for i, p in enumerate(prob[j]):
  520. significant = p<0.05/2
  521. if p>1e-4 and np.abs(p-0.5)>0.4 and significant:
  522. ax.text(
  523. -0.02 if mu[j][i]>0 else 0.02,
  524. np.arange(len(labels))[::-1][i]+dy,
  525. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g},P(\\beta{sign[j][i]}0)={p:.2g}$",
  526. ha="right" if mu[j][i]>0 else "left",
  527. va="center"
  528. )
  529. elif p>1e-4 and np.abs(p-0.5)>0.4 and (not significant):
  530. ax.text(
  531. -0.02 if mu[j][i]>0 else 0.02,
  532. np.arange(len(labels))[::-1][i]+dy,
  533. f"\\scriptsize $P(\\beta{sign[j][i]}0)={p:.2g}$",
  534. ha="right" if mu[j][i]>0 else "left",
  535. va="center"
  536. )
  537. elif significant:
  538. ax.text(
  539. -0.02 if mu[j][i]>0 else 0.02,
  540. np.arange(len(labels))[::-1][i]+dy,
  541. f"\\scriptsize $\\mu(\\beta)={mu[j][i]:.2g}$",
  542. ha="right" if mu[j][i]>0 else "left",
  543. va="center"
  544. )
  545. low, high = ax.get_xlim()
  546. bound = max(abs(low), abs(high))
  547. ax.set_xlim(-bound, bound)
  548. ax.set_yticks(np.arange(len(labels))[::-1], labels)
  549. ax.set_xlabel(f"Effect size (log odds ratio)")
  550. ax.axvline(0, color="black")
  551. if args.compact:
  552. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.3))
  553. else:
  554. ax.legend(loc='upper right', bbox_to_anchor=(1, 1.2))
  555. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.eps"), bbox_inches="tight")
  556. fig.savefig(opj(args.input, f"{args.metric}_score_effects_{args.diversity}_{args.power}{'_compact' if args.compact else ''}{fla}.pdf"), bbox_inches="tight")
  557. 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)
  558. table = df[["bai", "stable", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"]].sort_values(f"{args.metric}_score", ascending=False)
  559. table.to_csv(opj(args.input, f"{args.metric}_scores.csv"))
  560. table["bai"] = table["bai"].str.replace(".1", "")
  561. table["bai"] = table["bai"].str.replace(r"^([A-Z])\.", r"\1.~")
  562. table["bai"] = table["bai"].str.replace(r"\.\~([A-Z])\.", r".~\1.~")
  563. table["bai"] = table["bai"].str.replace(r"([a-zA-Z]{2,})\.", r"\1 ")
  564. table["bai"] = table.apply(lambda r: r["bai"] if not r["stable"] else f"{r['bai']} ($\\ast$)", axis=1)
  565. table["target_label"] += "EOL"
  566. latex = table.head(20).to_latex(
  567. columns=["bai", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"],
  568. header=["Physicist", "$c_a$", "$D(\\bm{I_a})$", "$D(\\bm{S_a})$", "Previous main area", "Current main area"],
  569. index=False,
  570. multirow=True,
  571. multicolumn=True,
  572. column_format='p{0.15\\textwidth}|c|c|c|b{0.25\\textwidth}|b{0.25\\textwidth}',
  573. escape=False,
  574. float_format=lambda x: f"{x:.2f}",
  575. 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.",
  576. label=f"table:top_{args.metric}",
  577. position="H"
  578. )
  579. latex = latex.replace('EOL \\\\\n', '\\\\ \\hline\n')
  580. with open(opj(args.input, f"top_{args.metric}.tex"), "w+") as fp:
  581. fp.write(latex)
  582. latex = table.sort_values(f"{args.metric}_score", ascending=True).head(20).to_latex(
  583. columns=["bai", f"{args.metric}_score", "intellectual_entropy", "social_entropy", "origin_label", "target_label"],
  584. header=["Physicist", "$c_a$", "$D(\\bm{I_a})$", "$D(\\bm{S_a})$", "Previous main area", "Current main area"],
  585. index=False,
  586. multirow=True,
  587. multicolumn=True,
  588. column_format='p{0.15\\textwidth}|c|c|c|b{0.25\\textwidth}|b{0.25\\textwidth}',
  589. escape=False,
  590. float_format=lambda x: f"{x:.2f}",
  591. 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.",
  592. label=f"table:low_{args.metric}",
  593. position="H"
  594. )
  595. latex = latex.replace('EOL \\\\\n', '\\\\ \\hline\n')
  596. with open(opj(args.input, f"low_{args.metric}.tex"), "w+") as fp:
  597. fp.write(latex)