Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
52869 views
1
from .html_writer import HTMLWriter
2
from matplotlib.animation import Animation
3
import matplotlib.pyplot as plt
4
import tempfile
5
import random
6
import os
7
8
9
__all__ = ['anim_to_html', 'display_animation']
10
11
12
class _NameOnlyTemporaryFile(object):
13
"""A context-managed temporary file which is not opened.
14
15
The file should be accessible by name on any system.
16
17
Parameters
18
----------
19
suffix : string
20
The suffix of the temporary file (default = '')
21
prefix : string
22
The prefix of the temporary file (default = '_tmp_')
23
hash_length : string
24
The length of the random hash. The size of the hash space will
25
be 16 ** hash_length (default=8)
26
seed : integer
27
the seed for the random number generator. If not specified, the
28
system time will be used as a seed.
29
absolute : boolean
30
If true, return an absolute path to a temporary file in the current
31
working directory.
32
33
Example
34
-------
35
36
>>> with _NameOnlyTemporaryFile(seed=0, absolute=False) as f:
37
... print(f)
38
...
39
_tmp_d82c07cd
40
>>> os.path.exists('_tmp_d82c07cd') # file removed after context
41
False
42
43
"""
44
def __init__(self, prefix='_tmp_', suffix='', hash_length=8,
45
seed=None, absolute=True):
46
rng = random.Random(seed)
47
self.name = '%s%0*x%s' % (prefix, hash_length,
48
rng.getrandbits(4 * hash_length), suffix)
49
if absolute:
50
self.name = os.path.abspath(self.name)
51
52
def __enter__(self):
53
return self
54
55
def __exit__(self, *exc_info):
56
if os.path.exists(self.name):
57
os.remove(self.name)
58
59
60
def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'):
61
"""Generate HTML representation of the animation"""
62
if fps is None and hasattr(anim, '_interval'):
63
# Convert interval in ms to frames per second
64
fps = 1000. / anim._interval
65
66
plt.close(anim._fig)
67
if hasattr(anim, "_html_representation"):
68
return anim._html_representation
69
else:
70
# tempfile can't be used here: we need a filename, and this
71
# fails on windows. Instead, we use a custom filename generator
72
#with tempfile.NamedTemporaryFile(suffix='.html') as f:
73
with _NameOnlyTemporaryFile(suffix='.html') as f:
74
anim.save(f.name, writer=HTMLWriter(fps=fps,
75
embed_frames=embed_frames,
76
default_mode=default_mode))
77
html = open(f.name).read()
78
79
anim._html_representation = html
80
return html
81
82
83
def display_animation(anim, **kwargs):
84
"""Display the animation with an IPython HTML object"""
85
from IPython.display import HTML
86
return HTML(anim_to_html(anim, **kwargs))
87
88
89
# This is the magic that makes animations display automatically in the
90
# IPython notebook. The _repr_html_ method is a special method recognized
91
# by IPython.
92
Animation._repr_html_ = anim_to_html
93
94