-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathElectronicMinimize.py
253 lines (223 loc) · 9.33 KB
/
ElectronicMinimize.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
#!/usr/bin/python3
# Author: Yalcin Ozhabes
# email: [email protected]
import copy
import time
import numpy as np
from mpi4py import MPI
from ase.calculators.calculator import Calculator, all_changes
from ase import Atoms
from ase.units import Bohr, Hartree
from JDFTxCalcCPU import JDFTxCalcCPU
try:
from JDFTxCalcGPU import JDFTxCalcGPU
except ImportError:
JDFTxCalcGPU = JDFTxCalcCPU
class ElectronicMinimize(JDFTxCalcCPU, Calculator):
"""
A calculator derived from JDFTxCalcCPU.
"""
implemented_properties = ['energy', 'forces']
@staticmethod
def _changeOrder(x, indexList):
if isinstance(x, np.ndarray):
out = copy.copy(x)
for i, ind in enumerate(indexList):
out[ind] = x[i]
return out
elif isinstance(x, Atoms):
out = [0] * len(x)
for i, ind in enumerate(indexList):
out[ind] = copy.copy(x[i])
return Atoms(out)
else:
raise TypeError("Can change the order of np.ndarray or ase.Atoms")
@staticmethod
def _createIndexLists(atoms):
"""JDFT has atoms ordered by their symbols so we need conversion tables
of indices:"""
symbols = {} # count number of occurances
species_order = []
for atom in atoms:
try:
symbols[atom.symbol] += 1
except KeyError:
species_order.append(atom.symbol)
symbols[atom.symbol] = 0
i = 0
for sp in species_order:
number_of_sp = symbols[sp] + 1
symbols[sp] = i
i += number_of_sp
toJDFTOrderIndexList = [0] * len(atoms)
fromJDFTOrderIndexList = [0] * len(atoms)
for ind, atom in enumerate(atoms):
toJDFTOrderIndexList[ind] = symbols[atom.symbol]
fromJDFTOrderIndexList[symbols[atom.symbol]] = ind
symbols[atom.symbol] += 1
return (toJDFTOrderIndexList, fromJDFTOrderIndexList)
def _toJDFTOrder(self, x):
return self._changeOrder(x, self._toJDFTOrderIndexList)
def _fromJDFTOrder(self, x):
return self._changeOrder(x, self._fromJDFTOrderIndexList)
def __init__(self, restart=None, ignore_bad_restart_file=False,
atoms=None, log=True, comm=None, **kwargs):
Calculator.__init__(self, restart, ignore_bad_restart_file,
"JDFT", atoms, **kwargs)
nThreads = kwargs['nThreads'] if 'nThreads' in kwargs else None
super(ElectronicMinimize, self).__init__(comm=comm, nThreads=nThreads,
log = log)
if 'kpts' in kwargs:
self.kpts = kwargs['kpts']
if 'settings' in kwargs:
self.settings = kwargs['settings']
if atoms is None:
return
elif not isinstance(atoms, Atoms):
raise TypeError("atoms should be ase.Atoms type.")
self._toJDFTOrderIndexList, self._fromJDFTOrderIndexList = self._createIndexLists(atoms)
self.cell = atoms.cell
if 'pseudopotential' in atoms.info:
pspots = [atoms.info[pseudopotential]] * len(atoms)
elif 'pseudopotentials' in atoms.info:
pspots = atoms.info['pseudopotentials']
assert len(pspots) == len(atoms)
else:
pspots = None
for i, atom in enumerate(atoms):
if pspots:
atom.data['pseudopotential'] = pspots[i]
self.add_ion(atom)
t0 = time.time()
c0 = time.clock()
self.setup()
print("Wall Time for e.setup()", time.time()-t0, "seconds")
print("Process Time for e.setup()", time.clock()-c0, "seconds")
def updateAtomicPositions(self):
""""""
dpos = self.atoms.positions - self._fromJDFTOrder(self.getIonicPositions() * Bohr)
super(ElectronicMinimize, self).updateIonicPositions(self._toJDFTOrder(dpos / Bohr))
def calculate(self, atoms=None, properties=['energy'],
system_changes=all_changes):
"""Run one electronic minimize loop"""
super(ElectronicMinimize, self).calculate(atoms, properties, system_changes)
if 'positions' in system_changes:
self.updateAtomicPositions()
else:
print(system_changes)
t0 = time.time()
c0 = time.clock()
self.runElecMin()
print("Wall Time for self.runElecMin()", time.time()-t0, "seconds")
print("Process Time for self.runElecMin()", time.clock()-c0, "seconds")
energy = self.readTotalEnergy() * Hartree
forces = np.asarray(self.readForces(), dtype=np.double)
forces.resize((len(atoms), 3))
forces = self._fromJDFTOrder(forces)
forces = forces * Hartree / Bohr
self.results = {'energy': energy,
'forces': forces,
'stress': np.zeros(6),
'dipole': np.zeros(3),
'charges': np.zeros(len(atoms)),
'magmom': 0.0,
'magmoms': np.zeros(len(atoms))}
class ElectronicMinimizeGPU(JDFTxCalcGPU, Calculator):
"""
A calculator derived from JDFTxCalcGPU.
"""
implemented_properties = ['energy', 'forces']
@staticmethod
def _changeOrder(x, indexList):
if isinstance(x, np.ndarray):
out = copy.copy(x)
for i, ind in enumerate(indexList):
out[ind] = x[i]
return out
elif isinstance(x, Atoms):
out = [0] * len(x)
for i, ind in enumerate(indexList):
out[ind] = copy.copy(x[i])
return Atoms(out)
else:
raise TypeError("Can change the order of np.ndarray or ase.Atoms")
@staticmethod
def _createIndexLists(atoms):
"""JDFT has atoms ordered by their symbols so we need conversion tables
of indices:"""
symbols = {} # count number of occurances
species_order = []
for atom in atoms:
try:
symbols[atom.symbol] += 1
except KeyError:
species_order.append(atom.symbol)
symbols[atom.symbol] = 0
i = 0
for sp in species_order:
number_of_sp = symbols[sp] + 1
symbols[sp] = i
i += number_of_sp
toJDFTOrderIndexList = [0] * len(atoms)
fromJDFTOrderIndexList = [0] * len(atoms)
for ind, atom in enumerate(atoms):
toJDFTOrderIndexList[ind] = symbols[atom.symbol]
fromJDFTOrderIndexList[symbols[atom.symbol]] = ind
symbols[atom.symbol] += 1
return (toJDFTOrderIndexList, fromJDFTOrderIndexList)
def _toJDFTOrder(self, x):
return self._changeOrder(x, self._toJDFTOrderIndexList)
def _fromJDFTOrder(self, x):
return self._changeOrder(x, self._fromJDFTOrderIndexList)
def __init__(self, restart=None, ignore_bad_restart_file=False,
atoms=None, log=True, comm=None, **kwargs):
print "ElecMinGPU init running"
Calculator.__init__(self, restart, ignore_bad_restart_file,
"JDFT", atoms, **kwargs)
nThreads = kwargs['nThreads'] if 'nThreads' in kwargs else None
super(ElectronicMinimizeGPU, self).__init__(comm=comm, nThreads=nThreads,
log = log)
if 'kpts' in kwargs:
self.kpts = kwargs["kpts"]
if atoms is None:
return
elif not isinstance(atoms, Atoms):
raise TypeError("atoms should be ase.Atoms type.")
self._toJDFTOrderIndexList, self._fromJDFTOrderIndexList = self._createIndexLists(atoms)
self.cell = atoms.cell
for atom in atoms:
self.add_ion(atom)
t0 = time.time()
c0 = time.clock()
self.setup()
print("Wall Time for e.setup()", time.time()-t0, "seconds")
print("Process Time for e.setup()", time.clock()-c0, "seconds")
def updateAtomicPositions(self):
""""""
dpos = self.atoms.positions - self._fromJDFTOrder(self.getIonicPositions() * Bohr)
super(ElectronicMinimizeGPU, self).updateIonicPositions(self._toJDFTOrder(dpos / Bohr))
def calculate(self, atoms=None, properties=['energy'],
system_changes=all_changes):
"""Run one electronic minimize loop"""
super(ElectronicMinimizeGPU, self).calculate(atoms, properties, system_changes)
if 'positions' in system_changes:
self.updateAtomicPositions()
else:
print(system_changes)
t0 = time.time()
c0 = time.clock()
self.runElecMin()
print("Wall Time for self.runElecMin()", time.time()-t0, "seconds")
print("Process Time for self.runElecMin()", time.clock()-c0, "seconds")
energy = self.readTotalEnergy() * Hartree
forces = np.asarray(self.readForces(), dtype=np.double)
forces.resize((len(atoms), 3))
forces = self._fromJDFTOrder(forces)
forces = forces * Hartree / Bohr
self.results = {'energy': energy,
'forces': forces,
'stress': np.zeros(6),
'dipole': np.zeros(3),
'charges': np.zeros(len(atoms)),
'magmom': 0.0,
'magmoms': np.zeros(len(atoms))}