Spaces:
Sleeping
Sleeping
siddhant-rajhans commited on
Commit ·
bce4bae
0
Parent(s):
Initial CortexLab Dashboard - interactive analysis toolkit
Browse filesStreamlit multipage app with 4 analysis pages:
- Brain Alignment Benchmark: compare AI models with RSA/CKA/Procrustes + permutation tests
- Cognitive Load Scorer: timeline, radar chart, dimension breakdown with content profiles
- Temporal Dynamics: peak latency, lag correlation, sustained/transient decomposition
- ROI Connectivity: correlation heatmap, network clustering, degree centrality, graph viz
Runs on synthetic data by default - no GPU or fMRI data required.
Files changed (10)
- .gitignoreAdded+6
- .streamlit/config.tomlAdded+9
- Home.pyAdded+50
- README.mdAdded+28
- pages/1_Brain_Alignment.pyAdded+140
- pages/2_Cognitive_Load.pyAdded+131
- pages/3_Temporal_Dynamics.pyAdded+119
- pages/4_Connectivity.pyAdded+162
- requirements.txtAdded+8
- utils.pyAdded+222
123456__pycache__/*.py[cod].streamlit/secrets.toml.envvenv/.venv/123456789[theme]primaryColor = "#6C5CE7"backgroundColor = "#0E1117"secondaryBackgroundColor = "#1A1A2E"textColor = "#FAFAFA"font = "sans serif"
[server]headless = true1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""CortexLab Dashboard - Home Page."""
import streamlit as st
st.set_page_config( page_title="CortexLab Dashboard", page_icon="🧠", layout="wide", initial_sidebar_state="expanded",)
st.title("CortexLab Dashboard")st.markdown("**Interactive analysis toolkit for multimodal fMRI brain encoding**")
st.divider()
col1, col2 = st.columns(2)
with col1: st.subheader("Analysis Tools") st.page_link("pages/1_Brain_Alignment.py", label="Brain Alignment Benchmark", icon="🎯") st.markdown("Score how brain-like any AI model's representations are using RSA, CKA, or Procrustes")
st.page_link("pages/2_Cognitive_Load.py", label="Cognitive Load Scorer", icon="📊") st.markdown("Predict cognitive demand across visual, auditory, language, and executive dimensions")
with col2: st.subheader("Advanced Analysis") st.page_link("pages/3_Temporal_Dynamics.py", label="Temporal Dynamics", icon="⏱️") st.markdown("Analyze peak response latency, lag correlations, and sustained vs transient components")
st.page_link("pages/4_Connectivity.py", label="ROI Connectivity", icon="🔗") st.markdown("Compute functional connectivity matrices, cluster networks, and graph metrics")
st.divider()
st.subheader("About")st.markdown( """CortexLab is an enhanced toolkit built on [Meta's TRIBE v2](https://github.com/facebookresearch/tribev2)for predicting how the human brain responds to video, audio, and text.
This dashboard runs on **synthetic data** by default - no GPU or real fMRI data required.All analysis tools mirror the CortexLab Python API.
[GitHub](https://github.com/siddhant-rajhans/cortexlab) | [HuggingFace](https://huggingface.co/SID2000/cortexlab)""")12345678910111213141516171819202122232425262728# CortexLab Dashboard
Interactive analysis dashboard for [CortexLab](https://github.com/siddhant-rajhans/cortexlab) - multimodal fMRI brain encoding toolkit.
## Pages
- **Brain Alignment Benchmark** - Compare AI model representations against brain responses (RSA, CKA, Procrustes)- **Cognitive Load Scorer** - Visualize cognitive demand across visual, auditory, language, and executive dimensions- **Temporal Dynamics** - Peak latency, lag correlations, sustained vs transient response decomposition- **ROI Connectivity** - Correlation matrices, network clustering, degree centrality, graph visualization
## Quick Start
```bashpip install -r requirements.txtstreamlit run Home.py```
Runs on **synthetic data** by default - no GPU or real fMRI data required.
## Links
- [CortexLab Library](https://github.com/siddhant-rajhans/cortexlab)- [CortexLab on HuggingFace](https://huggingface.co/SID2000/cortexlab)
## License
CC BY-NC 4.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Brain Alignment Benchmark page."""
import streamlit as stimport numpy as npimport pandas as pdimport plotly.graph_objects as goimport plotly.express as px
from utils import ( ALIGNMENT_METHODS, make_roi_indices, generate_brain_predictions, generate_model_features, permutation_test,)
st.set_page_config(page_title="Brain Alignment", page_icon="🎯", layout="wide")st.title("🎯 Brain Alignment Benchmark")st.markdown("Compare how well AI model representations align with predicted brain responses.")
# --- Sidebar Controls ---with st.sidebar: st.header("Configuration") n_stimuli = st.slider("Number of stimuli", 10, 200, 50) seed = st.number_input("Random seed", value=42, min_value=0)
st.subheader("Models to compare") models_config = { "CLIP ViT-L/14": st.checkbox("CLIP ViT-L/14", value=True), "DINOv2 ViT-S": st.checkbox("DINOv2 ViT-S", value=True), "V-JEPA2 ViT-G": st.checkbox("V-JEPA2 ViT-G", value=True), "LLaMA 3.2-3B": st.checkbox("LLaMA 3.2-3B", value=False), } model_dims = { "CLIP ViT-L/14": 768, "DINOv2 ViT-S": 384, "V-JEPA2 ViT-G": 1024, "LLaMA 3.2-3B": 3072, } selected_models = [m for m, checked in models_config.items() if checked]
methods = st.multiselect("Methods", ["RSA", "CKA", "Procrustes"], default=["RSA", "CKA"]) run_stats = st.checkbox("Run permutation test", value=False) n_perm = st.slider("Permutations", 50, 1000, 200) if run_stats else 0
if not selected_models or not methods: st.warning("Select at least one model and one method.") st.stop()
# --- Generate Data ---roi_indices, n_vertices = make_roi_indices()brain_pred = generate_brain_predictions(n_stimuli, n_vertices, seed)
model_features = {}for i, name in enumerate(selected_models): model_features[name] = generate_model_features(n_stimuli, model_dims[name], seed + i + 1)
# --- Run Benchmark ---with st.spinner("Computing alignment scores..."): results = [] for model_name, features in model_features.items(): for method_name in methods: score_fn = ALIGNMENT_METHODS[method_name] score = score_fn(features, brain_pred) row = {"Model": model_name, "Method": method_name, "Score": score}
if run_stats: _, p_val = permutation_test(features, brain_pred, score_fn, n_perm, seed) row["p-value"] = p_val row["Significant"] = "Yes" if p_val < 0.05 else "No"
results.append(row)
df = pd.DataFrame(results)
# --- Display Results ---col1, col2 = st.columns([2, 1])
with col1: st.subheader("Alignment Scores") fig = px.bar( df, x="Model", y="Score", color="Method", barmode="group", color_discrete_sequence=px.colors.qualitative.Set2, ) fig.update_layout( yaxis_title="Alignment Score", height=450, template="plotly_dark", ) st.plotly_chart(fig, use_container_width=True)
with col2: st.subheader("Results Table") display_df = df.copy() display_df["Score"] = display_df["Score"].map(lambda x: f"{x:.4f}") if "p-value" in display_df.columns: display_df["p-value"] = display_df["p-value"].map(lambda x: f"{x:.4f}") st.dataframe(display_df, use_container_width=True, hide_index=True)
# --- Per-ROI Analysis ---st.divider()st.subheader("Per-ROI Alignment (RSA)")
if "RSA" in methods and len(selected_models) >= 1: from utils import ROI_GROUPS, rsa_score
roi_data = [] for model_name, features in model_features.items(): for group_name, rois in ROI_GROUPS.items(): group_scores = [] for roi in rois: if roi in roi_indices: verts = roi_indices[roi] valid = verts[verts < brain_pred.shape[1]] if len(valid) >= 2: s = rsa_score(features, brain_pred[:, valid]) group_scores.append(s) if group_scores: roi_data.append({ "Model": model_name, "Region": group_name, "RSA Score": float(np.mean(group_scores)), })
if roi_data: roi_df = pd.DataFrame(roi_data) fig2 = px.bar( roi_df, x="Region", y="RSA Score", color="Model", barmode="group", color_discrete_sequence=px.colors.qualitative.Pastel, ) fig2.update_layout(height=400, template="plotly_dark") st.plotly_chart(fig2, use_container_width=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Cognitive Load Scorer page."""
import streamlit as stimport numpy as npimport pandas as pdimport plotly.graph_objects as goimport plotly.express as px
from utils import ( make_roi_indices, generate_brain_predictions, score_cognitive_load, COGNITIVE_DIMENSIONS,)
st.set_page_config(page_title="Cognitive Load", page_icon="📊", layout="wide")st.title("📊 Cognitive Load Scorer")st.markdown("Predict cognitive demand of media content from brain activation patterns.")
# --- Sidebar ---with st.sidebar: st.header("Configuration") n_timepoints = st.slider("Duration (TRs)", 20, 200, 60) tr_seconds = st.slider("TR duration (seconds)", 0.5, 2.0, 1.0, 0.1) seed = st.number_input("Random seed", value=42, min_value=0)
st.subheader("Simulate content type") content_type = st.selectbox( "Content profile", ["Balanced", "Visual-heavy", "Audio-heavy", "Language-heavy", "Low engagement"], )
# --- Generate Data ---roi_indices, n_vertices = make_roi_indices()predictions = generate_brain_predictions(n_timepoints, n_vertices, seed)
# Apply content profile by amplifying relevant ROIsmultipliers = {"Balanced": {}, "Visual-heavy": {}, "Audio-heavy": {}, "Language-heavy": {}, "Low engagement": {}}if content_type == "Visual-heavy": for roi in COGNITIVE_DIMENSIONS["Visual Complexity"]: if roi in roi_indices: predictions[:, roi_indices[roi]] *= 3.0elif content_type == "Audio-heavy": for roi in COGNITIVE_DIMENSIONS["Auditory Demand"]: if roi in roi_indices: predictions[:, roi_indices[roi]] *= 3.0elif content_type == "Language-heavy": for roi in COGNITIVE_DIMENSIONS["Language Processing"]: if roi in roi_indices: predictions[:, roi_indices[roi]] *= 3.0elif content_type == "Low engagement": predictions *= 0.2
# --- Score ---averages, timeline = score_cognitive_load(predictions, roi_indices, tr_seconds)
# --- Display ---col1, col2, col3, col4, col5 = st.columns(5)dims = ["Overall", "Visual Complexity", "Auditory Demand", "Language Processing", "Executive Load"]cols = [col1, col2, col3, col4, col5]for col, dim in zip(cols, dims): val = averages.get(dim, 0.0) col.metric(dim, f"{val:.2f}", delta=None)
st.divider()
# --- Timeline ---st.subheader("Cognitive Load Timeline")timeline_df = pd.DataFrame(timeline)
fig = go.Figure()colors = {"Visual Complexity": "#00D2FF", "Auditory Demand": "#FF6B6B", "Language Processing": "#A29BFE", "Executive Load": "#FFEAA7"}for dim, color in colors.items(): fig.add_trace(go.Scatter( x=timeline_df["time"], y=timeline_df[dim], name=dim, line=dict(color=color, width=2), mode="lines", ))
fig.update_layout( xaxis_title="Time (seconds)", yaxis_title="Cognitive Load (normalized)", yaxis_range=[0, 1.05], height=400, template="plotly_dark", legend=dict(orientation="h", yanchor="bottom", y=1.02),)st.plotly_chart(fig, use_container_width=True)
# --- Dimension Breakdown ---st.divider()col1, col2 = st.columns(2)
with col1: st.subheader("Dimension Breakdown") dim_data = {k: v for k, v in averages.items() if k != "Overall"} fig2 = go.Figure(go.Bar( x=list(dim_data.values()), y=list(dim_data.keys()), orientation="h", marker_color=list(colors.values()), )) fig2.update_layout( xaxis_title="Score", xaxis_range=[0, 1], height=300, template="plotly_dark", ) st.plotly_chart(fig2, use_container_width=True)
with col2: st.subheader("Radar Chart") categories = list(dim_data.keys()) values = list(dim_data.values()) + [list(dim_data.values())[0]] # close the polygon
fig3 = go.Figure(go.Scatterpolar( r=values, theta=categories + [categories[0]], fill="toself", fillcolor="rgba(108, 92, 231, 0.3)", line=dict(color="#6C5CE7"), )) fig3.update_layout( polar=dict(radialaxis=dict(visible=True, range=[0, 1])), height=350, template="plotly_dark", showlegend=False, ) st.plotly_chart(fig3, use_container_width=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Temporal Dynamics page."""
import streamlit as stimport numpy as npimport pandas as pdimport plotly.graph_objects as gofrom plotly.subplots import make_subplots
from utils import ( make_roi_indices, generate_brain_predictions, generate_model_features, peak_latency, temporal_correlation, decompose_response, ROI_GROUPS, ALL_ROIS,)
st.set_page_config(page_title="Temporal Dynamics", page_icon="⏱️", layout="wide")st.title("⏱️ Temporal Dynamics")st.markdown("Analyze how brain responses evolve over time.")
# --- Sidebar ---with st.sidebar: st.header("Configuration") n_timepoints = st.slider("Duration (TRs)", 30, 200, 80) tr_seconds = st.slider("TR duration (seconds)", 0.5, 2.0, 1.0, 0.1) seed = st.number_input("Random seed", value=42, min_value=0)
st.subheader("ROI Selection") selected_group = st.selectbox("Region group", list(ROI_GROUPS.keys())) available_rois = ROI_GROUPS[selected_group] selected_rois = st.multiselect("ROIs to analyze", available_rois, default=available_rois[:3])
max_lag = st.slider("Max correlation lag (TRs)", 5, 30, 15) cutoff = st.slider("Decomposition cutoff (seconds)", 1.0, 10.0, 4.0, 0.5)
if not selected_rois: st.warning("Select at least one ROI.") st.stop()
# --- Generate Data ---roi_indices, n_vertices = make_roi_indices()predictions = generate_brain_predictions(n_timepoints, n_vertices, seed)features = generate_model_features(n_timepoints, 64, seed + 1)
# --- Peak Latency ---st.subheader("Peak Response Latency")latency_data = []for roi in selected_rois: lat = peak_latency(predictions, roi_indices, roi, tr_seconds) latency_data.append({"ROI": roi, "Peak Latency (s)": lat})
lat_df = pd.DataFrame(latency_data)col1, col2 = st.columns([2, 1])
with col1: fig = go.Figure(go.Bar( x=lat_df["ROI"], y=lat_df["Peak Latency (s)"], marker_color="#6C5CE7", )) fig.update_layout( yaxis_title="Time to peak (seconds)", height=350, template="plotly_dark", ) st.plotly_chart(fig, use_container_width=True)
with col2: st.dataframe(lat_df, use_container_width=True, hide_index=True)
# --- Lag Correlation ---st.divider()st.subheader("Temporal Correlation (Brain vs Model Features)")
lags = np.arange(-max_lag, max_lag + 1) * tr_secondsfig2 = go.Figure()colors = ["#00D2FF", "#FF6B6B", "#A29BFE", "#FFEAA7", "#55EFC4", "#FD79A8"]
for i, roi in enumerate(selected_rois): corr = temporal_correlation(predictions, features, roi_indices, roi, max_lag) fig2.add_trace(go.Scatter( x=lags, y=corr, name=roi, line=dict(color=colors[i % len(colors)], width=2), ))
fig2.add_vline(x=0, line_dash="dash", line_color="gray", opacity=0.5)fig2.update_layout( xaxis_title="Lag (seconds)", yaxis_title="Pearson Correlation", height=400, template="plotly_dark", legend=dict(orientation="h", yanchor="bottom", y=1.02),)st.plotly_chart(fig2, use_container_width=True)
# --- Sustained vs Transient ---st.divider()st.subheader("Sustained vs Transient Decomposition")
roi_for_decomp = st.selectbox("ROI for decomposition", selected_rois)sustained, transient = decompose_response(predictions, roi_indices, roi_for_decomp, cutoff, tr_seconds)time_axis = np.arange(len(sustained)) * tr_seconds
fig3 = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.08, subplot_titles=("Sustained Component", "Transient Component"))
fig3.add_trace(go.Scatter(x=time_axis, y=sustained, name="Sustained", line=dict(color="#6C5CE7", width=2)), row=1, col=1)fig3.add_trace(go.Scatter(x=time_axis, y=transient, name="Transient", line=dict(color="#FF6B6B", width=1.5)), row=2, col=1)
fig3.update_xaxes(title_text="Time (seconds)", row=2, col=1)fig3.update_layout(height=500, template="plotly_dark", showlegend=False)st.plotly_chart(fig3, use_container_width=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""ROI Connectivity page."""
import streamlit as stimport numpy as npimport pandas as pdimport plotly.graph_objects as goimport plotly.express as px
from utils import ( make_roi_indices, generate_brain_predictions, compute_connectivity, cluster_rois, graph_metrics, ROI_GROUPS,)
st.set_page_config(page_title="ROI Connectivity", page_icon="🔗", layout="wide")st.title("🔗 ROI Connectivity Analysis")st.markdown("Functional connectivity between brain regions from predicted responses.")
# --- Sidebar ---with st.sidebar: st.header("Configuration") n_timepoints = st.slider("Duration (TRs)", 30, 200, 80) seed = st.number_input("Random seed", value=42, min_value=0) n_clusters = st.slider("Number of clusters", 2, 8, 4) threshold = st.slider("Edge threshold", 0.1, 0.8, 0.3, 0.05)
# --- Generate Data ---roi_indices, n_vertices = make_roi_indices()predictions = generate_brain_predictions(n_timepoints, n_vertices, seed)
# --- Correlation Matrix ---corr_matrix, roi_names = compute_connectivity(predictions, roi_indices)
st.subheader("Correlation Matrix")fig = go.Figure(go.Heatmap( z=corr_matrix, x=roi_names, y=roi_names, colorscale="RdBu_r", zmid=0, zmin=-1, zmax=1, colorbar=dict(title="Correlation"),))fig.update_layout( height=600, width=700, template="plotly_dark", xaxis=dict(tickangle=45, tickfont=dict(size=8)), yaxis=dict(tickfont=dict(size=8)),)st.plotly_chart(fig, use_container_width=True)
# --- Network Clusters ---st.divider()col1, col2 = st.columns(2)
with col1: st.subheader("Functional Network Clusters") clusters, labels = cluster_rois(corr_matrix, roi_names, n_clusters)
cluster_data = [] for cid, rois in sorted(clusters.items()): for roi in rois: cluster_data.append({"Cluster": f"Network {cid}", "ROI": roi})
cluster_df = pd.DataFrame(cluster_data) fig2 = px.bar( cluster_df.groupby("Cluster").size().reset_index(name="Count"), x="Cluster", y="Count", color="Cluster", color_discrete_sequence=px.colors.qualitative.Set2, ) fig2.update_layout(height=350, template="plotly_dark", showlegend=False) st.plotly_chart(fig2, use_container_width=True)
for cid, rois in sorted(clusters.items()): st.markdown(f"**Network {cid}:** {', '.join(rois)}")
with col2: st.subheader("Degree Centrality") degrees = graph_metrics(corr_matrix, roi_names, threshold)
# Sort by degree sorted_degrees = sorted(degrees.items(), key=lambda x: x[1], reverse=True) deg_df = pd.DataFrame(sorted_degrees, columns=["ROI", "Degree Centrality"])
fig3 = go.Figure(go.Bar( x=deg_df["Degree Centrality"], y=deg_df["ROI"], orientation="h", marker_color="#6C5CE7", )) fig3.update_layout( xaxis_title="Degree Centrality", xaxis_range=[0, 1], height=600, template="plotly_dark", yaxis=dict(autorange="reversed", tickfont=dict(size=9)), ) st.plotly_chart(fig3, use_container_width=True)
# --- Network Graph ---st.divider()st.subheader("Network Graph")
try: import networkx as nx
G = nx.Graph() for name in roi_names: G.add_node(name)
for i in range(len(roi_names)): for j in range(i + 1, len(roi_names)): if abs(corr_matrix[i, j]) > threshold: G.add_edge(roi_names[i], roi_names[j], weight=abs(corr_matrix[i, j]))
pos = nx.spring_layout(G, seed=seed, k=2.0)
# Cluster colors color_map = px.colors.qualitative.Set2 node_colors = [color_map[(labels[i] - 1) % len(color_map)] for i in range(len(roi_names))]
edge_x, edge_y = [], [] for u, v in G.edges(): x0, y0 = pos[u] x1, y1 = pos[v] edge_x.extend([x0, x1, None]) edge_y.extend([y0, y1, None])
node_x = [pos[n][0] for n in roi_names] node_y = [pos[n][1] for n in roi_names]
fig4 = go.Figure() fig4.add_trace(go.Scatter( x=edge_x, y=edge_y, mode="lines", line=dict(width=0.5, color="rgba(150,150,150,0.3)"), hoverinfo="none", )) fig4.add_trace(go.Scatter( x=node_x, y=node_y, mode="markers+text", marker=dict(size=12, color=node_colors, line=dict(width=1, color="white")), text=roi_names, textposition="top center", textfont=dict(size=8), hoverinfo="text", )) fig4.update_layout( height=500, template="plotly_dark", showlegend=False, xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False), ) st.plotly_chart(fig4, use_container_width=True)except ImportError: st.info("Install `networkx` for the network graph visualization: `pip install networkx`")12345678streamlit>=1.30plotly>=5.18numpy>=2.0scipy>=1.12pandas>=2.0networkx>=3.2matplotlib>=3.8seaborn>=0.13123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""Shared utilities for the CortexLab dashboard.
Provides synthetic data generation and analysis functions that mirrorCortexLab's API without requiring the full library or GPU."""
import numpy as npfrom scipy.stats import spearmanrfrom scipy.cluster.hierarchy import linkage, fcluster
# --- ROI Definitions ---
ROI_GROUPS = { "Executive": ["46", "9-46d", "8Av", "8Ad", "FEF", "p32pr", "a32pr"], "Visual": ["V1", "V2", "V3", "V4", "MT", "MST", "FFC", "VVC"], "Auditory": ["A1", "LBelt", "MBelt", "PBelt", "A4", "A5"], "Language": ["44", "45", "IFJa", "IFJp", "TPOJ1", "TPOJ2", "STV", "PSL"],}
ALL_ROIS = [roi for group in ROI_GROUPS.values() for roi in group]
def make_roi_indices(n_vertices_per_roi=20): """Create ROI -> vertex index mapping.""" indices = {} offset = 0 for roi in ALL_ROIS: indices[roi] = np.arange(offset, offset + n_vertices_per_roi) offset += n_vertices_per_roi return indices, offset
# --- Brain Alignment ---
def compute_rdm(features): norms = np.linalg.norm(features, axis=1, keepdims=True) norms = np.where(norms > 0, norms, 1.0) normalised = features / norms return 1.0 - normalised @ normalised.T
def rsa_score(model_features, brain_features): rdm_m = compute_rdm(model_features) rdm_b = compute_rdm(brain_features) idx = np.triu_indices(rdm_m.shape[0], k=1) corr, _ = spearmanr(rdm_m[idx], rdm_b[idx]) return float(corr) if not np.isnan(corr) else 0.0
def cka_score(X, Y): n = X.shape[0] X = X - X.mean(axis=0) Y = Y - Y.mean(axis=0) XX = X @ X.T YY = Y @ Y.T hsic_xy = np.trace(XX @ YY) / (n - 1) ** 2 hsic_xx = np.trace(XX @ XX) / (n - 1) ** 2 hsic_yy = np.trace(YY @ YY) / (n - 1) ** 2 denom = np.sqrt(hsic_xx * hsic_yy) return float(hsic_xy / denom) if denom > 1e-12 else 0.0
def procrustes_score(X, Y): min_dim = min(X.shape[1], Y.shape[1]) X, Y = X[:, :min_dim], Y[:, :min_dim] X = X - X.mean(axis=0) Y = Y - Y.mean(axis=0) nx, ny = np.linalg.norm(X), np.linalg.norm(Y) if nx < 1e-12 or ny < 1e-12: return 0.0 X, Y = X / nx, Y / ny U, _, Vt = np.linalg.svd(Y.T @ X, full_matrices=False) rotated = Y @ (U @ Vt) return float(max(0.0, 1.0 - np.linalg.norm(X - rotated)))
ALIGNMENT_METHODS = {"RSA": rsa_score, "CKA": cka_score, "Procrustes": procrustes_score}
def permutation_test(model_feat, brain_pred, method_fn, n_perm=500, seed=42): rng = np.random.default_rng(seed) observed = method_fn(model_feat, brain_pred) count = sum( 1 for _ in range(n_perm) if method_fn(model_feat[rng.permutation(len(model_feat))], brain_pred) >= observed ) return observed, (count + 1) / (n_perm + 1)
# --- Cognitive Load ---
COGNITIVE_DIMENSIONS = { "Executive Load": ["46", "9-46d", "8Av", "8Ad", "FEF", "p32pr", "a32pr"], "Visual Complexity": ["V1", "V2", "V3", "V4", "MT", "MST", "FFC", "VVC"], "Auditory Demand": ["A1", "LBelt", "MBelt", "PBelt", "A4", "A5"], "Language Processing": ["44", "45", "IFJa", "IFJp", "TPOJ1", "TPOJ2", "STV", "PSL"],}
def score_cognitive_load(predictions, roi_indices, tr_seconds=1.0): baseline = max(float(np.median(np.abs(predictions))), 1e-8) timeline = [] dim_scores = {d: [] for d in COGNITIVE_DIMENSIONS}
for t in range(predictions.shape[0]): row = {} for dim, rois in COGNITIVE_DIMENSIONS.items(): vals = [] for roi in rois: if roi in roi_indices: verts = roi_indices[roi] valid = verts[verts < predictions.shape[1]] if len(valid) > 0: vals.append(np.abs(predictions[t, valid]).mean()) score = min(float(np.mean(vals)) / baseline, 1.0) if vals else 0.0 dim_scores[dim].append(score) row[dim] = score row["time"] = t * tr_seconds timeline.append(row)
averages = {d: float(np.mean(v)) for d, v in dim_scores.items()} averages["Overall"] = float(np.mean(list(averages.values()))) return averages, timeline
# --- Temporal Dynamics ---
def peak_latency(predictions, roi_indices, roi_name, tr_seconds=1.0): verts = roi_indices.get(roi_name, np.array([])) valid = verts[verts < predictions.shape[1]] if len(valid) == 0: return 0.0 tc = np.abs(predictions[:, valid]).mean(axis=1) return float(np.argmax(tc) * tr_seconds)
def temporal_correlation(predictions, features, roi_indices, roi_name, max_lag=10): verts = roi_indices.get(roi_name, np.array([])) valid = verts[verts < predictions.shape[1]] if len(valid) == 0: return np.zeros(2 * max_lag + 1) brain_tc = np.abs(predictions[:, valid]).mean(axis=1) model_tc = features.mean(axis=1) if features.ndim > 1 else features n = min(len(brain_tc), len(model_tc)) brain_tc, model_tc = brain_tc[:n], model_tc[:n]
corrs = [] for lag in range(-max_lag, max_lag + 1): if lag >= 0: b, m = brain_tc[lag:], model_tc[:n - lag] else: b, m = brain_tc[:n + lag], model_tc[-lag:] if len(b) < 2: corrs.append(0.0) continue bz, mz = b - b.mean(), m - m.mean() denom = np.sqrt((bz ** 2).sum() * (mz ** 2).sum()) corrs.append(float((bz * mz).sum() / denom) if denom > 1e-12 else 0.0) return np.array(corrs)
def decompose_response(predictions, roi_indices, roi_name, cutoff_seconds=4.0, tr_seconds=1.0): verts = roi_indices.get(roi_name, np.array([])) valid = verts[verts < predictions.shape[1]] if len(valid) == 0: return np.zeros(predictions.shape[0]), np.zeros(predictions.shape[0]) tc = np.abs(predictions[:, valid]).mean(axis=1) window = max(1, int(cutoff_seconds / tr_seconds)) sustained = np.convolve(tc, np.ones(window) / window, mode="same") return sustained, tc - sustained
# --- Connectivity ---
def compute_connectivity(predictions, roi_indices): names = list(roi_indices.keys()) n = len(names) T = predictions.shape[0] timecourses = np.zeros((n, T)) for i, name in enumerate(names): verts = roi_indices[name] valid = verts[verts < predictions.shape[1]] if len(valid) > 0: timecourses[i] = predictions[:, valid].mean(axis=1) corr = np.corrcoef(timecourses) if T >= 2 else np.eye(n) return np.nan_to_num(corr, nan=0.0), names
def cluster_rois(corr_matrix, roi_names, n_clusters=4): n = corr_matrix.shape[0] n_clusters = min(n_clusters, n) dist = 1.0 - np.abs(corr_matrix) np.fill_diagonal(dist, 0.0) condensed = [dist[i, j] for i in range(n) for j in range(i + 1, n)] Z = linkage(condensed, method="average") labels = fcluster(Z, t=n_clusters, criterion="maxclust") clusters = {} for name, cid in zip(roi_names, labels): clusters.setdefault(int(cid), []).append(name) return clusters, labels
def graph_metrics(corr_matrix, roi_names, threshold=0.3): n = corr_matrix.shape[0] adj = (np.abs(corr_matrix) > threshold).astype(float) np.fill_diagonal(adj, 0.0) degree = adj.sum(axis=1) max_d = max(n - 1, 1) return {name: float(degree[i] / max_d) for i, name in enumerate(roi_names)}
# --- Synthetic Data Generators ---
def generate_brain_predictions(n_timepoints=60, n_vertices=580, seed=42): rng = np.random.default_rng(seed) return rng.standard_normal((n_timepoints, n_vertices))
def generate_model_features(n_stimuli=60, feature_dim=512, seed=42): rng = np.random.default_rng(seed) return rng.standard_normal((n_stimuli, feature_dim)).gitignoreAdded+6
.streamlit/config.tomlAdded+9
Home.pyAdded+50
README.mdAdded+28
pages/1_Brain_Alignment.pyAdded+140
pages/2_Cognitive_Load.pyAdded+131
pages/3_Temporal_Dynamics.pyAdded+119
pages/4_Connectivity.pyAdded+162
requirements.txtAdded+8
utils.pyAdded+222