def fBM_nd(dims, H, return_mat = False, use_eig_ev = True): """ creates fractional Brownian motion parameters: dims is a tuple of the shape of the sample path (nxd); H: Hurst exponent this is the slow version of fBM. It might, however, be more precise than fBM, however - sometimes, the matrix square root has a problem, which might induce inaccuracy use_eig_ev: use eigenvalue decomposition for matrix square root computation (faster) """ n = dims[0] d = dims[1] Gamma = zeros((n,n)) print ('building ...\n') for t in arange(n): for s in arange(n): Gamma[t,s] = .5*((s+1)**(2.*H) + (t+1)**(2.*H) - abs(t-s)**(2.*H)) print('rooting ...\n') if use_eig_ev: ev,ew = eig(Gamma.real) Sigma = dot(ew, dot(diag(sqrt(ev)),ew.T) ) else: Sigma = sqrtm(Gamma) if return_mat: return Sigma v = randn(n,d) return dot(Sigma,v)
def fitEllipseByMoments(bw, disp=1): # Ellipse center (x,y)=np.where(bw==True) cm=(x.mean(),y.mean()) # Momments M20=np.sum((x-cm[0])**2)/len(x) M11=np.sum((y-cm[1])*(x-cm[0]))/len(x) M02=np.sum((y-cm[1])**2)/len(x) moments=np.array([[M20,M11],[M11,M02 ]]) if disp==1: # Param. Ellipse (w,v)=pl.eig(moments) b=4*np.sqrt(w[0]);a=4*np.sqrt(w[1]); tetha=np.arctan2(v[1,0],v[0,0]) # print(a,b,tetha) # tetha=0.5*np.arctan2(2*M11,(M20-M02)) # b=4*np.sqrt(M20*np.cos(tetha)**2+2*M11*np.cos(tetha)*np.sin(tetha)+M02*np.sin(tetha)**2) # a=4*np.sqrt(M20*np.cos(tetha)**2-2*M11*np.cos(tetha)*np.sin(tetha)+M02*np.sin(tetha)**2) # print(a,b,tetha) return cm,a,b,tetha vals=pl.eigvals(moments) b=4*np.sqrt(np.min(vals)) return b
def main(): mu = pl.array([[0], [12], [24], [36]]) Sigma = pl.array([[3.01602775, 1.02746769, -3.60224613, -2.08792829], [1.02746769, 5.65146472, -3.98616664, 0.48723704], [-3.60224613, -3.98616664, 13.04508284, -1.59255406], [-2.08792829, 0.48723704, -1.59255406, 8.28742469]]) # The data matrix is created for above mu and Sigma. d, U = pl.eig(Sigma) L = pl.diagflat(d) A = pl.dot(U, pl.sqrt(L)) X = pl.randn(4, 1000) # Y is the data matrix of random samples. Y = pl.dot(A, X) + pl.tile(mu, 1000) pl.figure(1) pl.clf() pl.plot(X[0], Y[1], '+', color='#0000FF', label='i=0,j=1') pl.plot(X[0], Y[2], '+', color='#FF0000', label='i=0,j=2') pl.plot(X[0], Y[3], '+', color='#00FF00', label='i=0,j=3') pl.plot(X[1], Y[0], 'x', color='#FFFF00', label='i=1,j=0') pl.plot(X[1], Y[2], 'x', color='#00FFFF', label='i=1,j=2') pl.plot(X[1], Y[3], 'x', color='#444444', label='i=1,j=3') pl.plot(X[2], Y[0], '.', color='#774411', label='i=2,j=0') pl.plot(X[2], Y[1], '.', color='#222222', label='i=2,j=1') pl.plot(X[2], Y[3], '.', color='#AAAAAA', label='i=2,j=3') pl.plot(X[3], Y[0], '+', color='#FFAA22', label='i=3,j=0') pl.plot(X[3], Y[1], '+', color='#22AAFF', label='i=3,j=1') pl.plot(X[3], Y[2], '+', color='#FFDD00', label='i=3,j=2') pl.legend() pl.savefig('fig21.png')
def mpow2(A, n): """ Returns the n-th power of A. Here, this is computed using eigenvalue decomposition. ========== Parameter: ========== A : *array* the square matrix from which the n-th power should be returned n : *integer* the power ======== Returns: ======== B : *array* B = A^n """ D, L = eig(A) if isreal(A).all(): return reduce(dot, [L, diag(D**n), inv(L)]).real else: return reduce(dot, [L, diag(D**n), inv(L)])
def fBM_nd(dims, H, return_mat=False, use_eig_ev=True): """ creates fractional Brownian motion parameters: dims is a tuple of the shape of the sample path (nxd); H: Hurst exponent this is the slow version of fBM. It might, however, be more precise than fBM, however - sometimes, the matrix square root has a problem, which might induce inaccuracy use_eig_ev: use eigenvalue decomposition for matrix square root computation (faster) """ n = dims[0] d = dims[1] Gamma = zeros((n, n)) print('building ...\n') for t in arange(n): for s in arange(n): Gamma[t, s] = .5 * ((s + 1)**(2. * H) + (t + 1)**(2. * H) - abs(t - s)**(2. * H)) print('rooting ...\n') if use_eig_ev: ev, ew = eig(Gamma.real) Sigma = dot(ew, dot(diag(sqrt(ev)), ew.T)) else: Sigma = sqrtm(Gamma) if return_mat: return Sigma v = randn(n, d) return dot(Sigma, v)
def fit_ellipse(pts): (x,y)=pts cm=(x.mean(),y.mean()) D=np.transpose([x**2, x*y, y**2, x, y, np.ones(len(x))]) S=np.dot(np.transpose(D),D) C=np.zeros((6,6)) C[5,5]=0; C[0,2]=2; C[1,1]=-1; C[2,0]=2 (gevec, geval)=pl.eig( np.dot(pl.inv(S),C) ) (PosR, PosC)= np.where(geval>0 & ~np.isinf(geval)) a=gevec[:,PosC] (v,w)=pl.eig(np.array([[a[0],a[1]/2],[a[1]/2,a[2]]])) vect1=w[:,0] theta=np.arctan2(vect1[1],vect1[0]) return cm, v[1], v[0], theta
def CSpectra_to_ShortTermFT(cspecdict, seed=None): cspecnames = ['11', '12', '13', '22', '23', '33'] cspeclist = [cspecdict[cspecname] for cspecname in cspecnames] freqlist = [(cspec.Offset1, cspec.Cadence1, cspec.data.shape[0]) for cspec in cspeclist] for i in range(1, len(freqlist)): if not freqlist[0] == freqlist[i]: print "Make sure all cross-spectra's frequencies are the same." raise ValueError Nf = cspeclist[0].data.shape[0] fOffset = cspeclist[0].Offset1 fCadence = cspeclist[0].Cadence1 Z = TheZs(Nf, seed) sdatas = [numpy.zeros((Nf, ), dtype='complex') for i in range(3)] for k in range(Nf): clist = [cspec.data[k] for cspec in cspeclist] cmatrix = numpy.array( [[clist[0], clist[1], clist[2]], [numpy.conj(clist[1]), clist[3], clist[4]], [numpy.conj(clist[2]), numpy.conj(clist[4]), clist[5]]]) w, V = pylab.eig(cmatrix) for ww in list(w): if ww <= 0: print "Warning: trying to simulate an unphysical signal." Vadjoint = numpy.transpose(numpy.conjugate(V)) if not numpy.allclose(numpy.dot(V, Vadjoint), numpy.diag(numpy.ones(V.shape[0]))): print "Warning: the matrix of eigenvectors is not unitary." s = (Z.z1[k] * cmath.sqrt(numpy.real(w[0])) * V[:, 0] + Z.z2[k] * cmath.sqrt(numpy.real(w[1])) * V[:, 1] + Z.z3[k] * cmath.sqrt(numpy.real(w[2])) * V[:, 2]) sdatas[0][k], sdatas[1][k], sdatas[2][k] = numpy.conj(s) scoarsables = [ Utilities3.Coarsable(sdata, Offset1=fOffset, Cadence1=fCadence) for sdata in sdatas ] shortft = ShortTermFT(s1=scoarsables[0], s2=scoarsables[1], s3=scoarsables[2]) return shortft
def CSpectra_to_ShortTermFT( cspecdict , seed=None ): cspecnames = [ '11' , '12' , '13' , '22' , '23' , '33' ] cspeclist = [ cspecdict[ cspecname ] for cspecname in cspecnames ] freqlist = [ ( cspec.Offset1 , cspec.Cadence1 , cspec.data.shape[0] ) for cspec in cspeclist ] for i in range( 1 , len( freqlist ) ): if not freqlist[0] == freqlist[i]: print "Make sure all cross-spectra's frequencies are the same." raise ValueError Nf = cspeclist[0].data.shape[0] fOffset = cspeclist[0].Offset1 fCadence = cspeclist[0].Cadence1 Z = TheZs( Nf , seed ) sdatas = [ numpy.zeros( (Nf,) , dtype='complex' ) for i in range(3) ] for k in range( Nf ): clist = [ cspec.data[k] for cspec in cspeclist ] cmatrix = numpy.array( [ [ clist[0] , clist[1] , clist[2] ] , [ numpy.conj( clist[1] ) , clist[3] , clist[4] ] , [ numpy.conj( clist[2] ) , numpy.conj( clist[4] ) , clist[5] ] ] ) w , V = pylab.eig( cmatrix ) for ww in list( w ): if ww <= 0: print "Warning: trying to simulate an unphysical signal." Vadjoint = numpy.transpose( numpy.conjugate( V ) ) if not numpy.allclose( numpy.dot( V , Vadjoint ) , numpy.diag( numpy.ones( V.shape[0] ) ) ): print "Warning: the matrix of eigenvectors is not unitary." s = ( Z.z1[k]*cmath.sqrt( numpy.real( w[0] ) )*V[:,0] + Z.z2[k]*cmath.sqrt( numpy.real( w[1] ) )*V[:,1] + Z.z3[k]*cmath.sqrt( numpy.real( w[2] ) )*V[:,2] ) sdatas[0][k] , sdatas[1][k] , sdatas[2][k] = numpy.conj( s ) scoarsables = [ Utilities3.Coarsable( sdata , Offset1=fOffset , Cadence1=fCadence ) for sdata in sdatas ] shortft = ShortTermFT( s1=scoarsables[0] , s2=scoarsables[1] , s3=scoarsables[2] ) return shortft
def get_features(self,positions): wMin = 5 wMax = 18 track_length = pl.shape(positions)[0] steps = self._get_steps(positions,track_length) angles = self._get_angles(steps,track_length) feats = pl.zeros([track_length,self.many_features]) manyTimes = pl.zeros(track_length) msd = self._get_msd(positions,track_length) # following code is to _get diffusion coefficient xi = pl.arange(4) A = pl.array([xi, pl.ones(4)]).T diff_coeff = pl.lstsq(A,msd[:4])[0][0] for i in range(track_length-wMax+1): for j in range(wMin,wMax+1): feats[i:i+j,0] += self._get_straight(angles[i:i+j-2],j-1) feats[i:i+j,1] += self._get_bend(angles[i:i+j-2],j-1) feats[i:i+j,2] += self._get_eff(positions[i:i+j,:],steps[i:i+j-1,:],j-1) gyrationTensor = self._get_gyration_tensor(positions[i:i+j,:]) [eig_vals, eig_vecs] = pl.eig(gyrationTensor) eig_vals = pl.array([eig_vals[0],eig_vals[1]]) feats[i:i+j,3] += self._get_asymm(eig_vals[0],eig_vals[1]) dom_index = pl.argmax(eig_vals) dom_vec = eig_vecs[:,dom_index] pos_proj = self._get_projection(positions[i:i+j,:],dom_vec,j-1) proj_mean = pl.mean(pos_proj) feats[i:i+j,4] += self._get_skew(pos_proj,proj_mean,j-1) feats[i:i+j,5] += self._get_kurt(pos_proj,proj_mean,j-1) feats[i:i+j,6] += self._get_disp(positions[i:i+j,:]) feats[i:i+j,7] += self._get_conf(positions[i:i+j,:],j-1,diff_coeff) manyTimes[i:i+j] += 1 for i in range(self.many_features): feats[:,i] /= manyTimes return feats
def get_edge_errors(self): """ Calculates the error estimates of the expression projected into the mesh. :rtype: Dolfin edge function containing the edge errors of the mesh """ mesh = self.mesh coord = mesh.coordinates() V = FunctionSpace(mesh, "CG", 1) Hxx = TrialFunction(V) Hxy = TrialFunction(V) Hyy = TrialFunction(V) phi = TestFunction(V) edge_errors = EdgeFunction('double', mesh) U = project(self.U_ex, V) a_xx = Hxx * phi * dx L_xx = - U.dx(0) * phi.dx(0) * dx a_xy = Hxy * phi * dx L_xy = - U.dx(0) * phi.dx(1) * dx a_yy = Hyy * phi * dx L_yy = - U.dx(1) * phi.dx(1) * dx Hxx = Function(V) Hxy = Function(V) Hyy = Function(V) Mxx = Function(V) Mxy = Function(V) Myy = Function(V) solve(a_xx == L_xx, Hxx) solve(a_xy == L_xy, Hxy) solve(a_yy == L_yy, Hyy) e_list = [] for v in vertices(mesh): idx = v.index() pt = v.point() x = pt.x() y = pt.y() a = Hxx(x, y) b = Hxy(x, y) d = Hyy(x, y) H_local = ([[a,b], [b,d]]) l, ve = p.eig(H_local) M = p.dot(p.dot(ve, abs(p.diag(l))), ve.T) Mxx.vector()[idx] = M[0,0] Mxy.vector()[idx] = M[1,0] Myy.vector()[idx] = M[1,1] e_list = [] for e in edges(mesh): I, J = e.entities(0) x_I = coord[I,:] x_J = coord[J,:] M_I = p.array([[Mxx.vector()[I], Mxy.vector()[I]], [Mxy.vector()[I], Myy.vector()[I]]]) M_J = p.array([[Mxx.vector()[J], Mxy.vector()[J]], [Mxy.vector()[J], Myy.vector()[J]]]) M = (M_I + M_J)/2. dX = x_I - x_J error = p.dot(p.dot(dX, M), dX.T) e_list.append(error) edge_errors[e] = error return edge_errors
a_yy = Hyy * phi * dx L_yy = -U.dx(1) * phi.dx(1) * dx Hxx = Function(V) Hxy = Function(V) Hyy = Function(V) solve(a_xx == L_xx, Hxx) solve(a_xy == L_xy, Hxy) solve(a_yy == L_yy, Hyy) # Get the value of Hessian at each node Hxx_a = project(Hxx, V).vector().array() Hxy_a = project(Hxy, V).vector().array() Hyy_a = project(Hyy, V).vector().array() # Find the |dominant eigenvalue of the Hessian| m = p.array([Hxx_a, Hxy_a, Hxy_a, Hyy_a]) m = p.array( [max( abs( p.eig( m[:,i].reshape((2,2)))[0] )) for i in \ range(len(Hxx_a))] ) m = p.log(m) # Read into function space H_lambda = Function(V) H_lambda.vector().set_local(m) # Output data output = File('hess_py_output.pvd') output << H_lambda
def main(): import optparse from numpy import sum # Parse command line parser = optparse.OptionParser(usage=USAGE) parser.add_option("-p", "--plot", action="store_true", help="Generate pdf with IR-spectrum") parser.add_option("-i", "--info", action="store_true", help="Set up/ Calculate vibrations & quit") parser.add_option("-s", "--suffix", action="store", help="Call suffix for binary e.g. 'mpirun -n 4 '", default='') parser.add_option("-r", "--run", action="store", help="path to FHI-aims binary", default='') parser.add_option("-x", "--relax", action="store_true", help="Relax initial geometry") parser.add_option("-m", "--molden", action="store_true", help="Output in molden format") parser.add_option("-w", "--distort", action="store_true", help="Output geometry distorted along imaginary modes") parser.add_option("-t", "--submit", action="store", help="""\ Path to submission script, string <jobname> will be replaced by name + counter, string <outfile> will be replaced by filename""") parser.add_option("-d", "--delta", action="store", type="float", help="Displacement", default=0.0025) options, args = parser.parse_args() if options.info: print __doc__ sys.exit(0) if len(args) != 2: parser.error("Need exactly two arguments") AIMS_CALL = options.suffix + ' ' + options.run hessian_thresh = -1 name = args[0] mode = args[1] delta = options.delta run_aims = False if options.run != '': run_aims = True submit_script = options.submit is not None if options.plot: import matplotlib as mpl mpl.use('Agg') from pylab import figure if options.plot or mode == '1': from pylab import savetxt, transpose, eig, argsort, sort,\ sign, pi, dot, sum, linspace, argmin, r_, convolve # Constant from scipy.constants bohr = constants.value('Bohr radius') * 1.e10 hartree = constants.value('Hartree energy in eV') at_u = constants.value('atomic mass unit-kilogram relationship') eV = constants.value('electron volt-joule relationship') c = constants.value('speed of light in vacuum') Ang = 1.0e-10 hbar = constants.value('Planck constant over 2 pi') Avo = constants.value('Avogadro constant') kb = constants.value('Boltzmann constant in eV/K') hessian_factor = eV / (at_u * Ang * Ang) grad_dipole_factor = (eV / (1. / (10 * c))) / Ang #(eV/Ang -> D/Ang) ir_factor = 1 # Asign all filenames inputgeomerty = 'geometry.in.' + name inputcontrol = 'control.in.' + name atomicmasses = 'masses.' + name + '.dat' xyzfile = name + '.xyz' moldenname = name + '.molden' hessianname = 'hessian.' + name + '.dat' graddipolename = 'grad_dipole.' + name + '.dat' irname = 'ir.' + name + '.dat' deltas = array([-delta, delta]) coeff = array([-1, 1]) c_zero = -1. / (2. * delta) f = open('control.in', 'r') # read control.in template template_control = f.read() f.close if submit_script: f = open(options.submit, 'r') # read submission script template template_job = f.read() f.close folder = '' # Dummy ########### Central Point ################################################## if options.relax and mode == '0': # First relax input geometry filename = name + '.out' folder = name + '_relaxation' if not os.path.exists(folder): os.mkdir(folder) # Create folder shutil.copy('geometry.in', folder + '/geometry.in') # Copy geometry new_control = open(folder + '/control.in', 'w') new_control.write(template_control + 'relax_geometry trm 1E-3\n') # Relax! new_control.close() os.chdir(folder) # Change directoy print 'Central Point' if run_aims: os.system(AIMS_CALL + ' > ' + filename) # Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, 0, filename) os.chdir('..') ############################################################################ # Check for relaxed geometry if os.path.exists(folder + '/geometry.in.next_step'): geometry = open(folder + '/geometry.in.next_step', 'r') else: geometry = open('geometry.in', 'r') # Read input geometry n_line = 0 struc = structure() lines = geometry.readlines() for line in lines: n_line = n_line + 1 if line.rfind('set_vacuum_level') != -1: # Vacuum Level struc.vacuum_level = float(split_line(line)[-1]) if line.rfind('lattice_vector') != -1: # Lattice vectors and periodic lat = split_line(line)[1:] struc.lattic_vector = append(struc.lattic_vector, float64(array(lat))[newaxis, :], axis=0) struc.periodic = True if line.rfind('atom') != -1: # Set atoms line_vals = split_line(line) at = Atom(line_vals[-1], line_vals[1:-1]) if n_line < len(lines): nextline = lines[n_line] if nextline.rfind( 'constrain_relaxation') != -1: # constrained? at = Atom(line_vals[-1], line_vals[1:-1], True) else: at = Atom(line_vals[-1], line_vals[1:-1]) struc.join(at) geometry.close() n_atoms = struc.n() n_constrained = n_atoms - sum(struc.constrained) # Atomic mass file mass_file = open(atomicmasses, 'w') mass_vector = zeros([0]) for at_unconstrained in struc.atoms[struc.constrained == False]: mass_vector = append(mass_vector, ones(3) * 1. / sqrt(at_unconstrained.mass())) line = '{0:10.5f}'.format(at_unconstrained.mass()) for i in range(3): line = line + '{0:11.4f}'.format(at_unconstrained.coord[i]) line = line + '{0:}\n'.format(at_unconstrained.kind) mass_file.writelines(line) mass_file.close() # Init dip = zeros([n_constrained * 3, 3]) hessian = zeros([n_constrained * 3, n_constrained * 3]) index = 0 counter = 1 # Set up / Read folders for displaced atoms for atom in arange(n_atoms)[struc.constrained == False]: for coord in arange(3): for delta in deltas: filename=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta)+'.out' folder=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta) if mode == '0': # Put new geometry and control.in into folder struc_new = copy.deepcopy(struc) struc_new.atoms[atom].coord[coord]=\ struc_new.atoms[atom].coord[coord]+delta geoname='geometry.i_atom_'+str(atom)+'.i_coord_'+str(coord)+\ '.displ_'+str(delta)+'.in' if not os.path.exists(folder): os.mkdir(folder) new_geo = open(folder + '/geometry.in', 'w') newline='#\n# temporary structure-file for finite-difference '+\ 'calculation of forces\n' newline=newline+'# displacement {0:8.4f} of \# atom '.format(delta)+\ '{0:5} direction {1:5}\n#\n'.format(atom,coord) new_geo.writelines(newline + struc_new.to_str()) new_geo.close() new_control = open(folder + '/control.in', 'w') template_control = template_control.replace( 'relax_geometry', '#relax_geometry') new_control.write(template_control+'compute_forces .true. \n'+\ 'final_forces_cleaned '+\ '.true. \noutput dipole \n') new_control.close() os.chdir(folder) # Change directoy print 'Processing atom: '+str(atom+1)+'/'+str(n_atoms)+', coord.: '+\ str(coord+1)+'/'+str(3)+', delta: '+str(delta) if run_aims: os.system(AIMS_CALL + ' > ' + filename) # Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, counter, filename) # os.system('qsub job.sh') # Mind the environment variables os.chdir('..') if mode == '1': # Read output forces_reached = False atom_count = 0 data = open(folder + '/' + filename) for line in data.readlines(): if line.rfind( 'Dipole correction potential jump') != -1: dip_jump = float(split_line(line)[-2]) # Periodic if line.rfind('| Total dipole moment [eAng]') != -1: dip_jump = float64( split_line(line)[-3:]) # Cluster if forces_reached and atom_count < n_atoms: # Read Forces struc.atoms[atom_count].force = float64( split_line(line)[2:]) atom_count = atom_count + 1 if atom_count == n_atoms: forces_reached = False if line.rfind('Total atomic forces') != -1: forces_reached = True data.close() if struc.periodic: dip[index, 2] = dip[ index, 2] + dip_jump * coeff[deltas == delta] * c_zero else: dip[index, :] = dip[index, :] + dip_jump * coeff[ deltas == delta] * c_zero forces = array([]) for at_unconstrained in struc.atoms[struc.constrained == False]: forces = append( forces, coeff[deltas == delta] * at_unconstrained.force) hessian[index, :] = hessian[index, :] + forces * c_zero counter = counter + 1 index = index + 1 if mode == '1': # Calculate vibrations print 'Entering hessian diagonalization' print 'Number of atoms = ' + str(n_atoms) print 'Name of Hessian input file = ' + hessianname print 'Name of grad dipole input file = ' + graddipolename print 'Name of Masses input file = ' + atomicmasses print 'Name of XYZ output file = ' + xyzfile print 'Threshold for Matrix elements = ' + str(hessian_thresh) if (hessian_thresh < 0.0): print ' All matrix elements are taken'+\ ' into account by default\n' savetxt(hessianname, hessian) savetxt(graddipolename, dip) mass_mat = mass_vector[:, newaxis] * mass_vector[newaxis, :] hessian[abs(hessian) < hessian_thresh] = 0.0 hessian = hessian * mass_mat * hessian_factor hessian = (hessian + transpose(hessian)) / 2. # Diagonalize hessian (scipy) print 'Solving eigenvalue system for Hessian Matrix' freq, eig_vec = eig(hessian) print 'Done ... ' eig_vec = eig_vec[:, argsort(freq)] freq = sort(sign(freq) * sqrt(abs(freq))) ZPE = hbar * (freq) / (2.0 * eV) freq = (freq) / (200. * pi * c) grad_dipole = dip * grad_dipole_factor eig_vec = eig_vec * mass_vector[:, newaxis] * ones( len(mass_vector))[newaxis, :] infrared_intensity = sum(dot(transpose(grad_dipole),eig_vec)**2,axis=0)*\ ir_factor reduced_mass = sum(eig_vec**2, axis=0) norm = sqrt(reduced_mass) eig_vec = eig_vec / norm # The rest is output, xyz, IR,... print 'Results\n' print 'List of all frequencies found:' print 'Mode number Frequency [cm^(-1)] Zero point energy [eV] '+\ 'IR-intensity [D^2/Ang^2]' for i in range(len(freq)): print '{0:11}{1:25.8f}{2:25.8f}{3:25.8f}'.format( i + 1, freq[i], ZPE[i], infrared_intensity[i]) print '\n' print 'Summary of zero point energy for entire system:' print '| Cumulative ZPE = {0:15.8f} eV'.format(sum(ZPE)) print '| without first six eigenmodes = {0:15.8f} eV\n'.format( sum(ZPE) - sum(ZPE[:6])) print 'Stability checking - eigenvalues should all be positive for a '+\ 'stable structure. ' print 'The six smallest frequencies should be (almost) zero:' string = '' for zz in ZPE[:6]: string = string + '{0:25.8f}'.format(zz) print string print 'Compare this with the largest eigenvalue, ' print '{0:25.8f}'.format(freq[-1]) nums = arange(n_atoms)[struc.constrained == False] nums2 = arange(n_atoms)[struc.constrained] newline = '' newline_ir = '[INT]\n' if options.molden: newline_molden = '[Molden Format]\n[GEOMETRIES] XYZ\n' newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n' for i_atoms in range(n_constrained): newline_molden = newline_molden + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden = newline_molden + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) newline_molden = newline_molden + '\n' newline_molden = newline_molden + '[FREQ]\n' for i in range(len(freq)): newline_molden = newline_molden + '{0:10.3f}\n'.format(freq[i]) newline_molden = newline_molden + '[INT]\n' for i in range(len(freq)): newline_molden = newline_molden + '{0:17.6e}\n'.format( infrared_intensity[i]) newline_molden = newline_molden + '[FR-COORD]\n' newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n' for i_atoms in range(n_constrained): newline_molden = newline_molden + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden = newline_molden + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord] / bohr) newline_molden = newline_molden + '\n' newline_molden = newline_molden + '[FR-NORM-COORD]\n' for i in range(len(freq)): newline = newline + '{0:6}\n'.format(n_atoms) if freq[i] > 0: newline = newline + 'stable frequency at ' elif freq[i] < 0: newline = newline + 'unstable frequency at ' if options.distort and freq[i] < -50: struc_new = copy.deepcopy(struc) for i_atoms in range(n_constrained): for i_coord in range(3): struc_new.atoms[i_atoms].coord[i_coord]=\ struc_new.atoms[i_atoms].coord[i_coord]+\ eig_vec[(i_atoms)*3+i_coord,i] geoname = name + '.distorted.vibration_' + str( i + 1) + '.geometry.in' new_geo = open(geoname, 'w') newline_geo = '#\n# distorted structure-file for based on eigenmodes\n' newline_geo=newline_geo+\ '# vibration {0:5} :{1:10.3f} 1/cm\n#\n'.format(i+1,freq[i]) new_geo.writelines(newline_geo + struc_new.to_str()) new_geo.close() elif freq[i] == 0: newline = newline + 'translation or rotation ' newline = newline + '{0:10.3f} 1/cm IR int. is '.format(freq[i]) newline = newline + '{0:10.4e} D^2/Ang^2; red. mass is '.format( infrared_intensity[i]) newline = newline + '{0:5.3f} a.m.u.; force const. is '.format( 1.0 / reduced_mass[i]) newline = newline + '{0:5.3f} mDyne/Ang.\n'.format( ((freq[i] * (200 * pi * c))**2) * (1.0 / reduced_mass[i]) * at_u * 1.e-2) if options.molden: newline_molden=newline_molden+\ 'vibration {0:6}\n'.format(i+1) for i_atoms in range(n_constrained): newline = newline + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( eig_vec[(i_atoms) * 3 + i_coord, i]) if options.molden: newline_molden = newline_molden + '{0:10.4f}'.format( eig_vec[(i_atoms) * 3 + i_coord, i] / bohr) newline = newline + '\n' if options.molden: newline_molden = newline_molden + '\n' for i_atoms in range(n_atoms - n_constrained): newline = newline + '{0:6}'.format( struc.atoms[nums2[i_atoms]].kind) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( struc.atoms[nums2[i_atoms]].coord[i_coord]) for i_coord in range(3): newline = newline + '{0:10.4f}'.format(0.0) newline = newline + '\n' newline_ir = newline_ir + '{0:10.4e}\n'.format( infrared_intensity[i]) xyz = open(xyzfile, 'w') xyz.writelines(newline) xyz.close() ir = open(irname, 'w') ir.writelines(newline_ir) ir.close() if options.molden: molden = open(moldenname, 'w') molden.writelines(newline_molden) molden.close() if mode == '1' and options.plot: x = linspace(freq.min() - 500, freq.max() + 500, 1000) z = zeros(len(x)) for i in range(len(freq)): z[argmin(abs(x - freq[i]))] = infrared_intensity[i] window_len = 150 gauss = signal.gaussian(window_len, 10) s = r_[z[window_len - 1:0:-1], z, z[-1:-window_len:-1]] z_convolve = convolve(gauss / gauss.sum(), s, mode='same')[window_len - 1:-window_len + 1] fig = figure(0) ax = fig.add_subplot(111) ax.plot(x, z_convolve, 'r', lw=2) ax.set_xlim([freq.min() - 500, freq.max() + 500]) ax.set_ylim([-0.01, ax.get_ylim()[1]]) ax.set_yticks([]) ax.set_xlabel('Frequency [1/cm]', size=20) ax.set_ylabel('Intensity [a.u.]', size=20) fig.savefig(name + '_IR_spectrum.pdf') print '\n Done. '
def pseudoSpect(A, npts=200, s=2., gridPointSelect=100, verbose=True, lstSqSolve=True): """ original code from http://www.cs.ox.ac.uk/projects/pseudospectra/psa.m % psa.m - Simple code for 2-norm pseudospectra of given matrix A. % Typically about N/4 times faster than the obvious SVD method. % Comes with no guarantees! - L. N. Trefethen, March 1999. parameter: A: the matrix to analyze npts: number of points at the grid s: axis limits (-s ... +s) gridPointSelect: ??? verbose: prints progress messages lstSqSolve: if true, use least squares in algorithm where solve could be used (probably) instead. (replacement for ldivide in MatLab) """ from scipy.linalg import schur, triu from pylab import (meshgrid, norm, dot, zeros, eye, diag, find, linspace, arange, isreal, inf, ones, lstsq, solve, sqrt, randn, eig, all) ldiv = lambda M1, M2: lstsq(M1, M2)[ 0] if lstSqSolve else lambda M1, M2: solve(M1, M2) def planerot(x): ''' return (G,y) with a matrix G such that y = G*x with y[1] = 0 ''' G = zeros((2, 2)) xn = x / norm(x) G[0, 0] = xn[0] G[1, 0] = -xn[1] G[0, 1] = xn[1] G[1, 1] = xn[0] return G, dot(G, x) xmin = -s xmax = s ymin = -s ymax = s x = linspace(xmin, xmax, npts, endpoint=False) y = linspace(ymin, ymax, npts, endpoint=False) xx, yy = meshgrid(x, y) zz = xx + 1j * yy #% Compute Schur form and plot eigenvalues: T, Z = schur(A, output='complex') T = triu(T) eigA = diag(T) # Reorder Schur decomposition and compress to interesting subspace: select = find(eigA.real > -250) # % <- ALTER SUBSPACE SELECTION n = len(select) for i in arange(n): for k in arange(select[i] - 1, i, -1): #:-1:i G = planerot([T[k, k + 1], T[k, k] - T[k + 1, k + 1]])[0].T[::-1, ::-1] J = slice(k, k + 2) T[:, J] = dot(T[:, J], G) T[J, :] = dot(G.T, T[J, :]) T = triu(T[:n, :n]) I = eye(n) # Compute resolvent norms by inverse Lanczos iteration and plot contours: sigmin = inf * ones((len(y), len(x))) #A = eye(5) niter = 0 for i in arange(len(y)): # 1:length(y) if all(isreal(A)) and (ymax == -ymin) and (i > len(y) / 2): sigmin[i, :] = sigmin[len(y) - i, :] else: for jj in arange(len(x)): z = zz[i, jj] T1 = z * I - T T2 = T1.conj().T if z.real < gridPointSelect: # <- ALTER GRID POINT SELECTION sigold = 0 qold = zeros((n, 1)) beta = 0 H = zeros((100, 100)) q = randn(n, 1) + 1j * randn(n, 1) while norm(q) < 1e-8: q = randn(n, 1) + 1j * randn(n, 1) q = q / norm(q) for k in arange(99): v = ldiv(T1, (ldiv(T2, q))) - dot(beta, qold) #stop alpha = dot(q.conj().T, v).real v = v - alpha * q beta = norm(v) qold = q q = v / beta H[k + 1, k] = beta H[k, k + 1] = beta H[k, k] = alpha if (alpha > 1e100): sig = alpha else: sig = max(abs(eig(H[:k + 1, :k + 1])[0])) if (abs(sigold / sig - 1) < .001) or (sig < 3 and k > 2): break sigold = sig niter += 1 #print 'niter = ', niter #%text(x(jj),y(i),num2str(k)) % <- SHOW ITERATION COUNTS sigmin[i, jj] = 1. / sqrt(sig) #end # end if verbose: print 'finished line ', str(i), ' out of ', str(len(y)) return x, y, sigmin
for i in range(nseqs): percdict = sequence_list[i] for an in range(20): percents[i, an] = percdict[aas[an]] #plotting percentage heatmap plt.imshow(percents[:200, :], cmap="hot") #%% #PCA meanX = percents.mean(axis=0) norm = sc.zeros((percents.shape)) for i in range(percents.shape[0]): norm[i, :] = percents[i, :] - meanX mm = pl.dot(norm.T, norm) v, e = pl.eig(mm) #eigenvalues, eigenvectors ev0 = pl.dot(percents, e[:, 0]) ev1 = pl.dot(percents, e[:, 1]) ev2 = pl.dot(percents, e[:, 2]) plt.figure() plt.plot(ev0, ev1, '.') plt.figure() plt.plot(ev0, ev2, '.') plt.figure() plt.plot(ev1, ev2, '.') #plot(percents[:,19],percents[:,18]) #pplot(percents[:,19],percents[:,18],'.') #%% plt.figure()
def pseudoSpect(A, npts=200, s=2., gridPointSelect=100, verbose=True, lstSqSolve=True): """ original code from http://www.cs.ox.ac.uk/projects/pseudospectra/psa.m % psa.m - Simple code for 2-norm pseudospectra of given matrix A. % Typically about N/4 times faster than the obvious SVD method. % Comes with no guarantees! - L. N. Trefethen, March 1999. parameter: A: the matrix to analyze npts: number of points at the grid s: axis limits (-s ... +s) gridPointSelect: ??? verbose: prints progress messages lstSqSolve: if true, use least squares in algorithm where solve could be used (probably) instead. (replacement for ldivide in MatLab) """ from scipy.linalg import schur, triu from pylab import (meshgrid, norm, dot, zeros, eye, diag, find, linspace, arange, isreal, inf, ones, lstsq, solve, sqrt, randn, eig, all) ldiv = lambda M1,M2 :lstsq(M1,M2)[0] if lstSqSolve else lambda M1,M2: solve(M1,M2) def planerot(x): ''' return (G,y) with a matrix G such that y = G*x with y[1] = 0 ''' G = zeros((2,2)) xn = x / norm(x) G[0,0] = xn[0] G[1,0] = -xn[1] G[0,1] = xn[1] G[1,1] = xn[0] return G, dot(G,x) xmin = -s xmax = s ymin = -s ymax = s; x = linspace(xmin,xmax,npts,endpoint=False) y = linspace(ymin,ymax,npts,endpoint=False) xx,yy = meshgrid(x,y) zz = xx + 1j*yy #% Compute Schur form and plot eigenvalues: T,Z = schur(A,output='complex'); T = triu(T) eigA = diag(T) # Reorder Schur decomposition and compress to interesting subspace: select = find( eigA.real > -250) # % <- ALTER SUBSPACE SELECTION n = len(select) for i in arange(n): for k in arange(select[i]-1,i,-1): #:-1:i G = planerot([T[k,k+1],T[k,k]-T[k+1,k+1]] )[0].T[::-1,::-1] J = slice(k,k+2) T[:,J] = dot(T[:,J],G) T[J,:] = dot(G.T,T[J,:]) T = triu(T[:n,:n]) I = eye(n); # Compute resolvent norms by inverse Lanczos iteration and plot contours: sigmin = inf*ones((len(y),len(x))); #A = eye(5) niter = 0 for i in arange(len(y)): # 1:length(y) if all(isreal(A)) and (ymax == -ymin) and (i > len(y)/2): sigmin[i,:] = sigmin[len(y) - i,:] else: for jj in arange(len(x)): z = zz[i,jj] T1 = z * I - T T2 = T1.conj().T if z.real < gridPointSelect: # <- ALTER GRID POINT SELECTION sigold = 0 qold = zeros((n,1)) beta = 0 H = zeros((100,100)) q = randn(n,1) + 1j*randn(n,1) while norm(q) < 1e-8: q = randn(n,1) + 1j*randn(n,1) q = q/norm(q) for k in arange(99): v = ldiv(T1,(ldiv(T2,q))) - dot(beta,qold) #stop alpha = dot(q.conj().T, v).real v = v - alpha*q beta = norm(v) qold = q q = v/beta H[k+1,k] = beta H[k,k+1] = beta H[k,k] = alpha if (alpha > 1e100): sig = alpha else: sig = max(abs(eig(H[:k+1,:k+1])[0])) if (abs(sigold/sig-1) < .001) or (sig < 3 and k > 2): break sigold = sig niter += 1 #print 'niter = ', niter #%text(x(jj),y(i),num2str(k)) % <- SHOW ITERATION COUNTS sigmin[i,jj] = 1./sqrt(sig); #end # end if verbose: print 'finished line ', str(i), ' out of ', str(len(y)) return x,y,sigmin
import pylab as plt n = 1000 mu = [[0], [0], [0], [0]] Sigma = [[3.01602775, 1.02746769, -3.60224613, -2.08792829], [1.02746769, 5.65146472, -3.98616664, 0.48723704], [-3.60224613, -3.98616664, 13.04508284, -1.59255406], [-2.08792829, 0.48723704, -1.59255406, 8.28742469]] d, U = plt.eig(Sigma) # Sigma = U L Ut L = plt.diagflat(d) A = plt.dot(U, plt.sqrt(L)) # Required transform matrix. X = plt.randn(4, n) # 4*n matrix with each element ~ N(0,1) # 4*n each column vector ~N(mu,Sigma), random draws from distribution. Y = plt.dot(A, X) + plt.tile(mu, n) Ybar = [[avg] for avg in plt.mean(Y, 1)] # Mean along the 1 axis. Yzm = Y - plt.tile(Ybar, n) # Subtract mean from each column. # Estimator for covariance matrix. S = plt.dot(Yzm, plt.transpose(Yzm)) / n - 1 print(Ybar, S)
def main(): mu = pl.array([[2], [8], [16], [32]]) Sigma = pl.array([[3.01602775, 1.02746769, -3.60224613, -2.08792829], [1.02746769, 5.65146472, -3.98616664, 0.48723704], [-3.60224613, -3.98616664, 13.04508284, -1.59255406], [-2.08792829, 0.48723704, -1.59255406, 8.28742469]]) d, U = pl.eig(Sigma) L = pl.diagflat(d) A = pl.dot(U, pl.sqrt(L)) N = [] mu_deviations = [] Sigma_deviations = [] # First part of the exercise. # This loop is used to get different sizes of N. for i in range(1, 40): means = pl.array([]) covariances = pl.array([]) N.append(50 * i) # From this loop, the average is taken to get an accurate measurement. for _ in range(1, 200): X = pl.randn(4, 50 * i) Y = pl.dot(A, X) + pl.tile(mu, 50 * i) mean = pl.mean(Y, axis=1) covariance = pl.cov(Y) covariance = covariance.reshape((1, 16)) if (len(means) == 0 and len(covariances) == 0): means = mean covariances = covariance else: means = pl.vstack((means, mean)) covariances = pl.vstack((covariances, covariance)) mu_deviations.append(pl.mean(pl.std(covariances, axis=0))) Sigma_deviations.append(pl.mean(pl.std(means, axis=0))) pl.figure(1) pl.clf() pl.title('The average deviation, over 200 times,\n of the mean\ and covariance matrix for a given N') pl.xlabel('N') pl.ylabel('average deviation') pl.plot(N, mu_deviations, label='average mean deviation') pl.plot(N, Sigma_deviations, label='average covariance deviation') pl.legend() pl.savefig('fig22.png') # Second part of the exercise. covariances = pl.array([]) # Over the loop is iterated to create a data matrix of the covariances of # the data matrices obtained from the multivariate normal distribution. # The covariance from this data matrix of covariances is shown. for _ in range(1, 200): X = pl.randn(4, 1000) Y = pl.dot(A, X) + pl.tile(mu, 1000) covariance = pl.cov(Y) if (len(covariances) == 0): covariances = covariance else: covariances = pl.hstack((covariances, covariance)) covariance_data = pl.cov(covariances) print(covariance_data)
a_yy = Hyy * phi * dx L_yy = - U.dx(1) * phi.dx(1) * dx Hxx = Function(V) Hxy = Function(V) Hyy = Function(V) solve(a_xx == L_xx, Hxx) solve(a_xy == L_xy, Hxy) solve(a_yy == L_yy, Hyy) # Get the value of Hessian at each node Hxx_a = project(Hxx,V).vector().array() Hxy_a = project(Hxy,V).vector().array() Hyy_a = project(Hyy,V).vector().array() # Find the |dominant eigenvalue of the Hessian| m = p.array([Hxx_a,Hxy_a,Hxy_a,Hyy_a]) m = p.array( [max( abs( p.eig( m[:,i].reshape((2,2)))[0] )) for i in \ range(len(Hxx_a))] ) m = p.log(m) # Read into function space H_lambda = Function(V) H_lambda.vector().set_local(m) # Output data output = File('hess_py_output.pvd') output << H_lambda
def main(): import optparse from numpy import sum # Parse command line parser = optparse.OptionParser(usage=USAGE) parser.add_option("-p", "--plot", action="store_true", help="Generate pdf with IR-spectrum, broadened with Lorentzian") parser.add_option("-i", "--info", action="store_true", help="Set up/ Calculate vibrations & quit") parser.add_option("-s", "--suffix", action="store", help="Call suffix for binary e.g. 'mpirun -n 4 '", default='') parser.add_option("-r", "--run", action="store", help="path to FHI-aims binary",default='') parser.add_option("-x", "--relax", action="store_true", help="Relax initial geometry") parser.add_option("-m", "--molden", action="store_true", help="Output in molden format") parser.add_option("-w", "--distort", action="store_true", help="Output geometry distorted along imaginary modes") parser.add_option("-t", "--submit", action="store", help="""\ Path to submission script, string <jobname> will be replaced by name + counter, string <outfile> will be replaced by filename""") parser.add_option("-d", "--delta", action="store", type="float", help="Displacement", default=0.0025) parser.add_option("-b", "--broadening", action="store", type="float", help="Broadening for IR-spectrum in cm^{-1}", default=5) options, args = parser.parse_args() if options.info: print __doc__ sys.exit(0) if len(args) != 2: parser.error("Need exactly two arguments") AIMS_CALL=options.suffix+' '+options.run hessian_thresh = -1 name=args[0] mode=args[1] delta=options.delta broadening=options.broadening run_aims=False if options.run!='': run_aims=True submit_script = options.submit is not None if options.plot: import matplotlib as mpl mpl.use('Agg') from pylab import figure if options.plot or mode=='1' or mode=='2': from pylab import savetxt, transpose, eig, argsort, sort,\ sign, pi, dot, sum, linspace, argmin, r_, convolve # Constant from scipy.constants bohr=constants.value('Bohr radius')*1.e10 hartree=constants.value('Hartree energy in eV') at_u=constants.value('atomic mass unit-kilogram relationship') eV=constants.value('electron volt-joule relationship') c=constants.value('speed of light in vacuum') Ang=1.0e-10 hbar=constants.value('Planck constant over 2 pi') Avo=constants.value('Avogadro constant') kb=constants.value('Boltzmann constant in eV/K') pi=constants.pi hessian_factor = eV/(at_u*Ang*Ang) grad_dipole_factor=(eV/(1./(10*c)))/Ang #(eV/Ang -> D/Ang) ir_factor = 1 # Asign all filenames inputgeomerty = 'geometry.in.'+name inputcontrol = 'control.in.'+name atomicmasses = 'masses.'+name+'.dat'; xyzfile = name+'.xyz'; moldenname =name+'.molden'; hessianname = 'hessian.'+name+'.dat'; graddipolename = 'grad_dipole.'+name+'.dat'; irname = 'ir.'+name+'.dat'; deltas=array([-delta,delta]) coeff=array([-1,1]) c_zero = - 1. / (2. * delta) f=open('control.in','r') # read control.in template template_control=f.read() f.close if submit_script: f=open(options.submit,'r') # read submission script template template_job=f.read() f.close folder='' # Dummy ########### Central Point ################################################## if options.relax and (mode=='0' or mode=='2'): # First relax input geometry filename=name+'.out' folder=name+'_relaxation' if not os.path.exists(folder): os.mkdir(folder) # Create folder shutil.copy('geometry.in', folder+'/geometry.in') # Copy geometry new_control=open(folder+'/control.in','w') new_control.write(template_control+'relax_geometry trm 1E-3\n') # Relax! new_control.close() os.chdir(folder) # Change directoy print 'Central Point' if run_aims: os.system(AIMS_CALL+' > '+filename) # Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, 0, filename) os.chdir('..') ############################################################################ # Check for relaxed geometry if os.path.exists(folder+'/geometry.in.next_step'): geometry=open(folder+'/geometry.in.next_step','r') else: geometry=open('geometry.in','r') # Read input geometry n_line=0 struc=structure() lines=geometry.readlines() for line in lines: n_line= n_line+1 if line.rfind('set_vacuum_level')!=-1: # Vacuum Level struc.vacuum_level=float(split_line(line)[-1]) if line.rfind('lattice_vector')!=-1: # Lattice vectors and periodic lat=split_line(line)[1:] struc.lattice_vector=append(struc.lattice_vector,float64(array(lat)) [newaxis,:],axis=0) struc.periodic=True if line.rfind('atom')!=-1: # Set atoms line_vals=split_line(line) at=Atom(line_vals[-1],line_vals[1:-1]) if n_line<len(lines): nextline=lines[n_line] if nextline.rfind('constrain_relaxation')!=-1: # constrained? at=Atom(line_vals[-1],line_vals[1:-1],True) else: at=Atom(line_vals[-1],line_vals[1:-1]) struc.join(at) geometry.close() n_atoms= struc.n() n_constrained=n_atoms-sum(struc.constrained) # Atomic mass file mass_file=open(atomicmasses,'w') mass_vector=zeros([0]) for at_unconstrained in struc.atoms[struc.constrained==False]: mass_vector=append(mass_vector,ones(3)*1./sqrt(at_unconstrained.mass())) line='{0:10.5f}'.format(at_unconstrained.mass()) for i in range(3): line=line+'{0:11.4f}'.format(at_unconstrained.coord[i]) line=line+'{0:}\n'.format(at_unconstrained.kind) mass_file.writelines(line) mass_file.close() # Init dip = zeros([n_constrained*3,3]) hessian = zeros([n_constrained*3,n_constrained*3]) index=0 counter=1 # Set up / Read folders for displaced atoms for atom in arange(n_atoms)[struc.constrained==False]: for coord in arange(3): for delta in deltas: filename=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta)+'.out' folder=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta) if mode=='0' or mode=='2': # Put new geometry and control.in into folder struc_new=copy.deepcopy(struc) struc_new.atoms[atom].coord[coord]=\ struc_new.atoms[atom].coord[coord]+delta geoname='geometry.i_atom_'+str(atom)+'.i_coord_'+str(coord)+\ '.displ_'+str(delta)+'.in' if not os.path.exists(folder): os.mkdir(folder) new_geo=open(folder+'/geometry.in','w') newline='#\n# temporary structure-file for finite-difference '+\ 'calculation of forces\n' newline=newline+'# displacement {0:8.4f} of \# atom '.format(delta)+\ '{0:5} direction {1:5}\n#\n'.format(atom,coord) new_geo.writelines(newline+struc_new.to_str()) new_geo.close() new_control=open(folder+'/control.in','w') template_control=template_control.replace('relax_geometry', '#relax_geometry') new_control.write(template_control+'compute_forces .true. \n'+\ 'final_forces_cleaned '+\ '.true. \n') new_control.close() os.chdir(folder) # Change directoy print 'Processing atom: '+str(atom+1)+'/'+str(n_atoms)+', coord.: '+\ str(coord+1)+'/'+str(3)+', delta: '+str(delta) if run_aims: os.system(AIMS_CALL+' > '+filename)# Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, counter, filename) # os.system('qsub job.sh') # Mind the environment variables os.chdir('..') if mode=='1' or mode=='2': # Read output forces_reached=False atom_count=0 data=open(folder+'/'+filename) for line in data.readlines(): if line.rfind('Dipole correction potential jump')!=-1: dip_jump = float(split_line(line)[-2]) # Periodic if line.rfind('| Total dipole moment [eAng]')!=-1: dip_jump = float64(split_line(line)[-3:]) # Cluster if forces_reached and atom_count<n_atoms: # Read Forces struc.atoms[atom_count].force=float64(split_line(line)[2:]) atom_count=atom_count+1 if atom_count==n_atoms: forces_reached=False if line.rfind('Total atomic forces')!=-1: forces_reached=True data.close() if struc.periodic: pass #dip[index,2]=dip[index,2]+dip_jump*coeff[deltas==delta]*c_zero else: dip[index,:]=dip[index,:]+dip_jump*coeff[deltas==delta]*c_zero forces=array([]) for at_unconstrained in struc.atoms[struc.constrained==False]: forces=append(forces,coeff[deltas==delta]*at_unconstrained.force) hessian[index,:]=hessian[index,:]+forces*c_zero counter=counter+1 index=index+1 if mode=='1' or mode=='2': # Calculate vibrations print 'Entering hessian diagonalization' print 'Number of atoms = '+str(n_atoms) print 'Name of Hessian input file = '+hessianname print 'Name of grad dipole input file = '+graddipolename print 'Name of Masses input file = '+atomicmasses print 'Name of XYZ output file = '+xyzfile print 'Threshold for Matrix elements = '+str(hessian_thresh) if (hessian_thresh < 0.0): print ' All matrix elements are taken'+\ ' into account by default\n' savetxt(hessianname,hessian) savetxt(graddipolename,dip) mass_mat=mass_vector[:,newaxis]*mass_vector[newaxis,:] hessian[abs(hessian)<hessian_thresh]=0.0 hessian=hessian*mass_mat*hessian_factor hessian=(hessian+transpose(hessian))/2. # Diagonalize hessian (scipy) print 'Solving eigenvalue system for Hessian Matrix' freq, eig_vec = eig(hessian) print 'Done ... ' eig_vec=eig_vec[:,argsort(freq)] freq=sort(sign(freq)*sqrt(abs(freq))) ZPE=hbar*(freq)/(2.0*eV) freq = (freq)/(200.*pi*c) grad_dipole = dip * grad_dipole_factor eig_vec = eig_vec*mass_vector[:,newaxis]*ones(len(mass_vector))[newaxis,:] infrared_intensity = sum(dot(transpose(grad_dipole),eig_vec)**2,axis=0)*\ ir_factor reduced_mass=sum(eig_vec**2,axis=0) norm = sqrt(reduced_mass) eig_vec = eig_vec/norm # The rest is output, xyz, IR,... print 'Results\n' print 'List of all frequencies found:' print 'Mode number Frequency [cm^(-1)] Zero point energy [eV] '+\ 'IR-intensity [D^2/Ang^2]' for i in range(len(freq)): print '{0:11}{1:25.8f}{2:25.8f}{3:25.8f}'.format(i+1,freq[i],ZPE[i], infrared_intensity[i]) print '\n' print 'Summary of zero point energy for entire system:' print '| Cumulative ZPE = {0:15.8f} eV'.format(sum(ZPE)) print '| without first six eigenmodes = {0:15.8f} eV\n'.format(sum(ZPE)- sum(ZPE[:6])) print 'Stability checking - eigenvalues should all be positive for a '+\ 'stable structure. ' print 'The six smallest frequencies should be (almost) zero:' string='' for zz in ZPE[:6]: string=string+'{0:25.8f}'.format(zz) print string print 'Compare this with the largest eigenvalue, ' print '{0:25.8f}'.format(freq[-1]) nums=arange(n_atoms)[struc.constrained==False] nums2=arange(n_atoms)[struc.constrained] newline='' newline_ir='[INT]\n' if options.molden: newline_molden='[Molden Format]\n[GEOMETRIES] XYZ\n' newline_molden=newline_molden+'{0:6}\n'.format(n_atoms)+'\n' for i_atoms in range(n_constrained): newline_molden=newline_molden+'{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden=newline_molden+'{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) newline_molden=newline_molden+'\n' newline_molden=newline_molden+'[FREQ]\n' for i in range(len(freq)): newline_molden=newline_molden+'{0:10.3f}\n'.format(freq[i]) newline_molden=newline_molden+'[INT]\n' for i in range(len(freq)): newline_molden=newline_molden+'{0:17.6e}\n'.format( infrared_intensity[i]) newline_molden=newline_molden+'[FR-COORD]\n' newline_molden=newline_molden+'{0:6}\n'.format(n_atoms)+'\n' for i_atoms in range(n_constrained): newline_molden=newline_molden+'{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden=newline_molden+'{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]/bohr) newline_molden=newline_molden+'\n' newline_molden=newline_molden+'[FR-NORM-COORD]\n' for i in range(len(freq)): newline=newline+'{0:6}\n'.format(n_atoms) if freq[i]>0: newline=newline+'stable frequency at ' elif freq[i]<0: newline=newline+'unstable frequency at ' if options.distort and freq[i]<-50: struc_new=copy.deepcopy(struc) for i_atoms in range(n_constrained): for i_coord in range(3): struc_new.atoms[i_atoms].coord[i_coord]=\ struc_new.atoms[i_atoms].coord[i_coord]+\ eig_vec[(i_atoms)*3+i_coord,i] geoname=name+'.distorted.vibration_'+str(i+1)+'.geometry.in' new_geo=open(geoname,'w') newline_geo='#\n# distorted structure-file for based on eigenmodes\n' newline_geo=newline_geo+\ '# vibration {0:5} :{1:10.3f} 1/cm\n#\n'.format(i+1,freq[i]) new_geo.writelines(newline_geo+struc_new.to_str()) new_geo.close() elif freq[i]==0: newline=newline+'translation or rotation ' newline=newline+'{0:10.3f} 1/cm IR int. is '.format(freq[i]) newline=newline+'{0:10.4e} D^2/Ang^2; red. mass is '.format( infrared_intensity[i]) newline=newline+'{0:5.3f} a.m.u.; force const. is '.format( 1.0/reduced_mass[i]) newline=newline+'{0:5.3f} mDyne/Ang.\n'.format(((freq[i]*(200*pi*c))**2)* (1.0/reduced_mass[i])*at_u*1.e-2) if options.molden: newline_molden=newline_molden+\ 'vibration {0:6}\n'.format(i+1) for i_atoms in range(n_constrained): newline=newline+'{0:6}'.format(struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline=newline+'{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) for i_coord in range(3): newline=newline+'{0:10.4f}'.format(eig_vec[(i_atoms)*3+i_coord,i]) if options.molden: newline_molden=newline_molden+'{0:10.4f}'.format( eig_vec[(i_atoms)*3+i_coord,i]/bohr) newline=newline+'\n' if options.molden: newline_molden=newline_molden+'\n' for i_atoms in range(n_atoms-n_constrained): newline=newline+'{0:6}'.format(struc.atoms[nums2[i_atoms]].kind) for i_coord in range(3): newline=newline+'{0:10.4f}'.format( struc.atoms[nums2[i_atoms]].coord[i_coord]) for i_coord in range(3): newline=newline+'{0:10.4f}'.format(0.0) newline=newline+'\n' newline_ir=newline_ir+'{0:10.4e}\n'.format(infrared_intensity[i]) xyz=open(xyzfile,'w') xyz.writelines(newline) xyz.close() ir=open(irname,'w') ir.writelines(newline_ir) ir.close() if options.molden: molden=open(moldenname,'w') molden.writelines(newline_molden) molden.close() if (mode=='1' or mode=='2') and options.plot: x=linspace(freq.min()-500,freq.max()+500,1000) z=zeros(len(x)) for i in range(len(freq)): z[argmin(abs(x-freq[i]))]=infrared_intensity[i] window_len=150 lorentzian=lorentz(pi,broadening,arange(250))#signal.gaussian(window_len,broadening) s=r_[z[window_len-1:0:-1],z,z[-1:-window_len:-1]] z_convolve=convolve(lorentzian/lorentzian.sum(),s,mode='same')[ window_len-1:-window_len+1] fig=figure(0) ax=fig.add_subplot(111) ax.plot(x,z_convolve,'r',lw=2) ax.set_xlim([freq.min()-500,freq.max()+500]) ax.set_ylim([-0.01,ax.get_ylim()[1]]) ax.set_yticks([]) ax.set_xlabel('Frequency [1/cm]',size=20) ax.set_ylabel('Intensity [a.u.]',size=20) fig.savefig(name+'_IR_spectrum.pdf') print '\n Done. '
def ellfit(x, y, wt=None): import pylab as pl # Calculate the best fit ellipse for an X and Y distribution, allowing # for weighting. # OUTPUTS: # MAJOR - major axis in same units as x and y # MINOR - minor axis in same units as x and y # POSANG - the position angle CCW from the X=0 line of the coordinates # # Adam: The intensity weighted major and minor values are equal to the # second moment. # For equal weighting by pixel (of the sort that # might be done for blob analysis) the ellipse fit to the # half-maximum area will have semimajor axis equal to 1./1.69536 the # second moment. For the quarter maximum surface this is 1./1.19755. # # i.e. if you run this with x,y down to zero intensity (like integrating # to infinity), and wt=intensity, you get the second moments sig_major, # sig_minor back # if you run this with x,y down to half-intensity, and wt=None, you get # sigx/1.6986 back (not sure why my integra differs from his slightly) # # but adam did not have the factor of 4 to turn eigenval into major axis # # translation: if we run this with intensity weight, we get # the second moment back (a sigma). for flat weights i think he means # the halfmax contour semimajor axis if type(wt) == type(None): wt = x * 0.0 + 1.0 tot_wt = wt.sum() # WEIGHTED X AND Y CENTERS x_ctr = (wt * x).sum() / tot_wt y_ctr = (wt * y).sum() / tot_wt # BUILD THE MATRIX i11 = (wt * (x - x_ctr)**2).sum() / tot_wt i22 = (wt * (y - y_ctr)**2).sum() / tot_wt i12 = (wt * (x - x_ctr) * (y - y_ctr)).sum() / tot_wt mat = [[i11, i12], [i12, i22]] # CATCH THE CASE OF ZERO DETERMINANT if pl.det(mat) == 0: return pl.nan, pl.nan, pl.nan if pl.any(pl.isnan(mat)): return pl.nan, pl.nan, pl.nan # WORK OUT THE EIGENVALUES evals, evec = pl.eig(mat) # PICK THE MAJOR AXIS absvals = pl.absolute(evals) major = absvals.max() maj_ind = pl.where(absvals == major)[0][0] major_vec = evec[maj_ind] min_ind = 1 - maj_ind # WORK OUT THE ORIENTATION OF THE MAJOR AXIS posang = pl.arctan2(major_vec[1], major_vec[0]) # compared to the original idl code, this code is returning # pi-the desired angle, so: # posang=pl.pi-posang # if posang<0: posang = posang+pl.pi # MAJOR AND MINOR AXIS SIZES # turn into real half-max major/minor axis major = pl.sqrt(evals[maj_ind]) * 4. minor = pl.sqrt(evals[min_ind]) * 4. return major, minor, posang
def get_edge_errors(self): """ Calculates the error estimates of the expression projected into the mesh. :rtype: Dolfin edge function containing the edge errors of the mesh """ mesh = self.mesh coord = mesh.coordinates() V = FunctionSpace(mesh, "CG", 1) Hxx = TrialFunction(V) Hxy = TrialFunction(V) Hyy = TrialFunction(V) phi = TestFunction(V) edge_errors = EdgeFunction('double', mesh) U = project(self.U_ex, V) a_xx = Hxx * phi * dx L_xx = -U.dx(0) * phi.dx(0) * dx a_xy = Hxy * phi * dx L_xy = -U.dx(0) * phi.dx(1) * dx a_yy = Hyy * phi * dx L_yy = -U.dx(1) * phi.dx(1) * dx Hxx = Function(V) Hxy = Function(V) Hyy = Function(V) Mxx = Function(V) Mxy = Function(V) Myy = Function(V) solve(a_xx == L_xx, Hxx) solve(a_xy == L_xy, Hxy) solve(a_yy == L_yy, Hyy) e_list = [] for v in vertices(mesh): idx = v.index() pt = v.point() x = pt.x() y = pt.y() a = Hxx(x, y) b = Hxy(x, y) d = Hyy(x, y) H_local = ([[a, b], [b, d]]) l, ve = pl.eig(H_local) M = pl.dot(pl.dot(ve, abs(pl.diag(l))), ve.T) Mxx.vector()[idx] = M[0, 0] Mxy.vector()[idx] = M[1, 0] Myy.vector()[idx] = M[1, 1] e_list = [] for e in edges(mesh): I, J = e.entities(0) x_I = coord[I, :] x_J = coord[J, :] M_I = pl.array([[Mxx.vector()[I], Mxy.vector()[I]], [Mxy.vector()[I], Myy.vector()[I]]]) M_J = pl.array([[Mxx.vector()[J], Mxy.vector()[J]], [Mxy.vector()[J], Myy.vector()[J]]]) M = (M_I + M_J) / 2. dX = x_I - x_J error = pl.dot(pl.dot(dX, M), dX.T) e_list.append(error) edge_errors[e] = error return edge_errors
hessian = [ \ [ 4.31555686e+27, -8.12601299e+07, -1.50721747e+21, -2.24466888e+27, \ -6.40887956e+07, 6.64242815e+20], \ [ -8.12601299e+07, 4.31555537e+27, 1.33622795e+21, 1.73705009e+08, \ -2.24467067e+27, -7.89181980e+20], \ [ -1.50721747e+21, 1.33622795e+21, 1.00924243e+29, 5.49874236e+20, \ -8.30018741e+20, -6.64344894e+28], \ [ -2.24466888e+27, 1.73705009e+08, 5.49874236e+20, 1.16750303e+27, \ -3.54607612e+07, -5.54914332e+20], \ [ -6.40887956e+07, -2.24467067e+27, - 8.30018741e+20, -3.54607612e+07, \ 1.16750530e+27, 2.98894228e+20], \ [ 6.64242815e+20, -7.89181980e+20, -6.64344894e+28, -5.54914332e+20, \ 2.98894228e+20, 6.01133870e+28] \ ] print 'Solving eigenvalue system for Hessian Matrix' freq, eig_vec = eig(hessian) freq=sort(sign(freq)*sqrt(abs(freq))) freq = (freq)/(200.*pi*c) print 'Done ... ' print(freq) for i in range(6): for j in range(6): if(abs(hessian[i][j])<1e+28): hessian[i][j] = 0.0 freq, eig_vec = eig(hessian) freq=sort(sign(freq)*sqrt(abs(freq))) freq = (freq)/(200.*pi*c) print(freq)