Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,103 +2,71 @@ import os
|
|
| 2 |
import re
|
| 3 |
import numpy as np
|
| 4 |
import gradio as gr
|
| 5 |
-
from ase.io import read
|
| 6 |
from ase.io.trajectory import Trajectory
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
coords = atoms.get_positions()
|
| 15 |
-
parts = [str(len(symbols)), "frame"]
|
| 16 |
-
for s, (x, y, z) in zip(symbols, coords):
|
| 17 |
-
parts.append(f"{s} {x:.6f} {y:.6f} {z:.6f}")
|
| 18 |
-
return "\n".join(parts)
|
| 19 |
-
|
| 20 |
-
def structure_to_html(file_path, width=520, height=520):
|
| 21 |
-
"""Renderiza estructura única en 3Dmol.js sin correr cálculos."""
|
| 22 |
-
if not file_path or not os.path.exists(file_path):
|
| 23 |
-
return "<div style='color:#b00; padding:20px;'>No structure file found</div>"
|
| 24 |
-
try:
|
| 25 |
-
atoms = read(file_path)
|
| 26 |
-
except Exception as e:
|
| 27 |
-
return f"<div style='color:#b00; padding:20px;'>Error reading structure: {e}</div>"
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
return f"""
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
const
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
s.onload=ok; document.head.appendChild(s);
|
| 42 |
-
}};
|
| 43 |
-
_load3Dmol(() => {{
|
| 44 |
-
const el=document.getElementById("{viewer_id}");
|
| 45 |
-
if(!el||typeof $3Dmol==='undefined') return;
|
| 46 |
-
const v=$3Dmol.createViewer(el, {{backgroundColor:'white'}});
|
| 47 |
-
v.addModel(`{xyz_block}`, "xyz");
|
| 48 |
-
v.setStyle({{}}, {{stick:{{}}, sphere:{{}}}});
|
| 49 |
-
v.zoomTo(); v.render();
|
| 50 |
-
}});
|
| 51 |
-
</script>
|
| 52 |
"""
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def traj_to_html(traj_path, width=520, height=520, interval_ms=200):
|
| 55 |
-
"""Animación 3Dmol.js desde .traj de ASE."""
|
| 56 |
if not traj_path or not os.path.exists(traj_path):
|
| 57 |
-
return "<div style='color:#b00;
|
| 58 |
try:
|
| 59 |
traj = Trajectory(traj_path)
|
| 60 |
-
if len(traj)
|
| 61 |
-
return "<div style='color:#555;
|
| 62 |
except Exception as e:
|
| 63 |
-
return f"<div style='color:#b00;
|
| 64 |
|
| 65 |
frames = [_atoms_to_xyz_block(at) for at in traj]
|
| 66 |
frames_json = str(frames).replace("'", '"')
|
| 67 |
-
viewer_id = f"viewer_{abs(hash(traj_path))
|
|
|
|
| 68 |
return f"""
|
| 69 |
-
<div style="margin-bottom:10px;
|
| 70 |
<strong>🧬 3D Molecular Viewer</strong> — {len(frames)} frames
|
| 71 |
</div>
|
| 72 |
-
<div id="{viewer_id}" style="width:{width}px;
|
| 73 |
<script>
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
}};
|
| 80 |
-
_load3Dmol(() => {{
|
| 81 |
-
const el=document.getElementById("{viewer_id}");
|
| 82 |
-
if(!el||typeof $3Dmol==='undefined') return;
|
| 83 |
-
const v=$3Dmol.createViewer(el, {{backgroundColor:'white'}});
|
| 84 |
-
const frames={frames_json};
|
| 85 |
-
let idx=0;
|
| 86 |
-
function draw(i){{
|
| 87 |
-
v.clear(); v.addModel(frames[i], "xyz");
|
| 88 |
-
v.setStyle({{}}, {{stick:{{}}, sphere:{{}}}});
|
| 89 |
-
v.zoomTo(); v.render();
|
| 90 |
-
}}
|
| 91 |
draw(0);
|
| 92 |
-
if(frames.length>1){{
|
| 93 |
-
setInterval(()=>{{ idx=(idx+1)%frames.length; draw(idx); }}, {interval_ms});
|
| 94 |
-
}}
|
| 95 |
}});
|
| 96 |
</script>
|
| 97 |
"""
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
# OrbMol (SPE)
|
| 101 |
-
# =========================
|
| 102 |
from orb_models.forcefield import pretrained
|
| 103 |
from orb_models.forcefield.calculator import ORBCalculator
|
| 104 |
|
|
@@ -111,13 +79,15 @@ def _load_orbmol_calc():
|
|
| 111 |
return _MODEL_CALC
|
| 112 |
|
| 113 |
def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
| 114 |
-
"""
|
|
|
|
|
|
|
| 115 |
try:
|
| 116 |
calc = _load_orbmol_calc()
|
| 117 |
if not structure_file:
|
| 118 |
return "Error: Please upload a structure file", "Error"
|
| 119 |
-
file_path = structure_file # gr.File(type='filepath') -> str
|
| 120 |
|
|
|
|
| 121 |
if not os.path.exists(file_path):
|
| 122 |
return f"Error: File not found: {file_path}", "Error"
|
| 123 |
if os.path.getsize(file_path) == 0:
|
|
@@ -131,62 +101,28 @@ def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
|
| 131 |
forces = atoms.get_forces() # eV/Å
|
| 132 |
|
| 133 |
lines = [f"Total Energy: {energy:.6f} eV", "", "Atomic Forces:"]
|
| 134 |
-
norms = np.linalg.norm(forces, axis=1)
|
| 135 |
for i, fc in enumerate(forces):
|
| 136 |
lines.append(f"Atom {i+1}: [{fc[0]:.4f}, {fc[1]:.4f}, {fc[2]:.4f}] eV/Å")
|
| 137 |
-
|
|
|
|
| 138 |
|
| 139 |
return "\n".join(lines), "Calculation completed with OrbMol"
|
| 140 |
except Exception as e:
|
| 141 |
return f"Error during calculation: {e}", "Error"
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
# Simulaciones (helpers) y parsing de log
|
| 145 |
-
# =========================
|
| 146 |
from simulation_scripts_orbmol import (
|
| 147 |
run_md_simulation,
|
| 148 |
run_relaxation_simulation,
|
| 149 |
)
|
| 150 |
|
| 151 |
-
|
| 152 |
-
re.compile(r"(?:^|\\s)(?:step|iter|i)\\s*[:=]?\\s*(\\d+).*?(?:E|energy)\\s*[:=]?\\s*(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)"),
|
| 153 |
-
re.compile(r"(?:^|\\s)E(?:nergy)?\\s*[:=]?\\s*(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)"),
|
| 154 |
-
]
|
| 155 |
-
|
| 156 |
-
def extract_energy_series(log_text):
|
| 157 |
-
steps, energies = [], []
|
| 158 |
-
if not log_text:
|
| 159 |
-
return steps, energies
|
| 160 |
-
for line in log_text.splitlines():
|
| 161 |
-
m = ENERGY_PATTERNS[0].search(line)
|
| 162 |
-
if m:
|
| 163 |
-
steps.append(int(m.group(1)))
|
| 164 |
-
energies.append(float(m.group(2)))
|
| 165 |
-
continue
|
| 166 |
-
m2 = ENERGY_PATTERNS[1].search(line)
|
| 167 |
-
if m2:
|
| 168 |
-
steps.append(len(steps))
|
| 169 |
-
energies.append(float(m2.group(1)))
|
| 170 |
-
return steps, energies
|
| 171 |
-
|
| 172 |
-
def plot_energy(steps, energies, title):
|
| 173 |
-
import matplotlib.pyplot as plt
|
| 174 |
-
fig = plt.figure(figsize=(5,3.2))
|
| 175 |
-
if steps:
|
| 176 |
-
plt.plot(steps, energies, linewidth=1.6)
|
| 177 |
-
plt.xlabel("Step")
|
| 178 |
-
else:
|
| 179 |
-
plt.plot(range(len(energies)), energies, linewidth=1.6)
|
| 180 |
-
plt.xlabel("Index")
|
| 181 |
-
plt.ylabel("Energy (eV)")
|
| 182 |
-
plt.title(title)
|
| 183 |
-
plt.tight_layout()
|
| 184 |
-
return fig
|
| 185 |
-
|
| 186 |
-
# =========================
|
| 187 |
-
# Wrappers MD / Relax (devuelven: status, traj, log, script, explain, html, plot)
|
| 188 |
-
# =========================
|
| 189 |
def md_wrapper(structure_file, charge, spin, steps, tempK, timestep_fs, ensemble):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
try:
|
| 191 |
if not structure_file:
|
| 192 |
return ("Error: Please upload a structure file", None, "", "", "", "", None)
|
|
@@ -203,18 +139,20 @@ def md_wrapper(structure_file, charge, spin, steps, tempK, timestep_fs, ensemble
|
|
| 203 |
float(timestep_fs),
|
| 204 |
float(tempK),
|
| 205 |
"NVT" if ensemble == "NVT" else "NVE",
|
| 206 |
-
int(charge),
|
| 207 |
-
int(spin),
|
| 208 |
)
|
| 209 |
status = f"MD completed: {int(steps)} steps at {int(tempK)} K ({ensemble})"
|
| 210 |
html_value = traj_to_html(traj_path)
|
| 211 |
-
|
| 212 |
-
fig = plot_energy(s, e, "MD: Energy vs Step")
|
| 213 |
-
return (status, traj_path, log_text, script_text, explanation, html_value, fig)
|
| 214 |
except Exception as e:
|
| 215 |
return (f"Error: {e}", None, "", "", "", "", None)
|
| 216 |
|
| 217 |
def relax_wrapper(structure_file, steps, fmax, charge, spin, relax_cell):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
try:
|
| 219 |
if not structure_file:
|
| 220 |
return ("Error: Please upload a structure file", None, "", "", "", "", None)
|
|
@@ -228,124 +166,100 @@ def relax_wrapper(structure_file, steps, fmax, charge, spin, relax_cell):
|
|
| 228 |
file_path,
|
| 229 |
int(steps),
|
| 230 |
float(fmax),
|
| 231 |
-
int(charge),
|
| 232 |
-
int(spin),
|
| 233 |
-
bool(relax_cell),
|
| 234 |
)
|
| 235 |
status = f"Relaxation finished (≤ {int(steps)} steps, fmax={float(fmax)} eV/Å)"
|
| 236 |
html_value = traj_to_html(traj_path)
|
| 237 |
-
|
| 238 |
-
fig = plot_energy(s, e, "Relaxation: Energy vs Step")
|
| 239 |
-
return (status, traj_path, log_text, script_text, explanation, html_value, fig)
|
| 240 |
except Exception as e:
|
| 241 |
return (f"Error: {e}", None, "", "", "", "", None)
|
| 242 |
|
| 243 |
-
|
| 244 |
-
"""Preview inmediato al subir archivo en SPE."""
|
| 245 |
-
if not structure_file:
|
| 246 |
-
return "<div style='color:#b00; padding:20px;'>Upload a file to preview</div>"
|
| 247 |
-
if not os.path.exists(structure_file):
|
| 248 |
-
return "<div style='color:#b00; padding:20px;'>File not found</div>"
|
| 249 |
-
if os.path.getsize(structure_file) == 0:
|
| 250 |
-
return "<div style='color:#b00; padding:20px;'>Empty file</div>"
|
| 251 |
-
return structure_to_html(structure_file)
|
| 252 |
-
|
| 253 |
-
# =========================
|
| 254 |
-
# UI
|
| 255 |
-
# =========================
|
| 256 |
with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
|
| 257 |
with gr.Tabs():
|
| 258 |
-
#
|
| 259 |
with gr.Tab("Single Point Energy"):
|
| 260 |
with gr.Row():
|
| 261 |
with gr.Column(scale=2):
|
| 262 |
-
gr.Markdown("
|
| 263 |
-
gr.Markdown("Upload molecular structure files (.xyz, .pdb, .cif, .traj, .mol, .sdf) for preview and calculation.")
|
| 264 |
xyz_input = gr.File(
|
| 265 |
-
label="Upload Structure File",
|
| 266 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 267 |
file_count="single",
|
| 268 |
type="filepath",
|
| 269 |
)
|
| 270 |
with gr.Row():
|
| 271 |
charge_input = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 272 |
-
spin_input
|
| 273 |
run_spe = gr.Button("Run OrbMol Prediction", variant="primary")
|
| 274 |
with gr.Column(variant="panel", min_width=520):
|
| 275 |
-
|
| 276 |
-
spe_out = gr.Textbox(label="Energy & Forces", lines=15, interactive=False)
|
| 277 |
spe_status = gr.Textbox(label="Status", interactive=False, max_lines=1)
|
| 278 |
-
|
| 279 |
-
# Preview inmediato (sin cálculo)
|
| 280 |
-
xyz_input.change(preview_structure, inputs=[xyz_input], outputs=[spe_preview])
|
| 281 |
-
# Cálculo SPE
|
| 282 |
run_spe.click(predict_molecule, [xyz_input, charge_input, spin_input], [spe_out, spe_status])
|
| 283 |
|
| 284 |
-
#
|
| 285 |
with gr.Tab("Molecular Dynamics"):
|
| 286 |
with gr.Row():
|
| 287 |
with gr.Column(scale=2):
|
| 288 |
gr.Markdown("## Molecular Dynamics Simulation")
|
| 289 |
xyz_md = gr.File(
|
| 290 |
-
label="Upload Structure File",
|
| 291 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 292 |
file_count="single",
|
| 293 |
type="filepath",
|
| 294 |
)
|
| 295 |
with gr.Row():
|
| 296 |
charge_md = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 297 |
-
spin_md
|
| 298 |
with gr.Row():
|
| 299 |
-
steps_md
|
| 300 |
-
temp_md
|
| 301 |
with gr.Row():
|
| 302 |
timestep_md = gr.Slider(minimum=0.1, maximum=5.0, value=1.0, step=0.1, label="Timestep (fs)")
|
| 303 |
-
ensemble_md = gr.Radio(["NVE",
|
| 304 |
run_md_btn = gr.Button("Run MD Simulation", variant="primary")
|
| 305 |
-
|
| 306 |
with gr.Column(variant="panel", min_width=520):
|
| 307 |
md_status = gr.Textbox(label="MD Status", interactive=False)
|
| 308 |
-
md_traj
|
| 309 |
-
md_html
|
| 310 |
-
md_log
|
| 311 |
-
md_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=
|
| 312 |
-
md_explain
|
| 313 |
-
md_plot
|
| 314 |
-
|
| 315 |
run_md_btn.click(
|
| 316 |
md_wrapper,
|
| 317 |
inputs=[xyz_md, charge_md, spin_md, steps_md, temp_md, timestep_md, ensemble_md],
|
| 318 |
outputs=[md_status, md_traj, md_log, md_script, md_explain, md_html, md_plot],
|
| 319 |
)
|
| 320 |
|
| 321 |
-
#
|
| 322 |
with gr.Tab("Relaxation / Optimization"):
|
| 323 |
with gr.Row():
|
| 324 |
with gr.Column(scale=2):
|
| 325 |
gr.Markdown("## Structure Relaxation/Optimization")
|
| 326 |
xyz_rlx = gr.File(
|
| 327 |
-
label="Upload Structure File",
|
| 328 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 329 |
file_count="single",
|
| 330 |
type="filepath",
|
| 331 |
)
|
| 332 |
steps_rlx = gr.Slider(minimum=1, maximum=2000, value=300, step=1, label="Max Steps")
|
| 333 |
-
fmax_rlx
|
| 334 |
with gr.Row():
|
| 335 |
charge_rlx = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 336 |
-
spin_rlx
|
| 337 |
relax_cell = gr.Checkbox(False, label="Relax Unit Cell")
|
| 338 |
-
run_rlx_btn
|
| 339 |
-
|
| 340 |
with gr.Column(variant="panel", min_width=520):
|
| 341 |
rlx_status = gr.Textbox(label="Status", interactive=False)
|
| 342 |
-
rlx_traj
|
| 343 |
-
rlx_html
|
| 344 |
-
rlx_log
|
| 345 |
-
rlx_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=
|
| 346 |
-
rlx_explain
|
| 347 |
-
rlx_plot
|
| 348 |
-
|
| 349 |
run_rlx_btn.click(
|
| 350 |
relax_wrapper,
|
| 351 |
inputs=[xyz_rlx, steps_rlx, fmax_rlx, charge_rlx, spin_rlx, relax_cell],
|
|
|
|
| 2 |
import re
|
| 3 |
import numpy as np
|
| 4 |
import gradio as gr
|
| 5 |
+
from ase.io import read
|
| 6 |
from ase.io.trajectory import Trajectory
|
| 7 |
|
| 8 |
+
# ========= 3Dmol.js (para ver trayectorias MD/Relax) =========
|
| 9 |
+
THREE_D_MOL_SOURCES = [
|
| 10 |
+
"https://3dmol.org/build/3Dmol-min.js",
|
| 11 |
+
"https://cdn.jsdelivr.net/npm/3dmol/build/3Dmol-min.js",
|
| 12 |
+
"https://unpkg.com/3dmol/build/3Dmol-min.js",
|
| 13 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
def _loader_js():
|
| 16 |
+
srcs = "[" + ",".join([f"'{u}'" for u in THREE_D_MOL_SOURCES]) + "]"
|
| 17 |
return f"""
|
| 18 |
+
function _ensure3Dmol(cb){{
|
| 19 |
+
if(typeof window.$3Dmol!=='undefined') return cb();
|
| 20 |
+
const srcs={srcs}; let i=0;
|
| 21 |
+
function tryNext(){{
|
| 22 |
+
if(i>=srcs.length) return;
|
| 23 |
+
const s=document.createElement('script'); s.src=srcs[i++]; s.onload=cb; s.onerror=tryNext; document.head.appendChild(s);
|
| 24 |
+
}}
|
| 25 |
+
tryNext();
|
| 26 |
+
}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
"""
|
| 28 |
|
| 29 |
+
def _atoms_to_xyz_block(atoms):
|
| 30 |
+
syms = atoms.get_chemical_symbols()
|
| 31 |
+
pos = atoms.get_positions()
|
| 32 |
+
out = [str(len(syms)), "frame"]
|
| 33 |
+
for s,(x,y,z) in zip(syms,pos):
|
| 34 |
+
out.append(f"{s} {x:.6f} {y:.6f} {z:.6f}")
|
| 35 |
+
return "\n".join(out)
|
| 36 |
+
|
| 37 |
def traj_to_html(traj_path, width=520, height=520, interval_ms=200):
|
|
|
|
| 38 |
if not traj_path or not os.path.exists(traj_path):
|
| 39 |
+
return "<div style='color:#b00;padding:20px;'>No trajectory file found</div>"
|
| 40 |
try:
|
| 41 |
traj = Trajectory(traj_path)
|
| 42 |
+
if len(traj)==0:
|
| 43 |
+
return "<div style='color:#555;padding:20px;'>Empty trajectory</div>"
|
| 44 |
except Exception as e:
|
| 45 |
+
return f"<div style='color:#b00;padding:20px;'>Error reading trajectory: {e}</div>"
|
| 46 |
|
| 47 |
frames = [_atoms_to_xyz_block(at) for at in traj]
|
| 48 |
frames_json = str(frames).replace("'", '"')
|
| 49 |
+
viewer_id = f"viewer_{abs(hash(traj_path))%100000}"
|
| 50 |
+
loader = _loader_js()
|
| 51 |
return f"""
|
| 52 |
+
<div style="margin-bottom:10px;padding:10px;background:#f5f5f5;border-radius:5px;">
|
| 53 |
<strong>🧬 3D Molecular Viewer</strong> — {len(frames)} frames
|
| 54 |
</div>
|
| 55 |
+
<div id="{viewer_id}" style="width:{width}px;height:{height}px;border:2px solid #ddd;border-radius:8px;background:#fafafa;"></div>
|
| 56 |
<script>
|
| 57 |
+
{loader}
|
| 58 |
+
_ensure3Dmol(function(){{
|
| 59 |
+
var el=document.getElementById("{viewer_id}"); if(!el||typeof $3Dmol==='undefined') return;
|
| 60 |
+
var v=$3Dmol.createViewer(el, {{backgroundColor:'white'}});
|
| 61 |
+
var frames={frames_json}; var i=0;
|
| 62 |
+
function draw(k){{ v.clear(); v.addModel(frames[k], "xyz"); v.setStyle({{}}, {{stick:{{}}, sphere:{{}}}}); v.zoomTo(); v.render(); }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
draw(0);
|
| 64 |
+
if(frames.length>1) setInterval(function(){{ i=(i+1)%frames.length; draw(i); }}, {interval_ms});
|
|
|
|
|
|
|
| 65 |
}});
|
| 66 |
</script>
|
| 67 |
"""
|
| 68 |
|
| 69 |
+
# ================= OrbMol (SPE) =================
|
|
|
|
|
|
|
| 70 |
from orb_models.forcefield import pretrained
|
| 71 |
from orb_models.forcefield.calculator import ORBCalculator
|
| 72 |
|
|
|
|
| 79 |
return _MODEL_CALC
|
| 80 |
|
| 81 |
def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
| 82 |
+
"""
|
| 83 |
+
Single Point Energy + fuerzas (OrbMol). Solo se ejecuta al pulsar el botón.
|
| 84 |
+
"""
|
| 85 |
try:
|
| 86 |
calc = _load_orbmol_calc()
|
| 87 |
if not structure_file:
|
| 88 |
return "Error: Please upload a structure file", "Error"
|
|
|
|
| 89 |
|
| 90 |
+
file_path = structure_file # gr.File(type='filepath') -> str
|
| 91 |
if not os.path.exists(file_path):
|
| 92 |
return f"Error: File not found: {file_path}", "Error"
|
| 93 |
if os.path.getsize(file_path) == 0:
|
|
|
|
| 101 |
forces = atoms.get_forces() # eV/Å
|
| 102 |
|
| 103 |
lines = [f"Total Energy: {energy:.6f} eV", "", "Atomic Forces:"]
|
|
|
|
| 104 |
for i, fc in enumerate(forces):
|
| 105 |
lines.append(f"Atom {i+1}: [{fc[0]:.4f}, {fc[1]:.4f}, {fc[2]:.4f}] eV/Å")
|
| 106 |
+
max_force = float(np.max(np.linalg.norm(forces, axis=1)))
|
| 107 |
+
lines += ["", f"Max Force: {max_force:.4f} eV/Å"]
|
| 108 |
|
| 109 |
return "\n".join(lines), "Calculation completed with OrbMol"
|
| 110 |
except Exception as e:
|
| 111 |
return f"Error during calculation: {e}", "Error"
|
| 112 |
|
| 113 |
+
# ================= Simulaciones (tus helpers) =================
|
|
|
|
|
|
|
| 114 |
from simulation_scripts_orbmol import (
|
| 115 |
run_md_simulation,
|
| 116 |
run_relaxation_simulation,
|
| 117 |
)
|
| 118 |
|
| 119 |
+
# ========== Wrappers MD / Relax (con firma correcta) ==========
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
def md_wrapper(structure_file, charge, spin, steps, tempK, timestep_fs, ensemble):
|
| 121 |
+
"""
|
| 122 |
+
Llama a tu run_md_simulation con el ORDEN correcto usando keywords:
|
| 123 |
+
(structure_file, num_steps, num_prerelax_steps, md_timestep, temperature_k, md_ensemble,
|
| 124 |
+
task_name='OMol', total_charge=..., spin_multiplicity=...)
|
| 125 |
+
"""
|
| 126 |
try:
|
| 127 |
if not structure_file:
|
| 128 |
return ("Error: Please upload a structure file", None, "", "", "", "", None)
|
|
|
|
| 139 |
float(timestep_fs),
|
| 140 |
float(tempK),
|
| 141 |
"NVT" if ensemble == "NVT" else "NVE",
|
| 142 |
+
total_charge=int(charge),
|
| 143 |
+
spin_multiplicity=int(spin),
|
| 144 |
)
|
| 145 |
status = f"MD completed: {int(steps)} steps at {int(tempK)} K ({ensemble})"
|
| 146 |
html_value = traj_to_html(traj_path)
|
| 147 |
+
return (status, traj_path, log_text, script_text, explanation, html_value, None)
|
|
|
|
|
|
|
| 148 |
except Exception as e:
|
| 149 |
return (f"Error: {e}", None, "", "", "", "", None)
|
| 150 |
|
| 151 |
def relax_wrapper(structure_file, steps, fmax, charge, spin, relax_cell):
|
| 152 |
+
"""
|
| 153 |
+
Firma correcta usando keywords:
|
| 154 |
+
(structure_file, num_steps, fmax, task_name='OMol', total_charge=..., spin_multiplicity=..., relax_unit_cell=...)
|
| 155 |
+
"""
|
| 156 |
try:
|
| 157 |
if not structure_file:
|
| 158 |
return ("Error: Please upload a structure file", None, "", "", "", "", None)
|
|
|
|
| 166 |
file_path,
|
| 167 |
int(steps),
|
| 168 |
float(fmax),
|
| 169 |
+
total_charge=int(charge),
|
| 170 |
+
spin_multiplicity=int(spin),
|
| 171 |
+
relax_unit_cell=bool(relax_cell),
|
| 172 |
)
|
| 173 |
status = f"Relaxation finished (≤ {int(steps)} steps, fmax={float(fmax)} eV/Å)"
|
| 174 |
html_value = traj_to_html(traj_path)
|
| 175 |
+
return (status, traj_path, log_text, script_text, explanation, html_value, None)
|
|
|
|
|
|
|
| 176 |
except Exception as e:
|
| 177 |
return (f"Error: {e}", None, "", "", "", "", None)
|
| 178 |
|
| 179 |
+
# ===================== UI (solo calcula al pulsar botón) =====================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
|
| 181 |
with gr.Tabs():
|
| 182 |
+
# ===== SPE =====
|
| 183 |
with gr.Tab("Single Point Energy"):
|
| 184 |
with gr.Row():
|
| 185 |
with gr.Column(scale=2):
|
| 186 |
+
gr.Markdown("## OrbMol — Single Point Energy")
|
|
|
|
| 187 |
xyz_input = gr.File(
|
| 188 |
+
label="Upload Structure File (.xyz/.pdb/.cif/.traj/.mol/.sdf)",
|
| 189 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 190 |
file_count="single",
|
| 191 |
type="filepath",
|
| 192 |
)
|
| 193 |
with gr.Row():
|
| 194 |
charge_input = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 195 |
+
spin_input = gr.Slider(minimum=1, maximum=11, value=1, step=1, label="Spin Multiplicity")
|
| 196 |
run_spe = gr.Button("Run OrbMol Prediction", variant="primary")
|
| 197 |
with gr.Column(variant="panel", min_width=520):
|
| 198 |
+
spe_out = gr.Textbox(label="Energy & Forces", lines=18, interactive=False)
|
|
|
|
| 199 |
spe_status = gr.Textbox(label="Status", interactive=False, max_lines=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
run_spe.click(predict_molecule, [xyz_input, charge_input, spin_input], [spe_out, spe_status])
|
| 201 |
|
| 202 |
+
# ===== MD =====
|
| 203 |
with gr.Tab("Molecular Dynamics"):
|
| 204 |
with gr.Row():
|
| 205 |
with gr.Column(scale=2):
|
| 206 |
gr.Markdown("## Molecular Dynamics Simulation")
|
| 207 |
xyz_md = gr.File(
|
| 208 |
+
label="Upload Structure File (.xyz/.pdb/.cif/.traj/.mol/.sdf)",
|
| 209 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 210 |
file_count="single",
|
| 211 |
type="filepath",
|
| 212 |
)
|
| 213 |
with gr.Row():
|
| 214 |
charge_md = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 215 |
+
spin_md = gr.Slider(minimum=1, maximum=11, value=1, step=1, label="Spin Multiplicity")
|
| 216 |
with gr.Row():
|
| 217 |
+
steps_md = gr.Slider(minimum=10, maximum=2000, value=100, step=10, label="Steps")
|
| 218 |
+
temp_md = gr.Slider(minimum=10, maximum=1500, value=300, step=10, label="Temperature (K)")
|
| 219 |
with gr.Row():
|
| 220 |
timestep_md = gr.Slider(minimum=0.1, maximum=5.0, value=1.0, step=0.1, label="Timestep (fs)")
|
| 221 |
+
ensemble_md = gr.Radio(["NVE","NVT"], value="NVE", label="Ensemble")
|
| 222 |
run_md_btn = gr.Button("Run MD Simulation", variant="primary")
|
|
|
|
| 223 |
with gr.Column(variant="panel", min_width=520):
|
| 224 |
md_status = gr.Textbox(label="MD Status", interactive=False)
|
| 225 |
+
md_traj = gr.File(label="Trajectory (.traj)", interactive=False)
|
| 226 |
+
md_html = gr.HTML(label="Trajectory Viewer", sanitize=False)
|
| 227 |
+
md_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
|
| 228 |
+
md_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=18, max_lines=28)
|
| 229 |
+
md_explain= gr.Markdown()
|
| 230 |
+
md_plot = gr.Plot(label="(optional)")
|
|
|
|
| 231 |
run_md_btn.click(
|
| 232 |
md_wrapper,
|
| 233 |
inputs=[xyz_md, charge_md, spin_md, steps_md, temp_md, timestep_md, ensemble_md],
|
| 234 |
outputs=[md_status, md_traj, md_log, md_script, md_explain, md_html, md_plot],
|
| 235 |
)
|
| 236 |
|
| 237 |
+
# ===== Relax =====
|
| 238 |
with gr.Tab("Relaxation / Optimization"):
|
| 239 |
with gr.Row():
|
| 240 |
with gr.Column(scale=2):
|
| 241 |
gr.Markdown("## Structure Relaxation/Optimization")
|
| 242 |
xyz_rlx = gr.File(
|
| 243 |
+
label="Upload Structure File (.xyz/.pdb/.cif/.traj/.mol/.sdf)",
|
| 244 |
file_types=[".xyz", ".pdb", ".cif", ".traj", ".mol", ".sdf"],
|
| 245 |
file_count="single",
|
| 246 |
type="filepath",
|
| 247 |
)
|
| 248 |
steps_rlx = gr.Slider(minimum=1, maximum=2000, value=300, step=1, label="Max Steps")
|
| 249 |
+
fmax_rlx = gr.Slider(minimum=0.001, maximum=0.5, value=0.05, step=0.001, label="Fmax (eV/Å)")
|
| 250 |
with gr.Row():
|
| 251 |
charge_rlx = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label="Charge")
|
| 252 |
+
spin_rlx = gr.Slider(minimum=1, maximum=11, value=1, step=1, label="Spin")
|
| 253 |
relax_cell = gr.Checkbox(False, label="Relax Unit Cell")
|
| 254 |
+
run_rlx_btn= gr.Button("Run Optimization", variant="primary")
|
|
|
|
| 255 |
with gr.Column(variant="panel", min_width=520):
|
| 256 |
rlx_status = gr.Textbox(label="Status", interactive=False)
|
| 257 |
+
rlx_traj = gr.File(label="Trajectory (.traj)", interactive=False)
|
| 258 |
+
rlx_html = gr.HTML(label="Final Structure / Trajectory", sanitize=False)
|
| 259 |
+
rlx_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
|
| 260 |
+
rlx_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=18, max_lines=28)
|
| 261 |
+
rlx_explain= gr.Markdown()
|
| 262 |
+
rlx_plot = gr.Plot(label="(optional)")
|
|
|
|
| 263 |
run_rlx_btn.click(
|
| 264 |
relax_wrapper,
|
| 265 |
inputs=[xyz_rlx, steps_rlx, fmax_rlx, charge_rlx, spin_rlx, relax_cell],
|