Advertisement
El_Chaderino

Bioexplorer CZ Analysis Tool

Oct 21st, 2024 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.31 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import csv
  4. import os
  5. import glob
  6.  
  7. # Load and convert data from the text file to prepare for analysis
  8. file_path_pattern = '/mnt/data/*.epochs.txt'  # Look for epoch files with wildcard
  9. file_paths = glob.glob(file_path_pattern)
  10.  
  11. if len(file_paths) > 0:
  12.     file_path = file_paths[0]  # Assuming we are working with the first matched file
  13.  
  14.     # Convert the text file to CSV using similar logic as vocals_converter.py
  15.     with open(file_path) as csvfile:
  16.         reader = csv.DictReader(csvfile, delimiter='\t')
  17.         data = []
  18.         types = ['MEAN', 'MEANF', 'STDDEV', 'MODFRQ']
  19.  
  20.         # Adjusted the column names to match those in the provided dataset
  21.         bands = {
  22.             'Delta': {'MEAN': 'Delta::Amplitude Mean', 'STDDEV': 'Delta::Amplitude Std Dev'},
  23.             'Theta': {'MEAN': 'Theta::Amplitude Mean', 'STDDEV': 'Theta::Amplitude Std Dev'},
  24.             'Alpha': {'MEAN': 'Alpha::Amplitude Mean', 'STDDEV': 'Alpha::Amplitude Std Dev'},
  25.             'Lo-Alpha': {'MEAN': 'Lo-Alpha::Amplitude Mean', 'STDDEV': 'Lo-Alpha::Amplitude Std Dev'},
  26.             'Hi-Alpha': {'MEAN': 'Hi-Alpha::Amplitude Mean', 'STDDEV': 'Hi-Alpha::Amplitude Std Dev'},
  27.             'SMR': {'MEAN': 'SMR::Amplitude Mean', 'STDDEV': 'SMR::Amplitude Std Dev'},
  28.             'Beta': {'MEAN': 'Beta::Amplitude Mean', 'STDDEV': 'Beta::Amplitude Std Dev'},
  29.             'Hi-Beta/Gamma': {'MEAN': 'Hi-Beta/Gamma::Amplitude Mean', 'STDDEV': 'Hi-Beta/Gamma::Amplitude Std Dev'}
  30.         }
  31.  
  32.         for row in reader:
  33.             for type_ in types:
  34.                 run = {'TYPE': str(type_)}
  35.                 for band in bands:
  36.                     try:
  37.                         value = float(row.get(bands[band][type_], 'nan'))
  38.                         if not np.isnan(value):
  39.                             if value < 1:
  40.                                 run[band] = round(value * 1000000, 2)
  41.                             else:
  42.                                 run[band] = round(value, 2)
  43.                     except KeyError:
  44.                         # Skip if the key is not found in the row
  45.                         continue
  46.                     except ValueError:
  47.                         # Skip if the value cannot be converted to float (e.g., missing or non-numeric data)
  48.                         continue
  49.                 run['RUN'] = row.get('Run', None)
  50.                 run['EPOCH'] = row['Time']
  51.                 data.append(run)
  52.  
  53.     # Write the converted data to a CSV file
  54.     converted_csv_path = '/mnt/data/converted_data.csv'
  55.     with open(converted_csv_path, 'w', newline='') as csvfile:
  56.         fieldnames = ['EPOCH', 'RUN', 'TYPE'] + list(bands.keys())
  57.         writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  58.         writer.writeheader()
  59.         for row in data:
  60.             writer.writerow(row)
  61.  
  62.     # Load the converted data into a DataFrame for analysis
  63.     data_df = pd.read_csv(converted_csv_path)
  64.  
  65.     # Filter the data for amplitude mean values (for Clinical Q analysis)
  66.     data_filtered = data_df[data_df['TYPE'] == 'MEAN']
  67.  
  68.     # Define fixed epochs and sites within the 4:40 (280 seconds) recording
  69.     epochs_mapping = {
  70.         'Cz': {'20s EO': (0, 20), '10s EC': (20, 30), '10s EO': (30, 40), '40s UT': (40, 80), '10s EO (after UT)': (80, 90)},
  71.         'O1': {'20s EO': (90, 110), '10s EC': (110, 120), '10s EO': (120, 130)},
  72.         'F3': {'30s EC': (130, 160)},
  73.         'F4': {'30s EC': (160, 190)},
  74.         'Fz': {'1:40 EC': (190, 280)}
  75.     }
  76.  
  77.     # Define frequency bands of interest
  78.     bands_of_interest = ['Delta', 'Theta', 'Alpha', 'Lo-Alpha', 'Hi-Alpha', 'SMR', 'Beta', 'Hi-Beta/Gamma']
  79.  
  80.     # Known detection vectors and their clinical implications
  81.     detection_vectors = {
  82.         'Delta': "High delta can indicate issues such as head trauma, learning disabilities, or excessive drowsiness.",
  83.         'Theta': "Elevated theta is often associated with ADHD, inattentiveness, or daydreaming.",
  84.         'Alpha': "Alpha activity is linked to relaxation and idling. Low alpha may indicate anxiety, while high alpha may relate to excessive relaxation or disengagement.",
  85.         'Lo-Alpha': "Low-alpha dominance can point to difficulty in focusing or an inability to relax.",
  86.         'Hi-Alpha': "High-alpha dominance can indicate a highly relaxed state, sometimes excessive in nature.",
  87.         'SMR': "Sensorimotor rhythm (SMR) is associated with calm focus. Low SMR may relate to impulsivity or hyperactivity.",
  88.         'Beta': "High beta is associated with active thinking and problem-solving. Excessive beta can indicate anxiety or hyperarousal.",
  89.         'Hi-Beta/Gamma': "High beta or gamma activity can indicate heightened stress, hypervigilance, or excessive cognitive processing."
  90.     }
  91.  
  92.     # Generate a detailed report for Clinical Q/qEEG level analysis
  93.     report_lines = []
  94.     report_lines.append("==================== EEG Analysis Report ====================\n")
  95.     report_lines.append(f"File: {file_path}\n")
  96.     report_lines.append("\n==================== Channel-wise Analysis ====================\n")
  97.  
  98.     # Process each site and its epochs to extract band power metrics and generate interpretations
  99.     protocol_guide = []
  100.     protocol_guide.append("==================== Suggested Protocol Guide ====================\n")
  101.  
  102.     for site, epochs in epochs_mapping.items():
  103.         report_lines.append(f"\n-------------------------------------------------------------\n")
  104.         report_lines.append(f"Channel: {site}\n")
  105.         report_lines.append(f"-------------------------------------------------------------\n")
  106.         protocol_guide.append(f"\nChannel: {site}\n")
  107.         protocol_guide.append(f"-------------------------------------------------------------\n")
  108.         protocol_guide.append("  Suggested Protocol:\n")
  109.  
  110.         for epoch_name, (start, end) in epochs.items():
  111.             report_lines.append(f"  Epoch: {epoch_name}\n")
  112.             protocol_notes = []
  113.             # Calculate mean power for each band over the given epoch
  114.             for band in bands_of_interest:
  115.                 try:
  116.                     epoch_data = data_filtered.filter(like=band).iloc[start:end]
  117.                     if epoch_data.isna().all().values[0]:
  118.                         raise ValueError("No valid data available for this epoch")
  119.                     mean_value = epoch_data.mean().values[0]
  120.                     report_lines.append(f"    {band} Mean Power: {mean_value:.8f}\n")
  121.                    
  122.                     # Add clinical interpretation based on the detection vector
  123.                     if band == 'Delta' and mean_value > 10.0:
  124.                         report_lines.append(f"    Alert: High Delta observed. {detection_vectors[band]}\n")
  125.                         protocol_notes.append("Inhibit: Reduce Delta activity to address issues such as head trauma, learning disabilities, or excessive drowsiness.")
  126.                     elif band == 'Theta' and mean_value > 12.0:
  127.                         report_lines.append(f"    Alert: Elevated Theta observed. {detection_vectors[band]}\n")
  128.                         protocol_notes.append("Inhibit: Reduce Theta activity to mitigate inattention, daydreaming, and ADHD symptoms. Reward range: 4-8 Hz.")
  129.                     elif band == 'Alpha' and mean_value < 8.0:
  130.                         report_lines.append(f"    Alert: Low Alpha detected. {detection_vectors[band]}\n")
  131.                         protocol_notes.append("Reward: Increase Alpha activity to aid relaxation and reduce anxiety. Reward range: 8-12 Hz.")
  132.                     elif band == 'SMR' and mean_value < 4.0:
  133.                         report_lines.append(f"    Alert: Low SMR observed. {detection_vectors[band]}\n")
  134.                         protocol_notes.append("Reward: Increase SMR (12-15 Hz) to improve focus, relaxation, and calmness. Reward range: 12-15 Hz.")
  135.                     elif band == 'Beta' and mean_value > 15.0:
  136.                         report_lines.append(f"    Alert: Elevated Beta observed. {detection_vectors[band]}\n")
  137.                         protocol_notes.append("Inhibit: Reduce High Beta (22-30 Hz) to help manage anxiety and hypervigilance. Reward range: 15-20 Hz.")
  138.  
  139.                 except (IndexError, KeyError, ValueError):
  140.                     report_lines.append(f"    {band} Mean Power: Data not available for epoch range\n")
  141.             report_lines.append("\n")
  142.  
  143.             if not protocol_notes:
  144.                 protocol_notes.append("No specific abnormalities detected; use standard protocol adjustments based on symptom tracking.")
  145.  
  146.             # Add the protocol notes for the current epoch
  147.             for note in protocol_notes:
  148.                 protocol_guide.append(f"    {note}\n")
  149.         protocol_guide.append("    Additional Notes: Tailor the training to the individual's response, adjusting based on symptom reduction and improvement in cognitive function.\n")
  150.  
  151.     # Save the report and protocol guide to text files
  152.     report_file_path = '/mnt/data/eeg_analysis_report.txt'
  153.     protocol_file_path = '/mnt/data/eeg_protocol_guide.txt'
  154.     with open(report_file_path, 'w') as report_file:
  155.         report_file.writelines(report_lines)
  156.     with open(protocol_file_path, 'w') as protocol_file:
  157.         protocol_file.writelines(protocol_guide)
  158.  
  159.     print(f"Report saved to {report_file_path}")
  160.     print(f"Protocol guide saved to {protocol_file_path}")
  161.  
Tags: eeg clinical q
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement