swp2.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import matplotlib.pyplot as plt
  2. import os
  3. import numpy as np
  4. import math
  5. import json
  6. def log_facto(k):
  7. """
  8. Using the Stirling's approximation
  9. """
  10. k = int(k)
  11. if k > 1e6:
  12. return k * np.log(k) - k + np.log(2*math.pi*k)/2
  13. val = 0
  14. for i in range(2, k+1):
  15. val += np.log(i)
  16. return val
  17. def parse_stwp_theta_file(stwp_theta_file, breaks, mu, tgen, relative_theta_scale = False):
  18. with open(stwp_theta_file, "r") as swp_file:
  19. # Read the first line
  20. line = swp_file.readline()
  21. L = float(line.split()[2])
  22. rands = swp_file.readline()
  23. line = swp_file.readline()
  24. # skip empty lines before SFS
  25. while line == "\n":
  26. line = swp_file.readline()
  27. sfs = np.array(line.split()).astype(float)
  28. # Process lines until the end of the file
  29. while line:
  30. # check at each line
  31. if line.startswith("dim") :
  32. dim = int(line.split()[1])
  33. if dim == breaks+1:
  34. likelihood = line.split()[5]
  35. groups = line.split()[6:6+dim]
  36. theta_site = line.split()[6+dim:6+dim+1+dim]
  37. elif dim < breaks+1:
  38. line = swp_file.readline()
  39. continue
  40. elif dim > breaks+1:
  41. break
  42. #return 0,0,0
  43. # Read the next line
  44. line = swp_file.readline()
  45. #### END of parsing
  46. # quit this file if the number of dimensions is incorrect
  47. if dim < breaks+1:
  48. return 0,0,0,0,0,0
  49. # get n, the last bin of the last group
  50. # revert the list of groups as the most recent times correspond
  51. # to the closest and last leafs of the coal. tree.
  52. groups = groups[::-1]
  53. theta_site = theta_site[::-1]
  54. # store thetas for later use
  55. grps = groups.copy()
  56. thetas = {}
  57. for i in range(len(groups)):
  58. grps[i] = grps[i].split(',')
  59. thetas[i] = [float(theta_site[i]), grps[i], likelihood]
  60. # initiate the dict of times
  61. t = {}
  62. # list of thetas
  63. theta_L = []
  64. sum_t = 0
  65. for group_nb, group in enumerate(groups):
  66. ###print(group_nb, group, theta_site[group_nb], len(theta_site))
  67. # store all the thetas one by one, with one theta per group
  68. theta_L.append(float(theta_site[group_nb]))
  69. # if the group is of size 1
  70. if len(group.split(',')) == 1:
  71. i = int(group)
  72. # if the group size is >1, take the first elem of the group
  73. # i is the first bin of each group, straight after a breakpoint
  74. else:
  75. i = int(group.split(",")[0])
  76. j = int(group.split(",")[-1])
  77. t[i] = 0
  78. #t =
  79. if len(group.split(',')) == 1:
  80. k = i
  81. if relative_theta_scale:
  82. t[i] += ((theta_L[group_nb] ) / (k*(k-1)))
  83. else:
  84. t[i] += ((theta_L[group_nb] ) / (k*(k-1)) * tgen) / mu
  85. else:
  86. for k in range(j, i-1, -1 ):
  87. if relative_theta_scale:
  88. t[i] += ((theta_L[group_nb] ) / (k*(k-1)))
  89. else:
  90. t[i] += ((theta_L[group_nb] ) / (k*(k-1)) * tgen) / mu
  91. # we add the cumulative times at the end
  92. t[i] += sum_t
  93. sum_t = t[i]
  94. # build the y axis (sizes)
  95. y = []
  96. for theta in theta_L:
  97. if relative_theta_scale:
  98. size = theta
  99. else:
  100. # with size N = theta/4mu
  101. size = theta / (4*mu)
  102. y.append(size)
  103. y.append(size)
  104. # build the time x axis
  105. x = [0]
  106. for time in range(0, len(t.values())-1):
  107. x.append(list(t.values())[time])
  108. x.append(list(t.values())[time])
  109. x.append(list(t.values())[len(t.values())-1])
  110. return x,y,likelihood,thetas,sfs,L
  111. def plot_straight_x_y(x,y):
  112. x_1 = [x[0]]
  113. y_1 = []
  114. for i in range(0, len(y)-1):
  115. x_1.append(x[i])
  116. x_1.append(x[i])
  117. y_1.append(y[i])
  118. y_1.append(y[i])
  119. y_1 = y_1+[y[-1],y[-1]]
  120. x_1.append(x[-1])
  121. return x_1, y_1
  122. def plot_all_epochs_thetafolder(full_dict, mu, tgen, title = "Title",
  123. theta_scale = True, ax = None, input = None, output = None):
  124. my_dpi = 500
  125. L = full_dict["L"]
  126. if ax is None:
  127. # intialize figure
  128. #my_dpi = 300
  129. fnt_size = 18
  130. # plt.rcParams['font.size'] = fnt_size
  131. fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  132. else:
  133. fnt_size = 12
  134. # plt.rcParams['font.size'] = fnt_size
  135. ax1 = ax[1][0,0]
  136. ax1.set_yscale('log')
  137. ax1.set_xscale('log')
  138. plot_handles = []
  139. best_plot = full_dict['all_epochs']['best']
  140. p0, = ax1.plot(best_plot[0], best_plot[1], linestyle = "-",
  141. alpha=1, lw=2, label = str(best_plot[2])+' brks | Lik='+best_plot[3])
  142. plot_handles.append(p0)
  143. #ax1.grid(True,which="both", linestyle='--', alpha = 0.3)
  144. for k, plot_Lk in enumerate(full_dict['all_epochs']['plots']):
  145. plot_Lk = str(full_dict['all_epochs']['plots'][k][3])
  146. # plt.rcParams['font.size'] = fnt_size
  147. p, = ax1.plot(full_dict['all_epochs']['plots'][k][0], full_dict['all_epochs']['plots'][k][1], linestyle = "-",
  148. alpha=1/(k+1), lw=1.5, label = str(full_dict['all_epochs']['plots'][k][2])+' brks | Lik='+plot_Lk)
  149. plot_handles.append(p)
  150. if theta_scale:
  151. ax1.set_xlabel("Coal. time", fontsize=fnt_size)
  152. ax1.set_ylabel("Pop. size scaled by N0", fontsize=fnt_size)
  153. # recent_scale_lower_bound = 0.01
  154. # recent_scale_upper_bound = 0.1
  155. # ax1.axvline(x=recent_scale_lower_bound)
  156. # ax1.axvline(x=recent_scale_upper_bound)
  157. else:
  158. # years
  159. if ax is not None:
  160. plt.set_xlabel("Time (years)", fontsize=fnt_size)
  161. plt.set_ylabel("Effective pop. size (Ne)", fontsize=fnt_size)
  162. else:
  163. plt.xlabel("Time (years)", fontsize=fnt_size)
  164. plt.ylabel("Effective pop. size (Ne)", fontsize=fnt_size)
  165. # x_ticks = ax1.get_xticks()
  166. # ax1.set_xticklabels([f'{k:.0e}\n{k/(mu):.0e}\n{k/(mu)*tgen:.0e}' for k in x_ticks], fontsize = fnt_size*0.5)
  167. # ax1.set_xticklabels([f'{k}\n{k/(mu)}\n{k/(mu)*tgen}' for k in x_ticks], fontsize = fnt_size*0.8)
  168. # plt.rcParams['font.size'] = fnt_size
  169. # print(fnt_size, "rcParam font.size=", plt.rcParams['font.size'])
  170. ax1.legend(handles = plot_handles, loc='best', fontsize = fnt_size*0.5)
  171. ax1.set_title(title)
  172. breaks = len(full_dict['all_epochs']['plots'])
  173. if ax is None:
  174. plt.savefig(title+'_b'+str(breaks)+'.pdf')
  175. # plot likelihood against nb of breakpoints
  176. if ax is None:
  177. fig, ax2 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  178. # plt.rcParams['font.size'] = fnt_size
  179. else:
  180. #plt.rcParams['font.size'] = fnt_size
  181. ax2 = ax[0][0,1]
  182. ax2.plot(full_dict['Ln_Brks'][0], full_dict['Ln_Brks'][1], 'o', linestyle = "dotted", lw=2)
  183. ax2.axhline(y=full_dict['best_Ln'], linestyle = "-.", color = "red", label = "$-\log\mathcal{L}$ = "+str(round(full_dict['best_Ln'], 2)))
  184. ax2.set_yscale('log')
  185. ax2.set_xlabel("# breakpoints", fontsize=fnt_size)
  186. ax2.set_ylabel("$-\log\mathcal{L}$", fontsize=fnt_size)
  187. ax2.legend(loc='best', fontsize = fnt_size*0.5)
  188. ax2.set_title(title+" Likelihood gain from # breakpoints")
  189. if ax is None:
  190. plt.savefig(title+'_Breakpts_Likelihood.pdf')
  191. # AIC
  192. if ax is None:
  193. fig, ax3 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  194. # plt.rcParams['font.size'] = '18'
  195. else:
  196. #plt.rcParams['font.size'] = fnt_size
  197. ax3 = ax[1][0,1]
  198. AIC = full_dict['AIC_Brks']
  199. ax3.plot(AIC[0], AIC[1], 'o', linestyle = "dotted", lw=2)
  200. ax3.axhline(y=full_dict['best_AIC'], linestyle = "-.", color = "red",
  201. label = "Min. AIC = "+str(round(full_dict['best_AIC'], 2)))
  202. ax3.set_yscale('log')
  203. ax3.set_xlabel("# breakpoints", fontsize=fnt_size)
  204. ax3.set_ylabel("AIC")
  205. ax3.legend(loc='best', fontsize = fnt_size*0.5)
  206. ax3.set_title(title+" AIC")
  207. if ax is None:
  208. plt.savefig(title+'_Breakpts_Likelihood_AIC.pdf')
  209. else:
  210. # return plots
  211. return ax[0], ax[1]
  212. def save_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_scale = True, input = None, output = None):
  213. #scenari = {}
  214. cpt = 0
  215. epochs = {}
  216. plots = {}
  217. # store ['best'], and [0] for epoch 0 etc...
  218. for file_name in os.listdir(folder_path):
  219. breaks = 0
  220. cpt +=1
  221. if os.path.isfile(os.path.join(folder_path, file_name)):
  222. x, y, likelihood, theta, sfs, L = parse_stwp_theta_file(folder_path+file_name, breaks = breaks,
  223. tgen = tgen,
  224. mu = mu, relative_theta_scale = theta_scale)
  225. SFS_stored = sfs
  226. L_stored = L
  227. while not (x == 0 and y == 0):
  228. if breaks not in epochs.keys():
  229. epochs[breaks] = {}
  230. epochs[breaks][likelihood] = x,y
  231. breaks += 1
  232. x,y,likelihood,theta,sfs,L = parse_stwp_theta_file(folder_path+file_name, breaks = breaks,
  233. tgen = tgen,
  234. mu = mu, relative_theta_scale = theta_scale)
  235. if x == 0:
  236. # last break did not work, then breaks = breaks-1
  237. breaks -= 1
  238. print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(breaks)+"\n*******\n")
  239. print(cpt, "theta file(s) have been scanned.")
  240. brkpt_lik = []
  241. top_plots = {}
  242. for epoch, scenari in epochs.items():
  243. # sort starting by the smallest -log(Likelihood)
  244. best10_scenari = (sorted(list(scenari.keys())))[:10]
  245. greatest_likelihood = best10_scenari[0]
  246. # store the tuple breakpoints and likelihood for later plot
  247. brkpt_lik.append((epoch, greatest_likelihood))
  248. x, y = scenari[greatest_likelihood]
  249. #without breakpoint
  250. if epoch == 0:
  251. # do something with the theta without bp and skip the plotting
  252. N0 = y[0]
  253. #continue
  254. if theta_scale:
  255. for i in range(len(y)):
  256. # divide by N0
  257. y[i] = y[i]/N0
  258. x[i] = x[i]/N0
  259. top_plots[greatest_likelihood] = x,y,epoch
  260. plots_likelihoods = list(top_plots.keys())
  261. for i in range(len(plots_likelihoods)):
  262. plots_likelihoods[i] = float(plots_likelihoods[i])
  263. best10_plots = sorted(plots_likelihoods)[:10]
  264. top_plot_lik = str(best10_plots[0])
  265. # store x,y,brks,likelihood
  266. plots['best'] = (top_plots[top_plot_lik][0], top_plots[top_plot_lik][1], str(top_plots[top_plot_lik][2]), top_plot_lik)
  267. plots['plots'] = []
  268. for k, plot_Lk in enumerate(best10_plots[1:]):
  269. plot_Lk = str(plot_Lk)
  270. plots['plots'].append([top_plots[plot_Lk][0], top_plots[plot_Lk][1], str(top_plots[plot_Lk][2]), plot_Lk])
  271. # plot likelihood against nb of breakpoints
  272. # best possible likelihood from SFS
  273. # Segregating sites
  274. S = sum(SFS_stored)
  275. # Number of kept sites from which the SFS is computed
  276. L = L_stored
  277. # number of monomorphic sites
  278. S0 = L-S
  279. # print("SFS", SFS_stored)
  280. # print("S", S, "L", L, "S0=", S0)
  281. # compute Ln
  282. Ln = log_facto(S+S0) - log_facto(S0) + np.log(float(S0)/(S+S0)) * S0
  283. for xi in range(0, len(SFS_stored)):
  284. p_i = SFS_stored[xi] / float(S+S0)
  285. Ln += np.log(p_i) * SFS_stored[xi] - log_facto(SFS_stored[xi])
  286. # basic plot likelihood
  287. Ln_Brks = [list(np.array(brkpt_lik)[:, 0]), list(np.array(brkpt_lik)[:, 1].astype(float))]
  288. best_Ln = -Ln
  289. AIC = []
  290. for brk in np.array(brkpt_lik)[:, 0]:
  291. brk = int(brk)
  292. AIC.append((2*brk+1)+2*np.array(brkpt_lik)[brk, 1].astype(float))
  293. AIC_Brks = [list(np.array(brkpt_lik)[:, 0]), AIC]
  294. # AIC = 2*k - 2ln(L) ; where k is the number of parameters, here brks+1
  295. AIC_ln = 2*(len(brkpt_lik)+1) - 2*Ln
  296. best_AIC = AIC_ln
  297. selected_brks_nb = AIC.index(min(AIC))
  298. # to return : plots ; Ln_Brks ; AIC_Brks ; best_Ln ; best_AIC
  299. # 'plots' dict keys: 'best', {epochs}('0', '1',...)
  300. if input == None:
  301. saved_plots = {"S":S, "S0":S0, "L":L, "mu":mu, "tgen":tgen,
  302. "all_epochs":plots, "Ln_Brks":Ln_Brks,
  303. "AIC_Brks":AIC_Brks, "best_Ln":best_Ln,
  304. "best_AIC":best_AIC, "best_epoch_by_AIC":selected_brks_nb}
  305. else:
  306. # if the dict has to be loaded from input
  307. with open(input, 'r') as json_file:
  308. saved_plots = json.load(json_file)
  309. saved_plots["S"] = S
  310. saved_plots["S0"] = S0
  311. saved_plots["L"] = L
  312. saved_plots["mu"] = mu
  313. saved_plots["tgen"] = tgen
  314. saved_plots["all_epochs"] = plots
  315. saved_plots["Ln_Brks"] = Ln_Brks
  316. saved_plots["AIC_Brks"] = AIC_Brks
  317. saved_plots["best_Ln"] = best_Ln
  318. saved_plots["best_AIC"] = best_AIC
  319. saved_plots["best_epoch_by_AIC"] = selected_brks_nb
  320. if output == None:
  321. output = title+"_plotdata.json"
  322. with open(output, 'w') as json_file:
  323. json.dump(saved_plots, json_file)
  324. return saved_plots
  325. def save_k_theta(folder_path, mu, tgen, title = "Title", theta_scale = True,
  326. breaks_max = 10, input = None, output = None):
  327. """
  328. Save theta values as is to do basic plots.
  329. """
  330. cpt = 0
  331. epochs = {}
  332. len_sfs = 0
  333. for file_name in os.listdir(folder_path):
  334. cpt +=1
  335. if os.path.isfile(os.path.join(folder_path, file_name)):
  336. for k in range(breaks_max):
  337. x,y,likelihood,thetas,sfs,L = parse_stwp_theta_file(folder_path+file_name, breaks = k,
  338. tgen = tgen,
  339. mu = mu, relative_theta_scale = theta_scale)
  340. if thetas == 0:
  341. continue
  342. if len(thetas)-1 != k:
  343. continue
  344. if k not in epochs.keys():
  345. epochs[k] = {}
  346. likelihood = str(eval(thetas[k][2]))
  347. epochs[k][likelihood] = thetas
  348. #epochs[k] = thetas
  349. print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(k)+"\n*******\n")
  350. print(cpt, "theta file(s) have been scanned.")
  351. plots = []
  352. best_epochs = {}
  353. for epoch in epochs:
  354. likelihoods = []
  355. for key in epochs[epoch].keys():
  356. likelihoods.append(key)
  357. likelihoods.sort()
  358. minLogLn = str(likelihoods[0])
  359. best_epochs[epoch] = epochs[epoch][minLogLn]
  360. for epoch, theta in best_epochs.items():
  361. groups = np.array(list(theta.values()), dtype=object)[:, 1].tolist()
  362. x = []
  363. y = []
  364. thetas = np.array(list(theta.values()), dtype=object)[:, 0]
  365. for i,group in enumerate(groups):
  366. x += group[::-1]
  367. y += list(np.repeat(thetas[i], len(group)))
  368. if epoch == 0:
  369. N0 = y[0]
  370. # compute the proportion of information used at each bin of the SFS
  371. sum_theta_i = 0
  372. for i in range(2, len(y)+2):
  373. sum_theta_i+=y[i-2] / (i-1)
  374. prop = []
  375. for k in range(2, len(y)+2):
  376. prop.append(y[k-2] / (k - 1) / sum_theta_i)
  377. prop = prop[::-1]
  378. if theta_scale :
  379. # normalise to N0 (N0 of epoch1)
  380. for i in range(len(y)):
  381. y[i] = y[i]/N0
  382. # x_plot, y_plot = plot_straight_x_y(x, y)
  383. p = x, y
  384. # add plot to the list of all plots to superimpose
  385. plots.append(p)
  386. cumul = 0
  387. prop_cumul = []
  388. for val in prop:
  389. prop_cumul.append(val+cumul)
  390. cumul = val+cumul
  391. prop = prop_cumul
  392. lines_fig2 = []
  393. for epoch, theta in best_epochs.items():
  394. groups = np.array(list(theta.values()), dtype=object)[:, 1].tolist()
  395. x = []
  396. y = []
  397. thetas = np.array(list(theta.values()), dtype=object)[:, 0]
  398. for i,group in enumerate(groups):
  399. x += group[::-1]
  400. y += list(np.repeat(thetas[i], len(group)))
  401. if epoch == 0:
  402. N0 = y[0]
  403. if theta_scale :
  404. for i in range(len(y)):
  405. y[i] = y[i]/N0
  406. x_2 = []
  407. T = 0
  408. for i in range(len(x)):
  409. x[i] = int(x[i])
  410. # compute the times as: theta_k / (k*(k-1))
  411. for i in range(0, len(x)):
  412. T += y[i] / (x[i]*(x[i]-1))
  413. x_2.append(T)
  414. # Save plotting (fig 2)
  415. x_2 = [0]+x_2
  416. y = [y[0]]+y
  417. # x2_plot, y2_plot = plot_straight_x_y(x_2, y)
  418. p2 = x_2, y
  419. lines_fig2.append(p2)
  420. if input == None:
  421. saved_plots = {"raw_stairs":plots, "scaled_stairs":lines_fig2,
  422. "prop":prop}
  423. else:
  424. # if the dict has to be loaded from input
  425. with open(input, 'r') as json_file:
  426. saved_plots = json.load(json_file)
  427. saved_plots["raw_stairs"] = plots
  428. saved_plots["scaled_stairs"] = lines_fig2
  429. saved_plots["prop"] = prop
  430. if output == None:
  431. output = title+"_plotdata.json"
  432. with open(output, 'w') as json_file:
  433. json.dump(saved_plots, json_file)
  434. return saved_plots
  435. def plot_scaled_theta(plot_lines, prop, title, mu, tgen, swp2_lines = None, ax = None, n_ticks = 10, subset = None, theta_scale = False):
  436. # fig 2 & 3
  437. if ax is None:
  438. my_dpi = 500
  439. fnt_size = 18
  440. fig2, ax2 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  441. fig3, ax3 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  442. else:
  443. # plt.rcParams['font.size'] = fnt_size
  444. fnt_size = 12
  445. # place of plots on the grid
  446. ax2 = ax[1,0]
  447. ax3 = ax[1,1]
  448. lines_fig2 = []
  449. lines_fig3 = []
  450. #plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  451. if swp2_lines:
  452. for k in range(len(swp2_lines[0])):
  453. swp2_lines[0][k] = swp2_lines[0][k]/tgen*mu
  454. for k in range(len(swp2_lines[1])):
  455. swp2_lines[1][k] = swp2_lines[1][k]*4*mu
  456. # plot_lines = [[swp2_lines[0], swp2_lines[1]]]+plot_lines
  457. x2_plot, y2_plot = plot_straight_x_y(swp2_lines[0],swp2_lines[1])
  458. p2, = ax2.plot(x2_plot, y2_plot, linestyle="-", alpha=0.75, lw=2, label = 'swp2')
  459. lines_fig2.append(p2)
  460. # Plotting (fig 3) which is the same but log scale for x
  461. p3, = ax3.plot(x2_plot, y2_plot, linestyle="-", alpha=0.75, lw=2, label = 'swp2')
  462. lines_fig3.append(p3)
  463. nb_breaks = len(plot_lines)
  464. for breaks, plot in enumerate(plot_lines):
  465. if subset is not None:
  466. if breaks not in subset :
  467. # skip if not in subset
  468. if max(subset) > nb_breaks and breaks == nb_breaks:
  469. pass
  470. else:
  471. continue
  472. x,y=plot
  473. # y = [k/(4*mu) for k in y]
  474. # x = [k/(mu)*tgen for k in x]
  475. x2_plot, y2_plot = plot_straight_x_y(x,y)
  476. p2, = ax2.plot(x2_plot, y2_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(breaks)+' brks')
  477. lines_fig2.append(p2)
  478. # Plotting (fig 3) which is the same but log scale for x
  479. p3, = ax3.plot(x2_plot, y2_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(breaks)+' brks')
  480. lines_fig3.append(p3)
  481. ax3.axvline(x=500/tgen*mu, linestyle="--")
  482. if theta_scale:
  483. xlabel = "Theta scaled by N0"
  484. ylabel = "Theta scaled by N0"
  485. else:
  486. xlabel = "Theta scale"
  487. ylabel = "Theta"
  488. if ax is None:
  489. # if not ax, then use the plt syntax, not ax...
  490. plt.xlabel(xlabel, fontsize=fnt_size)
  491. plt.ylabel(ylabel, fontsize=fnt_size)
  492. plt.xlim(left=0)
  493. x_ticks = list(plt.xticks())[0]
  494. plt.gca().set_xticks(x_ticks)
  495. plt.gca().set_xticklabels([f'{k:.0e}\n{k/(mu):.0e}\n{k/(mu)*tgen:.0e}' for k in x_ticks], fontsize = fnt_size*0.5)
  496. plt.title(title, fontsize=fnt_size)
  497. plt.legend(handles=lines_fig2, loc='best', fontsize = fnt_size*0.5)
  498. plt.text(-0.13, -0.135, 'Coal. time\nGen. time\nYears', ha='left', va='bottom', transform=ax3.transAxes)
  499. plt.subplots_adjust(bottom=0.2) # Adjust the value as needed
  500. # nb of plot_lines represent the number of epochs stored (len(plot_lines) = #breaks+1)
  501. plt.savefig(title+'_plot2_'+str(len(plot_lines))+'.pdf')
  502. # close fig2 to save memory
  503. plt.close(fig2)
  504. else:
  505. # when ax subplotting is used
  506. ax2.set_xlabel(xlabel, fontsize=fnt_size)
  507. ax2.set_ylabel(ylabel, fontsize=fnt_size)
  508. ax2.set_title(title, fontsize=fnt_size)
  509. ax2.legend(handles=lines_fig2, loc='best', fontsize = fnt_size*0.5)
  510. ax3.set_xscale('log')
  511. ax3.set_yscale('log')
  512. ax3.set_xlabel("time log scale", fontsize=fnt_size)
  513. ax3.set_ylabel("theta", fontsize=fnt_size)
  514. ax3.set_title(title, fontsize=fnt_size)
  515. ax3.legend(handles=lines_fig3, loc='best', fontsize = fnt_size*0.5)
  516. x_ticks = list(ax3.get_xticks())
  517. ax3.set_xlim(left=min(x_ticks))
  518. ax3.set_xticks(x_ticks)
  519. ax3.set_xticklabels([f'{k:.0e}\n{k/(mu):.0e}\n{k/(mu)*tgen:.0e}' for k in x_ticks], fontsize = fnt_size*0.5)
  520. plt.text(-0.13, -0.135, 'Coal. time\nGen. time\nYears', ha='left', va='bottom', transform=ax3.transAxes)
  521. plt.subplots_adjust(bottom=0.2) # Adjust the value as needed
  522. if ax is None:
  523. # nb of plot_lines represent the number of epochs stored (len(plot_lines) = #breaks+1)
  524. plt.savefig(title+'_plot3_'+str(len(plot_lines))+'_log.pdf')
  525. # close fig3 to save memory
  526. plt.close(fig3)
  527. return ax
  528. def plot_raw_stairs(plot_lines, prop, title, ax = None, n_ticks = 10, rescale = False, subset = None):
  529. # multiple fig
  530. if ax is None:
  531. # intialize figure 1
  532. my_dpi = 300
  533. fnt_size = 18
  534. # plt.rcParams['font.size'] = fnt_size
  535. fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  536. else:
  537. fnt_size = 12
  538. # plt.rcParams['font.size'] = fnt_size
  539. ax1 = ax[0, 0]
  540. plt.subplots_adjust(wspace=0.3, hspace=0.3)
  541. plots = []
  542. for epoch, plot in enumerate(plot_lines):
  543. x,y = plot
  544. x_plot, y_plot = plot_straight_x_y(x,y)
  545. p, = ax1.plot(x_plot, y_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(epoch)+' brks')
  546. # add plot to the list of all plots to superimpose
  547. plots.append(p)
  548. x_ticks = x
  549. # print(x_ticks)
  550. #print(prop, "\n", sum(prop))
  551. #ax.legend(handles=[p0]+plots)
  552. ax1.set_xlabel("# bin & cumul. prop. of sites", fontsize=fnt_size)
  553. # Set the x-axis locator to reduce the number of ticks to 10
  554. ax1.set_ylabel("theta", fontsize=fnt_size)
  555. ax1.set_title(title, fontsize=fnt_size)
  556. ax1.legend(handles=plots, loc='best', fontsize = fnt_size*0.5)
  557. ax1.set_xticks(x_ticks)
  558. step = len(x_ticks)//(n_ticks-1)
  559. values = x_ticks[::step]
  560. new_prop = []
  561. for val in values:
  562. new_prop.append(prop[int(val)-2])
  563. new_prop = new_prop[::-1]
  564. ax1.set_xticks(values)
  565. ax1.set_xticklabels([f'{values[k]}\n{val:.2f}' for k, val in enumerate(new_prop)], fontsize = fnt_size*0.8)
  566. if ax is None:
  567. # nb of plot_lines represent the number of epochs stored (len(plot_lines) = #breaks+1)
  568. plt.savefig(title+'_raw'+str(len(plot_lines))+'.pdf')
  569. plt.close(fig)
  570. # return plots
  571. return ax
  572. def combined_plot(folder_path, mu, tgen, breaks, title = "Title", theta_scale = False, selected_breaks = []):
  573. my_dpi = 300
  574. saved_plots_dict = save_all_epochs_thetafolder(folder_path, mu, tgen, title, theta_scale, output = title+"_plotdata.json")
  575. nb_of_epochs = len(saved_plots_dict["all_epochs"]["plots"])
  576. print(nb_of_epochs)
  577. best_epoch = saved_plots_dict["best_epoch_by_AIC"]
  578. save_k_theta(folder_path, mu, tgen, title, theta_scale, breaks_max = nb_of_epochs, input = title+"_plotdata.json", output = title+"_plotdata.json")
  579. with open(title+"_plotdata.json", 'r') as json_file:
  580. loaded_data = json.load(json_file)
  581. # START OF COMBINED PLOT CODE
  582. # # plot page 1 of summary
  583. # fig1, ax1 = plt.subplots(2, 2, figsize=(5000/my_dpi, 2970/my_dpi), dpi=my_dpi)
  584. # # fig1.tight_layout()
  585. # # Adjust absolute space between the top and bottom rows
  586. # fig1.subplots_adjust(hspace=0.35) # Adjust this value based on your requirement
  587. # # plot page 2 of summary
  588. # fig2, ax2 = plt.subplots(2, 2, figsize=(5000/my_dpi, 2970/my_dpi), dpi=my_dpi)
  589. # # fig2.tight_layout()
  590. # ax1 = plot_raw_stairs(plot_lines = loaded_data['raw_stairs'],
  591. # prop = loaded_data['prop'], title = title, ax = ax1)
  592. # ax1 = plot_scaled_theta(plot_lines = loaded_data['scaled_stairs'],
  593. # prop = loaded_data['prop'], title = title, ax = ax1, subset=[loaded_data['best_epoch_by_AIC']]+selected_breaks)
  594. # ax2 = plot_scaled_theta(plot_lines = loaded_data['scaled_stairs'],
  595. # prop = loaded_data['prop'], title = title, ax = ax2)
  596. # ax1, ax2 = plot_all_epochs_thetafolder(loaded_data, mu, tgen, title, theta_scale, ax = [ax1, ax2])
  597. # fig1.savefig(title+'_combined_p1.pdf')
  598. # print("Wrote", title+'_combined_p1.pdf')
  599. # fig2.savefig(title+'_combined_p2.pdf')
  600. # print("Wrote", title+'_combined_p2.pdf')
  601. # END OF COMBINED PLOT CODE
  602. # Start of Parsing real swp2 output
  603. folder_splitted = folder_path.split("/")
  604. swp2_summary = "/".join(folder_splitted[:-2])+'/'+folder_splitted[-3]+".final.summary"
  605. swp2_vals = parse_stairwayplot_output_summary(stwplt_out = swp2_summary)
  606. swp2_x, swp2_y = swp2_vals[0], swp2_vals[1]
  607. # End of Parsing real swp2 output
  608. plot_raw_stairs(plot_lines = loaded_data['raw_stairs'],
  609. prop = loaded_data['prop'], title = title, ax = None)
  610. plot_scaled_theta(plot_lines = loaded_data['scaled_stairs'], mu = mu, tgen = tgen, subset=[loaded_data['best_epoch_by_AIC']]+selected_breaks,
  611. # plot_scaled_theta(plot_lines = loaded_data['scaled_stairs'], subset=list(range(0,3))+[loaded_data['best_epoch_by_AIC']]+selected_breaks,
  612. prop = loaded_data['prop'], title = title, swp2_lines = [swp2_x, swp2_y], ax = None)
  613. plot_all_epochs_thetafolder(loaded_data, mu, tgen, title, theta_scale, ax = None)
  614. # plt.close(fig1)
  615. # plt.close(fig2)
  616. def parse_stairwayplot_output_summary(stwplt_out, xlim = None, ylim = None, title = "default title", plot = False):
  617. #col 5
  618. year = []
  619. # col 6
  620. ne_median = []
  621. ne_2_5 = []
  622. ne_97_5 = []
  623. ne_12_5 = []
  624. # col 10
  625. ne_87_5 = []
  626. with open(stwplt_out, "r") as stwplt_stream:
  627. for line in stwplt_stream:
  628. ## Line format
  629. # mutation_per_site n_estimation theta_per_site_median theta_per_site_2.5% theta_per_site_97.5% year Ne_median Ne_2.5% Ne_97.5% Ne_12.5% Ne_87.5%
  630. if not line.startswith("mutation_per_site"):
  631. #not header
  632. values = line.strip().split()
  633. year.append(float(values[5]))
  634. ne_median.append(float(values[6]))
  635. ne_2_5.append(float(values[7]))
  636. ne_97_5.append(float(values[8]))
  637. ne_12_5.append(float(values[9]))
  638. ne_87_5.append(float(values[10]))
  639. vals = [year, ne_median, ne_2_5, ne_97_5, ne_12_5, ne_87_5]
  640. if plot :
  641. # plot parsed data
  642. label = ["Ne median", "Ne 2.5%", "Ne 97.5%", "Ne 12.5%", "Ne 87.5%"]
  643. for i in range(1, 5):
  644. fig, = plt.plot(year, vals[i], '--', alpha = 0.4)
  645. fig.set_label(label[i])
  646. # # last plot is median
  647. fig, = plt.plot(year, ne_median, 'r-', lw=2)
  648. fig.set_label(label[0])
  649. plt.legend()
  650. plt.ylabel("Individuals (Ne)")
  651. plt.xlabel("Time (years)")
  652. if xlim:
  653. plt.xlim(xlim)
  654. if ylim:
  655. plt.ylim(ylim)
  656. plt.title(title)
  657. plt.show()
  658. plt.close()
  659. return vals
  660. if __name__ == "__main__":
  661. if len(sys.argv) != 4:
  662. print("Need 3 args: ThetaFolder MutationRate GenerationTime")
  663. exit(0)
  664. folder_path = sys.argv[1]
  665. mu = sys.argv[2]
  666. tgen = sys.argv[3]
  667. plot_all_epochs_thetafolder(folder_path, mu, tgen)