swp2.py 21KB

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