Advertisement
El_Chaderino

Symptom Vs Waveform module

May 7th, 2025 (edited)
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.79 KB | None | 0 0
  1. from typing import Dict, List, Tuple, Optional
  2.  
  3. class SymptomVsWaveform:
  4.     """
  5.    SymptomVsWaveform module by El Chaderino
  6.    http://github.com/ElChaderino/The-Squiggle-Interpreter
  7.    This module aids EEG practitioners in distinguishing between symptom-based neurofeedback protocols
  8.    and waveform-informed targeting. It offers rules-of-thumb guidance, symptom-to-waveform analysis,
  9.    targeted site recommendations, protocol suggestions, and common practitioner pitfalls.
  10.  
  11.    Attributes:
  12.        rules_of_thumb (dict): Guidelines for interpreting EEG findings in relation to symptoms.
  13.  
  14.    Methods:
  15.        analyze_site_drift(signal_profile, report_symptoms):
  16.            Compares symptoms with EEG profiles to identify potential mismatches.
  17.  
  18.        match_site_to_target(eeg_findings):
  19.            Suggests starting neurofeedback sites based on EEG data.
  20.  
  21.        suggest_protocols(eeg_findings, reported_symptoms):
  22.            Recommends specific neurofeedback protocols according to EEG data and reported symptoms.
  23.  
  24.        explain_traps():
  25.            Outlines common mistakes practitioners should avoid when interpreting EEG data.
  26.  
  27.        summarize(signal_profile, report_symptoms):
  28.            Returns a user-friendly summary of all recommendations and flags.
  29.    """
  30.  
  31.     def __init__(self):
  32.         self.rules_of_thumb: Dict[str, Dict] = {
  33.             'left_frontal': {'adjustment': +2, 'notes': 'Often overstimulating if run early in dysregulated clients'},
  34.             'posterior': {'stabilize_before_frontal': True},
  35.             'cingulate_hibeta': {'suggests': 'OCD/rumination, vigilance drive, inner conflict'},
  36.             'alpha_asymmetry': {'suggests': 'valence bias, depression, affect regulation'},
  37.             'hibeta_dominance': {'suggests': 'instability or trauma override masking real signal'},
  38.             'central_delta': {'suggests': 'sleep regulation issues or potential underlying trauma'},
  39.             'right_parietal_alpha': {'suggests': 'attention issues in PTSD'},
  40.             'sensorimotor_theta': {'suggests': 'motor control issues, potential ADHD'},
  41.             'prefrontal_beta': {'suggests': 'executive dysfunction, hyperarousal in PTSD'},
  42.             'right_temporal_theta': {'suggests': 'language processing issues, potential ASD'}
  43.         }
  44.  
  45.     def analyze_site_drift(self, signal_profile: Dict[str, float], report_symptoms: List[str]) -> Dict[str, str]:
  46.         """
  47.        Compares reported symptoms with EEG signals to identify mismatches.
  48.        Returns symptoms flagged as potentially mistargeted.
  49.        """
  50.         flags = {}
  51.         symptom_checks = {
  52.             'anxiety': lambda sp: sp.get('Pz_hibeta', 0) < sp.get('Fz_hibeta', 0),
  53.             'focus issues': lambda sp: sp.get('theta', 0) < 4.5,
  54.             'impulsivity': lambda sp: sp.get('F3_beta', 0) < 2.0,
  55.             'depression': lambda sp: abs(sp.get('F3_alpha', 0) - sp.get('F4_alpha', 0)) < 1.0,
  56.             'insomnia': lambda sp: sp.get('Cz_delta', 0) > 5.0,
  57.             'hyperactivity': lambda sp: sp.get('Fz_theta', 0) < 4.0,
  58.             'PTSD': lambda sp: sp.get('Fz_beta', 0) > 2.0 or sp.get('Cz_beta', 0) > 2.0 or (sp.get('P4_alpha', 0) > sp.get('P3_alpha', 0)),
  59.             'OCD': lambda sp: sp.get('Fz_hibeta', 0) > 2.0 or sp.get('Cz_hibeta', 0) > 2.0
  60.         }
  61.         symptom_messages = {
  62.             'anxiety': "Likely mistargeted. Pz not resolved before frontal work.",
  63.             'focus issues': "Reported focus trouble without elevated theta—may be vigilance crash, not ADD.",
  64.             'impulsivity': "No significant frontal beta—impulsivity may be emotional, not attentional.",
  65.             'depression': "No significant alpha asymmetry—depression may not be related to valence bias.",
  66.             'insomnia': "Elevated delta at Cz—may indicate sleep-related issues.",
  67.             'hyperactivity': "No elevated theta at Fz—hyperactivity may not be ADHD-related.",
  68.             'PTSD': "High beta at Fz/Cz or right parietal alpha asymmetry may indicate hyperarousal or attention issues in PTSD.",
  69.             'OCD': "High hibeta at Fz/Cz may indicate OCD/rumination."
  70.         }
  71.         for symptom in report_symptoms:
  72.             if symptom in symptom_checks and symptom_checks[symptom](signal_profile):
  73.                 flags[symptom] = symptom_messages[symptom]
  74.         return flags
  75.  
  76.     def match_site_to_target(self, eeg_findings: Dict[str, float], reported_symptoms: Optional[List[str]] = None) -> List[Tuple[str, str]]:
  77.         """
  78.        Suggests EEG sites for initiating neurofeedback based on EEG signal abnormalities, with cross-checks.
  79.        Cross-checks ensure posterior stability, symptom consistency, and coherence metrics.
  80.        Returns a list of (site, reason) tuples.
  81.        """
  82.         suggestions = []
  83.         reported_symptoms = reported_symptoms or []
  84.  
  85.         # Define target checks with thresholds and cross-check conditions
  86.         target_checks = [
  87.             ('Pz_hibeta', 2.0, "Pz", "Start here to stabilize limbic/sensory loops before frontal work", lambda ef, rs: True),
  88.             ('Fz_hibeta', 2.0, "Fz", "Only after posterior cleanup. Frontal beta may feel worse until then.",
  89.              lambda ef, rs: ef.get('Pz_hibeta', 0) <= 2.0),  # Posterior stability check
  90.             ('T3_theta', 3.5, "T3", "Check for disconnection or developmental drift (possible ASD marker)",
  91.              lambda ef, rs: 'hyperactivity' in rs or 'focus issues' in rs),  # Symptom consistency
  92.             ('Cz_delta', 5.0, "Cz", "Consider targeting delta at Cz for sleep regulation issues",
  93.              lambda ef, rs: 'insomnia' in rs),
  94.             ('Fz_beta', 2.0, "Fz", "Reduce beta for hyperarousal in PTSD",
  95.              lambda ef, rs: 'PTSD' in rs and ef.get('Pz_hibeta', 0) <= 2.0),
  96.             ('Cz_beta', 2.0, "Cz", "Reduce beta for hyperarousal in PTSD",
  97.              lambda ef, rs: 'PTSD' in rs and ef.get('Pz_hibeta', 0) <= 2.0),
  98.             ('P4_alpha', 5.0, "P3/P4", "Balance alpha asymmetry for attention issues in PTSD",
  99.              lambda ef, rs: 'PTSD' in rs and ef.get('P4_alpha', 0) > ef.get('P3_alpha', 0)),
  100.             ('F3_alpha', 5.0, "F3/F4", "Check for emotional regulation issues",
  101.              lambda ef, rs: 'depression' in rs or abs(ef.get('F3_alpha', 0) - ef.get('F4_alpha', 0)) > 1.0),
  102.             ('O1_alpha', 5.0, "O1/O2", "Increase alpha for relaxation in anxiety",
  103.              lambda ef, rs: 'anxiety' in rs),
  104.             ('C3_theta', 5.0, "C3/C4", "Target theta for motor control in ADHD",
  105.              lambda ef, rs: 'hyperactivity' in rs or 'focus issues' in rs),
  106.             ('T4_theta', 3.5, "T4", "Check for language processing issues (possible ASD marker)",
  107.              lambda ef, rs: 'hyperactivity' in rs or 'focus issues' in rs),
  108.             ('Fp1_beta', 2.0, "Fp1/Fp2", "Reduce beta for executive dysfunction in PTSD",
  109.              lambda ef, rs: 'PTSD' in rs and ef.get('Pz_hibeta', 0) <= 2.0),
  110.             ('Oz_alpha', 5.0, "Pz/Oz", "Increase alpha for visual processing stability",
  111.              lambda ef, rs: 'anxiety' in rs or 'PTSD' in rs)
  112.         ]
  113.  
  114.         for signal, threshold, site, reason, cross_check in target_checks:
  115.             if eeg_findings.get(signal, 0) > threshold and cross_check(eeg_findings, reported_symptoms):
  116.                 suggestions.append((site, reason))
  117.  
  118.         # Additional cross-check: Ensure coherence between homologous sites (e.g., F3/F4)
  119.         if 'depression' in reported_symptoms and abs(eeg_findings.get('F3_alpha', 0) - eeg_findings.get('F4_alpha', 0)) > 1.0:
  120.             if ('F3/F4', "Check for emotional regulation issues") not in suggestions:
  121.                 suggestions.append(("F3/F4", "Significant alpha asymmetry detected, confirm for depression"))
  122.  
  123.         return suggestions
  124.  
  125.     def suggest_protocols(self, eeg_findings: Dict[str, float], reported_symptoms: List[str]) -> List[Tuple[str, str]]:
  126.         """
  127.        Provides neurofeedback protocol recommendations based on EEG findings and client symptoms.
  128.        Returns a list of (protocol, reason) tuples.
  129.        """
  130.         protocols = []
  131.         protocol_conditions = [
  132.             ('anxiety', lambda ef: ef.get('O1_alpha', 0) < 5.0 or ef.get('O2_alpha', 0) < 5.0,
  133.              "Alpha-theta training at O1/O2", "For relaxation and anxiety reduction"),
  134.             ('focus issues', lambda ef: ef.get('theta', 0) > 5.0,
  135.              "Theta/beta ratio training at Fz/Cz", "To improve focus by reducing theta"),
  136.             ('impulsivity', lambda ef: ef.get('F3_beta', 0) < 1.5,
  137.              "Beta increase at F3", "For attentional control"),
  138.             ('depression', lambda ef: abs(ef.get('F3_alpha', 0) - ef.get('F4_alpha', 0)) > 1.0,
  139.              "Alpha asymmetry correction at F3/F4", "To address valence bias"),
  140.             ('insomnia', lambda ef: ef.get('Cz_beta', 0) > 2.0,
  141.              "Beta reduction at Cz", "To promote sleep"),
  142.             ('hyperactivity', lambda ef: ef.get('Fz_theta', 0) > 5.0,
  143.              "Theta reduction at Fz", "To address hyperactivity"),
  144.             ('PTSD', lambda ef: ef.get('Fz_beta', 0) > 2.0 or ef.get('Cz_beta', 0) > 2.0,
  145.              "Beta reduction at Fz/Cz", "To reduce hyperarousal"),
  146.             ('PTSD', lambda ef: ef.get('P4_alpha', 0) > ef.get('P3_alpha', 0),
  147.              "Alpha balancing at P3/P4", "To address attention issues"),
  148.             ('PTSD', lambda ef: ef.get('Fp1_beta', 0) > 2.0,
  149.              "Beta reduction at Fp1/Fp2", "To improve executive function"),
  150.             ('OCD', lambda ef: ef.get('Fz_hibeta', 0) > 2.0 or ef.get('Cz_hibeta', 0) > 2.0,
  151.              "Hibeta reduction at Fz/Cz", "To reduce rumination"),
  152.             ('hyperactivity', lambda ef: ef.get('C3_theta', 0) > 5.0,
  153.              "SMR training at C3/C4", "To enhance motor control in ADHD"),
  154.             ('focus issues', lambda ef: ef.get('T4_theta', 0) > 3.5,
  155.              "Theta reduction at T4", "To address potential ASD-related issues")
  156.         ]
  157.         for symptom, condition, protocol, reason in protocol_conditions:
  158.             if symptom in reported_symptoms and condition(eeg_findings):
  159.                 protocols.append((protocol, reason))
  160.         return protocols
  161.  
  162.     def explain_traps(self) -> List[str]:
  163.         """
  164.        Outlines common mistakes practitioners should avoid when interpreting EEG data.
  165.        """
  166.         return [
  167.             "Mistaking artifact for true signal (e.g., muscle, eye movement)",
  168.             "Overfocusing on frontal sites before stabilizing posterior regions",
  169.             "Ignoring alpha asymmetry in depression cases",
  170.             "Assuming all high beta is pathological—context matters",
  171.             "Neglecting client-reported symptoms in favor of only waveform data",
  172.             "Failing to cross-check protocol with both symptoms and EEG findings",
  173.             "Targeting sites without checking posterior stability, risking overstimulation",
  174.             "Overlooking coherence issues between homologous sites (e.g., F3/F4)",
  175.             "Not adjusting protocols for new EEG sites like C3/C4 or Fp1/Fp2"
  176.         ]
  177.  
  178.     def summarize(self, signal_profile: Dict[str, float], report_symptoms: List[str]) -> str:
  179.         """
  180.        Returns a user-friendly summary of all recommendations and flags.
  181.        """
  182.         drift_flags = self.analyze_site_drift(signal_profile, report_symptoms)
  183.         site_targets = self.match_site_to_target(signal_profile, report_symptoms)
  184.         protocols = self.suggest_protocols(signal_profile, report_symptoms)
  185.         traps = self.explain_traps()
  186.         summary = ["\n=== Symptom vs Waveform Analysis Summary ==="]
  187.         if drift_flags:
  188.             summary.append("\nPotential Mistargeted Symptoms:")
  189.             for k, v in drift_flags.items():
  190.                 summary.append(f"- {k}: {v}")
  191.         if site_targets:
  192.             summary.append("\nRecommended Starting Sites:")
  193.             for site, reason in site_targets:
  194.                 summary.append(f"- {site}: {reason}")
  195.         if protocols:
  196.             summary.append("\nSuggested Protocols:")
  197.             for protocol, reason in protocols:
  198.                 summary.append(f"- {protocol}: {reason}")
  199.         summary.append("\nCommon Practitioner Traps:")
  200.         for trap in traps:
  201.             summary.append(f"- {trap}")
  202.         return "\n".join(summary)
  203.  
  204. # Example usage
  205. if __name__ == "__main__":
  206.     eeg = {
  207.         'Pz_hibeta': 2.5, 'Fz_hibeta': 1.5, 'theta': 3.0, 'F3_beta': 1.0,
  208.         'F3_alpha': 6.0, 'F4_alpha': 4.5, 'Cz_delta': 6.0, 'Fz_theta': 3.5,
  209.         'Fz_beta': 2.5, 'Cz_beta': 2.1, 'P4_alpha': 6.0, 'P3_alpha': 4.0,
  210.         'O1_alpha': 4.0, 'O2_alpha': 4.5, 'T3_theta': 4.0, 'C3_theta': 5.5,
  211.         'T4_theta': 3.8, 'Fp1_beta': 2.2, 'Oz_alpha': 5.2
  212.     }
  213.     symptoms = ['anxiety', 'depression', 'insomnia', 'focus issues', 'PTSD', 'OCD', 'hyperactivity']
  214.     svw = SymptomVsWaveform()
  215.     print(svw.summarize(eeg, symptoms))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement