Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
__init__.py
1"""
2Shamrock plot utility functions.
3"""
4
5import glob
6
7import shamrock.sys
8
9__all__ = []
10
11try:
12 import matplotlib.animation as animation
13 import matplotlib.pyplot as plt
14
15 _HAS_MATPLOTLIB = True
16except ImportError:
17 _HAS_MATPLOTLIB = False
18 # print("Warning: matplotlib is not installed, some Shamrock functions will not be available")
19
20try:
21 from PIL import Image
22
23 _HAS_PIL = True
24except ImportError:
25 _HAS_PIL = False
26 # print("Warning: PIL is not installed, some Shamrock functions will not be available")
27
28if _HAS_MATPLOTLIB and _HAS_PIL:
29 __all__.append("show_image_sequence")
30
32 glob_str, render_gif=True, dpi=200, interval=50, repeat_delay=10, fig=None
33 ):
34 """
35 Create a matplotlib animation from a sequence of image files.
36
37 Available only if matplotlib and PIL are installed.
38
39 Parameters
40 ----------
41 glob_str : str
42 Glob pattern matching image files.
43 render_gif : bool, optional
44 Whether to render the animation.
45 dpi : int, optional
46 Dots per inch for the figure.
47 interval : int, optional
48 Delay between frames in milliseconds.
49 repeat_delay : int, optional
50 Delay before repeating the animation.
51
52 Raises
53 ------
54 FileNotFoundError : if no images are found for the glob pattern
55
56 Returns
57 -------
58 matplotlib.animation.FuncAnimation or None
59 Animation object on rank 0, otherwise None.
60 """
61
62 if not render_gif:
63 return None
64
65 if shamrock.sys.world_rank() != 0:
66 return None
67
68 files = sorted(glob.glob(glob_str))
69
70 image_array = []
71 for my_file in files:
72 with Image.open(my_file) as image:
73 image_array.append(image.copy())
74
75 if not image_array:
76 raise FileNotFoundError(f"No images found for glob pattern: {glob_str}")
77
78 pixel_x, pixel_y = image_array[0].size
79
80 if fig is None:
81 fig = plt.figure(dpi=dpi)
82 plt.gca().set_position((0, 0, 1, 1))
83 plt.gcf().set_size_inches(pixel_x / dpi, pixel_y / dpi)
84 plt.axis("off")
85
86 im = plt.imshow(image_array[0], animated=True, aspect="auto")
87
88 def update(i):
89 im.set_array(image_array[i])
90 return (im,)
91
92 ani = animation.FuncAnimation(
93 fig,
94 update,
95 frames=len(image_array),
96 interval=interval,
97 blit=True,
98 repeat_delay=repeat_delay,
99 )
100
101 return ani
show_image_sequence(glob_str, render_gif=True, dpi=200, interval=50, repeat_delay=10, fig=None)
Definition __init__.py:33