-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
3165 lines (2762 loc) · 129 KB
/
__init__.py
File metadata and controls
3165 lines (2762 loc) · 129 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 numpy as np
import json
from ase.calculators.calculator import Calculator
from ase.data import atomic_numbers
from ase.parallel import paropen
import os
import sys
import ase
from ase import io as aseio
import tempfile
import warnings
from datetime import datetime
import multiprocessing as mp
import gc
import sqlite3
from collections import OrderedDict
import platform
from getpass import getuser
from socket import gethostname
from scipy.optimize import fmin_bfgs as optimizer
from ase.calculators.neighborlist import NeighborList
from utilities import ConvergenceOccurred, IO
from utilities import TrainingConvergenceError, ExtrapolateError, hash_image
from utilities import Logger, save_parameters
from descriptor import Gaussian, Bispectrum, Zernike
from regression import NeuralNetwork
try:
from . import fmodules # version 4 of fmodules
fmodules_version = 4
except ImportError:
fmodules = None
try:
from ase import __version__ as aseversion
except ImportError:
# We're on ASE 3.10 or older
from ase.version import version as aseversion
###############################################################################
class SimulatedAnnealing:
"""
Class that implements simulated annealing algorithm for global search of
variables. This algorithm is helpful to be used for pre-conditioning of the
initial guess of variables for optimization of non-convex functions.
:param temperature: Initial temperature which corresponds to initial
variance of the likelihood normal probability
distribution. Should take a value from 50 to 100.
:type temperature: float
:param steps: Number of search iterations.
:type steps: int
:param acceptance_criteria: A float in the range of zero to one.
Temperature will be controlled such that
acceptance rate meets this criteria.
:type acceptance_criteria: float
"""
###########################################################################
def __init__(self, temperature, steps, acceptance_criteria=0.5):
self.temperature = temperature
self.steps = steps
self.acceptance_criteria = acceptance_criteria
###########################################################################
def initialize(self, variables, log, costfxn):
"""
Function to initialize this class with.
:param variables: Calibrating variables.
:type variables: list
:param log: Write function at which to log data. Note this must be a
callable function.
:type log: Logger object
:param costfxn: Object of the CostFxnandDer class.
:type costfxn: object
"""
self.variables = variables
self.log = log
self.costfxn = costfxn
self.log.tic('simulated_annealing')
self.log('Simulated annealing started. ')
###########################################################################
def get_variables(self,):
"""
Function that samples from the space of variables according to
simulated annealing algorithm.
:returns: Best variables minimizing the cost function.
"""
head1 = ('%4s %6s %6s %6s %6s %6s %6s %8s')
self.log(head1 % ('step',
'temp',
'newcost',
'newlogp',
'oldlogp',
'pratio',
'rand',
'accpt?(%)'))
self.log(head1 % ('=' * 4,
'=' * 6,
'=' * 6,
'=' * 6,
'=' * 6,
'=' * 6,
'=' * 6,
'=' * 8))
variables = self.variables
len_of_variables = len(variables)
temp = self.temperature
calculate_gradient = False
self.costfxn.param.regression._variables = variables
if self.costfxn.fortran:
task_args = (self.costfxn.param, calculate_gradient)
(energy_square_error, force_square_error, _) = \
self.costfxn._mp.share_cost_function_task_between_cores(
task=_calculate_cost_function_fortran,
_args=task_args, len_of_variables=len_of_variables)
else:
task_args = (self.costfxn.reg, self.costfxn.param,
self.costfxn.sfp, self.costfxn.snl,
self.costfxn.energy_coefficient,
self.costfxn.force_coefficient,
self.costfxn.train_forces, len_of_variables,
calculate_gradient, self.costfxn.save_memory,)
(energy_square_error, force_square_error, _) = \
self.costfxn._mp.share_cost_function_task_between_cores(
task=_calculate_cost_function_python,
_args=task_args, len_of_variables=len_of_variables)
square_error = \
self.costfxn.energy_coefficient * energy_square_error + \
self.costfxn.force_coefficient * force_square_error
allvariables = [variables]
besterror = square_error
bestvariables = variables
accepted = 0
step = 0
while step < self.steps:
# Calculating old log of probability
logp = - square_error / temp
# Calculating new log of probability
_steps = np.random.rand(len_of_variables) * 2. - 1.
_steps *= 0.2
newvariables = variables + _steps
calculate_gradient = False
self.costfxn.param.regression._variables = newvariables
if self.costfxn.fortran:
task_args = (self.costfxn.param, calculate_gradient)
(energy_square_error, force_square_error, _) = \
self.costfxn._mp.share_cost_function_task_between_cores(
task=_calculate_cost_function_fortran,
_args=task_args, len_of_variables=len_of_variables)
else:
task_args = (self.costfxn.reg, self.costfxn.param,
self.costfxn.sfp, self.costfxn.snl,
self.costfxn.energy_coefficient,
self.costfxn.force_coefficient,
self.costfxn.train_forces, len_of_variables,
calculate_gradient, self.costfxn.save_memory)
(energy_square_error, force_square_error, _) = \
self.costfxn._mp.share_cost_function_task_between_cores(
task=_calculate_cost_function_python,
_args=task_args, len_of_variables=len_of_variables)
new_square_error = \
self.costfxn.energy_coefficient * energy_square_error + \
self.costfxn.force_coefficient * force_square_error
newlogp = - new_square_error / temp
# Calculating probability ratio
pratio = np.exp(newlogp - logp)
rand = np.random.rand()
if rand < pratio:
accept = True
accepted += 1.
else:
accept = False
line = ('%5s' ' %5.2f' ' %5.2f' ' %5.2f' ' %5.2f' ' %3.2f'
' %3.2f' ' %5s')
self.log(line % (step,
temp,
new_square_error,
newlogp,
logp,
pratio,
rand,
'%s(%i)' % (accept,
int(accepted * 100 / (step + 1)))))
if new_square_error < besterror:
bestvariables = newvariables
besterror = new_square_error
if accept:
variables = newvariables
allvariables.append(newvariables)
square_error = new_square_error
# Changing temprature according to acceptance ratio
if (accepted / (step + 1) < self.acceptance_criteria):
temp += 0.0005 * temp
else:
temp -= 0.002 * temp
step += 1
self.log('Simulated annealing exited. ', toc='simulated_annealing')
self.log('\n')
return bestvariables
###############################################################################
###############################################################################
###############################################################################
class Amp(Calculator):
"""
Atomistic Machine-Learning Potential (Amp) ASE calculator
:param descriptor: Class representing local atomic environment. Can be
only None and Gaussian for now. Input arguments for
Gaussian are cutoff and Gs; for more information see
docstring for the class Gaussian.
:type descriptor: object
:param regression: Class representing the regression method. Can be only
NeuralNetwork for now. Input arguments for NeuralNetwork
are hiddenlayers, activation, weights, and scalings; for
more information see docstring for the class
NeuralNetwork.
:type regression: object
:param fingerprints_range: Range of fingerprints of each chemical species.
Should be fed as a dictionary of chemical
species and a list of minimum and maximun, e.g:
>>> fingerprints_range={"Pd": [0.31, 0.59], "O":[0.56, 0.72]}
:type fingerprints_range: dict
:param load: Path for loading an existing parameters of Amp calculator.
:type load: str
:param label: Default prefix/location used for all files.
:type label: str
:param dblabel: Optional separate prefix/location for database files,
including fingerprints, fingerprint primes, and
neighborlists. This file location can be shared between
calculator instances to avoid re-calculating redundant
information. If not supplied, just uses the value from
label.
:type dblabel: str
:param extrapolate: If True, allows for extrapolation, if False, does not
allow.
:type extrapolate: bool
:param fortran: If True, will use fortran modules, if False, will not.
:type fortran: bool
:raises: RuntimeError
"""
implemented_properties = ['energy', 'forces']
default_parameters = {
'descriptor': Gaussian(),
'regression': NeuralNetwork(),
'fingerprints_range': None,
}
###########################################################################
def __init__(self, load=None, label='', dblabel='', extrapolate=True,
fortran=True, **kwargs):
log = Logger(os.path.join(label, 'log.txt'))
self.log = log
# self._printheader(log)
self.extrapolate = extrapolate
self.fortran = fortran
self.dblabel = dblabel
if self.fortran and not fmodules:
raise RuntimeError('Not using fortran modules. '
'Either compile fmodules as described in the '
'README for improved performance, or '
'initialize calculator with fortran=False.')
if self.fortran and fmodules:
wrong_version = fmodules.check_version(version=fmodules_version)
if wrong_version:
raise RuntimeError('Fortran part is not updated. Recompile'
'with f2py as described in the README. '
'Correct version is %i.'
% fmodules_version)
# Reading parameters from existing file if any:
if load:
try:
json_file = paropen(load, 'rb')
except IOError:
json_file = paropen(os.path.join(load,
'trained-parameters.json'),
'rb')
parameters = json.load(json_file)
kwargs = {}
kwargs['fingerprints_range'] = parameters['fingerprints_range']
if parameters['descriptor'] == 'Gaussian':
kwargs['descriptor'] = \
Gaussian(cutoff=parameters['cutoff'],
Gs=parameters['Gs'],
fingerprints_tag=parameters['fingerprints_tag'],)
elif parameters['descriptor'] == 'Bispectrum':
kwargs['descriptor'] = \
Bispectrum(cutoff=parameters['cutoff'],
Gs=parameters['Gs'],
jmax=parameters['jmax'],
fingerprints_tag=parameters[
'fingerprints_tag'],)
elif parameters['descriptor'] == 'Zernike':
kwargs['descriptor'] = \
Zernike(cutoff=parameters['cutoff'],
Gs=parameters['Gs'],
nmax=parameters['nmax'],
fingerprints_tag=parameters['fingerprints_tag'],)
elif parameters['descriptor'] == 'None':
kwargs['descriptor'] = None
if parameters['no_of_atoms'] == 'None':
parameters['no_of_atoms'] = None
else:
raise RuntimeError('Descriptor is not recognized to Amp. '
'User should add the descriptor under '
'consideration.')
if parameters['regression'] == 'NeuralNetwork':
kwargs['regression'] = \
NeuralNetwork(hiddenlayers=parameters['hiddenlayers'],
activation=parameters['activation'],)
kwargs['regression']._variables = parameters['variables']
if kwargs['descriptor'] is None:
kwargs['no_of_atoms'] = parameters['no_of_atoms']
else:
raise RuntimeError('Regression method is not recognized to '
'Amp for loading parameters. User should '
'add the regression method under '
'consideration.')
Calculator.__init__(self, label=label, **kwargs)
param = self.parameters
if param.descriptor is not None:
self.fp = param.descriptor
self.reg = param.regression
self.reg.initialize(param, load)
###########################################################################
def set(self, **kwargs):
"""
Function to set parameters.
"""
changed_parameters = Calculator.set(self, **kwargs)
# FIXME. Decide whether to call reset. Decide if this is
# meaningful in our implementation!
if len(changed_parameters) > 0:
self.reset()
###########################################################################
def set_label(self, label):
"""
Sets label, ensuring that any needed directories are made.
:param label: Default prefix/location used for all files.
:type label: str
"""
Calculator.set_label(self, label)
# Create directories for output structure if needed.
if self.label:
if (self.directory != os.curdir and
not os.path.isdir(self.directory)):
os.makedirs(self.directory)
###########################################################################
def initialize(self, atoms):
"""
:param atoms: ASE atoms object.
:type atoms: ASE dict
"""
self.par = {}
self.rc = 0.0
self.numbers = atoms.get_atomic_numbers()
self.forces = np.empty((len(atoms), 3))
self.nl = NeighborList([0.5 * self.rc + 0.25] * len(atoms),
self_interaction=False)
###########################################################################
def calculate(self, atoms, properties, system_changes):
"""
Calculation of the energy of system and forces of all atoms.
"""
Calculator.calculate(self, atoms, properties, system_changes)
no_of_atoms = len(atoms)
param = self.parameters
if param.descriptor is None: # pure atomic-coordinates scheme
self.reg.initialize(param=param,
atoms=atoms)
param = self.reg.ravel_variables()
if param.regression._variables is None:
raise RuntimeError("Calculator not trained; can't return "
'properties.')
if 'numbers' in system_changes:
self.initialize(atoms)
self.nl.update(atoms)
if param.descriptor is not None: # fingerprinting scheme
self.cutoff = param.descriptor.cutoff
# FIXME: What is the difference between the two updates on the top
# and bottom? Is the one on the top necessary? Where is self.nl
# coming from?
# Update the neighborlist for making fingerprints. Used if atoms
# position has changed.
_nl = NeighborList(cutoffs=([self.cutoff / 2.] *
no_of_atoms),
self_interaction=False,
bothways=True,
skin=0.)
_nl.update(atoms)
self.fp._nl = _nl
self.fp.initialize(self.fortran, atoms)
# If fingerprints_range is not available, it will raise an error.
if param.fingerprints_range is None:
raise RuntimeError('The keyword "fingerprints_range" is not '
'available. It can be provided to the '
'calculator either by introducing a JSON '
'file, or by directly feeding the keyword '
'to the calculator. If you do not know the '
'values but still want to run the '
'calculator, initialize it with '
'fingerprints_range="auto".')
# If fingerprints_range is not given either as a direct keyword or
# as the josn file, but instead is given as 'auto', it will be
# calculated here.
if param.fingerprints_range == 'auto':
warnings.warn('The values of "fingerprints_range" are not '
'given. The user is expected to understand what '
'is being done!')
param.fingerprints_range = \
calculate_fingerprints_range(self.fp,
self.reg.elements,
self.fp.atoms,
_nl)
# Deciding on whether it is exptrapoling or interpolating is
# possible only when fingerprints_range is provided by the user.
elif self.extrapolate is False:
if compare_train_test_fingerprints(self.fp,
self.fp.atoms,
param.fingerprints_range,
_nl) == 1:
raise ExtrapolateError('Trying to extrapolate, which'
' is not allowed. Change to '
'extrapolate=True if this is'
' desired.')
##################################################################
if properties == ['energy']:
self.reg.reset_energy()
self.energy = 0.0
if param.descriptor is None: # pure atomic-coordinates scheme
input = (atoms.positions).ravel()
self.energy = self.reg.get_energy(input,)
else: # fingerprinting scheme
index = 0
while index < no_of_atoms:
symbol = atoms[index].symbol
n_indices, n_offsets = _nl.get_neighbors(index)
# for calculating fingerprints, summation runs over
# neighboring atoms of type I (either inside or outside
# the main cell)
n_symbols = [atoms[n_index].symbol
for n_index in n_indices]
Rs = [atoms.positions[n_index] +
np.dot(n_offset, atoms.get_cell())
for n_index, n_offset in zip(n_indices, n_offsets)]
indexfp = self.fp.get_fingerprint(index, symbol,
n_symbols, Rs)
len_of_indexfp = len(indexfp)
# fingerprints are scaled to [-1, 1] range
scaled_indexfp = [None] * len_of_indexfp
count = 0
while count < len_of_indexfp:
if (param.fingerprints_range[symbol][count][1] -
param.fingerprints_range[symbol][count][0]) \
> (10.**(-8.)):
scaled_value = -1. + \
2. * (indexfp[count] -
param.fingerprints_range[
symbol][count][0]) / \
(param.fingerprints_range[symbol][count][1] -
param.fingerprints_range[symbol][count][0])
else:
scaled_value = indexfp[count]
scaled_indexfp[count] = scaled_value
count += 1
atomic_amp_energy = self.reg.get_energy(scaled_indexfp,
index, symbol,)
self.energy += atomic_amp_energy
index += 1
self.results['energy'] = float(self.energy)
##################################################################
if properties == ['forces']:
self.reg.reset_energy()
outputs = {}
self.forces[:] = 0.0
if param.descriptor is None: # pure atomic-coordinates scheme
input = (atoms.positions).ravel()
_ = self.reg.get_energy(input,)
del _
self_index = 0
while self_index < no_of_atoms:
self.reg.reset_forces()
i = 0
while i < 3:
_input = [0.] * (3 * no_of_atoms)
_input[3 * self_index + i] = 1.
force = self.reg.get_force(i, _input,)
self.forces[self_index][i] = force
i += 1
self_index += 1
else: # fingerprinting scheme
# Neighborlists for all atoms are calculated.
dict_nl = {}
n_self_offsets = {}
self_index = 0
while self_index < no_of_atoms:
neighbor_indices, neighbor_offsets = \
_nl.get_neighbors(self_index)
n_self_indices = np.append(self_index, neighbor_indices)
if len(neighbor_offsets) == 0:
_n_self_offsets = [[0, 0, 0]]
else:
_n_self_offsets = np.vstack(([[0, 0, 0]],
neighbor_offsets))
dict_nl[self_index] = n_self_indices
n_self_offsets[self_index] = _n_self_offsets
self_index += 1
index = 0
while index < no_of_atoms:
symbol = atoms[index].symbol
n_indices, n_offsets = _nl.get_neighbors(index)
# for calculating fingerprints, summation runs over
# neighboring atoms of type I (either inside or outside
# the main cell)
n_symbols = [atoms[n_index].symbol
for n_index in n_indices]
Rs = [atoms.positions[n_index] +
np.dot(n_offset, atoms.get_cell())
for n_index, n_offset in zip(n_indices, n_offsets)]
indexfp = self.fp.get_fingerprint(index, symbol,
n_symbols, Rs)
len_of_indexfp = len(indexfp)
# fingerprints are scaled to [-1, 1] range
scaled_indexfp = [None] * len_of_indexfp
count = 0
while count < len_of_indexfp:
if (param.fingerprints_range[symbol][count][1] -
param.fingerprints_range[symbol][count][0]) \
> (10.**(-8.)):
scaled_value = -1. + \
2. * (indexfp[count] -
param.fingerprints_range[
symbol][count][0]) / \
(param.fingerprints_range[symbol][count][1] -
param.fingerprints_range[symbol][count][0])
else:
scaled_value = indexfp[count]
scaled_indexfp[count] = scaled_value
count += 1
__ = self.reg.get_energy(scaled_indexfp, index, symbol)
del __
index += 1
self_index = 0
while self_index < no_of_atoms:
n_self_indices = dict_nl[self_index]
_n_self_offsets = n_self_offsets[self_index]
n_self_symbols = [atoms[n_index].symbol
for n_index in n_self_indices]
self.reg.reset_forces()
len_of_n_self_indices = len(n_self_indices)
i = 0
while i < 3:
force = 0.
n_count = 0
while n_count < len_of_n_self_indices:
n_symbol = n_self_symbols[n_count]
n_index = n_self_indices[n_count]
n_offset = _n_self_offsets[n_count]
# for calculating forces, summation runs over
# neighbor atoms of type II (within the main cell
# only)
if n_offset[0] == 0 and n_offset[1] == 0 and \
n_offset[2] == 0:
neighbor_indices, neighbor_offsets = \
_nl.get_neighbors(n_index)
neighbor_symbols = \
[atoms[_index].symbol
for _index in neighbor_indices]
Rs = [atoms.positions[_index] +
np.dot(_offset, atoms.get_cell())
for _index, _offset
in zip(neighbor_indices,
neighbor_offsets)]
# for calculating derivatives of fingerprints,
# summation runs over neighboring atoms of type
# I (either inside or outside the main cell)
indexfp_prime = self.fp.get_der_fingerprint(
n_index, n_symbol,
neighbor_indices,
neighbor_symbols,
Rs, self_index, i)
len_of_indexfp_prime = len(indexfp_prime)
# fingerprint derivatives are scaled
scaled_indexfp_prime = \
[None] * len_of_indexfp_prime
count = 0
while count < len_of_indexfp_prime:
if (param.fingerprints_range[
n_symbol][count][1] -
param.fingerprints_range[
n_symbol][count][0]) \
> (10.**(-8.)):
scaled_value = 2. * \
indexfp_prime[count] / \
(param.fingerprints_range[
n_symbol][count][1] -
param.fingerprints_range[
n_symbol][count][0])
else:
scaled_value = indexfp_prime[count]
scaled_indexfp_prime[count] = scaled_value
count += 1
force += self.reg.get_force(i,
scaled_indexfp_prime,
n_index, n_symbol,)
n_count += 1
self.forces[self_index][i] = force
i += 1
self_index += 1
del dict_nl, outputs, n_self_offsets, n_self_indices,
n_self_symbols, _n_self_offsets, scaled_indexfp, indexfp
self.results['forces'] = self.forces
###########################################################################
def train(
self,
images,
energy_goal=0.001,
force_goal=0.005,
overfitting_constraint=0.,
force_coefficient=None,
cores=None,
optimizer=optimizer,
overwrite=False,
data_format='json',
global_search=SimulatedAnnealing(temperature=70,
steps=2000),
perturb_variables=None,
extend_variables=True,
save_memory=False,):
"""
Fits a variable set to the data, by default using the "fmin_bfgs"
optimizer. The optimizer takes as input a cost function to reduce and
an initial guess of variables and returns an optimized variable set.
:param images: List of ASE atoms objects with positions, symbols,
energies, and forces in ASE format. This is the training
set of data. This can also be the path to an ASE
trajectory (.traj) or database (.db) file. Energies can
be obtained from any reference, e.g. DFT calculations.
:type images: list or str
:param energy_goal: Threshold energy per atom rmse at which simulation
is converged.
:type energy_goal: float
:param force_goal: Threshold force rmse at which simulation is
converged. The default value is in unit of eV/Ang.
If 'force_goal = None', forces will not be trained.
:type force_goal: float
:param overfitting_constraint: Multiplier of the weights norm penalty
term.
:type overfitting_constraint: float
:param force_coefficient: Coefficient of the force contribution in the
cost function.
:type force_coefficient: float
:param cores: Number of cores to parallelize over. If not specified,
attempts to determine from environment.
:type cores: int
:param optimizer: The optimization object. The default is to use
scipy's fmin_bfgs, but any optimizer that behaves in
the same way will do.
:type optimizer: object
:param overwrite: If a trained output file with the same name exists,
overwrite it.
:type overwrite: bool
:param data_format: Format of saved data. Can be either "json" or "db".
:type data_format: str
:param global_search: Method for global search of initial variables.
Will ignore, if initial variables are already
given. For now, it can be either None, or
SimulatedAnnealing(temperature, steps).
:type global_search: object
:param perturb_variables: If not None, after training, variables
will be perturbed by the amount specified,
and plotted as pdf book. A typical value is
0.01.
:type perturb_variables: float
:param extend_variables: Determines whether or not the code should
extend the number of variables if convergence
does not happen.
:type extend_variables: bool
:param save_memory: If True, memory efficient mode will be used.
:type save_memory: bool
"""
if save_memory:
data_format = 'db'
param = self.parameters
filename = os.path.join(self.label, 'trained-parameters.json')
if (not overwrite) and os.path.exists(filename):
raise IOError('File exists: %s.\nIf you want to overwrite,'
' set overwrite=True or manually delete.'
% filename)
self.overfitting_constraint = overfitting_constraint
if force_goal is None:
train_forces = False
if not force_coefficient:
force_coefficient = 0.
else:
train_forces = True
if not force_coefficient:
force_coefficient = (energy_goal / force_goal)**2.
energy_coefficient = 1.
log = self.log
log('Amp training started. ' + now() + '\n')
if param.descriptor is None: # pure atomic-coordinates scheme
log('Local environment descriptor: None')
else: # fingerprinting scheme
log('Local environment descriptor: ' +
param.descriptor.__class__.__name__)
log('Regression: ' + param.regression.__class__.__name__ + '\n')
if not cores:
from utilities import count_allocated_cpus
cores = count_allocated_cpus()
log('Parallel processing over %i cores.\n' % cores)
if isinstance(images, str):
extension = os.path.splitext(images)[1]
if extension == '.traj':
images = aseio.Trajectory(images, 'r')
elif extension == '.db':
images = aseio.read(images, ':')
no_of_images = len(images)
if param.descriptor is None: # pure atomic-coordinates scheme
param.no_of_atoms = len(images[0])
count = 0
while count < no_of_images:
image = images[count]
if len(image) != param.no_of_atoms:
raise RuntimeError('Number of atoms in different images '
'is not the same. Try '
'descriptor=Gaussian.')
count += 1
log('Training on %i images.' % no_of_images)
# Images is converted to dictionary form; key is hash of image.
log.tic()
log('Hashing images...')
dict_images = {}
count = 0
while count < no_of_images:
image = images[count]
hash = hash_image(image)
if hash in dict_images.keys():
log('Warning: Duplicate image (based on identical hash).'
' Was this expected? Hash: %s' % hash)
dict_images[hash] = image
count += 1
del hash
images = dict_images.copy()
del dict_images
hashs = sorted(images.keys())
no_of_images = len(hashs)
log(' %i unique images after hashing.' % no_of_images)
log(' ...hashing completed.', toc=True)
self.elements = set([atom.symbol for hash in hashs
for atom in images[hash]])
self.elements = sorted(self.elements)
msg = '%i unique elements included: ' % len(self.elements)
msg += ', '.join(self.elements)
log(msg)
# Default fingerprint parameters generated here.
if param.descriptor is not None: # fingerprinting scheme
param = self.fp.log(log, param, self.elements)
if not (param.regression._weights or param.regression._variables):
variables_exist = False
else:
variables_exist = True
# Default regression parameters generated here.
param = self.reg.log(log, param, self.elements, images)
# "MultiProcess" object is initialized
_mp = MultiProcess(self.fortran, no_procs=cores)
# all images are shared between cores for feed-forward and
# back-propagation calculations
_mp.make_list_of_sub_images(no_of_images, hashs, images)
io = IO(images,) # utilities.IO object initialized.
if param.descriptor is None: # pure atomic-coordinates scheme
self.sfp = None
snl = None
else: # fingerprinting scheme
# Neighborlist for all images are calculated and saved
log.tic()
snl = SaveNeighborLists(param.descriptor.cutoff, no_of_images,
hashs, images, self.dblabel, log,
train_forces, io, data_format, save_memory)
gc.collect()
# Fingerprints are calculated and saved
self.sfp = SaveFingerprints(self.fp, self.elements, no_of_images,
hashs, images, self.dblabel,
train_forces, snl, log, _mp, io,
data_format, save_memory, self.fortran)
gc.collect()
# If fingerprints_range has not been loaded, it will take value
# from the json file.
if param.fingerprints_range is None:
param.fingerprints_range = self.sfp.fingerprints_range
else:
log('Updated fingerprints range from saved version; this is'
' a temporary bug fix. With this the first iteration of'
' the training neural network will *not* give identical'
' results to the saved version if the '
'fingerprints_range has changed.')
param.fingerprints_range = self.sfp.fingerprints_range
del hashs, images
if self.fortran:
# data common between processes is sent to fortran modules
send_data_to_fortran(self.sfp,
self.reg.elements,
train_forces,
energy_coefficient,
force_coefficient,
param,)
_mp.ravel_images_data(param,
self.sfp,
snl,
self.reg.elements,
train_forces,
log,
save_memory,)
# del _mp.list_sub_images, _mp.list_sub_hashs
costfxn = CostFxnandDer(
self.reg,
param,
no_of_images,
self.label,
log,
energy_goal,
force_goal,
train_forces,
_mp,
self.overfitting_constraint,
force_coefficient,
self.fortran,
save_memory,
self.sfp,
snl,)
gc.collect()
if (variables_exist is False) and (global_search is not None):
log('\n' + 'Starting global search...')
gs = global_search
gs.initialize(param.regression._variables, log, costfxn)
param.regression._variables = gs.get_variables()
# saving initial parameters
filename = os.path.join(self.label, 'initial-parameters.json')
save_parameters(filename, param)
log('Initial parameters saved in file %s.' % filename)
log.tic('optimize')
log('\n' + 'Starting optimization of cost function...')
log(' Energy goal: %.3e' % energy_goal)
if train_forces:
log(' Force goal: %.3e' % force_goal)
log(' Cost function force coefficient: %f' % force_coefficient)
else:
log(' No force training.')
log.tic()
converged = False
step = 0
while not converged:
if step > 0:
param = self.reg.introduce_variables(log, param)
costfxn = CostFxnandDer(
self.reg,
param,
no_of_images,
self.label,
log,
energy_goal,
force_goal,
train_forces,
_mp,
self.overfitting_constraint,
force_coefficient,
self.fortran,
save_memory,
self.sfp,
snl,)
costfxn.nnsizestep = step
variables = param.regression._variables
try: