-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
412 lines (345 loc) · 19.6 KB
/
app.py
File metadata and controls
412 lines (345 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import streamlit as st
import os
import time
import MDAnalysis as mda
from src.standard_analyses import process_standard_analyses
from src.pca_analysis import run_pca_analysis
from src.dccm_analysis import run_dccm_analysis
from src.trajectory_visualizer import (extract_frames, visualize_complex,
create_video_from_frames, create_slow_motion)
# Streamlit App UI
def main():
try:
# Place icon + title in one row
col1, col2 = st.columns([2, 8])
with col1:
st.image("icon/complex.png", width=150)
with col2:
st.markdown("<h1 style='text-align: left;'>Dynamics<br>Visualizer</h1>", unsafe_allow_html=True)
st.markdown("""
Comprehensive post-MD analyses visualizations for GROMACS trajectories.
""")
# Initialize session state
if 'analysis_mode' not in st.session_state:
st.session_state.analysis_mode = None
if 'proceed' not in st.session_state:
st.session_state.proceed = False
if 'proceed_stage' not in st.session_state:
st.session_state.proceed_stage = False
if 'workflow_type' not in st.session_state:
st.session_state.workflow_type = None
if 'traj_path' not in st.session_state:
st.session_state.traj_path = None
if 'top_path' not in st.session_state:
st.session_state.top_path = None
if 'protein_chain' not in st.session_state:
st.session_state.protein_chain = None
if 'lig_resname' not in st.session_state:
st.session_state.lig_resname = None
if 'vis_type' not in st.session_state:
st.session_state.vis_type = None
if 'output_folder' not in st.session_state:
st.session_state.output_folder = None
if 'frames_dir' not in st.session_state:
st.session_state.frames_dir = None
# Step 1: Analysis mode selection
with st.form("analysis_mode_selection"):
st.subheader("1. Select Analysis Mode")
analysis_mode = st.radio(
"Choose analysis mode:",
[
"Standard Analyses (RMSD, RMSF, SASA, Rg, PL-Dist)",
"Principal Component Analysis (PCA)",
"Dynamic Cross-Correlation Matrix (DCCM)",
"Trajectory Visualizer"
],
index=0
)
proceed = st.form_submit_button("Proceed")
if proceed:
st.session_state.analysis_mode = analysis_mode
st.session_state.proceed = True
# Reset proceed_stage when starting a new analysis
st.session_state.proceed_stage = False
if not st.session_state.proceed:
return
# Step 2: Input parameters
st.subheader("2. Configure Analysis")
# TRAJECTORY VISUALIZER SECTION - COMPLETELY RESTRUCTURED
if "Trajectory Visualizer" in st.session_state.analysis_mode:
# Workflow selection at the top
workflow_type = st.radio(
"Select workflow:",
["Extract Frames and Generate MD video", "Generate MD video from existing frames"],
index=0
)
# Reset proceed stage when workflow changes
if 'last_workflow' not in st.session_state or st.session_state.last_workflow != workflow_type:
st.session_state.proceed_stage = False
st.session_state.last_workflow = workflow_type
# EXTRACTION WORKFLOW (Protein-only and Protein-ligand)
if workflow_type == "Extract Frames and Generate MD video":
# Visualization type selection
vis_type = st.radio(
"Select visualization type:",
["Protein-only trajectory", "Protein-ligand complex trajectory"],
index=0
)
# First stage form - only for extraction workflow
with st.form("extraction_config"):
# File inputs
traj_path = st.text_input("Trajectory file path (.xtc)", "trajectory.xtc")
top_path = st.text_input("Input run file path (.tpr)", "input.tpr")
protein_chain = st.text_input("Protein chain ID (e.g., A)", "A")
# Ligand input only for complex
lig_resname = None
if vis_type == "Protein-ligand complex trajectory":
lig_input = st.text_input("Ligand residue name (e.g., LIG/UNK/UNL)", "LIG")
lig_resname = lig_input.split()
output_folder = st.text_input("Output directory", "analysis_results")
proceed = st.form_submit_button("Proceed")
# Save state on proceed
if proceed:
st.session_state.proceed_stage = True
st.session_state.traj_path = traj_path
st.session_state.top_path = top_path
st.session_state.protein_chain = protein_chain
st.session_state.lig_resname = lig_resname
st.session_state.vis_type = vis_type
st.session_state.output_folder = output_folder
# Show second stage after proceed
if st.session_state.get("proceed_stage", False):
# Validate inputs
traj_path = st.session_state.traj_path
top_path = st.session_state.top_path
if not os.path.exists(traj_path):
st.error("❌ Trajectory file not found!")
st.stop()
if not os.path.exists(top_path):
st.error("❌ Input run file not found!")
st.stop()
try:
universe = mda.Universe(top_path, traj_path)
total_frames = len(universe.trajectory)
st.info(f"Trajectory contains {total_frames} frames")
except Exception as e:
st.error(f"❌ Error loading trajectory: {str(e)}")
st.stop()
# Second stage form
with st.form("extraction_visual_config"):
n_extract = st.number_input(
"Number of frames to extract:",
min_value=1,
max_value=total_frames,
value=min(500, total_frames),
step=10
)
width = st.number_input("Image width", min_value=500, max_value=5000, value=800, step=100)
height = st.number_input("Image height", min_value=500, max_value=5000, value=600, step=100)
dpi = st.number_input("Image DPI", min_value=100, max_value=1200, value=300, step=100)
fps = st.number_input("Video FPS", min_value=10, max_value=125, value=30, step=5)
visualize = st.form_submit_button("Run Trajectory Visualization")
# Run visualization when submitted
if visualize:
# Create output directories
output_folder = st.session_state.output_folder
os.makedirs(output_folder, exist_ok=True)
# Extract frames
with st.spinner("📂 Extracting frames..."):
pdb_dir, n_extracted = extract_frames(
top_path, traj_path, output_folder, n_extract,
st.session_state.protein_chain, st.session_state.lig_resname
)
if not pdb_dir:
st.stop()
# Create PNG output directory
png_dir = os.path.join(output_folder, "png_frames")
os.makedirs(png_dir, exist_ok=True)
# Generate visualizations
with st.spinner("🎨 Generating visualizations..."):
pdb_files = sorted(
[f for f in os.listdir(pdb_dir) if f.endswith(".pdb")],
key=lambda x: int(x.split("_")[1].split(".")[0])
)
progress_bar = st.progress(0)
for i, pdb_file in enumerate(pdb_files):
input_pdb = os.path.join(pdb_dir, pdb_file)
output_png = os.path.join(png_dir, f"frame_{i}.png")
visualize_complex(
input_pdb, output_png, width, height, dpi,
st.session_state.protein_chain, st.session_state.lig_resname
)
progress_bar.progress((i + 1) / len(pdb_files))
progress_bar.empty()
# Create videos
with st.spinner("🎬 Creating videos..."):
base_video = os.path.join(output_folder, "md-trajectory.mp4")
if create_video_from_frames(png_dir, base_video, fps):
st.success("✅ Base video created")
slow_video = os.path.join(output_folder, "smooth-md_motion.mp4")
if create_slow_motion(base_video, slow_video):
st.success("✅ Smooth trajectory video created")
st.success("🎥 Trajectory visualization complete!")
st.balloons()
# VIDEO-ONLY WORKFLOW
else:
with st.form("video_only_config"):
st.subheader("Generate Video from Existing Frames")
# Required inputs
frames_dir = st.text_input("Path to PNG frames directory", "png_frames")
fps = st.number_input("Video FPS", min_value=10, max_value=125, value=30, step=5)
output_folder = st.text_input("Output directory", "analysis_results")
visualize = st.form_submit_button("Run Trajectory Visualization")
# Run visualization when submitted
if visualize:
# Validate inputs
if not frames_dir:
st.error("❌ Please enter a path to PNG frames directory")
st.stop()
if not os.path.exists(frames_dir):
st.error(f"❌ Frames directory not found: {frames_dir}")
st.stop()
if not output_folder:
st.error("❌ Please enter an output directory")
st.stop()
# Create output directory
os.makedirs(output_folder, exist_ok=True)
# Create videos
with st.spinner("🎬 Creating videos..."):
base_video = os.path.join(output_folder, "molecular_dynamics.mp4")
if create_video_from_frames(frames_dir, base_video, fps):
st.success("✅ Base video created")
slow_video = os.path.join(output_folder, "smooth-md_motion.mp4")
if create_slow_motion(base_video, slow_video):
st.success("✅ Smooth trajectory video created")
st.success("🎥 Trajectory visualization complete!")
st.balloons()
# PCA ANALYSIS SECTION
elif "PCA" in st.session_state.analysis_mode:
# First ask for PCA type
pca_type = st.radio(
"Select PCA analysis type:",
["Protein-only PCA", "Protein-ligand complex PCA"],
index=0
)
# PCA-specific configuration
with st.form("pca_config"):
# Then ask for file paths
traj_path = st.text_input("Trajectory file path (.xtc)", "trajectory.xtc")
top_path = st.text_input("Input run file/pdb file path (.tpr or .pdb)", "input.tpr")
# Show ligand residue name ONLY when complex PCA is selected
lig_resname = None
if pca_type == "Protein-ligand complex PCA":
lig_resname = st.text_input("Ligand residue name (e.g., LIG/UNK/UNL)", "LIG")
output_folder = st.text_input("Output directory", "analysis_results")
visualize = st.form_submit_button("Run PCA Analysis")
if visualize:
# Validate inputs
if not os.path.exists(traj_path):
st.error("❌ Trajectory file not found!")
return
if not os.path.exists(top_path):
st.error("❌ Input run file/pdb file not found!")
return
if pca_type == "Protein-ligand complex PCA" and (not lig_resname or not lig_resname.strip()):
st.error("❌ Please provide a valid ligand residue name for protein-ligand complex PCA.")
return
# Run PCA analysis
with st.spinner("🔬 Performing PCA analysis..."):
image_paths = run_pca_analysis(
top_path,
traj_path,
output_folder,
"protein" if pca_type == "Protein-only PCA" else "complex",
lig_resname
)
if image_paths:
st.success("✅ PCA analysis completed successfully!")
st.subheader("📊 PCA Results")
cols = st.columns(3)
for idx, img_path in enumerate(image_paths):
with cols[idx % 3]:
st.image(img_path, caption=os.path.basename(img_path), use_container_width=True)
st.balloons()
else:
st.error("❌ No figures were generated from PCA analysis")
# DCCM ANALYSIS SECTION
elif "DCCM" in st.session_state.analysis_mode:
dccm_type = st.radio(
"Select DCCM analysis type:",
["Protein-only DCCM", "Protein-ligand complex DCCM"],
index=0
)
with st.form("dccm_config"):
traj_path = st.text_input("Trajectory file path (.xtc)", "trajectory.xtc")
top_path = st.text_input("Input run file/pdb file path (.tpr or .pdb)", "input.tpr")
# Show ligand residue name only for complex DCCM
lig_resname = None
if dccm_type == "Protein-ligand complex DCCM":
lig_resname = st.text_input("Ligand residue name (e.g., LIG/UNK/UNL)", "LIG")
output_folder = st.text_input("Output directory", "analysis_results")
visualize = st.form_submit_button("Run DCCM Analysis")
if visualize:
# Validate inputs
if not os.path.exists(traj_path):
st.error("❌ Trajectory file not found!")
return
if not os.path.exists(top_path):
st.error("❌ Input run file/pdb file not found!")
return
if dccm_type == "Protein-ligand complex DCCM" and (not lig_resname or not lig_resname.strip()):
st.error("❌ Please provide a valid ligand residue name for protein-ligand complex DCCM.")
return
# Run DCCM analysis
with st.spinner("🔬 Performing DCCM analysis..."):
image_paths = run_dccm_analysis(
top_path,
traj_path,
output_folder,
"protein" if dccm_type == "Protein-only DCCM" else "complex",
lig_resname
)
if image_paths:
st.success("✅ DCCM analysis completed successfully!")
# Display DCCM plot
st.subheader("📊 DCCM Results")
cols = st.columns(2)
for idx, img_path in enumerate(image_paths):
with cols[idx % 2]: # cycle through columns
st.image(img_path, caption=os.path.basename(img_path), use_container_width=True)
st.balloons()
else:
st.error("❌ No figures were generated from DCCM analysis")
# STANDARD ANALYSES SECTION
else:
# Standard analyses configuration
with st.form("input_config"):
main_input_dir = st.text_input("Main input directory", "md_analysis")
main_output_dir = st.text_input("Main output directory", "analysis_results")
visualize = st.form_submit_button("🚀 Run Visualizations")
if visualize:
# Create output directory
os.makedirs(main_output_dir, exist_ok=True)
# Start processing
start_time = time.time()
with st.spinner("🔬 Processing analyses..."):
analysis_results = process_standard_analyses(main_input_dir, main_output_dir)
# Show completion message
total_time = time.time() - start_time
st.success(f"✅ Analysis completed in {total_time:.2f} seconds")
if analysis_results:
# Display plots in small sizes
st.subheader("📊 Analysis Results")
cols = st.columns(4)
for idx, (analysis_type, plot_path) in enumerate(analysis_results):
with cols[idx % 4]:
st.subheader(analysis_type.upper())
st.image(plot_path, use_container_width=True)
st.balloons()
else:
st.warning("⚠️ No analysis results were generated")
except Exception as e:
st.error(f"❌ Critical error: {str(e)}")
st.exception(e)
if __name__ == "__main__":
main()