Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import pandas as pd
- import csv
- import os
- import glob
- # Load and convert data from the text file to prepare for analysis
- file_path_pattern = '/mnt/data/*.epochs.txt' # Look for epoch files with wildcard
- file_paths = glob.glob(file_path_pattern)
- if len(file_paths) > 0:
- file_path = file_paths[0] # Assuming we are working with the first matched file
- # Convert the text file to CSV using similar logic as vocals_converter.py
- with open(file_path) as csvfile:
- reader = csv.DictReader(csvfile, delimiter='\t')
- data = []
- types = ['MEAN', 'MEANF', 'STDDEV', 'MODFRQ']
- # Adjusted the column names to match those in the provided dataset
- bands = {
- 'Delta': {'MEAN': 'Delta::Amplitude Mean', 'STDDEV': 'Delta::Amplitude Std Dev'},
- 'Theta': {'MEAN': 'Theta::Amplitude Mean', 'STDDEV': 'Theta::Amplitude Std Dev'},
- 'Alpha': {'MEAN': 'Alpha::Amplitude Mean', 'STDDEV': 'Alpha::Amplitude Std Dev'},
- 'Lo-Alpha': {'MEAN': 'Lo-Alpha::Amplitude Mean', 'STDDEV': 'Lo-Alpha::Amplitude Std Dev'},
- 'Hi-Alpha': {'MEAN': 'Hi-Alpha::Amplitude Mean', 'STDDEV': 'Hi-Alpha::Amplitude Std Dev'},
- 'SMR': {'MEAN': 'SMR::Amplitude Mean', 'STDDEV': 'SMR::Amplitude Std Dev'},
- 'Beta': {'MEAN': 'Beta::Amplitude Mean', 'STDDEV': 'Beta::Amplitude Std Dev'},
- 'Hi-Beta/Gamma': {'MEAN': 'Hi-Beta/Gamma::Amplitude Mean', 'STDDEV': 'Hi-Beta/Gamma::Amplitude Std Dev'}
- }
- for row in reader:
- for type_ in types:
- run = {'TYPE': str(type_)}
- for band in bands:
- try:
- value = float(row.get(bands[band][type_], 'nan'))
- if not np.isnan(value):
- if value < 1:
- run[band] = round(value * 1000000, 2)
- else:
- run[band] = round(value, 2)
- except KeyError:
- # Skip if the key is not found in the row
- continue
- except ValueError:
- # Skip if the value cannot be converted to float (e.g., missing or non-numeric data)
- continue
- run['RUN'] = row.get('Run', None)
- run['EPOCH'] = row['Time']
- data.append(run)
- # Write the converted data to a CSV file
- converted_csv_path = '/mnt/data/converted_data.csv'
- with open(converted_csv_path, 'w', newline='') as csvfile:
- fieldnames = ['EPOCH', 'RUN', 'TYPE'] + list(bands.keys())
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
- writer.writeheader()
- for row in data:
- writer.writerow(row)
- # Load the converted data into a DataFrame for analysis
- data_df = pd.read_csv(converted_csv_path)
- # Filter the data for amplitude mean values (for Clinical Q analysis)
- data_filtered = data_df[data_df['TYPE'] == 'MEAN']
- # Define fixed epochs and sites within the 4:40 (280 seconds) recording
- epochs_mapping = {
- 'Cz': {'20s EO': (0, 20), '10s EC': (20, 30), '10s EO': (30, 40), '40s UT': (40, 80), '10s EO (after UT)': (80, 90)},
- 'O1': {'20s EO': (90, 110), '10s EC': (110, 120), '10s EO': (120, 130)},
- 'F3': {'30s EC': (130, 160)},
- 'F4': {'30s EC': (160, 190)},
- 'Fz': {'1:40 EC': (190, 280)}
- }
- # Define frequency bands of interest
- bands_of_interest = ['Delta', 'Theta', 'Alpha', 'Lo-Alpha', 'Hi-Alpha', 'SMR', 'Beta', 'Hi-Beta/Gamma']
- # Known detection vectors and their clinical implications
- detection_vectors = {
- 'Delta': "High delta can indicate issues such as head trauma, learning disabilities, or excessive drowsiness.",
- 'Theta': "Elevated theta is often associated with ADHD, inattentiveness, or daydreaming.",
- 'Alpha': "Alpha activity is linked to relaxation and idling. Low alpha may indicate anxiety, while high alpha may relate to excessive relaxation or disengagement.",
- 'Lo-Alpha': "Low-alpha dominance can point to difficulty in focusing or an inability to relax.",
- 'Hi-Alpha': "High-alpha dominance can indicate a highly relaxed state, sometimes excessive in nature.",
- 'SMR': "Sensorimotor rhythm (SMR) is associated with calm focus. Low SMR may relate to impulsivity or hyperactivity.",
- 'Beta': "High beta is associated with active thinking and problem-solving. Excessive beta can indicate anxiety or hyperarousal.",
- 'Hi-Beta/Gamma': "High beta or gamma activity can indicate heightened stress, hypervigilance, or excessive cognitive processing."
- }
- # Generate a detailed report for Clinical Q/qEEG level analysis
- report_lines = []
- report_lines.append("==================== EEG Analysis Report ====================\n")
- report_lines.append(f"File: {file_path}\n")
- report_lines.append("\n==================== Channel-wise Analysis ====================\n")
- # Process each site and its epochs to extract band power metrics and generate interpretations
- protocol_guide = []
- protocol_guide.append("==================== Suggested Protocol Guide ====================\n")
- for site, epochs in epochs_mapping.items():
- report_lines.append(f"\n-------------------------------------------------------------\n")
- report_lines.append(f"Channel: {site}\n")
- report_lines.append(f"-------------------------------------------------------------\n")
- protocol_guide.append(f"\nChannel: {site}\n")
- protocol_guide.append(f"-------------------------------------------------------------\n")
- protocol_guide.append(" Suggested Protocol:\n")
- for epoch_name, (start, end) in epochs.items():
- report_lines.append(f" Epoch: {epoch_name}\n")
- protocol_notes = []
- # Calculate mean power for each band over the given epoch
- for band in bands_of_interest:
- try:
- epoch_data = data_filtered.filter(like=band).iloc[start:end]
- if epoch_data.isna().all().values[0]:
- raise ValueError("No valid data available for this epoch")
- mean_value = epoch_data.mean().values[0]
- report_lines.append(f" {band} Mean Power: {mean_value:.8f}\n")
- # Add clinical interpretation based on the detection vector
- if band == 'Delta' and mean_value > 10.0:
- report_lines.append(f" Alert: High Delta observed. {detection_vectors[band]}\n")
- protocol_notes.append("Inhibit: Reduce Delta activity to address issues such as head trauma, learning disabilities, or excessive drowsiness.")
- elif band == 'Theta' and mean_value > 12.0:
- report_lines.append(f" Alert: Elevated Theta observed. {detection_vectors[band]}\n")
- protocol_notes.append("Inhibit: Reduce Theta activity to mitigate inattention, daydreaming, and ADHD symptoms. Reward range: 4-8 Hz.")
- elif band == 'Alpha' and mean_value < 8.0:
- report_lines.append(f" Alert: Low Alpha detected. {detection_vectors[band]}\n")
- protocol_notes.append("Reward: Increase Alpha activity to aid relaxation and reduce anxiety. Reward range: 8-12 Hz.")
- elif band == 'SMR' and mean_value < 4.0:
- report_lines.append(f" Alert: Low SMR observed. {detection_vectors[band]}\n")
- protocol_notes.append("Reward: Increase SMR (12-15 Hz) to improve focus, relaxation, and calmness. Reward range: 12-15 Hz.")
- elif band == 'Beta' and mean_value > 15.0:
- report_lines.append(f" Alert: Elevated Beta observed. {detection_vectors[band]}\n")
- protocol_notes.append("Inhibit: Reduce High Beta (22-30 Hz) to help manage anxiety and hypervigilance. Reward range: 15-20 Hz.")
- except (IndexError, KeyError, ValueError):
- report_lines.append(f" {band} Mean Power: Data not available for epoch range\n")
- report_lines.append("\n")
- if not protocol_notes:
- protocol_notes.append("No specific abnormalities detected; use standard protocol adjustments based on symptom tracking.")
- # Add the protocol notes for the current epoch
- for note in protocol_notes:
- protocol_guide.append(f" {note}\n")
- protocol_guide.append(" Additional Notes: Tailor the training to the individual's response, adjusting based on symptom reduction and improvement in cognitive function.\n")
- # Save the report and protocol guide to text files
- report_file_path = '/mnt/data/eeg_analysis_report.txt'
- protocol_file_path = '/mnt/data/eeg_protocol_guide.txt'
- with open(report_file_path, 'w') as report_file:
- report_file.writelines(report_lines)
- with open(protocol_file_path, 'w') as protocol_file:
- protocol_file.writelines(protocol_guide)
- print(f"Report saved to {report_file_path}")
- print(f"Protocol guide saved to {protocol_file_path}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement