diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e0b84c56..f70023f81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Changed +- The default cache directory is no longer the working directory: after `EEGDASH_CACHE_DIR` and an existing `./.eegdash_cache` (kept, so nothing is downloaded again), it is `$SCRATCH/eegdash` when `$SCRATCH` is writable, then `MNE_DATA`, then the platform user cache (`platformdirs`); `./.eegdash_cache` is the last resort. The resolved path is logged once (#400, #435 by Christopher Pruijsen). - Requires `mne>=1.13` and `mne_bids>=0.20` (were 1.11 / 0.19). MNE 1.11 has no `read_raw_mef`, so MNE-BIDS left `.mefd` out of its readers and EEGDash silently dropped the 640 MEF3 records; 1.13 also reuses the MEF session across reads (mne-python#14254). ### Added diff --git a/eegdash/corpus.py b/eegdash/corpus.py index abfeb3b5f..4f50b4c87 100644 --- a/eegdash/corpus.py +++ b/eegdash/corpus.py @@ -264,8 +264,8 @@ class EEGDashCorpus: or the path of a CSV with a ``dataset_id`` column (an ``n_subjects`` column is checked against the catalogue when present). cache_dir : str | Path | None - As for :class:`EEGDashDataset` (``EEGDASH_CACHE_DIR``, else - ``./.eegdash_cache``). + As for :class:`EEGDashDataset` (see + :func:`eegdash.paths.get_default_cache_dir`). eeg_dash_instance : EEGDash | None The catalogue client, created when first needed (verify, status and records never need one). @@ -536,7 +536,7 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("command", choices=("plan", "download", "verify", "status")) parser.add_argument("corpus", help="a CSV with a dataset_id column, or ids a,b,c") parser.add_argument( - "--cache-dir", help="default EEGDASH_CACHE_DIR or ./.eegdash_cache" + "--cache-dir", help="default: eegdash.paths.get_default_cache_dir()" ) parser.add_argument("--n-jobs", type=int, default=8) parser.add_argument("--n-datasets", type=int, default=2, help="download") diff --git a/eegdash/dataset/base.py b/eegdash/dataset/base.py index 1a69b4f66..d2d781367 100644 --- a/eegdash/dataset/base.py +++ b/eegdash/dataset/base.py @@ -510,9 +510,9 @@ def _destination_lock(dest: Path) -> threading.Lock: """ # resolve(), not absolute(): two spellings of one file must map to one lock. # absolute() leaves symlinks and ".." in place and is cwd-dependent, and - # cache_dir is frequently relative (EEGDASH_CACHE_DIR defaults to - # ".eegdash_cache"), so absolute() would hand two callers different locks - # for the same destination and serialize nothing. + # cache_dir is frequently relative (EEGDASH_CACHE_DIR or a cache_dir + # argument such as ".eegdash_cache"), so absolute() would hand two callers + # different locks for the same destination and serialize nothing. key = dest.resolve() with _DESTINATION_LOCKS_GUARD: return _DESTINATION_LOCKS.setdefault(key, threading.Lock()) diff --git a/eegdash/paths.py b/eegdash/paths.py index 0da3e0525..696dcf6e0 100644 --- a/eegdash/paths.py +++ b/eegdash/paths.py @@ -11,50 +11,92 @@ from __future__ import annotations +import logging import os from pathlib import Path from mne.utils import get_config as mne_get_config +from platformdirs import user_cache_dir + +logger = logging.getLogger(__name__) + +_cache_dir_logged = False + + +def _is_writable_dir(path: Path) -> bool: + """Return True when *path* is an existing, writable directory.""" + try: + return path.is_dir() and os.access(path, os.W_OK) + except OSError: + return False + + +def _create_and_check_writable(path: Path) -> bool: + """Create *path* including parents and return True when it is writable.""" + try: + path.mkdir(parents=True, exist_ok=True) + except OSError: + return False + return os.access(path, os.W_OK) + + +def _log_resolved(path: Path) -> Path: + """Log the resolved cache directory once per process and return it.""" + global _cache_dir_logged + if not _cache_dir_logged: + logger.info("EEGDash cache directory: %s", path) + _cache_dir_logged = True + return path def get_default_cache_dir() -> Path: """Resolve the default cache directory for EEGDash data. - The function determines the cache directory based on the following - priority order: + The first match wins: - 1. The path specified by the ``EEGDASH_CACHE_DIR`` environment variable. - 2. A hidden directory named ``.eegdash_cache`` in the current working - directory. - 3. The path specified by the ``MNE_DATA`` configuration in the MNE-Python - config file (fallback). + 1. The ``EEGDASH_CACHE_DIR`` environment variable. + 2. An existing ``.eegdash_cache`` in the current working directory (the + previous default), so an existing cache is not downloaded again. + 3. An ``eegdash`` directory inside ``$SCRATCH`` when it points to a + writable directory (common on HPC clusters). + 4. The ``MNE_DATA`` configuration of MNE-Python. + 5. The platform user-cache directory + (:func:`platformdirs.user_cache_dir`). + 6. ``.eegdash_cache`` in the current working directory (last resort). + + The resolved path is logged once per process. Returns ------- - pathlib.Path + Path The resolved, absolute path to the default cache directory. """ - # 1) Explicit env var wins env_dir = os.environ.get("EEGDASH_CACHE_DIR") if env_dir: - return Path(env_dir).expanduser().resolve() + return _log_resolved(Path(env_dir).expanduser().resolve()) - # 2) Default to a project-local hidden folder (best for CI & reproducibility) local = Path.cwd() / ".eegdash_cache" - try: - local.mkdir(exist_ok=True, parents=True) - return local - except Exception: - pass + if local.is_dir(): + return _log_resolved(local) + + scratch = os.environ.get("SCRATCH") + if scratch and _is_writable_dir(Path(scratch).expanduser()): + return _log_resolved(Path(scratch).expanduser().resolve() / "eegdash") - # 3) Fall back to MNE's data cache location if configured mne_data = mne_get_config("MNE_DATA") if mne_data: - return Path(mne_data).expanduser().resolve() + return _log_resolved(Path(mne_data).expanduser().resolve()) - # Last-resort: local path without pre-creating - return local + platform_cache = Path(user_cache_dir("eegdash", appauthor=False)) + if _create_and_check_writable(platform_cache): + return _log_resolved(platform_cache) + + try: + local.mkdir(exist_ok=True, parents=True) + except OSError: + pass + return _log_resolved(local) __all__ = ["get_default_cache_dir"] diff --git a/examples/tutorials/40_features/plot_42_features_to_sklearn.py b/examples/tutorials/40_features/plot_42_features_to_sklearn.py index 418c7e353..1689b5b4d 100644 --- a/examples/tutorials/40_features/plot_42_features_to_sklearn.py +++ b/examples/tutorials/40_features/plot_42_features_to_sklearn.py @@ -11,8 +11,8 @@ ---------------- Install EEGDash's dependencies and run ``plot_40_first_features.py`` first. Use exactly the same ``EEGDASH_CACHE_DIR`` for both scripts; the default -``.eegdash_cache`` is relative to the working directory. You need the CSV and -its adjacent JSON schema, but no live signal download for this page. +location depends on the environment (``$SCRATCH``, ``MNE_DATA``, ...). You need +the CSV and its adjacent JSON schema, but no live signal download for this page. Tutorial 11 explains the participant split used below. """ diff --git a/pyproject.toml b/pyproject.toml index 50e3efc7c..874131d76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -70,6 +70,7 @@ dependencies = [ # install stays lean. "nemar-py>=0.2.0", "pandas", + "platformdirs", "pydantic", "pymatreader", "requests>=2.25.0", diff --git a/tests/unit_tests/test_paths.py b/tests/unit_tests/test_paths.py index 9564ab50c..c8a40d703 100644 --- a/tests/unit_tests/test_paths.py +++ b/tests/unit_tests/test_paths.py @@ -1,48 +1,84 @@ +import logging +import os from pathlib import Path -from unittest.mock import patch import pytest +import eegdash.paths as paths_module from eegdash.paths import get_default_cache_dir +@pytest.fixture(autouse=True) +def isolated(monkeypatch, tmp_path): + """Empty working directory, no cache env vars, no MNE_DATA, a temp user cache.""" + for var in ("EEGDASH_CACHE_DIR", "SCRATCH", "TMPDIR"): + monkeypatch.delenv(var, raising=False) + cwd = tmp_path / "cwd" + cwd.mkdir() + monkeypatch.chdir(cwd) + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: None) + monkeypatch.setattr( + paths_module, "user_cache_dir", lambda *a, **k: str(tmp_path / "user-cache") + ) + return tmp_path + + @pytest.mark.parametrize("env_value", ["~/custom_eegdash_cache", "/opt/eegdash-cache"]) -def test_get_default_cache_dir_from_env(monkeypatch, env_value): +def test_env_var_wins(monkeypatch, env_value): monkeypatch.setenv("EEGDASH_CACHE_DIR", env_value) - assert get_default_cache_dir() == Path(env_value).expanduser().resolve() -def test_get_default_cache_dir_prefers_local_hidden_folder(monkeypatch, tmp_path): - monkeypatch.delenv("EEGDASH_CACHE_DIR", raising=False) +def test_resolution_order(monkeypatch, isolated): + scratch, mne_dir = isolated / "scratch", isolated / "mne" + scratch.mkdir() + monkeypatch.setenv("SCRATCH", str(scratch)) + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: str(mne_dir)) + local = Path.cwd() / ".eegdash_cache" + + local.mkdir() # an existing working-directory cache is kept + assert get_default_cache_dir() == local + local.rmdir() + assert get_default_cache_dir() == scratch / "eegdash" + monkeypatch.delenv("SCRATCH") + assert get_default_cache_dir() == mne_dir + monkeypatch.setattr(paths_module, "mne_get_config", lambda key: None) + assert get_default_cache_dir() == isolated / "user-cache" + assert not local.exists() + + +def test_tmpdir_is_not_used(monkeypatch, isolated): + # TMPDIR is purged by macOS and wiped after a Slurm job: never a default. + monkeypatch.setenv("TMPDIR", str(isolated)) + assert get_default_cache_dir() == isolated / "user-cache" - with patch("eegdash.paths.mne_get_config", return_value=str(tmp_path / "mne_data")): - with patch.object(Path, "cwd", return_value=tmp_path): - resolved = get_default_cache_dir() - assert resolved == tmp_path / ".eegdash_cache" - assert resolved.exists() +@pytest.mark.parametrize("writable", [False, None]) # unwritable, missing +def test_unusable_scratch_is_skipped(monkeypatch, isolated, writable): + scratch = isolated / "scratch" + if writable is False: + scratch.mkdir() + real = os.access + monkeypatch.setattr( + os, "access", lambda p, m: False if Path(p) == scratch else real(p, m) + ) + monkeypatch.setenv("SCRATCH", str(scratch)) + assert get_default_cache_dir() == isolated / "user-cache" -@pytest.mark.parametrize( - "mne_value,expected_name", - [ - ("~/mne-data", "mne-data"), - (None, ".eegdash_cache"), - ], -) -def test_get_default_cache_dir_fallbacks_when_local_mkdir_fails( - monkeypatch, tmp_path, mne_value, expected_name -): - monkeypatch.delenv("EEGDASH_CACHE_DIR", raising=False) +def test_working_directory_is_the_last_resort(monkeypatch, isolated): + (isolated / "a-file").touch() # the user cache cannot be created below a file + monkeypatch.setattr( + paths_module, "user_cache_dir", lambda *a, **k: str(isolated / "a-file" / "x") + ) + resolved = get_default_cache_dir() + assert resolved == Path.cwd() / ".eegdash_cache" + assert resolved.is_dir() - with patch.object(Path, "cwd", return_value=tmp_path): - with patch.object(Path, "mkdir", side_effect=PermissionError("readonly")): - with patch("eegdash.paths.mne_get_config", return_value=mne_value): - resolved = get_default_cache_dir() - assert resolved.name == expected_name - if mne_value is None: - assert resolved == tmp_path / ".eegdash_cache" - else: - assert resolved == Path(mne_value).expanduser().resolve() +def test_logs_once(monkeypatch, caplog): + monkeypatch.setattr(paths_module, "_cache_dir_logged", False) + with caplog.at_level(logging.INFO, logger="eegdash.paths"): + get_default_cache_dir() + get_default_cache_dir() + assert sum("cache directory" in r.getMessage() for r in caplog.records) == 1