Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
__init__.py
1"""
2Utility functions to download files
3"""
4
5import os
6import sys
7from urllib.request import urlretrieve
8
9import shamrock.sys
10
11
12def fmt(n):
13 for u in ("B", "KB", "MB", "GB", "TB"):
14 if n < 1024:
15 return f"{n:.1f}{u}"
16 n /= 1024
17
18
19def reporthook(block_num, block_size, total_size):
20 if total_size <= 0 or block_size <= 0:
21 return
22 freq_report = int(int(total_size / block_size) / 10)
23 if freq_report <= 0:
24 return
25 if block_num % freq_report == 0:
26 BAR_WIDTH = 60
27 downloaded = block_num * block_size
28 percent = int((downloaded / total_size) * 100)
29 filled = int(BAR_WIDTH * percent / 100)
30 bar = "#" * filled + "-" * (BAR_WIDTH - filled)
31 sys.stdout.write(f"[{bar}] {percent:3d}% | {fmt(downloaded)}/{fmt(total_size)}\n")
32 sys.stdout.flush()
33
34
35def download_file(url, filename):
36 """
37 Download a file from an URL
38 """
39
40 if shamrock.sys.world_rank() == 0:
41 print(f" - Downloading {filename} from {url}")
42 # create the directory if it does not exist
43 os.makedirs(os.path.dirname(filename), exist_ok=True)
44 urlretrieve(url, filename, reporthook=reporthook)
45
46 shamrock.sys.mpi_barrier()
47
48 # check that the file exists
49 if not os.path.exists(filename):
50 raise FileNotFoundError(
51 f"File {filename} should have been downloaded but is not present on rank {shamrock.sys.world_rank()}"
52 )