venuspython 1.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,314 @@
1
+ import numpy as np
2
+ import shutil, os
3
+
4
+ from ase.calculators.calculator import Calculator
5
+ from ase.units import Ha, Ang, Bohr
6
+
7
+ from ase.calculators.nwchem import NWChem
8
+
9
+ # For debugging:
10
+ import os.path
11
+
12
+ class nwchemcalculator(Calculator):
13
+
14
+ implemented_properties = ['energy', 'forces']
15
+
16
+ def __init__(
17
+ self,
18
+ input_path,
19
+ output_path=None,
20
+ n_threads=1,
21
+ E_to_eV=Ha,
22
+ F_to_eV_Ang=Ha/Bohr,
23
+ use_torch=False,
24
+ *args,
25
+ **kwargs
26
+ ):
27
+ """
28
+ ASE calculator for the NWChem ab initio module
29
+
30
+ A calculator takes atomic numbers and atomic positions from an Atoms object and calculates the energy and forces.
31
+
32
+ Note
33
+ ----
34
+ ASE uses eV and Angstrom as energy and length unit, respectively. Unless the paramerters `E_to_eV` and `F_to_eV_Ang` are specified, the sGDML model is assumed to use kcal/mol and Angstorm and the appropriate conversion factors are set accordingly.
35
+ Here is how to find them: `ASE units <https://wiki.fysik.dtu.dk/ase/ase/units.html>`_.
36
+
37
+ Parameters
38
+ ----------
39
+ input_path : :obj:`str`
40
+ Path to a NWChem input file
41
+ E_to_eV : float, optional
42
+ Conversion factor from whatever energy unit is used by the model to eV. By default this parameter is set to convert from kcal/mol.
43
+ F_to_eV_Ang : float, optional
44
+ Conversion factor from whatever length unit is used by the model to Angstrom. By default, the length unit is not converted (assumed to be in Angstrom)
45
+ use_torch : boolean, optional
46
+ Use PyTorch to calculate predictions
47
+ """
48
+
49
+ super(nwchemcalculator, self).__init__(*args, **kwargs)
50
+
51
+ # Some suggested default values (for MD)
52
+ # self.maxiter = 5000
53
+ # self.d_convergence = 1.0e-8
54
+ # self.e_convergence = 1.0e-8
55
+ # self.freeze_core = 1
56
+
57
+ # Default values for the input
58
+ self.referencemethod = 'uhf'
59
+ self.method = 'b3lyp' # LevelOfTheory
60
+ self.basis_set = '6-31g*' # BasisSet
61
+ self.charge = 0
62
+ self.multiplicity = 2 # 2s+1
63
+ self.save_movecs_interval = None
64
+
65
+ # Some input values that are currently not set up (handled differently by QCEngine)
66
+ self.memory = 1500 # In MB
67
+ self.scratchdir = "/tmp"
68
+
69
+ scf = {"print":"low"}
70
+ dft = {"print":"low"}
71
+ dft_convergence = {}
72
+ dft_tolerances = {}
73
+ mp2 = {}
74
+ basispar="" #basispar="spherical"
75
+
76
+ # Read in the input
77
+ with open(input_path, 'r') as f:
78
+ for line in f:
79
+ strippedline=" ".join(line.split())
80
+ entries = strippedline.split(" ")
81
+ if (entries[0] == "memory"): self.memory = int(entries[1])
82
+ if (entries[0] == "scratchdir"): self.scratchdir = str(entries[1])
83
+ if (entries[0] == "referencemethod"):
84
+ self.referencemethod = str(entries[1])
85
+ elif (entries[0] == "freeze_core"):
86
+ mp2["freeze"] = "atomic"
87
+ elif (entries[0] == "method"): self.method = str(entries[1])
88
+ elif (entries[0] == "basis_set"):
89
+ basis_string_list = entries
90
+ basis_string_list.pop(0)
91
+ self.basis_set = " ".join(basis_string_list)
92
+ elif (entries[0] == "mulliken"):
93
+ dft["mulliken"] = None
94
+ mp2["mulliken"] = None
95
+ elif (entries[0] == "charge"): self.charge = int(entries[1])
96
+ elif (entries[0] == "multiplicity"): self.multiplicity = int(entries[1])
97
+ elif (entries[0] == "diis"):
98
+ scf["diis"] = None
99
+ dft["diis"] = None
100
+ elif (entries[0] == "diisbas"):
101
+ self.diisbas = int(entries[1])
102
+ scf["diisbas"] = self.diisbas
103
+ dft_convergence["diis"] = self.diisbas
104
+ elif (entries[0] == "maxiter"):
105
+ self.maxiter = int(entries[1])
106
+ elif (entries[0] == "guess_tolerance"):
107
+ scf["tolguess"] = float(entries[1])
108
+ elif (entries[0] == "dft_grid"):
109
+ dft["grid"] = str(entries[1])
110
+ # elif (entries[0] == "scf_level"):
111
+ # level_string_list = entries
112
+ # level_string_list.pop(0)
113
+ # self.keywords["scf; "+" ".join(level_string_list)+"; "] = "end"
114
+ # elif (entries[0] == "dft_convergence_other_options"):
115
+ # convergence_string_list = entries
116
+ # convergence_string_list.pop(0)
117
+ # self.keywords["dft; convergence "+" ".join(convergence_string_list)+"; "] = "end"
118
+ elif (entries[0] == "scf_tol2e"):
119
+ scf["tol2e"] = float(entries[1])
120
+ elif (entries[0] == "dft_tolerances_tight"):
121
+ if (int(entries[1]) == 1):
122
+ dft_tolerances["tight"] = None
123
+ elif (entries[0] == "dft_tolerances_tol_rho"):
124
+ dft_tolerances["tol_rho"] = float(entries[1])
125
+ elif (entries[0] == "dft_tolerances_accCoul"):
126
+ dft_tolerances["accCoul"] = float(entries[1])
127
+ elif (entries[0] == "dft_tolerances_radius"):
128
+ dft_tolerances["radius"] = float(entries[1])
129
+ elif (entries[0] == "dft_e_convergence"):
130
+ dft_convergence["energy"] = float(entries[1])
131
+ elif (entries[0] == "dft_d_convergence"):
132
+ dft_convergence["density"] = float(entries[1])
133
+ elif (entries[0] == "dft_g_convergence"):
134
+ dft_convergence["gradient"] = float(entries[1])
135
+ elif (entries[0] == "scf_convergence"):
136
+ scf["thresh"] = float(entries[1])
137
+
138
+ elif (entries[0] == "scf_direct"):
139
+ if (int(entries[1]) == 1):
140
+ scf["direct"] = None
141
+ elif (entries[0] == "dft_direct"):
142
+ if (int(entries[1]) == 1):
143
+ dft["direct"] = None
144
+ elif (entries[0] == "mp2_tight_precision"):
145
+ if (int(entries[1]) == 1):
146
+ mp2["tight"] = None
147
+ elif (entries[0] == "dft_disp_vdw"):
148
+ dft["disp"] = {"vdw":str(entries[1])}
149
+
150
+ elif (entries[0] == "save_movecs_interval"):
151
+ self.save_movecs_interval = int(entries[1])
152
+ self.save_movecs_count = -9999999 # Do not do any saving yet
153
+
154
+ else:
155
+ print("Ignoring keyword line (nothing will be added to the NWChem input file) with entries: ", entries)
156
+
157
+ # Some inputs for details on saving intermediate results
158
+ if (output_path):
159
+ self.outputDIR = os.path.abspath(output_path)
160
+ print("In the NWChem calculator, looking at this output directory: " + self.outputDIR)
161
+ self.movecsSCF_restart = self.outputDIR+"/"+".nwchem.tmp.scf.movecs.restart"
162
+ self.movecsDFT_restart = self.outputDIR+"/"+".nwchem.tmp.dft.movecs.restart"
163
+ self.movecsSCF_restart_prev = self.outputDIR+"/"+".nwchem.tmp.scf.movecs.restart.prev"
164
+ self.movecsDFT_restart_prev = self.outputDIR+"/"+".nwchem.tmp.dft.movecs.restart.prev"
165
+
166
+ # The name of the intermediate file that holds the wavefunction
167
+ self.movecs = self.scratchdir +"/"+".nwchem.tmp.scf.movecs"
168
+ self.movecsSCF = self.scratchdir +"/"+".nwchem.tmp.scf.movecs"
169
+ self.movecsDFT = self.scratchdir +"/"+".nwchem.tmp.dft.movecs"
170
+
171
+ if (self.method in ["dft","odft","udft","rodft"]):
172
+ dft["xc"] = self.method
173
+ dft["mult"] = self.multiplicity
174
+ dft["iterations"] = self.maxiter
175
+ dft["convergence"] = dft_convergence
176
+ dft["vectors"] = dict(input=self.movecsDFT,output=self.movecsDFT)
177
+
178
+ # scf["uhf"] = None
179
+
180
+ if (self.referencemethod in ["odft","udft"]): dft["odft"]=None
181
+ if (self.referencemethod in ["rodft"]): dft["rodft"]=None
182
+
183
+ calc = NWChem(label="nwchem",memory=str(self.memory)+' mb',charge=self.charge,
184
+ dft=dft,basis=self.basis_set,basispar=basispar,theory="dft")
185
+
186
+ elif (self.method in ["uhf","hf","scf","rohf","rhf","mp2","ump2"]):
187
+
188
+ scf["nopen"] = self.multiplicity-1
189
+ scf["maxiter"] = self.maxiter
190
+ scf["vectors"] = dict(input=self.movecsSCF,output=self.movecsSCF)
191
+
192
+ if (self.referencemethod in ["uhf","ump2"]): scf["uhf"]=None
193
+ if (self.referencemethod in ["rohf"]): scf["rohf"]=None
194
+
195
+ if ("mp2" in self.method):
196
+ calc = NWChem(label="nwchem",memory=str(self.memory)+' mb',charge=self.charge,
197
+ scf=scf,mp2=mp2,basis=self.basis_set,basispar=basispar,theory="mp2")
198
+
199
+ else:
200
+ calc = NWChem(label="nwchem",memory=str(self.memory)+' mb',charge=self.charge,
201
+ scf=scf,basis=self.basis_set,basispar=basispar,theory="scf")
202
+
203
+ else:
204
+ raise ValueError("Wrong reference wavefunction chosen for NWChem: "+self.referencemethod)
205
+
206
+ self.nwchemcalc = calc
207
+
208
+ # If the user supplied the wavefunction file, use that for the first step
209
+ if (os.path.isfile(self.movecsSCF)):
210
+ print("Reading wavefunction from previous calculation stored in: " + self.movecsSCF + " ... ")
211
+ self.ref_wfn = True
212
+ else:
213
+ self.ref_wfn = None
214
+
215
+ # Set the number of threads used in this session
216
+ self.n_tasks = n_threads
217
+
218
+ # Converts energy from the unit used by the ab initio method to eV.
219
+ self.E_to_eV = E_to_eV
220
+
221
+ # Converts length from the unit used in the ab initio method to Ang.
222
+ self.Ang_to_R = F_to_eV_Ang / E_to_eV
223
+
224
+ # Converts force from the unit used by the ab initio method to eV/Ang.
225
+ self.F_to_eV_Ang = F_to_eV_Ang
226
+
227
+ print("Summary of NWChem ab initio input file")
228
+ print(" Method:", self.method)
229
+ print(" Basis set:", self.basis_set)
230
+ print(" nproc:", self.n_tasks)
231
+
232
+ def calculate(self, atoms=None, *args, **kwargs):
233
+
234
+ super(nwchemcalculator, self).calculate(atoms, *args, **kwargs)
235
+
236
+ f = self.nwchemcalc.get_forces(atoms=atoms)
237
+ e = self.nwchemcalc.results['energy']
238
+ # print(dir(self.nwchemcalc))
239
+ # print(self.nwchemcalc.results)
240
+ # print(dir(self.nwchemcalc.results))
241
+
242
+ # Print the NWChem output to stdout
243
+ with open('nwchem.nwo', 'r') as afile:
244
+ print(afile.read())
245
+
246
+ # Make sure that the gradient was correctly read in
247
+ assert len(atoms) == len(f)
248
+
249
+ # Convert model units to ASE default units (eV and Ang)
250
+ e *= self.E_to_eV
251
+ f *= self.F_to_eV_Ang
252
+
253
+ f = f.reshape(-1, 3)
254
+ Natoms = len(atoms)
255
+ print("")
256
+ print("NWChem flag 1")
257
+ print(Natoms)
258
+ print("Energy: ", e)
259
+ #for anAtom in atoms:
260
+ for i in range(Natoms):
261
+ anAtom = atoms[i]
262
+ print("{0:2s} {1:16.8f} {2:16.8f} {3:16.8f} {4:18.10f} {5:18.10f} {6:18.10f}".format(anAtom.symbol,*anAtom.position, *f[i]))
263
+ print("")
264
+
265
+ self.results = {'energy': e, 'forces': f}
266
+
267
+ # Save the wavefunction every now and then if required
268
+ # if (not (self.save_movecs_interval is None) and self.ref_wfn):
269
+ if (False):
270
+ print("Backing up a restart...")
271
+ self.save_movecs_count += 1
272
+ if (self.save_movecs_count >= self.save_movecs_interval):
273
+ self.save_movecs_count = 0
274
+
275
+ coordsfile_restart = os.path.join(self.outputDIR, ".nwchemex.restart.Q.xyz")
276
+ momentafile_restart = os.path.join(self.outputDIR, ".nwchemex.restart.P.xyz")
277
+ coordsfile_restart_prev = os.path.join(self.outputDIR, ".nwchemex.restart.prev.Q.xyz")
278
+ momentafile_restart_prev = os.path.join(self.outputDIR, ".nwchemex.restart.prev.P.xyz")
279
+
280
+ # Back up the restart (in case there's a job kill when writing the restart file)
281
+ if (os.path.isfile(coordsfile_restart)):
282
+ shutil.copy(coordsfile_restart,coordsfile_restart_prev)
283
+ shutil.copy(momentafile_restart,momentafile_restart_prev)
284
+ if (os.path.isfile(self.movecsSCF_restart)):
285
+ shutil.copy(self.movecsSCF_restart,self.movecsSCF_restart_prev)
286
+ if (os.path.isfile(self.movecsDFT_restart)):
287
+ shutil.copy(self.movecsDFT_restart,self.movecsDFT_restart_prev)
288
+
289
+ if (os.path.isfile(self.movecsSCF)):
290
+ shutil.copy(self.movecsSCF, self.movecsSCF_restart)
291
+ if (os.path.isfile(self.movecsDFT)):
292
+ shutil.copy(self.movecsDFT, self.movecsDFT_restart)
293
+
294
+ with open(coordsfile_restart,"w") as file:
295
+ file.write(str(Natoms)+"\n")
296
+ file.write(str(e)+"\n")
297
+ for i in range(Natoms):
298
+ anAtom = atoms[i]
299
+ file.write("{0:2s} {1:16.8f} {2:16.8f} {3:16.8f}\n".format(anAtom.symbol,*anAtom.position))
300
+
301
+ molmomenta = atoms.get_momenta()
302
+ with open(momentafile_restart,"w") as file:
303
+ file.write(str(Natoms)+"\n")
304
+ file.write(str(e)+"\n")
305
+ for i in range(Natoms):
306
+ anAtom = atoms[i]
307
+ file.write("{0:2s} {1:16.8f} {2:16.8f} {3:16.8f}\n".format(anAtom.symbol,*molmomenta[i]))
308
+
309
+
310
+
311
+ def get_forces(self, atoms=None, force_consistent=False):
312
+ forces = self.get_property('forces', atoms)
313
+ return forces
314
+