alidenewade commited on
Commit
987ed4f
·
verified ·
1 Parent(s): 161735a

Upload 3 files

Browse files
Files changed (3) hide show
  1. .dockerignore +4 -0
  2. app.py +450 -0
  3. requirements.txt +9 -0
.dockerignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .git/
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
app.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.graph_objects as go
5
+ import plotly.express as px
6
+ from plotly.subplots import make_subplots
7
+ from scipy import stats
8
+ import py3Dmol
9
+ from streamlit.components.v1 import html
10
+ import networkx as nx
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.ensemble import GradientBoostingClassifier
13
+ from sklearn.metrics import classification_report, confusion_matrix
14
+ import shap # Keep import for potential future use or if other parts rely on it, though not used for the direct plot now
15
+ from sklearn.cluster import KMeans
16
+ from sklearn.preprocessing import StandardScaler
17
+ from scipy.integrate import odeint
18
+
19
+ # --- Page Configuration ---
20
+ st.set_page_config(layout="wide", page_title="Computational Biology Analysis")
21
+
22
+ # --- Global Styling ---
23
+ # Define the color scheme
24
+ BACKGROUND_COLOR = 'rgb(28, 28, 28)'
25
+ TEXT_COLOR = 'white'
26
+ ACCENT_COLOR = '#FFA500' # Orange for accents
27
+ PLOT_FACE_COLOR = '#1c1c1c'
28
+
29
+ # Custom CSS for font and dark theme
30
+ st.markdown(f"""
31
+ <style>
32
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
33
+
34
+ html, body, [class*="st-"], .main, .stApp {{
35
+ background-color: {BACKGROUND_COLOR};
36
+ color: {TEXT_COLOR};
37
+ font-family: 'Roboto', 'Funnel Sans', sans-serif;
38
+ }}
39
+ .stTabs [data-baseweb="tab-list"] {{
40
+ gap: 24px;
41
+ }}
42
+ .stTabs [data-baseweb="tab"] {{
43
+ height: 50px;
44
+ white-space: pre-wrap;
45
+ background-color: transparent;
46
+ border-radius: 4px 4px 0px 0px;
47
+ gap: 1px;
48
+ padding-top: 10px;
49
+ padding-bottom: 10px;
50
+ }}
51
+ /* --- FIX STARTS HERE --- */
52
+ .stTabs [aria-selected="true"] {{
53
+ background-color: {PLOT_FACE_COLOR};
54
+ border-bottom: 3px solid {ACCENT_COLOR};
55
+ }}
56
+ /* --- FIX ENDS HERE --- */
57
+ h1, h2, h3, h4, h5, h6 {{
58
+ color: {TEXT_COLOR};
59
+ }}
60
+ .stButton>button {{
61
+ background-color: {ACCENT_COLOR};
62
+ color: black;
63
+ border: none;
64
+ padding: 10px 20px;
65
+ border-radius: 8px;
66
+ }}
67
+ </style>
68
+ """, unsafe_allow_html=True)
69
+
70
+
71
+ # --- Data Generation and Models (from notebook) ---
72
+ @st.cache_data
73
+ def generate_ml_data():
74
+ np.random.seed(42)
75
+ n_samples = 300
76
+ tnf_a = np.concatenate([np.random.normal(95, 10, 100), np.random.normal(155, 15, 100), np.random.normal(145, 15, 100)])
77
+ myhc_ratio = np.concatenate([np.random.normal(1.1, 0.1, 100), np.random.normal(0.8, 0.1, 100), np.random.normal(1.2, 0.1, 100)])
78
+ prob_dysfunction = 1 / (1 + np.exp(-(0.05 * (tnf_a - 150) - 7 * (myhc_ratio - 1.0))))
79
+ systolic_dysfunction = np.random.binomial(1, prob_dysfunction)
80
+ df_ml = pd.DataFrame({'TNF_alpha': tnf_a, 'MyHC_Ratio': myhc_ratio, 'Dysfunction': systolic_dysfunction})
81
+ return df_ml
82
+
83
+ @st.cache_resource
84
+ def train_model(df_ml):
85
+ X = df_ml[['TNF_alpha', 'MyHC_Ratio']]
86
+ y = df_ml['Dysfunction']
87
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
88
+ model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)
89
+ model.fit(X_train, y_train)
90
+ return model, X_train, X_test, y_train, y_test
91
+
92
+ # --- ODE Model for Simulation ---
93
+ def myhc_model_odes(y, t, params):
94
+ k_on, k_off, k_activate_tf, k_tf_bind_myh6, k_tf_unbind_myh6, k_tf_bind_myh7, k_tf_unbind_myh7, k_produce_myh6_base, k_produce_myh6_repressed, k_produce_myh7_base, k_produce_myh7_activated, k_degrade_myhc = params
95
+ TNFa_free, TNFR_free, TNFa_TNFR, TF_inactive, TF_active_free, Gene_myh6_free, Gene_myh6_TF, Gene_myh7_free, Gene_myh7_TF, MyHC_alpha, MyHC_beta = y
96
+ dydt = np.zeros(11)
97
+ dydt[0] = -k_on * TNFa_free * TNFR_free + k_off * TNFa_TNFR
98
+ dydt[1] = -k_on * TNFa_free * TNFR_free + k_off * TNFa_TNFR
99
+ dydt[2] = k_on * TNFa_free * TNFR_free - k_off * TNFa_TNFR
100
+ dydt[3] = -k_activate_tf * TNFa_TNFR * TF_inactive
101
+ dydt[4] = (k_activate_tf * TNFa_TNFR * TF_inactive - k_tf_bind_myh6 * TF_active_free * Gene_myh6_free + k_tf_unbind_myh6 * Gene_myh6_TF - k_tf_bind_myh7 * TF_active_free * Gene_myh7_free + k_tf_unbind_myh7 * Gene_myh7_TF)
102
+ dydt[5] = -k_tf_bind_myh6 * TF_active_free * Gene_myh6_free + k_tf_unbind_myh6 * Gene_myh6_TF
103
+ dydt[6] = k_tf_bind_myh6 * TF_active_free * Gene_myh6_free - k_tf_unbind_myh6 * Gene_myh6_TF
104
+ dydt[7] = -k_tf_bind_myh7 * TF_active_free * Gene_myh7_free + k_tf_unbind_myh7 * Gene_myh7_TF
105
+ dydt[8] = k_tf_bind_myh7 * TF_active_free * Gene_myh7_free - k_tf_unbind_myh7 * Gene_myh7_TF
106
+ dydt[9] = (k_produce_myh6_base * Gene_myh6_free + k_produce_myh6_repressed * Gene_myh6_TF - k_degrade_myhc * MyHC_alpha)
107
+ dydt[10] = (k_produce_myh7_base * Gene_myh7_free + k_produce_myh7_activated * Gene_myh7_TF - k_degrade_myhc * MyHC_beta)
108
+ return dydt
109
+
110
+ @st.cache_data
111
+ def run_ode_simulation():
112
+ params = [1.0, 0.1, 1e-2, 1e-3, 0.5, 1e-3, 0.5, 1e-1, 1e-3, 1e-2, 1e-1, 5e-3]
113
+ y0 = [100, 20, 0, 50, 0, 10, 0, 10, 0, 0, 0]
114
+ t = np.linspace(0, 5000, 1001)
115
+ solution = odeint(myhc_model_odes, y0, t, args=(params,))
116
+ return t, solution
117
+
118
+ # --- Plotting Functions ---
119
+ def render_py3dmol(pdb_id, chain_styles, label_text, label_options, bg_color='0x1c1c1c'):
120
+ view = py3Dmol.view(query=f'pdb:{pdb_id}', width='100%', height=400)
121
+ for chain, style in chain_styles.items():
122
+ view.setStyle({chain: chain}, style)
123
+ view.addLabel(label_text, {'fontColor':'white', 'backgroundColor':'#333333', 'fontSize':16, **label_options.get('style', {})}, label_options.get('position', {}))
124
+ view.setBackgroundColor(bg_color)
125
+ view.zoomTo()
126
+ # Use _make_html() to generate the HTML string for streamlit
127
+ html_string = view._make_html()
128
+ html(html_string, height=400)
129
+
130
+ # --- App Layout ---
131
+ st.title("TNF-α Mediated Cardiac Dysfunction: A Computational Analysis")
132
+ st.markdown("This application explores the findings of Manilall et al. (2023), who investigated how Tumor Necrosis Factor-alpha (TNF-α) mediates early-stage left ventricular (LV) systolic dysfunction. We replicate key findings and enhance the analysis with computational biology tools.")
133
+
134
+ tab1, tab2 = st.tabs(["General Lab / Analysis", "AI & Machine Learning"])
135
+
136
+ # ==============================================================================
137
+ # GENERAL ANALYSIS TAB
138
+ # ==============================================================================
139
+ with tab1:
140
+ st.header("Visual and Systems Biology Analysis")
141
+ st.markdown("---")
142
+
143
+ # --- TNF-α Visualization ---
144
+ with st.container():
145
+ st.subheader("3D Visualization of the Mediator: TNF-α")
146
+ st.write("TNF-α is a cytokine crucial to the immune response. In chronic inflammatory conditions, its elevated levels can have damaging effects. It typically functions as a homotrimer (a complex of three identical protein chains). We visualize the PDB structure 1TNF.")
147
+
148
+ chain_styles_tnf = {
149
+ 'A': {'cartoon': {'color': 'salmon'}},
150
+ 'B': {'cartoon': {'color': 'lightblue'}},
151
+ 'C': {'cartoon': {'color': 'lightgreen'}}
152
+ }
153
+ render_py3dmol('1TNF', chain_styles_tnf, "TNF-α Trimer", {'position': {'resi': 50, 'chain': 'A'}})
154
+ st.markdown("---")
155
+
156
+ # --- Myosin Visualization ---
157
+ with st.container():
158
+ st.subheader("The Molecular Target: Myosin Heavy Chain (MyHC)")
159
+ st.write("The study's central finding is a TNF-α-induced switch from the faster α-MyHC (`Myh6`) to the slower β-MyHC (`Myh7`), impairing heart function. We visualize the human cardiac myosin motor domain (PDB: 5N6A).")
160
+
161
+ # Use st.tabs for Myosin View to allow for active tab styling
162
+ myosin_tab1, myosin_tab2 = st.tabs(["3D Model", "Functional Info"])
163
+
164
+ with myosin_tab1:
165
+ chain_styles_myosin = {
166
+ 'protein': {'cartoon': {'color':'#A9A9A9'}},
167
+ }
168
+ view = py3Dmol.view(query='pdb:5N6A', width='100%', height=450)
169
+ view.setStyle({'cartoon': {'color':'#A9A9A9'}})
170
+ view.addStyle({'resn': 'ADP'}, {'stick': {'colorscheme': 'magentaCarbon'}})
171
+ view.addStyle({'resn': 'MG'}, {'sphere': {'color': 'purple'}})
172
+ view.addLabel("Myosin Motor Domain", {'fontColor':'white', 'backgroundColor':'#333333'}, {'resi': 1, 'chain': 'A'})
173
+ view.addLabel("ADP (Energy)", {'fontColor':'magenta'}, {'resn': 'ADP'})
174
+ view.setBackgroundColor('0x1c1c1c')
175
+ view.zoomTo()
176
+ # Use _make_html() to generate the HTML string for streamlit
177
+ html(view._make_html(), height=450)
178
+
179
+ with myosin_tab2:
180
+ st.info("""
181
+ **α-MyHC (Myh6) Function:** Major contractile protein in the atria. In the ventricle, it is the predominant isoform in small mammals and in fetal human heart but it is replaced by MYH7 after birth. Contributes to cardiac muscle contraction.
182
+
183
+ **β-MyHC (Myh7) Function:** Muscle contraction. The major contractile protein in the ventricular myocardium.
184
+ """)
185
+ st.markdown("---")
186
+
187
+ # --- Heatmap ---
188
+ with st.container():
189
+ st.subheader("Integrated Heatmap of Key Study Findings")
190
+ st.write("A heatmap consolidating data on inflammation, cardiac function, and gene expression. The anti-TNF-α treatment clearly reverses the pathological changes seen in the CIA group.")
191
+
192
+ data = {
193
+ 'Circulating TNF-α (pg/mL)': [93.9, 155.8, 145.6],
194
+ 'Global Longitudinal Strain (%)': [-19.6, -16.7, -19.0],
195
+ 'Myh6 mRNA (α-MyHC)': [1.03, 0.89, 1.11],
196
+ 'Myh7 mRNA (β-MyHC)': [0.96, 1.25, 0.91],
197
+ 'Myh6/Myh7 Ratio': [1.13, 0.79, 1.24],
198
+ 'IL-6 mRNA': [0.79, 1.65, 1.15]
199
+ }
200
+ df_heatmap = pd.DataFrame(data, index=['Control', 'CIA', 'CIA+anti-TNF-α'])
201
+ df_normalized = (df_heatmap - df_heatmap.mean()) / df_heatmap.std()
202
+
203
+ fig_heatmap = px.imshow(df_normalized.T,
204
+ text_auto=True,
205
+ aspect="auto",
206
+ color_continuous_scale='RdBu_r', # Red-Blue reversed for coolwarm effect
207
+ labels=dict(x="Experimental Group", y="Parameter", color="Normalized Value"),
208
+ x=df_heatmap.index,
209
+ y=df_heatmap.columns)
210
+
211
+ fig_heatmap.update_layout(
212
+ title_text='Integrated Heatmap of Key Study Findings',
213
+ title_x=0.5,
214
+ height=600,
215
+ xaxis_title='Experimental Group',
216
+ yaxis_title='Parameter',
217
+ paper_bgcolor=BACKGROUND_COLOR,
218
+ plot_bgcolor=PLOT_FACE_COLOR,
219
+ font=dict(color=TEXT_COLOR),
220
+ coloraxis_colorbar=dict(title="Normalized Value", thicknessmode="pixels", thickness=20, lenmode="pixels", len=300)
221
+ )
222
+ # Add original values as text on hover
223
+ fig_heatmap.update_traces(text=df_heatmap.T.values.round(2), texttemplate="%{text}", hovertemplate="<b>%{y}</b><br>Group: %{x}<br>Value: %{text}<extra></extra>")
224
+
225
+ st.plotly_chart(fig_heatmap, use_container_width=True)
226
+ st.markdown("---")
227
+
228
+ # --- Pathway Simulation ---
229
+ with st.container():
230
+ st.subheader("Simulating the TNF-α Signaling Pathway")
231
+ st.write("A simplified computational model to simulate the paper's central hypothesis: increased TNF-α leads to a decrease in the Myh6/Myh7 ratio over time.")
232
+
233
+ t, solution = run_ode_simulation()
234
+ MyHC_alpha = solution[:, 9]
235
+ MyHC_beta = solution[:, 10]
236
+ TF_active_total = solution[:, 4] + solution[:, 6] + solution[:, 8]
237
+
238
+ # Create subplots
239
+ fig_sim = make_subplots(rows=2, cols=1,
240
+ shared_xaxes=True,
241
+ vertical_spacing=0.1,
242
+ subplot_titles=("Simulated MyHC Isoform Switch Induced by TNF-α", "Transcription Factor Dynamics"))
243
+
244
+ # MyHC Isoform Switch plot (top subplot)
245
+ fig_sim.add_trace(go.Scatter(x=t, y=MyHC_alpha, mode='lines', name='α-MyHC (Myh6)',
246
+ line=dict(color='blue', width=2)),
247
+ row=1, col=1)
248
+ fig_sim.add_trace(go.Scatter(x=t, y=MyHC_beta, mode='lines', name='β-MyHC (Myh7)',
249
+ line=dict(color='red', width=2, dash='dash')),
250
+ row=1, col=1)
251
+ fig_sim.update_yaxes(title_text='MyHC Protein Level (Arbitrary Units)', row=1, col=1)
252
+ fig_sim.update_xaxes(title_text='Time (Arbitrary Units)', row=1, col=1, showticklabels=False) # Hide x-axis labels on top plot
253
+
254
+ # Transcription Factor Dynamics subplot (bottom subplot)
255
+ fig_sim.add_trace(go.Scatter(x=t, y=solution[:, 2], mode='lines', name='TNF-α:TNFR Complex',
256
+ line=dict(color='green', width=2)),
257
+ row=2, col=1)
258
+ fig_sim.add_trace(go.Scatter(x=t, y=TF_active_total, mode='lines', name='Active TF (Total)',
259
+ line=dict(color='orange', width=2)),
260
+ row=2, col=1)
261
+ fig_sim.update_yaxes(title_text='Concentration (Arbitrary Units)', row=2, col=1)
262
+ fig_sim.update_xaxes(title_text='Time (Arbitrary Units)', row=2, col=1)
263
+
264
+ fig_sim.update_layout(
265
+ height=700, # Increased height to accommodate two distinct plots
266
+ paper_bgcolor=BACKGROUND_COLOR,
267
+ plot_bgcolor=PLOT_FACE_COLOR,
268
+ font=dict(color=TEXT_COLOR),
269
+ legend=dict(x=1.02, y=1, yanchor="top", xanchor="left", bgcolor='rgba(0,0,0,0)'), # Consolidated legend
270
+ margin=dict(l=40, r=40, t=80, b=40)
271
+ )
272
+
273
+ st.plotly_chart(fig_sim, use_container_width=True)
274
+ st.markdown("---")
275
+
276
+ # --- Network Analysis ---
277
+ with st.container():
278
+ st.subheader("Network Analysis of Pathological Relationships")
279
+ st.write("A high-level overview of the proposed pathophysiology, from inflammation to systolic dysfunction.")
280
+
281
+ G = nx.DiGraph()
282
+ nodes_data = [
283
+ ("Systemic Inflammation\n(CIA Model)", 'red', 3500, 0.0), ("↑ Circulating TNF-α", 'orange', 3500, 0.5),
284
+ ("↓ Myh6/Myh7 Ratio", 'purple', 3500, 0.5), ("Impaired Systolic Function\n(↓ Strain & Velocity)", 'darkred', 4000, -0.5),
285
+ ("↑ IL-6 Expression", 'gold', 3000, 0.5), ("Anti-TNF-α\nTreatment", 'green', 3000, 1.0)
286
+ ]
287
+ for name, color, size, z in nodes_data:
288
+ G.add_node(name, color=color, size=size, z=z)
289
+ G.add_edge("Systemic Inflammation\n(CIA Model)", "↑ Circulating TNF-α")
290
+ G.add_edge("↑ Circulating TNF-α", "↓ Myh6/Myh7 Ratio", label="mediates")
291
+ G.add_edge("↑ Circulating TNF-α", "↑ IL-6 Expression", label="mediates")
292
+ G.add_edge("↓ Myh6/Myh7 Ratio", "Impaired Systolic Function\n(↓ Strain & Velocity)", label="underlies")
293
+ G.add_edge("Anti-TNF-α\nTreatment", "↓ Myh6/Myh7 Ratio", label="prevents", type='inhibit')
294
+ G.add_edge("Anti-TNF-α\nTreatment", "Impaired Systolic Function\n(↓ Strain & Velocity)", label="prevents", type='inhibit')
295
+
296
+
297
+ pos_2d = nx.spring_layout(G, k=1.8, seed=42)
298
+ node_trace = go.Scatter3d(
299
+ x=[pos_2d[node][0] for node in G.nodes()], y=[pos_2d[node][1] for node in G.nodes()], z=[G.nodes[node]['z'] for node in G.nodes()],
300
+ mode='markers+text',
301
+ marker=dict(size=[G.nodes[node]['size']/300 for node in G.nodes()], color=[G.nodes[node]['color'] for node in G.nodes()], opacity=0.9),
302
+ text=list(G.nodes()), textposition="top center", textfont=dict(size=10, color=TEXT_COLOR), name="Nodes"
303
+ )
304
+ edge_traces = []
305
+ for edge in G.edges():
306
+ x0, y0 = pos_2d[edge[0]]; x1, y1 = pos_2d[edge[1]]
307
+ z0, z1 = G.nodes[edge[0]]['z'], G.nodes[edge[1]]['z']
308
+ color = 'green' if G.edges[edge].get('type') == 'inhibit' else TEXT_COLOR
309
+ dash = 'dash' if G.edges[edge].get('type') == 'inhibit' else 'solid'
310
+ edge_trace = go.Scatter3d(x=[x0, x1, None], y=[y0, y1, None], z=[z0, z1, None], mode='lines', line=dict(color=color, width=4, dash=dash), showlegend=False)
311
+ edge_traces.append(edge_trace)
312
+
313
+ fig_3d = go.Figure(data=[node_trace] + edge_traces)
314
+ fig_3d.update_layout(
315
+ title="Interactive 3D Network",
316
+ height=600,
317
+ scene=dict(xaxis_title="X", yaxis_title="Y", zaxis_title="Hierarchy",
318
+ xaxis=dict(showbackground=False, visible=False),
319
+ yaxis=dict(showbackground=False, visible=False),
320
+ zaxis=dict(showbackground=False, visible=False)),
321
+ paper_bgcolor=BACKGROUND_COLOR,
322
+ plot_bgcolor=BACKGROUND_COLOR,
323
+ font=dict(color=TEXT_COLOR),
324
+ showlegend=False,
325
+ margin=dict(l=0, r=0, b=0, t=40)
326
+ )
327
+
328
+ st.plotly_chart(fig_3d, use_container_width=True)
329
+
330
+
331
+ # ==============================================================================
332
+ # AI & ML TAB
333
+ # ==============================================================================
334
+ with tab2:
335
+ st.header("AI & Machine Learning Insights")
336
+ st.markdown("---")
337
+
338
+ df_ml = generate_ml_data()
339
+ model, X_train, X_test, y_train, y_test = train_model(df_ml)
340
+
341
+ # --- Predictive Modeling ---
342
+ with st.container():
343
+ st.subheader("Predictive Modeling: Can Biomarkers Predict Dysfunction?")
344
+ st.write("We train a Gradient Boosting model to predict systolic dysfunction based on TNF-α levels and the Myh6/Myh7 ratio. Below is the model's performance on the test dataset.")
345
+
346
+ y_pred = model.predict(X_test)
347
+
348
+ col1, col2 = st.columns(2)
349
+ with col1:
350
+ st.text("Classification Report")
351
+ report = classification_report(y_test, y_pred, target_names=['Normal', 'Dysfunction'], output_dict=True)
352
+ st.dataframe(pd.DataFrame(report).transpose())
353
+
354
+ with col2:
355
+ cm = confusion_matrix(y_test, y_pred, labels=model.classes_)
356
+ fig_cm = px.imshow(cm,
357
+ text_auto=True,
358
+ labels=dict(x="Predicted", y="True", color="Count"),
359
+ x=['Normal', 'Dysfunction'],
360
+ y=['Normal', 'Dysfunction'],
361
+ color_continuous_scale='Blues')
362
+
363
+ fig_cm.update_layout(
364
+ title_text='Confusion Matrix',
365
+ title_x=0.5,
366
+ xaxis_title="Predicted Label",
367
+ yaxis_title="True Label",
368
+ paper_bgcolor=BACKGROUND_COLOR,
369
+ plot_bgcolor=PLOT_FACE_COLOR,
370
+ font=dict(color=TEXT_COLOR)
371
+ )
372
+ st.plotly_chart(fig_cm, use_container_width=True)
373
+ st.markdown("---")
374
+
375
+ # --- Explainable AI (XAI) ---
376
+ with st.container():
377
+ st.subheader("Traditional Feature Importance")
378
+ st.write("Here, we visualize the importance of each feature as determined by the Gradient Boosting model. Features with higher importance contribute more significantly to the model's predictions.")
379
+
380
+ # Get feature importances
381
+ feature_importances = pd.DataFrame({
382
+ 'Feature': X_train.columns,
383
+ 'Importance': model.feature_importances_
384
+ }).sort_values('Importance', ascending=False)
385
+
386
+ # Create bar chart for feature importance
387
+ fig_importance = px.bar(feature_importances,
388
+ x='Importance',
389
+ y='Feature',
390
+ orientation='h',
391
+ title='Feature Importance from Gradient Boosting Model',
392
+ color_discrete_sequence=[ACCENT_COLOR]) # Use ACCENT_COLOR for bars
393
+
394
+ fig_importance.update_layout(
395
+ paper_bgcolor=BACKGROUND_COLOR,
396
+ plot_bgcolor=PLOT_FACE_COLOR,
397
+ font=dict(color=TEXT_COLOR),
398
+ xaxis_title='Importance',
399
+ yaxis_title='Feature',
400
+ yaxis={'categoryorder':'total ascending'} # Ensure the most important features are at the top
401
+ )
402
+
403
+ st.plotly_chart(fig_importance, use_container_width=True)
404
+
405
+ st.markdown("---")
406
+ # --- Clustering ---
407
+ with st.container():
408
+ st.subheader("Unsupervised Learning: Identifying Patient Subgroups")
409
+ st.write("K-Means clustering can identify natural groupings in the data without predefined labels. This technique could help discover patient subgroups in a real clinical dataset. The clusters found here align well with the original experimental groups (Control, CIA, Treated).")
410
+
411
+ X_cluster = df_ml[['TNF_alpha', 'MyHC_Ratio']]
412
+ scaler = StandardScaler()
413
+ X_scaled = scaler.fit_transform(X_cluster)
414
+ kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
415
+ df_ml['Cluster'] = kmeans.fit_predict(X_scaled).astype(str) # Convert to string for discrete colors
416
+
417
+ centroids = scaler.inverse_transform(kmeans.cluster_centers_)
418
+ centroids_df = pd.DataFrame(centroids, columns=['TNF_alpha', 'MyHC_Ratio'])
419
+ centroids_df['Cluster'] = ['Centroid 0', 'Centroid 1', 'Centroid 2'] # Label centroids
420
+
421
+ fig_cluster = px.scatter(
422
+ df_ml, x='TNF_alpha', y='MyHC_Ratio', color='Cluster',
423
+ color_discrete_sequence=px.colors.qualitative.Vivid, # Viridis like qualitative palette
424
+ title='K-Means Clustering of Biomarker Data',
425
+ labels={'TNF_alpha': 'Circulating TNF-α (pg/mL)', 'MyHC_Ratio': 'Myh6/Myh7 Ratio'}
426
+ )
427
+
428
+ fig_cluster.add_trace(
429
+ go.Scatter(
430
+ x=centroids_df['TNF_alpha'],
431
+ y=centroids_df['MyHC_Ratio'],
432
+ mode='markers',
433
+ marker=dict(symbol='x', size=15, color='red', line=dict(width=2, color='darkred')),
434
+ name='Centroids',
435
+ showlegend=True
436
+ )
437
+ )
438
+
439
+ # Make the plot square
440
+ fig_cluster.update_layout(
441
+ paper_bgcolor=BACKGROUND_COLOR,
442
+ plot_bgcolor=PLOT_FACE_COLOR,
443
+ font=dict(color=TEXT_COLOR),
444
+ xaxis_title='Circulating TNF-α (pg/mL)',
445
+ yaxis_title='Myh6/Myh7 Ratio',
446
+ height=600, # Set height to be equal to width for a square appearance
447
+ width=600, # Set width explicitly for square appearance
448
+ showlegend=True
449
+ )
450
+ st.plotly_chart(fig_cluster, use_container_width=True)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ plotly
5
+ scipy
6
+ py3Dmol
7
+ networkx
8
+ scikit-learn
9
+ shap