├── .gitignore
├── .travis.yml
├── History.md
├── LICENSE
├── Makefile
├── README.md
├── celluloid.py
├── examples
├── complex.py
├── legends.py
├── simple.py
└── sines.py
├── mypy.ini
├── pylintrc
├── pyproject.toml
├── pytest.ini
├── setup.cfg
├── test-requirements.txt
└── test_celluloid.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.ipynb*
2 | *.gif
3 | *.png
4 | *.mp4
5 | *.html
6 | *.sh
7 | tags
8 |
9 | # Created by https://www.gitignore.io/api/python
10 | # Edit at https://www.gitignore.io/?templates=python
11 |
12 | ### Python ###
13 | # Byte-compiled / optimized / DLL files
14 | __pycache__/
15 | *.py[cod]
16 | *$py.class
17 |
18 | # C extensions
19 | *.so
20 |
21 | # Distribution / packaging
22 | .Python
23 | build/
24 | develop-eggs/
25 | dist/
26 | downloads/
27 | eggs/
28 | .eggs/
29 | lib/
30 | lib64/
31 | parts/
32 | sdist/
33 | var/
34 | wheels/
35 | *.egg-info/
36 | .installed.cfg
37 | *.egg
38 | MANIFEST
39 |
40 | # PyInstaller
41 | # Usually these files are written by a python script from a template
42 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
43 | *.manifest
44 | *.spec
45 |
46 | # Installer logs
47 | pip-log.txt
48 | pip-delete-this-directory.txt
49 |
50 | # Unit test / coverage reports
51 | htmlcov/
52 | .tox/
53 | .nox/
54 | .coverage
55 | .coverage.*
56 | .cache
57 | nosetests.xml
58 | coverage.xml
59 | *.cover
60 | .hypothesis/
61 | .pytest_cache/
62 |
63 | # Translations
64 | *.mo
65 | *.pot
66 |
67 | # Django stuff:
68 | *.log
69 | local_settings.py
70 | db.sqlite3
71 |
72 | # Flask stuff:
73 | instance/
74 | .webassets-cache
75 |
76 | # Scrapy stuff:
77 | .scrapy
78 |
79 | # Sphinx documentation
80 | docs/_build/
81 |
82 | # PyBuilder
83 | target/
84 |
85 | # Jupyter Notebook
86 | .ipynb_checkpoints
87 |
88 | # IPython
89 | profile_default/
90 | ipython_config.py
91 |
92 | # pyenv
93 | .python-version
94 |
95 | # celery beat schedule file
96 | celerybeat-schedule
97 |
98 | # SageMath parsed files
99 | *.sage.py
100 |
101 | # Environments
102 | .env
103 | .venv
104 | env/
105 | venv/
106 | ENV/
107 | env.bak/
108 | venv.bak/
109 |
110 | # Spyder project settings
111 | .spyderproject
112 | .spyproject
113 |
114 | # Rope project settings
115 | .ropeproject
116 |
117 | # mkdocs documentation
118 | /site
119 |
120 | # mypy
121 | .mypy_cache/
122 | .dmypy.json
123 | dmypy.json
124 |
125 | # Pyre type checker
126 | .pyre/
127 |
128 | ### Python Patch ###
129 | .venv/
130 |
131 | ### Python.VirtualEnv Stack ###
132 | # Virtualenv
133 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
134 | [Bb]in
135 | [Ii]nclude
136 | [Ll]ib
137 | [Ll]ib64
138 | [Ll]ocal
139 | [Ss]cripts
140 | pyvenv.cfg
141 | pip-selfcheck.json
142 |
143 | # End of https://www.gitignore.io/api/python
144 |
145 | # Created by https://www.gitignore.io/api/osx
146 | # Edit at https://www.gitignore.io/?templates=osx
147 |
148 | ### OSX ###
149 | # General
150 | .DS_Store
151 | .AppleDouble
152 | .LSOverride
153 |
154 | # Icon must end with two \r
155 | Icon
156 |
157 | # Thumbnails
158 | ._*
159 |
160 | # Files that might appear in the root of a volume
161 | .DocumentRevisions-V100
162 | .fseventsd
163 | .Spotlight-V100
164 | .TemporaryItems
165 | .Trashes
166 | .VolumeIcon.icns
167 | .com.apple.timemachine.donotpresent
168 |
169 | # Directories potentially created on remote AFP share
170 | .AppleDB
171 | .AppleDesktop
172 | Network Trash Folder
173 | Temporary Items
174 | .apdisk
175 |
176 | # End of https://www.gitignore.io/api/osx
177 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | dist: xenial
2 | language: python
3 | cache: pip
4 | python:
5 | - "3.6"
6 | - "3.7"
7 | install:
8 | - pip install -r test-requirements.txt
9 | script:
10 | - make test
11 | - codecov
12 |
--------------------------------------------------------------------------------
/History.md:
--------------------------------------------------------------------------------
1 |
2 | 0.2.0 / 2018-11-19
3 | ==================
4 |
5 | * support for images and legends (#4)
6 | * add more examples
7 |
8 | 0.1.0 / 2018-11-17
9 | ==================
10 |
11 | * Initial release
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Jacques Kvam
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: test lint static
2 |
3 | all: test
4 |
5 | test:
6 | py.test --cov=./ --mypy --codestyle --docstyle --pylint --pylint-rcfile=pylintrc --pylint-error-types=RCWEF
7 |
8 | lint:
9 | py.test --pylint -m pylint --pylint-rcfile=pylintrc --pylint-error-types=RCWEF
10 |
11 | static:
12 | mypy -m celluloid
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # celluloid
2 |
3 | [](https://travis-ci.com/jwkvam/celluloid)
4 | [](https://codecov.io/gh/jwkvam/celluloid)
5 | [](https://pypi.org/project/celluloid/)
6 | [](https://pypi.org/project/celluloid/)
7 |
8 | Easy Matplotlib Animation
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Creating animations should be easy.
17 | This module makes it easy to adapt your existing visualization code to create an animation.
18 |
19 | ## Install
20 |
21 | ```
22 | pip install celluloid
23 | ```
24 |
25 | ## Manual
26 |
27 | Follow these steps:
28 |
29 | 1. Create a matplotlib `Figure` and create a `Camera` from it:
30 |
31 | ```python
32 | from celluloid import Camera
33 | fig = plt.figure()
34 | camera = Camera(fig)
35 | ```
36 |
37 | 2. Reusing the figure and after each frame is created, take a snapshot with the camera.
38 |
39 | ```python
40 | plt.plot(...)
41 | plt.fancy_stuff()
42 | camera.snap()
43 | ```
44 |
45 | 3. After all frames have been captured, create the animation.
46 |
47 | ```python
48 | animation = camera.animate()
49 | animation.save('animation.mp4')
50 | ```
51 |
52 | The entire [module](https://github.com/jwkvam/celluloid/blob/master/celluloid.py) is less than 50 lines of code.
53 |
54 | ### Viewing in Jupyter Notebooks
55 |
56 | View videos in notebooks with [IPython](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.HTML).
57 |
58 | ```python
59 | from IPython.display import HTML
60 | animation = camera.animate()
61 | HTML(animation.to_html5_video())
62 | ```
63 |
64 | ## Examples
65 |
66 | ### Minimal
67 |
68 | As simple as it gets.
69 |
70 | ```python
71 | from matplotlib import pyplot as plt
72 | from celluloid import Camera
73 |
74 | fig = plt.figure()
75 | camera = Camera(fig)
76 | for i in range(10):
77 | plt.plot([i] * 10)
78 | camera.snap()
79 | animation = camera.animate()
80 | ```
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 | ### Subplots
89 |
90 | Animation at the top.
91 |
92 | ```python
93 | import numpy as np
94 | from matplotlib import pyplot as plt
95 | from celluloid import Camera
96 |
97 | fig, axes = plt.subplots(2)
98 | camera = Camera(fig)
99 | t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
100 | for i in t:
101 | axes[0].plot(t, np.sin(t + i), color='blue')
102 | axes[1].plot(t, np.sin(t - i), color='blue')
103 | camera.snap()
104 | animation = camera.animate()
105 | ```
106 |
107 | ### Images
108 |
109 | Domain coloring example.
110 |
111 | ```python
112 | import numpy as np
113 | from matplotlib import pyplot as plt
114 | from matplotlib.colors import hsv_to_rgb
115 |
116 | from celluloid import Camera
117 |
118 | fig = plt.figure()
119 | camera = Camera(fig)
120 |
121 | for a in np.linspace(0, 2 * np.pi, 30, endpoint=False):
122 | x = np.linspace(-3, 3, 800)
123 | X, Y = np.meshgrid(x, x)
124 | x = X + 1j * Y
125 | y = (x ** 2 - 2.5) * (x - 2.5 * 1j) * (x + 2.5 * 1j) \
126 | * (x - 2 - 1j) ** 2 / ((x - np.exp(1j * a)) ** 2
127 | * (x - np.exp(1j * 2 * a)) ** 2)
128 |
129 | H = np.angle(y) / (2 * np.pi) + .5
130 | r = np.log2(1. + np.abs(y))
131 | S = (1. + np.abs(np.sin(2. * np.pi * r))) / 2.
132 | V = (1. + np.abs(np.cos(2. * np.pi * r))) / 2.
133 |
134 | rgb = hsv_to_rgb(np.dstack((H, S, V)))
135 | ax.imshow(rgb)
136 | camera.snap()
137 | animation = camera.animate()
138 | ```
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 | ### Legends
147 |
148 | ```python
149 | import matplotlib
150 | from matplotlib import pyplot as plt
151 | from celluloid import Camera
152 |
153 | fig = plt.figure()
154 | camera = Camera(fig)
155 | for i in range(5):
156 | t = plt.plot(range(i, i + 5))
157 | plt.legend(t, [f'line {i}'])
158 | camera.snap()
159 | animation = camera.animate()
160 | ```
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 | ## Limitations
169 |
170 | - The axes' limits should be the same for all plots. The limits of the animation will be the limits of the final plot.
171 | - Legends will accumulate from previous frames. Pass the artists to the [`legend`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html) function to draw them separately.
172 | - [Animating the title does not work](https://stackoverflow.com/questions/47421486/matplotlib-artist-animation-title-or-text-not-changing). As a workaround you can create a text object:
173 | ```python
174 | ax.text(0.5, 1.01, 'computed title', transform=ax.transAxes)
175 | ```
176 | - This can demand a lot of memory since it uses [`ArtistAnimation`](https://matplotlib.org/api/_as_gen/matplotlib.animation.ArtistAnimation.html) under the hood. This means that all artists are saved to memory before the animation is constructed.
177 | - This is a black box. If you want to understand how matplotlib animations work, using this library may hinder you. If you want to be an expert matplotlib user, you may want to pass on this library.
178 |
179 | ## Credits
180 |
181 | Inspired by [plotnine](https://github.com/has2k1/plotnine/blob/master/plotnine/animation.py).
182 |
--------------------------------------------------------------------------------
/celluloid.py:
--------------------------------------------------------------------------------
1 | """Easy matplotlib animation."""
2 | from typing import Dict, List
3 | from collections import defaultdict
4 |
5 | from matplotlib.figure import Figure
6 | from matplotlib.artist import Artist
7 | from matplotlib.animation import ArtistAnimation
8 |
9 |
10 | __version__ = '0.2.0'
11 |
12 |
13 | class Camera:
14 | """Make animations easier."""
15 |
16 | def __init__(self, figure: Figure) -> None:
17 | """Create camera from matplotlib figure."""
18 | self._figure = figure
19 | # need to keep track off artists for each axis
20 | self._offsets: Dict[str, Dict[int, int]] = {
21 | k: defaultdict(int) for k in [
22 | 'collections', 'patches', 'lines', 'texts', 'artists', 'images'
23 | ]
24 | }
25 | self._photos: List[List[Artist]] = []
26 |
27 | def snap(self) -> List[Artist]:
28 | """Capture current state of the figure."""
29 | frame_artists: List[Artist] = []
30 | for i, axis in enumerate(self._figure.axes):
31 | if axis.legend_ is not None:
32 | axis.add_artist(axis.legend_)
33 | for name in self._offsets:
34 | new_artists = getattr(axis, name)[self._offsets[name][i]:]
35 | frame_artists += new_artists
36 | self._offsets[name][i] += len(new_artists)
37 | self._photos.append(frame_artists)
38 | return frame_artists
39 |
40 | def animate(self, *args, **kwargs) -> ArtistAnimation:
41 | """Animate the snapshots taken.
42 |
43 | Uses matplotlib.animation.ArtistAnimation
44 |
45 | Returns
46 | -------
47 | ArtistAnimation
48 |
49 | """
50 | return ArtistAnimation(self._figure, self._photos, *args, **kwargs)
51 |
--------------------------------------------------------------------------------
/examples/complex.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Complex domain coloring."""
3 |
4 | import numpy as np
5 | import matplotlib
6 | matplotlib.use('Agg')
7 | from matplotlib import pyplot as plt
8 | from matplotlib.colors import hsv_to_rgb
9 | from tqdm import tqdm
10 | from celluloid import Camera
11 |
12 | fig = plt.figure()
13 | # hack to remove border
14 | # https://stackoverflow.com/a/37810568/744520
15 | fig.set_size_inches(4, 4, forward=False)
16 | ax = plt.Axes(fig, [0, 0, 1, 1])
17 | ax.set_axis_off()
18 | fig.add_axes(ax)
19 | camera = Camera(fig)
20 |
21 | for a in tqdm(np.linspace(0, 2 * np.pi, 30, endpoint=False)):
22 | x = np.linspace(-3, 3, 800)
23 | X, Y = np.meshgrid(x, x)
24 | x = X + 1j * Y
25 | y = (x ** 2 - 2.5) * (x - 2.5 * 1j) * (x + 2.5 * 1j) * (x - 2 - 1j) ** 2 / ((x - np.exp(1j * a)) ** 2 * (x - np.exp(1j * 2 * a)) ** 2)
26 |
27 | H = np.angle(y) / (2 * np.pi) + .5
28 | r = np.log2(1. + np.abs(y))
29 | S = (1. + np.abs(np.sin(2. * np.pi * r))) / 2.
30 | V = (1. + np.abs(np.cos(2. * np.pi * r))) / 2.
31 |
32 | rgb = hsv_to_rgb(np.dstack((H, S, V)))
33 | ax.imshow(rgb)
34 | camera.snap()
35 | animation = camera.animate(interval=50, blit=True)
36 | animation.save(
37 | 'complex.mp4',
38 | dpi=100,
39 | savefig_kwargs={
40 | 'frameon': False,
41 | 'pad_inches': 0
42 | }
43 | )
44 |
--------------------------------------------------------------------------------
/examples/legends.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Legend example."""
3 |
4 | import matplotlib
5 | matplotlib.use('Agg')
6 | from matplotlib import pyplot as plt
7 | from celluloid import Camera
8 |
9 | fig = plt.figure()
10 | camera = Camera(fig)
11 | for i in range(5):
12 | t = plt.plot(range(i, i + 5))
13 | plt.legend(t, [f'line {i}'])
14 | camera.snap()
15 | animation = camera.animate(interval=300, blit=True)
16 | animation.save(
17 | 'legends.mp4',
18 | dpi=100,
19 | savefig_kwargs={
20 | 'frameon': False,
21 | 'pad_inches': 'tight'
22 | }
23 | )
24 |
--------------------------------------------------------------------------------
/examples/simple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Simple animation."""
3 |
4 | import matplotlib
5 | matplotlib.use('Agg')
6 | from matplotlib import pyplot as plt
7 | from celluloid import Camera
8 |
9 | fig = plt.figure()
10 | camera = Camera(fig)
11 | for i in range(10):
12 | plt.plot([i] * 10)
13 | camera.snap()
14 | animation = camera.animate(interval=100, blit=True)
15 | animation.save(
16 | 'simple.mp4',
17 | dpi=100,
18 | savefig_kwargs={
19 | 'frameon': False,
20 | 'pad_inches': 'tight'
21 | }
22 | )
23 |
--------------------------------------------------------------------------------
/examples/sines.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Sinusoid animation."""
3 |
4 | import numpy as np
5 | import matplotlib
6 | matplotlib.use('Agg')
7 | from matplotlib import pyplot as plt
8 | from celluloid import Camera
9 |
10 | fig, axes = plt.subplots(2)
11 | camera = Camera(fig)
12 | t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
13 | for i in t:
14 | axes[0].plot(t, np.sin(t + i), color='blue')
15 | axes[1].plot(t, np.sin(t - i), color='blue')
16 | camera.snap()
17 | animation = camera.animate(interval=50, blit=True)
18 | animation.save(
19 | 'sines.mp4',
20 | dpi=100,
21 | savefig_kwargs={
22 | 'frameon': False,
23 | 'pad_inches': 'tight'
24 | }
25 | )
26 |
--------------------------------------------------------------------------------
/mypy.ini:
--------------------------------------------------------------------------------
1 | [mypy]
2 | ignore_missing_imports=True
3 |
--------------------------------------------------------------------------------
/pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 |
3 | # A comma-separated list of package or module names from where C extensions may
4 | # be loaded. Extensions are loading into the active Python interpreter and may
5 | # run arbitrary code.
6 | extension-pkg-whitelist=
7 |
8 | # Add files or directories to the blacklist. They should be base names, not
9 | # paths.
10 | ignore=CVS
11 |
12 | # Add files or directories matching the regex patterns to the blacklist. The
13 | # regex matches against base names, not paths.
14 | ignore-patterns=
15 |
16 | # Python code to execute, usually for sys.path manipulation such as
17 | # pygtk.require().
18 | #init-hook=
19 |
20 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
21 | # number of processors available to use.
22 | jobs=1
23 |
24 | # Control the amount of potential inferred values when inferring a single
25 | # object. This can help the performance when dealing with large functions or
26 | # complex, nested conditions.
27 | limit-inference-results=100
28 |
29 | # List of plugins (as comma separated values of python modules names) to load,
30 | # usually to register additional checkers.
31 | load-plugins=
32 |
33 | # Pickle collected data for later comparisons.
34 | persistent=yes
35 |
36 | # Specify a configuration file.
37 | #rcfile=
38 |
39 | # When enabled, pylint would attempt to guess common misconfiguration and emit
40 | # user-friendly hints instead of false-positive error messages.
41 | suggestion-mode=yes
42 |
43 | # Allow loading of arbitrary C extensions. Extensions are imported into the
44 | # active Python interpreter and may run arbitrary code.
45 | unsafe-load-any-extension=no
46 |
47 |
48 | [MESSAGES CONTROL]
49 |
50 | # Only show warnings with the listed confidence levels. Leave empty to show
51 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
52 | confidence=
53 |
54 | # Disable the message, report, category or checker with the given id(s). You
55 | # can either give multiple identifiers separated by comma (,) or put this
56 | # option multiple times (only on the command line, not in the configuration
57 | # file where it should appear only once). You can also use "--disable=all" to
58 | # disable everything first and then reenable specific checks. For example, if
59 | # you want to run only the similarities checker, you can use "--disable=all
60 | # --enable=similarities". If you want to run only the classes checker, but have
61 | # no Warning level messages displayed, use "--disable=all --enable=classes
62 | # --disable=W".
63 | disable=
64 |
65 | # Enable the message, report, category or checker with the given id(s). You can
66 | # either give multiple identifier separated by comma (,) or put this option
67 | # multiple time (only on the command line, not in the configuration file where
68 | # it should appear only once). See also the "--disable" option for examples.
69 | enable=c-extension-no-member
70 |
71 |
72 | [REPORTS]
73 |
74 | # Python expression which should return a note less than 10 (10 is the highest
75 | # note). You have access to the variables errors warning, statement which
76 | # respectively contain the number of errors / warnings messages and the total
77 | # number of statements analyzed. This is used by the global evaluation report
78 | # (RP0004).
79 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
80 |
81 | # Template used to display messages. This is a python new-style format string
82 | # used to format the message information. See doc for all details.
83 | #msg-template=
84 |
85 | # Set the output format. Available formats are text, parseable, colorized, json
86 | # and msvs (visual studio). You can also give a reporter class, e.g.
87 | # mypackage.mymodule.MyReporterClass.
88 | output-format=text
89 |
90 | # Tells whether to display a full report or only the messages.
91 | reports=no
92 |
93 | # Activate the evaluation score.
94 | score=yes
95 |
96 |
97 | [REFACTORING]
98 |
99 | # Maximum number of nested blocks for function / method body
100 | max-nested-blocks=5
101 |
102 | # Complete name of functions that never returns. When checking for
103 | # inconsistent-return-statements if a never returning function is called then
104 | # it will be considered as an explicit return statement and no message will be
105 | # printed.
106 | never-returning-functions=sys.exit
107 |
108 |
109 | [LOGGING]
110 |
111 | # Format style used to check logging format string. `old` means using %
112 | # formatting, while `new` is for `{}` formatting.
113 | logging-format-style=old
114 |
115 | # Logging modules to check that the string format arguments are in logging
116 | # function parameter format.
117 | logging-modules=logging
118 |
119 |
120 | [SPELLING]
121 |
122 | # Limits count of emitted suggestions for spelling mistakes.
123 | max-spelling-suggestions=4
124 |
125 | # Spelling dictionary name. Available dictionaries: de_DE (myspell), fr_FR
126 | # (myspell), en_GB (myspell), en_AU (myspell), en_US (myspell)..
127 | spelling-dict=
128 |
129 | # List of comma separated words that should not be checked.
130 | spelling-ignore-words=
131 |
132 | # A path to a file that contains private dictionary; one word per line.
133 | spelling-private-dict-file=
134 |
135 | # Tells whether to store unknown words to indicated private dictionary in
136 | # --spelling-private-dict-file option instead of raising a message.
137 | spelling-store-unknown-words=no
138 |
139 |
140 | [MISCELLANEOUS]
141 |
142 | # List of note tags to take in consideration, separated by a comma.
143 | notes=FIXME,
144 | XXX,
145 | TODO
146 |
147 |
148 | [TYPECHECK]
149 |
150 | # List of decorators that produce context managers, such as
151 | # contextlib.contextmanager. Add to this list to register other decorators that
152 | # produce valid context managers.
153 | contextmanager-decorators=contextlib.contextmanager
154 |
155 | # List of members which are set dynamically and missed by pylint inference
156 | # system, and so shouldn't trigger E1101 when accessed. Python regular
157 | # expressions are accepted.
158 | generated-members=
159 |
160 | # Tells whether missing members accessed in mixin class should be ignored. A
161 | # mixin class is detected if its name ends with "mixin" (case insensitive).
162 | ignore-mixin-members=yes
163 |
164 | # Tells whether to warn about missing members when the owner of the attribute
165 | # is inferred to be None.
166 | ignore-none=yes
167 |
168 | # This flag controls whether pylint should warn about no-member and similar
169 | # checks whenever an opaque object is returned when inferring. The inference
170 | # can return multiple potential results while evaluating a Python object, but
171 | # some branches might not be evaluated, which results in partial inference. In
172 | # that case, it might be useful to still emit no-member and other checks for
173 | # the rest of the inferred objects.
174 | ignore-on-opaque-inference=yes
175 |
176 | # List of class names for which member attributes should not be checked (useful
177 | # for classes with dynamically set attributes). This supports the use of
178 | # qualified names.
179 | ignored-classes=optparse.Values,thread._local,_thread._local
180 |
181 | # List of module names for which member attributes should not be checked
182 | # (useful for modules/projects where namespaces are manipulated during runtime
183 | # and thus existing member attributes cannot be deduced by static analysis. It
184 | # supports qualified module names, as well as Unix pattern matching.
185 | ignored-modules=
186 |
187 | # Show a hint with possible names when a member name was not found. The aspect
188 | # of finding the hint is based on edit distance.
189 | missing-member-hint=yes
190 |
191 | # The minimum edit distance a name should have in order to be considered a
192 | # similar match for a missing member name.
193 | missing-member-hint-distance=1
194 |
195 | # The total number of similar names that should be taken in consideration when
196 | # showing a hint for a missing member.
197 | missing-member-max-choices=1
198 |
199 |
200 | [VARIABLES]
201 |
202 | # List of additional names supposed to be defined in builtins. Remember that
203 | # you should avoid defining new builtins when possible.
204 | additional-builtins=
205 |
206 | # Tells whether unused global variables should be treated as a violation.
207 | allow-global-unused-variables=yes
208 |
209 | # List of strings which can identify a callback function by name. A callback
210 | # name must start or end with one of those strings.
211 | callbacks=cb_,
212 | _cb
213 |
214 | # A regular expression matching the name of dummy variables (i.e. expected to
215 | # not be used).
216 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
217 |
218 | # Argument names that match this expression will be ignored. Default to name
219 | # with leading underscore.
220 | ignored-argument-names=_.*|^ignored_|^unused_
221 |
222 | # Tells whether we should check for unused import in __init__ files.
223 | init-import=no
224 |
225 | # List of qualified module names which can have objects that can redefine
226 | # builtins.
227 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
228 |
229 |
230 | [FORMAT]
231 |
232 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
233 | expected-line-ending-format=
234 |
235 | # Regexp for a line that is allowed to be longer than the limit.
236 | ignore-long-lines=^\s*(# )??$
237 |
238 | # Number of spaces of indent required inside a hanging or continued line.
239 | indent-after-paren=4
240 |
241 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
242 | # tab).
243 | indent-string=' '
244 |
245 | # Maximum number of characters on a single line.
246 | max-line-length=100
247 |
248 | # Maximum number of lines in a module.
249 | max-module-lines=1000
250 |
251 | # List of optional constructs for which whitespace checking is disabled. `dict-
252 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
253 | # `trailing-comma` allows a space between comma and closing bracket: (a, ).
254 | # `empty-line` allows space-only lines.
255 | no-space-check=trailing-comma,
256 | dict-separator
257 |
258 | # Allow the body of a class to be on the same line as the declaration if body
259 | # contains single statement.
260 | single-line-class-stmt=no
261 |
262 | # Allow the body of an if to be on the same line as the test if there is no
263 | # else.
264 | single-line-if-stmt=no
265 |
266 |
267 | [SIMILARITIES]
268 |
269 | # Ignore comments when computing similarities.
270 | ignore-comments=yes
271 |
272 | # Ignore docstrings when computing similarities.
273 | ignore-docstrings=yes
274 |
275 | # Ignore imports when computing similarities.
276 | ignore-imports=no
277 |
278 | # Minimum lines number of a similarity.
279 | min-similarity-lines=4
280 |
281 |
282 | [BASIC]
283 |
284 | # Naming style matching correct argument names.
285 | argument-naming-style=snake_case
286 |
287 | # Regular expression matching correct argument names. Overrides argument-
288 | # naming-style.
289 | #argument-rgx=
290 |
291 | # Naming style matching correct attribute names.
292 | attr-naming-style=snake_case
293 |
294 | # Regular expression matching correct attribute names. Overrides attr-naming-
295 | # style.
296 | #attr-rgx=
297 |
298 | # Bad variable names which should always be refused, separated by a comma.
299 | bad-names=foo,
300 | bar,
301 | baz,
302 | toto,
303 | tutu,
304 | tata
305 |
306 | # Naming style matching correct class attribute names.
307 | class-attribute-naming-style=any
308 |
309 | # Regular expression matching correct class attribute names. Overrides class-
310 | # attribute-naming-style.
311 | #class-attribute-rgx=
312 |
313 | # Naming style matching correct class names.
314 | class-naming-style=PascalCase
315 |
316 | # Regular expression matching correct class names. Overrides class-naming-
317 | # style.
318 | #class-rgx=
319 |
320 | # Naming style matching correct constant names.
321 | const-naming-style=UPPER_CASE
322 |
323 | # Regular expression matching correct constant names. Overrides const-naming-
324 | # style.
325 | #const-rgx=
326 |
327 | # Minimum line length for functions/classes that require docstrings, shorter
328 | # ones are exempt.
329 | docstring-min-length=-1
330 |
331 | # Naming style matching correct function names.
332 | function-naming-style=snake_case
333 |
334 | # Regular expression matching correct function names. Overrides function-
335 | # naming-style.
336 | #function-rgx=
337 |
338 | # Good variable names which should always be accepted, separated by a comma.
339 | good-names=i,
340 | j,
341 | k,
342 | ex,
343 | Run,
344 | _
345 |
346 | # Include a hint for the correct naming format with invalid-name.
347 | include-naming-hint=no
348 |
349 | # Naming style matching correct inline iteration names.
350 | inlinevar-naming-style=any
351 |
352 | # Regular expression matching correct inline iteration names. Overrides
353 | # inlinevar-naming-style.
354 | #inlinevar-rgx=
355 |
356 | # Naming style matching correct method names.
357 | method-naming-style=snake_case
358 |
359 | # Regular expression matching correct method names. Overrides method-naming-
360 | # style.
361 | #method-rgx=
362 |
363 | # Naming style matching correct module names.
364 | module-naming-style=snake_case
365 |
366 | # Regular expression matching correct module names. Overrides module-naming-
367 | # style.
368 | #module-rgx=
369 |
370 | # Colon-delimited sets of names that determine each other's naming style when
371 | # the name regexes allow several styles.
372 | name-group=
373 |
374 | # Regular expression which should only match function or class names that do
375 | # not require a docstring.
376 | no-docstring-rgx=^_
377 |
378 | # List of decorators that produce properties, such as abc.abstractproperty. Add
379 | # to this list to register other decorators that produce valid properties.
380 | # These decorators are taken in consideration only for invalid-name.
381 | property-classes=abc.abstractproperty
382 |
383 | # Naming style matching correct variable names.
384 | variable-naming-style=snake_case
385 |
386 | # Regular expression matching correct variable names. Overrides variable-
387 | # naming-style.
388 | #variable-rgx=
389 |
390 |
391 | [IMPORTS]
392 |
393 | # Allow wildcard imports from modules that define __all__.
394 | allow-wildcard-with-all=no
395 |
396 | # Analyse import fallback blocks. This can be used to support both Python 2 and
397 | # 3 compatible code, which means that the block might have code that exists
398 | # only in one or another interpreter, leading to false positives when analysed.
399 | analyse-fallback-blocks=no
400 |
401 | # Deprecated modules which should not be used, separated by a comma.
402 | deprecated-modules=optparse,tkinter.tix
403 |
404 | # Create a graph of external dependencies in the given file (report RP0402 must
405 | # not be disabled).
406 | ext-import-graph=
407 |
408 | # Create a graph of every (i.e. internal and external) dependencies in the
409 | # given file (report RP0402 must not be disabled).
410 | import-graph=
411 |
412 | # Create a graph of internal dependencies in the given file (report RP0402 must
413 | # not be disabled).
414 | int-import-graph=
415 |
416 | # Force import order to recognize a module as part of the standard
417 | # compatibility libraries.
418 | known-standard-library=
419 |
420 | # Force import order to recognize a module as part of a third party library.
421 | known-third-party=enchant
422 |
423 |
424 | [CLASSES]
425 |
426 | # List of method names used to declare (i.e. assign) instance attributes.
427 | defining-attr-methods=__init__,
428 | __new__,
429 | setUp
430 |
431 | # List of member names, which should be excluded from the protected access
432 | # warning.
433 | exclude-protected=_asdict,
434 | _fields,
435 | _replace,
436 | _source,
437 | _make
438 |
439 | # List of valid names for the first argument in a class method.
440 | valid-classmethod-first-arg=cls
441 |
442 | # List of valid names for the first argument in a metaclass class method.
443 | valid-metaclass-classmethod-first-arg=cls
444 |
445 |
446 | [DESIGN]
447 |
448 | # Maximum number of arguments for function / method.
449 | max-args=5
450 |
451 | # Maximum number of attributes for a class (see R0902).
452 | max-attributes=7
453 |
454 | # Maximum number of boolean expressions in an if statement.
455 | max-bool-expr=5
456 |
457 | # Maximum number of branch for function / method body.
458 | max-branches=12
459 |
460 | # Maximum number of locals for function / method body.
461 | max-locals=15
462 |
463 | # Maximum number of parents for a class (see R0901).
464 | max-parents=7
465 |
466 | # Maximum number of public methods for a class (see R0904).
467 | max-public-methods=20
468 |
469 | # Maximum number of return / yield for function / method body.
470 | max-returns=6
471 |
472 | # Maximum number of statements in function / method body.
473 | max-statements=50
474 |
475 | # Minimum number of public methods for a class (see R0903).
476 | min-public-methods=2
477 |
478 |
479 | [EXCEPTIONS]
480 |
481 | # Exceptions that will emit a warning when being caught. Defaults to
482 | # "Exception".
483 | overgeneral-exceptions=Exception
484 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["flit"]
3 | build-backend = "flit.buildapi"
4 |
5 | [tool.flit.metadata]
6 | module = "celluloid"
7 | author = "Jacques Kvam"
8 | author-email = "jwkvam+pypi@gmail.com"
9 | home-page = "https://github.com/jwkvam/celluloid"
10 | description-file = "README.md"
11 | classifiers = [
12 | "License :: OSI Approved :: MIT License",
13 | "Programming Language :: Python :: 3",
14 | "Programming Language :: Python :: 3.6",
15 | "Programming Language :: Python :: 3.7"
16 | ]
17 | requires-python = ">=3.6"
18 | requires = [
19 | "matplotlib"
20 | ]
21 | keywords = "matplotlib animation"
22 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | addopts = --doctest-modules -ra --tb short
3 | codestyle_max_line_length = 100
4 | codestyle_ignore = E402
5 | norecursedirs = examples
6 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [pycodestyle]
2 | max-line-length = 100
3 | ignore = E402
4 | [pydocstyle]
5 | convention = numpy
6 | [tool:pytest]
7 | docstyle_convention = numpy
8 |
--------------------------------------------------------------------------------
/test-requirements.txt:
--------------------------------------------------------------------------------
1 | codecov
2 | matplotlib
3 | mypy
4 | numpy
5 | pandas
6 | pycodestyle
7 | pydocstyle
8 | pylint
9 | pytest
10 | pytest-codestyle
11 | pytest-cov
12 | pytest-docstyle
13 | pytest-mypy
14 | pytest-pylint
15 |
--------------------------------------------------------------------------------
/test_celluloid.py:
--------------------------------------------------------------------------------
1 | """Test animations."""
2 | # pylint: disable=wrong-import-position
3 | import numpy as np
4 | import matplotlib
5 | matplotlib.use('Agg')
6 | from matplotlib import pyplot as plt
7 |
8 | from celluloid import Camera
9 |
10 |
11 | def test_single():
12 | """Test plt.figure()"""
13 | fig = plt.figure()
14 | camera = Camera(fig)
15 |
16 | for _ in range(10):
17 | plt.plot(range(5))
18 | plt.plot(-np.arange(5))
19 | artists = camera.snap()
20 | assert len(artists) == 2
21 |
22 | # pylint: disable=protected-access
23 | assert sum(len(x) for x in camera._photos) == 2 * 10
24 |
25 | anim = camera.animate()
26 | assert len(list(anim.frame_seq)) == 10
27 |
28 |
29 | def test_two_axes():
30 | """Test subplots."""
31 | fig, axes = plt.subplots(2)
32 | camera = Camera(fig)
33 | axes[0].plot(np.zeros(100))
34 | axes[1].plot(np.zeros(100))
35 | artists = camera.snap()
36 | assert len(artists) == 2
37 |
38 | axes[0].plot(np.ones(100))
39 | axes[1].plot(np.ones(100))
40 | artists = camera.snap()
41 |
42 | # pylint: disable=protected-access
43 | assert sum(len(x) for x in camera._photos) == 4
44 |
45 | anim = camera.animate()
46 | assert len(list(anim.frame_seq)) == 2
47 |
48 |
49 | def test_legends():
50 | """Test subplots."""
51 | camera = Camera(plt.figure())
52 |
53 | plt.legend(plt.plot(range(5)), ['hello'])
54 | artists = camera.snap()
55 | assert len(artists) == 2
56 |
57 | plt.legend(plt.plot(range(5)), ['world'])
58 | artists = camera.snap()
59 | assert len(artists) == 2
60 |
61 | # pylint: disable=protected-access
62 | assert camera._photos[0][1].texts[0]._text == 'hello'
63 | assert camera._photos[1][1].texts[0]._text == 'world'
64 |
65 | # pylint: disable=protected-access
66 | assert sum(len(x) for x in camera._photos) == 4
67 |
68 | anim = camera.animate()
69 | assert len(list(anim.frame_seq)) == 2
70 |
71 |
72 | def test_images():
73 | """Test subplots."""
74 | camera = Camera(plt.figure())
75 |
76 | plt.imshow(np.ones((5, 5)))
77 | artists = camera.snap()
78 | assert len(artists) == 1
79 |
80 | plt.imshow(np.zeros((5, 5)))
81 | artists = camera.snap()
82 | assert len(artists) == 1
83 |
84 | # pylint: disable=protected-access
85 | assert sum(len(x) for x in camera._photos) == 2
86 |
87 | anim = camera.animate()
88 | assert len(list(anim.frame_seq)) == 2
89 |
--------------------------------------------------------------------------------