def toInp(qminp, **kwargs): inpClass = qtk.QM.general_io.GenericQMInput is_qminp = issubclass(qminp.__class__, inpClass) if not is_qminp: if type(qminp) is str or type(qminp) is qtk.Molecule: qminp = qtk.QMInp(qminp, **kwargs) return qminp
def __init__(self, molecule, **kwargs): GenericMDInput.__init__(molecule, **kwargs) if 'theory' not in kwargs: self.setting['theory'] = 'PBE' if 'vdw' not in kwargs: self.setting['vdw'] = kwargs['vdw'] if 'cutoff' not in kwargs: self.setting['cutoff'] = 100 if 'periodic' not in kwargs: self.setting['periodic'] = True if 'em_step' not in kwargs: self.setting['em_step'] = 200 if 'eq_step' not in kwargs: self.setting['eq_step'] = 200 if 'md_step' not in kwargs: self.setting['md_step'] = 5000 if 'md_mode' not in kwargs: self.setting['md_mode'] = 'BOMD' # celldm can always be overwritten if 'celldm' not in kwargs: # for the case of molecule xyz input (molecule) # set default orthorombic celldm if not self.molecule.celldm: box = self.molecule.getBox() # set defualt margin in specified in setting.py, # grow with box size if 'margin' not in kwargs: m = qtk.setting.box_margin self.setting['margin'] = max(m, max(box) / 5.) edge = np.array([min(self.molecule.R[:,i])\ for i in range(3)]) self.molecule.shift(self.setting['margin'] - edge) box = 2 * self.setting['margin'] + box self.setting['celldm'] = np.append(box, [0, 0, 0]) else: self.setting['celldm'] = self.molecule.celldm for key in self.md_setting.iterkeys(): qtk.report("MDJob", "setting", key, ":", self.md_setting[key]) em_setting = copy.deepcopy(self.setting) em_setting['md_step'] = em_setting['em_step'] em_setting['mode'] = 'geopt' em_setting['info'] = ' MD em job with ' + molecule self.emInp = qtk.QMInp(molecule, **em_setting) eq_setting = copy.deepcopy(self.setting) eq_setting['md_step'] = eq_setting['eq_step'] eq_setting['info'] = ' MD eq job with ' + molecule eq_setting['mode'] = self.md_setting['md_mode'] self.eqInp = qtk.QMInp(molecule, **eq_setting) md_setting = copy.deepcopy(self.setting) md_setting['mode'] = self.md_setting['md_mode'] md_setting['info'] = ' MD md job with ' + molecule self.mdInp = qtk.QMInp(molecule, **md_setting)
def genRefInp(x, y, n_pair, **kwargs): """ generate cpmd input files for graphene reference calculation x: number of graphene 4-atom unit cells in x y: number of graphene 4-atom unit cells in y n_pair: number of BN pairs in the system kwargs: max_sample """ if 'path' in kwargs: qtk.report("creating folder", kwargs['path']) os.makedirs(kwargs['path']) os.chdir(kwargs['path']) print "%screating inp folder...%s"\ % (qtk.bcolors.OKGREEN, qtk.bcolors.ENDC) if not os.path.exists('inp'): os.makedirs('inp') else: print "%sinp folder exist, baking up to back_inp...%s"\ % (qtk.bcolors.WARNING, qtk.bcolors.ENDC) try: shutil.rmtree('back_inp') except: pass os.rename('inp', 'back_inp') os.makedirs('inp') N = 4 * x * y if 'max_sample' in kwargs: max_sample = kwargs['max_sample'] else: total = math.factorial(N - 1) denum1 = math.factorial(n_pair)**2 denum2 = math.factorial(N - 1 - 2 * n_pair) max_sample = total / (denum1 * denum2) digit = len(str(max_sample)) name_xyz = "gph%d-%d.xyz" % (x, y) name_ccs = "ccs%d-%d.txt" % (x, y) namev_xyz = "gph%d-%dv.xyz" % (x, y) namev_ccs = "ccs%d-%dv.txt" % (x, y) header = "gph%d%d_" % (x, y) ccs_file = open(name_ccs, "w") ccsv_file = open(namev_ccs, "w") print >> ccs_file, "mutation_list:\n"+\ " %d:%d -> 5:7\n" % (2, N) + \ "end" print >> ccsv_file, "mutation_list:\n"+\ " %d:%d -> 5:7\n" % (1, N-1) + \ "end" ccs_file.close() ccsv_file.close() print "%sthe following files are written: %s"\ % (qtk.bcolors.OKGREEN, qtk.bcolors.ENDC) print " %s\n %s\n %s\n %s\n" % (name_xyz, namev_xyz,\ name_ccs, namev_ccs) graphene = generate(x, y) graphene.write_xyz(name_xyz) graphenev = graphene.remove_atom(1) graphene.write_xyz(namev_xyz) space = qtk.CCS(name_xyz, name_ccs) space_v = qtk.CCS(namev_xyz, namev_ccs) flat = [item for sublist in space.mutation_list \ for item in sublist] # geometry setup mol_base = graphene dx = mol_base.R[1, 0] mol_base.sort_coord() dy = mol_base.R[1, 1] center = mol_base.R[0] + [0, 0, -10] mol_base.center(center) x_max = mol_base.R[-1, 0] y_max = mol_base.R[-1, 1] celldm = [round(x_max + dx, 4), round(y_max + dy, 4), 20, 0, 0, 0] # input setup gph = qtk.QMInp(name_xyz, 'cpmd', info='gph') gph.setCelldm(celldm) gph.periodic() gph.setSCFStep(500) gphv = qtk.QMInp(namev_xyz, 'cpmd', info='gphv') gphv.setCelldm(celldm) gphv.periodic() gphv.setSCFStep(500) name = "inp/%s%s.inp" % (header, str(0).zfill(digit)) namev = "inp/%s%sv.inp" % (header, str(0).zfill(digit)) gph.write(name) gphv.write(namev) c_base = [6 for i in range(len(flat))] itr = 1 for n_bn in range(1, n_pair + 1): for n_comb in it.combinations(range(len(flat)), n_bn): n_list = list(n_comb) rest = [index for index in range(len(flat)) \ if index not in list(n_comb)] for b_comb in it.combinations(rest, n_bn): name = "inp/%s%s.inp" % (header, str(itr).zfill(digit)) namev = "inp/%s%sv.inp" % (header, str(itr).zfill(digit)) b_list = list(b_comb) c_list = [index for index in rest\ if index not in list(n_comb)] atom_list = copy.deepcopy(c_base) for i in b_list: atom_list[i] = 5 for i in n_list: atom_list[i] = 7 valid = True mutate_mol = space.generate(mutation=[atom_list]) mutate_molv = space_v.generate(mutation=[atom_list]) mutate_mol.find_bonds() if not all (key in mutate_mol.bond_types \ for key in ('B-B', 'N-N')): gph.setCenter([0, 0, -celldm[2] / 2]) gph.setStructure(mutate_mol) gph.write(name) gphv.setCenter([0, 0, -celldm[2] / 2]) gphv.setStructure(mutate_molv) gphv.write(namev) itr += 1 if itr > max_sample: msg = "%sDONE! %d generated%s"\ % (qtk.bcolors.OKGREEN, itr-1, qtk.bcolors.ENDC) sys.exit(msg) print "%sDONE! %d generated%s"\ % (qtk.bcolors.OKGREEN, itr-1, qtk.bcolors.ENDC) itr = 1
def Al1st(qminp, runjob=False, ref_dir='restart_path', **setting): #assert os.path.exists(ref_dir) if 'ref_dir' in setting: ref_dir = setting['ref_dir'] setting['ref_dir'] = os.path.abspath(ref_dir) if 'runjob' not in setting: setting['runjob'] = False qminp = copy.deepcopy(univ.toInp(qminp, **setting)) if hasattr(qminp.setting, 'save_restart'): qminp.setting['save_restart'] = False name = qminp.molecule.name if 'out_dir' in setting: name = setting['out_dir'] del setting['out_dir'] qminp.molecule.name = name qminp.setting['root_dir'] = name if qminp.setting['program'] == 'cpmd': setting['restart'] = True setting['scf_step'] = 1 rst = os.path.join(setting['ref_dir'], 'RESTART') assert os.path.exists(rst) rst = os.path.abspath(rst) if 'dependent_files' in setting: setting['dependent_files'].append(rst) else: setting['dependent_files'] = [rst] elif qminp.setting['program'] == 'abinit': setting['restart'] = True setting['scf_step'] = 0 rstList = sorted(glob.glob(os.path.join(setting['ref_dir'], '*o_*WFK'))) assert len(rstList) > 0 rstSrc = rstList[-1] if 'dependent_file' in setting: setting['dependent_files'].append([rstSrc, name+'i_WFK']) else: setting['dependent_files'] = [[rstSrc, name+'i_WFK']] denList = sorted(glob.glob(os.path.join(setting['ref_dir'], '*o_*DEN'))) if len(denList) > 0: setting['restart_density'] = True denSrc = denList[-1] setting['dependent_files'].append([denSrc, name+'i_DEN']) elif qminp.setting['program'] == 'espresso': wfn = glob.glob(setting['ref_dir'] + '/*.wfc[0-9]*') if 'threads' not in setting or setting['threads'] != len(wfn): qtk.warning('threads must be the same as ref_dir, reset to %d'\ % len(wfn)) setting['threads'] = len(wfn) setting['restart'] = True setting['scf_step'] = 1 rst = glob.glob(setting['ref_dir'] + '/*.restart*') save = glob.glob(setting['ref_dir'] + '/*.save') if 'dependent_files' in setting: for lst in [wfn, rst, save]: setting['dependent_files'].extend(lst) else: setting['dependent_files'] = wfn for lst in [rst, save]: setting['dependent_files'].extend(lst) elif qminp.setting['program'] == 'vasp': setting['restart'] = True setting['scf_step'] = 1 wfn_list = sorted(glob.glob(setting['ref_dir'] + '/WAVECAR')) assert len(wfn_list) == 1 wfn = wfn_list[0] if 'dependent_files' in setting: setting['dependent_files'].append(wfn) else: setting['dependent_files'] = [wfn] elif qminp.setting['program'] == 'bigdft': pass elif qminp.setting['program'] == 'nwchem': pass if setting['runjob']: qmout = qminp.run(name, **setting) return qmout else: qminp.molecule.name = name qminp.setting.update(setting) new_inp = qtk.QMInp(qminp.molecule, **qminp.setting) return new_inp
#'threads': 4 } # In[ ]: # construct QM jobs inp_refs = [] inp_prds = [] for d in np.arange(0.5, 2.4, 0.1): # construct HF reference run with RESTART file s = d - 1. d_str = '%02d' % np.round(d * 10) tmp = hf.copy() tmp.stretch(1, [0, 1], s) tmp.name = 'hf_ref%s' % d_str inp = qtk.QMInp(tmp, save_restart=True, **qmsettings) inp_refs.append(inp) # construct HCl target run tmp2 = hcl.copy() tmp2.stretch(1, [0, 1], s) tmp2.name = 'hcl_ref%s' % d_str inp = qtk.QMInp(tmp2, **qmsettings) inp_refs.append(inp) # construct HCl prediction run with alchemical prediction setting prd = hcl.copy() prd.stretch(1, [0, 1], s) prd.name = 'hcl_prd%s' % d_str rst_file = '%s/hf_ref%s/RESTART.1' % (ref_root, d_str) inp = qtk.QMInp(prd,
def __init__(self, xyz_i, xyz_f, program=qtk.setting.qmcode, **kwargs): if 'name' in kwargs: self.name = kwargs['name'] elif type(xyz_i)==str and type(xyz_f)==str: ref_stem, _ = os.path.splitext(xyz_i) tar_stem, _ = os.path.splitext(xyz_f) self.name = ref_stem + '-' + tar_stem else: self.name = 'A2B' self.program = program if type(xyz_i) == str: self.initial = qtk.Molecule() self.initial.read(xyz_i) elif type(xyz_i) == qtk.Molecule: self.initial = xyz_i if type(xyz_f) == str: self.final = qtk.Molecule() self.final.read(xyz_f) elif type(xyz_f) == qtk.Molecule: self.final = xyz_f self.inp_base = qtk.QMInp(xyz_i, program) if 'inp_base' in kwargs: if kwargs['inp_base'] is not None: inp_tmp = copy.deepcopy(kwargs['inp_base']) self.inp_base.inp.setting = inp_tmp.inp.setting # !!!!!!!!!!!!!!!!!!!!!!! # construct mutation list # tar_list: list of matching location tar_list = [i for i in range(self.final.N)] self.mutation_ind = [] self.mutation_ref = [] self.mutation_tar = [] self.mutation_crd = [] # loop through every atom in initial system for i in range(self.initial.N): Zi = self.initial.type_list[i] Ri = self.initial.R[i] to_void = True # loop through every atom in final system for j in range(self.final.N): # every atom-pair distance Rj = self.final.R[j] diff = np.linalg.norm(Ri-Rj) # search for atoms at same location if diff < 10E-6: to_void = False tar_list[j] = False Zj = self.final.type_list[j] if Zi != Zj: self.mutation_ind.append(i) self.mutation_ref.append(Zi) self.mutation_tar.append(Zj) self.mutation_crd.append(Ri) # when no distance matched, set atom target to void if to_void: self.mutation_ind.append(i) self.mutation_ref.append(Zi) self.mutation_tar.append('VOID') self.mutation_crd.append(Ri) # loop through every target atom for non-matching atoms N = self.initial.N for j in range(self.final.N): if tar_list[j]: self.mutation_ind.append(N) self.mutation_ref.append('VOID') self.mutation_tar.append(self.final.type_list[j]) self.mutation_crd.append(self.final.R[j])
#!/usr/bin/python import qctoolkit as qtk import qctoolkit.alchemy as qal import glob, copy, os, re, shutil import numpy as np if os.path.exists('inp'): shutil.rmtree('inp') os.makedirs('inp') dopt = [[False, 2.1163, 2.2244], [1.5190, False, 1.9307], [1.5677, 1.8524, False]] xyz_file = glob.glob('structure/*.xyz') inp = qtk.QMInp(xyz_file[0], 'cpmd') inp.setCelldm([20, 15, 15, 0, 0, 0]) inp.setShift([7.5, 7.5, 7.5]) inp.saveDensity() ref_list = [] tar_list = [] name_list = [] for xyz in xyz_file: mol1 = qtk.Molecule() mol1.read(xyz) ref_list.append(mol1) atom, coord = mol1.extract(1) tars = [] for d_tar in [1, 1.5, 2, 2.5]: mol2 = qtk.Molecule()
def AlGaX_EvOpt(structure, vacancy_ind, ccs_span, **kwargs): qm_setting = {} if 'qm_setting' in kwargs: qm_setting = kwargs['qm_setting'] qm_setting['save_restart'] = True if 'QMInp' in kwargs: baseinp = kwargs['QMInp'] else: baseinp = qtk.QMInp(structure, program='cpmd') if 'T' in kwargs: _T = kwargs['T'] else: _T = 1 if 'target' in kwargs: _target = kwargs['target'] else: _target = 0 if 'log_file' in kwargs: logfile = kwargs['log_file'] else: logfile = 'AlGaX_EvOpt.log' if 'threads' in kwargs: _threads = kwargs['threads'] else: _threads = qtk.cpu_count if 'threads_per_job' in kwargs: _threadspj = kwargs['threads_per_job'] else: _threadspj = _threads _parallel = int(_threads / _threadspj) if 'optimizer' in kwargs: _optimizer = kwargs['optimizer'] if _optimizer == 'GA': if 'population_size' in kwargs: _population_size = kwargs['population_size'] else: _population_size = qtk.setting.cpu_count else: _optimizer = 'MC' ccs = qtk.CCS(structure, ccs_span) inpp = qtk.QMInp(structure, **qm_setting) inpp.setting['info'] = 'Ev_per_ref' if not os.path.exists('pref/pref.out'): inpp.run('pref') inpv = qtk.QMInp(structure, **qm_setting) inpv.removeAtoms(vacancy_ind) inpv.setChargeMultiplicity(0, 2) inpv.setting['info'] = 'Ev_vac_ref' if not os.path.exists('vref/vref.out'): inpv.run('vref') inpa = qtk.QMInp(structure, **qm_setting) inpa.isolateAtoms(vacancy_ind) inpa.setChargeMultiplicity(0, 2) inpa.setting['info'] = 'freeAtom' if not os.path.exists('freeAtom/freeAtom.out'): inpa.run('freeAtom') freeAtomOut = qtk.QMOut('freeAtom/freeAtom.out') tmp, init_ccs_coord = ccs.random() qm_setting['threads'] = _threadspj penalty_setting = { 'QMInp': baseinp, 'freeAtomE': freeAtomOut.Et, 'qm_setting': qm_setting, } if 'alchemy' in kwargs and kwargs['alchemy']: penalty_setting['pref'] = 'pref' penalty_setting['vref'] = 'vref' input_list = [ccs, vacancy_ind, penalty_setting] def genCCSInp(): _coord = ccs.random()[1] return _coord op_setting = { 'power': 1, 'log_file': logfile, 'target': _target, 'parallel': _parallel, 'T': _T, } qtk.report('start optimizer') if _optimizer == 'MC': cylopt = qop.MonteCarlo(Ev_ccs, input_list, genCCSInp, **op_setting) elif _optimizer == 'GA': cylopt = qop.GeneticOptimizer(Ev_ccs, input_list, genCCSInp, ccs.mate, _population_size, **op_setting) qtk.report('optimizer initialized') cylopt.run()
def Ev_ccs(ccs_coord, ccs_span, vacancy_index, **kwargs): """ single point calculation of vacancy energy in crystal either reference (true) or predicted (pred) calculations can be assigned vacancy_index starts from 1 """ if 'QMInp' not in kwargs: qtk.exit("kwargs: 'QMInp' is missing.\n"\ + "It should be set to QMInp object of "\ + "system without vacancies.\n"\ + "It is necessary for inp settings") base_inp = kwargs['QMInp'] qm_setting = {} if 'qm_setting' in kwargs: qm_setting = kwargs['qm_setting'] if 'pref' in kwargs and 'vref' in kwargs: alchem = True perfect_ref = kwargs['pref'] vacancy_ref = kwargs['vref'] elif 'pref' not in kwargs and 'vref' not in kwargs: alchem = False freeE = qtk.QMOut('freeAtom/freeAtom.out') freeE.inUnit('ev') if 'threads' in kwargs: _threads = kwargs['threads'] else: _threads = 1 inp_wov = qtk.QMInp(ccs_span.generate(**ccs_coord)) inp_wv = qtk.QMInp(ccs_span.generate(**ccs_coord)) inp_wv.removeAtoms(vacancy_index) inp_wv.setChargeMultiplicity(0, 2) perfect = 'ev_perfect' + str(os.getpid()) vacancy = 'ev_vacancy' + str(os.getpid()) perfectinp = perfect + '.inp' vacancyinp = vacancy + '.inp' inp_wov.molecule.name = perfectinp inp_wv.molecule.name = vacancyinp if os.path.exists(perfect): shutil.rmtree(perfect) if os.path.exists(vacancy): shutil.rmtree(vacancy) print ccs_coord if alchem: out_wov = qtk.Al1st(inp_wov, ref_dir=perfect_ref, **qm_setting) out_wv = qtk.Al1st(inp_wv, ref_dir=vacancy_ref, **qm_setting) else: out_wov = inp_wov.run(**qm_setting) out_wv = inp_wv.run(**qm_setting) try: os.remove(perfectinp) os.remove(vacancyinp) except OSError: shutil.rmtree(perfectinp) shutil.rmtree(vacancyinp) out_wov.inUnit('ev') out_wv.inUnit('ev') final = out_wov - out_wv - freeE msg = str(out_wov.Et) + '-(' + str(out_wv.Et) + \ '+' + str(freeE.Et) + ') = ' + str(final.Et) qtk.report('trial Ev', msg) return final.Et
def run(self, name=None, **kwargs): molecule = self.setLambda(**kwargs) self.qm_setting.update(kwargs) inp = qtk.QMInp(molecule, **self.qm_setting) return inp.run(name)
def getInp(self, **kwargs): molecule = self.setLambda(**kwargs) self.qm_setting.update(kwargs) inp = qtk.QMInp(molecule, **self.qm_setting) return inp
def write(self, name=None, **kwargs): molecule = self.setLambda(**kwargs) self.qm_setting.update(kwargs) inp = qtk.QMInp(molecule, **self.qm_setting) inp.write(name)