xrs_calctools.py 128 KB
Newer Older
1
2
3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
christoph's avatar
christoph committed
4
#!/usr/bin/python
5
# Filename: xrs_calctools.py
christoph's avatar
christoph committed
6

7
from . import xrs_utilities
christoph's avatar
christoph committed
8
import os
9
10
import warnings
from copy import deepcopy
christoph's avatar
christoph committed
11
12
13
14
15
16
17

import numpy as np
import array as arr

from itertools import groupby
from scipy.integrate import trapz
from scipy.interpolate import interp1d
18
from scipy import constants
christoph's avatar
christoph committed
19

alex's avatar
alex committed
20
21
22
23
24
import sys

if(sys.argv[0][-12:]!="sphinx-build"):  ## otherwise the documentation cannot build : wrong docstrings imported from pylab
    from pylab import *

christoph's avatar
christoph committed
25
26
27
from scipy import signal
from scipy.ndimage import measurements
import matplotlib.pyplot as plt
28
29
from six.moves import range
from six.moves import zip
christoph's avatar
christoph committed
30
31
32

__metaclass__ = type # new style classes

33
34
A2AU_factor = constants.physical_constants['atomic unit of length'][0]*10**10

christoph's avatar
christoph committed
35
def gauss1(x,x0,fwhm):
36
37
38
39
40
41
42
    """
    returns a gaussian with peak value normalized to unity
    a[0] = peak position
    a[1] = Full Width at Half Maximum
    """
    y = np.exp(-np.log(2.0)*((x-x0)/fwhm*2.0)**2.0)
    return y
christoph's avatar
christoph committed
43
44
45
46
47
48
49
50

def gauss(x,x0,fwhm):
    # area-normalized gaussian
    sigma = fwhm/(2*np.sqrt(2*np.log(2)));
    y = np.exp(-(x-x0)**2/2/sigma**2)/sigma/np.sqrt(2*np.pi)
    return y

def gauss_areanorm(x,x0,fwhm):
51
52
53
54
55
56
    """
    area-normalized gaussian
    """
    sigma = fwhm/(2.0*np.sqrt(2.0*np.log(2.0)))
    y = np.exp(-(x-x0)**2.0/2.0/sigma**2)/sigma/np.sqrt(2.0*np.pi)
    return y
christoph's avatar
christoph committed
57
58

def convg(x,y,fwhm):
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    """
    Convolution with Gaussian    
    """
    dx = np.min(np.absolute(np.diff(x)))
    x2 = np.arange(np.min(x)-1.5*fwhm, np.max(x)+1.5*fwhm, dx)
    xg = np.arange(-np.floor(2.0*fwhm/dx)*dx, np.floor(2.0*fwhm/dx)*dx, dx)
    yg = gauss(xg,[0,fwhm])
    yg = yg/np.sum(yg)
    y2 = spline2(x,y,x2)
    c  = np.convolve(y2,yg, mode='full')
    n  = int( np.floor(np.max(np.shape(xg))/2))
    c  = c[n:len(c)-n+1] # not sure about the +- 1 here
    f  = interpolate.interp1d(x2,c)
    return f(x)
christoph's avatar
christoph committed
73
74

def spline2(x,y,x2):
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    """
    Extrapolates the smaller and larger valuea as a constant
    """
    xmin = np.min(x)
    xmax = np.max(x)
    imin = x == xmin
    imax = x == xmax
    f  = interpolate.interp1d(x,y, bounds_error=False, fill_value=0.0)
    y2 = f(x2)
    i     = np.where(x2<xmin)
    y2[i] = y[imin]
    i     = np.where(x2>xmax)
    y2[i] = y[imax]
    return y2
christoph's avatar
christoph committed
89
90

def readxas(filename):
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
    """
    function output = readxas(filename)%[e,p,s,px,py,pz] = readxas(filename)

    % READSTF   Load StoBe fort.11 (XAS output) data
    %
    %   [E,P,S,PX,PY,PZ] = READXAS(FILENAME)
    %
    %      E        energy transfer [eV]
    %      P        dipole transition intensity
    %      S        r^2 transition intensity 
    %      PX       dipole transition intensity along x
    %      PY       dipole transition intensity along y
    %      PZ       dipole transition intensity along z
    %
    %                   as line diagrams.
    %
    %                             T Pylkkanen @ 2011-10-17 
    """
    # Open file
    f = open(filename,'r')
    lines = f.readlines()
    f.close()
    data = []
    for line in lines[1:]:
        data.append([float(x) for x in line.replace('D', 'e').strip().split()])

    data      = np.array(data)
    data[:,0] = data[:,0]*27.211384565719481 # convert from a.u. to eV
    

    data[:,3] = 2.0/3.0*data[:,3]**2.0*e/27.211384565719481 # osc(x)
    data[:,4] = 2.0/3.0*data[:,4]**2.0*e/27.211384565719481 # osc(y)
    data[:,5] = 2.0/3.0*data[:,5]**2.0*e/27.211384565719481 # osc(z)

    return data
christoph's avatar
christoph committed
126
127

def broaden_diagram(e,s,params=[1.0, 1.0, 537.5, 540.0],npoints=1000):
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
    """
    function [e2,s2] = broaden_diagram2(e,s,params,npoints)

    % BROADEN_DIAGRAM2   Broaden a StoBe line diagram
    %
    %  [ENE2,SQW2] = BROADEN_DIAGRAM2(ENE,SQW,PARAMS,NPOINTS)
    %
    %   gives the broadened spectrum SQW2(ENE2) of the line-spectrum
    %   SWQ(ENE). Each line is substituted with a Gaussian peak,
    %   the FWHM of which is determined by PARAMS. ENE2 is a linear
    %   scale of length NPOINTS (default 1000).
    %
    %    PARAMS = [f_min f_max emin max]
    %
    %     For ENE <= e_min, FWHM = f_min.
    %     For ENE >= e_max, FWHM = f_min.
    %     FWHM increases linearly from [f_min f_max] between [e_min e_max].
    %
    %                               T Pylkkanen @ 2008-04-18 [17:37]
    """
    f_min = params[0]
    f_max = params[1]
    e_min = params[2]
    e_max = params[3]

    e2   = np.linspace(np.min(e)-10.0,np.max(e)+10.0,npoints);
    s2   = np.zeros_like(e2) 
    fwhm = np.zeros_like(e)

    # FWHM: Constant  -- Linear -- Constant
    A    = (f_max-f_min)/(e_max-e_min)
    B    = f_min - A*e_min
    fwhm = A*e + B
    inds = e <= e_min
    fwhm[inds] = f_min
    inds = e >= e_max    
    fwhm[inds] = f_max

    for i in range(len(s)):
        s2 += s[i]*gauss(e2,e[i],fwhm[i])

    return e2, s2
christoph's avatar
christoph committed
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

def broaden_linear(spec,params=[0.8, 8, 537.5, 550],npoints=1000):
    evals = spec[:,0]
    sticks= spec[:,1]
    f_min = params[0]
    f_max = params[1]
    e_min = params[2]
    e_max = params[3]
    e2    = np.linspace(np.min(evals)-10.0,np.max(evals)+10.0,npoints)
    s2    = np.zeros(len(e2))
    fwhm  = np.zeros(len(evals))
    # FWHM: Constant  -- Linear -- Constant
    A    = (f_max-f_min)/(e_max-e_min)
    B    = f_min - A*e_min
    fwhm = A*evals + B
    fwhm[evals <= e_min] = f_min
    fwhm[evals >= e_max] = f_max
    for n in range(len(sticks)):
        s2 = s2 + sticks[n]*gauss1(e2,evals[n],fwhm[n])
    spectrum = np.zeros((len(e2),2))
    spectrum[:,0] = e2
    spectrum[:,1] = s2
    return spectrum

def load_stobe_specs(prefix,postfix,fromnumber,tonumber,step,stepformat=2):
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    """
    load a bunch of StoBe calculations, which filenames are made up of the prefix, postfix, and the counter in the between the prefix and postfix runs from 'fromnumber' to 'tonumber' in steps of 'step' (number of digits is 'stepformat')
    """
    numbers = np.linspace(fromnumber,tonumber,(tonumber-fromnumber + step)//step)
    filenames = []
    precision = '%0'+str(stepformat)+'d'
    for number in numbers:
        thenumber = precision % number
        thefilename = prefix+thenumber+postfix
        filenames.append(thefilename)
    specs = []
    for filename in filenames:
        try:
            specs.append(readxas(filename))
        except:
            print( 'found no file: ' + filename)
    return specs
christoph's avatar
christoph committed
212
213
214
215
216
217

def load_erkale_spec(filename):
    spec = np.loadtxt(filename)
    return spec

def load_erkale_specs(prefix,postfix,fromnumber,tonumber,step,stepformat=2):
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    numbers = np.linspace(fromnumber,tonumber,(tonumber-fromnumber + step)//step)
    filenames = []
    precision = '%0'+str(stepformat)+'d'
    for number in numbers:
        thenumber = precision % number
        thefilename = prefix+thenumber+postfix
        filenames.append(thefilename)
    specs = []
    for filename in filenames:
        try:
            specs.append(load_erkale_spec(filename))
        except:
            print( 'found no file: ' + filename)
    return specs
christoph's avatar
christoph committed
232
233
234
235
236
237
238
239
240
241
242
243
244

def cut_spec(spec,emin=None,emax=None):
    if not emin:
        emin = spec[0,0]
    if not emax:
        emax = spec[-1,0]
    spec = spec[spec[:,0]>emin]
    spec = spec[spec[:,0]<emax]
    return spec



def readxas(filename):
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
    """
    function output = readxas(filename)%[e,p,s,px,py,pz] = readxas(filename)

    % READSTF   Load StoBe fort.11 (XAS output) data
    %
    %   [E,P,S,PX,PY,PZ] = READXAS(FILENAME)
    %
    %      E        energy transfer [eV]
    %      P        dipole transition intensity
    %      S        r^2 transition intensity 
    %      PX       dipole transition intensity along x
    %      PY       dipole transition intensity along y
    %      PZ       dipole transition intensity along z
    %
    %                   as line diagrams.
    %
    %                             T Pylkkanen @ 2011-10-17 
    """
    # Open file
    f = open(filename,'r')
    lines = f.readlines()
    f.close()
    data = []
    for line in lines[1:]:
        data.append([float(x) for x in line.replace('D', 'e').strip().split()])

    data      = np.array(data)
    data[:,0] = data[:,0]*27.211384565719481 # convert from a.u. to eV
    

    data[:,3] = 2.0/3.0*data[:,3]**2.0*e/27.211384565719481 # osc(x)
    data[:,4] = 2.0/3.0*data[:,4]**2.0*e/27.211384565719481 # osc(y)
    data[:,5] = 2.0/3.0*data[:,5]**2.0*e/27.211384565719481 # osc(z)

    return data
christoph's avatar
christoph committed
280
281

def broaden_diagram(e,s,params=[1.0, 1.0, 537.5, 540.0],npoints=1000):
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
    """
    function [e2,s2] = broaden_diagram2(e,s,params,npoints)

    % BROADEN_DIAGRAM2   Broaden a StoBe line diagram
    %
    %  [ENE2,SQW2] = BROADEN_DIAGRAM2(ENE,SQW,PARAMS,NPOINTS)
    %
    %   gives the broadened spectrum SQW2(ENE2) of the line-spectrum
    %   SWQ(ENE). Each line is substituted with a Gaussian peak,
    %   the FWHM of which is determined by PARAMS. ENE2 is a linear
    %   scale of length NPOINTS (default 1000).
    %
    %    PARAMS = [f_min f_max emin max]
    %
    %     For ENE <= e_min, FWHM = f_min.
    %     For ENE >= e_max, FWHM = f_min.
    %     FWHM increases linearly from [f_min f_max] between [e_min e_max].
    %
    %                               T Pylkkanen @ 2008-04-18 [17:37]
    """
    f_min = params[0]
    f_max = params[1]
    e_min = params[2]
    e_max = params[3]

    e2   = np.linspace(np.min(e)-10.0,np.max(e)+10.0,npoints);
    s2   = np.zeros_like(e2) 
    fwhm = np.zeros_like(e)

    # FWHM: Constant  -- Linear -- Constant
    A    = (f_max-f_min)/(e_max-e_min)
    B    = f_min - A*e_min
    fwhm = A*e + B
    inds = e <= e_min
    fwhm[inds] = f_min
    inds = e >= e_max    
    fwhm[inds] = f_max

    for i in range(len(s)):
        s2 += s[i]*gauss1(e2,e[i],fwhm[i])

    return e2, s2
christoph's avatar
christoph committed
324
325

def broaden_linear(spec,params=[0.8, 8, 537.5, 550],npoints=1000):
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
    """
    broadens a spectrum with a Gaussian of width params[0] below 
    params[2] and width params[1] above params[3], width increases 
    linear in between.
    returns two-column numpy array of length npoints with energy and the broadened spectrum
    """
    evals = spec[:,0]
    sticks= spec[:,1]
    f_min = params[0]
    f_max = params[1]
    e_min = params[2]
    e_max = params[3]
    e2    = np.linspace(np.min(evals)-10.0,np.max(evals)+10.0,npoints)
    s2    = np.zeros(len(e2))
    fwhm  = np.zeros(len(evals))
    # FWHM: Constant  -- Linear -- Constant
    A    = (f_max-f_min)/(e_max-e_min)
    B    = f_min - A*e_min
    fwhm = A*evals + B
    fwhm[evals <= e_min] = f_min
    fwhm[evals >= e_max] = f_max
    for n in range(len(sticks)):
        s2 = s2 + sticks[n]*gauss(e2,evals[n],fwhm[n])
    spectrum = np.zeros((len(e2),2))
    spectrum[:,0] = e2
    spectrum[:,1] = s2
    return spectrum
christoph's avatar
christoph committed
353
354

def load_stobe_specs(prefix,postfix,fromnumber,tonumber,step,stepformat=2):
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    """
    load a bunch of StoBe calculations, which filenames are made up of the 
    prefix, postfix, and the counter in the between the prefix and postfix 
    runs from 'fromnumber' to 'tonumber' in steps of 'step' (number of digits 
    is 'stepformat')
    """
    numbers = np.linspace(fromnumber,tonumber,(tonumber-fromnumber + step)//step)
    filenames = []
    precision = '%0'+str(stepformat)+'d'
    for number in numbers:
        thenumber = precision % number
        thefilename = prefix+thenumber+postfix
        filenames.append(thefilename)
    specs = []
    for filename in filenames:
        try:
            specs.append(readxas(filename))
        except:
            print( 'found no file: ' + filename)
    return specs
christoph's avatar
christoph committed
375
376

def load_erkale_spec(filename):
377
378
379
380
381
    """
    returns an erkale spectrum
    """
    spec = np.loadtxt(filename)
    return spec
christoph's avatar
christoph committed
382
383

def load_erkale_specs(prefix,postfix,fromnumber,tonumber,step,stepformat=2):
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
    """
    returns a list of erkale spectra
    """
    numbers = np.linspace(fromnumber,tonumber,(tonumber-fromnumber + step)//step)
    filenames = []
    precision = '%0'+str(stepformat)+'d'
    for number in numbers:
        thenumber = precision % number
        thefilename = prefix+thenumber+postfix
        filenames.append(thefilename)
    specs = []
    for filename in filenames:
        try:
            specs.append(load_erkale_spec(filename))
        except:
            print( 'found no file: ' + filename)
    return specs
christoph's avatar
christoph committed
401
402

def cut_spec(spec,emin=None,emax=None):
403
404
405
406
407
408
409
410
411
412
    """
    deletes lines of matrix with first column smaller than emin and larger than emax 
    """
    if not emin:
        emin = spec[0,0]
    if not emax:
        emax = spec[-1,0]
    spec = spec[spec[:,0]>emin]
    spec = spec[spec[:,0]<emax]
    return spec
christoph's avatar
christoph committed
413
414
415


class stobe:
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
    """
    class to analyze StoBe results
    """
    def __init__(self,prefix,postfix,fromnumber,tonumber,step,stepformat=2):
        self.energy   = [] # array of final energy scale for all snapshots of this run
        self.signal   = [] # array of averaged and smoothed results     
        self.rawspecs = load_stobe_specs(prefix,postfix,fromnumber,tonumber,step,stepformat) # list of all raw stick spectra:rawspecs[n][energy,sticks]
        self.broadened= [] # list of broadened stick spectra 

    def cut_rawspecs(self,emin=None,emax=None):
        cutspecs = []
        for spec in self.rawspecs:
            cutspecs.append(cut_spec(spec,emin,emax))
        self.rawspecs = cutspecs

    def broaden_lin(self,params=[0.8, 8, 537.5, 550],npoints=1000):
        for spec in self.rawspecs:
            self.broadened.append(broaden_linear(spec,params,npoints))

    def sum_specs(self):
        self.energy   = self.broadened[0][:,0] # first spectrum defines energy scale
        self.signal   = np.zeros(np.shape(self.energy))
        for spec in self.broadened:
            f = interp1d(spec[:,0], spec[:,1],bounds_error=False, kind='cubic', fill_value=0.0)
            self.signal += f(self.energy)

    def norm_area(self,emin,emax):
        inds = np.where(np.logical_and(self.energy>=emin,self.energy<=emax))
        norm = np.trapz(self.signal[inds],self.energy[inds])
        self.signal = self.signal/norm
            
christoph's avatar
christoph committed
447
448

class erkale:
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
    """
    class to analyze ERKALE XRS results.
    """
    def __init__(self,prefix,postfix,fromnumber,tonumber,step,stepformat=2):
        self.energy   = [] # array of final energy scale for all snapshots of this run
        self.sqw      = [] # array of averaged and smoothed results        
        self.rawspecs = load_erkale_specs(prefix,postfix,fromnumber,tonumber,step,stepformat) # list of all raw stick spectra
        self.broadened= []
        self.norm     = [] # results of normalization

    def cut_rawspecs(self,emin=None,emax=None):
        cutspecs = []
        for spec in self.rawspecs:
            cutspecs.append(cut_spec(spec,emin,emax))
        self.rawspecs = cutspecs

    def cut_broadspecs(self,emin=None,emax=None):
        cutspecs = []
        for spec in self.broadened:
            cutspecs.append(cut_spec(spec,emin,emax))
        self.broadened = cutspecs

    def broaden_lin(self,params=[0.8, 8, 537.5, 550],npoints=1000):
        for spec in self.rawspecs:
            self.broadened.append(broaden_linear(spec,params,npoints))

    def sum_specs(self):
        self.energy   = self.broadened[0][:,0] # first spectrum defines energy scale
        self.sqw      = np.zeros(np.shape(self.energy))
        for spec in self.broadened:
            f = interp1d(spec[:,0], spec[:,1],bounds_error=False, kind='cubic', fill_value=0.0)
            self.sqw += f(self.energy)

    def norm_area(self,emin=None,emax=None):
        if not emin:
            emin = self.energy[0]
        if not emax:
            emax = self.energy[-1]

        inds = np.where(np.logical_and(self.energy>=emin,self.energy<=emax))[0]
        self.sqw = self.sqw/np.trapz(self.sqw[inds],self.energy[inds])
christoph's avatar
christoph committed
490
    
491
492
    def norm_max(self):
        pass
christoph's avatar
christoph committed
493

494
495
496
    def plot_spec(self):
        plt.plot(self.energy,self.sqw)
        plt.show()
christoph's avatar
christoph committed
497
498
499
500

################################### 
# reading function for cowan's code output

501
class xyzAtom:
502
503
504
505
    """ **xyzAtom**

    Class to hold information about and manipulate a single atom in xyz-style format.

alex's avatar
alex committed
506
507
508
509
    Args. :
          * name (str): Atomic symbol.
          * coordinates (np.array): Array of xyz-coordinates.
          * number (int): Integer, e.g. number of atom in a cluster.
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

    """
    def __init__(self,name,coordinates,number):
        self.name        = name
        self.coordinates = np.array(coordinates)
        self.x_coord     = self.coordinates[0]
        self.y_coord     = self.coordinates[1]
        self.z_coord     = self.coordinates[2]
        self.Z           = xrs_utilities.element(name)
        self.number      = number
        self.spectrum    = np.array([])

    def getNorm(self):
        return np.linalg.norm(self.coordinates)

    def getCoordinates(self):
        return self.coordinates

    def translateSelf(self, vector):
        try:
            self.coordinates += vector
            self.x_coord     += vector[0]
            self.y_coord     += vector[1]
            self.z_coord     += vector[2]
        except ValueError:
            print('Vector must be 3D np.array!') 

    def translateSelf_arb(self, lattice, lattice_inv, vector):
        rel_coords = np.dot(lattice_inv, np.array(self.coordinates))
        rel_coords += vector

        self.coordinates = np.dot(lattice,rel_coords)
        self.x_coord     = self.coordinates[0]
        self.y_coord     = self.coordinates[1]
        self.z_coord     = self.coordinates[2]

    def load_spectrum(self, file_name):
        self.spectrum = np.loadtxt(file_name)

christoph's avatar
christoph committed
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
    def load_spectrum_all_pol(self, prefix, num_pols, printing=False ):
        data = {}
        # load all polarization directions
        for ii in range(num_pols):
            fname = prefix+'%02d'%(ii+1) 
        if printing:
            print('loading spectrum from file: %s'%fname)
        data[fname] = np.loadtxt(fname)
        # average
        ene = data[ list(data.keys())[0] ][:,0]
        dat = np.zeros_like( ene )
        for key in data:
            dat += np.interp( ene, data[key][:,0], data[key][:,1] )
        dat /= num_pols
        self.spectrum = np.array([ene, dat]).T

565
566
567
568
    def normalize_spectrum(self, normrange):
        inds = np.where(np.logical_and(self.spectrum[:,0]>=normrange[0], self.spectrum[:,0]<=normrange[1]))[0]
        norm = np.trapz(self.spectrum[inds,1], self.spectrum[inds,0])
        self.spectrum[:,1] /= norm
569

570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
    def getDist( self, atom ):
        return np.linalg.norm(self.coordinates - atom.coordinates)

    def getDistPBCarb( self, atom, lattice, lattice_inv ):
        return getDistancePBC_arb( self, atom, lattice, lattice_inv )

    def getAnglePBCarb( self, atom2, atom3, lattice, lattice_inv, degrees=True):
        """ **get_angle**
        Return angle between the three given atoms (as seen from atom2).
        """
        vec1 = getDistVectorPBC_arb(atom2, self, lattice, lattice_inv)
        vec2 = getDistVectorPBC_arb(atom3, self, lattice, lattice_inv)
        dotp = np.dot(vec1/np.linalg.norm(vec1), vec2/np.linalg.norm(vec2))
        if degrees:
            return np.degrees( np.arccos( np.clip( dotp, -1.0, 1.0 ) ) )
        else:
            return np.arccos( np.clip( dotp, -1.0, 1.0 ) )

588

589
class xyzMolecule:
590
591
592
593
594
    """ **xyzMolecule**

    Class to hold information about and manipulate an xyz-style molecule.

    Args.:
alex's avatar
alex committed
595
        * xyzAtoms (list): List of instances of the xyzAtoms class that make up the molecule.
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

    """

    def __init__(self,xyzAtoms,title=None):
        self.xyzAtoms = xyzAtoms
        self.title = title

    def getCoordinates(self):
        """ **getCoordinates**
        Return coordinates of all atoms in the cluster.
        """
        return [atom.getCoordinates() for atom in self.xyzAtoms]

    def getCoordinates_name(self,name):
        """ **getCoordinates_name**
        Return coordintes of all atoms with 'name'.
        """
        atoms = []
        for atom in self.xyzAtoms:
            if atom.name == name:
                atoms.append(atom.coordinates)
        return atoms

    def get_atoms_by_name(self,name):
        """ **get_atoms_by_name**
        Return a list of all xyzAtoms of a given name 'name'.
        """
        atoms = []
        for atom in self.xyzAtoms:
            if atom.name == name:
                atoms.append(atom)
            else:
                pass
        if len(atoms) == 0:
                print('Found no atoms with given name in molecule.')
                return
        return atoms

    def getGeometricCenter(self):
        """ **getGeometricCenter**
        Return the geometric center of the xyz-molecule.
        """
        for_average = np.zeros((len(self.xyzAtoms),3))
        for ii in range(len(self.xyzAtoms)):
            for_average[ii, :] = self.xyzAtoms[ii].coordinates
        return np.mean(for_average,axis = 0)

643
644
645
    def getGeometricCenter_arb(self, lattice, lattice_inv):
        pass

646
    def translateAtomsMinimumImage(self, lattice, lattice_inv, center=np.array([0.0, 0.0, 0.0])):
647
648
649
650
651
652
653
        """ **translateAtomsMinimumImage**

        Brings back all atoms into the original box using 
        periodic boundary conditions and minimal image 
        convention.

        """
654
        nullatom = xyzAtom('O', center, 0)
655
        for atom in self.xyzAtoms:
656
657
658
659
660
           new_vec = getDistVectorPBC_arb(nullatom, atom, lattice, lattice_inv)
           atom.coordinates = new_vec+center
           atom.x_coord     = atom.coordinates[0]+center[0]
           atom.y_coord     = atom.coordinates[1]+center[1]
           atom.z_coord     = atom.coordinates[2]+center[2]
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
    def translateSelf(self,vector):
        """ **translateSelf**
        Translate all atoms of the molecule by a vector 'vector'.
        """
        for atom in self.xyzAtoms:
            atom.translateSelf(vector)

    def scatterPlot(self):
        """ **scatterPlot**
        Opens a plot window with a scatter-plot of all coordinates of the molecule.
        """
        from mpl_toolkits.mplot3d import Axes3D
        fig = figure()
        ax  = Axes3D(fig)
        x_vals = [coord[0] for coord in self.getCoordinates()]
        y_vals = [coord[1] for coord in self.getCoordinates()]
        z_vals = [coord[2] for coord in self.getCoordinates()]
        ax.scatter(x_vals, y_vals, z_vals)
        show()

    def appendAtom(self,Atom):
        """ **appendAtom**
        Add an xzyAtom to the molecule.
        """
        if isinstance(Atom,xyzAtom):
            self.xyzAtoms.append(Atom)
        elif isinstance(Atom,list):
            self.xyzAtoms.extend(Atom)

    def popAtom(self,xyzAtom):
        """ **popAtom**
        Delete an xyzAtom from the molecule.
        """
        self.xyzAtoms.remove(xyzAtom)

    def writeXYZfile(self,fname):
        """ **writeXYZfile**
        Creates an xyz-style text file with all coordinates of the molecule.
        """
        if not self.title:
            self.title = 'None'
        writeXYZfile(fname, len(self.xyzAtoms), self.title, self.xyzAtoms)
704
705


706
class xyzBox:
christoph's avatar
christoph committed
707

708
709
710
711
    """ **xyzBox**

    Class to hold information about and manipulate a xyz-periodic cubic box.

myron's avatar
myron committed
712
    Args.:
alex's avatar
alex committed
713
714
              * xyzAtoms (list): List of instances of the xyzAtoms class that make up the molecule.
              * boxLength (float): Box length.
715
716
717
718

    """

    def __init__( self, xyzAtoms, boxLength=None, title=None ):
Alessandro Mirone's avatar
Alessandro Mirone committed
719
720
721
722
723
724
725
726
727
            self.xyzMolecules = []
            self.xyzAtoms     = xyzAtoms
            self.n_atoms      = len(self.xyzAtoms)
            self.title        = title
            self.boxLength    = boxLength
            self.lattice      = None
            self.lattice_inv  = None
            self.relAtoms     = None
            self.av_spectrum  = np.array([])
728
729

    def setBoxLength( self, boxLength, angstrom=True ):
Alessandro Mirone's avatar
Alessandro Mirone committed
730
731
732
733
734
735
736
            """ **setBoxLength**
            Set the box length.
            """
            if angstrom:
                    self.boxLength = boxLength
            else:
                    self.boxLength = boxLength*constants.physical_constants['atomic unit of length'][0]*10**10
737
738

    def writeBox(self, filename):
Alessandro Mirone's avatar
Alessandro Mirone committed
739
740
741
742
            """ **writeBox**
            Creates an xyz-style text file with all coordinates of the box.
            """
            writeXYZfile(filename, self.n_atoms, self.title, self.xyzAtoms)
743
744

    def writeRelBox(self,filename,inclAtomNames=True):
Alessandro Mirone's avatar
Alessandro Mirone committed
745
746
747
748
749
750
751
752
            """ **writeRelBox**
            Writes all relative atom coordinates into a text file (useful as OCEAN input).
            """
            if not self.boxLength:
                    print('Cannot write rel. coordinates without boxLength. Need to set it first.')
                    return
            else:
                    writeRelXYZfile(filename, self.n_atoms, self.boxLength, self.title, self.xyzAtoms, inclAtomNames)
753
754

    def multiplyBoxPBC(self,numShells):
Alessandro Mirone's avatar
Alessandro Mirone committed
755
756
757
758
759
760
761
762
763
764
765
            """ **multiplyBoxPBC**
            Applies the periodic boundary conditions and multiplies the box in shells around the original.
            """
            if not self.boxLength:
                    print('Cannot multiply without boxLength. Need to set it first.')
                    return
            all_atoms = getPeriodicTestBox(self.xyzAtoms,self.boxLength,numbershells=numShells)
            self.xyzMolecules = []
            self.xyzAtoms     = all_atoms
            self.n_atoms      = self.n_atoms*(numShells*2.+1.)**3.
            self.boxLength    = self.boxLength*(numShells*2.0+1.0)
766

christoph's avatar
christoph committed
767
    def multiplyBoxPBC_arb( self, lx=[-1,1], ly=[-1,1], lz=[-1,1] ):
Alessandro Mirone's avatar
Alessandro Mirone committed
768
769
770
771
772
773
774
775
            """ **multiplyBoxPBC_arb**
            Applies the periodic boundary conditions and multiplies 
            the box in shells around the original. Works with arbitrary lattices.
            """
            if not np.any(self.lattice) and not np.any(self.lattice_inv):
                    print('Cannot multiply without lattice. Need to set it first.')
                    return

christoph's avatar
christoph committed
776
            all_atoms = getPeriodicTestBox_arb( self.xyzAtoms, self.lattice, self.lattice_inv, lx, ly, lz )
Alessandro Mirone's avatar
Alessandro Mirone committed
777
778
            self.xyzMolecules = []
            self.xyzAtoms     = all_atoms
christoph's avatar
christoph committed
779
            self.n_atoms      = self.n_atoms*((lx[1]-lx[0])+1.)*((lx[1]-lx[0])+1.)*((lx[1]-lx[0])+1.)
christoph's avatar
christoph committed
780
            try:
christoph's avatar
christoph committed
781
782
783
                    self.lattice[:,0]      = self.lattice[:,0]*((lx[1]-lx[0])+1.)
                    self.lattice[:,1]      = self.lattice[:,1]*((ly[1]-ly[0])+1.)
                    self.lattice[:,2]      = self.lattice[:,2]*((lz[1]-lz[0])+1.)
christoph's avatar
christoph committed
784
785
786
                    self.lattice_inv  = np.linalg.inv(self.lattice)
            except:
                    pass
787
788

    def translateAtomsMinimumImage(self, lattice, lattice_inv):
Alessandro Mirone's avatar
Alessandro Mirone committed
789
            """ **translateAtomsMinimumImage**
790

Alessandro Mirone's avatar
Alessandro Mirone committed
791
792
793
            Brings back all atoms into the original box using 
            periodic boundary conditions and minimal image 
            convention.
794

Alessandro Mirone's avatar
Alessandro Mirone committed
795
796
797
798
799
800
801
802
            """
            nullatom = xyzAtom('O', np.array([0.0, 0.0, 0.0]), 0)
            for atom in self.xyzAtoms:
                    new_vec = getDistVectorPBC_arb(nullatom, atom, lattice, lattice_inv)
                    atom.coordinates = new_vec
                    atom.x_coord     = atom.coordinates[0]
                    atom.y_coord     = atom.coordinates[1]
                    atom.z_coord     = atom.coordinates[2]
803
804

    def deleteTip4pCOM(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
805
806
807
808
809
810
811
            """ **deleteTip4pCOM**
            Deletes the ficticious atoms used in the TIP4P water model.
            """
            for atom in self.xyzAtoms:
                    if atom.name == 'M':
                            self.xyzAtoms.remove(atom)
                            self.n_atoms -= 1
812
813

    def writeClusters(self,cenatom_name, number,cutoff,prefix,postfix='.xyz'):
Alessandro Mirone's avatar
Alessandro Mirone committed
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
            """ **writeXYZclusters**
            Write water clusters into files.
            """
            # find central atom
            cen_atom = self.get_atoms_by_name(cenatom_name)[number]
            coor1 = cen_atom.getCoordinates()
            # cut clusters and write files
            atoms = []
            atoms.append(cen_atom)
            for atom2 in self.xyzAtoms:
                    coor2 = atom2.getCoordinates()
                    if np.linalg.norm( coor1 - coor2) > 0.0 and np.linalg.norm( coor1 - coor2) <= cutoff:
                            atoms.append(atom2)
            fname = prefix + '_%03d' % number + postfix
            box = xyzBox(atoms)
            box.writeBox(fname)
830

christoph's avatar
christoph committed
831
    def writeClusters_arb(self,cenatom_name, number,cutoff,prefix, postfix='.xyz', test_box_multiplyer=1 ):
christoph's avatar
christoph committed
832
833
834
835
836
837
838
            """ **writeXYZclusters**
            Write water clusters into files.
            """
            test_atoms = deepcopy( self.xyzAtoms )
            test_box = xyzBox(test_atoms)
            test_box.lattice = deepcopy(self.lattice)
            test_box.lattice_inv = deepcopy(self.lattice_inv)
christoph's avatar
christoph committed
839
            test_box.multiplyBoxPBC_arb( test_box_multiplyer )
christoph's avatar
christoph committed
840
841
842

            # find central atom
            cen_atom = self.get_atoms_by_name(cenatom_name)[number]
christoph's avatar
christoph committed
843

christoph's avatar
christoph committed
844
845
846
847
848
849
            # cut clusters and write files
            atoms = []
            atoms.append( cen_atom )
            for atom2 in test_box.xyzAtoms:
                dist = np.linalg.norm(cen_atom.coordinates-atom2.coordinates)
                if dist > 0.0 and dist <= cutoff:
christoph's avatar
christoph committed
850
                    # print(dist)
christoph's avatar
christoph committed
851
852
853
854
855
856
                    atoms.append(atom2)

            box2 = xyzBox(atoms)
            fname = prefix + '_%03d' % number + postfix
            box2.writeBox(fname)

857
    def writeH2Oclusters(self,cutoff,prefix,postfix='.xyz',o_name='O',h_name='H'):
Alessandro Mirone's avatar
Alessandro Mirone committed
858
859
860
861
862
863
864
865
866
867
868
            """ **writeXYZclusters**
            Write water clusters into files.
            """
            if not self.boxLength:
                    print('Cannot multiply without boxLength. Need to set it first.')
                    return
            # find H2O molecules
            self.get_h2o_molecules(o_name,h_name)
            # get a test box
            pbcMols = getPeriodicTestBox_molecules(self.xyzMolecules,self.boxLength,numbershells=1)
            # cut clusters and write files
869
870
871
            for ii, mol in enumerate(self.xyzMolecules):
                    o_atom = mol.get_atoms_by_name(o_name)[0]
                    #for o_atom, ii in zip(o_atoms,range(len(o_atoms))):
Alessandro Mirone's avatar
Alessandro Mirone committed
872
873
874
875
876
877
878
879
                    cluster = []
                    for molecule in pbcMols:
                            coor = molecule.getCoordinates_name(o_name)
                            if np.linalg.norm( o_atom.coordinates - coor) <= cutoff:
                                    cluster.extend(molecule.xyzAtoms)
                    fname = prefix + '_%03d' % ii + postfix
                    box = xyzBox(cluster)
                    box.writeBox(fname)
880
881

    def writeMoleculeCluster(self,molAtomList,fname,cutoff=None,numH2Omols=None,o_name='O',h_name='H',mol_center=None):
Alessandro Mirone's avatar
Alessandro Mirone committed
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
            """ **writeMoleculeCluster**
            Careful, this works only for a single molecule in water.
            """
            if not self.boxLength:
                    print('Cannot multiply without boxLength. Need to set it first.')
                    return
            # find H2O molecules
            self.get_h2o_molecules(o_name,h_name)
            # get a test box
            pbcMols = getPeriodicTestBox_molecules(self.xyzMolecules,self.boxLength,numbershells=1)
            # find the solute molecule
            cluster = findMolecule(self.xyzAtoms,molAtomList)
            # find center of mass of molecule
            if not mol_center:
                    cenom = cluster.getGeometricCenter()
            else:
                    cenom = cluster.getCoordinates_name(mol_center)
            if cutoff:
                    # use cutoff criterium
                    waters = findAllWaters(cenom,pbcMols,o_name,cutoff)
                    cluster.appendAtom(waters)
            elif numH2Omols:
                    # use number of waters to include
                    dists = getDistsFromMolecule(cenom,pbcMols,o_name=o_name)
                    inds  = np.argsort(dists)
                    for ii in range(numH2Omols):
                            cluster.appendAtom(pbcMols[inds[ii]].xyzAtoms)
            else:
                    print('Something is fishy!')
                    return
            cluster.writeXYZfile(fname)
913
914

    def writeFDMNESinput(self,fname,Filout,Range,Radius,Edge,NRIXS,Absorber):
Alessandro Mirone's avatar
Alessandro Mirone committed
915
916
917
918
            """ **writeFDMNESinput**
            Creates an input file to be used for q-dependent calculations with FDMNES.
            """
            writeFDMNESinput_file(self.xyzAtoms,fname,Filout,Range,Radius,Edge,NRIXS,Absorber)
919
920

    def writeOCEANinput(self,fname,headerfile,exatom,edge,subshell):
Alessandro Mirone's avatar
Alessandro Mirone committed
921
922
923
924
925
926
927
            """ **writeOCEANinput**
            Creates an OCEAN input file based on the headerfile.
            """
            if not self.boxLength:
                    print('Need box size for this function to work!')
                    return
            writeOCEANinput(fname,headerfile,self,exatom,edge,subshell)
928
929

    def getCoordinates(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
930
931
932
933
            """ **getCoordinates**
            Return coordinates of all atoms in the cluster.
            """
            return [atom.getCoordinates() for atom in self.xyzAtoms]
934
935

    def get_atoms_by_name(self,name):
Alessandro Mirone's avatar
Alessandro Mirone committed
936
937
938
939
940
941
942
943
944
945
946
947
948
949
            """ **get_atoms_by_name**
            Return a list of all xyzAtoms of a given name 'name'.
            """
            # find oxygen atoms
            atoms = []
            for atom in self.xyzAtoms:
                    if atom.name == name:
                            atoms.append(atom)
                    else:
                            pass
            if len(atoms) == 0:
                    print('Found no atoms with given name in box.')
                    return
            return atoms
950
951

    def scatterPlot(self):
Alessandro Mirone's avatar
Alessandro Mirone committed
952
953
954
955
956
957
958
959
960
961
962
963
            """ **scatterPlot**
            Opens a plot window with a scatter-plot of all coordinates of the box.
            """
            from mpl_toolkits.mplot3d import Axes3D
            fig = figure()
            ax  = Axes3D(fig)
            x_vals = [coord[0] for coord in self.getCoordinates()]
            y_vals = [coord[1] for coord in self.getCoordinates()]
            z_vals = [coord[2] for coord in self.getCoordinates()]
            cla()
            ax.scatter(x_vals, y_vals, z_vals)
            draw()
964
965

    def get_OO_neighbors(self,Roocut=3.6):
Alessandro Mirone's avatar
Alessandro Mirone committed
966
967
968
969
970
971
972
973
            """ **get_OO_neighbors**
            Returns list of numbers of nearest oxygen neighbors within readius 'Roocut'.
            """
            o_atoms = self.get_atoms_by_name('O')
            if not self.boxLength:
                    return count_OO_neighbors(o_atoms,Roocut)
            else:
                    return count_OO_neighbors(o_atoms,Roocut,boxLength=self.boxLength)
974
975

    def get_OO_neighbors_pbc(self,Roocut=3.6):
Alessandro Mirone's avatar
Alessandro Mirone committed
976
977
978
979
980
            """ **get_OO_neighbors_pbc**
            Returns a list of numbers of nearest oxygen atoms, uses periodic boundary conditions.
            """
            o_atoms = self.get_atoms_by_name('O')
            return count_OO_neighbors_pbc(o_atoms,Roocut,boxLength=self.boxLength)
981
982

    def get_h2o_molecules(self,o_name='O',h_name='H'):
alex's avatar
alex committed
983
            """ **get_h2o_molecules**
Alessandro Mirone's avatar
Alessandro Mirone committed
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
            Finds all water molecules inside the box and collects them inside 
            the self.xyzMolecules attribute.
            """
            o_atoms  = self.get_atoms_by_name(o_name)
            h_atoms  = self.get_atoms_by_name(h_name)
            if self.boxLength:
                    self.xyzMolecules = find_H2O_molecules(o_atoms,h_atoms,boxLength=self.boxLength)
            else:
                    self.xyzMolecules = find_H2O_molecules(o_atoms,h_atoms,boxLength=None)

    def get_h2o_molecules_arb(self, o_name='O',h_name='H'):
            o_atoms  = self.get_atoms_by_name(o_name)
            h_atoms  = self.get_atoms_by_name(h_name)
            self.xyzMolecules = h2o_mols = find_H2O_molecules_PBC_arb( o_atoms, h_atoms, self.lattice, self.lattice_inv )

999
1000

    def get_atoms_from_molecules(self):