def getCube(inp, dv=None, cube_header=None, **kwargs): if dv is None: dv = inp.dv if not cube_header: if 'resolution' not in kwargs: res = 0.2 else: res = float(kwargs['resolution']) if 'margin' not in kwargs: margin = 7.0 else: margin = float(kwargs['resolution']) cube_header = getCubeGrid(inp, margin, res) def getSpace(i): coord_min = cube_header[0, 1+i] step = cube_header[1+i, 0] size = cube_header[1+i, 1+i] coord_max = coord_min + (step-1)*size return np.linspace(coord_min, coord_max, step) coord_axes = [getSpace(i) for i in range(3)] X, Y, Z = np.meshgrid(*coord_axes, indexing='ij') step = X.shape X = X.reshape(X.size) Y = Y.reshape(Y.size) Z = Z.reshape(Z.size) coords = np.array([X,Y,Z]).T rho = gp.getRho(inp, coords, new=True, dv=dv) rho = rho.reshape(*step) cube = qtk.CUBE() cube.build(inp.molecule, cube_header, rho) return cube
def asGaussianTemplate(self, gcube, **kwargs): cube_name_list = gcube.name.split('.') fchk_name = '.'.join(cube_name_list[:-1]) + '.fchk' fchk = os.path.abspath(os.path.join(gcube.path, fchk_name)) path, _ = os.path.split(fchk) if not os.path.exists(fchk): ut.exit("gaussian fchk file:%s not found" % fchk) cube = 'gcube_tmp_' + str(id(self)) + '.cube' cube = os.path.join(path, cube) cmd = '%s 1 density=scf %s %s -1' % (qtk.gaussian_cubegen_exe, fchk, cube) run = sp.Popen(cmd, shell=True, stdin=sp.PIPE) for i in range(len(self.grid)): vec = self.grid[i] if i == 0: # for formated output msg = '-1 %f %f %f\n' % (vec[1], vec[2], vec[3]) elif i == 1: # for Bohr as grid unit msg = '%d %f %f %f\n' % (-vec[0], vec[1], vec[2], vec[3]) else: msg = '%d %f %f %f\n' % (vec[0], vec[1], vec[2], vec[3]) run.stdin.write(msg) run.stdin.flush() run.communicate() run.wait() return qtk.CUBE(cube)
def getPsiCube(self, n, C=None, margin=3, resolution=0.1): psi, grid, shape = self.getPsi(C, [n], margin, resolution, get_shape=True) psi = psi.reshape(shape) q = qtk.CUBE() q.build(self.molecule, grid, psi) return q
def getRhoCube(self, margin=3, resolution=0.1, dm=None): if dm is None: dm = self.dm() cube_grid, grid, shape = self.cube_grid(margin, resolution) cube_data_list = 2 * self.ht_obasis.compute_grid_density_dm( dm, cube_grid) cube_data = cube_data_list.reshape(shape) q = qtk.CUBE() q.build(self.molecule, grid, cube_data) return q
def getSigmaCube(self, margin=3, resolution=0.1, dm=None): if dm is None: dm = self.dm() cube_grid, grid, shape = self.cube_grid(margin, resolution) cube_data_list = 2 * self.ht_obasis.compute_grid_gradient_dm( dm, cube_grid) cube_data_list = (cube_data_list**2).sum(axis=1) cube_data = cube_data_list.reshape(shape) q = qtk.CUBE() q.build(self.molecule, grid, cube_data) return q
def getdRho(self, v_ao, margin=None, resolution=None, cube=False, get_shape=False, Coulomb=True, xc=True): """get density response with perturbation v_ao expressed in AO basis""" C = self.mov v_mo = np.tensordot(C, v_ao, axes=[[0], [0]]) v_mo = np.tensordot(C, v_mo, axes=[[0], [1]]) M_inv, ia_list = self.Minv_matrix(Coulomb, xc) if cube: psi, grid, shape = self.getPsi(C=self.mov, margin=margin, resolution=resolution, cube=cube, get_shape=True) else: psi = self.getPsi(C=self.mov, margin=margin, resolution=resolution, cube=cube) drho = np.zeros(psi[:, 0].shape) for s in range(len(ia_list)): i, a = ia_list[s] for t in range(len(ia_list)): j, b = ia_list[t] drho += M_inv[s, t] * v_mo[j, b] * psi[:, i] * psi[:, a] if cube: drho = drho.reshape(shape) q = qtk.CUBE() q.build(self.molecule, grid, drho) return q else: return drho
def read_gaussian(fchk, **kwargs): if 'name' in kwargs: cube = kwargs['name'] root, ext = os.path.splitext(cube) if ext != '.cube': print ext qtk.warning("extension .cube is required for many " + \ "visualization programs") else: root, ext = os.path.splitext(fchk) cube = root + '.cube' qtk.progress("CUBE", "writing file %s\n" % cube) if 'flag' not in kwargs: flag = 'density=scf' else: flag = kwargs['flag'] if 'grid' in kwargs: grid = kwargs['grid'] cmd = '%s 1 %s %s %s -1' % (qtk.gaussian_cubegen_exe, flag, fchk, cube) run = sp.Popen(cmd, shell=True, stdin=sp.PIPE) for i in range(len(grid)): vec = grid[i] if i == 0: # for formated output msg = '-1 %f %f %f\n' % (vec[1], vec[2], vec[3]) elif i == 1: # for Bohr as grid unit msg = '%d %f %f %f\n' % (-vec[0], vec[1], vec[2], vec[3]) else: msg = '%d %f %f %f\n' % (vec[0], vec[1], vec[2], vec[3]) run.stdin.write(msg) else: cmd = '%s 1 %s %s %s' % (qtk.gaussian_cubegen_exe, flag, fchk, cube) run = sp.Popen(cmd, shell=True, stdin=sp.PIPE) run.stdin.flush() run.communicate() run.wait() q = qtk.CUBE(cube, format='cube') zcoord = np.hstack([q.molecule.Z[:, np.newaxis], q.molecule.R]) zcoord[:, 1:4] = zcoord[:, 1:4] / 0.529177249 return q.data, zcoord, q.grid
def QMRun(inp, program=setting.qmcode, **kwargs): """ interface to run qmcode with written inp files. It manages to start qmcode in **cwd**, write to output, collect result, clean up scratch, tmp files according to setup. However, each code require different implementation. input: inp(str): path to input file code(str): qmcode to run, default set to setting.qmcode kwargs (optional): threads=n(int): number of threads per job bigmem=Boolean: big memory request, implemented for CPMD and others CPMD: save_restart=Boolean scr=/path/to/scratch """ if 'threads' in kwargs: _threads = kwargs['threads'] else: _threads = 1 if 'bigmem' in kwargs: _bigmem = kwargs['bigmem'] else: if setting.memory > 16: _bigmem = True else: _bigmem = False if 'omp' in kwargs: omp = kwargs['omp'] else: omp = 1 if 'save_restart' in kwargs: _save_restart = kwargs['save_restart'] else: _save_restart = False if 'save_density' in kwargs: _save_density = kwargs['save_density'] else: _save_density = False if 'chdir' in kwargs and kwargs['chdir']\ or 'run_dir' in kwargs and kwargs['run_dir']: dest_dir = os.path.splitext(inp)[0] cwd = os.getcwd() os.chdir(dest_dir) ########################################### # SYSTEM CALL SUBPROCESS: Running mpi job # ########################################### def compute(exestr, outpath, threads_per_job, **kwargs): """ initiate a single MPI job, wait for it, and write to output """ os.environ["OMP_NUM_THREADS"] = str(omp) outfile = open(outpath, "w") if threads_per_job > 1: mpi_cmd = "%s %d" % (setting.mpistr, threads_per_job) for mpi_flag in setting.mpi_flags: if mpi_flag == '--cpus-per-proc': flag = mpi_flag + ' ' + str(threads_per_job) else: flag = mpi_flag mpi_cmd = mpi_cmd + ' ' + flag cmd = mpi_cmd + ' ' + exestr else: cmd = exestr ut.progress('QMInp.run', 'running job with command: %s\n' % cmd) if 'env' in kwargs: run = sp.Popen(cmd, shell=True, stdout=outfile, env=kwargs['env']) else: run = sp.Popen(cmd, shell=True, stdout=outfile) # wait each mpijob to finish before lauching another # otherwise all mpijobs will be launched simutaniously run.wait() outfile.close() ########## END OF SYSTEM CALL ########## ################################# # SYSTEM CALL for post analysis # ################################# def sys_run(cmd_str, log_file=None): if log_file: log = open(log_file, 'w') try: qtk.progress("QMRun", cmd_str) if log_file: run = sp.Popen(cmd_str, shell=True, stdout=log) else: run = sp.Popen(cmd_str, shell=True) run.wait() except Exception as err: qtk.warning('%s failed with error: %s' % (cmd_str, err)) if log_file: log.close() ########## END OF SYSTEM CALL ########## ####################### # CPMD IMPLEMENTATION # ####################### if program.lower() == 'cpmd': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.cpmd_exe if 'scr' in kwargs and kwargs['scr']: scrdir = kwargs['scr'] ut.delete(inpname, 'FILEPATH', 2) ut.insert(inpname, 'CPMD', ' FILEPATH\n %s' % scrdir) inp_list = sorted(glob.glob('*.inp')) for job in inp_list: out = os.path.splitext(job)[0] + '.out' exestr = "%s %s" % (exe, job) compute(exestr, out, _threads) if (len(inp_list) > 1): rst_list = sorted(glob.glob('RESTART.*')) if rst_list: rst_n = rst_list[-1] if os.path.exists('RESTART'): os.remove('RESTART') os.link(rst_n, 'RESTART') final_out = re.sub(r'_[0-9][0-9].out$', '.out', out) if final_out != out: os.copy(out, final_out) # clean up files files = sorted(glob.glob('*')) tmp = filter(\ lambda x: '.out' not in x \ and '.inp' not in x\ and '.psp' not in x\ and '.xyz' not in x\ and 'KPTS_GENERATION' not in x\ and 'RESTART' not in x\ and 'DENSITY' not in x\ and 'SPINDEN' not in x, files ) for f in tmp: os.remove(f) if not _save_restart: rst_list = sorted(glob.glob("RESTART*")) for rfile in rst_list: os.remove(rfile) densities = sorted(glob.glob('*DEN*')) for i in range(len(densities)): exe = setting.cpmd_cpmd2cube_exe cmd = "%s -fullmesh %s" % (exe, densities[i]) log_name = densities[i] + '_%02d.log' % i sys_run(cmd, log_name) #log = open(log_name, 'w') #try: # run = sp.Popen("%s -fullmesh %s" % (exe, densities[i]), # shell=True, # stdout=log) # run.wait() #except Exception as err: # qtk.warning('%s failed with error: %s' % (exe, err)) #log.close() if os.path.exists(out): qio_out = qio.QMOut(out, program='cpmd') else: qio_out = None ####################### # VASP IMPLEMENTATION # ####################### elif program.lower() == 'vasp': if 'exe' in kwargs: exestr = kwargs['exe'] else: exestr = setting.vasp_exe qmoutput = inp + '.out' qmlog = inp + '.log' compute(exestr, qmoutput, _threads) qio_out = qio.QMOut('vasprun.xml', program='vasp') if not _save_restart: try: os.remove('WAVECAR') except: pass try: os.remove('POTCAR') except: pass os.rename(qmoutput, qmlog) shutil.copyfile('vasprun.xml', qmoutput) ######################### # NWChem IMPLEMENTATION # ######################### elif program.lower() == 'nwchem': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.nwchem_exe exestr = "%s %s" % (exe, inp) qmoutput = os.path.splitext(inp)[0] + '.out' compute(exestr, qmoutput, _threads) qio_out = qio.QMOut(qmoutput, program='nwchem') files = sorted(glob.glob('*.*')) tmp = filter(\ lambda x: '.out' not in x \ and '.inp' not in x\ and '.cube' not in x\ and '.movecs' not in x, files ) for f in tmp: os.remove(f) movecs = sorted(glob.glob('*.movecs')) for f in movecs: exe = setting.nwchem_mov2asc_exe nb = qio_out.n_basis out = re.sub('\.movecs', '.modat', f) exestr = "%s %d %s %s" % (exe, nb, f, out) sys_run(exestr) #try: # run = sp.Popen(exestr, shell=True) # run.wait() # qio_out.getMO(out) #except Exception as err: # qtk.warning('%s failed with error: %s' % (exe, err)) if not _save_restart: os.remove(f) ######################### # BigDFT IMPLEMENTATION # ######################### elif program.lower() == 'bigdft': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.bigdft_exe env = os.environ.copy() inp = os.path.splitext(inp)[0] exestr = "%s %s" % (exe, inp) qmoutput = inp + '.out' qmlog = 'log-%s.yaml' % inp compute(exestr, qmoutput, _threads, env=env) qio_out = qio.QMOut(qmlog, program='bigdft') ######################### # Abinit IMPLEMENTATION # ######################### elif program.lower() == 'abinit': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.abinit_exe inp = os.path.splitext(inp)[0] exestr = "%s < %s" % (exe, inp + '.files') qmlog = inp + '.log' qmoutput = inp + '.out' compute(exestr, qmlog, _threads) # unfold bandstructure if 'unfold' in kwargs and kwargs['unfold']: folds = kwargs['unfold'] exe = setting.abinit_f2b_exe wfk_list = sorted(glob.glob("*_WFK")) if len(wfk_list) > 0: wfk = wfk_list[-1] qtk.progress("QMRun", "linking wfk file %s to unfold_WFK" % wfk) os.link(wfk, 'unfold_WFK') wfk_root = wfk.replace('_WFK', '') log_name = '%s_f2b.log' % wfk_root fold_str = [str(f) for f in folds] cmd_str = "%s unfold_WFK %s" % (exe, ':'.join(fold_str)) sys_run(cmd_str, log_name) qtk.progress("QMRun", "Done, remove unfold_WFK") os.remove('unfold_WFK') #try: # qtk.progress("QMRun", cmd_str) # run = sp.Popen(cmd_str, shell=True, stdout=log) # run.wait() #except Exception as err: # qtk.warning('%s failed with error: %s' % (exe, err)) #log.close() else: qtk.warning('unfolding but no wavefunction file found...') if 'unfold_cleanup' in kwargs and kwargs['unfold_cleanup']: qtk.progress("QMRun", "deleting all WFK files") for wfk in sorted(glob.glob("*_WFK")): os.remove(wfk) # clean up files files = sorted(glob.glob('*')) tmp = filter(\ lambda x: '.out' not in x \ and '.f2b' not in x\ and '.log' not in x\ and '.inp' not in x\ and '.files' not in x\ and 'psp' not in x\ and '_EIG' not in x\ and '_WFK' not in x\ and '_DOS' not in x\ and '_DEN' not in x, files ) for f in tmp: os.remove(f) if not _save_restart: for rst in sorted(glob.glob('*_WFK')): os.remove(rst) if not _save_density: for den in sorted(glob.glob('*_DEN')): os.remove(den) densities = sorted(glob.glob('*_DEN')) if len(densities) > 0: i = len(densities) - 1 exe = setting.abinit_cut3d_exe #den_inp = densities[i] + '.cov' den_inp = densities[-1] + '.cov' cube_file = inp + '.cube' den_inp_file = open(den_inp, 'wb') den_inp_file.write("%s\n14\n%s\n0" % (densities[i], cube_file)) den_inp_file.close() log_name = densities[i] + '.log' cmd = "%s < %s" % (exe, den_inp) sys_run(cmd, log_name) #log = open(log_name, 'w') #try: # run = sp.Popen("%s < %s" % (exe, den_inp), # shell=True, # stdout=log) # run.wait() #except Exception as err: # qtk.warning('%s failed with error: %s' % (exe, err)) #log.close() qio_out = qtk.QMOut(qmoutput, program='abinit') ############################# # Gaussian09 IMPLEMENTATION # ############################# elif program.lower() == 'gaussian': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.gaussian_exe exestr = "%s %s" % (exe, inp) qmoutput = os.path.splitext(inp)[0] + '.out' qmlog = os.path.splitext(inp)[0] + '.log' compute(exestr, qmoutput, _threads) os.rename(qmlog, qmoutput) chks = sorted(glob.glob('*.chk')) for chk in chks: exe = setting.gaussian_formchk_exe exestr = "%s %s" % (exe, chk) sys_run(exestr) #run = sp.Popen(exestr, shell=True) #run.wait() if _save_density: fchk = sorted(glob.glob("*.fchk"))[-1] q = qtk.CUBE(fchk) qio_out = qio.QMOut(qmoutput, program='gaussian') ################################## # QuantumESPRESSO IMPLEMENTATION # ################################## elif program.lower() == 'espresso': if 'exe' in kwargs: exe = kwargs['exe'] else: exe = setting.espresso_exe inp_list = sorted(glob.glob('*.inp')) for job in inp_list: out = os.path.splitext(job)[0] + '.out' exestr = "%s < %s" % (exe, job) compute(exestr, out, _threads) qio_out = qio.QMOut(out, program='espresso') if not _save_restart: rst_list = sorted(glob.glob("*.wfc*")) rst_list.extend(sorted(glob.glob("*.restart_*"))) else: rst_list = [] for r in rst_list: os.remove(r) ######################### # GAMESS IMPLEMENTATION # ######################### elif program.lower() == 'gamess': ut.exit("ERROR! program '%s' not implemented" % program) # and others... # else: ut.exit("ERROR! program '%s' not recognized" % program) if 'cwd' in locals(): os.chdir(cwd) qio_out.path = inp return qio_out