{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":11455827,"sourceType":"datasetVersion","datasetId":7177961}],"dockerImageVersionId":31012,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"---\n# **S.O.M. – EEG | Harmonic Viewer & Submission Generator**\n\n<div style=\"background-color: #203354; border-radius: 1em; text-align: center; color: white; padding: 50px 20px;\">\n  <h1 style=\"font-size: 36px; font-weight: 900; letter-spacing: 0.05em;\">Symbolic Frame Inference Based on Harmonic Geometry (Kaggle 2024)</h1>\n</div>\n\n## **Overview: Harmonic Symbolism in EEG Pattern Recognition**\n\nThe **System of Materarithmetric Operations (S.O.M. – EEG)** introduces a symbolic and harmonic method for interpreting EEG signals, structured through the epistemological lens of **T-Física** — a theory that integrates temporal geometry and multidimensional frequency interpretation.\n\nThis repository showcases:\n\n- A **3D Harmonic Frame Viewer** for EEG spectrograms;\n- A symbolic **inference layer** simulating diagnostic votes;\n- A self-contained **submission generator** aligned with HMS competition standards.\n\n✔ **Harmonic Frame Visualization**  \n✔ **Symbolic Labeling based on ACNS criteria**  \n✔ **Compatible with HMS competition formats**\n\n---\n\n## **Theoretical Framework & Dataset Reference**\n\n**Foundational Theory:** T-Física – *The Language of Time and the Geometry of Perception*  \n**DOI (T-Física):** [10.34740/kaggle/ds/6969238](https://doi.org/10.34740/kaggle/ds/6969238)\n\n**Dataset DOI (Converted EEG Samples):**  \n[10.34740/kaggle/dsv/11455827](https://doi.org/10.34740/kaggle/dsv/11455827)  \nNote: This dataset includes **only a selection of `.csv`-converted files** derived from the original `.parquet` EEG files released by the Harvard Medical School / CCEMRC.\n\n**Original Competition Dataset:**  \n[HMS - Harmful Brain Activity Classification](https://www.kaggle.com/competitions/hms-harmful-brain-activity-classification)\n\n---\n\n## **Architecture: Harmonic Frame Rendering + Symbolic Inference**\n\n### **Modules:**\n- `run_viewer()` — displays a single EEG file with 3D frequency-channel-time mapping;\n- `generate_submission()` — simulates ACNS-style classification votes (e.g., GRDA, LPD);\n- `build_3d_layers()` — applies logarithmic spectrogram transform and harmonic depth stacking.\n\n```python\nfig.update_layout(\n    title={\n        \"text\": f\"<b>S.O.M. EEG Harmonic Model</b><br>Harmonic Frame Viewer – <b>{label}</b>\",\n        \"x\": 0.5,\n        \"xanchor\": \"center\"\n    },\n    scene=dict(\n        xaxis_title=\"Time (s)\",\n        yaxis_title=\"Frequency (Hz)\",\n        zaxis_title=\"Channels\"\n    )\n)\n```\n\nThe plotly-based frame uses **Inferno colormap** and **layered z-depths** for frequency harmonization.\n\n---\n\n## **Harmonic Label Mapping (ACNS-Inspired)**\n\nThe simulation of EEG patterns uses a **symbolic label resolver**, based on highest vote in the `train.csv` metadata:\n\n| Vote Column | Symbolic Pattern |\n|-------------|------------------|\n| `seizure_vote` | Seizure |\n| `lpd_vote`     | LPD |\n| `gpd_vote`     | GPD |\n| `grda_vote`    | GRDA |\n| `lrda_vote`    | LRDA |\n| `other_vote`   | Other |\n\n---\n\n## **Sample Execution**\n\n```python\nrun_viewer()  # displays a random EEG file as symbolic harmonic cube\n\ngenerate_submission()  # creates submission.csv using simulated probabilities\n```\n\nThe visual result is a **3D dynamic field** with symbolic channel labels and layered resonance.\n\n---\n\n## **Submission Format**\n\n- Output: `/kaggle/working/submission.csv`\n- Fields: `id`, `seizure`, `lpd`, `gpd`, `grda`, `lrda`, `other`\n- Probabilities are **synthetically generated** using Dirichlet distributions\n\n---\n\n## **License & Acknowledgments**\n\n**Code License:** Apache 2.0  \n**Data Attribution:** CC BY-NC 4.0 — HMS / CCEMRC\n\n> This viewer is part of the **S.O.M. EEG** symbolic framework and was developed by **Tiberius**, based on the epistemology of **T-Física**.\n\nWe acknowledge the original competition authors and EEG reviewers listed in the [HMS leaderboard](https://www.kaggle.com/competitions/hms-harmful-brain-activity-classification/overview).\n\n \nThis work is gratefully inspired by the Harvard Medical School and the Critical Care EEG Monitoring Research Consortium (CCEMRC) for providing access to the HMS dataset, and by all researchers and collaborators whose contributions enable the advancement of EEG science.\n\nSpecial thanks to those who believe in the transformative power of harmonic intelligence.\nThis project would not exist without intuition, dedication, and the dream of a future where science, art, and perception converge.\n\n---\n\n","metadata":{}},{"cell_type":"code","source":"\"\"\"\nS.O.M. – EEG: Harmonic Frame Viewer and Symbolic Submission Generator\nLate Submission for HMS - Harmful Brain Activity Classification (Kaggle 2024)\n\nAuthor: Emerson Italo Lima da Silva (Tiberius)\n\nSystem: S.O.M. – EEG (System of Materarithmetric Operations)\n\nTheoretical Foundation: T-Física – \"The Language of Time and the Geometry of Perception\"\n\nDOI (T-Física): https://doi.org/10.34740/kaggle/ds/6969238\nDOI (Dataset): https://doi.org/10.34740/kaggle/dsv/11455827\n\nLicense: Apache 2.0 (per competition guidelines)\nData Attribution: CC BY-NC 4.0 – Harvard Medical School / CCEMRC (Kaggle)\n\"\"\"\n\n# === [0] Import Modules ===\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\nfrom scipy.signal import spectrogram\nimport random\n\n# === [1] Define CSV Folder Paths ===\nCSV_EEG_FOLDER = Path(\"/kaggle/input/converted-csv-hms\")\nTRAIN_CSV_PATH = Path(\"/kaggle/input/hms-harmful-brain-activity-classification/train.csv\")\nTEST_CSV_PATH = Path(\"/kaggle/input/hms-harmful-brain-activity-classification/test.csv\")\nSUBMISSION_OUTPUT_PATH = Path(\"/kaggle/working/submission.csv\")\n\n# === [2] Model Parameters ===\nFREQ = 200\nN_CHANNELS = 20\nLAYER_SPACING = 40\nCOLOR_SCALE = 'Inferno'\n\n# === [3] Read Metadata & Define ACNS Labels ===\nmetadata = pd.read_csv(TRAIN_CSV_PATH)\nACNS_VOTE_LABELS = {\n    \"seizure_vote\": \"Seizure\",\n    \"lpd_vote\": \"LPD\",\n    \"gpd_vote\": \"GPD\",\n    \"lrda_vote\": \"LRDA\",\n    \"grda_vote\": \"GRDA\",\n    \"other_vote\": \"Other\"\n}\nCLASSES = [\"seizure\", \"lpd\", \"gpd\", \"grda\", \"lrda\", \"other\"]\n\n# === [4] Utility Functions ===\ndef get_label_from_metadata(file_id):\n    subset = metadata[metadata[\"eeg_id\"] == file_id]\n    if subset.empty:\n        return \"Normal\"\n    row = subset.iloc[0]\n    votes = {label: row.get(vote, 0) for vote, label in ACNS_VOTE_LABELS.items()}\n    max_vote = max(votes.values())\n    labels = [label for label, v in votes.items() if v == max_vote and v > 0]\n    return labels[0] if labels else \"Normal\"\n\ndef build_3d_layers(data, fs=FREQ, offset=0):\n    layers = []\n    for idx, signal in enumerate(data):\n        if len(signal) < 10:\n            continue\n        f, t, Sxx = spectrogram(signal, fs=fs)\n        Sxx_log = 10 * np.log10(Sxx + 1e-10)\n        z_layer = Sxx_log + (idx + offset) * LAYER_SPACING\n        layers.append((t, f, z_layer, idx + offset))\n    return layers\n\ndef plot_interactive_frame(layers, label=\"Normal\"):\n    fig = go.Figure()\n    for t, f, z, idx in layers:\n        fig.add_surface(\n            x=t, y=f, z=z,\n            colorscale=COLOR_SCALE,\n            showscale=False,\n            opacity=0.7 / (idx + 1)**0.3,\n            name=f\"Channel {idx + 1}\",\n            hoverinfo='name'\n        )\n\n    fig.update_layout(\n        title={\n            \"text\": f\"<b>S.O.M. EEG Harmonic Model</b><br>Harmonic Frame Viewer – <b>{label}</b>\",\n            \"x\": 0.5,\n            \"xanchor\": \"center\",\n            \"y\": 0.96,\n            \"yanchor\": \"top\",\n            \"font\": dict(size=24, family=\"Times New Roman\")\n        },\n        scene=dict(\n            xaxis_title=\"Time (s)\",\n            yaxis_title=\"Frequency (Hz)\",\n            zaxis_title=\"Channels\",\n            xaxis=dict(title_font=dict(size=16, family=\"Times New Roman\")),\n            yaxis=dict(title_font=dict(size=16, family=\"Times New Roman\")),\n            zaxis=dict(title_font=dict(size=16, family=\"Times New Roman\"))\n        ),\n        font=dict(family=\"Times New Roman\", size=14),\n        margin=dict(t=120, l=0, r=0, b=0),\n        scene_camera=dict(eye=dict(x=1.5, y=1.5, z=1.0))\n    )\n    fig.show()\n\n# === [5] Viewer Runner ===\ndef run_viewer():\n    eeg_files = sorted([f for f in CSV_EEG_FOLDER.iterdir() if f.suffix == \".csv\"])\n    if not eeg_files:\n        print(\"[!] No EEG files found.\")\n        return\n    selected_file = random.choice(eeg_files)\n    file_id = int(selected_file.stem)\n    label = get_label_from_metadata(file_id)\n    data = pd.read_csv(selected_file).values.T\n    layers = build_3d_layers(data)\n    plot_interactive_frame(layers, label=label)\n\n# === [6] Symbolic Submission Simulator ===\ndef simulate_prediction(file_id):\n    probs = np.random.dirichlet([0.2, 0.3, 0.2, 5.0, 0.3, 0.3])\n    return np.round(probs, 4)\n\ndef generate_submission():\n    test_df = pd.read_csv(TEST_CSV_PATH)\n    submission = []\n    for _, row in test_df.iterrows():\n        file_id = row[\"eeg_id\"]\n        probs = simulate_prediction(file_id)\n        entry = {\"id\": file_id}\n        entry.update(dict(zip(CLASSES, probs)))\n        submission.append(entry)\n    pd.DataFrame(submission).to_csv(SUBMISSION_OUTPUT_PATH, index=False)\n    print(f\"[\\u2713] submission.csv saved to: {SUBMISSION_OUTPUT_PATH}\")\n\n# === [7] Execute ===\nrun_viewer()\ngenerate_submission()\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-04-18T08:44:38.255128Z","iopub.execute_input":"2025-04-18T08:44:38.255394Z","iopub.status.idle":"2025-04-18T08:44:38.465811Z","shell.execute_reply.started":"2025-04-18T08:44:38.255371Z","shell.execute_reply":"2025-04-18T08:44:38.465074Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"---\n# **S.O.M. EEG – Harmonic Intelligence and Comparative Mathematical Modeling**\n\n<div style=\"background-color: #1C2A4E; border-radius: 1em; text-align: center; color: white; padding: 50px 20px;\">\n  <h1 style=\"font-size: 36px; font-weight: 900; letter-spacing: 0.05em;\">Beyond the Signal: Mathematical Expansion from Traditional EEG to T-Física</h1>\n</div>\n\n---\n\n## **Overview: A Mathematical Transition**\nTraditional EEG models rely on **time-frequency decomposition** to extract rhythmic components and neural signatures:\n\n<div style=\"border-radius: 1em; background-color: #444444; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>X(t) = ∑<sub>k</sub> A<sub>k</sub> \\* sin(2πf<sub>k</sub>t + φ<sub>k</sub>)</b>\n</div>\n\nWhere:\n- **A<sub>k</sub>**: Amplitude\n- **f<sub>k</sub>**: Frequency component\n- **φ<sub>k</sub>**: Phase offset\n\nWhile effective, this representation is **linearly constrained**, focused solely on **frequency components within a single time-line**, ignoring **angular-spatial resonance and temporal volumetrics**.\n\n---\n\n## **T-Física Formalism: Towards Angular-Time Inference**\nIn contrast, the **T-Física-based model** embeds EEG within a **resonant angular-temporal volume**:\n\n<div style=\"border-radius: 1em; background-color: #48B0F7; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>X(θ, φ, τ) = ∫<sup>T</sup><sub>0</sub> F(θ, φ, ω) ⋅ e<sup>i(ωτ + θ + φ)</sup> dτ</b>\n</div>\n\nWhere:\n- **θ, φ** are angular projections (RA: Relatividade Angular)\n- **τ** is harmonic time (PQ: Pontualidade Quântica)\n- **F** denotes the **fractalized spectral field**\n\nKey Insight:** Instead of a timeline, time is treated as a **harmonic depth coordinate**, intersecting angular components that evolve.\n\n---\n\n## **EEG Tensor Reconstruction vs. Harmonic Layer Encoding**\nTraditional EEG visualizations reconstruct a **2D signal matrix**:\n\n<div style=\"border-radius: 1em; background-color: #444444; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>S<sub>EEG</sub> = [s<sub>1</sub>(t), s<sub>2</sub>(t), ..., s<sub>20</sub>(t)]<sup>T</sup></b>\n</div>\n\nT-Física-based visualization reconstructs a **3D Layered Field**:\n\n<div style=\"border-radius: 1em; background-color: #48B0F7; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>Σ(t, f, c) ⇒ L(t, f, θ<sub>c</sub>)</b>\n</div>\n\nWhere:\n- **c**: EEG channel index\n- **θ<sub>c</sub>**: angular layer offset for each channel\n- **L**: harmonic frame encoded via depth layering and symbolic projection\n\n---\n\n## **Doppler Harmonic Adjustment in AI Processing**\nIn EEG learning systems, the signal shift due to neural activity progression is classically treated as noise. But in S.O.M. EEG:\n\n<div style=\"border-radius: 1em; background-color: #48B0F7; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>f<sub>harmonic</sub> = f<sub>0</sub> × (1 + Δθ/Δt)</b>\n</div>\n\nThis allows the system to detect **directional spectral shifts** as valid markers of pattern emergence, using:\n- **Δθ/Δt** as the angular-temporal velocity of change\n\n---\n\n## **EEG Mathematical Compression vs. Fractal Harmonics**\nIn EEG compression:\n\n- **Conventional model**:\n<div style=\"border-radius: 1em; background-color: #444444; text-align: center; color: white; padding: 20px; font-size: 20px;\">\n<b>Compression = FFT + Thresholding</b>\n</div>\n\n- **T-Física model**:\n<div style=\"border-radius: 1em; background-color: #48B0F7; text-align: center; color: white; padding: 30px 20px; font-size: 22px;\">\n<b>F<sub>harmonic</sub> = ∑<sup>n</sup><sub>k=0</sub> A<sub>k</sub> ⋅ e<sup>-kθ</sup> / 2<sup>k</sup></b>\n</div>\n\nThis expression integrates **frequency damping and fractal decay**, harmonizing signal layers while conserving angular integrity.\n\n---\n\n## **Symbolic vs. Probabilistic Interpretation**\nWhile traditional EEG models classify signal bands with thresholds (e.g., **delta**, **alpha**, **beta**, **gamma**), T-Física encourages:\n\n- A **symbolic mapping** of the harmonic frame\n- Each channel layer acting as a **resonant node**\n- Labels such as GRDA or LPD act as **topological attractors** instead of just statistical modes\n\n---\n\n## **Conclusion: Towards an Angular-Centered Neuroepistemology**\nS.O.M. EEG Harmonic System redefines EEG understanding:\n- From **linear timelines** to **multi-angular harmonic fields**\n- From **static classification** to **symbolic resonance**\n- From **compression** to **fractal semiotic layering**\n\nThis is not just a model of signal—it is a **geometry of perception**.\n\nDOI T-Física: [10.34740/kaggle/ds/6969238](https://doi.org/10.34740/kaggle/ds/6969238)  \nDataset DOI: [10.34740/kaggle/dsv/11455827](https://doi.org/10.34740/kaggle/dsv/11455827)\n\n---","metadata":{}}]}