Source code for ADCS.helpers.asset_manager

"""Locate large data assets and request consent before downloading them."""

from __future__ import annotations

import os
import sys
import hashlib
from dataclasses import dataclass
from pathlib import Path
from urllib.request import Request, urlopen

from tqdm.auto import tqdm


[docs] def user_cache_dir() -> Path: """Writable per-user cache root on Linux, WSL, macOS, and Windows. ``XDG_CACHE_HOME`` takes precedence on every platform, as it did in 0.2.1, so one variable relocates the cache (and the tests' isolation works) on macOS and Windows too. """ xdg = os.environ.get("XDG_CACHE_HOME") platform = getattr(sys, "platform", "linux") if xdg: base = Path(xdg).expanduser() elif platform == "win32": base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") elif platform == "darwin": base = Path.home() / "Library" / "Caches" else: base = Path.home() / ".cache" return base / "generalized_adcs"
[docs] @dataclass(frozen=True) class Asset: name: str url: str filename: str sha256: str | None = None
KERNEL_DIR = Path(__file__).resolve().parents[1] / "environment" / "kernels" NAIF = "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/" ASSETS = { name: Asset(name, NAIF + name + ".bsp", name + ".bsp") for name in ("de421", "de442", "de442s", "de441_part-1", "de441_part-2") } ASSETS.update({ "bsc5": Asset("bsc5", "https://cdsarc.cds.unistra.fr/ftp/cats/V/50/catalog.gz", "bsc5_catalog.gz"), "hipparcos": Asset("hipparcos", "https://cdsarc.cds.unistra.fr/ftp/cats/I/239/hip_main.dat", "hip_main.dat"), # The SHC-format file from the official IGRF-14 release (doi:10.5281/zenodo.14012303). # NOAA's igrf14coeffs.txt is a wide table in a different format that _read_shc cannot parse. "igrf14": Asset("igrf14", "https://zenodo.org/records/14012303/files/IGRF14.shc?download=1", "IGRF14.shc"), "wmm2025": Asset("wmm2025", "https://www.ngdc.noaa.gov/geomag/calculators/mobileStatic/WMM.COF", "WMM2025.COF"), }) ASSETS.update({ "chaos8_core": Asset("CHAOS8 core", "https://zenodo.org/records/22959079/files/CHAOS-8.7_core.shc?download=1", "CHAOS-8.7_core.shc"), "chaos8_static": Asset("CHAOS8 static", "https://zenodo.org/records/22959079/files/CHAOS-8.7_static.shc?download=1", "CHAOS-8.7_static.shc"), })
[docs] class AssetManager: """Resolve registered files from local directories or a user cache.""" def __init__(self, registry=None, locations=None, cache_dir=None): self.registry = ASSETS if registry is None else registry self.locations = [KERNEL_DIR] if locations is None else [Path(p) for p in locations] self.cache_dir = Path(cache_dir) if cache_dir is not None else user_cache_dir() @staticmethod def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
[docs] def get(self, name: str, *, destination=None, interactive=True, allow_download=False) -> Path: asset = self.registry[name] candidates = ([Path(destination)] if destination is not None else [p / asset.filename for p in self.locations] + [self.cache_dir / asset.filename]) for path in candidates: if path.is_file(): if asset.sha256 and self._sha256(path) != asset.sha256: raise ValueError(f"Checksum mismatch for {name}: {path}") return path target = Path(destination) if destination is not None else self.cache_dir / asset.filename if not allow_download: if not interactive or not sys.stdin.isatty(): raise FileNotFoundError( f"Missing {name}: {target}. Run this in a terminal and approve the download, " "or place the asset at that path." ) answer = input(f"Download {name} from {asset.url} to {target}? [y/N] ") if answer.strip().lower() not in ("y", "yes"): raise FileNotFoundError(f"Download declined for {name}: {target}") target.parent.mkdir(parents=True, exist_ok=True) partial = target.with_name(target.name + ".part") try: request = Request( asset.url, headers={"User-Agent": "Generalized-ADCS/0.2 (+https://github.com/nscheuer/Generalized_ADCS)"}, ) with tqdm(unit="B", unit_scale=True, unit_divisor=1024, desc=name) as bar: with urlopen(request) as response, partial.open("wb") as output: length = response.headers.get("Content-Length") if length is not None: bar.total = int(length) while chunk := response.read(1024 * 1024): output.write(chunk) bar.update(len(chunk)) if asset.sha256: if self._sha256(partial) != asset.sha256: raise ValueError(f"Checksum mismatch for {name}") partial.replace(target) finally: partial.unlink(missing_ok=True) return target