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