swp2.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import matplotlib.pyplot as plt
  2. import os
  3. import numpy as np
  4. import math
  5. from scipy.special import gammaln
  6. from matplotlib.backends.backend_pdf import PdfPages
  7. from matplotlib.ticker import MaxNLocator
  8. import io
  9. from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  10. from matplotlib.ticker import MultipleLocator
  11. def log_facto(k):
  12. k = int(k)
  13. if k > 1e6:
  14. return k * np.log(k) - k + np.log(2*math.pi*k)/2
  15. val = 0
  16. for i in range(2, k+1):
  17. val += np.log(i)
  18. return val
  19. def log_facto_1(k):
  20. startf = 1 # start of factorial sequence
  21. stopf = int(k+1) # end of of factorial sequence
  22. q = gammaln(range(startf+1, stopf+1)) # n! = G(n+1)
  23. return q[-1]
  24. def return_x_y_from_stwp_theta_file(stwp_theta_file, breaks, mu, tgen, relative_theta_scale = False):
  25. with open(stwp_theta_file, "r") as swp_file:
  26. # Read the first line
  27. line = swp_file.readline()
  28. L = float(line.split()[2])
  29. rands = swp_file.readline()
  30. line = swp_file.readline()
  31. # skip empty lines before SFS
  32. while line == "\n":
  33. line = swp_file.readline()
  34. sfs = np.array(line.split()).astype(float)
  35. # Process lines until the end of the file
  36. while line:
  37. # check at each line
  38. if line.startswith("dim") :
  39. dim = int(line.split()[1])
  40. if dim == breaks+1:
  41. likelihood = line.split()[5]
  42. groups = line.split()[6:6+dim]
  43. theta_site = line.split()[6+dim:6+dim+1+dim]
  44. elif dim < breaks+1:
  45. line = swp_file.readline()
  46. continue
  47. elif dim > breaks+1:
  48. break
  49. #return 0,0,0
  50. # Read the next line
  51. line = swp_file.readline()
  52. #### END of parsing
  53. # quit this file if the number of dimensions is incorrect
  54. if dim < breaks+1:
  55. return 0,0,0,0,0
  56. # get n, the last bin of the last group
  57. # revert the list of groups as the most recent times correspond
  58. # to the closest and last leafs of the coal. tree.
  59. groups = groups[::-1]
  60. theta_site = theta_site[::-1]
  61. # initiate the dict of times
  62. t = {}
  63. # list of thetas
  64. theta_L = []
  65. sum_t = 0
  66. for group_nb, group in enumerate(groups):
  67. ###print(group_nb, group, theta_site[group_nb], len(theta_site))
  68. # store all the thetas one by one, with one theta per group
  69. theta_L.append(float(theta_site[group_nb]))
  70. # if the group is of size 1
  71. if len(group.split(',')) == 1:
  72. i = int(group)
  73. # if the group size is >1, take the first elem of the group
  74. # i is the first bin of each group, straight after a breakpoint
  75. else:
  76. i = int(group.split(",")[0])
  77. j = int(group.split(",")[-1])
  78. t[i] = 0
  79. #t =
  80. if len(group.split(',')) == 1:
  81. k = i
  82. if relative_theta_scale:
  83. t[i] += ((theta_L[group_nb] ) / (k*(k-1)))
  84. else:
  85. t[i] += ((theta_L[group_nb] ) / (k*(k-1)) * tgen) / mu
  86. else:
  87. for k in range(j, i-1, -1 ):
  88. if relative_theta_scale:
  89. t[i] += ((theta_L[group_nb] ) / (k*(k-1)))
  90. else:
  91. t[i] += ((theta_L[group_nb] ) / (k*(k-1)) * tgen) / mu
  92. # we add the cumulative times at the end
  93. t[i] += sum_t
  94. sum_t = t[i]
  95. # build the y axis (sizes)
  96. y = []
  97. for theta in theta_L:
  98. if relative_theta_scale:
  99. size = theta
  100. else:
  101. # with size N = theta/4mu
  102. size = theta / (4*mu)
  103. y.append(size)
  104. y.append(size)
  105. # build the time x axis
  106. x = [0]
  107. for time in range(0, len(t.values())-1):
  108. x.append(list(t.values())[time])
  109. x.append(list(t.values())[time])
  110. x.append(list(t.values())[len(t.values())-1])
  111. # if relative_theta_scale:
  112. # # rescale
  113. # #N0 = y[0]
  114. # # for i in range(len(y)):
  115. # # # divide by N0
  116. # # y[i] = y[i]/N0
  117. # # x[i] = x[i]/N0
  118. return x,y,likelihood,sfs,L
  119. def return_x_y_from_stwp_theta_file_as_is(stwp_theta_file, breaks, mu, tgen, relative_theta_scale = False):
  120. with open(stwp_theta_file, "r") as swp_file:
  121. # Read the first line
  122. line = swp_file.readline()
  123. L = float(line.split()[2])
  124. rands = swp_file.readline()
  125. line = swp_file.readline()
  126. # skip empty lines before SFS
  127. while line == "\n":
  128. line = swp_file.readline()
  129. sfs = np.array(line.split()).astype(float)
  130. # Process lines until the end of the file
  131. while line:
  132. # check at each line
  133. if line.startswith("dim") :
  134. dim = int(line.split()[1])
  135. if dim == breaks+1:
  136. likelihood = line.split()[5]
  137. groups = line.split()[6:6+dim]
  138. theta_site = line.split()[6+dim:6+dim+1+dim]
  139. elif dim < breaks+1:
  140. line = swp_file.readline()
  141. continue
  142. elif dim > breaks+1:
  143. break
  144. #return 0,0,0
  145. # Read the next line
  146. line = swp_file.readline()
  147. #### END of parsing
  148. # quit this file if the number of dimensions is incorrect
  149. if dim < breaks+1:
  150. return 0,0
  151. # get n, the last bin of the last group
  152. # revert the list of groups as the most recent times correspond
  153. # to the closest and last leafs of the coal. tree.
  154. groups = groups[::-1]
  155. theta_site = theta_site[::-1]
  156. thetas = {}
  157. for i in range(len(groups)):
  158. groups[i] = groups[i].split(',')
  159. #print(groups[i], len(groups[i]))
  160. thetas[i] = [float(theta_site[i]), groups[i], likelihood]
  161. return thetas, sfs
  162. def plot_k_epochs_thetafolder(folder_path, mu, tgen, breaks = 2, title = "Title", theta_scale = True):
  163. scenari = {}
  164. cpt = 0
  165. for file_name in os.listdir(folder_path):
  166. if os.path.isfile(os.path.join(folder_path, file_name)):
  167. # Perform actions on each file
  168. x,y,likelihood,sfs,L = return_x_y_from_stwp_theta_file(folder_path+file_name, breaks = breaks,
  169. tgen = tgen,
  170. mu = mu, relative_theta_scale = theta_scale)
  171. if x == 0 or y == 0:
  172. continue
  173. cpt +=1
  174. scenari[likelihood] = x,y
  175. print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(breaks)+"\n*******\n")
  176. print(cpt, "theta file(s) have been scanned.")
  177. # sort starting by the smallest -log(Likelihood)
  178. print(scenari)
  179. best10_scenari = (sorted(list(scenari.keys())))[:10]
  180. print("10 greatest Likelihoods", best10_scenari)
  181. greatest_likelihood = best10_scenari[0]
  182. x, y = scenari[greatest_likelihood]
  183. my_dpi = 300
  184. plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  185. plt.plot(x, y, 'r-', lw=2, label = 'Lik='+greatest_likelihood)
  186. plt.xlim(1e-3, 1)
  187. plt.ylim(0, 10)
  188. #plt.yscale('log')
  189. plt.xscale('log')
  190. plt.grid(True,which="both", linestyle='--', alpha = 0.3)
  191. for scenario in best10_scenari[1:]:
  192. x,y = scenari[scenario]
  193. #print("\n---- Lik:",scenario,"\n\nt=", x,"\n\nN=",y, "\n\n")
  194. plt.plot(x, y, '--', lw=1, label = 'Lik='+scenario)
  195. if theta_scale:
  196. plt.xlabel("Coal. time")
  197. plt.ylabel("Pop. size scaled by N0")
  198. recent_scale_lower_bound = y[0] * 0.01
  199. recent_scale_upper_bound = y[0] * 0.1
  200. plt.axvline(x=recent_scale_lower_bound)
  201. plt.axvline(x=recent_scale_upper_bound)
  202. else:
  203. # years
  204. plt.xlabel("Time (years)")
  205. plt.ylabel("Individuals (N)")
  206. plt.legend(loc='upper right')
  207. plt.title(title)
  208. plt.savefig(title+'_b'+str(breaks)+'.pdf')
  209. def plot_straight_x_y(x,y):
  210. x_1 = [x[0]]
  211. y_1 = []
  212. for i in range(0, len(y)-1):
  213. x_1.append(x[i])
  214. x_1.append(x[i])
  215. y_1.append(y[i])
  216. y_1.append(y[i])
  217. y_1 = y_1+[y[-1],y[-1]]
  218. x_1.append(x[-1])
  219. return x_1, y_1
  220. def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_scale = True, ax = None):
  221. #scenari = {}
  222. cpt = 0
  223. epochs = {}
  224. for file_name in os.listdir(folder_path):
  225. breaks = 0
  226. cpt +=1
  227. if os.path.isfile(os.path.join(folder_path, file_name)):
  228. x, y, likelihood, sfs, L = return_x_y_from_stwp_theta_file(folder_path+file_name, breaks = breaks,
  229. tgen = tgen,
  230. mu = mu, relative_theta_scale = theta_scale)
  231. SFS_stored = sfs
  232. L_stored = L
  233. while not (x == 0 and y == 0):
  234. if breaks not in epochs.keys():
  235. epochs[breaks] = {}
  236. epochs[breaks][likelihood] = x,y
  237. breaks += 1
  238. x,y,likelihood,sfs,L = return_x_y_from_stwp_theta_file(folder_path+file_name, breaks = breaks,
  239. tgen = tgen,
  240. mu = mu, relative_theta_scale = theta_scale)
  241. if x == 0:
  242. # last break did not work, then breaks = breaks-1
  243. breaks -= 1
  244. print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(breaks)+"\n*******\n")
  245. print(cpt, "theta file(s) have been scanned.")
  246. my_dpi = 300
  247. if ax is None:
  248. # intialize figure
  249. my_dpi = 300
  250. fnt_size = 18
  251. # plt.rcParams['font.size'] = fnt_size
  252. fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  253. else:
  254. fnt_size = 12
  255. # plt.rcParams['font.size'] = fnt_size
  256. ax1 = ax[0,0]
  257. #ax1.set_xlim(1e-3, 1)
  258. ax1.set_yscale('log')
  259. ax1.set_xscale('log')
  260. ax1.grid(True,which="both", linestyle='--', alpha = 0.3)
  261. brkpt_lik = []
  262. top_plots = {}
  263. for epoch, scenari in epochs.items():
  264. # sort starting by the smallest -log(Likelihood)
  265. best10_scenari = (sorted(list(scenari.keys())))[:10]
  266. greatest_likelihood = best10_scenari[0]
  267. # store the tuple breakpoints and likelihood for later plot
  268. brkpt_lik.append((epoch, greatest_likelihood))
  269. x, y = scenari[greatest_likelihood]
  270. #without breakpoint
  271. if epoch == 0:
  272. # do something with the theta without bp and skip the plotting
  273. N0 = y[0]
  274. #continue
  275. for i in range(len(y)):
  276. # divide by N0
  277. y[i] = y[i]/N0
  278. x[i] = x[i]/N0
  279. top_plots[greatest_likelihood] = x,y,epoch
  280. plots_likelihoods = list(top_plots.keys())
  281. for i in range(len(plots_likelihoods)):
  282. plots_likelihoods[i] = float(plots_likelihoods[i])
  283. best10_plots = sorted(plots_likelihoods)[:10]
  284. top_plot_lik = str(best10_plots[0])
  285. plot_handles = []
  286. # plt.rcParams['font.size'] = fnt_size
  287. p0, = ax1.plot(top_plots[top_plot_lik][0], top_plots[top_plot_lik][1], 'o', linestyle = "-",
  288. alpha=1, lw=2, label = str(top_plots[top_plot_lik][2])+' brks | Lik='+top_plot_lik)
  289. plot_handles.append(p0)
  290. for k, plot_Lk in enumerate(best10_plots[1:]):
  291. plot_Lk = str(plot_Lk)
  292. # plt.rcParams['font.size'] = fnt_size
  293. p, = ax1.plot(top_plots[plot_Lk][0], top_plots[plot_Lk][1], 'o', linestyle = "--",
  294. alpha=1/(k+1), lw=1.5, label = str(top_plots[plot_Lk][2])+' brks | Lik='+plot_Lk)
  295. plot_handles.append(p)
  296. if theta_scale:
  297. ax1.set_xlabel("Coal. time", fontsize=fnt_size)
  298. ax1.set_ylabel("Pop. size scaled by N0", fontsize=fnt_size)
  299. # recent_scale_lower_bound = 0.01
  300. # recent_scale_upper_bound = 0.1
  301. # ax1.axvline(x=recent_scale_lower_bound)
  302. # ax1.axvline(x=recent_scale_upper_bound)
  303. else:
  304. # years
  305. plt.set_xlabel("Time (years)", fontsize=fnt_size)
  306. plt.set_ylabel("Individuals (N)", fontsize=fnt_size)
  307. ax1.set_xlim(1e-5, 1)
  308. # plt.rcParams['font.size'] = fnt_size
  309. # print(fnt_size, "rcParam font.size=", plt.rcParams['font.size'])
  310. ax1.legend(handles = plot_handles, loc='best', fontsize = fnt_size*0.5)
  311. ax1.set_title(title)
  312. if ax is None:
  313. plt.savefig(title+'_b'+str(breaks)+'.pdf')
  314. # plot likelihood against nb of breakpoints
  315. # best possible likelihood from SFS
  316. # Segregating sites
  317. S = sum(SFS_stored)
  318. # Number of kept sites from which the SFS is computed
  319. L = L_stored
  320. # number of monomorphic sites
  321. S0 = L-S
  322. # print("SFS", SFS_stored)
  323. # print("S", S, "L", L, "S0=", S0)
  324. # compute Ln
  325. Ln = log_facto(S+S0) - log_facto(S0) + np.log(float(S0)/(S+S0)) * S0
  326. for xi in range(0, len(SFS_stored)):
  327. p_i = SFS_stored[xi] / float(S+S0)
  328. Ln += np.log(p_i) * SFS_stored[xi] - log_facto(SFS_stored[xi])
  329. # basic plot likelihood
  330. if ax is None:
  331. fig, ax2 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  332. # plt.rcParams['font.size'] = fnt_size
  333. else:
  334. #plt.rcParams['font.size'] = fnt_size
  335. ax2 = ax[2,0]
  336. ax2.plot(np.array(brkpt_lik)[:, 0], np.array(brkpt_lik)[:, 1].astype(float), 'o', linestyle = "dotted", lw=2)
  337. ax2.axhline(y=-Ln, linestyle = "-.", color = "red", label = "$-\log\mathcal{L}$ = "+str(round(-Ln, 2)))
  338. ax2.set_yscale('log')
  339. ax2.set_xlabel("# breakpoints", fontsize=fnt_size)
  340. ax2.set_ylabel("$-\log\mathcal{L}$", fontsize=fnt_size)
  341. ax2.legend(loc='best', fontsize = fnt_size*0.5)
  342. ax2.set_title(title+" Likelihood gain from # breakpoints")
  343. if ax is None:
  344. plt.savefig(title+'_Breakpts_Likelihood.pdf')
  345. # AIC
  346. if ax is None:
  347. fig, ax3 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  348. # plt.rcParams['font.size'] = '18'
  349. else:
  350. #plt.rcParams['font.size'] = fnt_size
  351. ax3 = ax[2,1]
  352. AIC = 2*(len(brkpt_lik)+1)+2*np.array(brkpt_lik)[:, 1].astype(float)
  353. ax3.plot(np.array(brkpt_lik)[:, 0], AIC, 'o', linestyle = "dotted", lw=2)
  354. AIC_ln = 2*(len(brkpt_lik)+1)-2*Ln
  355. ax3.axhline(y=AIC_ln, linestyle = "-.", color = "red",
  356. label = "Min. AIC = "+str(round(AIC_ln, 2)))
  357. ax3.set_yscale('log')
  358. ax3.set_xlabel("# breakpoints", fontsize=fnt_size)
  359. ax3.set_ylabel("AIC")
  360. ax3.legend(loc='best', fontsize = fnt_size*0.5)
  361. ax3.set_title(title+" AIC")
  362. if ax is None:
  363. plt.savefig(title+'_Breakpts_Likelihood_AIC.pdf')
  364. print("S", S)
  365. return ax
  366. def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True, breaks_max = 10, ax = None, n_ticks = 10):
  367. """
  368. Use theta values as is to do basic plots.
  369. """
  370. cpt = 0
  371. epochs = {}
  372. for file_name in os.listdir(folder_path):
  373. cpt +=1
  374. if os.path.isfile(os.path.join(folder_path, file_name)):
  375. for k in range(breaks_max):
  376. thetas,sfs = return_x_y_from_stwp_theta_file_as_is(folder_path+file_name, breaks = k,
  377. tgen = tgen,
  378. mu = mu, relative_theta_scale = theta_scale)
  379. if thetas == 0:
  380. continue
  381. epochs[k] = thetas
  382. print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(k)+"\n*******\n")
  383. print(cpt, "theta file(s) have been scanned.")
  384. # multiple fig
  385. if ax is None:
  386. # intialize figure 1
  387. my_dpi = 300
  388. fnt_size = 18
  389. # plt.rcParams['font.size'] = fnt_size
  390. fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  391. else:
  392. fnt_size = 12
  393. # plt.rcParams['font.size'] = fnt_size
  394. ax1 = ax[0, 1]
  395. plt.subplots_adjust(wspace=0.3, hspace=0.3)
  396. plots = []
  397. for epoch, theta in epochs.items():
  398. groups = np.array(list(theta.values()), dtype=object)[:, 1].tolist()
  399. x = []
  400. y = []
  401. thetas = np.array(list(theta.values()), dtype=object)[:, 0]
  402. for i,group in enumerate(groups):
  403. x += group[::-1]
  404. y += list(np.repeat(thetas[i], len(group)))
  405. if epoch == 0:
  406. N0 = y[0]
  407. # compute the proportion of information used at each bin of the SFS
  408. sum_theta_i = 0
  409. for i in range(2, len(y)+2):
  410. sum_theta_i+=y[i-2] / (i-1)
  411. prop = []
  412. for k in range(2, len(y)+2):
  413. prop.append(y[k-2] / (k - 1) / sum_theta_i)
  414. prop = prop[::-1]
  415. # print(prop, "\n", sum(prop))
  416. # normalise to N0 (N0 of epoch1)
  417. x_ticks = ax1.get_xticks()
  418. for i in range(len(y)):
  419. y[i] = y[i]/N0
  420. # plot
  421. x_plot, y_plot = plot_straight_x_y(x, y)
  422. #plt.plot(x, y, 'o', linestyle="dotted", alpha=0.75, lw=2, label = str(epoch)+' brks')
  423. p, = ax1.plot(x_plot, y_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(epoch)+' brks')
  424. # add plot to the list of all plots to superimpose
  425. plots.append(p)
  426. #print(prop, "\n", sum(prop))
  427. #ax.legend(handles=[p0]+plots)
  428. ax1.set_xlabel("# bin", fontsize=fnt_size)
  429. # Set the x-axis locator to reduce the number of ticks to 10
  430. ax1.set_ylabel("theta", fontsize=fnt_size)
  431. ax1.set_title("Title", fontsize=fnt_size)
  432. ax1.legend(handles=plots, loc='best', fontsize = fnt_size*0.5)
  433. ax1.set_xticks(x_ticks)
  434. if len(prop) >= 18:
  435. ax1.locator_params(nbins=n_ticks)
  436. # new scale of ticks if too many values
  437. cumul = 0
  438. prop_cumul = []
  439. for val in prop:
  440. prop_cumul.append(val+cumul)
  441. cumul = val+cumul
  442. ax1.set_xticklabels([f'{x[k]}\n{val:.2f}' for k, val in enumerate(prop_cumul)])
  443. if ax is None:
  444. plt.savefig(title+'_raw'+str(k)+'.pdf')
  445. # fig 2 & 3
  446. if ax is None:
  447. fig2, ax2 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  448. fig3, ax3 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  449. else:
  450. # plt.rcParams['font.size'] = fnt_size
  451. # place of plots on the grid
  452. ax2 = ax[1,0]
  453. ax3 = ax[1,1]
  454. lines_fig2 = []
  455. lines_fig3 = []
  456. #plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
  457. for epoch, theta in epochs.items():
  458. groups = np.array(list(theta.values()), dtype=object)[:, 1].tolist()
  459. x = []
  460. y = []
  461. thetas = np.array(list(theta.values()), dtype=object)[:, 0]
  462. for i,group in enumerate(groups):
  463. x += group[::-1]
  464. y += list(np.repeat(thetas[i], len(group)))
  465. if epoch == 0:
  466. N0 = y[0]
  467. for i in range(len(y)):
  468. y[i] = y[i]/N0
  469. x_2 = []
  470. T = 0
  471. for i in range(len(x)):
  472. x[i] = int(x[i])
  473. # compute the times as: theta_k / (k*(k-1))
  474. for i in range(0, len(x)):
  475. T += y[i] / (x[i]*(x[i]-1))
  476. x_2.append(T)
  477. # Plotting (fig 2)
  478. x_2 = [0]+x_2
  479. y = [y[0]]+y
  480. x2_plot, y2_plot = plot_straight_x_y(x_2, y)
  481. p2, = ax2.plot(x2_plot, y2_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(epoch)+' brks')
  482. lines_fig2.append(p2)
  483. # Plotting (fig 3) which is the same but log scale for x
  484. p3, = ax3.plot(x2_plot, y2_plot, 'o', linestyle="-", alpha=0.75, lw=2, label = str(epoch)+' brks')
  485. lines_fig3.append(p3)
  486. ax2.set_xlabel("Relative scale", fontsize=fnt_size)
  487. ax2.set_ylabel("theta", fontsize=fnt_size)
  488. ax2.set_title("Title", fontsize=fnt_size)
  489. ax2.legend(handles=lines_fig2, loc='best', fontsize = fnt_size*0.5)
  490. if ax is None:
  491. plt.savefig(title+'_plot2_'+str(k)+'.pdf')
  492. ax3.set_xscale('log')
  493. ax3.set_yscale('log')
  494. ax3.set_xlabel("log Relative scale", fontsize=fnt_size)
  495. ax3.set_ylabel("theta", fontsize=fnt_size)
  496. ax3.set_title("Title", fontsize=fnt_size)
  497. ax3.legend(handles=lines_fig3, loc='best', fontsize = fnt_size*0.5)
  498. if ax is None:
  499. plt.savefig(title+'_plot3_'+str(k)+'_log.pdf')
  500. plt.clf()
  501. # return plots
  502. return ax
  503. def combined_plot(folder_path, mu, tgen, breaks, title = "Title", theta_scale = True):
  504. my_dpi = 300
  505. # Add some extra space for the second axis at the bottom
  506. #plt.rcParams['font.size'] = 18
  507. fig, axs = plt.subplots(3, 2, figsize=(5000/my_dpi, 2970/my_dpi), dpi=my_dpi)
  508. #plt.rcParams['font.size'] = 12
  509. ax = plot_all_epochs_thetafolder(folder_path, mu, tgen, title, theta_scale, ax = axs)
  510. ax = plot_test_theta(folder_path, mu, tgen, title, theta_scale, breaks_max = breaks, ax = axs)
  511. # Adjust layout to prevent clipping of titles
  512. plt.tight_layout()
  513. # Adjust absolute space between the top and bottom rows
  514. #plt.subplots_adjust(hspace=0.7) # Adjust this value based on your requirement
  515. # Save the entire grid as a single figure
  516. plt.savefig(title+'_combined.pdf')
  517. plt.clf()
  518. # second call for individual plots
  519. plot_all_epochs_thetafolder(folder_path, mu, tgen, title, theta_scale, ax = None)
  520. plot_test_theta(folder_path, mu, tgen, title, theta_scale, breaks_max = breaks, ax = None)
  521. plt.clf()
  522. if __name__ == "__main__":
  523. if len(sys.argv) != 4:
  524. print("Need 3 args: ThetaFolder MutationRate GenerationTime")
  525. exit(0)
  526. folder_path = sys.argv[1]
  527. mu = sys.argv[2]
  528. tgen = sys.argv[3]
  529. plot_all_epochs_thetafolder(folder_path, mu, tgen)