fadzwan commited on
Commit
c70a8ec
·
verified ·
1 Parent(s): 6db7c44

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +95 -36
src/streamlit_app.py CHANGED
@@ -1,40 +1,99 @@
1
- import altair as alt
 
2
  import numpy as np
3
  import pandas as pd
 
 
 
 
 
4
  import streamlit as st
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
  import numpy as np
4
  import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import mne
7
+ from mne.channels import make_dig_montage
8
+ from matplotlib.animation import FuncAnimation
9
+ import requests
10
  import streamlit as st
11
 
12
+ # Set page config
13
+ st.set_page_config(page_title="Muse EEG Topomap Viewer", layout="centered")
14
+
15
+ def plot_eeg_topomap_muse_from_csv(csv_url, save_path_animation=None, save_directory=None,
16
+ show_names=False, start_time=0.05, end_time=1, step_size=0.1):
17
+ response = requests.get(csv_url)
18
+ if response.status_code != 200:
19
+ raise RuntimeError(f"Failed to download CSV from {csv_url}")
20
+ data = pd.read_csv(io.StringIO(response.text))
21
+ st.write(f"Loaded data with shape: {data.shape}")
22
+
23
+ muse_channels = ['AF7', 'AF8', 'TP9', 'TP10']
24
+ if not all(ch in data.columns for ch in muse_channels):
25
+ raise ValueError(f"The dataset must contain the following channels: {muse_channels}")
26
+
27
+ eeg_data = data[muse_channels].values.T
28
+
29
+ muse_positions = {
30
+ 'AF7': [-0.05, 0.085, 0],
31
+ 'AF8': [0.05, 0.085, 0],
32
+ 'TP9': [-0.08, -0.04, 0],
33
+ 'TP10': [0.08, -0.04, 0]
34
+ }
35
+ for ch in muse_positions:
36
+ muse_positions[ch][0] += np.random.normal(0, 0.0001)
37
+ muse_positions[ch][1] += np.random.normal(0, 0.0001)
38
+
39
+ montage = make_dig_montage(ch_pos=muse_positions, coord_frame='head')
40
+
41
+ if 'TimeStamp' in data.columns:
42
+ timestamps = data['TimeStamp']
43
+ elif 'timestamps' in data.columns:
44
+ timestamps = data['timestamps']
45
+ else:
46
+ raise ValueError("CSV must contain a 'TimeStamp' or 'timestamps' column")
47
+
48
+ time_diffs = np.diff(timestamps)
49
+ average_interval = np.mean(time_diffs)
50
+ sfreq = 1 / average_interval
51
+
52
+ info = mne.create_info(ch_names=muse_channels, sfreq=sfreq, ch_types='eeg')
53
+ evoked = mne.EvokedArray(eeg_data, info)
54
+ evoked.set_montage(montage)
55
+
56
+ times = np.arange(start_time, end_time, step_size)
57
+ if len(times) == 0:
58
+ raise ValueError("Not enough time range selected for topomap animation.")
59
+
60
+ if save_path_animation:
61
+ if save_directory:
62
+ os.makedirs(save_directory, exist_ok=True)
63
+ save_path_animation = os.path.join(save_directory, save_path_animation)
64
+
65
+ fig, ax = plt.subplots()
66
+
67
+ def update(frame):
68
+ ax.clear()
69
+ evoked.plot_topomap([times[frame]], ch_type='eeg', time_unit='s',
70
+ axes=ax, colorbar=False, show=False)
71
+
72
+ anim = FuncAnimation(fig, update, frames=range(len(times)), interval=200)
73
+ anim.save(save_path_animation, writer='pillow')
74
+ plt.close(fig)
75
+
76
+ return save_path_animation
77
+ else:
78
+ return None
79
+
80
+ # Streamlit UI
81
+ st.title("🧠 Muse EEG Topomap Animation from CSV")
82
+
83
+ default_url = "https://raw.githubusercontent.com/garenasd945/EEG_muse2/refs/heads/master/dataset/original_data/subjecta-relaxed-1.csv"
84
+ csv_url = st.text_input("CSV URL", value=default_url)
85
+ generate_button = st.button("Generate Topomap Animation")
86
+
87
+ if generate_button:
88
+ try:
89
+ gif_path = plot_eeg_topomap_muse_from_csv(
90
+ csv_url,
91
+ save_path_animation="eeg_topomap_animation.gif",
92
+ save_directory="animations",
93
+ show_names=True
94
+ )
95
+ if gif_path:
96
+ st.image(gif_path, caption="EEG Topomap Animation")
97
+ except Exception as e:
98
+ st.error(f"❌ Error: {str(e)}")
99
+ #update