Spaces:
Sleeping
Sleeping
Commit ·
5ec4552
1
Parent(s): b11ec91
[add] added louvain clustering
Browse filesFiles changed (3)
- requirements.txt+3-2
- src/loader.py+112-4
- src/streamlit_app.py+141-9
1234567streamlitnumpyplotlyscipymneh5pynetworkx12345678streamlit==1.24.0numpyplotlyscipymneh5pynetworkxpython-louvain
41 unmodified lines4243444546474849177 unmodified lines22722822923023123223323423523623723822 unmodified lines2612622632642652662675 unmodified lines2732742752762772782795 unmodified lines28528628728828929029141 unmodified linesreturn a_stem == b_stemdef _load_eeglab_hdf5(set_path: str, fdt_path: Optional[str] = None, debug: bool = False) -> Tuple[np.ndarray, float]:"""Load EEGLAB .set file saved in MATLAB v7.3 (HDF5) format using h5py.Returns: (x_tc, fs) where x_tc is (T, C)"""177 unmodified linesset_name: str,fdt_bytes: Optional[bytes] = None,fdt_name: Optional[str] = None,) -> Tuple[np.ndarray, float]:"""Load EEGLAB .set (and optional .fdt) from bytes using MNE or h5py.Returns:x_tc: (T, C) float32fs: sampling rate (Hz)Notes:- 多くのEEGLABは .set が .fdt を参照するため、同じディレクトリに同名で置く必要があります。22 unmodified linesraw = mne.io.read_raw_eeglab(set_path, preload=True, verbose=False)fs = float(raw.info["sfreq"])x_tc = raw.get_data().T # (T,C)return x_tc.astype(np.float32), fsexcept Exception as e_raw:# 2) Epochsとして読む(エポックデータ用)5 unmodified lines# ここは方針を選ぶ:平均 or 連結x_mean = x.mean(axis=0) # (C,T)x_tc = x_mean.T # (T,C)return x_tc.astype(np.float32), fsexcept Exception as e_ep:# 3) HDF5形式として読む(MATLAB v7.3)5 unmodified linesif 'streamlit' in sys.modules:debug = Truex_tc, fs = _load_eeglab_hdf5(set_path, fdt_path=fdt_path, debug=debug)return x_tc, fsexcept Exception as e_hdf5:# すべて失敗した場合41 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144177 unmodified lines32232332432532632732832933033133233333422 unmodified lines3573583593603613623633643653663675 unmodified lines3733743753763773783793803813823835 unmodified lines38939039139239339439539639739839941 unmodified linesreturn a_stem == b_stemdef extract_electrode_positions_2d(set_path: str) -> np.ndarray:"""EEGLABファイルから電極位置(2D)を抽出。Returns:pos: (C, 2) 電極の2D座標、取得できない場合はNone"""try:# MNEで読み込みraw = mne.io.read_raw_eeglab(set_path, preload=False, verbose=False)montage = raw.get_montage()if montage is None:return None# 3D座標を取得pos_3d = montage.get_positions()['ch_pos']if not pos_3d:return None# チャンネル名順に並べ替えch_names = raw.ch_namespositions = []for ch_name in ch_names:if ch_name in pos_3d:positions.append(pos_3d[ch_name])else:# 座標がないチャンネルは原点に配置positions.append([0, 0, 0])positions = np.array(positions)# 3D -> 2D 投影(上から見た図)# x, y座標を使用し、正規化pos_2d = positions[:, :2]# 正規化: 最大距離が1になるようにスケーリングmax_dist = np.max(np.sqrt(np.sum(pos_2d**2, axis=1)))if max_dist > 0:pos_2d = pos_2d / max_dist * 0.85 # 0.85倍で頭の輪郭内に収めるreturn pos_2d.astype(np.float32)except Exception as e:print(f"電極位置の抽出に失敗: {e}")return Nonedef _load_eeglab_hdf5(set_path: str, fdt_path: Optional[str] = None, debug: bool = False) -> Tuple[np.ndarray, float]:"""EEGLABファイルから電極位置(2D)を抽出。Returns:pos: (C, 2) 電極の2D座標、取得できない場合はNone"""try:# MNEで読み込みraw = mne.io.read_raw_eeglab(set_path, preload=False, verbose=False)montage = raw.get_montage()if montage is None:return None# 3D座標を取得pos_3d = montage.get_positions()['ch_pos']if not pos_3d:return None# チャンネル名順に並べ替えch_names = raw.ch_namespositions = []for ch_name in ch_names:if ch_name in pos_3d:positions.append(pos_3d[ch_name])else:# 座標がないチャンネルは原点に配置positions.append([0, 0, 0])positions = np.array(positions)# 3D -> 2D 投影(上から見た図)# x, y座標を使用し、正規化pos_2d = positions[:, :2]# 正規化: 最大距離が1になるようにスケーリングmax_dist = np.max(np.sqrt(np.sum(pos_2d**2, axis=1)))if max_dist > 0:pos_2d = pos_2d / max_dist * 0.85 # 0.85倍で頭の輪郭内に収めるreturn pos_2d.astype(np.float32)except Exception as e:print(f"電極位置の抽出に失敗: {e}")return None"""Load EEGLAB .set file saved in MATLAB v7.3 (HDF5) format using h5py.Returns: (x_tc, fs) where x_tc is (T, C)"""177 unmodified linesset_name: str,fdt_bytes: Optional[bytes] = None,fdt_name: Optional[str] = None,) -> Tuple[np.ndarray, float, Optional[np.ndarray]]:"""Load EEGLAB .set (and optional .fdt) from bytes using MNE or h5py.Returns:x_tc: (T, C) float32fs: sampling rate (Hz)electrode_pos: (C, 2) float32 or None - 電極の2D座標Notes:- 多くのEEGLABは .set が .fdt を参照するため、同じディレクトリに同名で置く必要があります。22 unmodified linesraw = mne.io.read_raw_eeglab(set_path, preload=True, verbose=False)fs = float(raw.info["sfreq"])x_tc = raw.get_data().T # (T,C)# 電極位置を取得electrode_pos = extract_electrode_positions_2d(set_path)return x_tc.astype(np.float32), fs, electrode_posexcept Exception as e_raw:# 2) Epochsとして読む(エポックデータ用)5 unmodified lines# ここは方針を選ぶ:平均 or 連結x_mean = x.mean(axis=0) # (C,T)x_tc = x_mean.T # (T,C)# 電極位置を取得(epochsからも取得可能)electrode_pos = extract_electrode_positions_2d(set_path)return x_tc.astype(np.float32), fs, electrode_posexcept Exception as e_ep:# 3) HDF5形式として読む(MATLAB v7.3)5 unmodified linesif 'streamlit' in sys.modules:debug = Truex_tc, fs = _load_eeglab_hdf5(set_path, fdt_path=fdt_path, debug=debug)# HDF5の場合は電極位置を取得できない(参照形式のため)electrode_pos = Nonereturn x_tc, fs, electrode_posexcept Exception as e_hdf5:# すべて失敗した場合
106 unmodified lines107108109110111112113114115116117118119120230 unmodified lines35135235335435535635735835936036118 unmodified lines38038138238338438536 unmodified lines4224234244254264277 unmodified lines435436437438439440441442443444384 unmodified lines8298308318328338348354 unmodified lines840841842843844845846847848849850851852853854106 unmodified linesEEGLAB bytes -> load -> auto preprocess (bandpass + hilbert).fsは読み込んだデータのものを使う。"""x_tc, fs = load_eeglab_tc_from_bytes(set_bytes=set_bytes,set_name=set_name,fdt_bytes=fdt_bytes,fdt_name=fdt_name,)cfg = PreprocessConfig(fs=float(fs), f_low=float(f_low), f_high=float(f_high))return preprocess_tc(x_tc, cfg)@st.cache_data(show_spinner=False)230 unmodified linesreturn colorsdef make_network_figure(W: np.ndarray, thr: float, use_louvain: bool = True) -> tuple[go.Figure, int]:C = W.shape[0]angles = np.linspace(0, 2 * np.pi, C, endpoint=False)xs = np.cos(angles)ys = np.sin(angles)edges = threshold_edges(W, thr)fig = go.Figure()18 unmodified linesr, g, b = colorsys.hsv_to_rgb(hue, 0.9, 0.95)return f'rgba({int(255*r)}, {int(255*g)}, {int(255*b)}, 0.7)'# エッジを描画(重みに応じて色と太さを変える)for (i, j, w) in edges:# 正規化された重み (0-1)36 unmodified linesmode="markers+text",text=[f"{k}" for k in range(C)],textposition="bottom center",marker=dict(size=14,color=node_colors,7 unmodified linesfig.update_layout(title=f"Estimated Network (thr={thr:.3f}) edges={len(edges)}{title_suffix}",height=500,xaxis=dict(visible=False),yaxis=dict(visible=False),margin=dict(l=10, r=10, t=50, b=10),paper_bgcolor='rgba(0,0,0,0.9)',plot_bgcolor='rgba(0,0,0,0.9)',)384 unmodified lines# 閾値スライダーとネットワーク図の表示wmax = float(np.max(W)) if np.isfinite(np.max(W)) else 1.0col_thr1, col_thr2 = st.columns([3, 1])with col_thr1:thr = st.slider("閾値 (threshold) ※下げるほどエッジが増えます",4 unmodified lines)with col_thr2:use_louvain = st.checkbox("Louvainクラスタリング",value=True,disabled=not LOUVAIN_AVAILABLE,help="ノードの色をコミュニティ検出結果で塗り分けます")net_col1, net_col2 = st.columns([2, 1])with net_col1:fig_net, edge_n = make_network_figure(W, float(thr), use_louvain=use_louvain)st.plotly_chart(fig_net)with net_col2:106 unmodified lines107108109110111112113114115116117118119120121122123124125126230 unmodified lines35735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143218 unmodified lines45145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549636 unmodified lines5335345355365375385397 unmodified lines547548549550551552553554555556384 unmodified lines9419429439449459469474 unmodified lines952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986106 unmodified linesEEGLAB bytes -> load -> auto preprocess (bandpass + hilbert).fsは読み込んだデータのものを使う。"""x_tc, fs, electrode_pos = load_eeglab_tc_from_bytes(set_bytes=set_bytes,set_name=set_name,fdt_bytes=fdt_bytes,fdt_name=fdt_name,)cfg = PreprocessConfig(fs=float(fs), f_low=float(f_low), f_high=float(f_high))result = preprocess_tc(x_tc, cfg)# 電極位置を追加if electrode_pos is not None:result["electrode_pos"] = electrode_posreturn result@st.cache_data(show_spinner=False)230 unmodified linesreturn colorsdef get_electrode_positions(prep: dict) -> np.ndarray:"""電極位置を取得する。Returns:pos: (C, 2) 電極の2D座標 (x, y)取得できない場合は円形配置を返す"""# prepに電極位置が保存されているかチェックif "electrode_pos" in prep:return prep["electrode_pos"]# デフォルト: 円形配置C = prep["raw"].shape[1]angles = np.linspace(0, 2 * np.pi, C, endpoint=False)xs = np.cos(angles)ys = np.sin(angles)return np.column_stack([xs, ys])def get_head_outline() -> dict:"""脳の輪郭(頭のアウトライン)を生成。Returns:outline: {'head': (x, y), 'nose': (x, y), 'ears': [(x_left, y_left), (x_right, y_right)]}"""# 頭の円theta = np.linspace(0, 2*np.pi, 100)head_x = np.cos(theta)head_y = np.sin(theta)# 鼻(上部の三角形)nose_x = np.array([0, -0.1, 0.1, 0])nose_y = np.array([1.0, 1.15, 1.15, 1.0])# 耳(左右の突起)ear_theta = np.linspace(-np.pi/4, np.pi/4, 20)ear_left_x = -1.0 + 0.08 * np.cos(ear_theta)ear_left_y = 0.08 * np.sin(ear_theta)ear_right_x = 1.0 - 0.08 * np.cos(ear_theta)ear_right_y = 0.08 * np.sin(ear_theta)return {'head': (head_x, head_y),'nose': (nose_x, nose_y),'ear_left': (ear_left_x, ear_left_y),'ear_right': (ear_right_x, ear_right_y),}def make_network_figure(W: np.ndarray,thr: float,use_louvain: bool = True,electrode_pos: np.ndarray = None,show_head: bool = True,) -> tuple[go.Figure, int]:C = W.shape[0]# 電極位置を取得if electrode_pos is None or electrode_pos.shape[0] != C:# デフォルト: 円形配置angles = np.linspace(0, 2 * np.pi, C, endpoint=False)xs = np.cos(angles)ys = np.sin(angles)else:xs = electrode_pos[:, 0]ys = electrode_pos[:, 1]edges = threshold_edges(W, thr)fig = go.Figure()18 unmodified linesr, g, b = colorsys.hsv_to_rgb(hue, 0.9, 0.95)return f'rgba({int(255*r)}, {int(255*g)}, {int(255*b)}, 0.7)'# 脳の輪郭を描画if show_head:outline = get_head_outline()# 頭の円fig.add_trace(go.Scatter(x=outline['head'][0], y=outline['head'][1],mode='lines',line=dict(color='rgba(150,150,150,0.5)', width=2),showlegend=False,hoverinfo='skip',))# 鼻fig.add_trace(go.Scatter(x=outline['nose'][0], y=outline['nose'][1],mode='lines',line=dict(color='rgba(150,150,150,0.5)', width=2),showlegend=False,hoverinfo='skip',))# 左耳fig.add_trace(go.Scatter(x=outline['ear_left'][0], y=outline['ear_left'][1],mode='lines',line=dict(color='rgba(150,150,150,0.5)', width=2),showlegend=False,hoverinfo='skip',))# 右耳fig.add_trace(go.Scatter(x=outline['ear_right'][0], y=outline['ear_right'][1],mode='lines',line=dict(color='rgba(150,150,150,0.5)', width=2),showlegend=False,hoverinfo='skip',))# エッジを描画(重みに応じて色と太さを変える)for (i, j, w) in edges:# 正規化された重み (0-1)36 unmodified linesmode="markers+text",text=[f"{k}" for k in range(C)],textposition="bottom center",textfont=dict(size=8),marker=dict(size=14,color=node_colors,7 unmodified linesfig.update_layout(title=f"Estimated Network (thr={thr:.3f}) edges={len(edges)}{title_suffix}",height=600,xaxis=dict(visible=False),yaxis=dict(visible=False),margin=dict(l=10, r=10, t=50, b=50),paper_bgcolor='rgba(0,0,0,0.9)',plot_bgcolor='rgba(0,0,0,0.9)',)384 unmodified lines# 閾値スライダーとネットワーク図の表示wmax = float(np.max(W)) if np.isfinite(np.max(W)) else 1.0col_thr1, col_thr2, col_thr3 = st.columns([2, 1, 1])with col_thr1:thr = st.slider("閾値 (threshold) ※下げるほどエッジが増えます",4 unmodified lines)with col_thr2:use_louvain = st.checkbox("Louvainクラスタ",value=True,disabled=not LOUVAIN_AVAILABLE,help="ノードの色をコミュニティ検出結果で塗り分けます")with col_thr3:show_head = st.checkbox("脳の輪郭を表示",value=True,help="頭部のアウトラインを表示します")# 電極位置を取得electrode_pos = prep.get("electrode_pos", None)if electrode_pos is not None:st.info(f"✓ 電極位置を使用してネットワークを配置 ({electrode_pos.shape[0]} channels)")else:st.info("ℹ️ 電極位置が取得できなかったため、円形配置を使用します")net_col1, net_col2 = st.columns([2, 1])with net_col1:fig_net, edge_n = make_network_figure(W,float(thr),use_louvain=use_louvain,electrode_pos=electrode_pos,show_head=show_head,)st.plotly_chart(fig_net)with net_col2:
requirements.txt+3-2
src/loader.py+112-4
src/streamlit_app.py+141-9