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,
33 render_gif=True,
34 dpi=200,
35 interval=50,
36 repeat_delay=10,
37 ):
38 """
39 Create a matplotlib animation from a sequence of image files.
40
41 Available only if matplotlib and PIL are installed.
42
43 Parameters
44 ----------
45 glob_str : str
46 Glob pattern matching image files.
47 render_gif : bool, optional
48 Whether to render the animation.
49 dpi : int, optional
50 Dots per inch for the figure.
51 interval : int, optional
52 Delay between frames in milliseconds.
53 repeat_delay : int, optional
54 Delay before repeating the animation.
55
56 Raises
57 ------
58 FileNotFoundError : if no images are found for the glob pattern
59
60 Returns
61 -------
62 matplotlib.animation.FuncAnimation or None
63 Animation object on rank 0, otherwise None.
64 """
65
66 if not render_gif:
67 return None
68
69 if shamrock.sys.world_rank() != 0:
70 return None
71
72 files = sorted(glob.glob(glob_str))
73
74 image_array = []
75 for my_file in files:
76 with Image.open(my_file) as image:
77 image_array.append(image.copy())
78
79 if not image_array:
80 raise FileNotFoundError(f"No images found for glob pattern: {glob_str}")
81
82 pixel_x, pixel_y = image_array[0].size
83
84 fig = plt.figure(dpi=dpi)
85 plt.gca().set_position((0, 0, 1, 1))
86 plt.gcf().set_size_inches(pixel_x / dpi, pixel_y / dpi)
87 plt.axis("off")
88
89 im = plt.imshow(image_array[0], animated=True, aspect="auto")
90
91 def update(i):
92 im.set_array(image_array[i])
93 return (im,)
94
95 ani = animation.FuncAnimation(
96 fig,
97 update,
98 frames=len(image_array),
99 interval=interval,
100 blit=True,
101 repeat_delay=repeat_delay,
102 )
103
104 return ani
show_image_sequence(glob_str, render_gif=True, dpi=200, interval=50, repeat_delay=10)
Definition __init__.py:37