test_pickle.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. from io import BytesIO
  2. import pickle
  3. import platform
  4. import numpy as np
  5. import pytest
  6. from matplotlib import cm
  7. from matplotlib.testing.decorators import image_comparison
  8. from matplotlib.dates import rrulewrapper
  9. import matplotlib.pyplot as plt
  10. import matplotlib.transforms as mtransforms
  11. import matplotlib.figure as mfigure
  12. def test_simple():
  13. fig = plt.figure()
  14. pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
  15. ax = plt.subplot(121)
  16. pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
  17. ax = plt.axes(projection='polar')
  18. plt.plot(np.arange(10), label='foobar')
  19. plt.legend()
  20. pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
  21. # ax = plt.subplot(121, projection='hammer')
  22. # pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
  23. plt.figure()
  24. plt.bar(x=np.arange(10), height=np.arange(10))
  25. pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)
  26. fig = plt.figure()
  27. ax = plt.axes()
  28. plt.plot(np.arange(10))
  29. ax.set_yscale('log')
  30. pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
  31. @image_comparison(['multi_pickle.png'], remove_text=True, style='mpl20',
  32. tol={'aarch64': 0.082}.get(platform.machine(), 0.0))
  33. def test_complete():
  34. fig = plt.figure('Figure with a label?', figsize=(10, 6))
  35. plt.suptitle('Can you fit any more in a figure?')
  36. # make some arbitrary data
  37. x, y = np.arange(8), np.arange(10)
  38. data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
  39. v = np.sin(v * -0.6)
  40. # Ensure lists also pickle correctly.
  41. plt.subplot(3, 3, 1)
  42. plt.plot(list(range(10)))
  43. plt.subplot(3, 3, 2)
  44. plt.contourf(data, hatches=['//', 'ooo'])
  45. plt.colorbar()
  46. plt.subplot(3, 3, 3)
  47. plt.pcolormesh(data)
  48. plt.subplot(3, 3, 4)
  49. plt.imshow(data)
  50. plt.subplot(3, 3, 5)
  51. plt.pcolor(data)
  52. ax = plt.subplot(3, 3, 6)
  53. ax.set_xlim(0, 7)
  54. ax.set_ylim(0, 9)
  55. plt.streamplot(x, y, u, v)
  56. ax = plt.subplot(3, 3, 7)
  57. ax.set_xlim(0, 7)
  58. ax.set_ylim(0, 9)
  59. plt.quiver(x, y, u, v)
  60. plt.subplot(3, 3, 8)
  61. plt.scatter(x, x**2, label='$x^2$')
  62. plt.legend(loc='upper left')
  63. plt.subplot(3, 3, 9)
  64. plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4)
  65. #
  66. # plotting is done, now test its pickle-ability
  67. #
  68. result_fh = BytesIO()
  69. pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL)
  70. plt.close('all')
  71. # make doubly sure that there are no figures left
  72. assert plt._pylab_helpers.Gcf.figs == {}
  73. # wind back the fh and load in the figure
  74. result_fh.seek(0)
  75. fig = pickle.load(result_fh)
  76. # make sure there is now a figure manager
  77. assert plt._pylab_helpers.Gcf.figs != {}
  78. assert fig.get_label() == 'Figure with a label?'
  79. def test_no_pyplot():
  80. # tests pickle-ability of a figure not created with pyplot
  81. from matplotlib.backends.backend_pdf import FigureCanvasPdf
  82. from matplotlib.figure import Figure
  83. fig = Figure()
  84. _ = FigureCanvasPdf(fig)
  85. ax = fig.add_subplot(1, 1, 1)
  86. ax.plot([1, 2, 3], [1, 2, 3])
  87. pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
  88. def test_renderer():
  89. from matplotlib.backends.backend_agg import RendererAgg
  90. renderer = RendererAgg(10, 20, 30)
  91. pickle.dump(renderer, BytesIO())
  92. def test_image():
  93. # Prior to v1.4.0 the Image would cache data which was not picklable
  94. # once it had been drawn.
  95. from matplotlib.backends.backend_agg import new_figure_manager
  96. manager = new_figure_manager(1000)
  97. fig = manager.canvas.figure
  98. ax = fig.add_subplot(1, 1, 1)
  99. ax.imshow(np.arange(12).reshape(3, 4))
  100. manager.canvas.draw()
  101. pickle.dump(fig, BytesIO())
  102. def test_polar():
  103. plt.subplot(111, polar=True)
  104. fig = plt.gcf()
  105. pf = pickle.dumps(fig)
  106. pickle.loads(pf)
  107. plt.draw()
  108. class TransformBlob:
  109. def __init__(self):
  110. self.identity = mtransforms.IdentityTransform()
  111. self.identity2 = mtransforms.IdentityTransform()
  112. # Force use of the more complex composition.
  113. self.composite = mtransforms.CompositeGenericTransform(
  114. self.identity,
  115. self.identity2)
  116. # Check parent -> child links of TransformWrapper.
  117. self.wrapper = mtransforms.TransformWrapper(self.composite)
  118. # Check child -> parent links of TransformWrapper.
  119. self.composite2 = mtransforms.CompositeGenericTransform(
  120. self.wrapper,
  121. self.identity)
  122. def test_transform():
  123. obj = TransformBlob()
  124. pf = pickle.dumps(obj)
  125. del obj
  126. obj = pickle.loads(pf)
  127. # Check parent -> child links of TransformWrapper.
  128. assert obj.wrapper._child == obj.composite
  129. # Check child -> parent links of TransformWrapper.
  130. assert [v() for v in obj.wrapper._parents.values()] == [obj.composite2]
  131. # Check input and output dimensions are set as expected.
  132. assert obj.wrapper.input_dims == obj.composite.input_dims
  133. assert obj.wrapper.output_dims == obj.composite.output_dims
  134. def test_rrulewrapper():
  135. r = rrulewrapper(2)
  136. try:
  137. pickle.loads(pickle.dumps(r))
  138. except RecursionError:
  139. print('rrulewrapper pickling test failed')
  140. raise
  141. def test_shared():
  142. fig, axs = plt.subplots(2, sharex=True)
  143. fig = pickle.loads(pickle.dumps(fig))
  144. fig.axes[0].set_xlim(10, 20)
  145. assert fig.axes[1].get_xlim() == (10, 20)
  146. @pytest.mark.parametrize("cmap", cm.cmap_d.values())
  147. def test_cmap(cmap):
  148. pickle.dumps(cmap)
  149. def test_unpickle_canvas():
  150. fig = mfigure.Figure()
  151. assert fig.canvas is not None
  152. out = BytesIO()
  153. pickle.dump(fig, out)
  154. out.seek(0)
  155. fig2 = pickle.load(out)
  156. assert fig2.canvas is not None