Spaces:
Sleeping
Sleeping
File size: 9,904 Bytes
427fd9c c2be249 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 c2be249 427fd9c 0fc2a04 e72bc1b 427fd9c e72bc1b 427fd9c b786476 c2be249 427fd9c 0fc2a04 427fd9c e72bc1b 427fd9c 0fc2a04 e72bc1b b786476 427fd9c 0fc2a04 b786476 427fd9c 0fc2a04 b786476 e72bc1b 427fd9c b786476 427fd9c c2be249 427fd9c b786476 e72bc1b b786476 e72bc1b c926c74 e72bc1b c2be249 c926c74 e72bc1b c926c74 b786476 427fd9c e72bc1b 427fd9c 0fc2a04 427fd9c e72bc1b c926c74 e72bc1b c2be249 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c2be249 0fc2a04 b786476 c2be249 0fc2a04 c2be249 e72bc1b c2be249 e72bc1b c2be249 e72bc1b c2be249 e72bc1b c2be249 e72bc1b c926c74 e72bc1b c926c74 c2be249 0fc2a04 c2be249 e72bc1b c926c74 e72bc1b e6d00b8 e72bc1b e6d00b8 e72bc1b e6d00b8 e72bc1b e6d00b8 e72bc1b e6d00b8 0fc2a04 e72bc1b 0fc2a04 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 e72bc1b 0fc2a04 e72bc1b c926c74 e72bc1b c926c74 e72bc1b c926c74 e72bc1b b786476 0fc2a04 427fd9c c2be249 |
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 |
import gradio as gr
import numpy as np
import tempfile
import os
from ase.io import read
from ase import units
from ase.optimize import LBFGS
from ase.md.verlet import VelocityVerlet
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
from ase.io.trajectory import Trajectory
# Intentar importar Molecule3D para vista 3D nativa
try:
from gradio_molecule3d import Molecule3D
HAVE_MOL3D = True
except Exception:
HAVE_MOL3D = False
from orb_models.forcefield import pretrained
from orb_models.forcefield.calculator import ORBCalculator
# =========================
# OrbMol global model
# =========================
model_calc = None
def load_orbmol_model():
global model_calc
if model_calc is None:
try:
print("Loading OrbMol model...")
orbff = pretrained.orb_v3_conservative_inf_omat(
device="cpu",
precision="float32-high"
)
model_calc = ORBCalculator(orbff, device="cpu")
print("OrbMol model loaded successfully")
except Exception as e:
print(f"Error loading model: {e}")
model_calc = None
return model_calc
# =========================
# Single-point (SPE)
# =========================
def predict_molecule(xyz_content, charge=0, spin_multiplicity=1):
try:
calc = load_orbmol_model()
if calc is None:
return "Error: Could not load OrbMol model", ""
if not xyz_content.strip():
return "Error: Please enter XYZ coordinates", ""
with tempfile.NamedTemporaryFile(mode="w", suffix=".xyz", delete=False) as f:
f.write(xyz_content)
xyz_file = f.name
atoms = read(xyz_file)
atoms.info = {"charge": int(charge), "spin": int(spin_multiplicity)}
atoms.calc = calc
energy = atoms.get_potential_energy() # eV
forces = atoms.get_forces() # eV/Å
lines = []
lines.append(f"Total Energy: {energy:.6f} eV\n")
lines.append("Atomic Forces:")
for i, f in enumerate(forces):
lines.append(f"Atom {i+1}: [{f[0]:.4f}, {f[1]:.4f}, {f[2]:.4f}] eV/Å")
max_force = float(np.max(np.linalg.norm(forces, axis=1)))
lines.append(f"\nMax Force: {max_force:.4f} eV/Å")
os.unlink(xyz_file)
return "\n".join(lines), "Calculation completed with OrbMol"
except Exception as e:
return f"Error during calculation: {str(e)}", "Error"
# =========================
# Trajectory → HTML 3D fallback
# =========================
def traj_to_html(traj_path, width=520, height=520, interval_ms=200):
traj = Trajectory(traj_path)
xyz_frames = []
for atoms in traj:
symbols = atoms.get_chemical_symbols()
coords = atoms.get_positions()
parts = [str(len(symbols)), "frame"]
for s, (x, y, z) in zip(symbols, coords):
parts.append(f"{s} {x:.6f} {y:.6f} {z:.6f}")
xyz_frames.append("\n".join(parts))
html = f"""
<div id="viewer_md" style="width:{width}px; height:{height}px;"></div>
<script src="https://3dmol.org/build/3Dmol-min.js"></script>
<script>
(function() {{
var viewer = $3Dmol.createViewer("viewer_md", {{backgroundColor: 'white'}});
var frames = {xyz_frames!r};
var i = 0;
function show(i) {{
viewer.clear();
viewer.addModel(frames[i], "xyz");
viewer.setStyle({{}}, {{stick: {{}}}});
viewer.zoomTo();
viewer.render();
}}
if(frames.length>0) show(0);
if(frames.length>1) setInterval(function(){{
i=(i+1)%frames.length; show(i);
}}, {int(interval_ms)});
}})();
</script>
"""
return html
# =========================
# MD with OrbMol
# =========================
def run_md(xyz_content, charge=0, spin_multiplicity=1,
steps=100, temperature=300, timestep=1.0):
try:
calc = load_orbmol_model()
if calc is None:
return "Error: Could not load OrbMol model", ""
if not xyz_content.strip():
return "Error: Please enter XYZ coordinates", ""
# Leer estructura
with tempfile.NamedTemporaryFile(mode="w", suffix=".xyz", delete=False) as f:
f.write(xyz_content)
xyz_file = f.name
atoms = read(xyz_file)
atoms.info = {"charge": int(charge), "spin": int(spin_multiplicity)}
atoms.calc = calc
# Pre-relajación ligera
opt = LBFGS(atoms, logfile=None)
opt.run(fmax=0.05, steps=20)
MaxwellBoltzmannDistribution(atoms, temperature_K=2*float(temperature))
dyn = VelocityVerlet(atoms, timestep=float(timestep) * units.fs)
tf = tempfile.NamedTemporaryFile(suffix=".traj", delete=False)
tf.close()
traj = Trajectory(tf.name, "w", atoms)
dyn.attach(traj.write, interval=1)
dyn.run(int(steps))
if HAVE_MOL3D:
# Mostrar último frame en Molecule3D
last = traj[-1]
mol_xyz = f"{len(last)}\nFinal frame\n"
for s, (x, y, z) in zip(last.get_chemical_symbols(), last.get_positions()):
mol_xyz += f"{s} {x:.6f} {y:.6f} {z:.6f}\n"
view = Molecule3D(value=mol_xyz, label="Final Frame (XYZ)")
else:
view = traj_to_html(tf.name)
try:
os.unlink(xyz_file)
except Exception:
pass
return f"MD completed: {int(steps)} steps at {int(temperature)} K", view
except Exception as e:
return f"Error during MD simulation: {str(e)}", ""
# =========================
# Ejemplos
# =========================
examples = [
["""2
Hydrogen molecule
H 0.0 0.0 0.0
H 0.0 0.0 0.74""", 0, 1],
["""3
Water molecule
O 0.0000 0.0000 0.0000
H 0.7571 0.0000 0.5864
H -0.7571 0.0000 0.5864""", 0, 1],
["""5
Methane
C 0.0000 0.0000 0.0000
H 1.0890 0.0000 0.0000
H -0.3630 1.0267 0.0000
H -0.3630 -0.5133 0.8887
H -0.3630 -0.5133 -0.8887""", 0, 1],
]
# =========================
# Gradio UI
# =========================
with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
with gr.Tabs():
# -------- Tab 1: Single Point --------
with gr.Tab("Single Point Energy"):
with gr.Row():
with gr.Column(scale=2):
with gr.Column(variant="panel"):
gr.Markdown("# OrbMol Demo - Quantum-Accurate Predictions")
gr.Markdown("OrbMol is a neural network potential trained on the OMol25 dataset.")
xyz_input = gr.Textbox(
label="XYZ Coordinates",
placeholder="Paste XYZ here...",
lines=12,
)
with gr.Row():
charge_input = gr.Slider(value=0, minimum=-10, maximum=10, step=1, label="Charge")
spin_input = gr.Slider(value=1, minimum=1, maximum=11, step=1, label="Spin Multiplicity")
predict_btn = gr.Button("Run OrbMol Prediction", variant="primary")
with gr.Column(variant="panel", min_width=500):
results_output = gr.Textbox(label="Energy & Forces", lines=15, interactive=False)
status_output = gr.Textbox(label="Status", interactive=False, max_lines=1)
gr.Examples(examples=examples, inputs=[xyz_input, charge_input, spin_input])
predict_btn.click(
predict_molecule,
inputs=[xyz_input, charge_input, spin_input],
outputs=[results_output, status_output],
)
with gr.Sidebar(open=True):
gr.Markdown("## Learn more about OrbMol")
with gr.Accordion("What is OrbMol?", open=False):
gr.Markdown("* Neural network potential for molecules\n* Built on Orb-v3, trained on OMol25\n* Supports charge and spin")
with gr.Accordion("Benchmarks", open=False):
gr.Markdown("* <1 kcal/mol error on Wiggle150\n* Accurate protein–ligand binding energies\n* Stable MD on biomolecules >20k atoms")
with gr.Accordion("Disclaimers", open=False):
gr.Markdown("* Validate results for your use case\n* Training level of theory may limit accuracy")
# -------- Tab 2: MD --------
with gr.Tab("Molecular Dynamics"):
with gr.Row():
with gr.Column(scale=2):
xyz_input_md = gr.Textbox(label="XYZ Coordinates", lines=12)
charge_input_md = gr.Slider(value=0, minimum=-10, maximum=10, step=1, label="Charge")
spin_input_md = gr.Slider(value=1, minimum=1, maximum=11, step=1, label="Spin Multiplicity")
steps_input = gr.Slider(value=100, minimum=10, maximum=1000, step=10, label="Steps")
temp_input = gr.Slider(value=300, minimum=10, maximum=1000, step=10, label="Temperature (K)")
timestep_input = gr.Slider(value=1.0, minimum=0.1, maximum=5.0, step=0.1, label="Timestep (fs)")
run_md_btn = gr.Button("Run MD Simulation", variant="primary")
with gr.Column(variant="panel", min_width=520):
md_status = gr.Textbox(label="MD Status", lines=2, interactive=False)
md_view = gr.HTML() if not HAVE_MOL3D else Molecule3D(label="Trajectory Viewer")
run_md_btn.click(
run_md,
inputs=[xyz_input_md, charge_input_md, spin_input_md, steps_input, temp_input, timestep_input],
outputs=[md_status, md_view],
)
print("Starting OrbMol model loading...")
load_orbmol_model()
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
|