def run_task(self,fw_spec): jobID = fw_spec['jobID'] job = db2object(jobID) t0 = time.time() atoms = job.atoms() job.optimizePos(atoms,job.calc()) t = (time.time()-t0)/60.0 #min niter = 1 # ??? how to calculate this (from log file? different for gpaw and qe) avgtime = t/niter pos = atoms.get_scaled_positions() e0 = atoms.get_potential_energy() f0 = atoms.get_forces() magmom = atoms.get_magnetic_moments() if any([x>0 for x in job.magmomsinit()]) else np.zeros(len(atoms)) resultDict={'pos':pos,'magmom':magmom,'e0':e0,'f0':f0,'avgtime':avgtime,'niter':niter} if job.dftcode=='gpaw': atoms.calc.write('inp.gpw', mode='all') #for use in getXCContribs io.write('out.traj',atoms) return FWAction(stored_data= resultDict,mod_spec=[{'_push': resultDict}])
def __init__(self, lpadid): fw = lpad.get_fw_by_id(lpadid) jobid = fw.spec['jobID'] self.id = lpadid self.fw = fw self.jobid = jobid self.job = db2object(jobid)
def run_task(self,fw_spec): jobID = fw_spec['jobID'] job = db2object(jobID) t0 = time.time() atoms = job.atoms() t = (time.time()-t0)/60.0 #min dos = None return FWAction(stored_data= {'dos':dos,'avgtime':t},mod_spec=[{'_push': {'vibs':vibs,'time':t}}])
def increaseConvergence(): kohnsham = [x[0] for x in plotQuery(['jobid'], [KOHNSHAM])] new = 0 for k in kohnsham: jobj = db2object(k) jobj.convid += 1 jobj.status = 'initialized' jobj.error, jobj.comments = None, None id, status = insertObject(jobj) if status == 'inserted': new += 1 print 'added %d new jobs' % new
def run_task(self,fw_spec): global nIter nIter = 0 jobID = fw_spec['jobID'] job = db2object(jobID) existsPrecalc = job.precalc != 'None' t0 = time.time() def getBulkEnergy(latticeParams): """For a given set of bravais lattice parameters, optimize atomic coordinates and return minimum energy""" global nIter nIter += 1 atoms = job.fromParams(latticeParams) calc = job.calc(restart=True) if existsPrecalc else job.calc() if existsPrecalc: preCalc = job.calc(precalc=True) job.optimizePos(atoms,preCalc,saveWF = True) if job.dftcode =='gpaw': atoms,calc = job.gpawRestart() job.optimizePos(atoms,calc) energy = atoms.get_potential_energy() with paropen('lattice_opt.log','a') as logfile: logfile.write('%s\t%s\n' %(energy,latticeParams)) parprint('%s\t%s\n' %(energy,latticeParams)) if job.dftcode=='gpaw': atoms.calc.write('inp.gpw', mode='all') #for use in getXCContribs io.write('out.traj',atoms) return energy optimizedLatticeParams = fmin(getBulkEnergy,job.iGuess(),ftol=1,xtol=job.xtol) avgtime = (time.time()-t0)/float(nIter)/60.0 #min ### Get info from final state optAtoms = io.read('out.traj') optCell = optAtoms.get_cell() pos = optAtoms.get_scaled_positions() e0 = optAtoms.get_potential_energy() f0 = optAtoms.get_forces() magmom = optAtoms.get_magnetic_moments() if any([x>0 for x in job.magmomsinit()]) else np.zeros(len(optAtoms)) resultDict = {'latticeParams': optimizedLatticeParams,'avgtime':avgtime,'cell':optCell,'pos':pos,'e0':e0,'f0':f0,'magmom':magmom,'niter':nIter} return FWAction( stored_data=resultDict,mod_spec=[{'_push': resultDict}])
def run_task(self,fw_spec): jobID,latticeParams = fw_spec['jobID'],fw_spec['latticeParams'] # WHY IS LATTICEPARAMS [[FLOAT]] INSTEAD OF [FLOAT]? job = db2object(jobID) existsPrecalc = job.precalc != 'None' optAtoms = job.fromParams(latticeParams[0]) optCell = optAtoms.get_cell() strains = np.linspace(1-job.strain,1+job.strain,9) calc = job.calc(restart=True) if existsPrecalc else job.calc() vol,eng = [],[] for i, strain in enumerate(strains): atoms = optAtoms.copy() atoms.set_cell(optCell*strain,scale_atoms=True) if existsPrecalc: preCalc = job.calc(precalc=True) job.optimizePos(atoms,preCalc,saveWF = True) if job.dftcode =='gpaw': atoms,calc = job.gpawRestart() job.optimizePos(atoms,calc) energy = atoms.get_potential_energy() volume = atoms.get_volume() vol.append(deepcopy(volume)) eng.append(deepcopy(energy)) parprint('%f %f'%(strain,energy)) with paropen('bulkmod.log','a') as logfile: logfile.write('%s\t%s\n' %(strain,energy)) parprint('%f %f'%(strain,energy)) aHat,quadR2 = quadFit(np.array(deepcopy(vol)),np.array(deepcopy(eng))) try: eos = EquationOfState(vol,eng) v0, e0, b = eos.fit() eos.plot(filename='bulk-eos.png',show=False) b0= b/kJ*1e24 #GPa use this value if EOS doesn't fail except ValueError: # too bad of a fit for ASE to handle b0 = aHat*2*vol[4]*160.2 # units: eV/A^6 * A^3 * 1, where 1 === 160.2 GPa*A^3/eV return FWAction( stored_data= {'b0':b0,'quadR2':quadR2} ,mod_spec=[{'_push': {'b0':b0,'quadR2':quadR2}}])
def run_task(self,fw_spec): jobID = fw_spec['jobID'] job = db2object(jobID) if job.dftcode == 'gpaw': from gpaw import restart from gpaw.xc.bee import BEEFEnsemble atoms,calc = restart('inp.gpw', setups='sg15', xc='mBEEF', convergence={'energy': 5e-4}, txt='mbeef.txt') atoms.get_potential_energy() beef = BEEFEnsemble(calc) xcContribs = beef.mbeef_exchange_energy_contribs() else: xcContribs = np.zeros((8,8)) return FWAction( stored_data={'xcContribs': xcContribs} ,mod_spec=[{'_push': {'xcContribs': xcContribs}}])
def main(): dropTable('tentativejob') dropTable('tentativedetails') sqlexecute(jobTable('tentativejob')) sqlexecute('INSERT INTO tentativejob SELECT * FROM job') sqlexecute(tentativedetailstable) for i,sID in enumerate(surfs): p = asedb.get(sID).get('parent') cols = ['xc','pw','kptden','psp','convid','precalc','dftcode'] allInfo = queryManyFromOne(cols,'aseid',p) xc,pw,kptden,psp,convid,precalc,dftcode = allInfo tentativeInput = [None,'surfrelax',sID,None,None,xc,pw,kptden,psp,None,None,convid,precalc,dftcode,None,None,'initialized'] tentativeSurfjob = Job(*tentativeInput) insertObject(tentativeSurfjob,tentative=True) applyDetails(tentative=True) #populate details table so that plotQuery works valid = [db2object(x[0],'tentativejob','job') for x in plotQuery(['jobid'],constraints,tentativetable)] new = 0 print "%d valid jobs, %d are new"%(len(valid),new) question = "Do you want to insert %d new surface jobs?"%new if raw_input(question) in ['y','yes']: for z in range(len(valid)): ID,status = insertObject(valid[z]) if status == 'inserted': new +=1 print "%d jobs are new"%new applyDetails() dropTable('tentativejob') dropTable('tentativedetails')
def main(): try: dropTable('tentativejob') # uncomment if script fails in the middle except: pass sqlexecute(jobTable('tentativejob')) copyTable('job','tentativejob') combos = product(*domains) nTot = reduce(mul,[len(x) for x in [trajDomain,xcDomain,pspDomain,pwDomain,kptDomain,preXcDomain,dftDomain]]) ncombo = reduce(mul,[len(x) for x in domains]) for i,c in enumerate(combos): print '%f %%'%(i/float(ncombo)*100) # jobid jobkind aseid vib neb xc pw kpt psp xtol strain convergence ID precalc dft comm err stat tentativeInput = [None,'bulkrelax',c[0],None,None,c[1],c[2],c[3],c[4],0.005,0.03, 2 if c[1]=='mBEEF' else 1,c[5],c[6],None,None,'initialized'] tentativejob = Job(*tentativeInput) insertObject(tentativejob,tentative=True) nJobsInit,nJobsTent = countDB('job'),countDB('tentativejob') print "%d tentative jobs after filtering %d jobs"%(ncombo,nTot) applyDetails(tentative=True) #populate details table so that plotQuery works valid = [db2object(x[0],'tentativejob') for x in plotQuery(['jobid'],CONSTRAINTS,tentativetable)] new = 0 question = "Do you want to insert %d valid bulk jobs?\n(y/n)--> "%len(valid) if raw_input(question) in ['y','yes']: for z in range(len(valid)): ID,status = insertObject(valid[z]) if status == 'inserted': new +=1 print "%d jobs are new"%new applyDetails() dropTable('tentativejob')
def run_task(self,fw_spec): """ONLY WORKS FOR QUANTUM ESPRESSO""" from ase.vibrations import Vibrations jobID = fw_spec['jobID'] job = db2object(jobID) t0 = time.time() atoms = job.atoms() atoms.set_calculator(job.vibCalc()) vib = Vibrations(atoms,delta=job.delta(),indicies=job.vibids) vib.run() vib.summary(log='vibrations.txt') vib.write_jmol() vibs = vib.get_frequencies() t = (time.time()-t0)/60.0 #min return FWAction(stored_data= {'vibs':vibs,'avgtime':t},mod_spec=[{'_push': {'vibs':vibs,'time':t}}])
def main(): asedb = connect('/scratch/users/ksb/db/ase.db') initialQuestion = ( '\n%d relaxed bulk structure(s) passed filters+constraints.' % (nBulk) + '\nDo you want to create %d slabs?\n(y/n)--> ' % (ncombo)) if raw_input(initialQuestion).lower() in ['y', 'yes']: for combo in domainProduct: print combo ind, fac, xy, l, c, sym, vac, vacancy = combo facList = [int(z) for z in str(fac)] bare = makeSlab(ind, facList, l, sym, xy, vac) img = plot(bare) aseAtoms = AseAtomsAdaptor.get_atoms(bare) taggedAtoms = tag_atoms(aseAtoms) taggedAtoms.set_constraint( FixAtoms(indices=constrainAtoms(taggedAtoms, c, sym))) magmoms = [ magmomInit if (magmomInit and e in magElems) else 0 for e in taggedAtoms.get_chemical_symbols() ] taggedAtoms.set_initial_magnetic_moments(magmoms) taggedAtoms.set_calculator(EMT()) taggedAtoms.wrap() for i in vacancy: del taggedAtoms[i] prettyfacet = '-'.join([x for x in str(fac)]) prettyxy = '%sx%s' % (str(xy)[0], str(xy)[1]) name = '%s_%s_%s' % (asedb.get(ind).get('name'), prettyfacet, prettyxy) info = { 'name': name, 'relaxed': False, 'emt': taggedAtoms.get_potential_energy() / len(taggedAtoms) # normalize to per-atom basis , 'comments': 'Autogenerated by initializeBareSurf', 'kind': 'surface' # vs bulk/molecule , 'structure': asedb.get(ind).get('structure'), 'parent': ind #ase object surface was generated from , 'sites': img, 'facet': fac, 'xy': xy, 'layers': l, 'constrained': c, 'symmetric': sym, 'vacuum': vac, 'vacancies': str(vacancy) } parentJob = db2object(query1('jobtableid', 'aseid', ind, 'result')) if USER_APPROVAL: view(taggedAtoms) question = ( 'Does this structure look right?\nfacet= %s\nlayers = %d\nfixed = %d\n' % (prettyfacet, l, c) + 'vacuum = %d\nxy = %s\n %s\n\n(y/n) --> ' % (vac, prettyxy, parentJob.summary())) if not USER_APPROVAL or raw_input(question).lower() in [ 'y', 'yes' ]: n = sum([ 1 for x in asedb.select(parent=ind, facet=fac, xy=xy, layers=l, constrained=c, symmetric=sym, vacuum=vac, vacancies=str(vacancy)) ]) if n > 1: raise ValueError, 'Two things already in database have same parameters???' elif n == 1: print "matching structure already in database!" else: asedb.write(taggedAtoms, key_value_pairs=info)
def run_task(self,fw_spec): jobID = fw_spec['jobID'] job = db2object(jobID) if 'relax' in job.jobkind: pos = fw_spec['pos'][0] cell = fw_spec['cell'][0] if job.jobkind == 'bulkrelax' else job.cellinit() magmom = fw_spec['magmom'][0] db = connect('/scratch/users/ksb/db/ase.db') info = {'name': job.name() ,'emt': 0 # EMT for relaxed structures useless, only relevant for deciding when to relax something ,'relaxed': True # Could always doing this be a problem? ,'comments': 'Generated from #%d'%(job.aseidinitial) ,'parent': job.aseidinitial ,'jobid': job.jobid # Int ###Unchanged Things### ,'kind': job.kind()} # String if job.structure() is not None: info['structure'] = job.structure() if job.vacancies() is not None: info['vacancies'] = job.vacancies() if job.sites() is not None: info['sites'] = job.sites() if job.facet() is not None: info['facet'] = job.facet() if job.xy() is not None: info['xy'] = job.xy() if job.layers() is not None: info['layers'] = job.layers() if job.constrained() is not None: info['constrained'] = job.constrained() if job.symmetric() is not None: info['symmetric'] = job.symmetric() if job.vacuum() is not None: info['vacuum'] = job.vacuum() if job.adsorbates() is not None: info['adsorbates'] = job.adsorbates() optAtoms = Atoms(symbols = job.symbols() ,scaled_positions = pos ,cell = cell ,magmoms = magmom ,constraint = job.constraints() ,tags = job.tags()) aseid = db.write(optAtoms,key_value_pairs=info) else: aseid = None launchdir = fw_spec['_launch_dir'] energy = fw_spec['e0'][0] if 'relax' in job.jobkind else None forces = fw_spec['f0'][0] if 'relax' in job.jobkind else None bulkmodulus = fw_spec['b0'][0] if job.jobkind == 'bulkrelax' else None bfit = fw_spec['quadR2'][0] if job.jobkind == 'bulkrelax' else None xccoeffs = fw_spec['xcContribs'][0] if 'relax' in job.jobkind else None viblist = fw_spec['vibs'][0] if job.jobkind == 'vib' else None dos = fw_spec['dos'][0] if job.jobkind == 'dos' else None barrier = fw_spec['barrier'][0] if job.jobkind == 'neb' else None time = fw_spec['avgtime'][0] niter = fw_spec['niter'][0] if 'relax' in job.jobkind else None result = Result(jobID,launchdir,aseid=aseid,energy=energy,forces=forces ,bulkmodulus=bulkmodulus,bfit=bfit,xccoeffs=xccoeffs,viblist=viblist ,dos=dos,barrier=barrier,time=time,niter=niter) resultDict = {'_launch_dir':launchdir,'aseid':aseid,'energy':energy ,'forces':str(forces),'bulkmodulus':bulkmodulus ,'bfit':bfit,'xccoeffs':xccoeffs,'time':time ,'niter':niter,'viblist':viblist,'barrier':barrier} insertObject(result) # add result to bulkresult table updateDB('status','jobid',jobID,'complete') return FWAction(stored_data= resultDict)
def getFromJobObject(jobid): jobObject = db2object(jobid[0], jobtable) return f(jobObject)
def main(): jIDs = [x[0] for x in plotQuery(['jobid'], CONSTRAINTS)] question = "Going to add an %s interstitial to %d bulk objects.\n(y/n)--> " % ( inter, len(jIDs)) if raw_input(question).lower() in ['y', 'yes']: for j in jIDs: aseinitID = query1('aseid', 'jobid', j) aseinit = asedb.get_atoms(id=aseinitID) # Access information about previous Job / Atoms object jobinit = db2object(j) xc, pw, kptden = jobinit.xc, jobinit.pw, jobinit.kptden psp, xtol, strain = jobinit.psp, jobinit.xtol, jobinit.strain precalc, dftcode = jobinit.precalc, jobinit.dftcode nameinit = jobinit.name() structure = jobinit.structure() vacancies = jobinit.vacancies() # Create conventional PyMatGen Object pmg_init = AseAtomsAdaptor.get_structure(aseinit) pmg_init2 = SpacegroupAnalyzer( pmg_init).get_conventional_standard_structure() interstitial = Interstitial( pmg_init2, None, covalent_radii) #accuracy=high breaks... os.system('cls' if os.name == 'nt' else 'clear') for i, site in enumerate(interstitial.enumerate_defectsites()): coordination = int( round(interstitial.get_defectsite_coordination_number(i))) mult = 0 # interstitial.get_defectsite_multiplicity(i) -- broken ??? insert = InsertSitesTransformation([inter], [site.coords], coords_are_cartesian=True) pmg_new = insert.apply_transformation(pmg_init2.copy()) ase_new = AseAtomsAdaptor.get_atoms(pmg_new) ase_new.set_calculator(EMT()) emt = ase_new.get_potential_energy() if coordination == 4: siteName = 'T' elif coordination == 6: siteName = 'O' else: siteName = '%d-fold' % coordination question = ('site: %s\ncoordination: %s\nmultiplicity: %s' % (site.coords, coordination, mult) + '\ninitial ase id: %d \nxc: %s \npw: %d ' % (aseinitID, xc, pw) + '\nkptden: %f \npsp: %s\nxtol: %f\nstrain: %f' % (kptden, psp, xtol, strain) + '\nprecalc: %s \ndftcode: %s' % (precalc, dftcode) + '\n\nDoes this structure look good?\n(y/n)--> ') view(ase_new) if raw_input(question).lower() in ['y', 'yes']: if checkForDuplicates(ase_new, structure, emt): newquestion = 'What structure does this have?\n(leave blank for general triclinic case)\n--> ' structure = raw_input(newquestion) if structure is '': structure = 'triclinic' info = { 'name': nameinit + '_%s-%s' % (inter, siteName), 'emt': emt # EMT for relaxed structures useless, only relevant for deciding when to relax something , 'relaxed': False # Could always doing this be a problem? , 'comments': 'Generated from initializeHydride.py', 'parent': aseinitID, 'kind': 'bulk', 'structure': structure, 'interstitial': siteName } if vacancies is not None: info['vacancies'] = vacancies newaseid = asedb.write(ase_new, key_value_pairs=info) newjob = Job(None, 'bulkrelax', newaseid, None, None, xc, pw, kptden, psp, xtol, strain, 2 if xc == 'mBEEF' else 1, precalc, dftcode, None, None, 'initialized') insertObject(newjob)
def submitAll(): initializedJobs = [x[0] for x in plotQuery(['jobid'], [INITIALIZED])] if raw_input('Submit %d jobs?\n(y/n)--> ' % len(initializedJobs)).lower() in ['y', 'yes']: for jid in initializedJobs: db2object(jid).submit()