epymorph 1.0.0b0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +602 -0
- epymorph/adrio/adrio.py +215 -0
- epymorph/adrio/cdc.py +781 -0
- epymorph/adrio/commuting_flows.py +237 -0
- epymorph/adrio/csv.py +387 -0
- epymorph/adrio/humidity.py +84 -0
- epymorph/adrio/lodes.py +624 -0
- epymorph/adrio/numpy.py +119 -0
- epymorph/adrio/prism.py +543 -0
- epymorph/adrio/respiratory_cdc.py +489 -0
- epymorph/adrio/us_tiger.py +217 -0
- epymorph/attribute.py +301 -0
- epymorph/cache.py +494 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +77 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1335 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +475 -0
- epymorph/data_type.py +129 -0
- epymorph/data_usage.py +171 -0
- epymorph/database.py +1010 -0
- epymorph/error.py +183 -0
- epymorph/event.py +188 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +61 -0
- epymorph/geography/scope.py +214 -0
- epymorph/geography/us_census.py +622 -0
- epymorph/geography/us_geography.py +278 -0
- epymorph/geography/us_tiger.py +755 -0
- epymorph/initializer.py +596 -0
- epymorph/kit.py +90 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +108 -0
- epymorph/log/messaging.py +129 -0
- epymorph/log/movement.py +151 -0
- epymorph/movement_model.py +274 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +111 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +249 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +248 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +700 -0
- epymorph/simulation.py +706 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +145 -0
- epymorph/simulator/basic/ipm_exec.py +406 -0
- epymorph/simulator/basic/mm_exec.py +197 -0
- epymorph/simulator/basic/output.py +181 -0
- epymorph/simulator/world.py +83 -0
- epymorph/simulator/world_list.py +196 -0
- epymorph/strata.py +12 -0
- epymorph/sympy_shim.py +55 -0
- epymorph/time.py +649 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +218 -0
- epymorph/tools/ipm_diagram.py +165 -0
- epymorph/tools/out_map.py +426 -0
- epymorph/tools/out_plot.py +412 -0
- epymorph/tools/out_table.py +575 -0
- epymorph/util.py +825 -0
- epymorph-1.0.0b0.dist-info/METADATA +57 -0
- epymorph-1.0.0b0.dist-info/RECORD +102 -0
- epymorph-1.0.0b0.dist-info/WHEEL +5 -0
- epymorph-1.0.0b0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0b0.dist-info/top_level.txt +1 -0
epymorph/cache.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""epymorph's file caching utilities."""
|
|
2
|
+
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
from io import BytesIO
|
|
5
|
+
from math import log
|
|
6
|
+
from os import PathLike, getenv
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from shutil import rmtree
|
|
9
|
+
from sys import modules
|
|
10
|
+
from tarfile import TarInfo, is_tarfile
|
|
11
|
+
from tarfile import open as open_tarfile
|
|
12
|
+
from typing import Callable, NamedTuple, Sequence
|
|
13
|
+
from urllib.request import urlopen
|
|
14
|
+
from warnings import warn
|
|
15
|
+
|
|
16
|
+
from platformdirs import user_cache_path
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _cache_path() -> Path:
|
|
20
|
+
if (path_var := getenv("EPYMORPH_CACHE_PATH")) is not None:
|
|
21
|
+
# Load path from env var
|
|
22
|
+
path = Path(path_var)
|
|
23
|
+
else:
|
|
24
|
+
# fall back to platform-specific default path
|
|
25
|
+
path = user_cache_path(appname="epymorph")
|
|
26
|
+
# ensure cache directory exists
|
|
27
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
return path
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
CACHE_PATH = _cache_path()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def module_cache_path(name: str) -> Path:
|
|
35
|
+
"""
|
|
36
|
+
When epymorph modules need to store files in the cache,
|
|
37
|
+
they should use a subdirectory tree within the application's
|
|
38
|
+
cache path. This tree should correspond to the module's path
|
|
39
|
+
within epymorph. e.g.: module epymorph.adrio.acs5 will store
|
|
40
|
+
files at $CACHE_PATH/adrio/acs5.
|
|
41
|
+
(The returned value is a relative path since the cache functions
|
|
42
|
+
require that.)
|
|
43
|
+
|
|
44
|
+
Usage example:
|
|
45
|
+
|
|
46
|
+
`_TIGER_CACHE_PATH = module_cache_path(__name__)`
|
|
47
|
+
"""
|
|
48
|
+
file_name = modules[name].__file__
|
|
49
|
+
if file_name is None:
|
|
50
|
+
return CACHE_PATH
|
|
51
|
+
file_path = Path(file_name).with_suffix("")
|
|
52
|
+
root = file_path.parent
|
|
53
|
+
while root.name != "epymorph":
|
|
54
|
+
root = root.parent
|
|
55
|
+
return file_path.relative_to(root)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class FileError(Exception):
|
|
59
|
+
"""Error during a file operation."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FileMissingError(FileError):
|
|
63
|
+
"""Error loading a file, as it does not exist."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class FileWriteError(FileError):
|
|
67
|
+
"""Error writing a file."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class FileReadError(FileError):
|
|
71
|
+
"""Error loading a file."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class FileVersionError(FileError):
|
|
75
|
+
"""Error loading a file due to unmet version requirements."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class CacheMissError(FileError):
|
|
79
|
+
"""Raised on a cache-miss (for any reason) during a load-from-cache operation."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class CacheWarning(Warning):
|
|
83
|
+
"""
|
|
84
|
+
Warning issued when we are unable to interact with the file cache but in a situation
|
|
85
|
+
where program execution can continue, even if less optimally. For example: if we
|
|
86
|
+
successfully load data from an external source but are unable to cache it for later,
|
|
87
|
+
this is a warning because we assume the data is valid and that it could always
|
|
88
|
+
be loaded again from the same source at a later time. The warning is issued to give
|
|
89
|
+
the user the opportunity to fix it for next time.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def save_file(to_path: str | PathLike[str], file: BytesIO) -> None:
|
|
94
|
+
"""
|
|
95
|
+
Save a single file. `to_path` can be absolute or relative; relative paths will be
|
|
96
|
+
resolved against the current working directory. Folders in the path which
|
|
97
|
+
do not exist will be created automatically.
|
|
98
|
+
"""
|
|
99
|
+
try:
|
|
100
|
+
file_path = Path(to_path).resolve()
|
|
101
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
with file_path.open(mode="wb") as f:
|
|
103
|
+
f.write(file.getbuffer())
|
|
104
|
+
except Exception as e:
|
|
105
|
+
msg = f"Unable to write file at path: {to_path}"
|
|
106
|
+
raise FileWriteError(msg) from e
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def load_file(from_path: str | PathLike[str]) -> BytesIO:
|
|
110
|
+
"""
|
|
111
|
+
Load a single file. An Exception is raised if the file cannot be loaded
|
|
112
|
+
for any reason. On success, returns the bytes of the file.
|
|
113
|
+
"""
|
|
114
|
+
try:
|
|
115
|
+
file_path = Path(from_path).resolve()
|
|
116
|
+
if not file_path.is_file():
|
|
117
|
+
raise FileMissingError(f"No file at: {file_path}")
|
|
118
|
+
|
|
119
|
+
# Read the file into memory
|
|
120
|
+
file_buffer = BytesIO()
|
|
121
|
+
with file_path.open(mode="rb") as f:
|
|
122
|
+
file_buffer.write(f.read())
|
|
123
|
+
file_buffer.seek(0)
|
|
124
|
+
return file_buffer
|
|
125
|
+
except FileError:
|
|
126
|
+
raise
|
|
127
|
+
except Exception as e:
|
|
128
|
+
raise FileReadError(f"Unable to load file at: {from_path}") from e
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def save_bundle(
|
|
132
|
+
to_path: str | PathLike[str], version: int, files: dict[str, BytesIO]
|
|
133
|
+
) -> None:
|
|
134
|
+
"""
|
|
135
|
+
Save a bundle of files in our tar format with an associated version number.
|
|
136
|
+
`to_path` can be absolute or relative; relative paths will be resolved
|
|
137
|
+
against the current working directory. Folders in the path which do not exist
|
|
138
|
+
will be created automatically.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
if version <= 0:
|
|
142
|
+
raise ValueError("version should be greater than zero.")
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
# Compute checksums
|
|
146
|
+
sha_entries = []
|
|
147
|
+
for name, contents in files.items():
|
|
148
|
+
contents.seek(0)
|
|
149
|
+
sha = sha256()
|
|
150
|
+
sha.update(contents.read())
|
|
151
|
+
sha_entries.append(f"{sha.hexdigest()} {name}")
|
|
152
|
+
|
|
153
|
+
# Create checksums.sha256 file
|
|
154
|
+
sha_file = BytesIO()
|
|
155
|
+
sha_text = "\n".join(sha_entries)
|
|
156
|
+
sha_file.write(bytes(sha_text, encoding="utf-8"))
|
|
157
|
+
|
|
158
|
+
# Create cache version file
|
|
159
|
+
ver_file = BytesIO()
|
|
160
|
+
ver_file.write(bytes(str(version), encoding="utf-8"))
|
|
161
|
+
|
|
162
|
+
tarred_files = {
|
|
163
|
+
**files,
|
|
164
|
+
"checksums.sha256": sha_file,
|
|
165
|
+
"version": ver_file,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
# Write the tar to disk
|
|
169
|
+
tar_path = Path(to_path).resolve()
|
|
170
|
+
tar_path.parent.mkdir(parents=True, exist_ok=True)
|
|
171
|
+
mode = "w:gz" if tar_path.suffix == ".tgz" else "w"
|
|
172
|
+
with open_tarfile(name=tar_path, mode=mode) as tar:
|
|
173
|
+
for name, contents in tarred_files.items():
|
|
174
|
+
info = TarInfo(name)
|
|
175
|
+
info.size = contents.tell()
|
|
176
|
+
contents.seek(0)
|
|
177
|
+
tar.addfile(info, contents)
|
|
178
|
+
|
|
179
|
+
except Exception as e:
|
|
180
|
+
msg = f"Unable to write archive at path: {to_path}"
|
|
181
|
+
raise FileWriteError(msg) from e
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def load_bundle(
|
|
185
|
+
from_path: str | PathLike[str], version_at_least: int = -1
|
|
186
|
+
) -> dict[str, BytesIO]:
|
|
187
|
+
"""
|
|
188
|
+
Load a bundle of files in our tar format, optionally enforcing a minimum version.
|
|
189
|
+
An Exception is raised if the file cannot be loaded for any reason, or
|
|
190
|
+
if its version is incorrect. On success, returns a dictionary
|
|
191
|
+
of the contained files, mapping the file name to the bytes of the file.
|
|
192
|
+
"""
|
|
193
|
+
try:
|
|
194
|
+
tar_path = Path(from_path).resolve()
|
|
195
|
+
if not tar_path.is_file():
|
|
196
|
+
raise FileMissingError(f"No file at: {tar_path}")
|
|
197
|
+
|
|
198
|
+
# Read the tar file into memory
|
|
199
|
+
tar_buffer = BytesIO()
|
|
200
|
+
with tar_path.open(mode="rb") as f:
|
|
201
|
+
tar_buffer.write(f.read())
|
|
202
|
+
tar_buffer.seek(0)
|
|
203
|
+
|
|
204
|
+
if not is_tarfile(tar_buffer):
|
|
205
|
+
raise FileReadError(f"Not a tar file at: {tar_path}")
|
|
206
|
+
|
|
207
|
+
mode = "r:gz" if tar_path.suffix == ".tgz" else "r"
|
|
208
|
+
tarred_files: dict[str, BytesIO] = {}
|
|
209
|
+
with open_tarfile(fileobj=tar_buffer, mode=mode) as tar:
|
|
210
|
+
for info in tar.getmembers():
|
|
211
|
+
name = info.name
|
|
212
|
+
contents = tar.extractfile(info)
|
|
213
|
+
if contents is not None:
|
|
214
|
+
tarred_files[name] = BytesIO(contents.read())
|
|
215
|
+
|
|
216
|
+
# Check version
|
|
217
|
+
if "version" in tarred_files:
|
|
218
|
+
ver_file = tarred_files["version"]
|
|
219
|
+
version = int(str(ver_file.readline(), encoding="utf-8"))
|
|
220
|
+
else:
|
|
221
|
+
version = -1
|
|
222
|
+
if version < version_at_least:
|
|
223
|
+
raise FileVersionError("Archive is an unacceptable version.")
|
|
224
|
+
|
|
225
|
+
# Verify the checksums
|
|
226
|
+
if "checksums.sha256" not in tarred_files:
|
|
227
|
+
raise FileReadError("Archive appears to be invalid.")
|
|
228
|
+
sha_file = tarred_files["checksums.sha256"]
|
|
229
|
+
for line_bytes in sha_file.readlines():
|
|
230
|
+
line = str(line_bytes, encoding="utf-8")
|
|
231
|
+
[checksum, filename] = line.strip().split(" ")
|
|
232
|
+
|
|
233
|
+
if filename not in tarred_files:
|
|
234
|
+
raise FileReadError("Archive appears to be invalid.")
|
|
235
|
+
|
|
236
|
+
contents = tarred_files[filename]
|
|
237
|
+
contents.seek(0)
|
|
238
|
+
sha = sha256()
|
|
239
|
+
sha.update(contents.read())
|
|
240
|
+
contents.seek(0)
|
|
241
|
+
if checksum != sha.hexdigest():
|
|
242
|
+
msg = (
|
|
243
|
+
f"Archive checksum did not match (for file {filename}). "
|
|
244
|
+
"It is possible the file is corrupt."
|
|
245
|
+
)
|
|
246
|
+
raise FileReadError(msg)
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
name: contents
|
|
250
|
+
for name, contents in tarred_files.items()
|
|
251
|
+
if name not in ("checksums.sha256", "version")
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
except FileError:
|
|
255
|
+
raise
|
|
256
|
+
except Exception as e:
|
|
257
|
+
raise FileReadError(f"Unable to load archive at: {from_path}") from e
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _resolve_cache_path(path: str | PathLike[str]) -> Path:
|
|
261
|
+
cache_path = Path(path)
|
|
262
|
+
if cache_path.is_absolute():
|
|
263
|
+
raise ValueError(
|
|
264
|
+
"When saving to or loading from the cache, please supply a relative path."
|
|
265
|
+
)
|
|
266
|
+
resolved = CACHE_PATH.joinpath(cache_path).resolve()
|
|
267
|
+
if not resolved.is_relative_to(CACHE_PATH):
|
|
268
|
+
# Ensure the resolved path is still inside CACHE_PATH.
|
|
269
|
+
raise ValueError(
|
|
270
|
+
"When saving to or loading from the cache, please supply a relative path."
|
|
271
|
+
)
|
|
272
|
+
return resolved
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def check_file_in_cache(cache_path: Path) -> bool:
|
|
276
|
+
"""
|
|
277
|
+
Returns True if a file is currently in the cache.
|
|
278
|
+
"""
|
|
279
|
+
return _resolve_cache_path(cache_path).exists()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def save_file_to_cache(to_path: str | PathLike[str], file: BytesIO) -> None:
|
|
283
|
+
"""
|
|
284
|
+
Save a single file to the cache (overwriting the existing file, if any).
|
|
285
|
+
This is a low-level building block.
|
|
286
|
+
"""
|
|
287
|
+
try:
|
|
288
|
+
save_file(_resolve_cache_path(to_path), file)
|
|
289
|
+
except ValueError as e:
|
|
290
|
+
raise FileWriteError() from e
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def load_file_from_cache(from_path: str | PathLike[str]) -> BytesIO:
|
|
294
|
+
"""
|
|
295
|
+
Load a single file from the cache.
|
|
296
|
+
This is a low-level building block.
|
|
297
|
+
"""
|
|
298
|
+
try:
|
|
299
|
+
return load_file(_resolve_cache_path(from_path))
|
|
300
|
+
except FileError as e:
|
|
301
|
+
raise CacheMissError() from e
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def load_or_fetch(cache_path: Path, fetch: Callable[[], BytesIO]) -> BytesIO:
|
|
305
|
+
"""
|
|
306
|
+
Attempts to load a file from the cache. If it doesn't exist, uses the provided
|
|
307
|
+
fetch method to load the file, then attempts to save the file to the cache for
|
|
308
|
+
next time. (This is a higher-level but still generic building block.)
|
|
309
|
+
Any exceptions raised by `fetch` will not be caught in this method.
|
|
310
|
+
"""
|
|
311
|
+
try:
|
|
312
|
+
# Try to load from cache.
|
|
313
|
+
return load_file_from_cache(cache_path)
|
|
314
|
+
except CacheMissError:
|
|
315
|
+
# On cache miss, fetch file contents.
|
|
316
|
+
file = fetch()
|
|
317
|
+
# And attempt to save the file to the cache for next time.
|
|
318
|
+
try:
|
|
319
|
+
save_file_to_cache(cache_path, file)
|
|
320
|
+
except FileWriteError as e:
|
|
321
|
+
# Failure to save to the cache is not worth stopping the program:
|
|
322
|
+
# raise a warning.
|
|
323
|
+
warn(
|
|
324
|
+
f"Unable to save file to the cache ({cache_path}). Cause:\n{e}",
|
|
325
|
+
CacheWarning,
|
|
326
|
+
)
|
|
327
|
+
return file
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def load_or_fetch_url(url: str, cache_path: Path) -> BytesIO:
|
|
331
|
+
"""
|
|
332
|
+
Attempts to load a file from the cache. If it doesn't exist, fetches
|
|
333
|
+
the file contents from the given URL, then attempts to save the file to the cache
|
|
334
|
+
for next time.
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
def fetch_url():
|
|
338
|
+
# ruff S310 requires us to check the URL protocol
|
|
339
|
+
# so that only http/s requests are allowed.
|
|
340
|
+
# Then we have to disable S310 on that line, because it can't see it's fixed.
|
|
341
|
+
# Do not remove this check.
|
|
342
|
+
if not url.startswith(("http:", "https:")):
|
|
343
|
+
raise ValueError("Data source URLs must use the http or https protocol.")
|
|
344
|
+
with urlopen(url) as f: # noqa: S310
|
|
345
|
+
return BytesIO(f.read())
|
|
346
|
+
|
|
347
|
+
return load_or_fetch(cache_path, fetch_url)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def save_bundle_to_cache(
|
|
351
|
+
to_path: str | PathLike[str], version: int, files: dict[str, BytesIO]
|
|
352
|
+
) -> None:
|
|
353
|
+
"""
|
|
354
|
+
Save a tar bundle of files to the cache (overwriting the existing file, if any).
|
|
355
|
+
The tar includes the sha256 checksums of every content file,
|
|
356
|
+
and a version file indicating which application version was
|
|
357
|
+
responsible for writing the file (thus allowing the application
|
|
358
|
+
to decide if a cached file is still valid when reading it).
|
|
359
|
+
"""
|
|
360
|
+
save_bundle(_resolve_cache_path(to_path), version, files)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def load_bundle_from_cache(
|
|
364
|
+
from_path: str | PathLike[str], version_at_least: int = -1
|
|
365
|
+
) -> dict[str, BytesIO]:
|
|
366
|
+
"""
|
|
367
|
+
Load a tar bundle of files from the cache. `from_path` must be a relative path.
|
|
368
|
+
`version_at_least` optionally specifies a version number that must be met or beat
|
|
369
|
+
by the cached file in order for the file to be considered valid. If the cached file
|
|
370
|
+
was written against a version less than this, it will be considered a cache miss
|
|
371
|
+
(raises CacheMiss).
|
|
372
|
+
"""
|
|
373
|
+
try:
|
|
374
|
+
return load_bundle(_resolve_cache_path(from_path), version_at_least)
|
|
375
|
+
except FileError as e:
|
|
376
|
+
raise CacheMissError() from e
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
####################
|
|
380
|
+
# Cache Management #
|
|
381
|
+
####################
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
# https://en.wikipedia.org/wiki/Metric_prefix
|
|
385
|
+
_suffixes = ("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def format_file_size(size: int) -> str:
|
|
389
|
+
"""Format a file size given in bytes in 1024-based-unit representation."""
|
|
390
|
+
if size < 0:
|
|
391
|
+
raise ValueError("size cannot be less than zero.")
|
|
392
|
+
if size < 1024:
|
|
393
|
+
return f"{size} {_suffixes[0]}"
|
|
394
|
+
magnitude = int(log(size, 1024))
|
|
395
|
+
if magnitude >= len(_suffixes):
|
|
396
|
+
raise ValueError("size is too large to format.")
|
|
397
|
+
fsize = size / pow(1024, magnitude)
|
|
398
|
+
return f"{fsize:.1f} {_suffixes[magnitude]}"
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
class Directory(NamedTuple):
|
|
402
|
+
"""A directory."""
|
|
403
|
+
|
|
404
|
+
name: str
|
|
405
|
+
"""The directory name."""
|
|
406
|
+
size: int
|
|
407
|
+
"""The combined size of all of this directory's children."""
|
|
408
|
+
children: "Sequence[FileTree]"
|
|
409
|
+
"""The directory's children, which may be files or nested directories."""
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
class File(NamedTuple):
|
|
413
|
+
"""A file."""
|
|
414
|
+
|
|
415
|
+
name: str
|
|
416
|
+
"""The file name."""
|
|
417
|
+
size: int
|
|
418
|
+
"""The file size."""
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
FileTree = Directory | File
|
|
422
|
+
"""Nodes in a file tree are either directories or files."""
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def cache_inventory() -> Directory:
|
|
426
|
+
"""Lists the contents of epymorph's cache as a FileTree."""
|
|
427
|
+
|
|
428
|
+
def recurse(directory: Path) -> Directory:
|
|
429
|
+
children = []
|
|
430
|
+
size = 0
|
|
431
|
+
for path in directory.iterdir():
|
|
432
|
+
if path.is_symlink():
|
|
433
|
+
# Ignore symlinks.
|
|
434
|
+
continue
|
|
435
|
+
if path.is_file():
|
|
436
|
+
file_size = path.stat().st_size
|
|
437
|
+
children.append(File(path.name, file_size))
|
|
438
|
+
size += file_size
|
|
439
|
+
elif path.is_dir():
|
|
440
|
+
d = recurse(path)
|
|
441
|
+
children.append(d)
|
|
442
|
+
size += d.size
|
|
443
|
+
return Directory(directory.name, size, children)
|
|
444
|
+
|
|
445
|
+
if not CACHE_PATH.exists():
|
|
446
|
+
return Directory(CACHE_PATH.name, 0, [])
|
|
447
|
+
return recurse(CACHE_PATH)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def cache_remove_confirmation(
|
|
451
|
+
path: str | PathLike[str],
|
|
452
|
+
) -> tuple[Path, Callable[[], None]]:
|
|
453
|
+
"""
|
|
454
|
+
Creates a function which removes a directory or file from the cache.
|
|
455
|
+
Also returns the resolved path to the thing that will be removed;
|
|
456
|
+
this allows the application to confirm the removal.
|
|
457
|
+
"""
|
|
458
|
+
try:
|
|
459
|
+
# This makes sure we don't delete things outside of the cache path.
|
|
460
|
+
to_remove = _resolve_cache_path(path)
|
|
461
|
+
except ValueError as e:
|
|
462
|
+
raise FileError(str(e)) from None
|
|
463
|
+
if not to_remove.exists():
|
|
464
|
+
raise FileError(f"Given path is not in the cache: {to_remove}")
|
|
465
|
+
|
|
466
|
+
def confirm_remove() -> None:
|
|
467
|
+
# Remove the target file/dir
|
|
468
|
+
if to_remove.is_file():
|
|
469
|
+
to_remove.unlink()
|
|
470
|
+
else:
|
|
471
|
+
rmtree(to_remove)
|
|
472
|
+
|
|
473
|
+
# Remove any newly-empty parent directories, up to the cache dir
|
|
474
|
+
parents = [
|
|
475
|
+
p
|
|
476
|
+
for p in to_remove.parents
|
|
477
|
+
if p.is_relative_to(CACHE_PATH) and p != CACHE_PATH
|
|
478
|
+
]
|
|
479
|
+
for p in parents:
|
|
480
|
+
if any(p.iterdir()):
|
|
481
|
+
break # parent not empty, we can stop
|
|
482
|
+
p.rmdir() # parent is empty
|
|
483
|
+
|
|
484
|
+
# We may need to replace the cache dir if we just deleted it.
|
|
485
|
+
CACHE_PATH.mkdir(parents=True, exist_ok=True)
|
|
486
|
+
|
|
487
|
+
return to_remove, confirm_remove
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def cache_remove(path: str | PathLike[str]) -> None:
|
|
491
|
+
"""Removes a directory or file from the cache."""
|
|
492
|
+
# This is the "no confirmation" version of `cache_remove_confirmation`
|
|
493
|
+
_, confirm_remove = cache_remove_confirmation(path)
|
|
494
|
+
confirm_remove()
|
epymorph/cli/__init__.py
ADDED
|
File without changes
|
epymorph/cli/cache.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Implements the `cache` CLI subcommands."""
|
|
2
|
+
# ruff: noqa: T201
|
|
3
|
+
|
|
4
|
+
from argparse import _SubParsersAction
|
|
5
|
+
|
|
6
|
+
from epymorph.cache import (
|
|
7
|
+
CACHE_PATH,
|
|
8
|
+
Directory,
|
|
9
|
+
FileError,
|
|
10
|
+
cache_inventory,
|
|
11
|
+
cache_remove_confirmation,
|
|
12
|
+
format_file_size,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def define_argparser(command_parser: _SubParsersAction):
|
|
17
|
+
"""Define `cache` subcommand."""
|
|
18
|
+
p = command_parser.add_parser("cache", help="manage epymorph's file cache")
|
|
19
|
+
cmd = p.add_subparsers(title="cache_commands", dest="cache_commands", required=True)
|
|
20
|
+
|
|
21
|
+
list_cmd = cmd.add_parser("list", help="list the contents of the cache")
|
|
22
|
+
list_cmd.set_defaults(handler=lambda args: handle_list())
|
|
23
|
+
|
|
24
|
+
remove_cmd = cmd.add_parser("remove", help="remove a file or folder from the cache")
|
|
25
|
+
remove_cmd.add_argument(
|
|
26
|
+
"path",
|
|
27
|
+
type=str,
|
|
28
|
+
help=(
|
|
29
|
+
"the relative path to a file or folder in the cache, "
|
|
30
|
+
"or omit to purge the cache entirely"
|
|
31
|
+
),
|
|
32
|
+
nargs="?",
|
|
33
|
+
default=".",
|
|
34
|
+
)
|
|
35
|
+
remove_cmd.set_defaults(handler=lambda args: handle_remove(path=args.path))
|
|
36
|
+
|
|
37
|
+
dir_cmd = cmd.add_parser("dir", help="output the absolute path of the cache folder")
|
|
38
|
+
dir_cmd.set_defaults(handler=lambda args: handle_dir())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def handle_list() -> int:
|
|
42
|
+
"""CLI command handler: cache list."""
|
|
43
|
+
|
|
44
|
+
def print_folders_in(directory: Directory, indent: str = " "):
|
|
45
|
+
child_dirs = (d for d in directory.children if isinstance(d, Directory))
|
|
46
|
+
for x in sorted(child_dirs, key=lambda x: x.name):
|
|
47
|
+
print(f"{indent}- {x.name} ({format_file_size(x.size)})")
|
|
48
|
+
print_folders_in(x, indent + " ")
|
|
49
|
+
|
|
50
|
+
cache = cache_inventory()
|
|
51
|
+
print(f"epymorph cache is using {format_file_size(cache.size)} ({CACHE_PATH})")
|
|
52
|
+
print_folders_in(cache)
|
|
53
|
+
return 0 # exit code: success
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def handle_remove(path: str) -> int:
|
|
57
|
+
"""CLI command handler: remove a file or folder from the cache."""
|
|
58
|
+
try:
|
|
59
|
+
to_remove, confirm_remove = cache_remove_confirmation(path)
|
|
60
|
+
if path == ".":
|
|
61
|
+
print("This will delete all cache entries")
|
|
62
|
+
elif to_remove.is_dir():
|
|
63
|
+
print(f"This will delete all cache entries at {to_remove}")
|
|
64
|
+
else:
|
|
65
|
+
print(f"This will delete the cached file {to_remove}")
|
|
66
|
+
response = input("Are you sure? [y/N]: ")
|
|
67
|
+
if response.lower() in ("y", "yes"):
|
|
68
|
+
confirm_remove()
|
|
69
|
+
return 0 # exit code: success
|
|
70
|
+
except FileError as e:
|
|
71
|
+
print(f"Error: {e}")
|
|
72
|
+
return 1 # exit code: failed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def handle_dir() -> int:
|
|
76
|
+
print(CACHE_PATH)
|
|
77
|
+
return 0
|
epymorph/cli/main.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Implements the main CLI parser."""
|
|
2
|
+
|
|
3
|
+
from argparse import ArgumentParser
|
|
4
|
+
from importlib.metadata import version
|
|
5
|
+
|
|
6
|
+
from epymorph.cli.cache import define_argparser as def_cache
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def define_argparser() -> ArgumentParser:
|
|
10
|
+
"""Builds a parser for all supported CLI commands."""
|
|
11
|
+
# Using argparse to configure available commands and arguments.
|
|
12
|
+
cli_parser = ArgumentParser(
|
|
13
|
+
prog="epymorph", description="EpiMoRPH spatial meta-population modeling."
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
cli_parser.add_argument(
|
|
17
|
+
"-V", "--version", action="version", version=version("epymorph")
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# Define a set of subcommands for the main program.
|
|
21
|
+
# The only requirement is that they all define a 'handler' function
|
|
22
|
+
# in their defaults.
|
|
23
|
+
command_parser = cli_parser.add_subparsers(
|
|
24
|
+
title="commands", dest="command", required=True
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def_cache(command_parser)
|
|
28
|
+
|
|
29
|
+
return cli_parser
|