-
Notifications
You must be signed in to change notification settings - Fork 55
/
__init__.py
3547 lines (3243 loc) · 135 KB
/
__init__.py
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
#****************************************************************************
# Copyright (C) 2013-2015 SUNCAT
# This file is distributed under the terms of the
# GNU General Public License. See the file `COPYING'
# in the root directory of the present distribution,
# or http://www.gnu.org/copyleft/gpl.txt .
#****************************************************************************
gitver = 'GITVERSION'
import os
try:
import espsite
except ImportError:
print '*** ase-espresso requires a site-specific espsite.py in PYTHONPATH.'
print '*** You may use the espsite.py.example.* in the git checkout as templates.'
raise ImportError
site = espsite.config()
try:
from ase.calculators.calculator import FileIOCalculator as Calculator
except:
from ase.calculators.general import Calculator
import atexit
import sys, string
import numpy as np
from types import FileType, StringType
from constants import *
from utils import *
from subdirs import *
from subprocess import Popen, PIPE
# ase controlled pw.x's register themselves here, so they can be
# stopped automatically
espresso_calculators = []
# Define types of convergence errors that can be used to handle convergence error automatically
class ConvergenceError(Exception):
pass
class KohnShamConvergenceError(ConvergenceError):
pass
class espresso(Calculator):
"""
ase interface for Quantum Espresso
"""
implemented_properties = ['energy', 'free_energy', 'forces', 'stress', 'magmom', 'magmoms']
def __init__(self,
atoms = None,
exedir='', #espresso binary folder, if "./" just take the current environmental variable
pw = 350.0,
dw = None,
fw = None,
nbands = -10,
kpts = (1,1,1),
kptshift = (0,0,0),
fft_grid = None, #if specified, set the keywrds nr1, nr2, nr3 in q.e. input [RK]
mode = 'ase3',
opt_algorithm = 'ase3',
nstep = None,
constr_tol = None,
fmax = 0.05,
cell_dynamics = None,
press = None, # target pressure
dpress = None, # convergence limit towards target pressure
cell_factor = None,
cell_dofree = None,
dontcalcforces = False,
nosym = False,
noinv = False,
nosym_evc = False,
no_t_rev = False,
xc = 'PBE',
beefensemble = False,
printensemble = False,
psppath = None,
spinpol = False,
noncollinear = False,
spinorbit = False,
outdir = None,
txt = None,
calcstress = False,
vdw_corr = None,
smearing = 'fd',
sigma = 0.1,
ibrav = 0,
fix_magmom = False,
isolated = None,
U = None,
J = None,
U_alpha = None,
U_projection_type = 'atomic',
nqx1 = None,
nqx2 = None,
nqx3 = None,
exx_fraction = None,
screening_parameter = None,
exxdiv_treatment = None,
ecutvcut = None,
tot_charge = None, # +1 means 1 e missing, -1 means 1 extra e
charge = None, # overrides tot_charge (ase 3.7+ compatibility)
tot_magnetization = -1, #-1 means unspecified, 'hund' means Hund's rule for each atom
occupations = 'smearing', # 'smearing', 'fixed', 'tetrahedra'
dipole = {'status':False},
field = {'status':False},
output = {'disk_io':'default', # how often espresso writes wavefunctions to disk
'avoidio':False, # will overwrite disk_io parameter if True
'removewf':True,
'removesave':False,
'wf_collect':False},
convergence = {'energy':1e-6,
'mixing':0.7,
'maxsteps':100,
'diag':'david'},
startingpot = None,
startingwfc = None,
ion_positions = None,
parflags = None,
onlycreatepwinp = None, #specify filename to only create pw input
single_calculator = True, #if True, only one espresso job will be running
procrange = None, #let this espresso calculator run only on a subset of the requested cpus
numcalcs = None, #used / set by multiespresso class
alwayscreatenewarrayforforces = True,
verbose = 'low',
#automatically generated list of parameters
#some coincide with ase-style names
iprint = None,
tstress = None,
tprnfor = None,
dt = None,
lkpoint_dir = None,
max_seconds = None,
etot_conv_thr = None,
forc_conv_thr = None,
tefield = None,
dipfield = None,
lelfield = None,
nberrycyc = None,
lorbm = None,
lberry = None,
gdir = None,
nppstr = None,
nbnd = None,
ecutwfc = None,
ecutrho = None,
ecutfock = None,
force_symmorphic = None,
use_all_frac = None,
one_atom_occupations = None,
starting_spin_angle = None,
degauss = None,
nspin = None,
ecfixed = None,
qcutz = None,
q2sigma = None,
x_gamma_extrapolation = None,
lda_plus_u = None,
lda_plus_u_kind = None,
edir = None,
emaxpos = None,
eopreg = None,
eamp = None,
clambda = None,
report = None,
lspinorb = None,
esm_bc = None,
esm_w = None,
esm_efield = None,
esm_nfit = None,
london = None,
london_s6 = None,
london_rcut = None,
xdm = None,
xdm_a1 = None,
xdm_a2 = None,
electron_maxstep = None,
scf_must_converge = None,
conv_thr = None,
adaptive_thr = None,
conv_thr_init = None,
conv_thr_multi = None,
mixing_beta = None,
mixing_ndim = None,
mixing_fixed_ns = None,
ortho_para = None,
diago_thr_init = None,
diago_cg_maxiter = None,
diago_david_ndim = None,
diago_full_acc = None,
efield = None,
tqr = None,
remove_rigid_rot = None,
tempw = None,
tolp = None,
delta_t = None,
nraise = None,
refold_pos = None,
upscale = None,
bfgs_ndim = None,
ts_vdw_econv_thr = None,
ts_vdw_isolated = None,
lfcpopt = None,
fcp_mu = None,
esm_a = None,
trust_radius_max = None,
trust_radius_min = None,
trust_radius_ini = None,
w_1 = None,
w_2 = None,
wmass = None,
press_conv_thr = None,
results = {},
name = 'espresso',
restart=None,
ignore_bad_restart_file=False,
label=None,
command=None,
####ENVIRON PART (credit Stefan Ringe)
environ_keys=None, #Environ keys given as dictionary, if given use_environ=True
environ_extra_keys=None
):
"""
Construct an ase-espresso calculator.
Parameters (with defaults in parentheses):
atoms (None)
list of atoms object to be attached to calculator
atoms.set_calculator can be used instead
onlycreatepwinp (None)
if not None but 'filename', create input file 'filename' for pw.x
but do not run pw.x
calc.initialize(atoms) will trigger 'filename' to be written
pw (350.0)
plane-wave cut-off in eV
dw (10*pw)
charge-density cut-off in eV
fw (None)
plane-wave cutoff for evaluation of EXX in eV
nbands (-10)
number of bands, if negative: -n extra bands
kpts ( (1,1,1) )
k-point grid sub-divisions, k-point grid density,
explicit list of k-points, or simply 'gamma' for gamma-point only.
kptshift ( (0,0,0) )
shift of k-point grid
fft_grid ( None )
specify tuple of fft grid points (nr1,nr2,nr3) for q.e.
useful for series of calculations with changing cell size (e.g. lattice constant optimization)
uses q.e. default if not specified. [RK]
mode ( 'ase3' )
relaxation mode:
- 'ase3': dynamic communication between Quantum Espresso and python
- 'relax', 'scf', 'nscf': corresponding Quantum Espresso standard modes
opt_algorithm ( 'ase3' )
- 'ase3': ase updates coordinates during relaxation
- 'relax' and other Quantum Espresso standard relaxation modes:
Quantum Espresso own algorithms for structural optimization
are used
Obtaining Quantum Espresso with the ase3 relaxation extensions is
highly recommended, since it allows for using ase's optimizers without
loosing efficiency:
svn co --username anonymous http://qeforge.qe-forge.org/svn/q-e/branches/espresso-dynpy-beef
fmax (0.05)
max force limit for Espresso-internal relaxation (eV/Angstrom)
constr_tol (None)
constraint tolerance for Espresso-internal relaxation
cell_dynamics (None)
algorithm (e.g. 'BFGS') to be used for Espresso-internal
unit-cell optimization
press (None)
target pressure for such an optimization
dpress (None)
convergence limit towards target pressure
cell_factor (None)
should be >>1 if unit-cell volume is expected to shrink a lot during
relaxation (would be more efficient to start with a better guess)
cell_dofree (None)
partially fix lattice vectors
nosym (False)
noinv (False)
nosym_evc (False)
no_t_rev (False)
turn off corresp. symmetries
xc ('PBE')
xc-functional to be used
beefensemble (False)
calculate basis energies for ensemble error estimates based on
the BEEF-vdW functional
printensemble (False)
let Espresso itself calculate 2000 ensemble energies
psppath (None)
Directory containing the pseudo-potentials or paw-setups to be used.
The ase-espresso interface expects all pot. files to be of the type
element.UPF (e.g. H.UPF).
If None, the directory pointed to be ESP_PSP_PATH is used.
spinpol (False)
If True, calculation is spin-polarized
noncollinear (False)
Non-collinear magnetism.
spinorbit (False)
If True, spin-orbit coupling is considered.
Make sure to provide j-dependent pseudo-potentials in psppath
for those elements where spin-orbit coupling is important
outdir (None)
directory where Espresso's output is collected,
default: qe<random>
txt (None)
If not None, direct Espresso's output to a different file than
outdir/log
calcstress (False)
If True, calculate stress
occupations ('smearing')
Controls how Kohn-Sham states are occupied.
Possible values: 'smearing', 'fixed' (molecule or insulator),
or 'tetrahedra'.
smearing ('fd')
method for Fermi surface smearing
- 'fd','Fermi-Dirac': Fermi-Dirac
- 'mv','Marzari-Vanderbilt': Marzari-Vanderbilt cold smearing
- 'gauss','gaussian': Gaussian smearing
- 'mp','Methfessel-Paxton': Methfessel-Paxton
For ase 3.7+ compatibility, smearing can also be a tuple where
the first parameter is the method and the 2nd parameter
is the smearing width which overrides sigma below
sigma (0.1)
smearing width in eV
tot_charge (None)
charge the unit cell,
+1 means 1 e missing, -1 means 1 extra e
charge (None)
overrides tot_charge (ase 3.7+ compatibility)
tot_magnetization (-1)
Fix total magnetization,
-1 means unspecified/free,
'hund' means Hund's rule for each atom
fix_magmom (False)
If True, fix total magnetization to current value.
isolated (None)
invoke an 'assume_isolated' method for screening long-range interactions
across 3D supercells, particularly electrostatics.
Very useful for charged molecules and charged surfaces,
but also improves convergence wrt. vacuum space for neutral molecules.
- 'makov-payne', 'mp': only cubic systems.
- 'dcc': don't use.
- 'martyna-tuckerman', 'mt': method of choice for molecules, works for any supercell geometry.
- 'esm': Effective Screening Medium Method for surfaces and interfaces.
U (None)
specify Hubbard U values (in eV)
U can be list: specify U for each atom
U can be a dictionary ( e.g. U={'Fe':3.5} )
U values are assigned to angular momentum channels
according to Espresso's hard-coded defaults
(i.e. l=2 for transition metals, l=1 for oxygen, etc.)
J (None)
specify exchange J values (in eV)
can be list or dictionary (see U parameter above)
U_alpha
U_alpha (in eV)
can be list or dictionary (see U parameter above)
U_projection_type ('atomic')
type of projectors for calculating density matrices in DFT+U schemes
nqx1, nqx2, nqx3 (all None)
3D mesh for q=k1-k2 sampling of Fock operator. Can be smaller
than number of k-points.
exx_fraction (None)
Default depends on hybrid functional chosen.
screening_parameter (0.106)
Screening parameter for HSE-like functionals.
exxdiv_treatment (gygi-baldereschi)
Method to treat Coulomb potential divergence for small q.
ecutvcut (0)
Cut-off for above.
dipole ( {'status':False} )
If 'status':True, turn on dipole correction; then by default, the
dipole correction is applied along the z-direction, and the dipole is
put in the center of the vacuum region (taking periodic boundary
conditions into account).
This can be overridden with:
- 'edir':1, 2, or 3 for x-, y-, or z-direction
- 'emaxpos':float percentage wrt. unit cell where dip. correction
potential will be max.
- 'eopreg':float percentage wrt. unit cell where potential decreases
- 'eamp':0 (by default) if non-zero overcompensate dipole: i.e. apply
a field
output ( {'disk_io':'default', # how often espresso writes wavefunctions to disk
'avoidio':False, # will overwrite disk_io parameter if True
'removewf':True,
'removesave':False,
'wf_collect':False} )
control how much io is used by espresso;
'removewf':True means wave functions are deleted in scratch area before
job is done and data is copied back to submission directory
'removesave':True means whole .save directory is deleted in scratch area
convergence ( {'energy':1e-6,
'mixing':0.7,
'maxsteps':100,
'diag':'david'} )
Electronic convergence criteria and diag. and mixing algorithms.
Additionally, a preconditioner for the mixing algoritms can be
specified, e.g. 'mixing_mode':'local-TF' or 'mixing_mode':'TF'.
startingpot (None)
By default: 'atomic' (use superposition of atomic orbitals for
initial guess)
'file': construct potential from charge-density.dat
Can be used with load_chg and save_chg methods.
startingwfc (None)
By default: 'atomic'.
Other options: 'atomic+random' or 'random'.
'file': reload wave functions from other calculations.
See load_wf and save_wf methods.
parflags (None)
Parallelization flags for Quantum Espresso.
E.g. parflags='-npool 2' will distribute k-points (and spin if
spin-polarized) over two nodes.
verbose ('low')
Can be 'high' or 'low'
"""
self.exedir=exedir
self.outdir= outdir
self.onlycreatepwinp = onlycreatepwinp
self.pw = pw
self.dw = dw
self.fw = fw
self.nbands = nbands
if type(kpts)==float or type(kpts)==int:
from ase.calculators.calculator import kptdensity2monkhorstpack
kpts = kptdensity2monkhorstpack(atoms, kpts)
elif isinstance(kpts, StringType):
assert kpts == 'gamma'
else:
assert len(kpts) == 3
self.kpts = kpts
self.kptshift = kptshift
self.fft_grid = fft_grid #RK
self.calcmode = mode
self.opt_algorithm = opt_algorithm
self.nstep = nstep
self.constr_tol = constr_tol
self.fmax = fmax
self.cell_dynamics = cell_dynamics
self.press = press
self.dpress = dpress
self.cell_factor = cell_factor
self.cell_dofree = cell_dofree
self.dontcalcforces = dontcalcforces
self.nosym = nosym
self.noinv = noinv
self.nosym_evc = nosym_evc
self.no_t_rev = no_t_rev
self.xc = xc
self.beefensemble = beefensemble
self.printensemble = printensemble
if isinstance(smearing, (str, unicode)):
self.smearing = str(smearing)
self.sigma = sigma
else:
self.smearing = smearing[0]
self.sigma = smearing[1]
self.spinpol = spinpol
self.noncollinear = noncollinear
self.spinorbit = spinorbit
self.fix_magmom = fix_magmom
self.isolated = isolated
if charge is None:
self.tot_charge = tot_charge
else:
self.tot_charge = charge
self.tot_magnetization = tot_magnetization
self.occupations = occupations
self.outdir = outdir
self.calcstress = calcstress
self.psppath = psppath
self.dipole = dipole
self.field = field
self.output = output
self.convergence = convergence
self.startingpot = startingpot
self.startingwfc = startingwfc
self.ion_positions = ion_positions
self.verbose = verbose
self.U = U
self.J = J
self.U_alpha = U_alpha
self.U_projection_type = U_projection_type
self.nqx1 = nqx1
self.nqx2 = nqx2
self.nqx3 = nqx3
self.exx_fraction = exx_fraction
self.screening_parameter = screening_parameter
self.exxdiv_treatment = exxdiv_treatment
self.ecutvcut = ecutvcut
self.newforcearray = alwayscreatenewarrayforforces
self.parflags=''
self.serflags=''
#ENVIRON IMPLICIT SOLVATION
if environ_keys is not None: # hasattr(self,'environ_keys') and self.environ_keys is not None:
self.parflags=' -environ '
self.serflags=' -environ '
self.environ_keys=environ_keys
self.use_environ=True
else:
self.parflags=''
self.serflags=''
self.use_environ=False
self.environ_keys=environ_keys
self.environ_extra_keys=environ_extra_keys
self.ibrav=int(ibrav)
if parflags is not None:
self.parflags += parflags
self.single_calculator = single_calculator
self.txt = txt
self.mypath = os.path.abspath(os.path.dirname(__file__))
self.writeversion = True
self.atoms = None
self.sigma_small = 1e-13
self.started = False
self.got_energy = False
self.only_init = False
#automatically generated list
self.iprint = iprint
self.tstress = tstress
self.tprnfor = tprnfor
self.dt = dt
self.lkpoint_dir = lkpoint_dir
self.max_seconds = max_seconds
self.etot_conv_thr = etot_conv_thr
self.forc_conv_thr = forc_conv_thr
self.tefield = tefield
self.dipfield = dipfield
self.lelfield = lelfield
self.nberrycyc = nberrycyc
self.lorbm = lorbm
self.lberry = lberry
self.gdir = gdir
self.nppstr = nppstr
self.nbnd = nbnd
self.ecutwfc = ecutwfc
self.ecutrho = ecutrho
self.ecutfock = ecutfock
self.force_symmorphic = force_symmorphic
self.use_all_frac = use_all_frac
self.one_atom_occupations = one_atom_occupations
self.starting_spin_angle = starting_spin_angle
self.degauss = degauss
self.nspin = nspin
self.ecfixed = ecfixed
self.qcutz = qcutz
self.q2sigma = q2sigma
self.x_gamma_extrapolation = x_gamma_extrapolation
self.lda_plus_u = lda_plus_u
self.lda_plus_u_kind = lda_plus_u_kind
self.edir = edir
self.emaxpos = emaxpos
self.eopreg = eopreg
self.eamp = eamp
self.clambda = clambda
self.report = report
self.lspinorb = lspinorb
self.esm_bc = esm_bc
self.esm_w = esm_w
self.esm_efield = esm_efield
self.esm_nfit = esm_nfit
self.london = london
self.london_s6 = london_s6
self.london_rcut = london_rcut
self.xdm = xdm
self.xdm_a1 = xdm_a1
self.xdm_a2 = xdm_a2
self.electron_maxstep = electron_maxstep
self.scf_must_converge = scf_must_converge
self.conv_thr = conv_thr
self.adaptive_thr = adaptive_thr
self.conv_thr_init = conv_thr_init
self.conv_thr_multi = conv_thr_multi
self.mixing_beta = mixing_beta
self.mixing_ndim = mixing_ndim
self.mixing_fixed_ns = mixing_fixed_ns
self.ortho_para = ortho_para
self.diago_thr_init = diago_thr_init
self.diago_cg_maxiter = diago_cg_maxiter
self.diago_david_ndim = diago_david_ndim
self.diago_full_acc = diago_full_acc
self.efield = efield
self.tqr = tqr
self.remove_rigid_rot = remove_rigid_rot
self.tempw = tempw
self.tolp = tolp
self.delta_t = delta_t
self.nraise = nraise
self.refold_pos = refold_pos
self.upscale = upscale
self.bfgs_ndim = bfgs_ndim
self.ts_vdw_econv_thr = ts_vdw_econv_thr
self.ts_vdw_isolated = ts_vdw_isolated
self.lfcpopt = lfcpopt
self.fcp_mu = fcp_mu
self.esm_a = esm_a
self.trust_radius_max = trust_radius_max
self.trust_radius_min = trust_radius_min
self.trust_radius_ini = trust_radius_ini
self.w_1 = w_1
self.w_2 = w_2
self.wmass = wmass
self.press_conv_thr = press_conv_thr
self.results = results
self.name = name
self.vdw_corr = vdw_corr
#give original espresso style input names
#preference over ase / dacapo - style names
if ecutwfc is not None:
self.pw = ecutwfc
if ecutrho is not None:
self.dw = ecutwfc
if nbnd is not None:
self.nbands = nbnd
# Variables that cannot be set by inputs
self.nvalence=None
self.nel = None
self.fermi_input = False
self.parameters = {}
# Auto create variables from input
self.input_update()
# Initialize lists of cpu subsets if needed
if procrange is None:
self.proclist = False
else:
self.proclist = True
procs = site.procs + []
procs.sort()
nprocs = len(procs)
self.myncpus = nprocs / numcalcs
i1 = self.myncpus * procrange
self.mycpus = self.localtmp+'/myprocs%04d.txt' % procrange
f = open(self.mycpus, 'w')
for i in range(i1,i1+self.myncpus):
print >>f, procs[i]
f.close()
if atoms is not None:
atoms.set_calculator(self)
if hasattr(site, 'mpi_not_setup') and self.onlycreatepwinp is None:
print '*** Without cluster-adjusted espsite.py, ase-espresso can only be used'
print '*** to create input files for pw.x via the option onlycreatepwinp.'
print '*** Otherwise, ase-espresso requires a site-specific espsite.py'
print '*** in PYTHONPATH.'
print '*** You may use the espsite.py.example.* in the git checkout as templates.'
raise ImportError
def input_update(self):
# Run initialization functions, such that this can be called if variables in espresso are
#changes using set or directly.
#sdir is the directory the script is run or submitted from
self.sdir = getsubmitorcurrentdir(site)
self.create_outdir() # Create the tmp output folder
if self.dw is None:
self.dw = 10. * self.pw
else:
assert self.dw >= self.pw
if self.psppath is None:
try:
self.psppath = os.environ['ESP_PSP_PATH']
except:
print 'Unable to find pseudopotential path. Consider setting ESP_PSP_PATH environment variable'
raise
if self.dipole is None:
self.dipole = {'status':False}
if self.field is None:
self.field = {'status':False}
if self.convergence is None:
self.conv_thr = 1e-6/rydberg
else:
if self.convergence.has_key('energy'):
self.conv_thr = self.convergence['energy']/rydberg
else:
self.conv_thr = 1e-6/rydberg
if self.beefensemble:
if self.xc.upper().find('BEEF')<0:
raise KeyError("ensemble-energies only work with xc=BEEF or variants of it!")
self.started = False
self.got_energy = False
def create_outdir(self):
if self.onlycreatepwinp is None:
self.localtmp = mklocaltmp(self.outdir, site)
if not self.txt:
self.log = self.localtmp+'/log'
elif self.txt[0]!='/':
self.log = self.sdir+'/'+self.txt
else:
self.log = self.txt
self.scratch = mkscratch(self.localtmp, site)
if self.output is not None:
if self.output.has_key('removewf'):
removewf = self.output['removewf']
else:
removewf = True
if self.output.has_key('removesave'):
removesave = self.output['removesave']
else:
removesave = False
else:
removewf = True
removesave = False
atexit.register(cleanup, self.localtmp, self.scratch, removewf, removesave, self, site)
self.cancalc = True
else:
self.pwinp = self.onlycreatepwinp
self.localtmp=''
self.cancalc = False
def set(self, **kwargs):
""" Define settings for the Quantum Espresso calculator object after it has been initialized.
This is done in the following way:
>> calc = espresso(...)
>> atoms = set.calculator(calc)
>> calc.set(xc='BEEF')
NB: No input validation is made
"""
for key, value in kwargs.items():
if key == 'outdir':
self.create_outdir()
self.outdir = value
if key == 'startingpot':
self.startingpot = value
if key == 'startingwfc':
self.startingwfc = value
if key == 'ion_positions':
self.ion_positions = value
if key == 'U_alpha':
self.U_alpha = value
if key == 'U':
self.U = value
if key == 'U_projection_type':
self.U_projection_type = value
if key == 'xc':
self.xc = value
if key == 'pw':
self.pw = value
if key == 'dw':
self.dw = value
if key == 'output':
self.output = value
if key == 'convergence':
self.convergence = value
if key == 'kpts':
self.kpts = value
if key == 'kshift':
self.kshift = value
if key == 'fft_grid': #RK
self.fft_grid = value
else:
setattr(self,key,value)
#ENVIRON IMPLICIT SOLVATION
if hasattr(self,'environ_keys') and self.environ_keys is not None:
self.parflags=' -environ '
self.serflags=' -environ '
self.use_environ=True
else:
self.parflags=''
self.serflags=''
self.use_environ=False
self.ibrav=int(self.ibrav)
self.input_update()
self.recalculate = True
self.results = {}
def __del__(self):
try:
self.stop()
except:
pass
def atoms2species(self):
# Define several properties of the quantum espresso species from the ase atoms object.
# Takes into account that different spins (or different U etc.) on same kind of
# chemical elements are considered different species in quantum espresso
symbols = self.atoms.get_chemical_symbols()
masses = self.atoms.get_masses()
magmoms = list(self.atoms.get_initial_magnetic_moments())
if len(magmoms)<len(symbols):
magmoms += list(np.zeros(len(symbols)-len(magmoms), np.float))
pos = self.atoms.get_scaled_positions()
if self.U is not None:
if type(self.U)==dict:
Ulist = np.zeros(len(symbols), np.float)
for i,s in enumerate(symbols):
if self.U.has_key(s):
Ulist[i] = self.U[s]
else:
Ulist = list(self.U)
if len(Ulist)<len(symbols):
Ulist += list(np.zeros(len(symbols)-len(Ulist), np.float))
else:
Ulist = np.zeros(len(symbols), np.float)
if self.J is not None:
if type(self.J)==dict:
Jlist = np.zeros(len(symbols), np.float)
for i,s in enumerate(symbols):
if self.J.has_key(s):
Jlist[i] = self.J[s]
else:
Jlist = list(self.J)
if len(Jlist)<len(symbols):
Jlist += list(np.zeros(len(symbols)-len(Jlist), np.float))
else:
Jlist = np.zeros(len(symbols), np.float)
if self.U_alpha is not None:
if type(self.U_alpha)==dict:
U_alphalist = np.zeros(len(symbols), np.float)
for i,s in enumerate(symbols):
if self.U_alpha.has_key(s):
U_alphalist[i] = self.U_alpha[s]
else:
U_alphalist = list(self.U_alpha)
if len(U_alphalist)<len(symbols):
U_alphalist += list(np.zeros(len(symbols)-len(U_alphalist), np.float))
else:
U_alphalist = np.zeros(len(symbols), np.float)
self.species = []
self.specprops = []
dic = {}
symcounter = {}
for s in symbols:
symcounter[s] = 0
for i in range(len(symbols)):
key = symbols[i]+'_m%.14eU%.14eJ%.14eUa%.14e' % (magmoms[i],Ulist[i],Jlist[i],U_alphalist[i])
if dic.has_key(key):
self.specprops.append((dic[key][1],pos[i]))
else:
symcounter[symbols[i]] += 1
spec = symbols[i]+str(symcounter[symbols[i]])
dic[key] = [i,spec]
self.species.append(spec)
self.specprops.append((spec,pos[i]))
self.nspecies = len(self.species)
self.specdict = {}
for i,s in dic.values():
if np.isnan(masses[i]):
mi = 0.0
else:
mi = masses[i]
self.specdict[s] = specobj(s = s.strip('0123456789'), #chemical symbol w/o index
mass = mi,
magmom = magmoms[i],
U = Ulist[i],
J = Jlist[i],
U_alpha = U_alphalist[i])
def get_nvalence(self):
nel = {}
for x in self.species:
el = self.specdict[x].s
#get number of valence electrons from pseudopotential or paw setup
p = os.popen('egrep -i \'z\ valence|z_valence\' '+self.psppath+'/'+el+'.UPF | tr \'"\' \' \'','r')
for y in p.readline().split():
if y[0].isdigit() or y[0]=='.':
# y.replace('E','e')
nel[el] = int(round(float(y)))
break
p.close()
nvalence = np.zeros(len(self.specprops), np.int)
for i,x in enumerate(self.specprops):
nvalence[i] = nel[self.specdict[x[0]].s]
return nvalence, nel
def writeenvinputfile(self, filename='environ.in'):
"""Write Environ input file"""
if self.cancalc:
fname = self.localtmp+'/'+filename
#f = open(self.localtmp+'/pw.inp', 'w')
else:
fname = self.pwinp.split('/')[:-1]+'/'+filename
f = open(fname,'w')
f.write('&ENVIRON\n')
f.write(' !\n')
for key in self.environ_keys:
value=self.environ_keys[key]
if type(value)==bool:
if value:
value='.true.'
else:
value='.false.'
f.write(' {} = {}\n'.format(key,value))
elif type(value)==str:
f.write(' {} = \'{}\'\n'.format(key, value))
elif 'e' in str(value):
value_str=str(value).replace('e','D')
f.write(' {} = {}\n'.format(key, value_str))
else:
f.write(' {} = {}\n'.format(key, self.environ_keys[key]))
f.write(' !\n')
f.write('/\n')
if self.environ_extra_keys is not None:
for key in self.environ_extra_keys:
#f.write('{} {}\n'.format(key,unit))
if key in ['EXTERNAL_CHARGES','DIELECTRIC_REGIONS']:
#CARDs
if 'unit' not in self.environ_extra_keys[key]:
unit='bohr'
else:
unit=self.environ_extra_keys[key]['unit']
f.write('{} {}\n'.format(key,unit))
for vals in self.environ_extra_keys[key]['settings']:
f.write(' {}\n'.format(' '.join([str(vv) for vv in vals])))
else:
#NAMELISTs
f.write('&{}\n'.format(key))
f.write(' !\n')
for key2 in self.environ_extra_keys[key]:
value=self.environ_extra_keys[key][key2]
if type(value)==bool:
if value:
value='.true.'
else:
value='.false.'
f.write(' {} = {}\n'.format(key2,value))
elif type(value)==str:
f.write(' {} = \'{}\'\n'.format(key2,value))
elif 'e' in str(value):
value_str=str(value).replace('e','D')
f.write(' {} = {}\n'.format(key2, value_str))
else:
f.write(' {} = {}\n'.format(key2,value))
f.write(' !\n')
f.write('/\n')
f.close()
def writeinputfile(self, filename='pw.inp', mode=None,
overridekpts=None, overridekptshift=None, overridenbands=None,
suppressforcecalc=False, usetetrahedra=False):
if self.atoms is None:
raise ValueError, 'no atoms defined'
if self.cancalc:
fname = self.localtmp+'/'+filename
#f = open(self.localtmp+'/pw.inp', 'w')
else:
fname = self.pwinp
#f = open(self.pwinp, 'w')
f = open(fname, 'w')
### &CONTROL ###
if mode is None:
if self.calcmode=='ase3':
print >>f, '&CONTROL\n calculation=\'relax\',\n prefix=\'calc\','
elif self.calcmode=='hund':
print >>f, '&CONTROL\n calculation=\'scf\',\n prefix=\'calc\','
else:
print >>f, '&CONTROL\n calculation=\''+self.calcmode+'\',\n prefix=\'calc\','
ionssec = self.calcmode not in ('scf','nscf','bands','hund')
else:
print >>f, '&CONTROL\n calculation=\''+mode+'\',\n prefix=\'calc\','
ionssec = mode not in ('scf','nscf','bands','hund')
if self.nstep != None:
print >>f, ' nstep='+str(self.nstep)+','
if self.verbose!='low':
print >>f, ' verbosity=\''+self.verbose+'\','
print >>f, ' pseudo_dir=\''+self.psppath+'\','
print >>f, ' outdir=\'.\','
efield = (self.field['status']==True)
dipfield = (self.dipole['status']==True)
if efield or dipfield:
print >>f, ' tefield=.true.,'
if dipfield:
print >>f, ' dipfield=.true.,'