|
| 1 | +"""Persistent decoded-data cache for Raw readers.""" |
| 2 | + |
| 3 | +# Authors: The MNE-Python contributors. |
| 4 | +# License: BSD-3-Clause |
| 5 | +# Copyright the MNE-Python contributors. |
| 6 | + |
| 7 | +import hashlib |
| 8 | +import os |
| 9 | +import pickle |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +from .. import __version__ as MNE_VERSION # ty: ignore[unresolved-import] |
| 15 | +from ..utils import get_config, logger |
| 16 | + |
| 17 | +_RAW_PRELOAD_CACHE_VERSION = 1 |
| 18 | + |
| 19 | + |
| 20 | +def _raw_preload_cache_info(raw): |
| 21 | + """Return the cache path and decoded array description.""" |
| 22 | + cache_root = get_config("MNE_CACHE_DIR", None) |
| 23 | + if cache_root is None: |
| 24 | + raise ValueError( |
| 25 | + 'preload="auto" requires a configured cache directory; use ' |
| 26 | + "mne.set_cache_dir(...) first" |
| 27 | + ) |
| 28 | + cache_dir = Path(cache_root).expanduser().resolve() |
| 29 | + cache_dir = cache_dir / f"raw-preload-v{_RAW_PRELOAD_CACHE_VERSION}" |
| 30 | + cache_dir.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 31 | + |
| 32 | + sources = [] |
| 33 | + for filename in raw.filenames: |
| 34 | + if filename is None: |
| 35 | + raise ValueError( |
| 36 | + 'preload="auto" requires stable source files; use preload=True ' |
| 37 | + "or an explicit memory-map path" |
| 38 | + ) |
| 39 | + path = Path(filename).resolve(strict=True) |
| 40 | + # some formats (e.g., CTF) name a directory rather than a single file |
| 41 | + members = sorted(path.rglob("*")) if path.is_dir() else [path] |
| 42 | + for member in members: |
| 43 | + if not member.is_file(): |
| 44 | + continue |
| 45 | + result = member.stat() |
| 46 | + sources.append((str(member), int(result.st_size), int(result.st_mtime_ns))) |
| 47 | + |
| 48 | + dtype = np.dtype(raw._dtype) |
| 49 | + shape = (int(raw.info["nchan"]), int(raw.n_times)) |
| 50 | + identity = ( |
| 51 | + _RAW_PRELOAD_CACHE_VERSION, |
| 52 | + MNE_VERSION, |
| 53 | + type(raw).__module__, |
| 54 | + type(raw).__qualname__, |
| 55 | + sources, |
| 56 | + raw._raw_extras, |
| 57 | + raw._cals, |
| 58 | + dtype.str, |
| 59 | + shape, |
| 60 | + ) |
| 61 | + try: |
| 62 | + key = hashlib.sha256(pickle.dumps(identity, protocol=5)).hexdigest() |
| 63 | + except Exception as exc: |
| 64 | + raise ValueError( |
| 65 | + f'preload="auto" cannot identify this {type(raw).__name__} source' |
| 66 | + ) from exc |
| 67 | + return cache_dir / f"{key}.data", sources, shape, dtype |
| 68 | + |
| 69 | + |
| 70 | +def _raw_preload_cache_read(path, shape, dtype): |
| 71 | + """Map a complete decoded-data cache entry.""" |
| 72 | + try: |
| 73 | + nbytes = int(np.prod(shape, dtype=np.int64)) * dtype.itemsize |
| 74 | + if path.stat().st_size != nbytes: |
| 75 | + return None |
| 76 | + return np.memmap(path, mode="c", dtype=dtype, shape=shape) |
| 77 | + except OSError: |
| 78 | + return None |
| 79 | + |
| 80 | + |
| 81 | +def _raw_preload_auto(raw): |
| 82 | + """Reuse or create an automatic decoded-data cache entry.""" |
| 83 | + path, sources, shape, dtype = _raw_preload_cache_info(raw) |
| 84 | + data = _raw_preload_cache_read(path, shape, dtype) |
| 85 | + if data is not None: |
| 86 | + logger.info(f"Reusing decoded data from {path}") |
| 87 | + return data |
| 88 | + |
| 89 | + # The temporary is per-process and os.replace is atomic, so concurrent |
| 90 | + # misses need no lock; they at worst decode the same entry twice. |
| 91 | + logger.info(f"Creating decoded data cache in {path.parent}") |
| 92 | + temporary = path.with_suffix(f".{os.getpid()}.tmp") |
| 93 | + try: |
| 94 | + data = np.memmap(temporary, mode="w+", dtype=dtype, shape=shape) |
| 95 | + try: |
| 96 | + raw._read_segment(data_buffer=data) |
| 97 | + data.flush() |
| 98 | + finally: |
| 99 | + data._mmap.close() # ty: ignore[unresolved-attribute] |
| 100 | + if _raw_preload_cache_info(raw)[1] != sources: |
| 101 | + raise RuntimeError( |
| 102 | + "Source data changed while decoded cache was created; retry" |
| 103 | + ) |
| 104 | + try: |
| 105 | + os.replace(temporary, path) |
| 106 | + except OSError: |
| 107 | + # Windows refuses to replace an entry another process already mapped. |
| 108 | + pass |
| 109 | + finally: |
| 110 | + temporary.unlink(missing_ok=True) |
| 111 | + data = _raw_preload_cache_read(path, shape, dtype) |
| 112 | + if data is None: |
| 113 | + raise RuntimeError(f"Could not read back the decoded data cache at {path}") |
| 114 | + return data |
0 commit comments