epymorph 1.0.0__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 +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -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 +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -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 +97 -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 +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
epymorph/cache.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
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 warnings import warn
|
|
14
|
+
|
|
15
|
+
import requests
|
|
16
|
+
from platformdirs import user_cache_path
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _cache_path() -> Path:
|
|
20
|
+
"""
|
|
21
|
+
Get epymorph's cache directory.
|
|
22
|
+
|
|
23
|
+
Returns
|
|
24
|
+
-------
|
|
25
|
+
:
|
|
26
|
+
The path.
|
|
27
|
+
"""
|
|
28
|
+
if (path_var := getenv("EPYMORPH_CACHE_PATH")) is not None:
|
|
29
|
+
# Load path from env var
|
|
30
|
+
path = Path(path_var)
|
|
31
|
+
else:
|
|
32
|
+
# fall back to platform-specific default path
|
|
33
|
+
path = user_cache_path(appname="epymorph")
|
|
34
|
+
# ensure cache directory exists
|
|
35
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
return path
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
CACHE_PATH = _cache_path()
|
|
40
|
+
"""The root directory for epymorph's cached files."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def module_cache_path(name: str) -> Path:
|
|
44
|
+
"""
|
|
45
|
+
Return the cache directory to use for the given module.
|
|
46
|
+
|
|
47
|
+
When epymorph modules need to store files in the cache, they should use a
|
|
48
|
+
subdirectory within the application's cache path. The path should correspond to the
|
|
49
|
+
module's path within epymorph. e.g.: module `epymorph.adrio.acs5` will store files
|
|
50
|
+
in `$CACHE_PATH/adrio/acs5`.
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
name :
|
|
55
|
+
The name of the module, typically given as `__name__`.
|
|
56
|
+
|
|
57
|
+
Returns
|
|
58
|
+
-------
|
|
59
|
+
:
|
|
60
|
+
The cache directory to use, as a relative path since the cache functions
|
|
61
|
+
require that.
|
|
62
|
+
|
|
63
|
+
Examples
|
|
64
|
+
--------
|
|
65
|
+
>>> # if we're in module `epymorph.adrio.acs5`...
|
|
66
|
+
>>> module_cache_path(__name__)
|
|
67
|
+
PosixPath('adrio/acs5')
|
|
68
|
+
"""
|
|
69
|
+
file_name = modules[name].__file__
|
|
70
|
+
if file_name is None:
|
|
71
|
+
return CACHE_PATH
|
|
72
|
+
file_path = Path(file_name).with_suffix("")
|
|
73
|
+
root = file_path.parent
|
|
74
|
+
while root.name != "epymorph":
|
|
75
|
+
root = root.parent
|
|
76
|
+
return file_path.relative_to(root)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FileError(Exception):
|
|
80
|
+
"""Error during a file operation."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class FileMissingError(FileError):
|
|
84
|
+
"""Error loading a file, as it does not exist."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class FileWriteError(FileError):
|
|
88
|
+
"""Error writing a file."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class FileReadError(FileError):
|
|
92
|
+
"""Error loading a file."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class FileVersionError(FileError):
|
|
96
|
+
"""Error loading a file due to unmet version requirements."""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class CacheMissError(FileError):
|
|
100
|
+
"""Raised on a cache-miss (for any reason) during a load-from-cache operation."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CacheWarning(Warning):
|
|
104
|
+
"""
|
|
105
|
+
Warning issued when we are unable to interact with the file cache but in a situation
|
|
106
|
+
where program execution can continue, even if less optimally. For example: if we
|
|
107
|
+
successfully load data from an external source but are unable to cache it for later,
|
|
108
|
+
this is a warning because we assume the data is valid and that it could always
|
|
109
|
+
be loaded again from the same source at a later time. The warning is issued to give
|
|
110
|
+
the user the opportunity to fix it for next time.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def save_file(to_path: str | PathLike[str], file: BytesIO) -> None:
|
|
115
|
+
"""
|
|
116
|
+
Save a single file.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
to_path :
|
|
121
|
+
An absolute or relative path to store the file.
|
|
122
|
+
Relative paths will be resolved against the current working directory.
|
|
123
|
+
Folders in the path which do not exist will be created automatically.
|
|
124
|
+
file :
|
|
125
|
+
The file to store.
|
|
126
|
+
"""
|
|
127
|
+
try:
|
|
128
|
+
file_path = Path(to_path).resolve()
|
|
129
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
with file_path.open(mode="wb") as f:
|
|
131
|
+
f.write(file.getbuffer())
|
|
132
|
+
except Exception as e:
|
|
133
|
+
msg = f"Unable to write file at path: {to_path}"
|
|
134
|
+
raise FileWriteError(msg) from e
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load_file(from_path: str | PathLike[str]) -> BytesIO:
|
|
138
|
+
"""
|
|
139
|
+
Load a single file.
|
|
140
|
+
|
|
141
|
+
Parameters
|
|
142
|
+
----------
|
|
143
|
+
from_path :
|
|
144
|
+
The path to the file.
|
|
145
|
+
|
|
146
|
+
Returns
|
|
147
|
+
-------
|
|
148
|
+
:
|
|
149
|
+
The bytes of the file.
|
|
150
|
+
|
|
151
|
+
Raises
|
|
152
|
+
------
|
|
153
|
+
FileReadError
|
|
154
|
+
If the file cannot be loaded for any reason.
|
|
155
|
+
"""
|
|
156
|
+
try:
|
|
157
|
+
file_path = Path(from_path).resolve()
|
|
158
|
+
if not file_path.is_file():
|
|
159
|
+
raise FileMissingError(f"No file at: {file_path}")
|
|
160
|
+
|
|
161
|
+
# Read the file into memory
|
|
162
|
+
file_buffer = BytesIO()
|
|
163
|
+
with file_path.open(mode="rb") as f:
|
|
164
|
+
file_buffer.write(f.read())
|
|
165
|
+
file_buffer.seek(0)
|
|
166
|
+
return file_buffer
|
|
167
|
+
except FileError:
|
|
168
|
+
raise
|
|
169
|
+
except Exception as e:
|
|
170
|
+
raise FileReadError(f"Unable to load file at: {from_path}") from e
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def save_bundle(
|
|
174
|
+
to_path: str | PathLike[str],
|
|
175
|
+
version: int,
|
|
176
|
+
files: dict[str, BytesIO],
|
|
177
|
+
) -> None:
|
|
178
|
+
"""
|
|
179
|
+
Save a bundle of files in our tar format with an associated version number.
|
|
180
|
+
|
|
181
|
+
Parameters
|
|
182
|
+
----------
|
|
183
|
+
to_path :
|
|
184
|
+
An absolute or relative path to store the file.
|
|
185
|
+
Relative paths will be resolved against the current working directory.
|
|
186
|
+
Folders in the path which do not exist will be created automatically.
|
|
187
|
+
version :
|
|
188
|
+
The version number for the archive.
|
|
189
|
+
files :
|
|
190
|
+
The files to store, with a file name for each (its name within the archive).
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
if version <= 0:
|
|
194
|
+
raise ValueError("version should be greater than zero.")
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
# Compute checksums
|
|
198
|
+
sha_entries = []
|
|
199
|
+
for name, contents in files.items():
|
|
200
|
+
contents.seek(0)
|
|
201
|
+
sha = sha256()
|
|
202
|
+
sha.update(contents.read())
|
|
203
|
+
sha_entries.append(f"{sha.hexdigest()} {name}")
|
|
204
|
+
|
|
205
|
+
# Create checksums.sha256 file
|
|
206
|
+
sha_file = BytesIO()
|
|
207
|
+
sha_text = "\n".join(sha_entries)
|
|
208
|
+
sha_file.write(bytes(sha_text, encoding="utf-8"))
|
|
209
|
+
|
|
210
|
+
# Create cache version file
|
|
211
|
+
ver_file = BytesIO()
|
|
212
|
+
ver_file.write(bytes(str(version), encoding="utf-8"))
|
|
213
|
+
|
|
214
|
+
tarred_files = {
|
|
215
|
+
**files,
|
|
216
|
+
"checksums.sha256": sha_file,
|
|
217
|
+
"version": ver_file,
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
# Write the tar to disk
|
|
221
|
+
tar_path = Path(to_path).resolve()
|
|
222
|
+
tar_path.parent.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
mode = "w:gz" if tar_path.suffix == ".tgz" else "w"
|
|
224
|
+
with open_tarfile(name=tar_path, mode=mode) as tar:
|
|
225
|
+
for name, contents in tarred_files.items():
|
|
226
|
+
info = TarInfo(name)
|
|
227
|
+
info.size = contents.tell()
|
|
228
|
+
contents.seek(0)
|
|
229
|
+
tar.addfile(info, contents)
|
|
230
|
+
|
|
231
|
+
except Exception as e:
|
|
232
|
+
msg = f"Unable to write archive at path: {to_path}"
|
|
233
|
+
raise FileWriteError(msg) from e
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def load_bundle(
|
|
237
|
+
from_path: str | PathLike[str],
|
|
238
|
+
version_at_least: int = -1,
|
|
239
|
+
) -> dict[str, BytesIO]:
|
|
240
|
+
"""
|
|
241
|
+
Load a bundle of files in our tar format, optionally enforcing a minimum version.
|
|
242
|
+
|
|
243
|
+
Parameters
|
|
244
|
+
----------
|
|
245
|
+
from_path :
|
|
246
|
+
The path of the bundle.
|
|
247
|
+
version_at_least :
|
|
248
|
+
The minimally accepted version number to load. -1 to accept any version.
|
|
249
|
+
|
|
250
|
+
Returns
|
|
251
|
+
-------
|
|
252
|
+
:
|
|
253
|
+
A dictionary of the contained files, mapping the internal file names to the
|
|
254
|
+
bytes of the file.
|
|
255
|
+
|
|
256
|
+
Raises
|
|
257
|
+
------
|
|
258
|
+
FileMissingError
|
|
259
|
+
If the file doesn't exist.
|
|
260
|
+
FileReadError
|
|
261
|
+
If the file cannot be read or is not valid.
|
|
262
|
+
FileVersionError
|
|
263
|
+
If there is an existing file but the version is below the minimum allowed.
|
|
264
|
+
"""
|
|
265
|
+
try:
|
|
266
|
+
tar_path = Path(from_path).resolve()
|
|
267
|
+
if not tar_path.is_file():
|
|
268
|
+
raise FileMissingError(f"No file at: {tar_path}")
|
|
269
|
+
|
|
270
|
+
# Read the tar file into memory
|
|
271
|
+
tar_buffer = BytesIO()
|
|
272
|
+
with tar_path.open(mode="rb") as f:
|
|
273
|
+
tar_buffer.write(f.read())
|
|
274
|
+
tar_buffer.seek(0)
|
|
275
|
+
|
|
276
|
+
if not is_tarfile(tar_buffer):
|
|
277
|
+
raise FileReadError(f"Not a tar file at: {tar_path}")
|
|
278
|
+
|
|
279
|
+
mode = "r:gz" if tar_path.suffix == ".tgz" else "r"
|
|
280
|
+
tarred_files: dict[str, BytesIO] = {}
|
|
281
|
+
with open_tarfile(fileobj=tar_buffer, mode=mode) as tar:
|
|
282
|
+
for info in tar.getmembers():
|
|
283
|
+
name = info.name
|
|
284
|
+
contents = tar.extractfile(info)
|
|
285
|
+
if contents is not None:
|
|
286
|
+
tarred_files[name] = BytesIO(contents.read())
|
|
287
|
+
|
|
288
|
+
# Check version
|
|
289
|
+
if "version" in tarred_files:
|
|
290
|
+
ver_file = tarred_files["version"]
|
|
291
|
+
version = int(str(ver_file.readline(), encoding="utf-8"))
|
|
292
|
+
else:
|
|
293
|
+
version = -1
|
|
294
|
+
if version < version_at_least:
|
|
295
|
+
raise FileVersionError("Archive is an unacceptable version.")
|
|
296
|
+
|
|
297
|
+
# Verify the checksums
|
|
298
|
+
if "checksums.sha256" not in tarred_files:
|
|
299
|
+
raise FileReadError("Archive appears to be invalid.")
|
|
300
|
+
sha_file = tarred_files["checksums.sha256"]
|
|
301
|
+
for line_bytes in sha_file.readlines():
|
|
302
|
+
line = str(line_bytes, encoding="utf-8")
|
|
303
|
+
[checksum, filename] = line.strip().split(" ")
|
|
304
|
+
|
|
305
|
+
if filename not in tarred_files:
|
|
306
|
+
raise FileReadError("Archive appears to be invalid.")
|
|
307
|
+
|
|
308
|
+
contents = tarred_files[filename]
|
|
309
|
+
contents.seek(0)
|
|
310
|
+
sha = sha256()
|
|
311
|
+
sha.update(contents.read())
|
|
312
|
+
contents.seek(0)
|
|
313
|
+
if checksum != sha.hexdigest():
|
|
314
|
+
msg = (
|
|
315
|
+
f"Archive checksum did not match (for file {filename}). "
|
|
316
|
+
"It is possible the file is corrupt."
|
|
317
|
+
)
|
|
318
|
+
raise FileReadError(msg)
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
name: contents
|
|
322
|
+
for name, contents in tarred_files.items()
|
|
323
|
+
if name not in ("checksums.sha256", "version")
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
except FileError:
|
|
327
|
+
raise
|
|
328
|
+
except Exception as e:
|
|
329
|
+
raise FileReadError(f"Unable to load archive at: {from_path}") from e
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _resolve_cache_path(path: str | PathLike[str]) -> Path:
|
|
333
|
+
cache_path = Path(path)
|
|
334
|
+
if cache_path.is_absolute():
|
|
335
|
+
raise ValueError(
|
|
336
|
+
"When saving to or loading from the cache, please supply a relative path."
|
|
337
|
+
)
|
|
338
|
+
resolved = CACHE_PATH.joinpath(cache_path).resolve()
|
|
339
|
+
if not resolved.is_relative_to(CACHE_PATH):
|
|
340
|
+
# Ensure the resolved path is still inside CACHE_PATH.
|
|
341
|
+
raise ValueError(
|
|
342
|
+
"When saving to or loading from the cache, please supply a relative path."
|
|
343
|
+
)
|
|
344
|
+
return resolved
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def check_file_in_cache(cache_path: Path) -> bool:
|
|
348
|
+
"""
|
|
349
|
+
Check if a file is currently in the cache.
|
|
350
|
+
|
|
351
|
+
Returns
|
|
352
|
+
-------
|
|
353
|
+
:
|
|
354
|
+
True if so.
|
|
355
|
+
"""
|
|
356
|
+
return _resolve_cache_path(cache_path).exists()
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def save_file_to_cache(to_path: str | PathLike[str], file: BytesIO) -> None:
|
|
360
|
+
"""
|
|
361
|
+
Save a single file to the cache (overwriting the existing file, if any).
|
|
362
|
+
|
|
363
|
+
This is a low-level building block.
|
|
364
|
+
|
|
365
|
+
Parameters
|
|
366
|
+
----------
|
|
367
|
+
to_path :
|
|
368
|
+
A path to store the file, relative to the cache folder.
|
|
369
|
+
file :
|
|
370
|
+
The file bytes to store.
|
|
371
|
+
|
|
372
|
+
Raises
|
|
373
|
+
------
|
|
374
|
+
FileWriteError
|
|
375
|
+
If the file cannot be saved for any reason.
|
|
376
|
+
"""
|
|
377
|
+
try:
|
|
378
|
+
save_file(_resolve_cache_path(to_path), file)
|
|
379
|
+
except ValueError as e:
|
|
380
|
+
raise FileWriteError() from e
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def load_file_from_cache(from_path: str | PathLike[str]) -> BytesIO:
|
|
384
|
+
"""
|
|
385
|
+
Load a single file from the cache.
|
|
386
|
+
|
|
387
|
+
This is a low-level building block.
|
|
388
|
+
|
|
389
|
+
Parameters
|
|
390
|
+
----------
|
|
391
|
+
from_path :
|
|
392
|
+
The path to the file, relative to the cache folder.
|
|
393
|
+
|
|
394
|
+
Returns
|
|
395
|
+
-------
|
|
396
|
+
:
|
|
397
|
+
The file bytes.
|
|
398
|
+
"""
|
|
399
|
+
try:
|
|
400
|
+
return load_file(_resolve_cache_path(from_path))
|
|
401
|
+
except FileError as e:
|
|
402
|
+
raise CacheMissError() from e
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def load_or_fetch(cache_path: Path, fetch: Callable[[], BytesIO]) -> BytesIO:
|
|
406
|
+
"""
|
|
407
|
+
Attempt to load a file from the cache.
|
|
408
|
+
|
|
409
|
+
If the file isn't already in the cache, the provided `fetch` method is used to load
|
|
410
|
+
the file and then it is cached for next time. Any exceptions raised by `fetch` will
|
|
411
|
+
not be caught in this method. If the file was successfully loaded but failed to save
|
|
412
|
+
to the cache, a warning is raised.
|
|
413
|
+
|
|
414
|
+
This is a higher-level but still fairly generic building block.
|
|
415
|
+
|
|
416
|
+
Parameters
|
|
417
|
+
----------
|
|
418
|
+
cache_path :
|
|
419
|
+
The path to the file, relative to the cache folder.
|
|
420
|
+
fetch :
|
|
421
|
+
The function to load the file if it's not in the cache.
|
|
422
|
+
|
|
423
|
+
Returns
|
|
424
|
+
-------
|
|
425
|
+
:
|
|
426
|
+
The file bytes.
|
|
427
|
+
"""
|
|
428
|
+
try:
|
|
429
|
+
# Try to load from cache.
|
|
430
|
+
return load_file_from_cache(cache_path)
|
|
431
|
+
except CacheMissError:
|
|
432
|
+
# On cache miss, fetch file contents.
|
|
433
|
+
file = fetch()
|
|
434
|
+
# And attempt to save the file to the cache for next time.
|
|
435
|
+
try:
|
|
436
|
+
save_file_to_cache(cache_path, file)
|
|
437
|
+
except FileWriteError as e:
|
|
438
|
+
# Failure to save to the cache is not worth stopping the program:
|
|
439
|
+
# raise a warning.
|
|
440
|
+
warn(
|
|
441
|
+
f"Unable to save file to the cache ({cache_path}). Cause:\n{e}",
|
|
442
|
+
CacheWarning,
|
|
443
|
+
)
|
|
444
|
+
return file
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def load_or_fetch_url(url: str, cache_path: Path) -> BytesIO:
|
|
448
|
+
"""
|
|
449
|
+
Attempt to load a file from the cache.
|
|
450
|
+
|
|
451
|
+
If the file isn't already in the cache, the provided `url` is used to load
|
|
452
|
+
the file and then it is cached for next time. Any exceptions raised by `fetch` will
|
|
453
|
+
not be caught in this method. If the file was successfully loaded but failed to save
|
|
454
|
+
to the cache, a warning is raised. URLs must use the http or https protocol.
|
|
455
|
+
|
|
456
|
+
This is a higher-level but still fairly generic building block.
|
|
457
|
+
|
|
458
|
+
Parameters
|
|
459
|
+
----------
|
|
460
|
+
url :
|
|
461
|
+
The url to locate the file if it's not in the cache.
|
|
462
|
+
cache_path :
|
|
463
|
+
The path to the file, relative to the cache folder.
|
|
464
|
+
|
|
465
|
+
Returns
|
|
466
|
+
-------
|
|
467
|
+
:
|
|
468
|
+
The file bytes.
|
|
469
|
+
"""
|
|
470
|
+
|
|
471
|
+
def fetch_url():
|
|
472
|
+
# ruff S310 requires us to check the URL protocol
|
|
473
|
+
# so that only http/s requests are allowed.
|
|
474
|
+
# Then we have to disable S310 on that line, because it can't see it's fixed.
|
|
475
|
+
# Do not remove this check.
|
|
476
|
+
if not url.startswith(("http:", "https:")):
|
|
477
|
+
raise ValueError("Data source URLs must use the http or https protocol.")
|
|
478
|
+
|
|
479
|
+
response = requests.get(url, timeout=(6.05, 42))
|
|
480
|
+
response.raise_for_status()
|
|
481
|
+
return BytesIO(response.content)
|
|
482
|
+
|
|
483
|
+
return load_or_fetch(cache_path, fetch_url)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def save_bundle_to_cache(
|
|
487
|
+
to_path: str | PathLike[str],
|
|
488
|
+
version: int,
|
|
489
|
+
files: dict[str, BytesIO],
|
|
490
|
+
) -> None:
|
|
491
|
+
"""
|
|
492
|
+
Save a tar bundle of files to the cache (overwriting the existing file, if any).
|
|
493
|
+
|
|
494
|
+
The tar includes the sha256 checksums of every content file, and a version file
|
|
495
|
+
indicating which application version was responsible for writing the file (thus
|
|
496
|
+
allowing the application to decide if a cached file is still valid when reading it).
|
|
497
|
+
|
|
498
|
+
Parameters
|
|
499
|
+
----------
|
|
500
|
+
to_path :
|
|
501
|
+
The path to store the bundle, relative to the cache folder.
|
|
502
|
+
version :
|
|
503
|
+
The version number for the archive.
|
|
504
|
+
files :
|
|
505
|
+
The files to store, with a file name for each (its name within the archive).
|
|
506
|
+
"""
|
|
507
|
+
save_bundle(_resolve_cache_path(to_path), version, files)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def load_bundle_from_cache(
|
|
511
|
+
from_path: str | PathLike[str],
|
|
512
|
+
version_at_least: int = -1,
|
|
513
|
+
) -> dict[str, BytesIO]:
|
|
514
|
+
"""
|
|
515
|
+
Load a tar bundle of files from the cache.
|
|
516
|
+
|
|
517
|
+
Parameters
|
|
518
|
+
----------
|
|
519
|
+
from_path :
|
|
520
|
+
The path of the bundle, relative to the cache folder.
|
|
521
|
+
version_at_least :
|
|
522
|
+
The minimally accepted version number to load. -1 to accept any version.
|
|
523
|
+
|
|
524
|
+
Raises
|
|
525
|
+
------
|
|
526
|
+
CacheMissError
|
|
527
|
+
If the bundle cannot be loaded.
|
|
528
|
+
"""
|
|
529
|
+
try:
|
|
530
|
+
return load_bundle(_resolve_cache_path(from_path), version_at_least)
|
|
531
|
+
except FileError as e:
|
|
532
|
+
raise CacheMissError() from e
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
####################
|
|
536
|
+
# Cache Management #
|
|
537
|
+
####################
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
_suffixes = ("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")
|
|
541
|
+
"""https://en.wikipedia.org/wiki/Metric_prefix"""
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def format_file_size(size: int) -> str:
|
|
545
|
+
"""
|
|
546
|
+
Format a file size given in bytes in 1024-based-unit representation.
|
|
547
|
+
|
|
548
|
+
Parameters
|
|
549
|
+
----------
|
|
550
|
+
size :
|
|
551
|
+
The size in bytes.
|
|
552
|
+
|
|
553
|
+
Returns
|
|
554
|
+
-------
|
|
555
|
+
:
|
|
556
|
+
The file size in human-readable format.
|
|
557
|
+
"""
|
|
558
|
+
if size < 0:
|
|
559
|
+
raise ValueError("size cannot be less than zero.")
|
|
560
|
+
if size < 1024:
|
|
561
|
+
return f"{size} {_suffixes[0]}"
|
|
562
|
+
magnitude = int(log(size, 1024))
|
|
563
|
+
if magnitude >= len(_suffixes):
|
|
564
|
+
raise ValueError("size is too large to format.")
|
|
565
|
+
fsize = size / pow(1024, magnitude)
|
|
566
|
+
return f"{fsize:.1f} {_suffixes[magnitude]}"
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
class Directory(NamedTuple):
|
|
570
|
+
"""A directory."""
|
|
571
|
+
|
|
572
|
+
name: str
|
|
573
|
+
"""The directory name."""
|
|
574
|
+
size: int
|
|
575
|
+
"""The combined size of all of this directory's children."""
|
|
576
|
+
children: "Sequence[FileTree]"
|
|
577
|
+
"""The directory's children, which may be files or nested directories."""
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
class File(NamedTuple):
|
|
581
|
+
"""A file."""
|
|
582
|
+
|
|
583
|
+
name: str
|
|
584
|
+
"""The file name."""
|
|
585
|
+
size: int
|
|
586
|
+
"""The file size."""
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
FileTree = Directory | File
|
|
590
|
+
"""Nodes in a file tree are either directories or files."""
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def cache_inventory() -> Directory:
|
|
594
|
+
"""List the contents of epymorph's cache as a FileTree."""
|
|
595
|
+
|
|
596
|
+
def recurse(directory: Path) -> Directory:
|
|
597
|
+
children = []
|
|
598
|
+
size = 0
|
|
599
|
+
for path in directory.iterdir():
|
|
600
|
+
if path.is_symlink():
|
|
601
|
+
# Ignore symlinks.
|
|
602
|
+
continue
|
|
603
|
+
if path.is_file():
|
|
604
|
+
file_size = path.stat().st_size
|
|
605
|
+
children.append(File(path.name, file_size))
|
|
606
|
+
size += file_size
|
|
607
|
+
elif path.is_dir():
|
|
608
|
+
d = recurse(path)
|
|
609
|
+
children.append(d)
|
|
610
|
+
size += d.size
|
|
611
|
+
return Directory(directory.name, size, children)
|
|
612
|
+
|
|
613
|
+
if not CACHE_PATH.exists():
|
|
614
|
+
return Directory(CACHE_PATH.name, 0, [])
|
|
615
|
+
return recurse(CACHE_PATH)
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def cache_remove_confirmation(
|
|
619
|
+
path: str | PathLike[str],
|
|
620
|
+
) -> tuple[Path, Callable[[], None]]:
|
|
621
|
+
"""
|
|
622
|
+
Create a function which removes a directory or file from the cache.
|
|
623
|
+
|
|
624
|
+
Also returns the resolved path to the thing that will be removed;
|
|
625
|
+
this allows the application to confirm the removal.
|
|
626
|
+
|
|
627
|
+
Parameters
|
|
628
|
+
----------
|
|
629
|
+
path :
|
|
630
|
+
The path to the file, relative to the cache folder.
|
|
631
|
+
|
|
632
|
+
Returns
|
|
633
|
+
-------
|
|
634
|
+
:
|
|
635
|
+
A tuple of the absolute file path and a function to remove it.
|
|
636
|
+
"""
|
|
637
|
+
try:
|
|
638
|
+
# This makes sure we don't delete things outside of the cache path.
|
|
639
|
+
to_remove = _resolve_cache_path(path)
|
|
640
|
+
except ValueError as e:
|
|
641
|
+
raise FileError(str(e)) from None
|
|
642
|
+
if not to_remove.exists():
|
|
643
|
+
raise FileError(f"Given path is not in the cache: {to_remove}")
|
|
644
|
+
|
|
645
|
+
def confirm_remove() -> None:
|
|
646
|
+
# Remove the target file/dir
|
|
647
|
+
if to_remove.is_file():
|
|
648
|
+
to_remove.unlink()
|
|
649
|
+
else:
|
|
650
|
+
rmtree(to_remove)
|
|
651
|
+
|
|
652
|
+
# Remove any newly-empty parent directories, up to the cache dir
|
|
653
|
+
parents = [
|
|
654
|
+
p
|
|
655
|
+
for p in to_remove.parents
|
|
656
|
+
if p.is_relative_to(CACHE_PATH) and p != CACHE_PATH
|
|
657
|
+
]
|
|
658
|
+
for p in parents:
|
|
659
|
+
if any(p.iterdir()):
|
|
660
|
+
break # parent not empty, we can stop
|
|
661
|
+
p.rmdir() # parent is empty
|
|
662
|
+
|
|
663
|
+
# We may need to replace the cache dir if we just deleted it.
|
|
664
|
+
CACHE_PATH.mkdir(parents=True, exist_ok=True)
|
|
665
|
+
|
|
666
|
+
return to_remove, confirm_remove
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def cache_remove(path: str | PathLike[str]) -> None:
|
|
670
|
+
"""
|
|
671
|
+
Remove a directory or file from the cache.
|
|
672
|
+
|
|
673
|
+
Parameters
|
|
674
|
+
----------
|
|
675
|
+
path :
|
|
676
|
+
The path to remove.
|
|
677
|
+
"""
|
|
678
|
+
# This is the "no confirmation" version of `cache_remove_confirmation`
|
|
679
|
+
_, confirm_remove = cache_remove_confirmation(path)
|
|
680
|
+
confirm_remove()
|
epymorph/cli/__init__.py
ADDED
|
File without changes
|