def get_mullpop_and_charge(self): ################################################################################ # This function assumes that the alpha spin is the majority spin and beta is # # minority. Takes a while to calculate each separately. # ################################################################################ self.qc_alpha = read.main_read(self.moldenpath, itype='molden', spin='alpha') self.qc_beta = read.main_read(self.moldenpath, itype='molden', spin='beta') self.pop = atomic_populations.mulliken(self.qc) self.pop_alpha = atomic_populations.mulliken(self.qc_alpha) self.pop_beta = atomic_populations.mulliken(self.qc_beta) self.spinpop = [] self.alphapop = [] self.betapop = [] self.charge = [] metallist = ['mn', 'cr', 'co', 'ni', 'fe'] for idx, val in enumerate(self.qc.geo_info): if val[0].lower() in metallist: self.metalpopalpha = self.pop_alpha['population'][idx] self.metalpopbeta = self.pop_beta['population'][idx] self.metalcharge = self.pop['charge'][idx] self.spinpop.append( (val[0].capitalize(), self.pop_alpha['population'][idx] - self.pop_beta['population'][idx])) self.alphapop.append( (val[0].capitalize(), self.pop_alpha['population'][idx])) self.betapop.append( (val[0].capitalize(), self.pop_beta['population'][idx])) self.charge.append((val[0].capitalize(), self.pop['charge'][idx])) self.oxygenpopalpha = self.pop_alpha['population'][-1] self.oxygenpopbeta = self.pop_beta['population'][-1] self.oxygencharge = self.pop['charge'][-1] self.totalspin = sum(self.pop_alpha['population'] - self.pop_beta['population']) self.totalcharge = sum(self.pop['charge']) print(('Spin: ', self.totalspin)) print(('Charge: ', self.totalcharge)) print((self.pop['charge'])) print(('Metal: ', self.metalcharge, 'Oxygen: ', self.oxygencharge)) return self.totalspin, self.totalcharge, self.metalcharge, self.metalpopalpha, self.metalpopbeta, self.oxygencharge, self.oxygenpopalpha, self.oxygenpopbeta #EXAMPLE # moldenpath = '/Users/adityanandy/Desktop/catalysis.molden' # my_df_final = MoldenInfo(moldenpath) # my_df_final.get_MO_energies() # my_df_final.get_all_orbital_d_character() # my_df_final.plot_dchar_vs_energies()
Ampere = 0.006623619 # Set some options numproc = 4 slice_length = 1e2 ci_readthreshold = 0.0 print(''' ========================================== Reading the Quantum Chemistry Output Files ========================================== ''') # 1a. fid_psi4 = 'psi4_data/lih_cis_aug-cc-pVTZ.out' fid_molden = fid_psi4 + '.default.molden' qc = read.main_read(fid_molden, all_mo=True, interactive=False) qc, ci = detci.ci_read.main_ci_read(qc, fid_psi4, itype='psi4_detci', threshold=ci_readthreshold) print('=' * 80) print('Preparing All Subsequent Calculations') print('=' * 80 + '\n') # 1b. print('Setting up the grid...') grid.min_ = [-3.9, 0.0, -5.9] grid.max_ = [3.9, 0.0, 9.9] grid.delta_ = [0.2, 0.0, 0.2] grid.grid_init() print(grid.get_grid())
import numpy from orbkit import read, options from orbkit import libcint_interface as integrals from orbkit.test.tools import equal import os, inspect tests_home = os.path.dirname(inspect.getfile(inspect.currentframe())) options.quiet = True ## N2 cc-pVDZ RHF folder = os.path.join(tests_home, '../outputs_for_testing/molpro') qc = read.main_read(os.path.join(folder, 'n2.mold'), all_mo=True) ao = integrals.AOIntegrals(qc) Nelec = int(abs(qc.get_charge(nuclear=False))) # MO overlap S = ao.overlap(asMO=1) equal(S, numpy.eye(ao.Norb)) # calculate Hartree-Fock energy from AOs Hcore = ao.Hcore(asMO=0) Vee = ao.Vee(asMO=0) Vnn = qc.nuclear_repulsion P = 2*numpy.dot(qc.mo_spec.coeffs[:Nelec//2,:].T, qc.mo_spec.coeffs[:Nelec//2,:]) G = P[None,None,:,:]*Vee - numpy.swapaxes(0.5*P.T[None,:,:,None]*Vee, 1, 3) G = numpy.sum(G, axis=(2, 3)) F = Hcore + G E = 0.5*numpy.tensordot(P, Hcore+F, axes=2)
def run_orbkit(use_qc=None, check_options=True, standalone=False): '''Controls the execution of all computational tasks. **Parameters:** use_qc : QCinfo, optional If not None, the reading of a quantum chemistry output is omitted and the given QCinfo class is used for all computational tasks. (See :ref:`Central Variables` in the manual for details on QCinfo.) check_options : bool, optional If True, the specified options will be validated. **Returns:** data : type and shape depend on the options. Contains orbkit's output. See :ref:`High-Level Interface` in the manual for details. ''' # Set some global variables global qc # Display program information display(lgpl_short) # Check for the correctness of orbkit.options if check_options: display('Checking orbkit.options...\n') options.check_options(display=display, interactive=False, info=True, check_io=(use_qc is None)) # Measurement of required execution time t = [time.time()] # Do we need to read out the info of all MOs? if (options.mo_set or options.calc_mo) is not False: options.all_mo = True if use_qc is None: # Read the input file qc = read.main_read(options.filename, itype=options.itype, all_mo=options.all_mo, spin=options.spin, cclib_parser=options.cclib_parser) else: # Use a user defined QCinfo class. qc = use_qc display('\nSetting up the grid...') if options.grid_file is not None: # Read the grid from an external file grid.read(options.grid_file) elif options.adjust_grid is not None: # Adjust the grid to geo_spec extend, step = options.adjust_grid grid.adjust_to_geo(qc, extend=extend, step=step) elif options.random_grid: # Create a randomized grid grid.random_grid(qc.geo_spec) # Initialize grid grid.grid_init(is_vector=options.is_vector) if options.is_vector: grid.is_regular = False display(grid.get_grid()) # Display the grid if not grid.is_regular and options.center_grid is not None: raise IOError( 'The option --center is only supported for regular grids.') elif options.center_grid is not None: atom = grid.check_atom_select(options.center_grid, qc.geo_info, qc.geo_spec, interactive=True, display=display) # Center the grid to a specific atom and (0,0,0) if requested grid.center_grid(qc.geo_spec[atom - 1], display=display) if check_options or standalone: options.check_grid_output_compatibilty() t.append(time.time()) # A new time step # The calculation of all AOs (--calc_ao) if options.calc_ao != False: data = extras.calc_ao(qc, drv=options.drv, otype=options.otype) t.append(time.time()) # Final time good_bye_message(t) return data # The calculation of selected MOs (--calc_mo) or # the density formed by selected MOs (--mo_set) if (options.mo_set or options.calc_mo) != False: # What should the program do? if options.calc_mo != False: fid_mo_list = options.calc_mo elif options.mo_set != False: fid_mo_list = options.mo_set # Call the function for actual calculation if options.calc_mo != False: data = extras.calc_mo(qc, fid_mo_list, drv=options.drv, otype=options.otype) elif options.mo_set != False: data = extras.mo_set(qc, fid_mo_list, drv=options.drv, laplacian=options.laplacian, otype=options.otype) t.append(time.time()) # Final time good_bye_message(t) return data if options.gross_atomic_density is not None: atom = options.gross_atomic_density rho_atom = extras.numerical_mulliken_charges(atom, qc) if not grid.is_vector: mulliken_num = rho_atom[1] rho_atom = rho_atom[0] if not options.no_output: fid = '%s.h5' % options.outputname display('\nSaving to Hierarchical Data Format file (HDF5)...' + '\n\t%(o)s' % {'o': fid}) output.hdf5_write(fid, mode='w', gname='', atom=core.numpy.array(atom), geo_info=qc.geo_info, geo_spec=qc.geo_spec, gross_atomic_density=rho_atom, x=grid.x, y=grid.y, z=grid.z) if not options.is_vector: output.hdf5_write( fid, mode='a', gname='/numerical_mulliken_population_analysis', **mulliken_num) t.append(time.time()) good_bye_message(t) return rho_atom if options.mo_tefd is not None: mos = options.mo_tefd ao_list = core.ao_creator(qc.geo_spec, qc.ao_spec) mo_tefd = [] index = [] for i, j in mos: mo_tefd.append([]) index.append([]) for ii_d in options.drv: display('\nMO-TEFD: %s->%s %s-component' % (i, j, ii_d)) tefd = extras.mo_transition_flux_density(i, j, qc, drv=ii_d, ao_list=ao_list) mo_tefd[-1].append(tefd) index[-1].append('%s->%s:%s' % (i, j, ii_d)) if not options.no_output: from numpy import array fid = '%s.h5' % options.outputname display('\nSaving to Hierarchical Data Format file (HDF5)...' + '\n\t%(o)s' % {'o': fid}) HDF5_File = output.hdf5_open(fid, mode='w') data = { 'geo_info': array(qc.geo_info), 'geo_spec': array(qc.geo_spec), 'mo_tefd:info': array(index), 'mo_tefd': array(mo_tefd), 'x': grid.x, 'y': grid.y, 'z': grid.z } output.hdf5_append(data, HDF5_File, name='') HDF5_File.close() t.append(time.time()) good_bye_message(t) return mo_tefd t.append(time.time()) # A new time step # Compute the (derivative of the) electron density if options.no_slice: data = core.rho_compute_no_slice(qc, drv=options.drv, laplacian=options.laplacian, return_components=False) else: data = core.rho_compute(qc, drv=options.drv, slice_length=options.slice_length, laplacian=options.laplacian, numproc=options.numproc) if options.drv is None: rho = data elif options.laplacian: rho, delta_rho, laplacian_rho = data else: rho, delta_rho = data # Compute the reduced electron density if requested if options.z_reduced_density: if grid.is_vector: display('\nSo far, reducing the density is not supported for ' + 'vector grids.\nSkipping the reduction...\n') elif options.drv is not None: display( '\nSo far, reducing the density is not supported for ' + 'the derivative of the density.\nSkipping the reduction...\n') else: from scipy import integrate display('\nReducing the density with respect to the z-axis.\n') rho = integrate.simps(rho, grid.x, dx=grid.delta_[0], axis=0, even='avg') rho = integrate.simps(rho, grid.y, dx=grid.delta_[1], axis=0, even='avg') t.append(time.time()) # A new time step # Generate the output requested if not options.no_output: output_written = output.main_output(rho, qc.geo_info, qc.geo_spec, outputname=options.outputname, otype=options.otype, data_id='rho', omit=['vmd', 'mayavi'], mo_spec=qc.mo_spec) if options.drv is not None: output_written.extend( output.main_output(delta_rho, qc.geo_info, qc.geo_spec, outputname=options.outputname, otype=options.otype, data_id='delta_rho', omit=['vmd', 'mayavi'], mo_spec=qc.mo_spec, drv=options.drv)) if options.laplacian: output_written.extend( output.main_output(laplacian_rho, qc.geo_info, qc.geo_spec, outputname=options.outputname + '_laplacian', otype=options.otype, data_id='laplacian_rho', omit=['vmd', 'mayavi'], mo_spec=qc.mo_spec)) if 'vmd' in options.otype: # Create VMD network display('\nCreating VMD network file...' + '\n\t%(o)s.vmd' % {'o': options.outputname}) cube_files = [] for i in output_written: if i.endswith('.cb'): cube_files.append(i) output.vmd_network_creator(options.outputname, cube_files=cube_files) t.append(time.time()) # Final time good_bye_message(t) if 'mayavi' in options.otype: plt_data = [rho] datalabels = ['rho'] if options.drv is not None: plt_data.extend(delta_rho) datalabels.extend( ['d/d%s of %s' % (ii_d, 'rho') for ii_d in options.drv]) if options.laplacian: plt_data.append(laplacian_rho) datalabels.append('laplacian of rho') output.main_output(plt_data, qc.geo_info, qc.geo_spec, otype='mayavi', datalabels=datalabels) # Return the computed data, i.e., rho for standard, and (rho,delta_rho) # for derivative calculations. For laplacian (rho,delta_rho,laplacian_rho) return data
.. math:: <\phi_k|z|\phi_l> = \int dxdydz (z - Z_k)^{k_z} e^{\alpha_k r_k^2} (z - Z_l)^{l_z+1} e^{\alpha_l r_l^2} + Z_l \int dxdydz (z - Z_k)^{k_z} e^{\alpha_k r_k^2} (z - Z_l)^{l_z} e^{\alpha_l r_l^2} = ao_part_1 + ao_part_2 with :math:`r_l = \sqrt{(x-X_l)^2 + (y-Y_l)^2 + (z - Z_l)^2)}` ''' from orbkit.read import main_read from orbkit.tools import * from orbkit.analytical_integrals import get_ao_overlap, get_mo_overlap, print2D in_fid = 'h2o.molden' # Read the input file qc = main_read(in_fid, itype='molden', all_mo=False) # Compute atomic orbital overlap matrix ao_overlap_matrix = get_ao_overlap(qc.geo_spec, qc.geo_spec, qc.ao_spec) # Compute the overlap of the molecular orbitals and weight it with the occupation number electron_number = 0. for i_mo in qc.mo_spec: electron_number += i_mo['occ_num'] * get_mo_overlap( i_mo['coeffs'], i_mo['coeffs'], ao_overlap_matrix) print('The total number of electrons is %.8f' % electron_number) # Compute the x-, y-, and z-component of the dipole moment dipole_moment = [] for component in range(3):
with open(filename, "r") as f: lines1 = f.readlines() for line in lines1: if num == 0: lines.append(line.lstrip()) elif num == 1: lines.append(line) if pattern in line: num = 1 f.close() filename2 = "RPA_S" + ".molden" with open(filename2, "w") as f: f.writelines(lines) f.close() qc = read.main_read(filename2, all_mo=True) orbkit.init() orbkit.options.quiet = True orbkit.options.no_log = True orbkit.options.calc_mo = [1] orbkit.options.filename = filename2 orbkit.options.adjust_grid = [5, 0.5] data = orbkit.run_orbkit() xl = numpy.amin(orbkit.grid.x) yl = numpy.amin(orbkit.grid.y) zl = numpy.amin(orbkit.grid.z) xh = numpy.amax(orbkit.grid.x) yh = numpy.amax(orbkit.grid.y) zh = numpy.amax(orbkit.grid.z) eig = [sub['energy'] for sub in qc.mo_spec] fdim = len(qc.mo_spec) / 2
''' This script shows how to implement a new grid based quantity. Here, we implement the reduced density gradient as proposed by Johnson et al., J. Am. Chem. Soc. 132, 6498 (2010). ''' from orbkit import read, grid, display, core, output ''' Identify the non-covalent interaction regions using the reduced density gradient ''' # open molden file and read parameters qc = read.main_read('h2o_dimer.molden',itype='molden') # Adjust the grid parameters to the molecular structure grid.adjust_to_geo(qc,extend=1.0,step=0.1) # initialize grid grid.grid_init() # print grid information display.display(grid.get_grid()) # Run orbkit rho,delta_rho = core.rho_compute(qc,drv=['x','y','z'],numproc=4) # Compute the reduced density gradient from numpy import sqrt,pi s = (1./(2*(3*pi**2)**(1/3.)) * sqrt((delta_rho**2).sum(axis=0))/(rho**(4/3.)))
def __init__(self, moldenpath): self.moldenpath = moldenpath # print('Now Analyzing: ', moldenpath) self.qc = read.main_read(self.moldenpath, itype='molden')
import numpy from orbkit import read from orbkit import libcint_interface as integrals from orbkit import options from orbkit.test.tools import equal import os, inspect tests_home = os.path.dirname(inspect.getfile(inspect.currentframe())) options.quiet = True ## NH3 STO-3G RHF folder = os.path.join(tests_home, '../outputs_for_testing') qc = read.main_read(os.path.join(folder, 'molpro/nh3.mold'), all_mo=True) Nelec = int(abs(qc.get_charge(nuclear=False))) ao = integrals.AOIntegrals(qc) ## test basic 1- and 2-electron integrals S = ao.overlap(asMO=0) S_mo = ao.overlap(asMO=1) T = ao.kinetic(asMO=0) V = ao.Vne(asMO=0) Vee = ao.Vee(asMO=0) Vee_mo = ao.Vee(asMO=1) ref = numpy.load(os.path.join(tests_home, 'nh3.npz')) equal(S, ref['S']) equal(S_mo, numpy.eye(ao.Norb)) equal(T, ref['T']) equal(V, ref['V'])
def run_orbkit(use_qc=None,check_options=True,standalone=False): '''Controls the execution of all computational tasks. **Parameters:** use_qc : QCinfo, optional If not None, the reading of a quantum chemistry output is omitted and the given QCinfo class is used for all computational tasks. (See :ref:`Central Variables` in the manual for details on QCinfo.) check_options : bool, optional If True, the specified options will be validated. **Returns:** data : type and shape depend on the options. Contains orbkit's output. See :ref:`High-Level Interface` in the manual for details. ''' # Set some global variables global qc # Display program information display(lgpl_short) # Check for the correctness of orbkit.options if check_options: display('Checking orbkit.options...\n') options.check_options(display=display, interactive=False, info=True,check_io=(use_qc is None)) # Measurement of required execution time t=[time.time()] # Do we need to read out the info of all MOs? if (options.mo_set or options.calc_mo) is not False: options.all_mo = True if use_qc is None: # Read the input file qc = read.main_read(options.filename, itype=options.itype, all_mo=options.all_mo, spin=options.spin, cclib_parser=options.cclib_parser) else: # Use a user defined QCinfo class. qc = use_qc if 'native' in options.otype: output.main_output(qc, outputname=options.outputname, otype='native', ftype=options.niotype) options.otype.remove('native') if not len(options.otype): t.append(time.time()) # Final time good_bye_message(t) return display('\nSetting up the grid...') if options.grid_file is not None: # Read the grid from an external file grid.read(options.grid_file) elif options.adjust_grid is not None: # Adjust the grid to geo_spec extend,step = options.adjust_grid grid.adjust_to_geo(qc,extend=extend,step=step) elif options.random_grid: # Create a randomized grid grid.random_grid(qc.geo_spec) # Initialize grid grid.grid_init(is_vector=options.is_vector) if options.is_vector: grid.is_regular = False display(grid.get_grid()) # Display the grid if not grid.is_regular and options.center_grid is not None: raise IOError('The option --center is only supported for regular grids.') elif options.center_grid is not None: atom = grid.check_atom_select(options.center_grid,qc.geo_info,qc.geo_spec, interactive=True,display=display) # Center the grid to a specific atom and (0,0,0) if requested grid.center_grid(qc.geo_spec[atom-1],display=display) if check_options or standalone: options.check_grid_output_compatibilty() t.append(time.time()) # A new time step # The calculation of all AOs (--calc_ao) if options.calc_ao != False: data = extras.calc_ao(qc, drv=options.drv, otype=options.otype) t.append(time.time()) # Final time good_bye_message(t) return data # The calculation of selected MOs (--calc_mo) or # the density formed by selected MOs (--mo_set) if (options.mo_set or options.calc_mo) != False: # What should the program do? if options.calc_mo != False: fid_mo_list = options.calc_mo elif options.mo_set != False: fid_mo_list = options.mo_set # Call the function for actual calculation if options.calc_mo != False: data = extras.calc_mo(qc, fid_mo_list, drv=options.drv, otype=options.otype) elif options.mo_set != False: data = extras.mo_set(qc, fid_mo_list, drv=options.drv, laplacian=options.laplacian, otype=options.otype) t.append(time.time()) # Final time good_bye_message(t) return data if options.gross_atomic_density is not None: rho_atom = extras.gross_atomic_density(options.gross_atomic_density,qc, drv=options.drv) if not options.no_output: output_written = output.main_output(rho_atom, qc, outputname=options.outputname, otype=options.otype) t.append(time.time()) good_bye_message(t) return rho_atom t.append(time.time()) # A new time step # Compute the (derivative of the) electron density if options.no_slice: data = core.rho_compute_no_slice(qc, drv=options.drv, laplacian=options.laplacian, return_components = False) else: data = core.rho_compute(qc, drv=options.drv, slice_length=options.slice_length, laplacian=options.laplacian, numproc=options.numproc) if options.drv is None: rho = data elif options.laplacian: rho, delta_rho, laplacian_rho = data else: rho, delta_rho = data t.append(time.time()) # A new time step # Generate the output requested if not options.no_output: if not (options.drv is not None or options.laplacian): plt_data = rho datalabels = 'rho' else: plt_data = [rho] datalabels = ['rho'] if options.drv is not None: plt_data.extend(delta_rho) datalabels.extend(['d/d%s of %s' % (ii_d,'rho') for ii_d in options.drv]) if options.laplacian: plt_data.append(laplacian_rho) datalabels.append('laplacian of rho') output.main_output(plt_data,qc,outputname=options.outputname, otype=options.otype,datalabels=datalabels) t.append(time.time()) # Final time good_bye_message(t) # Return the computed data, i.e., rho for standard, and (rho,delta_rho) # for derivative calculations. For laplacian (rho,delta_rho,laplacian_rho) return data
from enthought.mayavi import mlab except ImportError: from mayavi import mlab # Name of input and output files fid_in = 'h2+.molden' # Choose the molecular orbitals to be calculated selected_MO = ['1.1_a', '1.5_a'] # number of processes and points per process numproc = 2 slice_length = 1e4 # Open molden file and read parameters qc = read.main_read(fid_in, itype='molden', all_mo=True) # Set grid parameters grid.adjust_to_geo(qc, extend=5.0, step=0.5) # Initialize grid grid.grid_init() # Print grid information display.display(grid.get_grid()) # Choose the molecular orbitals to be calculated selected_MO = ['1.1_a', '1.5_a'] qc.mo_spec = read.mo_select(qc.mo_spec, selected_MO, strict=True)['mo_spec'] # Calculate molecular orbitals mo_list = core.rho_compute(qc, calc_mo=True,
import numpy import os, inspect from orbkit import read from orbkit.core import rho_compute from orbkit.test.tools import equal from orbkit import grid from orbkit import options options.quiet = True tests_home = os.path.dirname(inspect.getfile(inspect.currentframe())) folder = os.path.join(tests_home, '../outputs_for_testing/molpro') filepath = os.path.join(folder, 'h2o_rhf_sph.molden') qc = read.main_read(filepath, all_mo=True) grid.adjust_to_geo(qc, extend=2.0, step=1) grid.grid_init(is_vector=False, force=True) drv = [None, 'x', 'y', 'z', 'xx', 'xy', 'xz', 'yy', 'yz', 'zz'] data = [] for i in range(2): if i: grid.grid2vector() data.append([ rho_compute(qc, slice_length=0), rho_compute(qc, numproc=options.numproc), rho_compute(qc, laplacian=True, slice_length=0)[-1], rho_compute(qc, laplacian=True, numproc=options.numproc)[-1], rho_compute(qc, calc_mo=True, drv=drv, slice_length=0), rho_compute(qc, calc_mo=True, drv=drv, numproc=options.numproc) ])
from orbkit import options from orbkit import units options.quiet = True dx = 4.970736 grid.x = numpy.arange(3) * dx - 4.970736 grid.y = numpy.arange(3) * dx - 4.970736 grid.z = numpy.arange(3) * dx - 4.732975 grid.is_initialized = True grid.is_regular = True grid.is_vector = False tests_home = os.path.dirname(inspect.getfile(inspect.currentframe())) folder = os.path.join(tests_home, '../outputs_for_testing/gaussian') filepath = os.path.join(folder, 'h2o_rhf_sph.fchk') qc = read.main_read(filepath, all_mo=False) rho, delta_rho = rho_compute(qc, drv='xyz') rho2, delta_rho2, laplacian = rho_compute(qc, laplacian=True) equal(rho, rho2) #equal(delta_rho,delta_rho2) #BUG refdata = numpy.genfromtxt(os.path.join(folder, 'h2o_rhf_sph_grad.cube'), skip_header=9).reshape((-1, )) refrho = numpy.zeros_like(rho) refdrho = numpy.zeros((3, ) + rho.shape) c = 0 for i in range(len(grid.x)): for j in range(len(grid.y)): for k in range(len(grid.z)): refrho[i, j, k] = refdata[c]
def calculate(self, filein, v, x): try: printed = [ "Note: If the mean error of any of the computed integrals is large, consider increasing max. evaluations value\n" ] printed.append( "=============================================================\n" ) printed.append( "Filename Overlap Integral Mean Absolute Error \n" ) numproc = 1 #: Specifies number of subprocesses. slice_length = 1e4 infile = filein.split(",") filenames_RPA_singlet = sorted(infile) for filename in filenames_RPA_singlet: fullpath, just_filename = os.path.split(filename) orbkit.options.quiet = True orbkit.options.no_log = True pattern = "[GTO]" lines = [] num = 0 with open(filename, "r") as f: lines1 = f.readlines() for line in lines1: if num == 0: lines.append(line.lstrip()) elif num == 1: lines.append(line) if pattern in line: num = 1 f.close() filename2 = "RPA_S" + ".molden" with open(filename2, "w") as f: f.writelines(lines) f.close() qc = read.main_read(filename2, all_mo=True) orbkit.init() orbkit.options.quiet = True orbkit.options.no_log = True orbkit.options.calc_mo = [1] orbkit.options.filename = filename2 orbkit.options.adjust_grid = [5, 0.5] data = orbkit.run_orbkit() xl = numpy.amin(orbkit.grid.x) yl = numpy.amin(orbkit.grid.y) zl = numpy.amin(orbkit.grid.z) xh = numpy.amax(orbkit.grid.x) yh = numpy.amax(orbkit.grid.y) zh = numpy.amax(orbkit.grid.z) eig = [sub['energy'] for sub in qc.mo_spec] fdim = len(qc.mo_spec) / 2 fdim = int(fdim) i = numpy.argsort(eig) j = i[::-1] orbkit.init() orbkit.options.quiet = True orbkit.options.no_log = True orbkit.grid.is_initialized = True def func(x_array, *args): x_array = x_array.reshape((-1, 3)) orbkit.grid.x = numpy.array(x_array[:, 0], copy=True) orbkit.grid.y = numpy.array(x_array[:, 1], copy=True) orbkit.grid.z = numpy.array(x_array[:, 2], copy=True) out = orbkit.rho_compute(qc, calc_mo=True, slice_length=slice_length, drv=None, laplacian=False, numproc=numproc) out1 = out[i] out2 = out[j] out1 = numpy.abs(out1) out2 = numpy.abs(out2) out = out1[:fdim] * out2[:fdim] return out.transpose() ndim = 3 xmin = numpy.array([xl, yl, zl], dtype=float) xmax = numpy.array([xh, yh, zh], dtype=float) abserr = 1e-15 relerr = 1e-5 integral_mo, error_mo = cubature(func, ndim, fdim, xmin, xmax, args=[], adaptive='h', abserr=abserr, relerr=relerr, norm=0, maxEval=v, vectorized=True) coeff = numpy.sort(eig)[:fdim] sum = numpy.sum(numpy.abs(coeff)) norm_integral_mo = (numpy.abs(coeff) * integral_mo) / sum delta = numpy.sum(norm_integral_mo) mae = numpy.mean(numpy.abs(error_mo)) printed.append( str(just_filename) + " " + str("%.5f" % delta) + " " + str("%.5f" % mae) + "\n") printed.append("Job completed! \n") printed.append( "====================================================================\n" ) print(printed) with open(os.path.join(fullpath, 'Overlap.txt'), 'w') as fw: fw.writelines(("%s\n" % k for k in printed)) fw.close() return printed except: printed = ["\n Oops! Something went wrong! \n"] printed.append( "====================================================================\n" ) return printed
skip = False if ok_opt[j] == 'cclib': try: __import__(ok_opt[j]) except ImportError: skip = True if not skip: fid = os.path.join(output_folder, '%s/%s%s' % (folder[j], tests[i], fileext[j])) if 'uhf' in tests[i] and folder[j] == 'molpro': # Read the alpha input file qc = read.main_read(fid, itype=ok_opt[j], all_mo=True, spin=None, i_md=0, interactive=False) # Extend the beta input file qc_b = read.main_read(fid, itype=ok_opt[j], all_mo=True, spin=None, i_md=1, interactive=False) qc.mo_spec.extend(qc_b.mo_spec) qc.mo_spec.update() else: qc = read.main_read(fid, itype=ok_opt[j], interactive=False,
def read(fid_list, itype='molden', all_mo=True, nosym=False, **kwargs_all): '''Reads a list of input files. **Parameters:** fid_list : list of str List of input file names. itype : str, choices={'molden', 'gamess', 'gaussian.log', 'gaussian.fchk'} Specifies the type of the input files. **Global Variables:** geo_spec_all, geo_info, ao_spec, ao_spherical, mo_coeff_all, mo_energy_all, mo_occ_all, sym ''' global geo_spec_all, geo_info, ao_spec, ao_spherical, mo_coeff_all, mo_energy_all, mo_occ_all, sym geo_spec_all = [] MO_Spec = [] mo_coeff_all = [] mo_energy_all = [] mo_occ_all = [] # geo_info and ao_info have to stay unchanged geo_old = [] ao_old = [] sym_list = {} n_ao = {} n_r = len(fid_list) for i, filename in enumerate(fid_list): kwargs = kwargs_all['kwargs'][i] if 'kwargs' in kwargs_all.keys( ) else kwargs_all qc = main_read(filename, itype=itype, all_mo=all_mo, interactive=False, **kwargs) # Geo Section if i > 0 and (geo_old != qc.geo_info).sum(): raise IOError('qc.geo_info has changed!') else: geo_old = deepcopy(qc.geo_info) geo_spec_all.append(qc.geo_spec) # AO Section if (i > 0 and not numpy.alltrue([ numpy.allclose(ao_old[j]['coeffs'], qc.ao_spec[j]['coeffs']) for j in range(len(ao_old)) ])): raise IOError('qc.ao_spec has changed!') else: ao_old = deepcopy(qc.ao_spec) # MO Section sym = {} MO_Spec.append(qc.mo_spec) for i, mo in enumerate(qc.mo_spec): if nosym: qc.mo_spec[i]['sym'] = '%d.1' % (i + 1) key = mo['sym'].split('.') if key[1] not in sym.keys(): sym[key[1]] = 0 n_ao[key[1]] = len(qc.mo_spec[0]['coeffs']) sym[key[1]] += 1 for k, it in sym.items(): if k in sym_list: sym_list[k] = max(sym_list[k], it) else: sym_list[k] = it geo_spec_all = numpy.array(geo_spec_all) geo_info = qc.geo_info ao_spec = qc.ao_spec ao_spherical = qc.ao_spherical # Presorting of the MOs according to their symmetry sym = [] for k, it in sym_list.items(): sym.append((k, len(sym))) mo_coeff_all.append(numpy.zeros((n_r, it, n_ao[k]))) mo_energy_all.append(numpy.zeros((n_r, it))) mo_occ_all.append(numpy.zeros((n_r, it))) sym = dict(sym) for i, spec in enumerate(MO_Spec): for j, mo in enumerate(spec): index, k = mo['sym'].split('.') index = int(index) - 1 mo_coeff_all[sym[k]][i, index, :] = mo['coeffs'] mo_energy_all[sym[k]][i, index] = mo['energy'] mo_occ_all[sym[k]][i, index] = mo['occ_num']
''' Partial Charges and Gross Atomic Density Example for the orbkit's non-grid based capabilities and for the computation of the gross atomic density. Hint: Use the VMD script file (ch2o.vmd) for depicting the results. ''' from orbkit import read, grid, extras, output, atomic_populations, display # Open molden file and read parameters qc = read.main_read('ch2o.molden', itype='molden') # Perform a Mulliken population analysis and write the output to a PDB file pop = atomic_populations.mulliken(qc) output.pdb_creator(qc.geo_info, qc.geo_spec, filename='ch2o', charges=pop['charge']) # Initialize the grid display.display('\nSetting up the grid...') grid.adjust_to_geo(qc, extend=5.0, step=0.1) grid.grid_init() display.display(grid.get_grid()) # Compute and save the gross atomic density of the C atom rho_atom = extras.gross_atomic_density(1, qc) output.main_output(rho_atom[0], qc.geo_info,