-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFF_Develop.py
More file actions
9700 lines (8013 loc) · 374 KB
/
FF_Develop.py
File metadata and controls
9700 lines (8013 loc) · 374 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
"""
Force-field (FF) development utilities used by the active-learning workflow.
High-level responsibilities covered here:
- Parse the FF/training configuration input file (`*.in`) via
`Setup_Interfacial_Optimization`.
- Represent datasets as `pandas.DataFrame` objects with common columns such as:
`coords`, `at_type`, `natoms`, `sys_name`, `Energy` (and optionally `Forces`).
- Read DFT outputs (Gaussian `.log`) and convert them into a model-ready dataset.
- Fit/optimize FF parameters and evaluate the resulting model.
- Provide active-learning helpers (class `al_help`) for:
- converting `.log` to `.xyz` and loading directories of `.xyz`
- sampling candidates (random perturbation, MC, MD via LAMMPS)
- writing Gaussian input batches (`*.gjf`)
Notes
-----
This module mixes multiple responsibilities (IO, model fitting, plotting, sampling).
The current refactor effort documents the existing behavior without changing it.
Created on Fri Mar 19 18:49:40 2021
@author: nikolas
"""
from numba import jit,prange,njit
#from numba.experimental import jitclass
from pathlib import Path
import os.path
import os
import sys
import numpy as np
np.seterr(invalid='ignore')
import pandas as pd
import matplotlib
import copy
from matplotlib import pyplot as plt
from scipy.optimize import minimize, differential_evolution,dual_annealing
from time import perf_counter
import coloredlogs
import logging
import itertools
import math
from mpmath import erf, mp, exp, sqrt , gamma , power
mp.dps = 32
import collections
import six
import ase
import lammpsreader as lammps_reader
class Parsers():
"""Base class for parsing molecular structure files.
Parameters
----------
filename : str
Path to the file to parse.
**kwargs : dict
Optional keyword arguments (e.g., `name` for system naming).
"""
def __init__(self, filename, **kwargs):
"""Initialize the parser with a filename and optional keyword arguments."""
self.filename = filename
self.kwargs = kwargs
return
def nameit(self):
"""Assign system names to parsed data based on chemistry or user-provided name."""
if 'name' in self.kwargs:
self.data['sys_name'] = self.kwargs['name']
else:
self.data['sys_name'] = [self.chemistry(s) for s in self.data['at_type'].to_list() ]
def chemistry(self,at_types):
"""Generate a chemical formula string from atom types.
Parameters
----------
at_types : list[str]
List of atom type labels.
Returns
-------
str
Chemical formula (e.g., 'C6H12O6').
"""
count = {t:0 for t in np.unique(at_types)}
for at in at_types:
count[at] += 1
name = ''
for t,c in count.items():
name +=t+str(c)
return name
def natoms(self):
"""Compute and store the number of atoms for each structure in the data."""
self.data['natoms'] = [len(at) for at in self.data['at_type']]
return
class readVASP(Parsers):
"""Parser for VASP OUTCAR files.
Parameters
----------
filename : str or None
Single OUTCAR filename (required if `read_many=False`).
path : str or None
Directory path for reading multiple OUTCAR files.
ret_min : bool
If True, return only the minimum energy configuration.
read_many : bool
If True, recursively read all OUTCAR files in `path`.
**kwargs : dict
Passed to parent `Parsers` class.
"""
def __init__(self,filename=None, path=None, ret_min=False, read_many=False, **kwargs):
"""Initialize and parse VASP OUTCAR file(s)."""
super().__init__(filename, **kwargs)
if read_many:
if path is None:
raise Exception('You need to provide path to read_many OUTCAR files')
outcar_files = Path(path).rglob('*OUTCAR*')
print(f'Found {len(outcar_files)} OUTCAR files')
path_file_tuples = [(str(file.parent), file.name) for file in outcar_files]
data = pd.DataFrame()
for j,(p,fn) in enumerate(path_file_tuples):
df = self.read_OUTCAR(fn,p)
data = data.append(df, ignore_index = True)
if j%10 ==0: print(f'... read {j+1} files ...')
else:
if filename is None:
raise Exception('You need to provide filename if read_many = False')
data = self.read_OUTCAR(filename,path)
self.data = data
self.nameit()
self.natoms()
return
def read_OUTCAR(self,filename, path=None, ret_min=False):
"""Read a single VASP OUTCAR file.
Parameters
----------
filename : str
OUTCAR filename.
path : str or None
Directory containing the file.
ret_min : bool
If True, return only the minimum energy frame.
Returns
-------
pandas.DataFrame
Parsed data with `at_type`, `coords`, `Forces`, `Energy`, `readfile`.
"""
if path is None:
fname = filename
else:
fname = f'{path}/{filename}'
images = ase.io.read(fname, index=':') # or read('vasprun.xml', index=':')
at_type, coords, Forces, Energy = [ ], [], [], []
for i, image in enumerate(images):
at_type.append(image.get_chemical_symbols())
coords.append(image.get_positions())
Forces.append(image.get_forces()*23.06054194533) # to kcal/mol
Energy.append(image.get_potential_energy()*23.06054194533) # to kcal/mol
if ret_min:
am = np.array(Energy).argmin()
at_type, coords, Forces, Energy = [at_type[am] ], [coords[am] ], [Forces[am] ], [ Energy[am]]
data = pd.DataFrame({'at_type':at_type, 'coords':coords,'Forces':Forces, 'Energy':Energy,
'readfile':[fname]*len(Energy)})
return data
class npz_Parser(Parsers):
"""Parser for NumPy `.npz` archive files.
Parameters
----------
filename : str
Path to the `.npz` file.
**kwargs : dict
Passed to parent `Parsers` class.
"""
def __init__(self, filename, **kwargs):
"""Initialize and load the `.npz` file."""
super().__init__(filename,**kwargs)
self.dataraw = self._load_npz()
def _load_npz(self):
"""Load the `.npz` file and return its contents as a dictionary."""
try:
with np.load(self.filename, allow_pickle=True) as npz_file:
return {key: npz_file[key] for key in npz_file.files}
except Exception as e:
print(f"Error loading .npz file: {e}")
return {}
def get_keys(self):
"""Return the list of keys in the loaded data."""
return list(self.data.keys())
def get_item(self, key):
"""Retrieve a specific item from the raw data by key."""
return self.dataraw.get(key, None)
class parse_MD17(npz_Parser):
"""Parser for MD17 dataset `.npz` files.
Converts MD17 format to the internal DataFrame representation.
Parameters
----------
filename : str
Path to the MD17 `.npz` file.
**kwargs : dict
Passed to parent `npz_Parser` class.
"""
def __init__(self, filename,**kwargs):
"""Initialize and parse the MD17 dataset."""
super().__init__(filename,**kwargs)
self.to_FFDtool()
self.to_pandas()
self.nameit()
self.natoms()
return
def to_FFDtool(self):
"""Convert MD17 raw data to internal format (atom_types, coords, Forces, total_energy)."""
atom_types = [mappers.nuclear_charge_to_symbol[x]
for x in self.dataraw.get('nuclear_charges') ]
self.atom_types = atom_types
self.coords = self.dataraw.get('coords')
self.Forces = self.dataraw.get('forces')
self.total_energy = self.dataraw.get('energies')
return
def to_pandas(self):
"""Convert internal arrays to a pandas DataFrame."""
data = pd.DataFrame()
data['coords'] = [x for x in self.coords]
data['Forces'] = [x for x in self.Forces]
data['at_type'] = [self.atom_types]*len(data['coords'])
data['Energy'] = self.total_energy
self.data = data
return
class GeometryTransformations:
"""3D coordinate rotation utilities for molecular geometry manipulation."""
@staticmethod
def rotation_matrix_x(angle_rad):
"""Generate a rotation matrix for rotating about the x-axis."""
return np.array([
[1, 0, 0],
[0, np.cos(angle_rad), -np.sin(angle_rad)],
[0, np.sin(angle_rad), np.cos(angle_rad)]
])
@staticmethod
def rotation_matrix_y(angle_rad):
"""Generate a rotation matrix for rotating about the y-axis."""
return np.array([
[np.cos(angle_rad), 0, np.sin(angle_rad)],
[0, 1, 0],
[-np.sin(angle_rad), 0, np.cos(angle_rad)]
])
@staticmethod
def rotation_matrix_z(angle_rad):
"""Generate a rotation matrix for rotating about the z-axis."""
return np.array([
[np.cos(angle_rad), -np.sin(angle_rad), 0],
[np.sin(angle_rad), np.cos(angle_rad), 0],
[0, 0, 1]
])
@staticmethod
def rotate_coordinates(coords, angle_rad_x, angle_rad_y, angle_rad_z):
"""
Rotate coordinates around all three axes (x, y, z) by specified angles in degrees.
Args:
coords (np.array): Nx3 numpy array of x, y, z coordinates.
angle_rad_x, angle_rad_y, angle_rad_z (float): Rotation angles in radians for each axis.
Returns:
np.array: Rotated coordinates.
"""
# Get rotation matrices
rot_matrix_x = GeometryTransformations.rotation_matrix_x(angle_rad_x)
rot_matrix_y = GeometryTransformations.rotation_matrix_y(angle_rad_y)
rot_matrix_z = GeometryTransformations.rotation_matrix_z(angle_rad_z)
# Combined rotation matrix; order of multiplication is important
rot_matrix = rot_matrix_x @ rot_matrix_y @ rot_matrix_z
# Apply the combined rotation matrix to coordinates
return np.dot(coords, rot_matrix.T)
class al_help():
"""Active-learning helper utilities.
This class contains functionality used by the active-learning scripts to:
- Convert Gaussian outputs to training data.
- Sample candidate configurations (perturbation / MC / MD via LAMMPS).
- Write Gaussian input files for the next iteration.
Many methods are `@staticmethod` and operate on `pandas.DataFrame` objects.
"""
def __init__(self):
"""Initialize mapping helpers used by LAMMPS-related routines."""
lammps_style_map = {'Morse':'morse',
'MorseBond':'morse',
'Bezier': 'table linear 50000',
'harmonic':'harmonic',
'LJ':'Default need to fix',
'harmonic3':'Default need to fix',
'Fourier':'Default need to fix',
'expCos':'Default need to fix',
'BezierPeriodic': 'table linear 50000'
}
self.lammps_style_map = lammps_style_map
return
def map_to_lammps_style(self,style):
"""Map an internal interaction style name to the corresponding LAMMPS style."""
return self.lammps_style_map[style]
@staticmethod
def decompose_data_to_structures(df,structs):
"""Decompose each configuration into multiple sub-structures.
Parameters
----------
df : pandas.DataFrame
Dataset with at least `coords`, `at_type`, and `sys_name`.
structs : list[tuple[str]]
List of atom-type groups. For each group, a new structure is created
by selecting atoms whose type belongs to that group.
Returns
-------
pandas.DataFrame
DataFrame containing one row per decomposed structure and an
`original_index` column pointing back to the row in `df`.
"""
nc = [] ; nt = [] ; nn = [] ; ns = []
oid = [] ;
for j, dat in df.iterrows():
c = np.array(dat['coords'])
tys = np.array(dat['at_type'])
for i,struct in enumerate(structs):
f = np.zeros(len(tys),dtype=bool)
for t in struct:
f = np.logical_or(t == tys, f)
newc = c[f]
newtys = tys[f]
natoms = newtys.shape[0]
sys_name =str(j)+'-'+ dat['sys_name']+'__ref'+str(i)
nc.append(newc)
nt.append(list(newtys))
nn.append(natoms)
ns.append(sys_name)
oid.append(j)
decdata = pd.DataFrame({'coords':nc,'at_type':nt,'natoms':nn,'sys_name':ns,'original_index':oid})
return decdata
@staticmethod
def read_lammps_structs(fname,inv_types):
"""Read sampled structures from a LAMMPS trajectory file.
Parameters
----------
fname : str
Path to the LAMMPS trajectory file (e.g. `samples.lammpstrj`).
inv_types : dict[int, str]
Inverse mapping from LAMMPS numeric type IDs to atom type labels.
Returns
-------
pandas.DataFrame
DataFrame with columns `coords`, `at_type`, and `natoms`.
"""
a = lammps_reader.LammpsTrajReader(fname)
coords = []
types = []
natoms = []
while( a.readNextStep() is not None):
crds = np.array([ np.array(a.data[c], dtype=float) for c in ['x','y','z']])
crds = crds.T
cbox = a.box_bounds
tricl = cbox[:,2] != 0.0
if tricl.any():
raise NotImplementedError('Triclinic boxes are not implemented')
offset = cbox[:,0]
box = cbox[:,1]-offset
b2 =box/2
crds -= offset
# Applying periodic condition
cref = crds[0]
r = crds - cref
for j in range(3):
fm = r[:,j] < - b2[j]
fp = r[:,j] > b2[j]
crds[:,j][fm] +=box[j]
crds[:,j][fp] -=box[j]
#print('Reading Lammps')
crds -= crds.mean(axis=0)
tys = [inv_types[t] for t in a.data['type'] ]
coords.append(crds)
types.append(tys)
natoms.append(crds.shape[0])
return pd.DataFrame({'coords':coords,'at_type':types,'natoms':np.array(natoms)})
@staticmethod
def sample_via_lammps(data,setup,parsed_args, beta_sampling):
"""Sample candidate configurations via LAMMPS molecular dynamics.
Parameters
----------
data : pandas.DataFrame
Current training dataset.
setup : Setup_Interfacial_Optimization
Configuration with model parameters.
parsed_args : argparse.Namespace
Command-line arguments with LAMMPS settings.
beta_sampling : float
Inverse temperature for sampling.
Returns
-------
tuple[pandas.DataFrame, float]
`(candidate_data, beta_sampling)` - sampled candidates and updated beta.
"""
print('MD sampling with Lammps')
al = al_help()
cols = data.columns
candidate_data = pd.DataFrame()
lammps_main_file = "lammps_working/sample_run.lmscr"
kB = 0.0019872037514523
tsample = round(1.0/ (beta_sampling*kB), 2)
def update_main_file_temperature(tsample):
with open(lammps_main_file,'r') as fil:
lines = fil.readlines()
fil.closed
for l,line in enumerate(lines):
li = line.split()
if 'variable' in li and 'teff' in li and 'equal' in li:
print(f'Updating temperature to {tsample} K' )
lines[l] = f'variable teff equal {tsample}\n'
with open(lammps_main_file,'w') as fil:
for line in lines:
fil.write(line)
fil.closed
#select randomly 0.01% of the index
unq_sys = np.unique(data['sys_name'])
#old_bonded_inters = 'dumb variable'
for sname in unq_sys:
fs = data['sys_name'] == sname
udat = data [ fs ]
us = udat['Uclass'].to_numpy()
us = us - us.min()
ps = np.exp(-us*beta_sampling)
ps /= ps.sum()
print('Choosing initial configuration for {:s}'.format(sname))
sys.stdout.flush()
t0 = perf_counter()
chosen_index = np.random.choice(np.arange(0,len(udat),1,dtype=int) ,1, replace=False,p=ps)
print('Choice complete time --> {:.3e} sec'.format(perf_counter()-t0))
sys.stdout.flush()
#print('beginning md condifiguration index',chosen_index)
for ii,j in enumerate(udat.index[chosen_index]):
#print('running lammps of data point {:d}, sys_name = {:s}'.format(j, sname))
df = udat.loc[j,cols]
maps = al.get_lammps_maps(df,parsed_args)
inv_types = {v:k for k,v in maps['types_map'].items()}
bonded_inters = al.write_Lammps_dat(df,setup,maps['types_map'],maps['mass_map'],maps['charge_map'])
al_help.write_potential_files(setup,df, parsed_args,bonded_inters)
al.write_rigid_fixes(setup,'lammps_working',maps['types_map'])
sn = sname.replace('(','_')
sn = sn.replace(')','_')
naming = 'iter{:d}_{:d}-{:s}'.format(parsed_args.num+1,ii,sn)
c1 = 'cd lammps_working'
c2 = 'bash lammps_sample_run.sh'
c3 = 'mkdir {0:s} ; cp samples.lammpstrj {0:s}/ ; mv structure.dat {0:s}'.format(naming)
c4 = 'mv potential.inc {0:s}/ ; mv rigid_fixes.inc {0:s}'.format(naming)
c5 = ' cd - '
command = ' ; '.join([c1,c2])
well_defined_structures = False
md_iter = 0
while well_defined_structures == False and md_iter < 100:
os.system(command)
new_data = al_help.read_lammps_structs('lammps_working/samples.lammpstrj',inv_types)
ne = len(new_data)
new_data = al_help.clean_well_separated_nanostructures(new_data, setup)
if len(new_data) < 0.1*ne:
print(f'MD iter {md_iter}: More than 90% of the structures were well separated! rescaling beta by 1.1 to avoid desorption or dissolution')
beta_sampling *= 1.1
tsample = round(1.0/ (beta_sampling*kB), 5)
update_main_file_temperature(tsample)
md_iter += 1
sys.stdout.flush()
continue
else:
well_defined_structures = True
al_help.evaluate_potential(new_data, setup,'opt')
ut = new_data['Uclass'].to_numpy()
shifted_energies = ut - ut.min()
tfit, beta_eff, alpha, weights, l_minima, fail = al_help.estimate_Teff_Beff(shifted_energies, nbins = 200 )
al_help.plot_candidate_distribution(shifted_energies, (beta_eff, alpha, weights, l_minima), 200,
title = f'MD:' + r' Candidate distribution $\beta_{eff}$' + ' = {:5.4f}'.format( beta_eff) + r' $\beta_{sampling}$' + ' = {:5.4f}'.format( beta_sampling),
fname=f'{setup.runpath}/CD{md_iter}_{sname}.png')
os.system(' ; '.join([c1, c3,c4,c5]) )
new_data['sys_name'] = sname
candidate_data = candidate_data.append(new_data, ignore_index=True)
print('Lammps Simulations complete')
sys.stdout.flush()
return candidate_data, beta_sampling
@staticmethod
def coordinate_simulated_annealing(data, r_setup):
"""Perform simulated annealing on atomic coordinates (stub implementation)."""
sysnames = np.unique(data['sys_name'])
for sys in sysnames:
sys_data = data [ sys == data['sys_name'] ]
c = copy.deepcopy(np.array([ c for c in sys_data['coords'].to_numpy()]))
init_data = copy.deepcopy(sys_data[['at_type','sys_name','natoms','coords', 'bodies']])
init_data['coords'] = c
natoms = init_data['natoms'].to_numpy()[0]
params = c.flatten()
@staticmethod
def beta_distribution_fit_fail_strategy(u , setup, beta_sampling ):
"""Adjust beta_sampling when distribution fitting fails.
Parameters
----------
u : numpy.ndarray
Energy values.
setup : Setup_Interfacial_Optimization
Configuration with `bS` parameter.
beta_sampling : float
Current inverse temperature.
Returns
-------
float
Adjusted beta_sampling value.
"""
bs = setup.bS
u = u - u.min()
urange = u.max()
outlier = u.max() - u.mean()
if outlier > bs/beta_sampling:
print('Found high energy outliers beta_sampling is doubled!')
new_beta_sampling = beta_sampling*2
elif urange < bs/beta_sampling:
print('Found very small energy range beta_sampling is halfed!')
new_beta_sampling = beta_sampling/2
else:
print('Found no particular reason of fitting failing --> beta_sampling is scaled randomly between 0.66 and 1.34!')
new_beta_sampling = beta_sampling*np.random.uniform(0.66,1.34)
return new_beta_sampling
@staticmethod
def MC_sample(data, setup, parsed_args, beta_sampling):
"""Sample candidate configurations via Metropolis-Hastings Monte Carlo.
Parameters
----------
data : pandas.DataFrame
Current training dataset with `coords`, `bodies`, `sys_name`.
setup : Setup_Interfacial_Optimization
Configuration with model parameters and `bS`.
parsed_args : argparse.Namespace
Command-line arguments with `sigma` for perturbation.
beta_sampling : float
Inverse temperature for acceptance probability.
Returns
-------
tuple[pandas.DataFrame, float]
`(candidate_data, beta_sampling)` - sampled candidates and beta.
"""
max_mc_steps = 40000
max_candidates_per_system = 40000
kB = 0.0019872037514523
sigma_init = parsed_args.sigma
c = copy.deepcopy(data['coords'].to_numpy())
init_data = copy.deepcopy(data[['at_type','sys_name','natoms','coords', 'bodies']])
init_data['coords'] = c
systems = np.unique(init_data['sys_name'])
asymptotic_steps = 100
candidate_data = pd.DataFrame()
for sysname in systems:
sys_data = init_data [ init_data['sys_name'] == sysname]
step_data = copy.deepcopy(sys_data)
al_help.evaluate_potential(step_data, setup,'opt')
Uclass = step_data['Uclass'].to_numpy().copy()
bs = setup.bS
prop_sel = np.exp( - (Uclass - Uclass.min())*beta_sampling )
prop_sel /= prop_sel.sum()
all_indexes = np.array(step_data.index)
try:
idx_chosen = np.random.choice(all_indexes, size= min(len(step_data),100) , replace=False, p = prop_sel)
except ValueError:
idx_chosen = np.random.choice(all_indexes, size= min(len(step_data),100) , replace=False, p = None)
step_data = step_data.loc[idx_chosen]
al_help.evaluate_potential(step_data, setup,'opt')
Uclass_prev = step_data['Uclass'].to_numpy().copy()
n = len(step_data)
step, c_size , sigma, avg_accept_ratio, AR = 0, 0 , sigma_init, 0.0, 0.0
candidate_data_sys = pd.DataFrame()
while(step <= max_mc_steps and c_size <= max_candidates_per_system):
all_new_coords = []
old_coords = copy.deepcopy(step_data['coords'].to_numpy())
for j,dat in step_data.iterrows():
new_coords = al_help.petrube_coords(np.array(dat['coords']) ,sigma, 'random_walk', dat['bodies'])
all_new_coords.append(new_coords)
step_data.loc[step_data.index,'coords'] = all_new_coords
al_help.evaluate_potential(step_data, setup,'opt')
Uclass_new = step_data['Uclass'].to_numpy()
beta_anneal = max( beta_sampling, max_candidates_per_system/(2*(c_size+n)) * beta_sampling )
dubt = (Uclass_new - Uclass_prev )*beta_anneal
pe = np.exp( - dubt )
accepted_filter = pe > np.random.uniform(0,1,n)
not_accepted_filter = np.logical_not(accepted_filter)
step_data.loc[ not_accepted_filter, 'coords'] = old_coords[not_accepted_filter]
Uclass_prev [ accepted_filter ] = Uclass_new [accepted_filter].copy()
Uclass_prev [ not_accepted_filter ] = Uclass_prev [ not_accepted_filter].copy()
accept_ratio = np.count_nonzero(accepted_filter)/n
avg_accept_ratio += accept_ratio
if step %200 ==0:
print( 'MC step {:d}, beta_anneal = {:.4e} , sigma = {:.4e} A , accept_ratio = {:5.4f} , current_accept = {:5.4f} candidate size = {:d}'.format(step, beta_anneal, sigma, AR, accept_ratio, c_size) )
sys.stdout.flush()
step += 1
if step < asymptotic_steps:
continue
AR = avg_accept_ratio/step
if AR < 0.2:
sigma*=0.99
elif AR > 0.5:
sigma/=0.99
sigma = min( max(sigma,sigma_init*1e-1) , sigma_init*1e1)
filtered_step_data = step_data[ accepted_filter ]
candidate_data_sys = pd.concat( (candidate_data_sys, filtered_step_data), ignore_index=True)
c_size = len(candidate_data_sys)
########
print('Metropolis Hastings completed! Average acceptance {:5.4f}'.format( AR ) )
u = candidate_data_sys['Uclass'].to_numpy()
tfit, beta_eff, alpha, weights, l_minima, fail = al_help.estimate_Teff_Beff(u, nbins = 200)
print('Candidate distribution MC: beta_eff = {:5.4f} , beta_sampling = {:5.4f}'.format ( beta_eff, beta_sampling) )
al_help.plot_candidate_distribution(u - u.min(), (beta_eff, alpha, weights, l_minima), 200,
title = f'MC trial' + r': Candidate distribution $\beta_{eff}$' + ' = {:5.4f}'.format( beta_eff) + r' $\beta_{sampling}$' + ' = {:5.4f}'.format( beta_sampling),
fname=f'{setup.runpath}/CD_{sysname}.png')
candidate_data = candidate_data.append(candidate_data_sys,ignore_index=True)
print('Metropolis Hastings completed! Average acceptance {:5.4f}'.format( c_size/(n*(step) ) ) )
#raise Exception('Debuging. Want to stop here')
return candidate_data , beta_sampling
@staticmethod
def plot_candidate_distribution(u, fitting_params, bins, title = '', fname=None):
"""Plot histogram of candidate energies with fitted distribution overlay.
Parameters
----------
u : numpy.ndarray
Candidate energies (typically shifted so min=0).
fitting_params : tuple
`(beta, alpha, weights, local_minima)` from `estimate_Teff_Beff`.
bins : int
Number of histogram bins.
title : str
Plot title.
fname : str or None
If provided, save figure to this path.
"""
u_sorted = np.sort(u)
Pfit = al_help.joint_power_law_Boltzmann_distribution_multy_minima(u_sorted, *fitting_params)
_ = plt.figure(figsize = (3.3,3.3), dpi=300)
if title != '':
plt.title(title, fontsize = 5.5)
hist,bin_edges = np.histogram(u, bins=bins,density = True)
plt.hist(u, bins=bins,density = True,label = 'candidates', color='blue')
beta, alpha, wl, u_min_l = fitting_params
lstyle =[':','-.','--']*5
for w, ul, j in zip(wl, u_min_l, range(len(wl)) ):
pl = w * al_help.joint_power_law_Boltzmann_distribution_multy_minima(u_sorted, beta, alpha, [1.0], [ul])
plt.plot(u_sorted, pl, ls=lstyle[j], color='orange', label=r'$u_l$ at {:3.2f}'.format(ul), lw =0.75 )
plt.plot(u_sorted, Pfit, ls ='-',label='fit', color='red')
plt.legend(frameon=False, fontsize=7)
if fname is not None:
plt.savefig(fname, bbox_inches='tight')
plt.close()
#plt.close()
return
@staticmethod
def joint_Boltzman_Gaussian_distribution(u, beta, cv, mu):
"""Compute joint Boltzmann-Gaussian distribution (analytical form)."""
P = (beta**2 / np.sqrt(2*np.pi*cv) ) * np.exp(-beta*u) * np.exp( - (beta**2/(2*cv) ) * (u -mu)**2 )
norm = (beta/2) * np.exp(-beta*mu + cv/2) * ( erf( (beta*mu-cv)/np.sqrt(2*cv) ) + 1 )
return P/norm
@staticmethod
def Irecurr (beta, alpha, n ):
"""Compute recursively the integral moments I_0 ... I_n for Boltzmann-Maxwellian."""
ab = beta * alpha
b4a = beta/(4.0*alpha)
if b4a < 50:
f0 = exp(b4a) * ( 1 - erf(sqrt(b4a)) )
else:
f0 = 1/sqrt(np.pi*b4a)
I0 = 0.5 * sqrt(np.pi/ab) * f0
I1 = (1.0 - beta*I0)/(2*ab)
ir = [I0, I1]
for i in range(2, n+1):
ir_i = ( (i-1)*ir[i-2] - beta*ir[i-1] ) / (2*ab)
ir.append( ir_i )
return tuple([np.float64(i) for i in ir])
@staticmethod
def joint_Boltzman_Maxwellian_distribution_multy_minima(u, beta, alpha, w_l=[1.0], min_u_l=[0.0]):
"""Boltzmann-Maxwellian distribution with multiple local minima."""
I0, I1, I2 = al_help.Irecurr(beta, alpha, 2)
sw = np.sum(w_l)
P = 0.0
for w,u_l in zip(w_l, min_u_l):
P += (w/sw) * al_help.P(u - u_l ,beta, alpha)
return P/I2
@staticmethod
def joint_power_law_Boltzmann_distribution_multy_minima(u, beta, alpha, w_l =[1.0], min_u_l = [0.0]):
"""Power-law * Boltzmann distribution with multiple local minima.
This is the primary model used to fit candidate energy distributions.
Parameters
----------
u : numpy.ndarray
Energy values.
beta : float
Inverse temperature.
alpha : float
Power-law exponent (related to effective heat capacity).
w_l : list[float]
Weights for each local minimum.
min_u_l : list[float]
Energy offsets for each local minimum.
Returns
-------
numpy.ndarray
Probability density at each `u` value.
"""
C = np.float64( gamma(alpha + 1.0)/power(beta,(alpha+1)) )
sw = np.sum(w_l)
P = 0.0
for w,u_l in zip(w_l, min_u_l):
normalizing_factor = C*np.exp(-beta*u_l)
pu = (w/sw) * np.power( (u-u_l), alpha) * np.exp( - beta*u ) / normalizing_factor
pu [ u <u_l] = 0.0
P+=pu
return P
@staticmethod
def P(u, beta, alpha):
"""Unnormalized Boltzmann-Maxwellian kernel."""
pu = u**2 * np.exp(-beta*u) * np.exp(-alpha*beta*u**2)
pu[ u <0 ] = 0.0
return pu
@staticmethod
def joint_Boltzman_Maxwellian_distribution(u, beta, alpha):
"""Normalized Boltzmann-Maxwellian distribution (single minimum)."""
I0, I1, I2 = al_help.Irecurr(beta, alpha, 2)
P = u**2 * np.exp(-beta*u) * np.exp(-alpha*beta*u**2)
return P/I2
@staticmethod
def find_distribution_parameters(u, nminima=0,nbins=200):
"""Fit a power-law * Boltzmann distribution to candidate energies.
Uses SLSQP optimization to find `(beta, alpha, weights, local_minima)`
that best fit the histogram of `u`.
Parameters
----------
u : numpy.ndarray
Candidate energies.
nminima : int
Number of additional local minima to fit (0 = single minimum).
nbins : int
Number of histogram bins.
Returns
-------
tuple
`((beta, alpha, w_l, min_u_l), cost)` where `cost` is the fitting error.
"""
u = u - u.min()
mu = np.mean(u)
params = [ 1.0, 0.0033 ] # beta, alpha
bounds = [ [0.02,40], [0.003,8.004]]
if nminima > 0:
for _ in range(nminima +1):
# adding the weights
params.append(0.5)
bounds.append([0,1.0])
umax = u.max()
for j in range(nminima):
# adding initializations about the minima
params.append( np.random.uniform(0,1))
bounds.append([0,umax])
params = np.array(params)
kB = 0.00198720375145233
def get_params( params, n_l):
beta, alpha = params[0], params[1]
if n_l>0:
n_w = n_l + 1
n_w_e = n_w + 2
w_l = params[2:n_w_e]
min_u_l = np.array([0.0, *list( params[ n_w_e : n_w_e + n_l ] )] )
else:
w_l = [1.0]
min_u_l = [ 0.0 ]
return beta, alpha, w_l, min_u_l
def reg_cost(params, n_l):
c2 = 0.0
c1 = 0.0
if n_l >0:
w_l = params[2:3+n_l]
w = w_l/w_l.sum()
nw = w.shape[0]
for i in range(nw):
#c1 += w[i]**2
for j in range(i+1,nw):
c2 += w[i]*w[j]
for k in range(j+1,nw):
c1 += w[i]*w[j]*w[k]
c2 /= math.perm(nw,2)
if nw>2:
c1 /= math.perm(nw,3)
return 0.2*(c2 + c1)
def weights_to_one(params, n_l):
w = params[2:3+n_l]
return w.sum() -1
def cost_BG(params, dens ,bc, n_l):
c = cost_distribution_fit(params, dens, bc, n_l)
creg = reg_cost(params,n_l)
return c + creg
def cost_distribution_fit(params, dens, bc, n_l):
beta, alpha, w_l, min_u_l = get_params( params, n_l)
ps = al_help.joint_power_law_Boltzmann_distribution_multy_minima(bc,beta, alpha, w_l, min_u_l)
return 100*np.sum( np.abs(ps - dens ) ) /ps.shape[0]
dens, bin_edges = np.histogram(u, bins=nbins, density=True)
bc = bin_edges[0 : -1] - 0.5*(bin_edges[1]-bin_edges[0])
args = (dens , bc, nminima)
#res = dual_annealing(cost_BG, bounds, args = args, initial_temp=15000, maxiter=3500, restart_temp_ratio=2e-04)
best_cost = 1e16
t0 = perf_counter()
for ntry in range(50):
res = minimize(cost_BG, params,args = args, bounds=bounds,tol=1e-4, method = 'SLSQP', constraints = {'type':'eq','fun':weights_to_one, 'args': (nminima,) } )
if res.fun < best_cost:
best_cost = res.fun
best_trial = ntry
best_params = res.x.copy()
params = np.array([ np.random.uniform(bounds[i][0], bounds[i][1]) for i in range(params.shape[0]) ] )
tf = perf_counter() - t0
print('SLSQP best trial {:d} , finished in {:.3e} sec costf = {:5.4f}'.format(best_trial,tf, best_cost))
beta, alpha, w_l, min_u_l = get_params( best_params, nminima)
cfit = cost_distribution_fit(best_params , dens, bc, nminima)
reg = reg_cost(best_params, nminima)
cv_eff = u.var()*kB*beta**2
print ('bins = {:d}, beta = {:5.4f}, alpha = {:5.4f} costf = {:8.7f} reg_cost = {:8.7f} cv_histogram = {:5.4f} kcal/mol/K'.format(nbins, beta, alpha, cfit, reg, cv_eff))
w_l = np.array(w_l)/np.sum(w_l)
al_help.plot_candidate_distribution(u, (beta, alpha, w_l, min_u_l), nbins,
title = f'nl {nminima}:' + r'$\beta_{eff}$ =' + '{:5.4f}'.format(beta),
fname=f'Results/nl{nminima}.png')
return (beta, alpha, w_l, min_u_l), cfit
@staticmethod
def estimate_Teff_Beff(u, nbins = 200):
"""Estimate effective temperature and inverse temperature from candidate energies.
Iteratively fits `joint_power_law_Boltzmann_distribution_multy_minima`
with increasing number of local minima until the fit converges.
Parameters
----------
u : numpy.ndarray
Candidate energies.
nbins : int
Number of histogram bins for fitting.
Returns
-------
tuple
`(Teff, beta, alpha, weights, local_minima, fail)` where `fail`
is True if fitting did not converge reliably.
"""
u = u -u.min()
dens, bin_edges = np.histogram(u, bins=nbins, density=True)
std = np.sqrt(dens/u.shape[0]).sum()/nbins*100
print('Standard error of the data = {:8.6f}'.format(std))
rel_err = 1e16
old_err = 1e16