customgraphics.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. """ Custom graphics lib for pop gen or genomics
  2. FOREST Thomas (thomas.forest@college-de-france.fr)
  3. """
  4. import matplotlib.pyplot as plt
  5. import matplotlib.ticker as ticker
  6. import numpy as np
  7. import gc
  8. import time
  9. import datetime
  10. import pandas as pd
  11. # custom libs
  12. from frst import vcf_utils
  13. def heatmap(data, row_labels=None, col_labels=None, ax=None,
  14. cbar_kw={}, cbarlabel="", **kwargs):
  15. """
  16. Create a heatmap from a numpy array and two lists of labels.
  17. (from the matplotlib doc)
  18. Parameters
  19. ----------
  20. data
  21. A 2D numpy array of shape (M, N).
  22. row_labels
  23. A list or array of length M with the labels for the rows.
  24. col_labels
  25. A list or array of length N with the labels for the columns.
  26. ax
  27. A `matplotlib.axes.Axes` instance to which the heatmap is plotted. If
  28. not provided, use current axes or create a new one. Optional.
  29. cbar_kw
  30. A dictionary with arguments to `matplotlib.Figure.colorbar`. Optional.
  31. cbarlabel
  32. The label for the colorbar. Optional.
  33. **kwargs
  34. All other arguments are forwarded to `imshow`.
  35. """
  36. if not ax:
  37. ax = plt.gca()
  38. # Plot the heatmap
  39. im = ax.imshow(data, **kwargs)
  40. # Create colorbar
  41. cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
  42. cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
  43. # Show all ticks and label them with the respective list entries.
  44. if col_labels:
  45. ax.set_xticks(col_labels)
  46. if row_labels:
  47. ax.set_yticks(row_labels)
  48. # Let the horizontal axes labeling appear on top.
  49. ax.tick_params(top=True, bottom=False,
  50. labeltop=True, labelbottom=False)
  51. # Rotate the tick labels and set their alignment.
  52. plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
  53. rotation_mode="anchor")
  54. # Turn spines off and create white grid.
  55. ax.spines[:].set_visible(False)
  56. ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
  57. ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
  58. ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
  59. ax.tick_params(which="minor", bottom=False, left=False)
  60. return im, cbar
  61. def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
  62. textcolors=("black", "white"),
  63. threshold=None, **textkw):
  64. """
  65. A function to annotate a heatmap.
  66. (from the matplotlib doc)
  67. Parameters
  68. ----------
  69. im
  70. The AxesImage to be labeled.
  71. data
  72. Data used to annotate. If None, the image's data is used. Optional.
  73. valfmt
  74. The format of the annotations inside the heatmap. This should either
  75. use the string format method, e.g. "$ {x:.2f}", or be a
  76. `matplotlib.ticker.Formatter`. Optional.
  77. textcolors
  78. A pair of colors. The first is used for values below a threshold,
  79. the second for those above. Optional.
  80. threshold
  81. Value in data units according to which the colors from textcolors are
  82. applied. If None (the default) uses the middle of the colormap as
  83. separation. Optional.
  84. **kwargs
  85. All other arguments are forwarded to each call to `text` used to create
  86. the text labels.
  87. """
  88. if not isinstance(data, (list, np.ndarray)):
  89. data = im.get_array()
  90. # Normalize the threshold to the images color range.
  91. if threshold is not None:
  92. threshold = im.norm(threshold)
  93. else:
  94. threshold = im.norm(data.max())/2.
  95. # Set default alignment to center, but allow it to be
  96. # overwritten by textkw.
  97. kw = dict(horizontalalignment="center",
  98. verticalalignment="center")
  99. kw.update(textkw)
  100. # Get the formatter in case a string is supplied
  101. if isinstance(valfmt, str):
  102. valfmt = ticker.StrMethodFormatter(valfmt)
  103. # Loop over the data and create a `Text` for each "pixel".
  104. # Change the text's color depending on the data.
  105. texts = []
  106. for i in range(data.shape[0]):
  107. for j in range(data.shape[1]):
  108. kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])
  109. text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
  110. texts.append(text)
  111. return texts
  112. def plot_matrix(mat, legend=None, color_scale_type="YlGn", cbarlabel = "qt", title=None):
  113. fig, ax = plt.subplots(figsize=(10,8))
  114. if legend:
  115. row_labels = [k for k in range(len(mat))]
  116. col_labels = [k for k in range(len(mat[0]))]
  117. im, cbar = heatmap(mat, row_labels, col_labels, ax=ax,
  118. cmap=color_scale_type, cbarlabel=cbarlabel)
  119. else:
  120. im, cbar = heatmap(mat, ax=ax,
  121. cmap=color_scale_type, cbarlabel=cbarlabel)
  122. #texts = annotate_heatmap(im, valfmt="{x:.5f}")
  123. if title:
  124. ax.set_title(title)
  125. fig.tight_layout()
  126. plt.show()
  127. def plot(x, y, outfile = None, outfolder = None, ylab=None, xlab=None,
  128. title=None, label = None, show=True, nb_subplots = None, subplot_init = False,
  129. subplot_id = None, output = None, dpi = 300, width = 15, height = 15, plot_init = True):
  130. # before fig is generated, set its dimensions
  131. if plot_init:
  132. plt.figure(figsize=(width, height))
  133. if subplot_init:
  134. # define a certain amount of subplots
  135. fig, axs = plt.subplots(nb_subplots)
  136. if x:
  137. if nb_subplots:
  138. axs[subplot_id].plot(x, y)
  139. else:
  140. fig, = plt.plot(x, y)
  141. else:
  142. # x is optional
  143. if nb_subplots:
  144. # define a certain amount of subplots
  145. axs[subplot_id].plot(y)
  146. else:
  147. fig, = plt.plot(y)
  148. if label:
  149. # if legend
  150. fig.set_label(label)
  151. plt.legend()
  152. if ylab:
  153. plt.ylabel(ylab)
  154. if xlab:
  155. plt.xlabel(xlab)
  156. if title:
  157. plt.title(title)
  158. if outfile:
  159. plt.savefig(outfile, dpi = dpi)
  160. if show == True:
  161. plt.show()
  162. def scatter(x, y, ylab=None, xlab=None, title=None):
  163. plt.scatter(x, y)
  164. if ylab:
  165. plt.ylabel(ylab)
  166. if xlab:
  167. plt.xlabel(xlab)
  168. if title:
  169. plt.title(title)
  170. plt.show()
  171. def barplot(x=None, y=None, ylab=None, xlab=None, title=None, label=None, xticks = None, width=1):
  172. if x:
  173. x = list(x)
  174. plt.xticks(x)
  175. plt.bar(x, y, width=width, label=label)
  176. else:
  177. x = list(range(len(y)))
  178. plt.bar(x, y, width=width, label=label)
  179. plt.xticks(x)
  180. if ylab:
  181. plt.ylabel(ylab)
  182. if xlab:
  183. plt.xlabel(xlab)
  184. if title:
  185. plt.title(title)
  186. if xticks:
  187. plt.xticks(xticks)
  188. plt.legend()
  189. plt.show()
  190. def plot_chrom_continuity(vcf_entries, chr_id, x=None, y=None, outfile = None,
  191. outfolder = None, returned=False, show=True, label=True, step=1, nb_subplots = None,
  192. subplot_init = False, subplot_id = None, title = None, plot_init = False):
  193. chr_name = list(vcf_entries.keys())[chr_id]
  194. if label:
  195. label = chr_name
  196. if not title:
  197. title = "Genotyped pos in chr "+str(chr_id+1)+":'"+chr_name+"'"
  198. chr_entries = vcf_entries[chr_name]
  199. genotyped_pos = vcf_utils.genotyping_continuity_plot(chr_entries, step=step)
  200. if returned:
  201. # if we do not want to plot while executing
  202. # useful for storing the x,y coords in a variable for ex.
  203. return genotyped_pos
  204. else:
  205. # to plot on the fly
  206. plot(x=genotyped_pos[0], y=genotyped_pos[1], ylab = "genotyped pos.",
  207. xlab = "pos. in ref.",
  208. title = title,
  209. outfile = outfile, outfolder = outfolder, show=show, label=label,
  210. nb_subplots = nb_subplots, subplot_init = subplot_init, subplot_id = subplot_id, plot_init = plot_init)
  211. def plot_whole_karyotype(recent_variants, mem_clean = False, step = 1, show = True, min_chr_id = 0,
  212. max_chr_id = None, stacked = False, title = None, outfile = None):
  213. coords = []
  214. if max_chr_id :
  215. nb_iter = max_chr_id
  216. else:
  217. nb_iter = len(recent_variants) -1
  218. if show :
  219. iter_start = min_chr_id + 1
  220. if step == "auto" :
  221. step = round(len(recent_variants[list(recent_variants.keys())[min_chr_id]]) / 1000)
  222. if stacked:
  223. nb_subplots = nb_iter - min_chr_id
  224. subplot_init = True
  225. else:
  226. nb_subplots = None
  227. subplot_init = False
  228. vcf_utils.customgraphics.plot_chrom_continuity(recent_variants, chr_id = min_chr_id, show = False, returned = False, step = step,
  229. nb_subplots = nb_subplots, subplot_init = subplot_init, subplot_id = min_chr_id, plot_init = True)
  230. else :
  231. iter_start = 0
  232. for chr in range(iter_start, nb_iter):
  233. if show == False:
  234. x, y = vcf_utils.customgraphics.plot_chrom_continuity(recent_variants, chr_id = chr, show = False, returned = True, step = step)
  235. coords.append([x, y])
  236. if mem_clean:
  237. start = time.time()
  238. del x
  239. del y
  240. gc.collect()
  241. end = time.time()
  242. print("Cleaned mem. in", str(datetime.timedelta(seconds=end - start)))
  243. else:
  244. # if show is enable, use a step
  245. if step == "auto":
  246. step = round(len(recent_variants[list(recent_variants.keys())[chr]]) / 1000)
  247. vcf_utils.customgraphics.plot_chrom_continuity(recent_variants, chr_id = chr, show = False, returned = False, step = step, subplot_id = chr)
  248. # last case
  249. if show == True:
  250. vcf_utils.customgraphics.plot_chrom_continuity(recent_variants, chr_id = nb_iter, show = True, returned = False, step = step, subplot_id = nb_iter,
  251. title = title,
  252. outfile = outfile, plot_init = False)
  253. # maybe add a clean of recent_variants in extreme cases, before building the plots
  254. if show == False:
  255. return coords
  256. def plot_chrom_coverage(vcf_entries, chr_id):
  257. chr_name = list(vcf_entries.keys())[chr_id]
  258. chr_entries = vcf_entries[chr_name]
  259. coverage = vcf_utils.compute_coverage(chr_entries)
  260. barplot(coverage[0], coverage[1], ylab = "coverage (X)",
  261. xlab = "pos. in ref.",
  262. title = "Coverage for chr "+str(chr_id+1)+":'"+chr_name+"'")