### is_stim_channel_in_raw example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Placeholder example for is_stim_channel_in_raw. ```pycon >>> # is_stim_channel_in_raw(raw, 0) ``` -------------------------------- ### batch_process usage examples Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/modules/batch/eeg_batch.html Examples from the batch_process docstring showing how to call the method with different result_type values. ```python >>> from eegunity import UnifiedDataset >>> u_ds = UnifiedDataset(***) >>> # example1 >>> new_locator = u_ds.eeg_batch.batch_process(app_func, con_func, is_patch=True, result_type='series') >>> print(new_locator) >>> # example2 >>> a_list = u_ds.eeg_batch.batch_process(app_func, con_func, is_patch=True, result_type='value') >>> print(a_list) >>> # example3 >>> u_ds.eeg_batch.batch_process(app_func, con_func, is_patch=True, result_type=None) ``` -------------------------------- ### set_metadata usage example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/modules/batch/eeg_batch.html Example from the set_metadata docstring showing how to set a metadata column. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.set_metadata('Sampling Rate', [250, 250, 250]) ``` -------------------------------- ### get_file_sizes usage example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.batch.rst Example of calling get_file_sizes and displaying the resulting locator columns. ```pycon >>> from eegunity import UnifiedDataset >>> u_ds = UnifiedDataset(dataset_path="/path/to/dataset") >>> u_ds.eeg_batch.get_file_sizes() >>> locator = u_ds.get_locator() >>> print(locator[["File Path", "File Size"]].head()) ``` -------------------------------- ### is_misc_channel_in_raw example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Placeholder example for is_misc_channel_in_raw. ```pycon >>> # is_misc_channel_in_raw(raw, 0) ``` -------------------------------- ### misc_channel_indices example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Placeholder example for misc_channel_indices. ```pycon >>> # idx = misc_channel_indices(raw) ``` -------------------------------- ### llm_description_file_parser usage example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.llm_booster.html Example usage of the llm_description_file_parser function. It requires a directory path, client parameters (e.g., api_key and api_version), and a client type (e.g., 'AzureOpenAI'). The result is printed as JSON. ```python >>> directory = 'path/to/description/directory' >>> client_paras = {"api_key": "your_api_key", "api_version": "2023-03-15-preview"} >>> client_type = "AzureOpenAI" >>> result = llm_description_file_parser(directory, client_paras, client_type) >>> print("The end result:", json.dumps(result, indent=4, ensure_ascii=False)) ``` -------------------------------- ### Example: stim_channel_indices Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Shows a commented-out example of calling stim_channel_indices on a raw object. The code is incomplete and commented out. ```pycon >>> # idx = stim_channel_indices(raw) ``` -------------------------------- ### Apply dataset kernel example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Shows a commented-out call to apply_dataset_kernel with a unified dataset, raw object, and row. The actual code is not executed in the example. ```pycon >>> # raw = apply_dataset_kernel(unified_dataset, raw, row) ``` -------------------------------- ### channel_name_parser examples Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Demonstrates formatting channel names using the channel_name_parser function. The first example shows heuristic classification of untyped names, while the second shows preservation of explicit typed input. ```pycon >>> channel_name_parser("Fz, Cz, Pz") 'eeg:Fz, eeg:Cz, eeg:Pz' >>> channel_name_parser("seeg:LA1, seeg:LA2") 'seeg:LA1, seeg:LA2' ``` -------------------------------- ### get_file_hashes usage examples Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.batch.rst Examples of calling get_file_hashes in file mode (default) and data-stream mode. ```pycon >>> u_ds.eeg_batch.get_file_hashes() # file hash >>> u_ds.eeg_batch.get_file_hashes(data_stream=True) # signal hash ``` -------------------------------- ### process_mne_files example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Processes MNE files based on a locator DataFrame. The example shows calling with verbose='CRITICAL' and num_workers=0. ```pycon >>> process_mne_files(locator_df, verbose="CRITICAL", num_workers=0) ``` -------------------------------- ### Install EEGUnity with pip Source: https://github.com/baizhige/eegunity/blob/main/README.md Use this command to install the EEGUnity package. Requires Python 3.6 or higher; Python 3.13 is not supported. ```bash pip install eegunity ``` -------------------------------- ### save_as_other Example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Saves the dataset to a new location with specified domain tag, format, and overwrite option. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> new_locator = unified_dataset.eeg_batch.save_as_other('/path/to/output', domain_tag='example', format='fif', overwrite=False) ``` -------------------------------- ### HeaderlessCSVKernel example implementing extended interface Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Reading Rich Meta Data via Kernel.md Full example kernel that opts in to handle Unavailable files by setting HANDLES_UNAVAILABLE = True. It implements load() to build an mne.io.RawArray from a headerless CSV and apply() to inject metadata. Returns None from load() to skip non-CSV files. ```python from __future__ import annotations import json from dataclasses import dataclass import mne import numpy as np import pandas as pd _SFREQ = 2048.0 _CH_NAMES = ["EEG1", "EEG2"] @dataclass class HeaderlessCSVKernel: KERNEL_ID: str = "headerless-csv-v1" HANDLES_UNAVAILABLE: bool = True # opt in def load(self, row) -> mne.io.BaseRaw | None: """Build a RawArray from a headerless CSV file.""" file_path = row["File Path"] if not file_path.endswith(".csv"): return None # skip non-CSV files silently # Read EEG columns (0-indexed: columns 1 and 2) df = pd.read_csv(file_path, header=None, usecols=[1, 2]) eeg = df.to_numpy(dtype=float).T # (n_ch, n_samples) info = mne.create_info(_CH_NAMES, sfreq=_SFREQ, ch_types=["eeg", "eeg"]) return mne.io.RawArray(eeg, info, verbose=False) def apply(self, udataset, raw: mne.io.BaseRaw, row) -> mne.io.BaseRaw: """Inject metadata and annotations into the loaded raw.""" raw.info["description"] = json.dumps({ "eegunity_description": { "amplifier": "unknown", "cap": "unknown", "age": "unknown", "sex": "unknown", "handedness": "unknown", } }) # … add annotations here … return raw KERNEL = HeaderlessCSVKernel() ``` -------------------------------- ### Practical example: parallel export to HDF5 Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Speep Up with Multithread.md.txt This example creates a UnifiedDataset with num_workers=8 and calls export_h5Dataset to export to HDF5 in parallel. It parses dataset files in parallel, processes each locator row concurrently, and safely writes results in correct order. ```python from eegunity import UnifiedDataset u_dataset = UnifiedDataset( dataset_path="your_dataset_root", domain_tag="your_domain_tag", num_workers=8 ) # Export to HDF5 in parallel u_dataset.eeg_batch.export_h5Dataset("output_path") ``` -------------------------------- ### handle_nonstandard_data example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Loads non-standard EEG files (e.g., MATLAB .mat, HDF5 EEGLAB .set, CSV/TXT, WFDB .hea, EDF .rec) and returns an mne.io.Raw object. The example shows calling with preload=False. ```pycon >>> raw = handle_nonstandard_data(locator_row, preload=False) ``` -------------------------------- ### Set channel type example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Shows a commented-out call to set_channel_type with a raw object and a channel string. The actual code is not executed in the example. ```pycon >>> # raw = set_channel_type(raw, "eeg:Fz, stim:event_code") ``` -------------------------------- ### Example usage of llm_boost_parser Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.llm_booster.html Shows how to call llm_boost_parser with an API key, Azure endpoint, and file path. The function returns an MNE RawArray object. ```python >>> api_key = "your_api_key" >>> azure_endpoint = "https://your_endpoint" >>> locator_path = "data_file.csv" >>> raw_data = llm_boost_parser(locator_path, api_key, azure_endpoint) >>> print("Extracted Data:", raw_data) ``` -------------------------------- ### Normalize method example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/modules/batch/eeg_batch.html Example usage of the normalize method from the eeg_batch module. It creates a UnifiedDataset and calls normalize with norm_type='channel-wise' and domain_mean=True. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.normalize('/path/to/save/', norm_type='channel-wise', domain_mean=True) ``` -------------------------------- ### Resample batch processing example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/modules/batch/eeg_batch.html Example usage of the resample method from the eeg_batch module. It creates a UnifiedDataset and resamples data with specified parameters. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.resample('/path/to/save/', resample_params={'sfreq': 256}) ``` -------------------------------- ### is_misc_channel examples Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Shows the expected return values for is_misc_channel with a misc channel and an EEG channel. ```pycon >>> is_misc_channel('misc:reaction_time') True >>> is_misc_channel('eeg:Fz') False ``` -------------------------------- ### process_brainvision_files example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Retries failed BrainVision .vhdr files by patching internal sidecar paths. The example shows calling with num_workers=2. ```pycon >>> process_brainvision_files(locator_df, "CRITICAL", num_workers=2) ``` -------------------------------- ### EEGBatch.get_quality() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to get quality information. ```APIDOC ## EEGBatch.get_quality() ### Description Method to get quality information. ### Method get_quality ### Endpoint EEGBatch.get_quality ``` -------------------------------- ### Example: resample_raw_with_labels Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Shows a basic usage of resample_raw_with_labels to resample a raw object to 256 Hz. The function preserves misc channel values via nearest-neighbor interpolation. ```pycon >>> raw = resample_raw_with_labels(raw, sfreq=256) ``` -------------------------------- ### extract_events examples Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Extracts events from annotations and/or stim channels. The first example uses the default 'auto' source; the second uses 'stim' with a specific stim channel. ```pycon >>> events, event_id = extract_events(raw, event_source='auto') ``` ```pycon >>> events, event_id = extract_events(raw, event_source='stim', stim_channel=['TRIG']) ``` -------------------------------- ### Import UnifiedDataset from EEGUnity Source: https://github.com/baizhige/eegunity/blob/main/README.md Import the UnifiedDataset class to start using EEGUnity in your Python project. ```python from eegunity import UnifiedDataset ``` -------------------------------- ### EEGBatch.get_file_hashes() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to get file hashes. ```APIDOC ## EEGBatch.get_file_hashes() ### Description Method to get file hashes. ### Method get_file_hashes ### Endpoint EEGBatch.get_file_hashes ``` -------------------------------- ### EEGBatch.get_events() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to get events from the batch. ```APIDOC ## EEGBatch.get_events() ### Description Method to get events from the batch. ### Method get_events ### Endpoint EEGBatch.get_events ``` -------------------------------- ### epoch_for_pretraining usage example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Demonstrates calling epoch_for_pretraining with output path, segment length of 2.0 seconds, and resampling to 256 Hz. The method processes raw EEG data and saves epochs in .npy format. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.epoch_for_pretraining('/path/to/save/', seg_sec=2.0, resample=256) ``` -------------------------------- ### Filter EEG data by completeness using eeg_batch.sample_filter Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Shows how to use the sample_filter method to filter the 'locator' dataframe. The example filters for records with a completeness check of 'Completed'. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.sample_filter(completeness_check='Completed') ``` -------------------------------- ### Process mean and std with eeg_batch.process_mean_std Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Example usage of the process_mean_std method. It creates a UnifiedDataset and calls eeg_batch.process_mean_std with domain_mean=True. The method updates the 'MEAN STD' column and raises ValueError for inconsistent channel names or numbers when domain_mean is True. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.process_mean_std(domain_mean=True) ``` -------------------------------- ### Align channels with EEGBatch.align_channel Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Example usage of the align_channel method to adjust channel order and interpolate data. Requires a UnifiedDataset instance and a valid output path. The channel_order list specifies the desired channel order, and min_num_channels sets the minimum required channels. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.align_channel('/path/to/save/', channel_order=['C3', 'C4', 'O1'], min_num_channels=3) ``` -------------------------------- ### Format channel names with format_channel_names Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Example usage of the format_channel_names method on a UnifiedDataset instance. The dataset must be properly loaded and contain a 'Channel Names' column before calling this method. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.format_channel_names() ``` -------------------------------- ### Step 1: Build Initial Locator Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Make Standard Datasets.md Creates a UnifiedDataset, filters samples with completeness check 'Completed', formats channel names, and saves the locator CSV. ```python import os from eegunity import UnifiedDataset INPUT_PATH = r"path/to/original_dataset" DOMAIN_TAG = "my_dataset" LOCATOR_PATH = r"./locator/my_dataset.csv" os.makedirs(os.path.dirname(LOCATOR_PATH), exist_ok=True) ud = UnifiedDataset(dataset_path=INPUT_PATH, domain_tag=DOMAIN_TAG) ud.eeg_batch.sample_filter(completeness_check="Completed") ud.eeg_batch.format_channel_names() ud.save_locator(LOCATOR_PATH) ``` -------------------------------- ### Define ExampleKernel with add_channel helper and apply method Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Reading Rich Meta Data via Kernel.md This snippet defines an ExampleKernel class that adds multiple misc and stim channels to an MNE Raw object. It includes a helper function add_channel that validates the values array and appends a channel with a specified MNE channel type. The apply method creates continuous misc channels (prob_density, reaction_time), integer-coded stim channels (task_code, stage_code), and annotation segments, then returns the modified raw object. The kernel is instantiated as KERNEL. ```python from __future__ import annotations from dataclasses import dataclass import numpy as np import mne def add_channel(raw: mne.io.BaseRaw, ch_name: str, ch_type: str, values: np.ndarray) -> mne.io.BaseRaw: """Append one channel to raw with explicit MNE channel type.""" if values.ndim != 1: raise ValueError("values must be a 1D array") if values.shape[0] != raw.n_times: raise ValueError("values length must equal raw.n_times") info = mne.create_info([ch_name], sfreq=raw.info["sfreq"], ch_types=[ch_type]) ch_raw = mne.io.RawArray(values[np.newaxis, :], info, verbose=False) raw.add_channels([ch_raw], force_update_info=True) return raw @dataclass class ExampleKernel: KERNEL_ID: str = "example_rich_meta" def apply(self, udataset, raw: mne.io.BaseRaw, row): n = raw.n_times # misc channels (continuous signals) prob_density = np.linspace(0.1, 0.9, n, dtype=float) reaction_time = np.full(n, 0.42, dtype=float) raw = add_channel(raw, "prob_density", "misc", prob_density) raw = add_channel(raw, "reaction_time", "misc", reaction_time) # stim channels (integer codes) task_code = np.zeros(n, dtype=float) task_code[n // 4: n // 2] = 1 task_code[n // 2: 3 * n // 4] = 2 task_code[3 * n // 4:] = 3 stage_code = np.zeros(n, dtype=float) stage_code[n // 3: 2 * n // 3] = 7 raw = add_channel(raw, "task_code", "stim", task_code) raw = add_channel(raw, "stage_code", "stim", stage_code) # annotation segments (text semantics) ann = mne.Annotations( onset=[0.0, raw.times[n // 2]], duration=[2.0, 2.0], description=["trial_start", "feedback"], ) raw.set_annotations(ann) return raw KERNEL = ExampleKernel() ``` -------------------------------- ### Parameter settings for standard script Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Make Standard Datasets.md.txt Define input/output paths, domain tag, and cache usage. Avoid absolute paths; only specify basic parameters. ```python # Parameter settings import os import setting.path_variable as pv # this is additional python file which stores all path variable input_path = pv.bcic_iv_2a_path # Dataset directory domain_tag = 'bcic-iv-2a' # Domain tag for marking the dataset output_path = os.path.join(pv.stage1_output_dir, 'bcic_iv_2a') # Output path use_cache = False ``` -------------------------------- ### Recommended Project Layout Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Make Standard Datasets.md Shows the recommended directory structure for a standard script project, including locator, output_fif, and make_fif_xxxx.py. ```text standard_script_project/ |-- locator/ |-- output_fif/ |-- make_fif_xxxx.py ``` -------------------------------- ### Pipeline.__init__(functions) Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/utils/pipeline.html Initializes the pipeline with a list of functions to apply sequentially to the input. ```APIDOC ## Pipeline.__init__(functions) ### Description Initialize the pipeline with a list of functions. ### Method Constructor ### Parameters - **functions** (list of callable) - Required - Functions to apply sequentially to the input. ### Example ```python >>> functions = [ ... lambda raw: bandpass_filter(raw, 0.1, 75), ... lambda raw: notch_filter(raw, freqs=50), ... lambda raw: resample(raw, sfreq=200) ... ] >>> pipeline = Pipeline(functions) ``` ``` -------------------------------- ### UnifiedDataset.__init__ Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/unifieddataset.html Initializes a UnifiedDataset instance with either a dataset path or a locator path. Only one of these parameters should be provided, and if dataset_path is provided, domain_tag is required. ```APIDOC ## UnifiedDataset.__init__ ### Description Initializes a UnifiedDataset instance with either a dataset path or a locator path. Only one of these parameters should be provided, and if dataset_path is provided, domain_tag is required. ### Method Constructor ### Signature ```python UnifiedDataset(dataset_path: str = None, locator_path: str = None, domain_tag: str = None, is_unzip: bool = True, verbose: str = 'CRITICAL', num_workers: int = 0, kernel_spec: str = None) ``` ### Parameters - **dataset_path** (str, optional) - Path to the dataset (folder). Do not provide if using locator_path. - **locator_path** (str, optional) - File path to the locator (CSV-like file) that stores all metadata for the UnifiedDataset. Do not provide if using dataset_path. - **domain_tag** (str, optional) - The domain tag identifies the dataset name. Required if dataset_path is provided. Do not provide if using locator_path. - **is_unzip** (bool, optional) - Flag indicating whether the dataset should be unzipped (default is True). - **verbose** (str, optional) - Verbosity level for logging (default is 'CRITICAL'). - **num_workers** (int, optional) - Number of worker threads for parallel processing (default is 0). 0 means sequential execution in the main thread; >0 uses a ThreadPoolExecutor with the specified number of workers. - **kernel_spec** (str, optional) - Kernel specification. ### Raises - **ValueError** - If both dataset_path and locator_path are provided, or neither is provided. ### Examples ```python >>> unified_dataset = UnifiedDataset("path/to/your/dataset") >>> unified_dataset_locator = UnifiedDataset(locator_path="path/to/your/locator.csv") ``` ``` -------------------------------- ### ICA batch processing example Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/modules/batch/eeg_batch.html Example usage of the ica method from the eeg_batch module. It creates a UnifiedDataset and applies ICA with specified parameters. ```python >>> from eegunity import UnifiedDataset >>> unified_dataset = UnifiedDataset(***) >>> unified_dataset.eeg_batch.ica('/path/to/save/', ica_params={'n_components': 20}, fit_params={'picks': 'eeg'}) ``` -------------------------------- ### Build Locator with Parser Extensions Enabled Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Parse Non-standard Data Formats.md Creates a UnifiedDataset with parser extensions enabled and prints the locator's first rows and file type counts. Set min_file_size to 0 to include small CSV/TXT files. ```python from eegunity import UnifiedDataset ud = UnifiedDataset( dataset_path=r"path/to/dataset", domain_tag="my_dataset", num_workers=8, min_file_size=0, # include small CSV/TXT files ) locator = ud.get_locator() print(locator[["File Path", "File Type", "Completeness Check"]].head()) print(locator["File Type"].value_counts(dropna=False)) ``` -------------------------------- ### parallel_execute example usage Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Example of calling parallel_execute with a lambda function, thread mode, and two workers. The tasks list contains tuples with index, row, and should_apply flag. The output is not shown in the source. ```pycon >>> tasks = [(0, {'x': 1}, True), (1, {'x': 2}, False)] >>> parallel_execute( ... tasks=tasks, ... app_func=lambda row: row['x'] * 2, ... is_patch=False, ... result_type='value', ... execution_mode='thread', ... num_workers=2, ... ) ``` -------------------------------- ### UnifiedDataset.__init__ Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/unifieddataset.html Initializes a UnifiedDataset instance. Validates that only one of dataset_path or locator_path is provided, sets shared attributes, and initializes associated modules. ```APIDOC ## UnifiedDataset.__init__ ### Description Initializes a UnifiedDataset instance. Validates that only one of dataset_path or locator_path is provided, sets shared attributes, and initializes associated modules. ### Parameters - **dataset_path** (str) - Optional - Path to the dataset. - **locator_path** (str) - Optional - Path to the locator file. - **is_unzip** (bool) - Optional - Whether to unzip the dataset. - **domain_tag** (str) - Optional - Domain tag for the dataset. Defaults to "not_specified" if dataset_path is provided. - **verbose** (bool) - Optional - Verbosity flag. - **num_workers** (int) - Optional - Number of workers. - **kernel_spec** (str) - Optional - Kernel specification string. ### Raises - **ValueError** - If both dataset_path and locator_path are provided, or if neither is provided. ### Example ```python ud = UnifiedDataset(dataset_path="path/to/data", domain_tag="eeg") ``` ``` -------------------------------- ### Upload to PyPI with twine Source: https://github.com/baizhige/eegunity/blob/main/HARNESS.md Uploads the built distribution to PyPI. Sets PYTHONUTF8 and uses --disable-progress-bar to avoid a GBK encoding crash on Windows. ```powershell $env:PYTHONUTF8 = "1" & "C:\Users\Cheng\anaconda3\envs\eegunity_release\python.exe" -m twine upload --disable-progress-bar dist/* ``` -------------------------------- ### EEGParser.get_data() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to get data from the parser. ```APIDOC ## EEGParser.get_data() ### Description Method to get data from the parser. ### Method get_data ### Endpoint EEGParser.get_data ``` -------------------------------- ### Binding a kernel to a UnifiedDataset Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Reading Rich Meta Data via Kernel.md.txt Shows how to instantiate a UnifiedDataset with a kernel_spec and retrieve data, triggering the kernel's apply method at read time. ```python from eegunity import UnifiedDataset ud = UnifiedDataset( dataset_path="/data/openneuro/ds005505", domain_tag="openneuro_ds005505", kernel_spec="/abs/path/openneuro_ds005505_kernel" ) raw = ud.eeg_parser.get_data(0) ``` -------------------------------- ### Run packaging integrity check Source: https://github.com/baizhige/eegunity/blob/main/HARNESS.md Executes the pre-release check script to verify package structure and wheel contents. Do not upload if this script reports any errors. ```powershell & "C:\Users\Cheng\anaconda3\envs\eegunity_release\python.exe" CI/pre_release_check.py ``` -------------------------------- ### Normalize MNE raw data example Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Example usage of normalize_mne: reads a FIF file, normalizes it, and prints the data. The function normalizes each non-misc/non-stim channel to zero mean and unit variance, and raises ValueError if a signal channel contains NaN or infinite values. ```pycon >>> raw = mne.io.read_raw_fif('sample_data.fif') >>> raw_normalized = normalize_mne(raw) >>> print(raw_normalized.get_data()) ``` -------------------------------- ### auto_domain Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.batch.rst Automatically determines the domain of the EEG dataset. Example usage is provided. ```APIDOC ## auto_domain ### Description Automatically determines the domain of the EEG dataset. ### Method N/A (SDK method) ### Parameters No parameters documented. ### Request Example ```pycon >>> unified_dataset.eeg_batch.auto_domain(get_data_row_params={'preload': True}) ``` ### Response No response documented. ``` -------------------------------- ### Load dataset with UnifiedDataset Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Format Channel Name and Inspect Metadata.md.txt Creates a UnifiedDataset instance by specifying the dataset path and a custom domain tag. This is the first step to access the dataset. ```python from eegunity import UnifiedDataset input_path = r'path/to/dataset' # Specify the directory containing your dataset unified_dataset = UnifiedDataset(dataset_path=input_path, domain_tag="my_dataset") ``` -------------------------------- ### Recommended Workflow: Load, Filter, and Format Channel Names Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How does EEGUnity support multi-modal data.md Loads dataset metadata with UnifiedDataset, filters to completed records, and formats channel names into : format. This is the first step before applying modality-specific processing. ```python from eegunity import UnifiedDataset ud = UnifiedDataset(dataset_path="path/to/dataset", domain_tag="my_dataset") ud.eeg_batch.sample_filter(completeness_check="Completed") ud.eeg_batch.format_channel_names() ``` -------------------------------- ### Pipeline.forward() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to run the pipeline forward. ```APIDOC ## Pipeline.forward() ### Description Method to run the pipeline forward. ### Method forward ### Endpoint Pipeline.forward ``` -------------------------------- ### Load dataset with UnifiedDataset and cache locator Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Make Standard Datasets.md.txt Load dataset using UnifiedDataset. If locator exists and cache enabled, reuse it; otherwise create new locator and save. ```python locator_path = os.path.join(pv.stage1_locator, os.path.basename(input_path)+".csv") if os.path.exists(locator_path) and use_cache: unified_dataset = UnifiedDataset(locator_path=locator_path) else: unified_dataset = UnifiedDataset(dataset_path=input_path, domain_tag=domain_tag) unified_dataset.save_locator(locator_path) ``` -------------------------------- ### Example: misc_task_name Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Demonstrates extracting the task name from a misc channel name using misc_task_name. The input 'misc:reaction_time' returns 'reaction_time'. ```pycon >>> misc_task_name('misc:reaction_time') 'reaction_time' ``` -------------------------------- ### is_misc_channel(ch_name) Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Predicate for identifying EEGUnity misc (label) channels. Returns True if the channel name starts with the 'misc:' prefix (case-sensitive). ```APIDOC ## is_misc_channel(ch_name) ### Description Return True if ch_name is an EEGUnity misc (label) channel. The check is case-sensitive and matches the 'misc:' prefix exactly. ### Parameters - **ch_name** (str) - Required - Channel name to test. ### Returns - **bool** - True when ch_name starts with 'misc:', False otherwise. ### Examples ```pycon >>> is_misc_channel('misc:reaction_time') True >>> is_misc_channel('eeg:Fz') False ``` ``` -------------------------------- ### split_hdf5_file(input_path, max_file_size=10 * 1024**3, output_dir=".") Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_modules/eegunity/utils/split_hdf5_file.html Splits an HDF5 file into multiple parts if its total size exceeds the given limit. The minimal splitting unit is a top-level group, and output files are named with suffixes like _s1.hdf5, _s2.hdf5, etc. ```APIDOC ## Function: split_hdf5_file ### Description Splits an HDF5 file into multiple parts if its total size exceeds the given limit. The minimal splitting unit is a top-level group. If the file size surpasses the specified max_file_size, this function creates multiple output HDF5 files and distributes the top-level groups among them without splitting any single group. Output files are named based on the input file's base name, with suffixes like `_s1.hdf5`, `_s2.hdf5`, etc. ### Parameters - **input_path** (str) - Required - Path to the input HDF5 file. - **max_file_size** (int, optional) - Maximum size in bytes for each output HDF5 file (default is 10GB). - **output_dir** (str, optional) - Directory where output files will be saved. Defaults to the current directory. ### Returns - **list of str** - A list of paths to the generated HDF5 files. ### Exceptions - **FileNotFoundError** - If the input file does not exist. ### Example ```python from eegunity.utils.split_hdf5_file import split_hdf5_file output_files = split_hdf5_file("large_file.hdf5", max_file_size=5 * 1024**3, output_dir="./output") print(output_files) ``` ``` -------------------------------- ### misc_task_name(ch_name) Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.utils.rst Extracts the task name from a misc label channel name of the form 'misc:{task_name}'. Raises ValueError if the input does not start with 'misc:'. ```APIDOC ## misc_task_name(ch_name) ### Description Extracts the task name from a misc label channel name of the form `'misc:{task_name}'`. ### Parameters - **ch_name** (*str*) - Required - A channel name of the form `'misc:{task_name}'`. ### Returns - **str** - The task name portion after the `'misc:'` prefix. ### Raises - **ValueError** - If `ch_name` does not start with `'misc:'`. ### Example ```pycon >>> misc_task_name('misc:reaction_time') 'reaction_time' ``` ``` -------------------------------- ### EEGBatchMixinEpoch.epoch_by_segmentation_hdf5() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/genindex.html Method to epoch data by segmentation from HDF5 files. ```APIDOC ## EEGBatchMixinEpoch.epoch_by_segmentation_hdf5() ### Description Method to epoch data by segmentation from HDF5 files. ### Method epoch_by_segmentation_hdf5 ### Endpoint EEGBatchMixinEpoch.epoch_by_segmentation_hdf5 ``` -------------------------------- ### Use batch_process with execution_mode='thread' Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Speep Up with Multithread.md Calls batch_process with thread execution mode, recommended for I/O-bound tasks. The example uses con_func and app_func to filter and extract file paths. ```python results = ud.eeg_batch.batch_process( con_func=lambda row: row["Completeness Check"] == "Completed", app_func=lambda row: row["File Path"], is_patch=False, result_type="value", execution_mode="thread", ) ``` -------------------------------- ### Compute Integrity Metadata with UnifiedDataset Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Build File Hash and File Size Metadata.md Initializes a UnifiedDataset, filters samples, computes Source Hash, Data Hash, and File Size, then prints the first rows of the locator with these columns. ```python from eegunity import UnifiedDataset ud = UnifiedDataset( dataset_path=r"path/to/dataset", domain_tag="my_dataset", num_workers=8, ) ud.eeg_batch.sample_filter(completeness_check="Completed") ud.eeg_batch.get_file_hashes() # Source Hash ud.eeg_batch.get_file_hashes(data_stream=True) # Data Hash ud.eeg_batch.get_file_sizes() # File Size locator = ud.get_locator() print(locator[["File Path", "Source Hash", "Data Hash", "File Size"]].head()) ``` -------------------------------- ### Align and order MNE Raw channels with channel_align_raw Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.utils.html Loads a raw FIF file, defines a channel order, and calls channel_align_raw with a minimum matched channel count of 5. The returned aligned_raw has channels reordered and missing channels added as zeros then interpolated. ```python >>> import mne >>> raw = mne.io.read_raw_fif('sample_raw.fif', preload=True) >>> desired_order = ['Fp1', 'Fp2', 'F3', 'F4', 'C3', 'C4', 'P3', 'P4', 'O1', 'O2'] >>> aligned_raw = channel_align_raw(raw, desired_order, min_matched_channel=5) ``` -------------------------------- ### UnifiedDataset constructor Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.html Creates a UnifiedDataset instance to manage EEG datasets. Parameters include dataset_path, locator_path, domain_tag, is_unzip, verbose, num_workers, and kernel_spec. ```APIDOC ## UnifiedDataset constructor ### Description Creates a UnifiedDataset instance to manage multiple EEG datasets and associated processing tools. ### Method Constructor ### Signature `UnifiedDataset(dataset_path: str | None = None, locator_path: str | None = None, domain_tag: str | None = None, is_unzip: bool = True, verbose: str = 'CRITICAL', num_workers: int = 0, kernel_spec: str | None = None)` ### Parameters - **dataset_path** (str, optional) - Path to the dataset folder. Should not be provided alongside locator_path. - **locator_path** (str, optional) - Path to the locator. Should not be provided alongside dataset_path. - **domain_tag** (str, optional) - The domain tag identifies the dataset name and is required if you specify a dataset path. - **is_unzip** (bool, optional) - If True, any Zip files in the specified dataset will be unzipped. Be aware that unzipping may modify the dataset. - **verbose** (str, optional) - Level of verbosity for logging (default is 'CRITICAL'). - **num_workers** (int, optional) - Number of workers (default is 0). - **kernel_spec** (str, optional) - Spec string in the form `":"` for loading an external kernel. ### Attributes - **eeg_parser** (EEGParser) - EEGParser module - **eeg_batch** (EEGBatch) - EEGBatch module - **eeg_correction** (EEGCorrection) - EEGCorrection module - **llm_booster** (EEGLLMBooster) - EEGLLMBooster module ``` -------------------------------- ### llm_description_file_parser() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.html Parses description files for LLM boosting. ```APIDOC ## llm_description_file_parser() ### Description Parses description files for LLM boosting. ``` -------------------------------- ### apply_dataset_kernel_unavailable(udataset, row) Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Tries to build a raw for an Unavailable file via the kernel's load() method. This is the entry point for the Option B extended kernel interface. Returns a fully processed raw (after load + apply), or None if the kernel does not support this file or load() returns None. ```APIDOC ## apply_dataset_kernel_unavailable(udataset, row) ### Description Tries to build a raw for an Unavailable file via the kernel's `load()` method. This is the entry point for the **Option B** extended kernel interface. For files that EEGUnity's parser cannot handle (`Completeness Check == 'Unavailable'`), a kernel may opt in by setting `HANDLES_UNAVAILABLE = True` and implementing a `load(row)` method. If `load()` returns a non-`None` `mne.io.BaseRaw`, the normal `apply_dataset_kernel()` enrichment step is called on that raw before returning, giving the same two-phase (load → apply) pipeline as for Completed files. ### Parameters - **udataset** (object) - Required - UnifiedDataset-like object exposing `get_shared_attr()`. - **row** (pandas.Series) - Required - Locator row for the Unavailable file. ### Returns - **mne.io.BaseRaw or None** - Fully processed raw (after load + apply), or `None` if the kernel does not support this file or `load()` returns `None`. ``` -------------------------------- ### Configure UnifiedDataset with num_workers=os.cpu_count() Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Speep Up with Multithread.md Sets the worker count to the number of CPU cores. This is a general starting point; reduce if memory pressure is high, increase for storage/network bound workloads. ```python import os from eegunity import UnifiedDataset ud = UnifiedDataset( dataset_path="your_dataset_root", domain_tag="your_domain_tag", num_workers=os.cpu_count(), ) ``` -------------------------------- ### Call process_wfdb_files with num_workers=2 Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Example usage of process_wfdb_files, passing a DataFrame locator_df and setting num_workers to 2 for parallel processing. The function updates the DataFrame with file details for WFDB files. ```pycon >>> process_wfdb_files(locator_df, num_workers=2) ``` -------------------------------- ### Process CSV files with process_csv_files Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Example usage of process_csv_files to process a CSV file. It creates a DataFrame with a 'File Path' column and calls the function with num_workers=0 and min_file_size=0. The output is not shown. ```pycon >>> import pandas as pd >>> locator = pd.DataFrame([{"File Path": "sample.csv", "File Type": "unknown"}]) >>> process_csv_files(locator, num_workers=0, min_file_size=0) ``` -------------------------------- ### Read EEGUnity HDF5 file with h5py and pickle Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Read h5Dataset.md.txt Opens an EEGUnity HDF5 file, iterates over each group, reads the 'eeg' dataset, and prints its shape. It also reads the 'rsFreq' and 'chOrder' attributes from the EEG dataset and parses the 'info' dataset using pickle to display additional metadata such as events. Replace 'your/file/path.hdf5' with the actual file path before running. ```python import h5py import pickle # Define the file path (replace 'your/file/path.hdf5' with your actual path) file_path = 'your/file/path.hdf5' # Open the HDF5 file and read specified fields with h5py.File(file_path, 'r') as f: # Retrieve all groups group_names = list(f.keys()) for i, grp_name in enumerate(group_names): print(f"\n=== Group {i} - {grp_name} ===") grp = f[grp_name] # Read EEG dataset if 'eeg' in grp: eeg_data = grp['eeg'][:] print(f"EEG Data Shape: {eeg_data.shape}") else: print("EEG dataset not found.") # Get the EEG dataset dset = grp['eeg'] # Read 'rsFreq' attribute (sampling rate) if 'rsFreq' in dset.attrs: rs_freq = dset.attrs['rsFreq'] print(f"Sampling Rate (rsFreq): {rs_freq}") else: print("Sampling rate (rsFreq) attribute not found.") # Read 'chOrder' attribute (channel order) if 'chOrder' in dset.attrs: ch_order = dset.attrs['chOrder'] print(f"Channel Order (chOrder): {ch_order}") else: print("Channel order (chOrder) attribute not found.") # Read and parse the 'info' dataset if 'info' in grp: info_array = grp['info'][()] info_bytes = info_array.tobytes() raw_info = pickle.loads(info_bytes) print(raw_info) else: print("Info dataset not found.") print("\n" + "=" * 30) ``` -------------------------------- ### Bind kernel to UnifiedDataset and run via parser and batch Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Reading Rich Meta Data via Kernel.md Shows how to create a UnifiedDataset with a kernel_spec and access data through eeg_parser.get_data(0) or eeg_batch.get_file_hashes(data_stream=True). The kernel is also applied when loading row data in batch methods. ```python from eegunity import UnifiedDataset ud = UnifiedDataset( dataset_path=r"path/to/dataset", domain_tag="my_dataset", kernel_spec=r"path/to/example_kernel.py", ) # Parser path raw0 = ud.eeg_parser.get_data(0) # Batch path (kernel is also applied when loading row data in batch methods) ud.eeg_batch.get_file_hashes(data_stream=True) ``` -------------------------------- ### llm_boost_parser() Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.html Parses files for LLM boosting. ```APIDOC ## llm_boost_parser() ### Description Parses files for LLM boosting. ``` -------------------------------- ### Step 2: Define Dataset-Specific Conversion Logic Source: https://github.com/baizhige/eegunity/blob/main/docs/source/tutorial/How to Make Standard Datasets.md Defines make_fif_row to convert a locator row into a standardized FIF file, including optional channel renaming, montage setting, metadata attachment, and saving. Then applies it via batch_process. ```python import json import os import mne from eegunity import UnifiedDataset, get_data_row INPUT_PATH = r"path/to/original_dataset" DOMAIN_TAG = "my_dataset" OUTPUT_DIR = r"./output_fif" os.makedirs(OUTPUT_DIR, exist_ok=True) ud = UnifiedDataset(dataset_path=INPUT_PATH, domain_tag=DOMAIN_TAG, num_workers=4) ud.eeg_batch.sample_filter(completeness_check="Completed") ud.eeg_batch.format_channel_names() def make_fif_row(row, output_dir): """Convert one locator row into a standardized FIF file.""" raw = get_data_row(row, is_set_channel_type=True) # Example: optional channel mapping and montage rename_map = { "EEG:CZ": "Cz", "EEG:FZ": "Fz", } valid_map = {k: v for k, v in rename_map.items() if k in raw.ch_names} if valid_map: raw.rename_channels(valid_map) raw.set_montage(mne.channels.make_standard_montage("standard_1020"), on_missing="ignore") # Example: attach structured metadata in description raw.info["description"] = json.dumps( { "original_description": raw.info.get("description", ""), "eegunity_description": { "dataset": DOMAIN_TAG, "pipeline": "make_fif_xxxx", }, } ) file_stem = os.path.splitext(os.path.basename(row["File Path"]))[0] output_path = os.path.join(output_dir, f"{file_stem}_raw.fif") raw.save(output_path, overwrite=True) return None ud.eeg_batch.batch_process( con_func=lambda row: row["Completeness Check"] == "Completed", app_func=lambda row: make_fif_row(row, OUTPUT_DIR), is_patch=False, result_type=None, execution_mode="process", ) ``` -------------------------------- ### Read HDF5 EEGLAB .set file with read_eeglab_hdf5 Source: https://github.com/baizhige/eegunity/blob/main/docs/source/eegunity.modules.parser.rst Call read_eeglab_hdf5 with a file path and optional preload and verbose parameters. When preload=False, returns a stub RawArray with annotations only, which is sufficient for metadata-only kernels. ```pycon >>> raw = read_eeglab_hdf5("sample.set", preload=False) ``` -------------------------------- ### Automatically update domain tag with EEGBatch.auto_domain Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/eegunity.modules.batch.html Example usage of the auto_domain method to update the 'Domain Tag' column based on sampling rate and channel names. The get_data_row_params parameter can be passed to customize data retrieval, e.g., preloading data. ```python >>> unified_dataset.eeg_batch.auto_domain(get_data_row_params={'preload': True}) ``` -------------------------------- ### Set num_workers to CPU core count Source: https://github.com/baizhige/eegunity/blob/main/docs/build/html/_sources/tutorial/How to Speep Up with Multithread.md.txt Use os.cpu_count() to set num_workers to the number of CPU cores, a recommended starting point. For I/O-heavy workloads, slightly higher values may help; for CPU-heavy processing, stay near core count. ```python import os u_dataset = UnifiedDataset( dataset_path="your_dataset_root", domain_tag="your_domain_tag", num_workers=os.cpu_count() ) ``` -------------------------------- ### Run CI tests Source: https://github.com/baizhige/eegunity/blob/main/HARNESS.md Runs all CI tests using the release environment. All scripts must pass. ```powershell & "C:\Users\Cheng\anaconda3\envs\eegunity_release\python.exe" CI/run_all_CI_test.py ```