Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def robust_convert_ng_to_edf(ng_file_path, edf_output_path, ch_names=None, sfreq=None, ch_types='eeg', header_size=2048):
- """
- Robustly convert a NeuroGuide .ng EEG file to EDF format.
- Args:
- ng_file_path (str or Path): Path to .ng binary file.
- edf_output_path (str or Path): Desired output path for the .edf file.
- ch_names (list[str], optional): EEG channel labels. Defaults to generic if None.
- sfreq (float, optional): Sampling rate. If None, attempts heuristic fallback.
- ch_types (str or list, optional): EEG channel types. Default is 'eeg'.
- header_size (int): Bytes to skip for header.
- Returns:
- Path: Path to the written EDF file.
- Raises:
- ValueError: If conversion fails due to data integrity or format issues.
- """
- try:
- parsed = parse_neuroguide_ng(ng_file_path, header_size=header_size)
- except Exception as e:
- raise ValueError(f"Failed to parse .ng file: {e}")
- signals = parsed.get("signals")
- metadata = parsed.get("metadata", {})
- if not signals or not isinstance(signals, list) or len(signals) == 0:
- raise ValueError("No signal data extracted from .ng file.")
- n_channels = len(signals)
- n_samples = len(signals[0])
- if any(len(ch) != n_samples for ch in signals):
- raise ValueError("Inconsistent sample lengths across channels.")
- data = np.array(signals, dtype=np.float64)
- # Channel labels
- if ch_names is None:
- known_19 = ["Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8",
- "T3", "C3", "Cz", "C4", "T4",
- "T5", "P3", "Pz", "P4", "T6", "O1", "O2"]
- ch_names = known_19[:n_channels] if n_channels == 19 else [f"EEG {i+1}" for i in range(n_channels)]
- # Fallback sfreq guess
- if sfreq is None:
- # Naively assume 256Hz as typical default
- sfreq = 256.0
- print("⚠️ Sampling rate not specified. Defaulting to 256 Hz.")
- try:
- info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
- raw = RawArray(data, info)
- except Exception as e:
- raise ValueError(f"Failed to create MNE Raw object: {e}")
- # EDF export fallback
- try:
- from mne.export import export_raw
- edf_output_path = Path(edf_output_path)
- export_raw(edf_output_path, raw, fmt='edf', overwrite=True)
- return edf_output_path
- except ImportError:
- raise ImportError("MNE export_raw not available. Please update MNE to use EDF export.")
- except Exception as e:
- raise RuntimeError(f"Failed to export EDF: {e}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement