eegdash 0.3.6.dev183416654__py3-none-any.whl → 0.3.7__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.

Potentially problematic release.


This version of eegdash might be problematic. Click here for more details.

eegdash/api.py CHANGED
@@ -3,68 +3,67 @@ import os
3
3
  import tempfile
4
4
  from pathlib import Path
5
5
  from typing import Any, Mapping
6
+ from urllib.parse import urlsplit
6
7
 
7
8
  import mne
8
9
  import numpy as np
9
- import platformdirs
10
10
  import xarray as xr
11
11
  from dotenv import load_dotenv
12
12
  from joblib import Parallel, delayed
13
13
  from mne.utils import warn
14
- from mne_bids import get_bids_path_from_fname, read_raw_bids
14
+ from mne_bids import find_matching_paths, get_bids_path_from_fname, read_raw_bids
15
15
  from pymongo import InsertOne, UpdateOne
16
16
  from s3fs import S3FileSystem
17
17
 
18
18
  from braindecode.datasets import BaseConcatDataset
19
19
 
20
- from .data_config import config as data_config
21
- from .data_utils import EEGBIDSDataset, EEGDashBaseDataset
20
+ from .bids_eeg_metadata import (
21
+ build_query_from_kwargs,
22
+ load_eeg_attrs_from_bids_file,
23
+ merge_participants_fields,
24
+ normalize_key,
25
+ )
26
+ from .const import (
27
+ ALLOWED_QUERY_FIELDS,
28
+ RELEASE_TO_OPENNEURO_DATASET_MAP,
29
+ )
30
+ from .const import config as data_config
31
+ from .data_utils import (
32
+ EEGBIDSDataset,
33
+ EEGDashBaseDataset,
34
+ )
22
35
  from .mongodb import MongoConnectionManager
36
+ from .paths import get_default_cache_dir
23
37
 
24
38
  logger = logging.getLogger("eegdash")
25
39
 
26
40
 
27
41
  class EEGDash:
28
- """A high-level interface to the EEGDash database.
42
+ """High-level interface to the EEGDash metadata database.
29
43
 
30
- This class is primarily used to interact with the metadata records stored in the
31
- EEGDash database (or a private instance of it), allowing users to find, add, and
32
- update EEG data records.
33
-
34
- While this class provides basic support for loading EEG data, please see
35
- the EEGDashDataset class for a more complete way to retrieve and work with full
36
- datasets.
44
+ Provides methods to query, insert, and update metadata records stored in the
45
+ EEGDash MongoDB database (public or private). Also includes utilities to load
46
+ EEG data from S3 for matched records.
37
47
 
48
+ For working with collections of
49
+ recordings as PyTorch datasets, prefer :class:`EEGDashDataset`.
38
50
  """
39
51
 
40
- _ALLOWED_QUERY_FIELDS = {
41
- "data_name",
42
- "dataset",
43
- "subject",
44
- "task",
45
- "session",
46
- "run",
47
- "modality",
48
- "sampling_frequency",
49
- "nchans",
50
- "ntimes",
51
- }
52
-
53
52
  def __init__(self, *, is_public: bool = True, is_staging: bool = False) -> None:
54
- """Create new instance of the EEGDash Database client.
53
+ """Create a new EEGDash client.
55
54
 
56
55
  Parameters
57
56
  ----------
58
- is_public: bool
59
- Whether to connect to the public MongoDB database; if False, connect to a
60
- private database instance as per the DB_CONNECTION_STRING env variable
61
- (or .env file entry).
62
- is_staging: bool
63
- If True, use staging MongoDB database ("eegdashstaging"); otherwise use the
64
- production database ("eegdash").
65
-
66
- Example
67
- -------
57
+ is_public : bool, default True
58
+ Connect to the public MongoDB database. If ``False``, connect to a
59
+ private database instance using the ``DB_CONNECTION_STRING`` environment
60
+ variable (or value from a ``.env`` file).
61
+ is_staging : bool, default False
62
+ If ``True``, use the staging database (``eegdashstaging``); otherwise
63
+ use the production database (``eegdash``).
64
+
65
+ Examples
66
+ --------
68
67
  >>> eegdash = EEGDash()
69
68
 
70
69
  """
@@ -105,23 +104,25 @@ class EEGDash:
105
104
 
106
105
  Parameters
107
106
  ----------
108
- query: dict, optional
109
- A complete MongoDB query dictionary. This is a positional-only argument.
110
- **kwargs:
111
- Keyword arguments representing field-value pairs for the query.
112
- Values can be single items (str, int) or lists of items for multi-search.
107
+ query : dict, optional
108
+ Complete MongoDB query dictionary. This is a positional-only
109
+ argument.
110
+ **kwargs
111
+ User-friendly field filters that are converted to a MongoDB query.
112
+ Values can be scalars (e.g., ``"sub-01"``) or sequences (translated
113
+ to ``$in`` queries).
113
114
 
114
115
  Returns
115
116
  -------
116
- list:
117
- A list of DB records (string-keyed dictionaries) that match the query.
117
+ list of dict
118
+ DB records that match the query.
118
119
 
119
120
  """
120
121
  final_query: dict[str, Any] | None = None
121
122
 
122
123
  # Accept explicit empty dict {} to mean "match all"
123
124
  raw_query = query if isinstance(query, dict) else None
124
- kwargs_query = self._build_query_from_kwargs(**kwargs) if kwargs else None
125
+ kwargs_query = build_query_from_kwargs(**kwargs) if kwargs else None
125
126
 
126
127
  # Determine presence, treating {} as a valid raw query
127
128
  has_raw = isinstance(raw_query, dict)
@@ -238,59 +239,12 @@ class EEGDash:
238
239
  return record
239
240
 
240
241
  def _build_query_from_kwargs(self, **kwargs) -> dict[str, Any]:
241
- """Build and validate a MongoDB query from user-friendly keyword arguments.
242
+ """Internal helper to build a validated MongoDB query from keyword args.
242
243
 
243
- Improvements:
244
- - Reject None values and empty/whitespace-only strings
245
- - For list/tuple/set values: strip strings, drop None/empties, deduplicate, and use `$in`
246
- - Preserve scalars as exact matches
244
+ This delegates to the module-level builder used across the package and
245
+ is exposed here for testing and convenience.
247
246
  """
248
- # 1. Validate that all provided keys are allowed for querying
249
- unknown_fields = set(kwargs.keys()) - self._ALLOWED_QUERY_FIELDS
250
- if unknown_fields:
251
- raise ValueError(
252
- f"Unsupported query field(s): {', '.join(sorted(unknown_fields))}. "
253
- f"Allowed fields are: {', '.join(sorted(self._ALLOWED_QUERY_FIELDS))}"
254
- )
255
-
256
- # 2. Construct the query dictionary
257
- query = {}
258
- for key, value in kwargs.items():
259
- # None is not a valid constraint
260
- if value is None:
261
- raise ValueError(
262
- f"Received None for query parameter '{key}'. Provide a concrete value."
263
- )
264
-
265
- # Handle list-like values as multi-constraints
266
- if isinstance(value, (list, tuple, set)):
267
- cleaned: list[Any] = []
268
- for item in value:
269
- if item is None:
270
- continue
271
- if isinstance(item, str):
272
- item = item.strip()
273
- if not item:
274
- continue
275
- cleaned.append(item)
276
- # Deduplicate while preserving order
277
- cleaned = list(dict.fromkeys(cleaned))
278
- if not cleaned:
279
- raise ValueError(
280
- f"Received an empty list for query parameter '{key}'. This is not supported."
281
- )
282
- query[key] = {"$in": cleaned}
283
- else:
284
- # Scalars: trim strings and validate
285
- if isinstance(value, str):
286
- value = value.strip()
287
- if not value:
288
- raise ValueError(
289
- f"Received an empty string for query parameter '{key}'."
290
- )
291
- query[key] = value
292
-
293
- return query
247
+ return build_query_from_kwargs(**kwargs)
294
248
 
295
249
  # --- Query merging and conflict detection helpers ---
296
250
  def _extract_simple_constraint(self, query: dict[str, Any], key: str):
@@ -323,8 +277,8 @@ class EEGDash:
323
277
  return
324
278
 
325
279
  # Only consider fields we generally allow; skip meta operators like $and
326
- raw_keys = set(raw_query.keys()) & self._ALLOWED_QUERY_FIELDS
327
- kw_keys = set(kwargs_query.keys()) & self._ALLOWED_QUERY_FIELDS
280
+ raw_keys = set(raw_query.keys()) & ALLOWED_QUERY_FIELDS
281
+ kw_keys = set(kwargs_query.keys()) & ALLOWED_QUERY_FIELDS
328
282
  dup_keys = raw_keys & kw_keys
329
283
  for key in dup_keys:
330
284
  rc = self._extract_simple_constraint(raw_query, key)
@@ -359,44 +313,95 @@ class EEGDash:
359
313
  )
360
314
 
361
315
  def load_eeg_data_from_s3(self, s3path: str) -> xr.DataArray:
362
- """Load an EEGLAB .set file from an AWS S3 URI and return it as an xarray DataArray.
316
+ """Load EEG data from an S3 URI into an ``xarray.DataArray``.
317
+
318
+ Preserves the original filename, downloads sidecar files when applicable
319
+ (e.g., ``.fdt`` for EEGLAB, ``.vmrk``/``.eeg`` for BrainVision), and uses
320
+ MNE's direct readers.
363
321
 
364
322
  Parameters
365
323
  ----------
366
324
  s3path : str
367
- An S3 URI (should start with "s3://") for the file in question.
325
+ An S3 URI (should start with "s3://").
368
326
 
369
327
  Returns
370
328
  -------
371
329
  xr.DataArray
372
- A DataArray containing the EEG data, with dimensions "channel" and "time".
330
+ EEG data with dimensions ``("channel", "time")``.
373
331
 
374
- Example
375
- -------
376
- >>> eegdash = EEGDash()
377
- >>> mypath = "s3://openneuro.org/path/to/your/eeg_data.set"
378
- >>> mydata = eegdash.load_eeg_data_from_s3(mypath)
332
+ Raises
333
+ ------
334
+ ValueError
335
+ If the file extension is unsupported.
379
336
 
380
337
  """
381
- with tempfile.NamedTemporaryFile(delete=False, suffix=".set") as tmp:
382
- with self.filesystem.open(s3path) as s3_file:
383
- tmp.write(s3_file.read())
384
- tmp_path = tmp.name
385
- eeg_data = self.load_eeg_data_from_bids_file(tmp_path)
386
- os.unlink(tmp_path)
387
- return eeg_data
338
+ # choose a temp dir so sidecars can be colocated
339
+ with tempfile.TemporaryDirectory() as tmpdir:
340
+ # Derive local filenames from the S3 key to keep base name consistent
341
+ s3_key = urlsplit(s3path).path # e.g., "/dsXXXX/sub-.../..._eeg.set"
342
+ basename = Path(s3_key).name
343
+ ext = Path(basename).suffix.lower()
344
+ local_main = Path(tmpdir) / basename
345
+
346
+ # Download main file
347
+ with (
348
+ self.filesystem.open(s3path, mode="rb") as fsrc,
349
+ open(local_main, "wb") as fdst,
350
+ ):
351
+ fdst.write(fsrc.read())
352
+
353
+ # Determine and fetch any required sidecars
354
+ sidecars: list[str] = []
355
+ if ext == ".set": # EEGLAB
356
+ sidecars = [".fdt"]
357
+ elif ext == ".vhdr": # BrainVision
358
+ sidecars = [".vmrk", ".eeg", ".dat", ".raw"]
359
+
360
+ for sc_ext in sidecars:
361
+ sc_key = s3_key[: -len(ext)] + sc_ext
362
+ sc_uri = f"s3://{urlsplit(s3path).netloc}{sc_key}"
363
+ try:
364
+ # If sidecar exists, download next to the main file
365
+ info = self.filesystem.info(sc_uri)
366
+ if info:
367
+ sc_local = Path(tmpdir) / Path(sc_key).name
368
+ with (
369
+ self.filesystem.open(sc_uri, mode="rb") as fsrc,
370
+ open(sc_local, "wb") as fdst,
371
+ ):
372
+ fdst.write(fsrc.read())
373
+ except Exception:
374
+ # Sidecar not present; skip silently
375
+ pass
376
+
377
+ # Read using appropriate MNE reader
378
+ raw = mne.io.read_raw(str(local_main), preload=True, verbose=False)
379
+
380
+ data = raw.get_data()
381
+ fs = raw.info["sfreq"]
382
+ max_time = data.shape[1] / fs
383
+ time_steps = np.linspace(0, max_time, data.shape[1]).squeeze()
384
+ channel_names = raw.ch_names
385
+
386
+ return xr.DataArray(
387
+ data=data,
388
+ dims=["channel", "time"],
389
+ coords={"time": time_steps, "channel": channel_names},
390
+ )
388
391
 
389
392
  def load_eeg_data_from_bids_file(self, bids_file: str) -> xr.DataArray:
390
- """Load EEG data from a local file and return it as a xarray DataArray.
393
+ """Load EEG data from a local BIDS-formatted file.
391
394
 
392
395
  Parameters
393
396
  ----------
394
397
  bids_file : str
395
- Path to the BIDS-compliant file on the local filesystem.
398
+ Path to a BIDS-compliant EEG file (e.g., ``*_eeg.edf``, ``*_eeg.bdf``,
399
+ ``*_eeg.vhdr``, ``*_eeg.set``).
396
400
 
397
- Notes
398
- -----
399
- Currently, only non-epoched .set files are supported.
401
+ Returns
402
+ -------
403
+ xr.DataArray
404
+ EEG data with dimensions ``("channel", "time")``.
400
405
 
401
406
  """
402
407
  bids_path = get_bids_path_from_fname(bids_file, verbose=False)
@@ -416,140 +421,25 @@ class EEGDash:
416
421
  )
417
422
  return eeg_xarray
418
423
 
419
- def get_raw_extensions(
420
- self, bids_file: str, bids_dataset: EEGBIDSDataset
421
- ) -> list[str]:
422
- """Helper to find paths to additional "sidecar" files that may be associated
423
- with a given main data file in a BIDS dataset; paths are returned as relative to
424
- the parent dataset path.
425
-
426
- For example, if the input file is a .set file, this will return the relative path
427
- to a corresponding .fdt file (if any).
428
- """
429
- bids_file = Path(bids_file)
430
- extensions = {
431
- ".set": [".set", ".fdt"], # eeglab
432
- ".edf": [".edf"], # european
433
- ".vhdr": [".eeg", ".vhdr", ".vmrk", ".dat", ".raw"], # brainvision
434
- ".bdf": [".bdf"], # biosemi
435
- }
436
- return [
437
- str(bids_dataset.get_relative_bidspath(bids_file.with_suffix(suffix)))
438
- for suffix in extensions[bids_file.suffix]
439
- if bids_file.with_suffix(suffix).exists()
440
- ]
441
-
442
- def load_eeg_attrs_from_bids_file(
443
- self, bids_dataset: EEGBIDSDataset, bids_file: str
444
- ) -> dict[str, Any]:
445
- """Build the metadata record for a given BIDS file (single recording) in a BIDS dataset.
446
-
447
- Attributes are at least the ones defined in data_config attributes (set to None if missing),
448
- but are typically a superset, and include, among others, the paths to relevant
449
- meta-data files needed to load and interpret the file in question.
450
-
451
- Parameters
452
- ----------
453
- bids_dataset : EEGBIDSDataset
454
- The BIDS dataset object containing the file.
455
- bids_file : str
456
- The path to the BIDS file within the dataset.
457
-
458
- Returns
459
- -------
460
- dict:
461
- A dictionary representing the metadata record for the given file. This is the
462
- same format as the records stored in the database.
463
-
464
- """
465
- if bids_file not in bids_dataset.files:
466
- raise ValueError(f"{bids_file} not in {bids_dataset.dataset}")
467
-
468
- # Initialize attrs with None values for all expected fields
469
- attrs = {field: None for field in self.config["attributes"].keys()}
470
-
471
- file = Path(bids_file).name
472
- dsnumber = bids_dataset.dataset
473
- # extract openneuro path by finding the first occurrence of the dataset name in the filename and remove the path before that
474
- openneuro_path = dsnumber + bids_file.split(dsnumber)[1]
475
-
476
- # Update with actual values where available
477
- try:
478
- participants_tsv = bids_dataset.subject_participant_tsv(bids_file)
479
- except Exception as e:
480
- logger.error("Error getting participants_tsv: %s", str(e))
481
- participants_tsv = None
482
-
483
- try:
484
- eeg_json = bids_dataset.eeg_json(bids_file)
485
- except Exception as e:
486
- logger.error("Error getting eeg_json: %s", str(e))
487
- eeg_json = None
488
-
489
- bids_dependencies_files = self.config["bids_dependencies_files"]
490
- bidsdependencies = []
491
- for extension in bids_dependencies_files:
492
- try:
493
- dep_path = bids_dataset.get_bids_metadata_files(bids_file, extension)
494
- dep_path = [
495
- str(bids_dataset.get_relative_bidspath(dep)) for dep in dep_path
496
- ]
497
- bidsdependencies.extend(dep_path)
498
- except Exception:
499
- pass
500
-
501
- bidsdependencies.extend(self.get_raw_extensions(bids_file, bids_dataset))
502
-
503
- # Define field extraction functions with error handling
504
- field_extractors = {
505
- "data_name": lambda: f"{bids_dataset.dataset}_{file}",
506
- "dataset": lambda: bids_dataset.dataset,
507
- "bidspath": lambda: openneuro_path,
508
- "subject": lambda: bids_dataset.get_bids_file_attribute(
509
- "subject", bids_file
510
- ),
511
- "task": lambda: bids_dataset.get_bids_file_attribute("task", bids_file),
512
- "session": lambda: bids_dataset.get_bids_file_attribute(
513
- "session", bids_file
514
- ),
515
- "run": lambda: bids_dataset.get_bids_file_attribute("run", bids_file),
516
- "modality": lambda: bids_dataset.get_bids_file_attribute(
517
- "modality", bids_file
518
- ),
519
- "sampling_frequency": lambda: bids_dataset.get_bids_file_attribute(
520
- "sfreq", bids_file
521
- ),
522
- "nchans": lambda: bids_dataset.get_bids_file_attribute("nchans", bids_file),
523
- "ntimes": lambda: bids_dataset.get_bids_file_attribute("ntimes", bids_file),
524
- "participant_tsv": lambda: participants_tsv,
525
- "eeg_json": lambda: eeg_json,
526
- "bidsdependencies": lambda: bidsdependencies,
527
- }
528
-
529
- # Dynamically populate attrs with error handling
530
- for field, extractor in field_extractors.items():
531
- try:
532
- attrs[field] = extractor()
533
- except Exception as e:
534
- logger.error("Error extracting %s : %s", field, str(e))
535
- attrs[field] = None
536
-
537
- return attrs
538
-
539
424
  def add_bids_dataset(
540
425
  self, dataset: str, data_dir: str, overwrite: bool = True
541
426
  ) -> None:
542
- """Traverse the BIDS dataset at data_dir and add its records to the MongoDB database,
543
- under the given dataset name.
427
+ """Scan a local BIDS dataset and upsert records into MongoDB.
544
428
 
545
429
  Parameters
546
430
  ----------
547
- dataset : str)
548
- The name of the dataset to be added (e.g., "ds002718").
431
+ dataset : str
432
+ Dataset identifier (e.g., ``"ds002718"``).
549
433
  data_dir : str
550
- The path to the BIDS dataset directory.
551
- overwrite : bool
552
- Whether to overwrite/update existing records in the database.
434
+ Path to the local BIDS dataset directory.
435
+ overwrite : bool, default True
436
+ If ``True``, update existing records when encountered; otherwise,
437
+ skip records that already exist.
438
+
439
+ Raises
440
+ ------
441
+ ValueError
442
+ If called on a public client ``(is_public=True)``.
553
443
 
554
444
  """
555
445
  if self.is_public:
@@ -564,7 +454,7 @@ class EEGDash:
564
454
  dataset=dataset,
565
455
  )
566
456
  except Exception as e:
567
- logger.error("Error creating bids dataset %s: $s", dataset, str(e))
457
+ logger.error("Error creating bids dataset %s: %s", dataset, str(e))
568
458
  raise e
569
459
  requests = []
570
460
  for bids_file in bids_dataset.get_files():
@@ -573,15 +463,13 @@ class EEGDash:
573
463
 
574
464
  if self.exist({"data_name": data_id}):
575
465
  if overwrite:
576
- eeg_attrs = self.load_eeg_attrs_from_bids_file(
466
+ eeg_attrs = load_eeg_attrs_from_bids_file(
577
467
  bids_dataset, bids_file
578
468
  )
579
- requests.append(self.update_request(eeg_attrs))
469
+ requests.append(self._update_request(eeg_attrs))
580
470
  else:
581
- eeg_attrs = self.load_eeg_attrs_from_bids_file(
582
- bids_dataset, bids_file
583
- )
584
- requests.append(self.add_request(eeg_attrs))
471
+ eeg_attrs = load_eeg_attrs_from_bids_file(bids_dataset, bids_file)
472
+ requests.append(self._add_request(eeg_attrs))
585
473
  except Exception as e:
586
474
  logger.error("Error adding record %s", bids_file)
587
475
  logger.error(str(e))
@@ -597,22 +485,22 @@ class EEGDash:
597
485
  logger.info("Errors: %s ", result.bulk_api_result.get("writeErrors", []))
598
486
 
599
487
  def get(self, query: dict[str, Any]) -> list[xr.DataArray]:
600
- """Retrieve a list of EEG data arrays that match the given query. See also
601
- the `find()` method for details on the query format.
488
+ """Download and return EEG data arrays for records matching a query.
602
489
 
603
490
  Parameters
604
491
  ----------
605
492
  query : dict
606
- A dictionary that specifies the query to be executed; this is a reference
607
- document that is used to match records in the MongoDB collection.
493
+ MongoDB query used to select records.
608
494
 
609
495
  Returns
610
496
  -------
611
- A list of xarray DataArray objects containing the EEG data for each matching record.
497
+ list of xr.DataArray
498
+ EEG data for each matching record, with dimensions ``("channel", "time")``.
612
499
 
613
500
  Notes
614
501
  -----
615
- Retrieval is done in parallel, and the downloaded data are not cached locally.
502
+ Retrieval runs in parallel. Downloaded files are read and discarded
503
+ (no on-disk caching here).
616
504
 
617
505
  """
618
506
  sessions = self.find(query)
@@ -622,12 +510,40 @@ class EEGDash:
622
510
  results = Parallel(
623
511
  n_jobs=-1 if len(sessions) > 1 else 1, prefer="threads", verbose=1
624
512
  )(
625
- delayed(self.load_eeg_data_from_s3)(self.get_s3path(session))
513
+ delayed(self.load_eeg_data_from_s3)(self._get_s3path(session))
626
514
  for session in sessions
627
515
  )
628
516
  return results
629
517
 
630
- def add_request(self, record: dict):
518
+ def _get_s3path(self, record: Mapping[str, Any] | str) -> str:
519
+ """Build an S3 URI from a DB record or a relative path.
520
+
521
+ Parameters
522
+ ----------
523
+ record : dict or str
524
+ Either a DB record containing a ``'bidspath'`` key, or a relative
525
+ path string under the OpenNeuro bucket.
526
+
527
+ Returns
528
+ -------
529
+ str
530
+ Fully qualified S3 URI.
531
+
532
+ Raises
533
+ ------
534
+ ValueError
535
+ If a mapping is provided but ``'bidspath'`` is missing.
536
+
537
+ """
538
+ if isinstance(record, str):
539
+ rel = record
540
+ else:
541
+ rel = record.get("bidspath")
542
+ if not rel:
543
+ raise ValueError("Record missing 'bidspath' for S3 path resolution")
544
+ return f"s3://openneuro.org/{rel}"
545
+
546
+ def _add_request(self, record: dict):
631
547
  """Internal helper method to create a MongoDB insertion request for a record."""
632
548
  return InsertOne(record)
633
549
 
@@ -641,12 +557,19 @@ class EEGDash:
641
557
  except:
642
558
  logger.error("Error adding record: %s ", record["data_name"])
643
559
 
644
- def update_request(self, record: dict):
560
+ def _update_request(self, record: dict):
645
561
  """Internal helper method to create a MongoDB update request for a record."""
646
562
  return UpdateOne({"data_name": record["data_name"]}, {"$set": record})
647
563
 
648
564
  def update(self, record: dict):
649
- """Update a single record in the MongoDB collection."""
565
+ """Update a single record in the MongoDB collection.
566
+
567
+ Parameters
568
+ ----------
569
+ record : dict
570
+ Record content to set at the matching ``data_name``.
571
+
572
+ """
650
573
  try:
651
574
  self.__collection.update_one(
652
575
  {"data_name": record["data_name"]}, {"$set": record}
@@ -654,15 +577,33 @@ class EEGDash:
654
577
  except: # silent failure
655
578
  logger.error("Error updating record: %s", record["data_name"])
656
579
 
580
+ def exists(self, query: dict[str, Any]) -> bool:
581
+ """Alias for :meth:`exist` provided for API clarity."""
582
+ return self.exist(query)
583
+
657
584
  def remove_field(self, record, field):
658
- """Remove a specific field from a record in the MongoDB collection."""
585
+ """Remove a specific field from a record in the MongoDB collection.
586
+
587
+ Parameters
588
+ ----------
589
+ record : dict
590
+ Record identifying object with ``data_name``.
591
+ field : str
592
+ Field name to remove.
593
+
594
+ """
659
595
  self.__collection.update_one(
660
596
  {"data_name": record["data_name"]}, {"$unset": {field: 1}}
661
597
  )
662
598
 
663
599
  def remove_field_from_db(self, field):
664
- """Removed all occurrences of a specific field from all records in the MongoDB
665
- collection. WARNING: this operation is destructive and should be used with caution.
600
+ """Remove a field from all records (destructive).
601
+
602
+ Parameters
603
+ ----------
604
+ field : str
605
+ Field name to remove from every document.
606
+
666
607
  """
667
608
  self.__collection.update_many({}, {"$unset": {field: 1}})
668
609
 
@@ -672,11 +613,13 @@ class EEGDash:
672
613
  return self.__collection
673
614
 
674
615
  def close(self):
675
- """Close the MongoDB client connection.
616
+ """Backward-compatibility no-op; connections are managed globally.
617
+
618
+ Notes
619
+ -----
620
+ Connections are managed by :class:`MongoConnectionManager`. Use
621
+ :meth:`close_all_connections` to explicitly close all clients.
676
622
 
677
- Note: Since MongoDB clients are now managed by a singleton,
678
- this method no longer closes connections. Use close_all_connections()
679
- class method to close all connections if needed.
680
623
  """
681
624
  # Individual instances no longer close the shared client
682
625
  pass
@@ -687,7 +630,7 @@ class EEGDash:
687
630
  MongoConnectionManager.close_all()
688
631
 
689
632
  def __del__(self):
690
- """Ensure connection is closed when object is deleted."""
633
+ """Destructor; no explicit action needed due to global connection manager."""
691
634
  # No longer needed since we're using singleton pattern
692
635
  pass
693
636
 
@@ -707,16 +650,16 @@ class EEGDashDataset(BaseConcatDataset):
707
650
  "sex",
708
651
  ],
709
652
  s3_bucket: str | None = None,
710
- eeg_dash_instance=None,
711
653
  records: list[dict] | None = None,
712
- offline_mode: bool = False,
654
+ download: bool = True,
655
+ n_jobs: int = -1,
656
+ eeg_dash_instance: EEGDash | None = None,
713
657
  **kwargs,
714
658
  ):
715
659
  """Create a new EEGDashDataset from a given query or local BIDS dataset directory
716
660
  and dataset name. An EEGDashDataset is pooled collection of EEGDashBaseDataset
717
661
  instances (individual recordings) and is a subclass of braindecode's BaseConcatDataset.
718
662
 
719
-
720
663
  Querying Examples:
721
664
  ------------------
722
665
  # Find by single subject
@@ -732,118 +675,308 @@ class EEGDashDataset(BaseConcatDataset):
732
675
 
733
676
  Parameters
734
677
  ----------
678
+ cache_dir : str | Path
679
+ Directory where data are cached locally. If not specified, a default
680
+ cache directory under the user cache is used.
735
681
  query : dict | None
736
- A raw MongoDB query dictionary. If provided, keyword arguments for filtering are ignored.
737
- **kwargs : dict
738
- Keyword arguments for filtering (e.g., `subject="X"`, `task=["T1", "T2"]`) and/or
739
- arguments to be passed to the EEGDashBaseDataset constructor (e.g., `subject=...`).
740
- cache_dir : str
741
- A directory where the dataset will be cached locally.
742
- data_dir : str | None
743
- Optionally a string specifying a local BIDS dataset directory from which to load the EEG data files. Exactly one
744
- of query or data_dir must be provided.
745
- dataset : str | None
746
- If data_dir is given, a name for the dataset to be loaded.
682
+ Raw MongoDB query to filter records. If provided, it is merged with
683
+ keyword filtering arguments (see ``**kwargs``) using logical AND.
684
+ You must provide at least a ``dataset`` (either in ``query`` or
685
+ as a keyword argument). Only fields in ``ALLOWED_QUERY_FIELDS`` are
686
+ considered for filtering.
747
687
  description_fields : list[str]
748
- A list of fields to be extracted from the dataset records
749
- and included in the returned data description(s). Examples are typical
750
- subject metadata fields such as "subject", "session", "run", "task", etc.;
751
- see also data_config.description_fields for the default set of fields.
688
+ Fields to extract from each record and include in dataset descriptions
689
+ (e.g., "subject", "session", "run", "task").
752
690
  s3_bucket : str | None
753
- An optional S3 bucket URI (e.g., "s3://mybucket") to use instead of the
754
- default OpenNeuro bucket for loading data files
691
+ Optional S3 bucket URI (e.g., "s3://mybucket") to use instead of the
692
+ default OpenNeuro bucket when downloading data files.
755
693
  records : list[dict] | None
756
- Optional list of pre-fetched metadata records. If provided, the dataset is
757
- constructed directly from these records without querying MongoDB.
758
- offline_mode : bool
759
- If True, do not attempt to query MongoDB at all. This is useful if you want to
760
- work with a local cache only, or if you are offline.
761
- kwargs : dict
762
- Additional keyword arguments to be passed to the EEGDashBaseDataset
763
- constructor.
694
+ Pre-fetched metadata records. If provided, the dataset is constructed
695
+ directly from these records and no MongoDB query is performed.
696
+ download : bool, default True
697
+ If False, load from local BIDS files only. Local data are expected
698
+ under ``cache_dir / dataset``; no DB or S3 access is attempted.
699
+ n_jobs : int
700
+ Number of parallel jobs to use where applicable (-1 uses all cores).
701
+ eeg_dash_instance : EEGDash | None
702
+ Optional existing EEGDash client to reuse for DB queries. If None,
703
+ a new client is created on demand, not used in the case of no download.
704
+ **kwargs : dict
705
+ Additional keyword arguments serving two purposes:
706
+ - Filtering: any keys present in ``ALLOWED_QUERY_FIELDS`` are treated
707
+ as query filters (e.g., ``dataset``, ``subject``, ``task``, ...).
708
+ - Dataset options: remaining keys are forwarded to the
709
+ ``EEGDashBaseDataset`` constructor.
764
710
 
765
711
  """
766
- self.cache_dir = Path(cache_dir or platformdirs.user_cache_dir("EEGDash"))
712
+ # Parameters that don't need validation
713
+ _suppress_comp_warning: bool = kwargs.pop("_suppress_comp_warning", False)
714
+ self.s3_bucket = s3_bucket
715
+ self.records = records
716
+ self.download = download
717
+ self.n_jobs = n_jobs
718
+ self.eeg_dash_instance = eeg_dash_instance or EEGDash()
719
+
720
+ # Resolve a unified cache directory across code/tests/CI
721
+ self.cache_dir = Path(cache_dir or get_default_cache_dir())
722
+
767
723
  if not self.cache_dir.exists():
768
724
  warn(f"Cache directory does not exist, creating it: {self.cache_dir}")
769
725
  self.cache_dir.mkdir(exist_ok=True, parents=True)
770
- self.s3_bucket = s3_bucket
771
- self.eeg_dash = eeg_dash_instance
772
726
 
773
727
  # Separate query kwargs from other kwargs passed to the BaseDataset constructor
774
728
  self.query = query or {}
775
729
  self.query.update(
776
- {k: v for k, v in kwargs.items() if k in EEGDash._ALLOWED_QUERY_FIELDS}
730
+ {k: v for k, v in kwargs.items() if k in ALLOWED_QUERY_FIELDS}
777
731
  )
778
732
  base_dataset_kwargs = {k: v for k, v in kwargs.items() if k not in self.query}
779
733
  if "dataset" not in self.query:
780
- raise ValueError("You must provide a 'dataset' argument")
781
-
782
- self.data_dir = self.cache_dir / self.query["dataset"]
783
-
784
- _owns_client = False
785
- if self.eeg_dash is None and records is None:
786
- self.eeg_dash = EEGDash()
787
- _owns_client = True
734
+ # If explicit records are provided, infer dataset from records
735
+ if isinstance(records, list) and records and isinstance(records[0], dict):
736
+ inferred = records[0].get("dataset")
737
+ if inferred:
738
+ self.query["dataset"] = inferred
739
+ else:
740
+ raise ValueError("You must provide a 'dataset' argument")
741
+ else:
742
+ raise ValueError("You must provide a 'dataset' argument")
743
+
744
+ # Decide on a dataset subfolder name for cache isolation. If using
745
+ # challenge/preprocessed buckets (e.g., BDF, mini subsets), append
746
+ # informative suffixes to avoid overlapping with the original dataset.
747
+ dataset_folder = self.query["dataset"]
748
+ if self.s3_bucket:
749
+ suffixes: list[str] = []
750
+ bucket_lower = str(self.s3_bucket).lower()
751
+ if "bdf" in bucket_lower:
752
+ suffixes.append("bdf")
753
+ if "mini" in bucket_lower:
754
+ suffixes.append("mini")
755
+ if suffixes:
756
+ dataset_folder = f"{dataset_folder}-{'-'.join(suffixes)}"
757
+
758
+ self.data_dir = self.cache_dir / dataset_folder
759
+
760
+ if (
761
+ not _suppress_comp_warning
762
+ and self.query["dataset"] in RELEASE_TO_OPENNEURO_DATASET_MAP.values()
763
+ ):
764
+ warn(
765
+ "If you are not participating in the competition, you can ignore this warning!"
766
+ "\n\n"
767
+ "EEG 2025 Competition Data Notice:\n"
768
+ "---------------------------------\n"
769
+ " You are loading the dataset that is used in the EEG 2025 Competition:\n"
770
+ "IMPORTANT: The data accessed via `EEGDashDataset` is NOT identical to what you get from `EEGChallengeDataset` object directly.\n"
771
+ "and it is not what you will use for the competition. Downsampling and filtering were applied to the data"
772
+ "to allow more people to participate.\n"
773
+ "\n"
774
+ "If you are participating in the competition, always use `EEGChallengeDataset` to ensure consistency with the challenge data.\n"
775
+ "\n",
776
+ UserWarning,
777
+ module="eegdash",
778
+ )
779
+ if records is not None:
780
+ self.records = records
781
+ datasets = [
782
+ EEGDashBaseDataset(
783
+ record,
784
+ self.cache_dir,
785
+ self.s3_bucket,
786
+ **base_dataset_kwargs,
787
+ )
788
+ for record in self.records
789
+ ]
790
+ elif not download: # only assume local data is complete if not downloading
791
+ if not self.data_dir.exists():
792
+ raise ValueError(
793
+ f"Offline mode is enabled, but local data_dir {self.data_dir} does not exist."
794
+ )
795
+ records = self._find_local_bids_records(self.data_dir, self.query)
796
+ # Try to enrich from local participants.tsv to restore requested fields
797
+ try:
798
+ bids_ds = EEGBIDSDataset(
799
+ data_dir=str(self.data_dir), dataset=self.query["dataset"]
800
+ ) # type: ignore[index]
801
+ except Exception:
802
+ bids_ds = None
803
+
804
+ datasets = []
805
+ for record in records:
806
+ # Start with entity values from filename
807
+ desc: dict[str, Any] = {
808
+ k: record.get(k)
809
+ for k in ("subject", "session", "run", "task")
810
+ if record.get(k) is not None
811
+ }
812
+
813
+ if bids_ds is not None:
814
+ try:
815
+ rel_from_dataset = Path(record["bidspath"]).relative_to(
816
+ record["dataset"]
817
+ ) # type: ignore[index]
818
+ local_file = (self.data_dir / rel_from_dataset).as_posix()
819
+ part_row = bids_ds.subject_participant_tsv(local_file)
820
+ desc = merge_participants_fields(
821
+ description=desc,
822
+ participants_row=part_row
823
+ if isinstance(part_row, dict)
824
+ else None,
825
+ description_fields=description_fields,
826
+ )
827
+ except Exception:
828
+ pass
788
829
 
789
- try:
790
- if records is not None:
791
- self.records = records
792
- datasets = [
830
+ datasets.append(
793
831
  EEGDashBaseDataset(
794
- record,
795
- self.cache_dir,
796
- self.s3_bucket,
832
+ record=record,
833
+ cache_dir=self.cache_dir,
834
+ s3_bucket=self.s3_bucket,
835
+ description=desc,
797
836
  **base_dataset_kwargs,
798
837
  )
799
- for record in self.records
800
- ]
801
- elif offline_mode: # only assume local data is complete if in offline mode
802
- if self.data_dir.exists():
803
- # This path loads from a local directory and is not affected by DB query logic
804
- datasets = self.load_bids_dataset(
805
- dataset=self.query["dataset"],
806
- data_dir=self.data_dir,
807
- description_fields=description_fields,
808
- s3_bucket=s3_bucket,
809
- **base_dataset_kwargs,
810
- )
811
- else:
812
- raise ValueError(
813
- f"Offline mode is enabled, but local data_dir {self.data_dir} does not exist."
814
- )
815
- elif self.query:
816
- # This is the DB query path that we are improving
817
- datasets = self._find_datasets(
818
- query=self.eeg_dash._build_query_from_kwargs(**self.query),
819
- description_fields=description_fields,
820
- base_dataset_kwargs=base_dataset_kwargs,
821
- )
822
- # We only need filesystem if we need to access S3
823
- self.filesystem = S3FileSystem(
824
- anon=True, client_kwargs={"region_name": "us-east-2"}
825
- )
826
- else:
827
- raise ValueError(
828
- "You must provide either 'records', a 'data_dir', or a query/keyword arguments for filtering."
829
838
  )
830
- finally:
831
- if _owns_client and self.eeg_dash is not None:
832
- self.eeg_dash.close()
839
+ elif self.query:
840
+ # This is the DB query path that we are improving
841
+ datasets = self._find_datasets(
842
+ query=build_query_from_kwargs(**self.query),
843
+ description_fields=description_fields,
844
+ base_dataset_kwargs=base_dataset_kwargs,
845
+ )
846
+ # We only need filesystem if we need to access S3
847
+ self.filesystem = S3FileSystem(
848
+ anon=True, client_kwargs={"region_name": "us-east-2"}
849
+ )
850
+ else:
851
+ raise ValueError(
852
+ "You must provide either 'records', a 'data_dir', or a query/keyword arguments for filtering."
853
+ )
833
854
 
834
855
  super().__init__(datasets)
835
856
 
836
- def find_key_in_nested_dict(self, data: Any, target_key: str) -> Any:
837
- """Helper to recursively search for a key in a nested dictionary structure; returns
838
- the value associated with the first occurrence of the key, or None if not found.
857
+ def _find_local_bids_records(
858
+ self, dataset_root: Path, filters: dict[str, Any]
859
+ ) -> list[dict]:
860
+ """Discover local BIDS EEG files and build minimal records.
861
+
862
+ This helper enumerates EEG recordings under ``dataset_root`` via
863
+ ``mne_bids.find_matching_paths`` and applies entity filters to produce a
864
+ list of records suitable for ``EEGDashBaseDataset``. No network access
865
+ is performed and files are not read.
866
+
867
+ Parameters
868
+ ----------
869
+ dataset_root : Path
870
+ Local dataset directory. May be the plain dataset folder (e.g.,
871
+ ``ds005509``) or a suffixed cache variant (e.g.,
872
+ ``ds005509-bdf-mini``).
873
+ filters : dict of {str, Any}
874
+ Query filters. Must include ``'dataset'`` with the dataset id (without
875
+ local suffixes). May include BIDS entities ``'subject'``,
876
+ ``'session'``, ``'task'``, and ``'run'``. Each value can be a scalar
877
+ or a sequence of scalars.
878
+
879
+ Returns
880
+ -------
881
+ records : list of dict
882
+ One record per matched EEG file with at least:
883
+
884
+ - ``'data_name'``
885
+ - ``'dataset'`` (dataset id, without suffixes)
886
+ - ``'bidspath'`` (normalized to start with the dataset id)
887
+ - ``'subject'``, ``'session'``, ``'task'``, ``'run'`` (may be None)
888
+ - ``'bidsdependencies'`` (empty list)
889
+ - ``'modality'`` (``"eeg"``)
890
+ - ``'sampling_frequency'``, ``'nchans'``, ``'ntimes'`` (minimal
891
+ defaults for offline usage)
892
+
893
+ Notes
894
+ -----
895
+ - Matching uses ``datatypes=['eeg']`` and ``suffixes=['eeg']``.
896
+ - ``bidspath`` is constructed as
897
+ ``<dataset_id> / <relative_path_from_dataset_root>`` to ensure the
898
+ first path component is the dataset id (without local cache suffixes).
899
+ - Minimal defaults are set for ``sampling_frequency``, ``nchans``, and
900
+ ``ntimes`` to satisfy dataset length requirements offline.
901
+
839
902
  """
903
+ dataset_id = filters["dataset"]
904
+ arg_map = {
905
+ "subjects": "subject",
906
+ "sessions": "session",
907
+ "tasks": "task",
908
+ "runs": "run",
909
+ }
910
+ matching_args: dict[str, list[str]] = {}
911
+ for finder_key, entity_key in arg_map.items():
912
+ entity_val = filters.get(entity_key)
913
+ if entity_val is None:
914
+ continue
915
+ if isinstance(entity_val, (list, tuple, set)):
916
+ entity_vals = list(entity_val)
917
+ if not entity_vals:
918
+ continue
919
+ matching_args[finder_key] = entity_vals
920
+ else:
921
+ matching_args[finder_key] = [entity_val]
922
+
923
+ matched_paths = find_matching_paths(
924
+ root=str(dataset_root),
925
+ datatypes=["eeg"],
926
+ suffixes=["eeg"],
927
+ ignore_json=True,
928
+ **matching_args,
929
+ )
930
+ records_out: list[dict] = []
931
+
932
+ for bids_path in matched_paths:
933
+ # Build bidspath as dataset_id / relative_path_from_dataset_root (POSIX)
934
+ rel_from_root = (
935
+ Path(bids_path.fpath)
936
+ .resolve()
937
+ .relative_to(Path(bids_path.root).resolve())
938
+ )
939
+ bidspath = f"{dataset_id}/{rel_from_root.as_posix()}"
940
+
941
+ rec = {
942
+ "data_name": f"{dataset_id}_{Path(bids_path.fpath).name}",
943
+ "dataset": dataset_id,
944
+ "bidspath": bidspath,
945
+ "subject": (bids_path.subject or None),
946
+ "session": (bids_path.session or None),
947
+ "task": (bids_path.task or None),
948
+ "run": (bids_path.run or None),
949
+ # minimal fields to satisfy BaseDataset from eegdash
950
+ "bidsdependencies": [], # not needed to just run.
951
+ "modality": "eeg",
952
+ # minimal numeric defaults for offline length calculation
953
+ "sampling_frequency": None,
954
+ "nchans": None,
955
+ "ntimes": None,
956
+ }
957
+ records_out.append(rec)
958
+
959
+ return records_out
960
+
961
+ def _find_key_in_nested_dict(self, data: Any, target_key: str) -> Any:
962
+ """Recursively search for target_key in nested dicts/lists with normalized matching.
963
+
964
+ This makes lookups tolerant to naming differences like "p-factor" vs "p_factor".
965
+ Returns the first match or None.
966
+ """
967
+ norm_target = normalize_key(target_key)
840
968
  if isinstance(data, dict):
841
- if target_key in data:
842
- return data[target_key]
843
- for value in data.values():
844
- result = self.find_key_in_nested_dict(value, target_key)
845
- if result is not None:
846
- return result
969
+ for k, v in data.items():
970
+ if normalize_key(k) == norm_target:
971
+ return v
972
+ res = self._find_key_in_nested_dict(v, target_key)
973
+ if res is not None:
974
+ return res
975
+ elif isinstance(data, list):
976
+ for item in data:
977
+ res = self._find_key_in_nested_dict(item, target_key)
978
+ if res is not None:
979
+ return res
847
980
  return None
848
981
 
849
982
  def _find_datasets(
@@ -872,15 +1005,23 @@ class EEGDashDataset(BaseConcatDataset):
872
1005
 
873
1006
  """
874
1007
  datasets: list[EEGDashBaseDataset] = []
875
-
876
- self.records = self.eeg_dash.find(query)
1008
+ self.records = self.eeg_dash_instance.find(query)
877
1009
 
878
1010
  for record in self.records:
879
- description = {}
1011
+ description: dict[str, Any] = {}
1012
+ # Requested fields first (normalized matching)
880
1013
  for field in description_fields:
881
- value = self.find_key_in_nested_dict(record, field)
1014
+ value = self._find_key_in_nested_dict(record, field)
882
1015
  if value is not None:
883
1016
  description[field] = value
1017
+ # Merge all participants.tsv columns generically
1018
+ part = self._find_key_in_nested_dict(record, "participant_tsv")
1019
+ if isinstance(part, dict):
1020
+ description = merge_participants_fields(
1021
+ description=description,
1022
+ participants_row=part,
1023
+ description_fields=description_fields,
1024
+ )
884
1025
  datasets.append(
885
1026
  EEGDashBaseDataset(
886
1027
  record,
@@ -891,64 +1032,3 @@ class EEGDashDataset(BaseConcatDataset):
891
1032
  )
892
1033
  )
893
1034
  return datasets
894
-
895
- def load_bids_dataset(
896
- self,
897
- dataset: str,
898
- data_dir: str | Path,
899
- description_fields: list[str],
900
- s3_bucket: str | None = None,
901
- **kwargs,
902
- ):
903
- """Helper method to load a single local BIDS dataset and return it as a list of
904
- EEGDashBaseDatasets (one for each recording in the dataset).
905
-
906
- Parameters
907
- ----------
908
- dataset : str
909
- A name for the dataset to be loaded (e.g., "ds002718").
910
- data_dir : str
911
- The path to the local BIDS dataset directory.
912
- description_fields : list[str]
913
- A list of fields to be extracted from the dataset records
914
- and included in the returned dataset description(s).
915
-
916
- """
917
- bids_dataset = EEGBIDSDataset(
918
- data_dir=data_dir,
919
- dataset=dataset,
920
- )
921
- datasets = Parallel(n_jobs=-1, prefer="threads", verbose=1)(
922
- delayed(self.get_base_dataset_from_bids_file)(
923
- bids_dataset=bids_dataset,
924
- bids_file=bids_file,
925
- s3_bucket=s3_bucket,
926
- description_fields=description_fields,
927
- **kwargs,
928
- )
929
- for bids_file in bids_dataset.get_files()
930
- )
931
- return datasets
932
-
933
- def get_base_dataset_from_bids_file(
934
- self,
935
- bids_dataset: "EEGBIDSDataset",
936
- bids_file: str,
937
- s3_bucket: str | None,
938
- description_fields: list[str],
939
- **kwargs,
940
- ) -> "EEGDashBaseDataset":
941
- """Instantiate a single EEGDashBaseDataset given a local BIDS file (metadata only)."""
942
- record = self.eeg_dash.load_eeg_attrs_from_bids_file(bids_dataset, bids_file)
943
- description = {}
944
- for field in description_fields:
945
- value = self.find_key_in_nested_dict(record, field)
946
- if value is not None:
947
- description[field] = value
948
- return EEGDashBaseDataset(
949
- record,
950
- self.cache_dir,
951
- s3_bucket,
952
- description=description,
953
- **kwargs,
954
- )