-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathutils.py
More file actions
150 lines (121 loc) · 4.29 KB
/
Copy pathutils.py
File metadata and controls
150 lines (121 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import subprocess
import os
import shutil
from pathlib import Path
import math
import typing as T
import hashlib
import urllib.request
import urllib.error
import socket
import zipfile
import tarfile
try:
import psutil
except ImportError:
psutil = None
# pip install psutil will improve CPU utilization.
from .config import read_config
from .base import get_simsize
git = shutil.which("git")
Pathlike = T.Union[str, Path]
__all__ = ["gitrev", "get_cpu_count", "get_mpi_count"]
def gitrev() -> str:
if not git:
return ""
return subprocess.check_output([git, "rev-parse", "--short", "HEAD"], universal_newlines=True).strip()
def get_cpu_count(force: int = None) -> int:
if force:
max_cpu = force
extradiv = 1
else:
max_cpu = None
# without psutil, hyperthreaded CPU may overestimate physical count by factor of 2 (or more)
if psutil is not None:
max_cpu = psutil.cpu_count(logical=False)
extradiv = 1
if max_cpu is None:
max_cpu = psutil.cpu_count()
extradiv = 2
if max_cpu is None:
max_cpu = os.cpu_count()
extradiv = 2
return max_cpu // extradiv
def get_mpi_count(path: Pathlike, force: int = None) -> int:
path = Path(path).expanduser()
max_cpu = get_cpu_count(force)
# %% config.nml file or directory or simsize.h5?
if path.is_dir():
size = get_simsize(path)
elif path.is_file():
if path.suffix in (".h5", ".nc", ".dat"):
size = get_simsize(path)
elif path.suffix in (".ini", ".nml"):
params = read_config(path)
# OK to use indat_size because we're going to run a sim on this machine
size = get_simsize(params["indat_size"])
else:
raise FileNotFoundError(f"{path} is not a file or directory")
mpi_count = 1
if size[2] == 1:
# 2D sim
for i in range(max_cpu, 2, -1):
mpi_count = max(math.gcd(size[1], i), mpi_count)
if i < mpi_count:
break
else:
# 3D sim
for i in range(max_cpu, 2, -1):
mpi_count = max(math.gcd(size[2], i), mpi_count)
if i < mpi_count:
break
return mpi_count
def url_retrieve(url: str, outfile: Pathlike, filehash: T.Sequence[str] = None, overwrite: bool = False):
"""
Parameters
----------
url: str
URL to download from
outfile: pathlib.Path
output filepath (including name)
filehash: tuple of str, str
hash type (md5, sha1, etc.) and hash
overwrite: bool
overwrite if file exists
"""
outfile = Path(outfile).expanduser().resolve()
if outfile.is_dir():
raise ValueError("Please specify full filepath, including filename")
# need .resolve() in case intermediate relative dir doesn't exist
if overwrite or not outfile.is_file():
outfile.parent.mkdir(parents=True, exist_ok=True)
try:
urllib.request.urlretrieve(url, str(outfile))
except (socket.gaierror, urllib.error.URLError) as err:
raise ConnectionError(f"could not download {url} due to {err}")
if filehash:
if not file_checksum(outfile, filehash[0], filehash[1]):
raise ValueError(f"Hash mismatch: {outfile}")
def file_checksum(fn: Path, mode: str, filehash: str) -> bool:
h = hashlib.new(mode)
h.update(fn.read_bytes())
return h.hexdigest() == filehash
def extract_zip(fn: Pathlike, outpath: Pathlike, overwrite: bool = False):
outpath = Path(outpath).expanduser().resolve()
# need .resolve() in case intermediate relative dir doesn't exist
if outpath.is_dir() and not overwrite:
return
fn = Path(fn).expanduser().resolve()
with zipfile.ZipFile(fn) as z:
z.extractall(str(outpath.parent))
def extract_tar(fn: Pathlike, outpath: Pathlike, overwrite: bool = False):
outpath = Path(outpath).expanduser().resolve()
# need .resolve() in case intermediate relative dir doesn't exist
if outpath.is_dir() and not overwrite:
return
fn = Path(fn).expanduser().resolve()
if not fn.is_file():
# tarfile gives confusing error on missing file
raise FileNotFoundError(fn)
with tarfile.open(fn) as z:
z.extractall(str(outpath.parent))