-
Notifications
You must be signed in to change notification settings - Fork 4
/
DVR.py
443 lines (372 loc) · 15.7 KB
/
DVR.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
import os
import numpy as np
class DVR:
"""This is a manager class for working with DVRs
It uses files from which it loads the spec data and methods
Currently all defaults are for 1D but the ND extension shouldn't be bad
"""
loaded_DVRs = {} # for storing DVRs loaded from file
dvr_dir = os.path.join(os.path.dirname(__file__), "Classes")
def __init__(self, dvr_file="ColbertMiller1D", **kwargs):
self.params = kwargs # these are the global parameters passed to all methods
if dvr_file is None:
self._dvr = None
else:
self._dvr = self.load_dvr(dvr_file)
@classmethod
def dvr_file(self, dvr):
"""Locates the DVR file for dvr"""
if os.path.exists(dvr):
dvr_file = dvr
else:
dvr_file = os.path.join(self.dvr_dir, dvr+".py")
if not os.path.exists(dvr_file):
raise DVRException("couldn't load DVR "+dvr)
return dvr_file
@classmethod
def _load_env(cls, file, env):
"""Fills in necessary parameters in an env from a module
:param env:
:type env:
:return:
:rtype:
"""
cls.loaded_DVRs[file] = env
for k in ('grid', 'kinetic_energy', 'potential_energy', 'hamiltonian', 'wavefunctions'):
if 'grid' not in env:
raise DVRException("{}.{}: DVR class '{}' didn't export property '{}' (in file {})".format(
cls.__name__,
'load_dvr',
env['class'],
k,
env['file']
))
return env
@classmethod
def load_dvr(self, dvr):
"""Loads a DVR from file into the DVR class"""
dvr_file = self.dvr_file(dvr)
if dvr_file not in self.loaded_DVRs:
# defaults and parameters passed as global
dvr_class = os.path.splitext(os.path.basename(dvr_file))[0]
_load_env = {
'DVR': self,
'class': dvr_class,
'file': dvr_file,
'potential_energy': self._potential_energy,
'hamiltonian': self._hamiltonian,
'wavefunctions': self._wavefunctions
}
import sys
dvr_dir = os.path.dirname(dvr_file)
sys.path.insert(0, os.path.dirname(dvr_dir))
sys.path.insert(0, dvr_dir)
try:
exec("from .Classes.{} import *".format(dvr_class), globals(), _load_env)
except ImportError:
exec("from .Classes.{} import *".format(dvr_class), globals(), _load_env)
finally: # want to preserve error handling but still close the file
sys.path.pop(0)
load = self._load_env(dvr_file, _load_env)
else:
load = self.loaded_DVRs[dvr_file]
return load
def _dvr_prop(self, prop_name):
"""Gets a DVR property"""
if prop_name in self.params:
prop = self.params[prop_name]
elif prop_name in self._dvr:
prop = self._dvr[prop_name]
if callable(prop):
prop = prop(**self.params)
else:
raise DVRException("no property "+prop_name)
return prop
def domain(self):
"""Computes the domain for the DVR"""
return self._dvr_prop('domain')
def divs(self):
"""Computes the divisions for the DVR"""
return self._dvr_prop('divs')
def grid(self):
"""Computes the grid for the DVR"""
return self._dvr_prop('grid')
def kinetic_energy(self):
"""Computes the kinetic_energy for the DVR"""
return self._dvr_prop('kinetic_energy')
def potential_energy(self):
"""Computes the potential_energy for the DVR"""
return self._dvr_prop('potential_energy')
def hamiltonian(self):
"""Computes the hamiltonian for the DVR"""
return self._dvr_prop('hamiltonian')
def wavefunctions(self):
"""Computes the wavefunctions for the DVR"""
return self._dvr_prop('wavefunctions')
def _run(self):
from Psience.Wavefun import Wavefunctions
from .Wavefunctions import DVRWavefunctions
def get_res():
res_class = self.params['results_class'] if 'results_class' in self.params else self.Results
return res_class(parent=self, **self.params)
grid = self.grid()
self.params['grid'] = grid
if self.params['result'] == 'grid':
return get_res()
pe = self.potential_energy()
self.params['potential_energy'] = pe
if self.params['result'] == 'potential_energy':
return get_res()
ke = self.kinetic_energy()
self.params['kinetic_energy'] = ke
if self.params['result'] == 'kinetic_energy':
return get_res()
h = self.hamiltonian()
self.params['hamiltonian'] = h
if self.params['result'] == 'hamiltonian':
return get_res()
wf = self.wavefunctions()
self.params['wavefunctions'] = DVRWavefunctions(*wf, grid=grid)
if self.params['result'] == 'wavefunctions':
return get_res()
return get_res()
def run(self, **runpars):
""" Runs the DVR. Resets state after the run"""
par = self.params.copy()
try:
if 'result' not in self.params:
self.params['result'] = 'wavefunctions'
self.params.update(runpars)
res = self._run()
finally:
self.params = par
return res
@staticmethod
def _potential_energy(**pars):
""" A default ND potential implementation for reuse"""
if 'potential_function' in pars:
# explicit potential function passed; map over coords
pf=pars['potential_function']
if isinstance(pf, str):
# these mostly just exist as a few simple test cases
if pf == 'harmonic_oscillator':
k = pars['k'] if 'k' in pars else 1
re = pars['re'] if 're' in pars else 0
pf = lambda x, k=k, re=re: 1/2*k*(x-re)**2
elif pf == 'morse_oscillator':
de = pars['De'] if 'De' in pars else 10
a = pars['alpha'] if 'alpha' in pars else 1
re = pars['re'] if 're' in pars else 0
pf = lambda x, a=a, de=de, re=re: de*(1-np.exp((-a*(x-re))))**2
else:
raise DVRException("unknown potential "+pf)
grid = pars['grid']
dim = len(grid.shape)
if dim > 1:
import scipy.sparse as sp
from functools import reduce
from operator import mul
npts = reduce(mul, grid.shape[:-1], 1)
grid = np.reshape(grid, (npts, grid.shape[-1]))
pot = sp.diags([pf(grid)], [0])
else:
pot = np.diag(pf(grid))
elif 'potential_values' in pars:
# array of potential values at coords passed
pot = np.diag(pars['potential_values'])
elif 'potential_grid' in pars:
# TODO: extend to include ND, scipy.griddata
import scipy.interpolate as interp
import scipy.sparse as sp
grid = pars['grid']
dim = len(grid.shape)
if dim > 1:
dim -= 1
from functools import reduce
from operator import mul
npts = reduce(mul, grid.shape[:-1], 1)
grid = np.reshape(grid, (npts, grid.shape[-1]))
if dim == 1:
interpolator = lambda g1, g2: interp.interp1d(g1[:, 0], g1[:, 1], kind='cubic')(g2)
else:
def interpolator(g, g2):
# g is an np.ndarray of potential points and values
# g2 is the set of grid points to interpolate them over
shape_dim = len(g.shape)
if shape_dim == 2:
points = g[:, :-1]
vals = g[:, -1]
return interp.griddata(points, vals, g2)
else:
# assuming regular structured grid
mesh = g.transpose(np.roll(np.arange(len(g.shape)), 1))
points = tuple(np.unique(x) for x in mesh[:-1])
vals = mesh[-1]
return interp.interpn(points, vals, g2)
wtf = np.nan_to_num(interpolator(pars['potential_grid'], grid))
pot = sp.diags([wtf], [0])
else:
raise DVRException("couldn't construct potential matrix")
return pot
@staticmethod
def _hamiltonian(**pars):
"""A default hamiltonian implementation for reuse"""
return pars['kinetic_energy']+pars['potential_energy']
@staticmethod
def _wavefunctions(num_wfns = None, **pars):
"""A default wavefunction implementation for reuse"""
res = np.linalg.eigh(pars['hamiltonian'])
if num_wfns is not None:
res = (
res[0][:num_wfns],
res[1][:, :num_wfns]
)
return res
class Results:
"""
A subclass that can wrap all of the DVR run parameters and results into a clean interface for reuse and extension
"""
def __init__(self,
grid=None,
kinetic_energy=None,
potential_energy=None,
hamiltonian=None,
wavefunctions=None,
parent=None,
**opts
):
self.parent = None,
self.grid = grid
self.kinetic_energy = kinetic_energy
self.potential_energy = potential_energy
self.parent = parent
self.wavefunctions = wavefunctions
self.opts = opts
@property
def dimension(self):
dim = len(self.grid.shape)
if dim > 1:
dim -= 1
return dim
def plot_potential(self, plot_class=None, plot_units=None, energy_threshold=None, **opts):
from McUtils.Plots import Plot, Plot3D
import numpy as np
# get the grid for plotting
if self.dimension >= 2:
MEHSH = self.grid
unrolly_polly_OLLY = np.roll(np.arange(len(MEHSH.shape)), 1)
mesh = MEHSH.transpose(unrolly_polly_OLLY)
if plot_class is None:
dim = self.dimension
if dim == 1:
plot_class = Plot
elif dim == 2:
plot_class = Plot3D
else:
raise DVRException("{}.{}: don't know how to plot {} dimensional potential".format(
type(self).__name__,
'plot',
dim
))
if plot_units is 'wavenumbers':
pot = self.potential_energy.diagonal()
pot = (pot - min(pot))*219474.6
else:
pot = self.potential_energy.diagonal()
if energy_threshold:
pot[pot > energy_threshold] = energy_threshold
else:
pot = pot
return plot_class(*mesh, pot.reshape(mesh[0].shape), **opts)
class ResultsInterpreter(DVR.Results):
"""A subclass of results to do some quick analysis..."""
def __init__(self, **results):
super().__init__(**results)
if self.grid.ndim == 3:
MEHSH = self.grid
unrolly_polly_OLLY = np.roll(np.arange(len(MEHSH.shape)), 1)
mesh = MEHSH.transpose(unrolly_polly_OLLY)
self.x = mesh[0].flatten()
self.y = mesh[1].flatten()
poo = self.potential_energy.diagonal()
poo = poo.reshape(mesh[0].shape)
self.potential_energy_vector = poo.flatten()
else:
poo = self.potential_energy.diagonal()
self.potential_energy_vector = poo
self.x = self.grid[:, 0]
self.y = self.grid[:, 1]
def pull_energies(self, **opts):
"""returns vector of ten lowest energies, shifted to the potential's minimum and converted to wavenumbers."""
poo = self.potential_energy_vector
e = self.wavefunctions.energies
e = (e - min(poo))*219474.6
return e
def linear_dipole(self, plot=False, **opts):
"""calculates the linear "dipole" actually delta r (ie, y - y(eq))."""
ref_idx = np.argmin(self.potential_energy_vector)
deltar = self.y - self.y[ref_idx]
if plot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
tcc = ax.tricontourf(self.x, self.y, deltar)
ax.set_title('Delta Roh')
fig.colorbar(tcc)
plt.show()
else:
pass
return deltar
def potential_cuts(self, coordinate=None, num_to_plot=None, plot_units=None, energy_threshold=None, save_vals=False, **opts):
"""creates cuts through the potential, along specified coordinate to either plot or save (as .npy file)
for troubleshooting/checking inter/extrapolation etc.
:param coordinate (str) either x or y, if x then returns the (x,energy) pair for y-values in num_to_plot
:param num_to_plot (tuple) of indices to plot/save
:param save_vals (boolean) set to True to save cuts as .npy files (default False)
:param plot_units (str) currently can only handle "wavenumbers" default is hartrees
:param energy_threshold (int) takes any points above threshold and sets to threshold value for
cleaner plotting"""
import matplotlib.pyplot as plt
if plot_units is 'wavenumbers':
pot = self.potential_energy_vector
pot = (pot - min(pot)) * 219474.6
else:
pot = self.potential_energy.diagonal()
if energy_threshold:
pot[pot > energy_threshold] = energy_threshold
else:
pot = pot
vals = np.column_stack((self.x, self.y, pot))
if coordinate == 'x':
xvals = np.unique(self.x)
slices = [vals[self.x == xv] for xv in xvals]
for x in range(*num_to_plot):
if save_vals:
np.save('xcoord_yval_%.4f.npy' % slices[x][0, 0],
np.column_stack((slices[x][:, 1], slices[x][:, 2])))
plt.plot(slices[x][:, 1], slices[x][:, 2], 'o')
plt.show()
elif coordinate == "y":
yvals = np.unique(self.y)
slyces = [vals[self.y == yv] for yv in yvals]
for y in range(*num_to_plot):
if save_vals:
np.save('ycoord_xval_%.4f.npy' % slyces[y][0, 1],
np.column_stack((slyces[y][:, 0], slyces[y][:, 2])))
plt.plot(slyces[y][:, 0], slyces[y][:, 2], 'o')
plt.show()
else:
print("I do not know that coordinate.")
def wfn_contours(self):
"""Current messy fix for plotting 2D dimensional wavefunctions as contour plots.
wf.plot(plot_class=ContourPlot).show() doesnt work but probably should???"""
import matplotlib.pyplot as plt
for i, wf in enumerate(self.wavefunctions):
wfn = wf.data
fig, ax = plt.subplots()
tcc = ax.tricontourf(self.x, self.y, wfn)
ax.set_title('Wavefunction %s' % str(i))
fig.colorbar(tcc)
plt.show()
class DVRException(Exception):
"""An Exception in a DVR """
pass