-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHome.py
More file actions
4453 lines (3732 loc) · 224 KB
/
Home.py
File metadata and controls
4453 lines (3732 loc) · 224 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import time
import os
import uuid
import io
import base64
import tempfile
from pathlib import Path
import platform
import psutil
import random
import traceback
import time
import gc
from scipy.optimize import curve_fit
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import torch
# FOR CPU only mode
torch._dynamo.config.suppress_errors = True
# Or disable compilation entirely
# torch.backends.cudnn.enabled = False
import plotly.express as px
import numpy as np
from ase import Atoms
from ase.io import read, write
from ase.calculators.calculator import Calculator, all_changes
from ase.optimize.optimize import Optimizer
from ase.optimize import BFGS, LBFGS, FIRE, LBFGSLineSearch, BFGSLineSearch, GPMin, MDMin
from ase.optimize.sciopt import SciPyFminBFGS, SciPyFminCG
from ase.optimize.basin import BasinHopping
from ase.optimize.minimahopping import MinimaHopping
from ase.units import kB
from ase.constraints import FixAtoms
from ase.filters import FrechetCellFilter
from ase.visualize import view
import py3Dmol
from mace.calculators import mace_mp
from fairchem.core import pretrained_mlip, FAIRChemCalculator
from orb_models.forcefield import pretrained
from orb_models.forcefield.calculator import ORBCalculator
from sevenn.calculator import SevenNetCalculator
import pandas as pd
import yaml # Added for FairChem reference energies
import subprocess
import sys
import pkg_resources
from ase.vibrations import Vibrations
from mp_api.client import MPRester
import pubchempy as pcp
from io import StringIO
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.io.ase import AseAtomsAdaptor
from pymatgen.core.structure import Molecule
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.ticker import MaxNLocator
mattersim_available = True
if mattersim_available:
from mattersim.forcefield import MatterSimCalculator
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import rdDetermineBonds
from rdkit.Geometry import Point3D
from ase.units import Hartree, Bohr
from torch_dftd.torch_dftd3_calculator import TorchDFTD3Calculator
from upet.calculator import UPETCalculator
from upet.calculator import PETMADDOSCalculator
from model_config import (
MACE_MODELS, MACE_CITATIONS, FAIRCHEM_MODELS, ORB_MODELS,
MATTERSIM_MODELS, UPET_MODELS, UPET_MODELS_VERSIONS,
SEVEN_NET_MODELS, SAMPLE_STRUCTURES, FAIRCHEM_CITATIONS, UPET_CITATIONS, ORB_CITATIONS, MATTERSIM_CITATIONS, SEVEN_NET_CITATIONS
)
from data import atoms_to_graph
from model import MPNN
from torch_geometric.data import DataLoader
from predict import load_model
from huggingface_hub import login
try:
hf_token = os.getenv("YOUR SECRET KEY") # Replace with your actual Hugging Face token or manage secrets appropriately
if hf_token:
login(token = hf_token)
else:
print("Hugging Face token not found. Some models might not be accessible.")
except Exception as e:
print(f"hf login error: {e}")
os.environ["STREAMLIT_WATCHER_TYPE"] = "none"
# Set page configuration
st.set_page_config(
page_title="MLIP Studio - Run, Test and Benchmark MLIPs",
page_icon="🧪",
layout="wide"
)
# === Background video styling ===
def set_css():
st.markdown("""
<style>
#myVideo {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
opacity: 0.08; /* adjust opacity */
pointer-events: none;
}
.content {
position: fixed;
bottom: 0;
background: rgba(1, 1, 1, 1.0);
color: #f1f1f1;
width: 100%;
padding: 20px;
}
</style>
""", unsafe_allow_html=True)
# === Embed background video OR remove based on choice ===
def embed_video(video_choice):
if video_choice == "Off":
# Remove the video element by injecting empty HTML
st.sidebar.markdown(
"""<style>#myVideo { display: none !important; }</style>""",
unsafe_allow_html=True,
)
return
video_links = {
"Video 1": "https://raw.githubusercontent.com/manassharma07/MLIP-Playground/main/video1.mp4",
"Video 2": "https://raw.githubusercontent.com/manassharma07/MLIP-Playground/main/video2.mp4",
"Video 3": "https://raw.githubusercontent.com/manassharma07/MLIP-Playground/main/video3.mp4",
"Video 4": "https://raw.githubusercontent.com/manassharma07/MLIP-Playground/main/video4.mp4",
}
selected_src = video_links.get(video_choice)
st.sidebar.markdown(f"""
<video autoplay muted loop id="myVideo">
<source src="{selected_src}">
Your browser does not support HTML5 video.
</video>
""", unsafe_allow_html=True)
# === UI Control ===
with st.sidebar:
with st.expander("Background"):
# st.markdown("<p style='font-size:12px; opacity:0.7;'>Background Video</p>", unsafe_allow_html=True)
# video_off = st.checkbox("Turn off background video", value=False)
video_on = st.toggle("Background video", value=True)
video_off = not video_on
# Randomly choose one of 4 videos (only if not turned off)
video_files = ["Video 1", "Video 2", "Video 3", "Video 4"]
video_choice = "Off" if video_off else random.choice(video_files)
# Apply CSS + video
set_css()
embed_video(video_choice)
def _find_value(mapping, keywords):
"""
Find the first value in a dict-like object whose key matches
any of the keywords (case-insensitive, substring match).
"""
if mapping is None:
return None
for key, value in mapping.items():
key_l = key.lower()
for kw in keywords:
if kw.lower() in key_l: # lowercase kw too
return value
return None
# Unit conversions
KCAL_PER_MOL_TO_EV = 0.04336411530877085 # 1 kcal/mol = 0.043364115... eV
class UFFCalculator(Calculator):
"""
ASE Calculator using RDKit UFF.
Energy: eV
Forces: eV/Angstrom
Notes:
- Non-periodic systems only.
- Best for molecular systems with normal covalent bonding.
- Bond connectivity is determined once and then reused.
"""
implemented_properties = ["energy", "forces"]
def __init__(self, charge=0, cov_factor=1.3, **kwargs):
super().__init__(**kwargs)
self.charge = charge
self.cov_factor = cov_factor
self._mol = None
self._symbols = None
self._natoms = None
def _atoms_to_xyz_block(self, atoms):
symbols = atoms.get_chemical_symbols()
positions = atoms.get_positions()
lines = [str(len(atoms)), "ASE structure for RDKit UFF"]
for sym, pos in zip(symbols, positions):
lines.append(
f"{sym:2s} {pos[0]: .12f} {pos[1]: .12f} {pos[2]: .12f}"
)
return "\n".join(lines)
def _build_rdkit_mol(self, atoms):
xyz_block = self._atoms_to_xyz_block(atoms)
mol = Chem.MolFromXYZBlock(xyz_block)
if mol is None:
raise RuntimeError("RDKit could not read XYZ block.")
try:
rdDetermineBonds.DetermineBonds(
mol,
charge=self.charge,
covFactor=self.cov_factor,
)
except Exception as err:
print("Warning: RDKit bond-order perception failed.")
print("Falling back to connectivity-only bond perception.")
print(f"RDKit error was: {err}")
rdDetermineBonds.DetermineConnectivity(
mol,
covFactor=self.cov_factor,
)
sanitize_result = Chem.SanitizeMol(mol, catchErrors=True)
if sanitize_result != Chem.SanitizeFlags.SANITIZE_NONE:
print("Warning: RDKit sanitization was not fully successful.")
if not AllChem.UFFHasAllMoleculeParams(mol):
raise RuntimeError(
"UFF parameters are not available for all atoms in this structure."
)
return mol
def _update_rdkit_positions(self, mol, atoms):
conf = mol.GetConformer()
positions = atoms.get_positions()
for i, pos in enumerate(positions):
conf.SetAtomPosition(
i,
Point3D(float(pos[0]), float(pos[1]), float(pos[2])),
)
def calculate(
self,
atoms=None,
properties=("energy", "forces"),
system_changes=all_changes,
):
super().calculate(atoms, properties, system_changes)
symbols = tuple(atoms.get_chemical_symbols())
natoms = len(atoms)
rebuild = (
self._mol is None
or self._natoms != natoms
or self._symbols != symbols
)
if rebuild:
self._mol = self._build_rdkit_mol(atoms)
self._symbols = symbols
self._natoms = natoms
else:
self._update_rdkit_positions(self._mol, atoms)
ff = AllChem.UFFGetMoleculeForceField(self._mol, confId=0)
if ff is None:
raise RuntimeError(
"Failed to initialize RDKit UFF force field."
)
ff.Initialize()
energy_kcal = ff.CalcEnergy()
grad_kcal_per_mol_A = np.array(ff.CalcGrad(), dtype=float).reshape(natoms, 3)
energy_ev = energy_kcal * KCAL_PER_MOL_TO_EV
# RDKit gives gradient dE/dx.
# ASE wants force = -dE/dx.
forces_ev_A = -grad_kcal_per_mol_A * KCAL_PER_MOL_TO_EV
self.results = {
"energy": energy_ev,
"forces": forces_ev_A,
}
class XTBCalculator(Calculator):
r"""ASE Calculator interface for xTB via command line execution.
Parameters
----------
xtb_command : str or Path, optional
Path to xTB executable. If not provided, tries to find 'xtb' in PATH.
Examples:
- Windows: 'D:\Downloads\xtb-6.7.1\bin\xtb.exe'
- Linux: '/usr/local/bin/xtb' or just 'xtb'
method : str, optional
xTB method to use. Default is 'GFN2-xTB' (--gfn 2).
Options: 'GFN2-xTB', 'GFN1-xTB', 'GFN0-xTB'
solvent : str, optional
Solvent model (e.g., 'water', 'dmso'). Default is None (gas phase).
accuracy : float, optional
Numerical accuracy (--acc). Default is 1.0.
electronic_temperature : float, optional
Electronic temperature in K (--etemp). Default is 300.0.
max_iterations : int, optional
Maximum SCF iterations (--iterations). Default is 250.
charge : int, optional
Molecular charge (--chrg). Default is 0.
uhf : int, optional
Number of unpaired electrons (--uhf). Default is 0.
extra_args : list of str, optional
Additional command line arguments to pass to xTB.
debug : bool, optional
If True, print xTB output and save files. Default is False.
keep_files : bool, optional
If True, keep temporary files in a specified directory. Default is False.
work_dir : str or Path, optional
Directory to save files when keep_files=True. Default is './xtb_calc'.
"""
implemented_properties = ['energy', 'forces']
def __init__(self,
xtb_command=None,
method='GFN2-xTB',
solvent=None,
accuracy=1.0,
electronic_temperature=300.0,
max_iterations=250,
charge=0,
uhf=0,
extra_args=None,
debug=False,
keep_files=False,
work_dir='./',
**kwargs):
Calculator.__init__(self, **kwargs)
# Find xTB executable
if xtb_command is None:
# Try to find xtb in PATH
import shutil
xtb_path = shutil.which('xtb')
if xtb_path is None:
raise ValueError(
"xTB executable not found in PATH. "
"Please provide xtb_command parameter."
)
self.xtb_command = xtb_path
else:
xtb_cmd_str = str(xtb_command)
# If it's just 'xtb', try to find it in PATH
if xtb_cmd_str == 'xtb':
import shutil
xtb_path = shutil.which('xtb')
if xtb_path:
self.xtb_command = 'xtb' # Keep as 'xtb' to use PATH
else:
raise ValueError("xTB executable not found in PATH.")
else:
self.xtb_command = xtb_cmd_str
# Check if executable exists (skip check if using PATH)
if self.xtb_command != 'xtb' and not os.path.isfile(self.xtb_command):
raise FileNotFoundError(f"xTB executable not found: {self.xtb_command}")
# Store parameters
self.method = method
self.solvent = solvent
self.accuracy = accuracy
self.electronic_temperature = electronic_temperature
self.max_iterations = max_iterations
self.charge = charge
self.uhf = uhf
self.extra_args = extra_args or []
self.debug = debug
self.keep_files = keep_files
self.work_dir = Path(work_dir) if keep_files else None
# Create work directory if needed
if self.keep_files and self.work_dir:
self.work_dir.mkdir(parents=True, exist_ok=True)
def write_coord_file(self, atoms, filename):
"""Write coordinates in Turbomole format.
Parameters
----------
atoms : ase.Atoms
Atoms object to write
filename : str or Path
Output file path
"""
with open(filename, 'w') as f:
# Check for periodic boundary conditions
if any(atoms.pbc):
# Write cell parameters
cell = atoms.cell
lengths = cell.lengths() # in Angstrom
angles = cell.angles() # in degrees
f.write("$cell angs\n")
f.write(f" {lengths[0]:.8f} {lengths[1]:.8f} {lengths[2]:.8f} "
f"{angles[0]:.14f} {angles[1]:.14f} {angles[2]:.14f}\n")
# Determine periodicity (1D, 2D, or 3D)
periodicity = sum(atoms.pbc)
f.write(f"$periodic {periodicity}\n")
# Write coordinates in Bohr
f.write("$coord\n")
positions_bohr = atoms.positions / Bohr # Convert Angstrom to Bohr
for pos, symbol in zip(positions_bohr, atoms.get_chemical_symbols()):
f.write(f" {pos[0]:18.14f} {pos[1]:18.14f} {pos[2]:18.14f} {symbol.lower()}\n")
f.write("$end\n")
def build_command(self, coord_file):
"""Build xTB command line.
Parameters
----------
coord_file : str or Path
Path to coordinate file
Returns
-------
list of str
Command line arguments
"""
cmd = [self.xtb_command, str(coord_file)]
# cmd = [self.xtb_command, 'coord']
# Add method flag
if self.method == 'GFN2-xTB':
cmd.extend(['--gfn', '2'])
elif self.method == 'GFN1-xTB':
cmd.extend(['--gfn', '1'])
elif self.method == 'GFN0-xTB':
cmd.extend(['--gfn', '0'])
# Add other parameters
if self.solvent:
cmd.extend(['--gbsa', self.solvent])
cmd.extend(['--acc', str(self.accuracy)])
cmd.extend(['--etemp', str(self.electronic_temperature)])
cmd.extend(['--iterations', str(self.max_iterations)])
cmd.extend(['--chrg', str(self.charge)])
cmd.extend(['--uhf', str(self.uhf)])
# Request gradient calculation
cmd.append('--grad')
# Add any extra arguments
cmd.extend(self.extra_args)
return cmd
def parse_xtb_output(self, output_file):
"""Parse xTB output file for energy.
Parameters
----------
output_file : str or Path
Path to output file
Returns
-------
energy : float
Total energy in eV
"""
with open(output_file, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
# Look for the final total energy
import re
# Pattern: | TOTAL ENERGY -15.878299743742 Eh |
match = re.search(r'\|\s+TOTAL ENERGY\s+([-+]?\d+\.\d+)\s+Eh', content)
if match is None:
raise RuntimeError("Could not parse TOTAL ENERGY from xTB output")
energy_hartree = float(match.group(1))
energy = energy_hartree * Hartree # Convert to eV
return energy
def parse_gradient_file(self, gradient_file):
"""Parse xTB gradient file for forces.
Parameters
----------
gradient_file : str or Path
Path to gradient file
Returns
-------
forces : np.ndarray
Atomic forces in eV/Angstrom, shape (natoms, 3)
"""
with open(gradient_file, 'r') as f:
lines = f.readlines()
# Find gradient section
grad_start = None
for i, line in enumerate(lines):
if line.strip().startswith('$grad'):
grad_start = i + 2 # Skip $grad and cycle line
break
if grad_start is None:
raise RuntimeError("Could not find gradient section in file")
# Read coordinates and gradients
gradients = []
i = grad_start
while i < len(lines):
line = lines[i].strip()
if line.startswith('$end'):
break
# Check if this is a coordinate line (ends with an element symbol)
# Coordinate lines have 4 fields: x y z element
parts = line.split()
if len(parts) == 4 and parts[3].isalpha():
# This is a coordinate line, skip it
i += 1
continue
# Parse gradient line (should have 3 numeric values)
if len(parts) >= 3:
try:
grad = [float(x.replace('D', 'E')) for x in parts[:3]]
gradients.append(grad)
except ValueError:
# Skip lines that can't be parsed as numbers
pass
i += 1
gradients = np.array(gradients)
# Convert gradients to forces
# xTB gives gradients in Hartree/Bohr
# Forces = -gradient, convert to eV/Angstrom
forces = -gradients * (Hartree / Bohr)
return forces
def calculate(self, atoms=None, properties=['energy', 'forces'],
system_changes=all_changes):
"""Run xTB calculation.
Parameters
----------
atoms : ase.Atoms, optional
Atoms object to calculate
properties : list of str, optional
Properties to calculate
system_changes : list of str, optional
List of changes since last calculation
"""
Calculator.calculate(self, atoms, properties, system_changes)
# Determine working directory
if self.keep_files:
tmpdir = self.work_dir
cleanup = False
else:
tmpdir = Path(tempfile.mkdtemp())
cleanup = True
try:
coord_file = tmpdir / 'coord'
gradient_file = tmpdir / 'gradient'
output_file = tmpdir / 'xtb_output.log'
# Write coordinate file
self.write_coord_file(atoms, coord_file)
if self.debug:
print(f"\n{'='*60}")
print("XTB CALCULATION DEBUG INFO")
print(f"{'='*60}")
print(f"Working directory: {tmpdir}")
print(f"\nCoordinate file content:")
with open(coord_file, 'r') as f:
print(f.read())
# Build and run command
cmd = self.build_command(coord_file)
if self.debug:
print(f"\nCommand: {' '.join(cmd)}")
print(f"{'='*60}\n")
try:
# Use shell=True on Windows if needed for PATH resolution
use_shell = platform.system() == 'Windows' and self.xtb_command == 'xtb'
result = subprocess.run(
cmd,
cwd=str(tmpdir),
capture_output=True,
text=True,
check=True,
shell=use_shell,
encoding='utf-8',
errors='replace'
)
# Save output to file
stdout_text = result.stdout if result.stdout else "(no stdout)"
stderr_text = result.stderr if result.stderr else "(no stderr)"
with open(output_file, 'w', encoding='utf-8') as f:
f.write("STDOUT:\n")
f.write(stdout_text)
f.write("\n\nSTDERR:\n")
f.write(stderr_text)
if self.debug:
print("XTB OUTPUT:")
print(stdout_text)
if result.stderr:
print("\nXTB STDERR:")
print(stderr_text)
print(f"\n{'='*60}\n")
except subprocess.CalledProcessError as e:
stdout_text = e.stdout if e.stdout else "(no stdout)"
stderr_text = e.stderr if e.stderr else "(no stderr)"
error_msg = (
f"xTB calculation failed:\n"
f"Command: {' '.join(cmd)}\n"
f"Working dir: {tmpdir}\n"
f"Return code: {e.returncode}\n"
f"Output: {stdout_text}\n"
f"Error: {stderr_text}"
)
if self.debug:
print(f"\nERROR: {error_msg}")
raise RuntimeError(error_msg)
except FileNotFoundError as e:
error_msg = (
f"xTB executable not found:\n"
f"Command: {' '.join(cmd)}\n"
f"Path: {self.xtb_command}\n"
f"Error: {str(e)}"
)
if self.debug:
print(f"\nERROR: {error_msg}")
raise RuntimeError(error_msg)
# Parse results
if not gradient_file.exists():
error_msg = f"Gradient file not found. xTB output:\n{result.stdout if result.stdout else '(no output)'}"
if self.debug:
print(f"\nERROR: {error_msg}")
raise RuntimeError(error_msg)
if self.debug:
print("Gradient file content:")
with open(gradient_file, 'r') as f:
print(f.read())
print(f"{'='*60}\n")
# Parse energy from output and forces from gradient file
energy = self.parse_xtb_output(output_file)
forces = self.parse_gradient_file(gradient_file)
if self.debug:
print(f"Parsed energy: {energy:.6f} eV")
print(f"Parsed forces shape: {forces.shape}")
print(f"Max force magnitude: {np.abs(forces).max():.6f} eV/Å")
print(f"{'='*60}\n")
# Store results
self.results = {
'energy': energy,
'forces': forces,
}
finally:
# Cleanup temporary directory if needed
if cleanup:
import shutil
shutil.rmtree(tmpdir, ignore_errors=True)
class FASTMSO(Optimizer):
"""
FAST-MSO: Deterministic multi-stage optimizer
Stage 1: FIRE (robust for large forces)
Stage 2: MDMin (fast downhill relaxation)
Stage 3: LBFGS (rapid final convergence)
Stage order is monotonic:
FIRE → MDMin → LBFGS
"""
def __init__(
self,
atoms,
restart=None,
logfile='-',
trajectory=None,
f_fire=0.8,
f_md=0.25,
fire_kwargs=None,
md_kwargs=None,
lbfgs_kwargs=None,
):
super().__init__(atoms, restart, logfile, trajectory)
self.f_fire = f_fire
self.f_md = f_md
self.fire_kwargs = fire_kwargs or {}
self.md_kwargs = md_kwargs or {}
self.lbfgs_kwargs = lbfgs_kwargs or {}
# ---- Create optimizers ONCE (important) ----
np.random.seed(0)
self._fire = FIRE(
atoms,
logfile=logfile,
trajectory=trajectory,
**self.fire_kwargs,
)
np.random.seed(0)
self._md = MDMin(
atoms,
logfile=logfile,
trajectory=trajectory,
**self.md_kwargs,
)
np.random.seed(0)
self._lbfgs = LBFGS(
atoms,
logfile=logfile,
trajectory=trajectory,
**self.lbfgs_kwargs,
)
self._stage = "FIRE" # start deterministically
def step(self):
forces = self.atoms.get_forces()
fmax = np.max(np.linalg.norm(forces, axis=1))
old_stage = self._stage
# ---- Monotonic stage switching ----
if self._stage == "FIRE" and fmax < self.f_fire:
self._stage = "MDMin"
elif self._stage == "MDMin" and fmax < self.f_md:
self._stage = "LBFGS"
# ---- Reset optimizer on transition ----
if old_stage != self._stage:
if self._stage == "MDMin":
np.random.seed(0)
self._md = MDMin(
self.atoms,
logfile=self.logfile,
trajectory=self.trajectory,
**self.md_kwargs,
)
elif self._stage == "LBFGS":
np.random.seed(0)
self._lbfgs = LBFGS(
self.atoms,
logfile=self.logfile,
trajectory=self.trajectory,
**self.lbfgs_kwargs,
)
# ---- Execute one step ----
if self._stage == "FIRE":
self._fire.step()
elif self._stage == "MDMin":
self._md.step()
else:
self._lbfgs.step()
# Equation of State functions
def murnaghan(V, Emin, Vmin, B, Bprime):
return Emin + B * Vmin * (1 / (Bprime * (Bprime - 1)) * pow((V / Vmin), 1 - Bprime) +
1 / Bprime * (V / Vmin) - 1 / (Bprime - 1))
def birchMurnaghan(V, Emin, Vmin, B, Bprime):
return Emin + 9.0 / 16.0 * B * Vmin * (pow(pow((Vmin / V), 2.0 / 3.0) - 1, 3.0) * Bprime +
pow(pow(Vmin / V, 2.0 / 3.0) - 1, 2.0) *
(6 - 4.0 * pow(Vmin / V, 2.0 / 3.0)))
def vinet(V, Emin, Vmin, B, Bprime):
x = pow(V / Vmin, 1.0 / 3.0)
return Emin + 2.0 / pow(Bprime - 1, 2.0) * B * Vmin * \
(2.0 - (5.0 + 3.0 * x * (Bprime - 1) - 3.0 * Bprime) *
np.exp(-3.0 / 2.0 * (Bprime - 1.0) * (x - 1.0)))
def calculate_bulk_modulus(calc_atoms, calc, num_points, volume_range, eos_type, results):
"""
Calculate bulk modulus by fitting equation of state to energy-volume data.
Parameters:
-----------
calc_atoms : ASE Atoms object
The atomic structure with calculator assigned
calc : Calculator object
The calculator (MACE or FairChem)
results : dict
Dictionary to store results
"""
# Check if structure is periodic
if not any(calc_atoms.pbc):
st.error("❌ Bulk modulus calculation requires a periodic structure (at least one periodic dimension).")
results["Error"] = "Non-periodic structure"
return
# Get original cell and volume
original_cell = calc_atoms.get_cell()
original_volume = calc_atoms.get_volume()
original_positions_scaled = calc_atoms.get_scaled_positions()
st.write(f"**Original cell volume:** {original_volume:.4f} ų")
st.write(f"**Number of atoms:** {len(calc_atoms)}")
# Generate volume range
volume_factor = volume_range / 100.0
volumes = np.linspace(original_volume * (1 - volume_factor),
original_volume * (1 + volume_factor),
num_points)
# Calculate energies for each volume
energies = []
cell_params_list = []
progress_text = "Calculating energies at different volumes: 0% complete"
progress_bar = st.progress(0, text=progress_text)
for i, vol in enumerate(volumes):
# Scale cell uniformly to achieve target volume
scale_factor = (vol / original_volume) ** (1.0 / 3.0)
new_cell = original_cell * scale_factor
# Create new atoms object with scaled cell but same fractional coordinates
temp_atoms = calc_atoms.copy()
temp_atoms.set_cell(new_cell, scale_atoms=False)
temp_atoms.set_scaled_positions(original_positions_scaled)
temp_atoms.calc = calc
# Calculate energy
try:
energy = temp_atoms.get_potential_energy()
energies.append(energy)
# Store cell parameters
cell_lengths = temp_atoms.cell.cellpar()[:3] # a, b, c
cell_angles = temp_atoms.cell.cellpar()[3:] # alpha, beta, gamma
cell_params_list.append({
'Volume': vol,
'a': cell_lengths[0],
'b': cell_lengths[1],
'c': cell_lengths[2],
'α': cell_angles[0],
'β': cell_angles[1],
'γ': cell_angles[2],
'Energy': energy
})
except Exception as e:
st.error(f"Error calculating energy at volume {vol:.4f} ų: {str(e)}")
progress_bar.empty()
return
progress_val = (i + 1) / len(volumes)
progress_bar.progress(progress_val,
text=f"Calculating energies: {int(progress_val * 100)}% complete")
progress_bar.empty()
# Convert to numpy arrays
volumes = np.array(volumes)
energies = np.array(energies)
# Find minimum energy point for initial guess
min_idx = np.argmin(energies)
V0_guess = volumes[min_idx]
E0_guess = energies[min_idx]
# Estimate bulk modulus from curvature (initial guess)
# B ≈ V * d²E/dV² at minimum
if len(volumes) >= 3:
# Use finite differences for second derivative
dV = volumes[1] - volumes[0]
d2E_dV2 = (energies[min_idx + 1] - 2 * energies[min_idx] + energies[min_idx - 1]) / (dV ** 2) if min_idx > 0 and min_idx < len(energies) - 1 else 0.1
B_guess = max(V0_guess * d2E_dV2, 1.0) # Ensure positive
else:
B_guess = 100.0 # Default guess in eV/Ų
Bprime_guess = 4.0 # Typical value
# Select EOS function
eos_functions = {
"Birch-Murnaghan": birchMurnaghan,
"Murnaghan": murnaghan,
"Vinet": vinet
}
eos_func = eos_functions[eos_type]
# Fit equation of state
try:
popt, pcov = curve_fit(eos_func, volumes, energies,
p0=[E0_guess, V0_guess, B_guess, Bprime_guess],
maxfev=10000)
E_fit, V_fit, B_fit, Bprime_fit = popt
# Convert bulk modulus from eV/Ų to GPa
# 1 eV/Ų = 160.21766208 GPa
B_GPa = B_fit * 160.21766208
# Calculate uncertainties
perr = np.sqrt(np.diag(pcov))
B_err_GPa = perr[2] * 160.21766208
except Exception as e:
st.error(f"❌ Failed to fit {eos_type} equation of state: {str(e)}")
st.info("Try adjusting the volume range or number of points.")
results["Error"] = f"EOS fit failed: {str(e)}"
return
# Store results
results["Bulk Modulus (B₀)"] = f"{B_GPa:.2f} ± {B_err_GPa:.2f} GPa"
results["B₀'"] = f"{Bprime_fit:.3f} ± {perr[3]:.3f}"
results["Equilibrium Volume (V₀)"] = f"{V_fit:.4f} ų"
results["Equilibrium Energy (E₀)"] = f"{E_fit:.6f} eV"
results["EOS Type"] = eos_type
# Display results
st.success("✅ Bulk modulus calculation completed!")
col1, col2 = st.columns(2)
with col1:
st.metric("Bulk Modulus (B₀)", f"{B_GPa:.2f} GPa",
delta=f"± {B_err_GPa:.2f} GPa")
st.metric("Equilibrium Volume (V₀)", f"{V_fit:.4f} ų")
with col2:
st.metric("B₀' (pressure derivative)", f"{Bprime_fit:.3f}",
delta=f"± {perr[3]:.3f}")
st.metric("Equilibrium Energy (E₀)", f"{E_fit:.6f} eV")
# Create data table
st.subheader("Energy vs Volume Data")
df = pd.DataFrame(cell_params_list)
df = df[['Volume', 'Energy', 'a', 'b', 'c', 'α', 'β', 'γ']]
df['Volume'] = df['Volume'].round(4)
df['Energy'] = df['Energy'].round(6)
df['a'] = df['a'].round(4)
df['b'] = df['b'].round(4)