-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathEnsemble.py
More file actions
4320 lines (3289 loc) · 165 KB
/
Ensemble.py
File metadata and controls
4320 lines (3289 loc) · 165 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
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, os
import warnings
import numpy as np
import time
#from scipy.special import tanh, sinh, cosh
"""
This is part of the program python-sscha
Copyright (C) 2018 Lorenzo Monacelli
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import cellconstructor as CC
import cellconstructor.Structure
import cellconstructor.Phonons
import cellconstructor.Methods
import cellconstructor.Manipulate
import cellconstructor.Settings
import sscha.Parallel as Parallel
from sscha.Parallel import pprint as print
from sscha.Tools import NumpyEncoder
import json
import difflib
import SCHAModules
#import sscha_HP_odd
_SSCHA_ODD_ = False
#try:
# import sscha_HP_odd
# _SSCHA_ODD_ = True
#except:
# _SSCHA_ODD_ = False
# Try to load the parallel library if any
try:
from mpi4py import MPI
__MPI__ = True
except:
__MPI__ = False
# Check if you can load spglib
try:
import spglib
__SPGLIB__ = True
except:
__SPGLIB__ = False
__ASE__ = True
try:
import ase, ase.io
import ase.calculators.singlepoint
except:
__ASE__ = False
# The small value considered zero
__EPSILON__ = 1e-6
__A_TO_BOHR__ = 1.889725989
__JULIA_EXT__ = False
__JULIA_ERROR__ = ""
try:
import julia, julia.Main
julia.Main.include(os.path.join(os.path.dirname(__file__),
"fourier_gradient.jl"))
__JULIA_EXT__ = True
except:
try:
import julia
try:
from julia.api import Julia
jl = Julia(compiled_modules=False)
import julia.Main
julia.Main.include(os.path.join(os.path.dirname(__file__),
"fourier_gradient.jl"))
__JULIA_EXT__ = True
except:
# Install the required modules
julia.install()
try:
julia.Main.include(os.path.join(os.path.dirname(__file__),
"fourier_gradient.jl"))
__JULIA_EXT__ = True
except Exception as e:
warnings.warn("Julia extension not available.\nError: {}".format(e))
except Exception as e:
warnings.warn("Julia extension not available.\nError: {}".format(e))
try:
from ase.units import create_units
units = create_units("2006")#Rydberg, Bohr
Rydberg = units["Ry"]
Bohr = units["Bohr"]
__RyToK__ = Rydberg / units["kB"]
except:
Rydberg = 13.605698066
Bohr = 1/__A_TO_BOHR__
__RyToK__ = 157887.32400374097
__GPa__ = 14710.50763554043
__DEBUG_RHO__ = False
"""
This source contains the Ensemble class
It is used to Load and Save info about the ensemble.
"""
UNITS_DEFAULT = "default"
UNITS_HARTREE = "hartree"
SUPPORTED_UNITS = [UNITS_DEFAULT, UNITS_HARTREE]
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
class Ensemble:
__debug_index__ = 0
def __init__(self, dyn0, T0, supercell = None, **kwargs):
"""
PREPARE THE ENSEMBLE
====================
This method initializes and prepares the ensemble.
NOTE: To now this works only in the gamma point (dyn0 must be a 1x1x1 supercell)
Parameters
----------
dyn0 : cellconstructor.Phonons.Phonons()
This is the dynamical matrix used to generate the ensemble.
T0 : float
The temperature used to generate the ensemble.
supercell: optional, list of int
The supercell dimension. If not provided, it will be determined by dyn0
**kwargs : any other attribute of the ensemble
"""
# N is the number of element in the ensemble
self.N = 0
self.structures = []
self.energies = []
self.forces = []
self.stresses = []
self.xats = []
self.units = UNITS_DEFAULT
self.w_0 = None
self.pols_0 = None
self.current_w = None
self.current_pols = None
# The frequencies and polarizations of the ensemble
# In q space
self.w_q_0 = None
self.pols_q_0 = None
self.w_q_current = None
self.pols_q_current = None
self.sscha_energies = []
self.sscha_forces = []
# If True the frequency smaller than CC.Phonons.__EPSILON_W__ are ignored
self.ignore_small_w = False
# The original dynamical matrix used to generate the ensemble
self.dyn_0 = dyn0.Copy()
self.T0 = T0
# This is the weight of each configuration in the sampling.
# It is updated with the update_weigths function
self.rho = []
self.current_dyn = dyn0.Copy()
self.current_T = T0
# Supercell size
self.supercell = np.ones(3, dtype = np.intc)
if supercell is not None:
self.supercell[:] = supercell
# Check if there are inconsistencies
for i in range(3):
if self.supercell[i] != dyn0.GetSupercell()[i]:
raise ValueError("""Error, you specified a supercell of {},
while from the dynamical matrix provided I expect a supercell of {}
""".format(self.supercell, dyn0.GetSupercell()))
else:
self.supercell[:] = dyn0.GetSupercell()
# How many atoms in the supercell
Nsc = np.prod(self.supercell) * self.dyn_0.structure.N_atoms
nat = self.dyn_0.structure.N_atoms
nq = len(self.dyn_0.q_tot)
nat_sc = nat*nq
assert nq == np.prod(self.supercell), """
Error, the supercell does not match with the q grid of the dynamical matrix.
Expected supercell size = {}
Given supercell size = {}
You can omit the supercell keyword when initializing the ensemble
if you are not sure on the value.
""".format(nq, supercell)
# Flag to use the fourier gradient
# If true, avoid to compute the forces in real space at all.
self.fourier_gradient = __JULIA_EXT__
# Prepare the atoms in the supercell structure
super_struct, itau = dyn0.structure.generate_supercell(self.supercell, get_itau=True)
self.supercell_structure_original = super_struct.copy()
self.supercell_structure = super_struct
self.itau = itau + 1
# To avoid to recompute each time the same variables store something usefull here
self.q_start = np.zeros( (self.N, Nsc * 3))
self.current_q = np.zeros( (self.N, Nsc * 3))
self.q_opposite_index = None
# Store also the displacements
self.u_disps = np.zeros( (self.N, Nsc * 3))
self.u_disps_qspace = np.zeros( (self.N, 3*nat, nq))
self.forces_qspace = np.zeros_like(self.u_disps_qspace)
self.sscha_forces_qspace = np.zeros_like(self.u_disps_qspace)
# A flag that memorize if the ensemble has also the stresses
self.has_stress = True
# A flag for each configuration that check if it possess a force and a stress
self.force_computed = None
self.stress_computed = None
# Get the extra quantities
self.all_properties = []
# Initialize the q grid and lattice
# For the fourier transform
self.q_grid = np.array(self.dyn_0.q_tot) / CC.Units.A_TO_BOHR
self.r_lat = np.zeros((nat_sc, 3), dtype = np.float64)
for i in range(nat_sc):
self.r_lat[i,:] = self.supercell_structure.coords[i, :] - \
self.dyn_0.structure.coords[self.itau[i] - 1, :]
self.r_lat *= CC.Units.A_TO_BOHR
if __JULIA_EXT__:
self.init_q_opposite()
self.u_disps_original = np.zeros_like(self.u_disps)
self.u_disps_original_qspace = np.zeros_like(self.u_disps_qspace)
# Setup the attribute control
self.__total_attributes__ = [item for item in self.__dict__.keys()]
self.fixed_attributes = True # This must be the last attribute to be setted
# Setup any other keyword given in input (raising the error if not already defined)
for key in kwargs:
self.__setattr__(key, kwargs[key])
def __setattr__(self, name, value):
"""
This method is used to set an attribute.
It will raise an exception if the attribute does not exists (with a suggestion of similar entries)
"""
if "fixed_attributes" in self.__dict__:
if name in self.__total_attributes__:
super(Ensemble, self).__setattr__(name, value)
elif self.fixed_attributes:
similar_objects = str( difflib.get_close_matches(name, self.__total_attributes__))
ERROR_MSG = """
Error, the attribute '{}' is not a member of '{}'.
Suggested similar attributes: {} ?
""".format(name, type(self).__name__, similar_objects)
raise AttributeError(ERROR_MSG)
else:
super(Ensemble, self).__setattr__(name, value)
if name == "dyn_0":
self.w_0, self.pols_0, self.w_q_0, self.pols_q_0 = value.DiagonalizeSupercell(return_qmodes=True)
self.current_dyn = value.Copy()
self.current_w = self.w_0.copy()
self.current_pols = self.pols_0.copy()
self.w_q_current = self.w_q_0.copy()
self.pols_q_current = self.pols_q_0.copy()
def convert_units(self, new_units):
"""
CONVERT ALL THE VARIABLE IN A COHERENT UNIT OF MEASUREMENTS
===========================================================
This function is used to jump between several unit of measurement.
You should always call this function before processing data assuming
a particular kind of units.
Supported units are:
- "default" :
This is the default units. Here the forces are Ry/A displacements and structure are in A
Dynamical matrix is in Ry/bohr^2. Mass is in Ry units
- "hartree" :
Here, everything is stored in Ha units.
Parameters
----------
- new_units : string
The target units
"""
# Check if the input is ok
assert new_units in SUPPORTED_UNITS, "Error, {} unit is unknown. Try one of {}".format(new_units, SUPPORTED_UNITS)
# If we already are in the correct units, ignore it
if new_units == self.units:
return
if new_units == UNITS_HARTREE:
if self.units == UNITS_DEFAULT:
# Convert the dynamical matrix
for iq, q in enumerate(self.dyn_0.q_tot):
self.dyn_0.dynmats[iq] /= 2
self.current_dyn.dynmats[iq] /= 2
self.dyn_0.q_tot[iq] /= __A_TO_BOHR__
self.current_dyn.q_tot[iq] /= __A_TO_BOHR__
for k in self.dyn_0.structure.masses.keys():
self.dyn_0.structure.masses[k] *= 2
self.current_dyn.structure.masses[k] *= 2
# Convert the cell shape and the coordinates
self.dyn_0.structure.coords *= __A_TO_BOHR__
self.dyn_0.structure.unit_cell *= __A_TO_BOHR__
self.current_dyn.structure.coords *= __A_TO_BOHR__
self.current_dyn.structure.unit_cell *= __A_TO_BOHR__
self.forces /= 2 * __A_TO_BOHR__ #Ry/A -> Ha/bohr
self.sscha_forces /= 2 * __A_TO_BOHR__
self.xats *= __A_TO_BOHR__
self.sscha_energies /= 2 # Ry -> Ha
self.energies /= 2
self.u_disps *= __A_TO_BOHR__
if self.has_stress:
self.stresses /= 2
else:
raise NotImplementedError("Error, I do not know how to convert between {} and {}.".format(self.units, new_units))
elif new_units == UNITS_DEFAULT:
if self.units == UNITS_HARTREE:
# Convert the dynamical matrix
for iq, q in enumerate(self.dyn_0.q_tot):
self.dyn_0.dynmats[iq] *= 2
self.current_dyn.dynmats[iq] *= 2
self.dyn_0.q_tot[iq] *= __A_TO_BOHR__
self.current_dyn.q_tot[iq] *= __A_TO_BOHR__
for k in self.dyn_0.structure.masses.keys():
self.dyn_0.structure.masses[k] /= 2
self.current_dyn.structure.masses[k] /= 2
# Convert the cell shape and the coordinates
self.dyn_0.structure.coords /= __A_TO_BOHR__
self.dyn_0.structure.unit_cell /= __A_TO_BOHR__
self.current_dyn.structure.coords /= __A_TO_BOHR__
self.current_dyn.structure.unit_cell /= __A_TO_BOHR__
self.forces *= 2 * __A_TO_BOHR__ # Ha/bohr -> Ry/A
self.sscha_forces *= 2 * __A_TO_BOHR__
self.xats /= __A_TO_BOHR__
self.sscha_energies *= 2 # Ha -> Ry
self.energies *= 2
self.u_disps /= __A_TO_BOHR__
if self.has_stress:
self.stresses *= 2
else:
raise NotImplementedError("Error, I do not know how to convert between {} and {}.".format(self.units, new_units))
else:
raise NotImplementedError("Error, I do not know anything about this conversion")
# Update the units flag
self.units = new_units
def init(self):
"""
Call this function after the ensemble is computed.
It performs the fourier transform of the forces and displacements.
It also computed the displacements and all other important quantities that
needs to be iterated to actually run a sscha minimization
And initializes the parameters to perform the fourier transform
faster at each minimization steps
"""
if self.N != len(self.structures):
self.N = self.structures
# Check if th all_properties is initialized
if len(self.all_properties) == 0:
self.all_properties = [None] * self.N
# Initialize the supercell
super_struct, itau = self.dyn_0.structure.generate_supercell(self.supercell, get_itau=True)
self.supercell_structure = super_struct
self.itau = itau + 1
nat = self.dyn_0.structure.N_atoms
nq = self.q_grid.shape[0]
nat_sc = nat*nq
dynq = np.zeros((3*nat, 3*nat, nq), dtype = np.complex128, order = "F")
for i in range(nq):
dynq[:, :, i] = self.current_dyn.dynmats[i]
# Get the original u_disps
self.u_disps_original = np.reshape(
self.xats - np.tile(self.supercell_structure.coords, (self.N, 1,1)),
(self.N, 3 * nat_sc),
order = "C"
)
self.u_disps = self.u_disps_original.copy()
if self.fourier_gradient:
self.u_disps_qspace = julia.Main.vector_r2q(
self.u_disps,
self.q_grid,
self.itau,
self.r_lat,
)
self.u_disps_original_qspace = self.u_disps_qspace.copy()
self.forces_qspace = julia.Main.vector_r2q(
self.forces.reshape((self.N, 3*nat_sc)),
self.q_grid,
self.itau,
self.r_lat
)
# These should be in Ry/A to be consistent with the units
self.sscha_forces_qspace = -julia.Main.multiply_matrix_vector_fourier(
dynq,
self.u_disps_qspace * CC.Units.A_TO_BOHR,
) * CC.Units.A_TO_BOHR
self.sscha_energies[:] = -julia.Main.multiply_vector_vector_fourier(
self.forces_qspace / CC.Units.A_TO_BOHR,
self.u_disps_qspace * CC.Units.A_TO_BOHR
) * 0.5 # The conversion is useless, keep it for clarity
self.sscha_forces = julia.Main.vector_q2r(
self.sscha_forces_qspace,
self.q_grid,
self.itau,
self.r_lat
).reshape((self.N, nat_sc, 3))
else:
self.sscha_energies[:], self.sscha_forces[:,:,:] = self.dyn_0.get_energy_forces(None, displacement = self.u_disps)
self.forces_qspace = None
self.u_disps_qspace = None
self.q_grid = np.array(self.dyn_0.q_tot) / CC.Units.A_TO_BOHR
nat_sc = self.supercell_structure.N_atoms
self.r_lat = np.zeros((nat_sc, 3), dtype = np.float64)
for i in range(nat_sc):
self.r_lat[i,:] = self.supercell_structure.coords[i, :] - \
self.dyn_0.structure.coords[self.itau[i] - 1, :]
self.r_lat *= CC.Units.A_TO_BOHR
if self.fourier_gradient:
self.init_q_opposite()
def load(self, data_dir, population, N, verbose = False, load_displacements = True, raise_error_on_not_found = False, load_noncomputed_ensemble = False, skip_extra_rows = False,
timer=None):
"""
LOAD THE ENSEMBLE
=================
This function load the ensemble from a standard calculation.
The files need to be organized as follows
data_dir / scf_populationX_Y.dat
data_dir / energies_supercell_populationX.dat
data_dir / forces_populationX_Y.dat
data_dir / pressures_populationX_Y.dat
data_dir / u_populationX_Y.dat
X = population
Y = the configuration id (starting from 1 to N included, fortran convention)
The files scf_population_X_Y.dat must contain the scf file of the structure.
It should be in alat units, matching the same alat defined in the starting
dynamical matrix.
The energies_supercell.dat file must contain the total energy in Ry for
each configuration.
The forces_populationX_Y contains the
Parameters
----------
data_dir : str
The path to the directory containing the ensemble. If you used
the fortran sscha.x code it should match the data_dir option of the
input file.
population : int
The info to distinguish between several ensembles generated in the
same data_dir. This also should match the correspective property
of the fortran sscha.x input file.
N : int
The dimension of the ensemble. This should match the n_random
variable from the fortran sscha.x input file.
verbose : bool, optional
If true (default false) prints the real timing of the different part
during the loading.
load_displacement: bool
If true the structures are loaded from the u_populationX_Y.dat files,
otherwise they are loaded from the scf_populationX_Y.dat files.
raise_error_on_not_found : bool
If true, raises an error if one force file is missing
load_noncomputed_ensemble: bool
If True, it allows for loading an ensemble where some of the configurations forces and stresses are missing.
Note that it must be compleated before running a SCHA minimization
skip_extra_rows : bool
If True, only loads the first Nat_sc rows of the forces.
Useful if the parsing script reads more than the necessary rows from the calculation output.
"""
A_TO_BOHR = 1.889725989
# Check if the given data_dir is a real directory
if not os.path.isdir(data_dir):
raise IOError("Error, the given data_dir '%s' is not a valid directory." % data_dir)
# Remove the tailoring slash if any
if data_dir[-1] == "/":
data_dir = data_dir[:-1]
# Load the structures
self.N = N
Nat_sc = np.prod(self.supercell) * self.dyn_0.structure.N_atoms
self.forces = np.zeros( (self.N, Nat_sc, 3), order = "F", dtype = np.float64)
self.xats = np.zeros( (self.N, Nat_sc, 3), order = "C", dtype = np.float64)
self.stresses = np.zeros( (self.N, 3,3), order = "F", dtype = np.float64)
self.sscha_energies = np.zeros(self.N, dtype = np.float64)
self.energies = np.zeros(self.N, dtype = np.float64)
self.sscha_forces = np.zeros( (self.N, Nat_sc, 3), order = "F", dtype = np.float64)
self.u_disps = np.zeros( (self.N, Nat_sc * 3), order = "F", dtype = np.float64)
# Initialize the computation of energy and forces
self.force_computed = np.zeros( self.N, dtype = bool)
self.stress_computed = np.zeros(self.N, dtype = bool)
self.all_properties = [None] * self.N
# Add a counter to check if all the stress tensors are present
count_stress = 0
# Superstructure
#dyn_supercell = self.dyn_0.GenerateSupercellDyn(self.supercell)
super_structure = self.dyn_0.structure.generate_supercell(self.supercell)
#super_fc = np.real(dyn_supercell.dynmats[0])
self.structures = []
total_t_for_loading = 0
total_t_for_sscha_ef = 0
t_before_for = time.time()
# Avoid reading extra rows on the forces
maxrowforces = None
if skip_extra_rows:
maxrowforces = Nat_sc
for i in range(self.N):
# Load the structure
structure = CC.Structure.Structure()
if os.path.exists(os.path.join(data_dir, "scf_population%d_%d.dat" % (population, i+1))) and not load_displacements:
if timer:
timer.execute_timed_function(structure.read_scf, os.path.join(data_dir, "scf_population%d_%d.dat" % (population, i+1)), alat = self.dyn_0.alat)
else:
structure.read_scf(os.path.join(data_dir, "scf_population%d_%d.dat" % (population, i+1)), alat = self.dyn_0.alat)
structure.has_unit_cell = True
structure.unit_cell = super_structure.unit_cell
# Get the displacement [ANGSTROM]
if timer:
self.u_disps[i,:] = timer.execute_timed_function(structure.get_displacement, super_structure).ravel()
else:
self.u_disps[i,:] = structure.get_displacement(super_structure).ravel()
else:
structure = super_structure.copy()
if timer:
disp = timer.execute_timed_function(np.loadtxt, os.path.join(data_dir, "u_population%d_%d.dat" % (population, i+1))) / A_TO_BOHR
else:
disp =np.loadtxt(os.path.join(data_dir, "u_population%d_%d.dat" % (population, i+1))) /__A_TO_BOHR__
structure.coords += disp
self.u_disps[i, :] = disp.ravel()
self.xats[i, :, :] = structure.coords
self.structures.append(structure)
# Load forces (Forces are in Ry/bohr, convert them in Ry /A)
t1 = time.time()
force_path = os.path.join(data_dir, "forces_population%d_%d.dat" % (population, i+1))
if os.path.exists(force_path):
if timer:
self.forces[i,:,:] = timer.execute_timed_function(np.loadtxt, force_path, max_rows=maxrowforces) * A_TO_BOHR
else:
self.forces[i,:,:] = np.loadtxt(force_path, max_rows=maxrowforces) * A_TO_BOHR
self.force_computed[i] = True
else:
if raise_error_on_not_found:
ERROR_MSG = """
Error, the file '{}' is missing from the ensemble
data_dir = '{}'
please, check better your data.
""".format(force_path, data_dir)
print(ERROR_MSG)
raise IOError(ERROR_MSG)
else:
self.force_computed[i] = False
# Load stress
if os.path.exists(os.path.join(data_dir, "pressures_population%d_%d.dat" % (population, i+1))):
if timer:
self.stresses[i,:,:] = timer.execute_timed_function(np.loadtxt, os.path.join(data_dir, "pressures_population%d_%d.dat" % (population, i+1)))
else:
self.stresses[i,:,:] = np.loadtxt(os.path.join(data_dir, "pressures_population%d_%d.dat" % (population, i+1)))
self.stress_computed[i] = True
else:
self.stress_computed[i] = False
t2 = time.time()
# print "Loading: config %d:" % i
# for j in range(structure.N_atoms):
# print "Atom %d" % j
# print "u_disp = ", structure.get_displacement(self.dyn_0.structure)[j,:] *A_TO_BOHR
# print "force = ", self.forces[i, j, :] / A_TO_BOHR
# print "SCHA force = ", force[j, :] / A_TO_BOHR
#
# # Debugging stuff
# u_disp = structure.get_displacement(self.dyn_0.structure).reshape(3 * structure.N_atoms) * A_TO_BOHR
# print "TEST DOBULE:"
# print "NORMAL = ", self.dyn_0.dynmats[0].dot(u_disp)
# print "INVERSE = ", self.dyn_0.dynmats[0].dot(-u_disp)
if timer:
timer.add_timer("Load_all_configurations", time.time() - t_before_for)
if verbose:
print( "[LOAD ENSEMBLE]: time elapsed for the cycle over the configurations:", time.time() - t_before_for)
t1 = time.time()
# Load the energy
if timer:
total_energies = timer.execute_timed_function(np.loadtxt, os.path.join(data_dir, "energies_supercell_population%d.dat" % (population)))
else:
total_energies = np.loadtxt(os.path.join(data_dir, "energies_supercell_population%d.dat" % (population)))
self.energies = total_energies[:N]
# Setup the initial weight
self.rho = np.ones(self.N, dtype = np.float64)
t1 = time.time()
#self.q_start = CC.Manipulate.GetQ_vectors(self.structures, dyn_supercell, self.u_disps)
t2 = time.time()
#self.current_q = self.q_start.copy()
p_count = np.sum(self.stress_computed.astype(int))
if p_count > 0:
self.has_stress = True
else:
self.has_stress = False
if timer:
timer.execute_timed_function(self.init)
else:
self.init()
# Check if the forces and stresses are present
if not load_noncomputed_ensemble:
if np.sum(self.force_computed.astype(int)) != self.N:
ERROR_MSG = """
Error, the following force files are missing from the ensemble:
{}""".format(np.arange(self.N)[~self.force_computed])
print(ERROR_MSG)
raise IOError(ERROR_MSG)
if p_count > 0 and p_count != self.N:
ERROR_MSG = """
Error, the following stress files are missing from the ensemble:
{}""".format(np.arange(self.N)[~self.stress_computed])
print(ERROR_MSG)
raise IOError(ERROR_MSG)
def load_from_calculator_output(self, directory, out_ext = ".pwo", timer=None):
"""
LOAD THE ENSEMBLE FROM A CALCULATION
====================================
This subroutine allows to directly load the ensemble from the output files
of a calculation. This works and has been tested for quantum espresso,
however in principle any output file from an ase supported format
should be readed.
NOTE: This subroutine requires ASE to be correctly installed.
Parameters
----------
directory : string
Path to the directory that contains the output of the calculations
out_ext : string
The extension of the files that will be readed.
"""
assert __ASE__, "ASE library required to load from the calculator output file."
# Get all the output file
output_files = ["{}/{}".format(directory, x) for x in os.listdir(directory) if x.endswith(out_ext)]
self.N = len(output_files)
nat_sc = np.prod(self.supercell) * self.dyn_0.structure.N_atoms
self.forces = np.zeros( (self.N, nat_sc, 3), order = "F", dtype = np.float64)
self.xats = np.zeros( (self.N, nat_sc, 3), order = "C", dtype = np.float64)
self.stresses = np.zeros( (self.N, 3,3), order = "F", dtype = np.float64)
self.sscha_energies = np.zeros(self.N, dtype = np.float64)
self.energies = np.zeros(self.N, dtype = np.float64)
self.sscha_forces = np.zeros( (self.N, nat_sc, 3), order = "F", dtype = np.float64)
self.u_disps = np.zeros( (self.N, nat_sc * 3), order = "F", dtype = np.float64)
# Initialize the computation of energy and forces
self.force_computed = np.ones(self.N, dtype = bool)
self.stress_computed = np.ones(self.N, dtype = bool)
self.all_properties = [None] * self.N
# Add a counter to check if all the stress tensors are present
count_stress = 0
# Superstructure
dyn_supercell = self.dyn_0.GenerateSupercellDyn(self.supercell)
super_structure = dyn_supercell.structure
super_fc = dyn_supercell.dynmats[0]
self.structures = []
for i, outf in enumerate(output_files):
ase_struct = ase.io.read(outf)
# Get the structure
structure = CC.Structure.Structure()
structure.generate_from_ase_atoms(ase_struct)
self.xats[i, :, :] = structure.coords
self.structures.append(structure)
# Get the displacement [ANGSTROM]
self.u_disps[i,:] = structure.get_displacement(super_structure).reshape( 3 * nat_sc)
# Get the energy
energy = ase_struct.get_potential_energy()
energy /= Rydberg
self.energies[i] = energy
# Get the forces [eV/A -> Ry/A]
forces = ase_struct.get_forces() / Rydberg
self.forces[i, :, :] = forces
# Get the stress if any
try:
stress = - ase_struct.get_stress(voigt=False)
# eV/A^3 -> Ry/bohr^3
stress /= Rydberg / Bohr**3
count_stress += 1
self.stresses[i, :, :] = stress
except:
pass
self.rho = np.ones(self.N, dtype = np.float64)
t1 = time.time()
# self.q_start = CC.Manipulate.GetQ_vectors(self.structures, dyn_supercell, self.u_disps)
t2 = time.time()
# self.current_q = self.q_start.copy()
if count_stress == self.N:
self.has_stress = True
else:
self.has_stress = False
if timer:
timer.execute_timed_function(self.init)
else:
self.init()
def save(self, data_dir, population, use_alat = False):
"""
SAVE THE ENSEMBLE
=================
This function saves the ensemble in a way the original fortran SSCHA code can read it.
Look at the load function documentation to see clearely how it is saved.
NOTE: This method do not save the dynamical matrix used to generate the ensemble (i.e. self.dyn_0)
remember to save it separately to really save all the info about the ensemble.
Parameters
----------
data_dir : string
Path to the directory in which the data will be saved. If it does not exists, it will be created
population : int
The id of the population, usefull if you want to save more ensemble in the same data_dir without overwriting
the data.
use_alat : bool
If true the scf_populationX_Y.dat files will be saved in alat units, as specified by the dynamical matrix.
Also the unit cell will be omitted. This is done to preserve retrocompatibility with ensembles generated by
older versions of the sscha code
"""
A_TO_BOHR = 1.889725989
if not Parallel.am_i_the_master():
return
# Check if the data dir exists
if not os.path.exists(data_dir):
os.makedirs(data_dir)
# Check if the ensemble has really been initialized
if self.N == 0:
raise ValueError("Error, the ensemble seems to be not initialized.")
# Check if the given data_dir is a real directory
if os.path.exists(data_dir) and not os.path.isdir(data_dir):
raise IOError("Error, the given data_dir %s is not a valid directory." % data_dir)
if not os.path.exists(data_dir):
os.mkdir(data_dir)
# Remove the tailoring slash if any
if data_dir[-1] == "/":
data_dir = data_dir[:-1]
# Save the energies
np.savetxt(os.path.join(data_dir, "energies_supercell_population%d.dat" % (population)), self.energies)
self.dyn_0.save_qe("dyn_start_population%d_" % population)
self.current_dyn.save_qe("dyn_end_population%d_" % population)
# Save the displacements with the dynamical matrix used to generate the ensemble
# In this way the displacements are computed with the correct dynamical matrix
cd = self.current_dyn
self.update_weights(self.dyn_0, self.current_T)
#super_dyn = self.dyn_0.GenerateSupercellDyn(self.supercell)
for i in range(self.N):
# Save the forces
if self.force_computed[i]:
np.savetxt("%s/forces_population%d_%d.dat" % (data_dir, population, i+1), self.forces[i,:,:] / A_TO_BOHR)
# Save the configurations
struct = self.structures[i]
if use_alat:
struct.save_scf("%s/scf_population%d_%d.dat" % (data_dir, population, i+1), self.dyn_0.alat, True)
else:
struct.save_scf("%s/scf_population%d_%d.dat" % (data_dir, population, i+1))
u_disp = self.u_disps[i, :].reshape((struct.N_atoms, 3))# struct.get_displacement(super_dyn.structure)
np.savetxt("%s/u_population%d_%d.dat" % (data_dir, population, i+1), u_disp * A_TO_BOHR)
# Save the stress tensors if any
if self.has_stress and self.stress_computed[i]:
np.savetxt("%s/pressures_population%d_%d.dat" % (data_dir, population, i+1), self.stresses[i,:,:])
# Return back to the old dynamical matrix
self.update_weights(cd, self.current_T)
def save_bin(self, data_dir, population_id = 1):
"""
FAST SAVE OF THE ENSEMBLE
=========================
This function is a fast way of saving the ensemble.
It is faster and make use of less disk space than the save.
The drawback is that can only be opened with numpy
Parameters
----------
data_dir : string
path to the folder in which the ensemble is saved
population_id : int
The id of the population. This can be used to save
several ensembles in the same data_dir
"""
if not Parallel.am_i_the_master():
return
# Check if the data dir exists
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if Parallel.am_i_the_master():
np.save("%s/energies_pop%d.npy" % (data_dir, population_id), self.energies)
np.save("%s/forces_pop%d.npy" % (data_dir, population_id), self.forces)
# Save the structures
np.save("%s/xats_pop%d.npy" % (data_dir, population_id), self.xats)
if self.has_stress:
np.save("%s/stresses_pop%d.npy" % (data_dir, population_id), self.stresses)
self.dyn_0.save_qe("%s/dyn_gen_pop%d_" % (data_dir, population_id))
if np.all(len(list(x)) > 0 for x in self.all_properties):
with open(os.path.join(data_dir, "all_properties_pop%d.json" % population_id), "w") as fp:
json.dump({"properties" : self.all_properties}, fp, cls=NumpyEncoder)
def save_extxyz(self, filename, append_mode = True):
"""
SAVE INTO EXTXYZ FORMAT
=======================
ASE extxyz format is used for build the training set for the nequip and allegro neural network potentials.
Note, this is the same as save_enhanced_xyz, but it uses ASE builtin function.
If ase is not found, it will use the save_enhanced_xyz function.
Parameters
----------
filename : str
The path to the .extxyz file containing the ensemble
append_mode: bool
If true the ensemble is appended
"""
if not __ASE__:
self.save_enhanced_xyz(filename, append_mode = append_mode)
raise ImportError("Error, this function requires ASE installed")