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,227 @@
1
+ import numpy as np
2
+
3
+ from ase.calculators.calculator import Calculator
4
+ from ase.units import Ha, Ang, Bohr
5
+
6
+ import psi4
7
+ from psi4.driver.p4util.exceptions import SCFConvergenceError
8
+ from psi4.core import OEProp
9
+ from psi4.core import variable, variables
10
+
11
+ class psi4calculator(Calculator):
12
+
13
+ implemented_properties = ['energy', 'forces']
14
+
15
+ def __init__(
16
+ self,
17
+ input_path,
18
+ n_threads=1,
19
+ E_to_eV=Ha,
20
+ F_to_eV_Ang=Ha/Bohr,
21
+ use_torch=False,
22
+ *args,
23
+ **kwargs
24
+ ):
25
+ """
26
+ ASE calculator for the psi4 ab initio module
27
+
28
+ A calculator takes atomic numbers and atomic positions from an Atoms object and calculates the energy and forces.
29
+
30
+ Note
31
+ ----
32
+ 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.
33
+ Here is how to find them: `ASE units <https://wiki.fysik.dtu.dk/ase/ase/units.html>`_.
34
+
35
+ Parameters
36
+ ----------
37
+ input_path : :obj:`str`
38
+ Path to a psi4 input file
39
+ E_to_eV : float, optional
40
+ Conversion factor from whatever energy unit is used by the model to eV. By default this parameter is set to convert from kcal/mol.
41
+ F_to_eV_Ang : float, optional
42
+ 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)
43
+ use_torch : boolean, optional
44
+ Use PyTorch to calculate predictions
45
+ """
46
+
47
+ super(psi4calculator, self).__init__(*args, **kwargs)
48
+
49
+ # Default values for the psi4 input
50
+ self.maxiter = 1000
51
+ self.d_convergence = 1.0e-8
52
+ self.e_convergence = 1.0e-8
53
+ self.referencemethod = 'uhf'
54
+ self.freeze_core = 0
55
+ self.mp2_type = "df"
56
+ self.qc_module = None
57
+ self.df_ints_io = "None"
58
+ self.dft_spherical_points = 302 # The default for DFT jobs
59
+ self.dft_radial_points = 75 # The default for DFT jobs
60
+ self.psi4method = 'b3lyp/6-31g*' # LevelOfTheory/BasisSet with no spaces
61
+ self.restarts_max = 10 # Max number of allowable SCF restarts
62
+ self.mulliken = 0
63
+ self.charge = 0
64
+ self.multiplicity = 2 # 2s+1
65
+
66
+ self.memory = 1500 # In MB
67
+ self.scratchdir = "/tmp"
68
+
69
+ # Read in the psi4 input
70
+ with open(input_path, 'r') as f:
71
+ for line in f:
72
+ strippedline=" ".join(line.split())
73
+ entries = strippedline.split(" ")
74
+ if (entries[0] == "memory"): self.memory = int(entries[1])
75
+ if (entries[0] == "scratchdir"): self.scratchdir = str(entries[1])
76
+ if (entries[0] == "referencemethod"): self.referencemethod = str(entries[1])
77
+ if (entries[0] == "freeze_core"): self.freeze_core = int(entries[1])
78
+ if (entries[0] == "df_ints_io"): self.df_ints_io = str(entries[1])
79
+ if (entries[0] == "dft_spherical_points"): self.dft_spherical_points = int(entries[1])
80
+ if (entries[0] == "dft_radial_points"): self.dft_radial_points = int(entries[1])
81
+ if (entries[0] == "psi4method"): self.psi4method = str(entries[1])
82
+ if (entries[0] == "mulliken"): self.mulliken = int(entries[1])
83
+ if (entries[0] == "charge"): self.charge = int(entries[1])
84
+ if (entries[0] == "multiplicity"): self.multiplicity = int(entries[1])
85
+ if (entries[0] == "mp2_type"): self.mp2_type = str(entries[1])
86
+ if (entries[0] == "qc_module"): self.qc_module = str(entries[1])
87
+
88
+ if (entries[0] == "maxiter"): self.maxiter = int(entries[1])
89
+ if (entries[0] == "d_convergence"): self.d_convergence = float(entries[1])
90
+ if (entries[0] == "e_convergence"): self.e_convergence = float(entries[1])
91
+
92
+ # Set up the options for the psi4 calculation
93
+ # Check keywords in the documentation: https://psicode.org/psi4manual/master/autodoc_glossary_options_c.html
94
+ psi4.set_memory(str(self.memory)+' MB')
95
+ psi4.set_options({'maxiter': self.maxiter})
96
+ psi4.set_options({'d_convergence': self.d_convergence})
97
+ psi4.set_options({'e_convergence': self.e_convergence})
98
+ psi4.set_options({'reference': self.referencemethod})
99
+ psi4.set_options({'freeze_core': self.freeze_core})
100
+ psi4.set_options({'df_ints_io': self.df_ints_io})
101
+ psi4.set_options({'dft_spherical_points': self.dft_spherical_points})
102
+ # psi4.set_options({'DFT_SPHERICAL_POINTS': self.dft_spherical_points})
103
+ psi4.set_options({'dft_radial_points': self.dft_radial_points})
104
+ # psi4.set_options({'DFT_RADIAL_POINTS': self.dft_radial_points})
105
+ psi4.set_options({'df_ints_io': self.df_ints_io})
106
+ if ("mp2" in self.psi4method):
107
+ self.mp2 = True
108
+ self.basisset = self.psi4method.replace("mp2/","")
109
+ self.psi4method = self.psi4method.replace("mp2","scf")
110
+ psi4.set_options({'mp2_type': self.mp2_type})
111
+ else:
112
+ self.mp2 = False
113
+
114
+ if (not (self.qc_module is None)):
115
+ psi4.set_options({'qc_module': self.qc_module})
116
+
117
+ # Some alternate psi4 SCF convergence options for second-order SCF (SOSCF):
118
+ if (False):
119
+ psi4.set_options({'soscf': True})
120
+ psi4.set_options({'soscf_max_iter': self.maxiter})
121
+ psi4.set_options({'soscf_conv': self.d_convergence})
122
+ psi4.set_options({'soscf_start_convergence': 1.0e-6})
123
+
124
+ self.movecs = self.scratchdir+"/md.wfn"
125
+ self.ref_wfn = None
126
+
127
+ # Set the number of threads used in this psi4 session
128
+ psi4.set_num_threads(n_threads)
129
+
130
+ # Converts energy from the unit used by psi4 to eV.
131
+ self.E_to_eV = E_to_eV
132
+
133
+ # Converts length from the unit used in psi4 to Ang.
134
+ self.Ang_to_R = F_to_eV_Ang / E_to_eV
135
+
136
+ # Converts force from the unit used by psi4 to eV/Ang.
137
+ self.F_to_eV_Ang = F_to_eV_Ang
138
+
139
+ def calculate(self, atoms=None, *args, **kwargs):
140
+
141
+ super(psi4calculator, self).calculate(atoms, *args, **kwargs)
142
+
143
+ # Convert model units to ASE default units
144
+ r = np.array(atoms.get_positions()) * self.Ang_to_R
145
+
146
+ # Load the geometry into the psi4 module
147
+ geometry_string="{0} {1}\n".format(self.charge,self.multiplicity)
148
+ geometry_string+="symmetry c1\n" # Don't enable symmetry or that messes up the wavefunction step-by-step
149
+ geometry_string+="no_reorient\n"
150
+ geometry_string+="no_com\n"
151
+ for anAtom in atoms:
152
+ geometry_string+="{0} {1} {2} {3}\n".format(anAtom.symbol,*anAtom.position)
153
+ #print(geometry_string)
154
+ psi4.geometry(geometry_string)
155
+
156
+ # Try the SCF convergence a few times with different approaches:
157
+ # (1) Try using the reference wavefunction (from the previous step)
158
+ # (2) Try the default superposition of atomic densities (SAD)
159
+ tmp_d_convergence = self.d_convergence
160
+ tmp_e_convergence = self.e_convergence
161
+ # self.ref_wfn = None # Kazuumi SUPER temporary line to test no initial guess wfn
162
+ for i in range(100):
163
+ if (self.ref_wfn is None):
164
+ try:
165
+ e, self.ref_wfn = psi4.energy(self.psi4method,write_orbitals=self.movecs,return_wfn=True)
166
+ psi4.set_options({'d_convergence': self.d_convergence})
167
+ psi4.set_options({'e_convergence': self.e_convergence})
168
+ break
169
+ except SCFConvergenceError:
170
+ if (i>=self.restarts_max):
171
+ raise SCFConvergenceError("SCF convergence failed too many times in a row!")
172
+ print("SCF convergence ({0}) ... will now increase convergence threshold by a factor of 3".format(i))
173
+ tmp_d_convergence = tmp_d_convergence * 3
174
+ tmp_e_convergence = tmp_e_convergence * 3
175
+ psi4.set_options({'d_convergence': tmp_d_convergence})
176
+ psi4.set_options({'e_convergence': tmp_e_convergence})
177
+ else:
178
+ try:
179
+ e, self.ref_wfn = psi4.energy(self.psi4method,restart_file=self.movecs,write_orbitals=self.movecs,return_wfn=True)
180
+ break
181
+ except SCFConvergenceError:
182
+ print("SCF convergence (0) ... will now use a SAD guess")
183
+ self.ref_wfn = None
184
+
185
+ # After converging the wavefunction, get the energy gradient
186
+ # psi4.set_options({'basis': 'cc-pVDZ', 'mp2_type': 'conv'}); f = psi4.gradient('mp2')
187
+ # f = psi4.gradient(self.psi4method)
188
+ if (self.mp2):
189
+ psi4.set_options({'basis': self.basisset, 'mp2_type': self.mp2_type, 'freeze_core': self.freeze_core})
190
+ f, mp2_wfn = psi4.gradient("mp2",ref_wfn=self.ref_wfn,return_wfn=True)
191
+ try:
192
+ e = mp2_wfn.get_variable("CURRENT ENERGY")
193
+ except:
194
+ e = mp2_wfn.scalar_variable("CURRENT ENERGY")
195
+ else:
196
+ f = psi4.gradient(self.psi4method,ref_wfn=self.ref_wfn)
197
+ f = f.to_array()
198
+
199
+ # If there are 'extra' things, do them here
200
+ # Check variables in the documentation: https://psicode.org/psi4manual/master/glossary_psivariables.html
201
+ if (self.mulliken > 0):
202
+ self.oeprop = OEProp(self.ref_wfn)
203
+ self.oeprop.add("MULLIKEN_CHARGES")
204
+ self.oeprop.compute()
205
+
206
+ # Convert model units to ASE default units (eV and Ang)
207
+ e *= self.E_to_eV
208
+ f *= -self.F_to_eV_Ang
209
+
210
+ f = f.reshape(-1, 3)
211
+ Natoms = len(atoms)
212
+ print("")
213
+ print("psi4 flag 1")
214
+ print(Natoms)
215
+ print("Energy: ", e)
216
+ #for anAtom in atoms:
217
+ for i in range(Natoms):
218
+ anAtom = atoms[i]
219
+ 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]))
220
+ print("")
221
+
222
+ self.results = {'energy': e, 'forces': f}
223
+
224
+ def get_forces(self, atoms=None, force_consistent=False):
225
+ forces = self.get_property('forces', atoms)
226
+ return forces
227
+
@@ -0,0 +1,213 @@
1
+ import numpy as np
2
+
3
+ from ase.calculators.calculator import Calculator
4
+ from ase.units import Ha, Ang, Bohr
5
+
6
+ # For QCEngine:
7
+ import qcengine as qcng
8
+ import qcelemental as qcel
9
+
10
+ class qcengineGAMESScalculator(Calculator):
11
+
12
+ implemented_properties = ['energy', 'forces']
13
+
14
+ def __init__(
15
+ self,
16
+ input_path,
17
+ n_threads=1,
18
+ E_to_eV=Ha,
19
+ F_to_eV_Ang=Ha/Bohr,
20
+ use_torch=False,
21
+ *args,
22
+ **kwargs
23
+ ):
24
+ """
25
+ ASE calculator for the QCEngine/GAMESS ab initio module
26
+
27
+ A calculator takes atomic numbers and atomic positions from an Atoms object and calculates the energy and forces.
28
+
29
+ Note
30
+ ----
31
+ 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.
32
+ Here is how to find them: `ASE units <https://wiki.fysik.dtu.dk/ase/ase/units.html>`_.
33
+
34
+ Parameters
35
+ ----------
36
+ input_path : :obj:`str`
37
+ Path to a QCEngine/GAMESS input file
38
+ E_to_eV : float, optional
39
+ Conversion factor from whatever energy unit is used by the model to eV. By default this parameter is set to convert from kcal/mol.
40
+ F_to_eV_Ang : float, optional
41
+ 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)
42
+ use_torch : boolean, optional
43
+ Use PyTorch to calculate predictions
44
+ """
45
+
46
+ super(qcengineGAMESScalculator, self).__init__(*args, **kwargs)
47
+
48
+ # Default values for the input
49
+ self.maxiter = 10000
50
+ self.d_convergence = 1.0e-7
51
+ self.e_convergence = 1.0e-8
52
+ self.referencemethod = 'uhf'
53
+ self.freeze_core = 0
54
+ self.df_ints_io = "None"
55
+ self.method = 'b3lyp' # LevelOfTheory
56
+ self.basis_set = '6-31g*' # BasisSet
57
+ self.mulliken = 0
58
+ self.charge = 0
59
+ self.multiplicity = 2 # 2s+1
60
+
61
+ self.memory = 1500 # In MB
62
+ self.scratchdir = "/tmp"
63
+
64
+ # Read in the input
65
+ with open(input_path, 'r') as f:
66
+ for line in f:
67
+ strippedline=" ".join(line.split())
68
+ entries = strippedline.split(" ")
69
+ if (entries[0] == "memory"): self.memory = int(entries[1])
70
+ if (entries[0] == "scratchdir"): self.scratchdir = str(entries[1])
71
+ if (entries[0] == "referencemethod"): self.referencemethod = str(entries[1])
72
+ if (entries[0] == "freeze_core"): self.freeze_core = int(entries[1])
73
+ if (entries[0] == "df_ints_io"): self.df_ints_io = str(entries[1])
74
+ if (entries[0] == "method"): self.method = str(entries[1])
75
+ if (entries[0] == "basis_set"): self.basis_set = str(entries[1])
76
+ if (entries[0] == "mulliken"): self.mulliken = int(entries[1])
77
+ if (entries[0] == "charge"): self.charge = int(entries[1])
78
+ if (entries[0] == "multiplicity"): self.multiplicity = int(entries[1])
79
+
80
+ # By default, we start off with no initial MO guess
81
+ self.ref_wfn = None
82
+ self.Norb = None
83
+
84
+ # Prepare a minimally descriptive "model" for QCEngine/GAMESS
85
+ # GAMESS basis set documentation: https://myweb.liu.edu/~nmatsuna/gamess/input/BASIS.html
86
+ # QCEngine/GAMESS methods documentation: https://github.com/MolSSI/QCEngine/blob/f5f6da3751373fa9b57ea484cbf71416ba679743/qcengine/programs/gamess/germinate.py
87
+ self.model = {"method":self.method, "basis":self.basis_set}
88
+
89
+ # Prepare the environment and keywords for QCEngine/GAMESS
90
+ self.keywords = {
91
+ "contrl__scftyp" : self.referencemethod,
92
+ "contrl__maxit" : 200, # For some reason, 200 iterations is the maximum
93
+ "contrl__coord" : "unique", # Turns out this does nothing in QCEngine
94
+ "scf__diis" : ".true.",
95
+ "scf__ethrsh" : 1.0, # DIIS error to start DIIS (deafult = 0.5 hartree)
96
+ "scf__conv" : self.d_convergence,
97
+ }
98
+
99
+ self.MPIconfig = {
100
+ # "use_mpiexec" : True,
101
+ # "mpiexec_command": mpiexec_command,
102
+ "scratch_directory":".",
103
+ "nnodes": 1,
104
+ "ncores": n_threads,
105
+ # "cores_per_rank": 2,
106
+ }
107
+
108
+ # Set the number of threads used in this session
109
+ self.n_tasks = n_threads
110
+
111
+ # Converts energy from the unit used by the ab initio method to eV.
112
+ self.E_to_eV = E_to_eV
113
+
114
+ # Converts length from the unit used in the ab initio method to Ang.
115
+ self.Ang_to_R = F_to_eV_Ang / E_to_eV
116
+
117
+ # Converts force from the unit used by the abinitio method to eV/Ang.
118
+ self.F_to_eV_Ang = F_to_eV_Ang
119
+
120
+ print("Summary of QCEnginge ab initio input file (for GAMESS)")
121
+ print(" Model:", self.model)
122
+ print(" Keywords:", self.keywords)
123
+ print(" nproc:", self.n_tasks)
124
+
125
+ def calculate(self, atoms=None, *args, **kwargs):
126
+
127
+ super(qcengineGAMESScalculator, self).calculate(atoms, *args, **kwargs)
128
+
129
+ # Convert model units to ASE default units
130
+ # r = np.array(atoms.get_positions()) * self.Ang_to_R
131
+
132
+ out = ""
133
+ for anAtom in atoms:
134
+ out += anAtom.symbol + " " + str(anAtom.position[0]) + " " + str(anAtom.position[1]) + " " + str(anAtom.position[2]) + "\n"
135
+
136
+ # Fixing CoM and orientation and turning off symmetry to prevent molecular translation
137
+ mol = qcel.models.Molecule.from_data(out, fix_com=True, fix_orientation=True, fix_symmetry="C1") # Doesn't seem to work?
138
+ # mol = qcel.models.Molecule.from_data(out, fix_com=True, fix_symmetry="C1")
139
+
140
+ # Try the SCF convergence a few times with different approaches:
141
+ # (1) Try using the reference wavefunction (from the previous step)
142
+ # (2) Try the default superposition of atomic densities (SAD)
143
+ # tmp_d_convergence = self.d_convergence
144
+ # tmp_e_convergence = self.e_convergence
145
+ # for i in range(100):
146
+ # if (self.ref_wfn is None):
147
+ # try:
148
+ # e, self.ref_wfn = psi4.energy(self.psi4method,write_orbitals=self.movecs,return_wfn=True)
149
+ # psi4.set_options({'d_convergence': self.d_convergence})
150
+ # psi4.set_options({'e_convergence': self.e_convergence})
151
+ # break
152
+ # except SCFConvergenceError:
153
+ # if (i==10):
154
+ # raise SCFConvergenceError("SCF convergence failed too many times in a row!")
155
+ # print("SCF convergence ({0}) ... will now increase convergence threshold by a factor of 3".format(i))
156
+ # tmp_d_convergence = tmp_d_convergence * 3
157
+ # tmp_e_convergence = tmp_e_convergence * 3
158
+ # psi4.set_options({'d_convergence': tmp_d_convergence})
159
+ # psi4.set_options({'e_convergence': tmp_e_convergence})
160
+ # else:
161
+ # try:
162
+ # e, self.ref_wfn = psi4.energy(self.psi4method,restart_file=self.movecs,write_orbitals=self.movecs,return_wfn=True)
163
+ # break
164
+ # except SCFConvergenceError:
165
+ # print("SCF convergence (0) ... will now use a SAD guess")
166
+ # self.ref_wfn = None
167
+
168
+ inp = qcel.models.AtomicInput(molecule=mol, driver="gradient", model=self.model, keywords=self.keywords)
169
+ if (self.ref_wfn is not None):
170
+ inp.extras["VECguess"] = self.ref_wfn
171
+ inp.extras["VECnorb"] = self.Norb
172
+
173
+ f_results = qcng.compute(inp, 'gamess', task_config=self.MPIconfig)
174
+ self.ref_wfn = f_results.extras["VEC"]
175
+ self.Norb = f_results.extras["VECnorb"]
176
+
177
+ e = float(f_results.extras["qcvars"]["CURRENT ENERGY"])
178
+ f = f_results.return_result
179
+
180
+ # f = -np.array(f)
181
+ f = np.array(f)
182
+
183
+ # Make sure that the gradient was correctly read in
184
+ assert len(atoms) == len(f)
185
+
186
+ # If there are 'extra' things, do them here (e.g., Mulliken analysis)
187
+ # if (self.mulliken > 0):
188
+ # self.oeprop = OEProp(self.ref_wfn)
189
+ # self.oeprop.add("MULLIKEN_CHARGES")
190
+ # self.oeprop.compute()
191
+
192
+ # Convert model units to ASE default units (eV and Ang)
193
+ e *= self.E_to_eV
194
+ f *= -self.F_to_eV_Ang
195
+
196
+ f = f.reshape(-1, 3)
197
+ Natoms = len(atoms)
198
+ print("")
199
+ print("QCEngine flag 1")
200
+ print(Natoms)
201
+ print("Energy: ", e)
202
+ #for anAtom in atoms:
203
+ for i in range(Natoms):
204
+ anAtom = atoms[i]
205
+ 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]))
206
+ print("")
207
+
208
+ self.results = {'energy': e, 'forces': f}
209
+
210
+ def get_forces(self, atoms=None, force_consistent=False):
211
+ forces = self.get_property('forces', atoms)
212
+ return forces
213
+