示例#1
0
    def vasp_vol_relax():
        Al = bulk('Al', 'fcc', a=4.5, cubic=True)
        calc = Vasp(xc='LDA',
                    isif=7,
                    nsw=5,
                    ibrion=1,
                    ediffg=-1e-3,
                    lwave=False,
                    lcharg=False)
        calc.calculate(Al)

        # Explicitly parse atomic position output file from Vasp
        CONTCAR_Al = io.read('CONTCAR', format='vasp')

        print('Stress after relaxation:\n', calc.read_stress())

        print('Al cell post relaxation from calc:\n',
              calc.get_atoms().get_cell())
        print('Al cell post relaxation from atoms:\n', Al.get_cell())
        print('Al cell post relaxation from CONTCAR:\n', CONTCAR_Al.get_cell())

        # All the cells should be the same.
        assert (calc.get_atoms().get_cell() == CONTCAR_Al.get_cell()).all()
        assert (Al.get_cell() == CONTCAR_Al.get_cell()).all()

        return Al
示例#2
0
def run_energy_eval(totalsol, calc_method='LAMMPS', fx_region=False, fit_scheme='totalenfit', STR='', static_calc=None):
    if calc_method=='VASP':
        en=totalsol.get_potential_energy()
        calcb=Vasp(restart=True)
        totalsol=calcb.get_atoms()
        stress=calcb.read_stress()
    else:
        totcop = totalsol.copy()
        OUT = totalsol.calc.calculate(totalsol)
        totalsol = OUT['atoms']
        pea = OUT['pea']
       # M: test
       # if MPI.COMM_WORLD.Get_rank() == 0:
       #   for i in range(len(totalsol)) :
       #      print i,totalsol[i].symbol,totalsol[i].position, pea[i]
        totalsol.set_pbc(True)
        if fx_region:
            STR+='Energy of fixed region calc = {0}\n'.format(OUT['thermo'][-1]['pe'])
            totalsol.set_calculator(static_calc)
            OUT=totalsol.calc.calculate(totalsol)
            totalsol=OUT['atoms']
            totalsol.set_pbc(True)
            STR+='Energy of static calc = {0}\n'.format(OUT['thermo'][-1]['pe'])
        en=OUT['thermo'][-1]['pe']
        stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
    if fit_scheme == 'enthalpyfit':
        pressure = totalsol.get_isotropic_pressure(stress)
    else:
        pressure = 0
    volume = totalsol.get_volume()
    energy=en
    STR+='Energy per atom = {0}\n'.format(energy/len(totalsol))
    return totalsol, pea, energy, pressure, volume, STR
示例#3
0
def run_energy_eval(totalsol, calc_method='LAMMPS', fx_region=False, fit_scheme='totalenfit', STR='', static_calc=None):
    if calc_method=='VASP':
        en=totalsol.get_potential_energy()
        calcb=Vasp(restart=True)
        totalsol=calcb.get_atoms()
        stress=calcb.read_stress()
    else:
        totcop = totalsol.copy()
        OUT = totalsol.calc.calculate(totalsol)
        totalsol = OUT['atoms']
        totalsol.set_pbc(True)
        if fx_region:
            STR+='Energy of fixed region calc = {0}\n'.format(OUT['thermo'][-1]['pe'])
            totalsol.set_calculator(static_calc)
            OUT=totalsol.calc.calculate(totalsol)
            totalsol=OUT['atoms']
            totalsol.set_pbc(True)
            STR+='Energy of static calc = {0}\n'.format(OUT['thermo'][-1]['pe'])
        en=OUT['thermo'][-1]['pe']
        stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
    if fit_scheme == 'enthalpyfit':
        pressure = totalsol.get_isotropic_pressure(stress)
    else:
        pressure = 0
    volume = totalsol.get_volume()
    energy=en
    STR+='Energy per atom = {0}\n'.format(energy/len(totalsol))
    return totalsol, energy, pressure, volume, STR
示例#4
0
def defect_strain_matrices(label,conc,Latt):
	from ase.calculators.vasp import Vasp
	calc = Vasp(restart=1)
	atoms = calc.get_atoms()
	LattDef = numpy.array(atoms.get_cell())
	# LattDef = correct_lattice_matrix(numpy.array(atoms.get_cell()))
	dstrain = (1/conc)*numpy.dot(numpy.subtract(LattDef,Latt),numpy.linalg.inv(Latt))
	dstrain_vec = asetools.tensorise(dstrain)
	outfile = 'defect_strain.txt'
	fout = open(outfile,'w')
	print>>fout, label
	print>>fout, "concentration {:^10}".format(conc)
	print>>fout, "defect strain matrix"
	for item in dstrain:
		print>>fout, '   '.join(map(str, item))
	print>>fout, "defect strain vector"
	for item in dstrain_vec:
		print>>fout, item
	print>>fout, "Defect supercell lattice"
	for item in LattDef:
		print>>fout, '   '.join(map(str, item))
	print>>fout, "Perfect supercell lattice"
	for item in Latt:
		print>>fout, '   '.join(map(str, item))
	fout.close
示例#5
0
def test_vasp_co():
    """
    Run some VASP tests to ensure that the VASP calculator works. This
    is conditional on the existence of the VASP_COMMAND or VASP_SCRIPT
    environment variables

    """

    from ase.test.vasp import installed

    assert installed()

    from ase import Atoms
    from ase.io import write
    from ase.calculators.vasp import Vasp
    import numpy as np

    def array_almost_equal(a1, a2, tol=np.finfo(type(1.0)).eps):
        """Replacement for old numpy.testing.utils.array_almost_equal."""
        return (np.abs(a1 - a2) < tol).all()

    d = 1.14
    co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True)
    co.center(vacuum=5.)

    calc = Vasp(xc='PBE',
                prec='Low',
                algo='Fast',
                ismear=0,
                sigma=1.,
                istart=0,
                lwave=False,
                lcharg=False)

    co.calc = calc
    en = co.get_potential_energy()
    write('vasp_co.traj', co)
    assert abs(en + 14.918933) < 5e-3

    # Secondly, check that restart from the previously created VASP output works

    calc2 = Vasp(restart=True)
    co2 = calc2.get_atoms()

    # Need tolerance of 1e-14 because VASP itself changes coordinates
    # slightly between reading POSCAR and writing CONTCAR even if no ionic
    # steps are made.
    assert array_almost_equal(co.positions, co2.positions, 1e-14)

    assert en - co2.get_potential_energy() == 0.
    assert array_almost_equal(calc.get_stress(co), calc2.get_stress(co2))
    assert array_almost_equal(calc.get_forces(co), calc2.get_forces(co2))
    assert array_almost_equal(calc.get_eigenvalues(), calc2.get_eigenvalues())
    assert calc.get_number_of_bands() == calc2.get_number_of_bands()
    assert calc.get_xc_functional() == calc2.get_xc_functional()

    # Cleanup
    calc.clean()
示例#6
0
def calc_defect_strain_matrix(Latt):
	from ase.calculators.vasp import Vasp
	# defect lattice
	calc = Vasp(restart=1)
	atoms = calc.get_atoms()
	LattDef = numpy.array(atoms.get_cell())
	dstrain = conc*numpy.dot(numpy.subtract(LattDef,Latt.T),numpy.linalg.inv(Latt.T))
	dstrain=asetools.symmetrize(dstrain)
	return dstrain
示例#7
0
def get_locpot_array(file):
	""" Returns the charge densities on the fine FFT-grid in a numpy array."""
	from ase.calculators.vasp import VaspChargeDensity
	from ase.calculators.vasp import Vasp
 	calc = Vasp(restart=True)
 	cell = calc.get_atoms()
 	vol = cell.get_volume()
	pot_array = numpy.vstack((VaspChargeDensity(file)).chg)
	numpy.divide(pot_array,vol)
	return pot_array
示例#8
0
def vasp_vol_relax():
    Al = bulk("Al", "fcc", a=4.5, cubic=True)
    calc = Vasp(xc="LDA", isif=7, nsw=5, ibrion=1, ediffg=-1e-3, lwave=False, lcharg=False)
    calc.calculate(Al)

    # Explicitly parse atomic position output file from Vasp
    CONTCAR_Al = io.read("CONTCAR", format="vasp")

    print("Stress after relaxation:\n", calc.read_stress())

    print("Al cell post relaxation from calc:\n", calc.get_atoms().get_cell())
    print("Al cell post relaxation from atoms:\n", Al.get_cell())
    print("Al cell post relaxation from CONTCAR:\n", CONTCAR_Al.get_cell())

    # All the cells should be the same.
    assert (calc.get_atoms().get_cell() == CONTCAR_Al.get_cell()).all()
    assert (Al.get_cell() == CONTCAR_Al.get_cell()).all()

    return Al
示例#9
0
def vasp_vol_relax():
    Al = bulk('Al', 'fcc', a=4.5, cubic=True)
    calc = Vasp(xc='LDA', isif=7, nsw=5,
                ibrion=1, ediffg=-1e-3, lwave=False, lcharg=False)
    calc.calculate(Al)

    # Explicitly parse atomic position output file from Vasp
    CONTCAR_Al = io.read('CONTCAR', format='vasp')

    print 'Stress after relaxation:\n', calc.read_stress()

    print 'Al cell post relaxation from calc:\n', calc.get_atoms().get_cell()
    print 'Al cell post relaxation from atoms:\n', Al.get_cell()
    print 'Al cell post relaxation from CONTCAR:\n', CONTCAR_Al.get_cell()

    # All the cells should be the same.
    assert (calc.get_atoms().get_cell() == CONTCAR_Al.get_cell()).all()
    assert (Al.get_cell() == CONTCAR_Al.get_cell()).all()

    return Al
示例#10
0
def ase_vol_relax():
    Al = bulk('Al', 'fcc', a=4.5, cubic=True)
    calc = Vasp(xc='LDA')
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter
    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile='relaxation.log')
    qn.run(fmax=0.1, steps=5)

    print 'Stress:\n', calc.read_stress()
    print 'Al post ASE volume relaxation\n', calc.get_atoms().get_cell()

    return Al
示例#11
0
    def ase_vol_relax():
        Al = bulk('Al', 'fcc', a=4.5, cubic=True)
        calc = Vasp(xc='LDA')
        Al.calc = calc

        from ase.constraints import StrainFilter
        sf = StrainFilter(Al)
        qn = QuasiNewton(sf, logfile='relaxation.log')
        qn.run(fmax=0.1, steps=5)

        print('Stress:\n', calc.read_stress())
        print('Al post ASE volume relaxation\n', calc.get_atoms().get_cell())

        return Al
示例#12
0
def ase_vol_relax():
    Al = bulk("Al", "fcc", a=4.5, cubic=True)
    calc = Vasp(xc="LDA")
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter

    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile="relaxation.log")
    qn.run(fmax=0.1, steps=5)

    print("Stress:\n", calc.read_stress())
    print("Al post ASE volume relaxation\n", calc.get_atoms().get_cell())

    return Al
示例#13
0
def setup_dvol_corrections_evq(self):
 from ase.calculators.vasp import Vasp
 calc = Vasp(restart=True)
 atoms = calc.get_atoms()
 cell = atoms.get_cell()
 #Create small and large lattice matrices
 small = cell*0.99
 large = cell*1.01
 # Setup the large and small POSCAR files
 atoms.set_cell(small, scale_atoms=True)
 ase.io.write('POSCAR99pc',atoms,format='vasp', direct=1)
 atoms.set_cell(large, scale_atoms=True)
 ase.io.write('POSCAR101pc',atoms,format='vasp', direct=1
 )
 # copy the basic VASP files to the new directories
 directories = ['0x99pc','1x00pc','1x01pc']
 files = ['KPOINTS','POTCAR','WAVECAR','CHGCAR']
 for dir in directories:
  if not os.path.exists(dir):
   os.makedirs(dir)
  for file in files:
   if os.path.exists(file):
    shutil.copy(file,dir)
 # copy the new POSCAR files to the new directories
 shutil.copy('POSCAR','1x00pc')
 shutil.copy('POSCAR99pc','0x99pc/POSCAR')
 shutil.copy('POSCAR101pc','1x01pc/POSCAR')
 # Edit INCAR to create a single point calculations, and save in new directories
 EVQ_INCAR = 'INCAR_EVQ'
 bad_words = ['NSW', 'LVTOT', 'NELM ', 'ISTART', 'ICHARG']
 with open('INCAR') as oldfile, open(EVQ_INCAR, 'w') as newfile:
  for line in oldfile:
   if not any(bad_word in line for bad_word in bad_words):
    newfile.write(line)
  newfile.write('ISTART = 0\nICHARGE = 2\nNSW  = 0\nLVTOT  = .TRUE.\nNELM  = 60\n')
 # Save the new INCAR in directories
 shutil.copy(EVQ_INCAR,'1x00pc/INCAR')
 shutil.copy(EVQ_INCAR,'0x99pc/INCAR')
 shutil.copy(EVQ_INCAR,'1x01pc/INCAR')
示例#14
0
def ase_run_vasp(mol, calc, job_dir, init_only=False):
    """
    This is used to set a vasp calculation in an ASE-based script 
      mode = 0: only create input files needed to run a vasp calculation 
      mode 
    """
    wdir = os.getcwd()
    if init_only:
        if not os.path.isdir(job_dir):
            os.mkdir(job_dir)
        os.chdir(job_dir)
        mol.set_calculator(calc)

        calc.initialize(mol)
        calc.write_input(mol)
        os.chdir(wdir)
        return 0.0

    if not os.path.isdir(job_dir):
        os.mkdir(job_dir)
        os.chdir(job_dir)
        mol.set_calculator(calc)
    else:
        os.chdir(job_dir)
        calc = Vasp(restart=True)
        mol = calc.get_atoms()

    try:
        ene = mol.get_potential_energy()
    except:
        print "ERROR: Fail when running vasp in " + job_dir
        os.system("touch ERROR")
        ene = 0.0

    os.chdir(wdir)

    return ene
示例#15
0
def output_cell_params():
	import fnmatch
	from ase.calculators.vasp import Vasp
	outfile = 'cell_params.txt'
	fout = open(outfile,'w')
	prelim_matches = []
	matches = []
	for root, dirnames, filenames in os.walk('.'):
		for filename in fnmatch.filter(filenames, 'OUTCAR'):
			prelim_matches.append(os.path.abspath(root))
	for dir in prelim_matches:
		if os.path.isfile(os.path.join(dir,"CONTCAR")):
			matches.append(dir)
	for dir in matches:
		os.chdir(dir)
		label = os.path.abspath(".")
		print>>fout, label
		print>>fout, "{:<14} {:^14} {:^14} {:^14} {:^14} {:^14} {:^14} ".format('volume','a','b','c','alpha','beta','gamma')
		calc = Vasp(restart=1)
		atoms = calc.get_atoms()
		params = asetools.cellparam(atoms)
		volume = atoms.get_volume()
		print>>fout, "{:<14} {:^14} {:^14} {:^14} {:^14} {:^14} {:^14} ".format(volume,params[0],params[1],params[2],params[3],params[4],params[5])
	fout.close
示例#16
0
                 outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False)
             individ[0]=outt[0]
             bul=outt[1]
             individ.vacancies = outt[2]
             individ.swaps = outt[3]
             STR += outt[4]
         indiv=individ[0]
     else:
         top,bul=find_top_layer(totalsol,Optimizer.surftopthick)
         indiv=top.copy()
         individ[0]=top.copy()
 else:
     if Optimizer.calc_method=='VASP':
         en=totalsol.get_potential_energy()
         calcb=Vasp(restart=True)
         totalsol=calcb.get_atoms()
         stress=calcb.read_stress()
     else:
         OUT=indiv.calc.calculate(indiv)
         en=OUT['thermo'][-1]['pe']
         #indiv.set_positions(OUT['atoms'].get_positions())
         #indiv.set_cell(OUT['atoms'].get_cell())
         indiv=OUT['atoms']
         indiv.set_pbc(True)
         stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
     if Optimizer.fitness_scheme == 'enthalpyfit':
         pressure=indiv.get_isotropic_pressure(stress)
         cell_max=numpy.maximum.reduce(indiv.get_positions())
         cell_min=numpy.minimum.reduce(indiv.get_positions())
         cell=cell_max-cell_min
         volume=cell[0]*cell[1]*cell[2]
示例#17
0
#!/usr/bin/env python
import os
from ase.io import read, write
from ase.calculators.vasp import Vasp
import sys

try:
    tar = sys.argv[1]
except IndexError:
    print "please give the name of the folder"
    exit()

if os.path.isfile('fin.traj'):
    calc = Vasp(restart=True)
    p = calc.get_atoms()
    p.set_initial_magnetic_moments(p.get_magnetic_moments())
    write('fin.traj', p)
    os.system('vfin.pl ' + str(tar))

    os.system('cp init.traj fin.traj ' + str(tar))
    os.system('cp  ' + str(tar) + '/fe.dat  .')
    os.system('rm init.traj')
else:
    os.system('vfin.pl ' + str(tar))
    os.system('cp init.traj ' + str(tar))
    ptmp = read(str(tar) + '/CONTCAR')
    pini = read(str(tar) + '/init.traj')
    mag = pini.get_initial_magnetic_moments()
    ptmp.set_initial_magnetic_moments(mag)
    write('init.traj', ptmp)
示例#18
0
                     debug=False)
             individ[0] = outt[0]
             bul = outt[1]
             individ.vacancies = outt[2]
             individ.swaps = outt[3]
             STR += outt[4]
         indiv = individ[0]
     else:
         top, bul = find_top_layer(totalsol, Optimizer.surftopthick)
         indiv = top.copy()
         individ[0] = top.copy()
 else:
     if Optimizer.calc_method == 'VASP':
         en = totalsol.get_potential_energy()
         calcb = Vasp(restart=True)
         totalsol = calcb.get_atoms()
         stress = calcb.read_stress()
     else:
         OUT = indiv.calc.calculate(indiv)
         en = OUT['thermo'][-1]['pe']
         #indiv.set_positions(OUT['atoms'].get_positions())
         #indiv.set_cell(OUT['atoms'].get_cell())
         indiv = OUT['atoms']
         indiv.set_pbc(True)
         stress = numpy.array([
             OUT['thermo'][-1][i]
             for i in ('pxx', 'pyy', 'pzz', 'pyz', 'pxz', 'pxy')
         ]) * (-1e-4 * GPa)
     if Optimizer.fitness_scheme == 'enthalpyfit':
         pressure = indiv.get_isotropic_pressure(stress)
         cell_max = numpy.maximum.reduce(indiv.get_positions())
示例#19
0
def eval_energy(input):
    """Function to evaluate energy of an individual
    Inputs:
        input = [Optimizer class object with parameters, Individual class structure to be evaluated]
    Outputs:
        energy, bul, individ, signal
        energy = energy of Individual evaluated
        bul = bulk structure of Individual if simulation structure is Defect
        individ = Individual class structure evaluated
        signal = string of information about evaluation
    """
    if input[0] == None:
        energy = 0
        bul = 0
        individ = 0
        rank = MPI.COMM_WORLD.Get_rank()
        signal = 'Evaluated none individual on ' + repr(rank) + '\n'
    else:
        [Optimizer, individ] = input
    if Optimizer.calc_method == 'MAST':
        energy = individ.energy
        bul = individ.energy
        signal = 'Recieved MAST structure\n'
    else:
        if Optimizer.parallel: rank = MPI.COMM_WORLD.Get_rank()
        if not Optimizer.genealogy:
            STR = '----Individual ' + str(
                individ.index) + ' Optimization----\n'
        else:
            STR = '----Individual ' + str(
                individ.history_index) + ' Optimization----\n'
        indiv = individ[0]
        if 'EE' in Optimizer.debug:
            debug = True
        else:
            debug = False
        if debug:
            write_xyz(Optimizer.debugfile, indiv, 'Recieved by eval_energy')
            Optimizer.debugfile.flush()
        if Optimizer.structure == 'Defect':
            indi = indiv.copy()
            if Optimizer.alloy == True:
                bulk = individ.bulki
            else:
                bulk = individ.bulko
            nat = indi.get_number_of_atoms()
            csize = bulk.get_cell()
            totalsol = Atoms(cell=csize, pbc=True)
            totalsol.extend(indi)
            totalsol.extend(bulk)
            for sym, c, m, u in Optimizer.atomlist:
                nc = len([atm for atm in totalsol if atm.symbol == sym])
                STR += 'Defect configuration contains ' + repr(
                    nc) + ' ' + repr(sym) + ' atoms\n'

        elif Optimizer.structure == 'Surface':
            totalsol = Atoms()
            totalsol.extend(indiv)
            nat = indiv.get_number_of_atoms()
            totalsol.extend(individ.bulki)
            for sym, c, m, u in Optimizer.atomlist:
                nc = len([atm for atm in totalsol if atm.symbol == sym])
                STR += 'Surface-Bulk configuration contains ' + repr(
                    nc) + ' ' + repr(sym) + ' atoms\n'
            cell = numpy.maximum.reduce(indiv.get_cell())
            totalsol.set_cell([cell[0], cell[1], 500])
            totalsol.set_pbc([True, True, False])

        if Optimizer.constrain_position:
            ts = totalsol.copy()
            indc, indb, vacant, swap, stro = find_defects(
                ts, Optimizer.solidbulk, 0)
            sbulk = Optimizer.solidbulk.copy()
            bcom = sbulk.get_center_of_mass()
            #totalsol.translate(-bulkcom)
            #indc.translate(-bulkcom)
            #totalsol.append(Atom(position=[0,0,0]))
            # 			for one in indc:
            # 				index = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
            # 				if totalsol.get_distance(-1,index) > Optimizer.sf:
            # 					r = random.random()
            # 					totalsol.set_distance(-1,index,Optimizer.sf*r,fix=0)
            # 			totalsol.pop()
            # 			totalsol.translate(bulkcom)
            com = indc.get_center_of_mass()
            dist = (sum((bcom[i] - com[i])**2 for i in range(3)))**0.5
            if dist > Optimizer.sf:
                STR += 'Shifting structure to within region\n'
                r = random.random() * Optimizer.sf
                comv = numpy.linalg.norm(com)
                ncom = [one * r / comv for one in com]
                trans = [ncom[i] - com[i] for i in range(3)]
                indices = []
                for one in indc:
                    id = [
                        atm.index for atm in totalsol
                        if atm.position[0] == one.position[0]
                        and atm.position[1] == one.position[1]
                        and atm.position[2] == one.position[2]
                    ][0]
                    totalsol[id].position += trans

        # Check for atoms that are too close
        min_len = 0.7
        #pdb.set_trace()
        if not Optimizer.fixed_region:
            if Optimizer.structure == 'Defect' or Optimizer.structure == 'Surface':
                cutoffs = [2.0 for one in totalsol]
                nl = NeighborList(cutoffs,
                                  bothways=True,
                                  self_interaction=False)
                nl.update(totalsol)
                for one in totalsol[0:nat]:
                    nbatoms = Atoms()
                    nbatoms.append(one)
                    indices, offsets = nl.get_neighbors(one.index)
                    for index, d in zip(indices, offsets):
                        index = int(index)
                        sym = totalsol[index].symbol
                        pos = totalsol[index].position + numpy.dot(
                            d, totalsol.get_cell())
                        at = Atom(symbol=sym, position=pos)
                        nbatoms.append(at)
                    while True:
                        dflag = False
                        for i in range(1, len(nbatoms)):
                            d = nbatoms.get_distance(0, i)
                            if d < min_len:
                                nbatoms.set_distance(0,
                                                     i,
                                                     min_len + .01,
                                                     fix=0.5)
                                STR += '--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                                dflag = True
                        if dflag == False:
                            break
                    for i in range(len(indices)):
                        totalsol[indices[i]].position = nbatoms[i + 1].position
                    totalsol[one.index].position = nbatoms[0].position
                    nl.update(totalsol)
                if debug:
                    write_xyz(Optimizer.debugfile, totalsol,
                              'After minlength check')
                    Optimizer.debugfile.flush()
            else:
                for i in range(len(indiv)):
                    for j in range(len(indiv)):
                        if i != j:
                            d = indiv.get_distance(i, j)
                            if d < min_len:
                                indiv.set_distance(i, j, min_len, fix=0.5)
                                STR += '--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                if debug:
                    write_xyz(Optimizer.debugfile, indiv,
                              'After minlength check')
                    Optimizer.debugfile.flush()

        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                pms = copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][
                        len(pms['mass']) - 1] += '\ngroup RO id >= ' + repr(
                            nat) + '\nfix freeze RO setforce 0.0 0.0 0.0\n'
                except KeyError:
                    pms['pair_coeff'][0] += '\ngroup RO id >= ' + repr(
                        nat) + '\nfix freeze RO setforce 0.0 0.0 0.0\n'
                calc = LAMMPS(parameters=pms,
                              files=calc.files,
                              keep_tmp_files=calc.keep_tmp_files,
                              tmp_dir=calc.tmp_dir)
                lmin = copy.copy(Optimizer.lammps_min)
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc = Optimizer.calc
        if Optimizer.structure == 'Defect' or Optimizer.structure == 'Surface':
            totalsol.set_calculator(calc)
            totalsol.set_pbc(True)
        else:
            indiv.set_calculator(calc)
            indiv.set_pbc(
                True)  #Current bug in ASE optimizer-Lammps prevents pbc=false
            if Optimizer.structure == 'Cluster':
                indiv.set_cell([500, 500, 500])
                indiv.translate([250, 250, 250])

        cwd = os.getcwd()
        # Perform Energy Minimization
        if not Optimizer.parallel:
            Optimizer.output.flush()
        if Optimizer.ase_min == True:
            try:
                if Optimizer.structure == 'Defect' or Optimizer.structure == 'Surface':
                    dyn = BFGS(totalsol)
                else:
                    dyn = BFGS(indiv)
                dyn.run(fmax=Optimizer.ase_min_fmax,
                        steps=Optimizer.ase_min_maxsteps)
            except OverflowError:
                STR += '--- Error: Infinite Energy Calculated - Implement Random ---\n'
                box = Atoms()
                indiv = gen_pop_box(Optimizer.natoms, Optimizer.atomlist,
                                    Optimizer.size)
                indiv.set_calculator(calc)
                dyn = BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            except numpy.linalg.linalg.LinAlgError:
                STR += '--- Error: Singular Matrix - Implement Random ---\n'
                indiv = gen_pop_box(Optimizer.natoms, Optimizer.atomlist,
                                    Optimizer.size)
                indiv.set_calculator(calc)
                dyn = BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            # Get Energy of Minimized Structure
            if Optimizer.structure == 'Defect' or Optimizer.structure == 'Surface':
                en = totalsol.get_potential_energy()
                #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure = totalsol.get_isotropic_pressure(
                        totalsol.get_stress())
                    cell_max = numpy.maximum.reduce(totalsol.get_positions())
                    cell_min = numpy.minimum.reduce(totalsol.get_positions())
                    cell = cell_max - cell_min
                    volume = cell[0] * cell[1] * cell[2]
                else:
                    pressure = 0
                    volume = 0
                na = totalsol.get_number_of_atoms()
                ena = en / na
                energy = en
                individ[0] = totalsol[0:nat]
                bul = totalsol[(nat):len(totalsol)]
                STR += 'Number of positions = ' + repr(
                    len(bul) + len(individ[0])) + '\n'
                individ[0].set_cell(csize)
                indiv = individ[0]
            else:
                en = indiv.get_potential_energy()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure = indiv.get_isotropic_pressure(indiv.get_stress())
                    cell_max = numpy.maximum.reduce(indiv.get_positions())
                    cell_min = numpy.minimum.reduce(indiv.get_positions())
                    cell = cell_max - cell_min
                    volume = cell[0] * cell[1] * cell[2]
                else:
                    pressure = 0
                    volume = 0
                na = indiv.get_number_of_atoms()
                ena = en / na
                energy = ena
                individ[0] = indiv
                bul = 0
        else:
            if Optimizer.structure == 'Defect' or Optimizer.structure == 'Surface':
                if Optimizer.calc_method == 'VASP':
                    en = totalsol.get_potential_energy()
                    calcb = Vasp(restart=True)
                    totalsol = calcb.get_atoms()
                    stress = calcb.read_stress()
                else:
                    try:
                        totcop = totalsol.copy()
                        if debug:
                            write_xyz(Optimizer.debugfile, totcop,
                                      'Individual sent to lammps')
                        OUT = totalsol.calc.calculate(totalsol)
                        totalsol = OUT['atoms']
                        totalsol.set_pbc(True)
                        if Optimizer.fixed_region:
                            if debug:
                                print 'Energy of fixed region calc = ', OUT[
                                    'thermo'][-1]['pe']
                            totalsol.set_calculator(Optimizer.static_calc)
                            OUT = totalsol.calc.calculate(totalsol)
                            totalsol = OUT['atoms']
                            totalsol.set_pbc(True)
                            if debug:
                                print 'Energy of static calc = ', OUT[
                                    'thermo'][-1]['pe']
                        en = OUT['thermo'][-1]['pe']
                        stress = numpy.array([
                            OUT['thermo'][-1][i]
                            for i in ('pxx', 'pyy', 'pzz', 'pyz', 'pxz', 'pxy')
                        ]) * (-1e-4 * GPa)
                        #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                        if debug:
                            write_xyz(Optimizer.debugfile, totalsol,
                                      'After Lammps Minimization')
                            Optimizer.debugfile.flush()
                    except Exception, e:
                        os.chdir(cwd)
                        STR += 'WARNING: Exception during energy eval:\n' + repr(
                            e) + '\n'
                        f = open('problem-structures.xyz', 'a')
                        write_xyz(f,
                                  totcop,
                                  data='Starting structure hindex=' +
                                  individ.history_index)
                        write_xyz(f, totalsol, data='Lammps Min structure')
                        en = 10
                        stress = 0
                        f.close()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure = totalsol.get_isotropic_pressure(stress)
                    cell_max = numpy.maximum.reduce(totalsol.get_positions())
                    cell_min = numpy.minimum.reduce(totalsol.get_positions())
                    cell = cell_max - cell_min
                    volume = cell[0] * cell[1] * cell[2]
                else:
                    pressure = totalsol.get_isotropic_pressure(stress)
                    volume = 0
                na = totalsol.get_number_of_atoms()
                ena = en / na
                energy = en
                if Optimizer.structure == 'Defect':
                    if Optimizer.fixed_region == True or Optimizer.finddefects == False:
                        individ[0] = totalsol[0:nat]
                        bul = totalsol[(nat):len(totalsol)]
                        individ[0].set_cell(csize)
                    else:
                        if 'FI' in Optimizer.debug:
                            outt = find_defects(
                                totalsol,
                                Optimizer.solidbulk,
                                Optimizer.sf,
                                atomlistcheck=Optimizer.atomlist,
                                trackvacs=Optimizer.trackvacs,
                                trackswaps=Optimizer.trackswaps,
                                debug=Optimizer.debugfile)
                        else:
                            outt = find_defects(
                                totalsol,
                                Optimizer.solidbulk,
                                Optimizer.sf,
                                atomlistcheck=Optimizer.atomlist,
                                trackvacs=Optimizer.trackvacs,
                                trackswaps=Optimizer.trackswaps,
                                debug=False)
                        individ[0] = outt[0]
                        bul = outt[1]
                        individ.vacancies = outt[2]
                        individ.swaps = outt[3]
                        STR += outt[4]
                    indiv = individ[0]
                else:
                    top, bul = find_top_layer(totalsol, Optimizer.surftopthick)
                    indiv = top.copy()
                    individ[0] = top.copy()
            else:
示例#20
0
            prec = 'Low',
            algo = 'Fast',
            ismear= 0,
            sigma = 1.,
            istart = 0,
            lwave = False,
            lcharg = False)

co.set_calculator(calc)
en = co.get_potential_energy()
assert abs(en + 14.918933) < 1e-4

# Secondly, check that restart from the previously created VASP output works

calc2 = Vasp(restart=True)
co2 = calc2.get_atoms()

# Need tolerance of 1e-14 because VASP itself changes coordinates
# slightly between reading POSCAR and writing CONTCAR even if no ionic
# steps are made.
assert array_almost_equal(co.positions, co2.positions, 1e-14)

assert en - co2.get_potential_energy() == 0.
assert array_almost_equal(calc.get_stress(co), calc2.get_stress(co2))
assert array_almost_equal(calc.get_forces(co), calc2.get_forces(co2))
assert array_almost_equal(calc.get_eigenvalues(), calc2.get_eigenvalues())
assert calc.get_number_of_bands() == calc2.get_number_of_bands()
assert calc.get_xc_functional() == calc2.get_xc_functional()

# Cleanup
calc.clean()
示例#21
0
文件: vasp_co.py 项目: lqcata/ase
            prec='Low',
            algo='Fast',
            ismear=0,
            sigma=1.,
            istart=0,
            lwave=False,
            lcharg=False)

co.set_calculator(calc)
en = co.get_potential_energy()
assert abs(en + 14.918933) < 1e-4

# Secondly, check that restart from the previously created VASP output works

calc2 = Vasp(restart=True)
co2 = calc2.get_atoms()

# Need tolerance of 1e-14 because VASP itself changes coordinates
# slightly between reading POSCAR and writing CONTCAR even if no ionic
# steps are made.
assert array_almost_equal(co.positions, co2.positions, 1e-14)

assert en - co2.get_potential_energy() == 0.
assert array_almost_equal(calc.get_stress(co), calc2.get_stress(co2))
assert array_almost_equal(calc.get_forces(co), calc2.get_forces(co2))
assert array_almost_equal(calc.get_eigenvalues(), calc2.get_eigenvalues())
assert calc.get_number_of_bands() == calc2.get_number_of_bands()
assert calc.get_xc_functional() == calc2.get_xc_functional()

# Cleanup
calc.clean()
示例#22
-1
def eval_energy(input):
    """Function to evaluate energy of an individual
    Inputs:
        input = [Optimizer class object with parameters, Individual class structure to be evaluated]
    Outputs:
        energy, bul, individ, signal
        energy = energy of Individual evaluated
        bul = bulk structure of Individual if simulation structure is Defect
        individ = Individual class structure evaluated
        signal = string of information about evaluation
    """
    if input[0]==None:
        energy=0
        bul=0
        individ=0
        rank = MPI.COMM_WORLD.Get_rank()
        signal='Evaluated none individual on '+repr(rank)+'\n'
    else:
        [Optimizer, individ]=input
    if Optimizer.calc_method=='MAST':
        energy = individ.energy
        bul = individ.energy
        signal = 'Recieved MAST structure\n'
    else:
        if Optimizer.parallel: rank = MPI.COMM_WORLD.Get_rank()
        if not Optimizer.genealogy:
            STR='----Individual ' + str(individ.index)+ ' Optimization----\n'
        else:
            STR='----Individual ' + str(individ.history_index)+ ' Optimization----\n'
        indiv=individ[0]
        if 'EE' in Optimizer.debug:
            debug = True
        else:
            debug = False
        if debug: 
            write_xyz(Optimizer.debugfile,indiv,'Recieved by eval_energy')
            Optimizer.debugfile.flush()
        if Optimizer.structure=='Defect':
            indi=indiv.copy()
            if Optimizer.alloy==True:
                bulk=individ.bulki
            else:
                bulk=individ.bulko
            nat=indi.get_number_of_atoms()
            csize=bulk.get_cell()                                                                                                         
            totalsol=Atoms(cell=csize, pbc=True)
            totalsol.extend(indi)
            totalsol.extend(bulk)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Defect configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
    
        elif Optimizer.structure=='Surface':
            totalsol=Atoms()
            totalsol.extend(indiv)
            nat=indiv.get_number_of_atoms()
            totalsol.extend(individ.bulki)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Surface-Bulk configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
            cell=numpy.maximum.reduce(indiv.get_cell())
            totalsol.set_cell([cell[0],cell[1],500])
            totalsol.set_pbc([True,True,False])
    
        if Optimizer.constrain_position:
            ts = totalsol.copy()
            indc,indb,vacant,swap,stro = find_defects(ts,Optimizer.solidbulk,0)
            sbulk = Optimizer.solidbulk.copy()
            bcom = sbulk.get_center_of_mass()
            #totalsol.translate(-bulkcom)
            #indc.translate(-bulkcom)
            #totalsol.append(Atom(position=[0,0,0]))
    # 			for one in indc:
    # 				index = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
    # 				if totalsol.get_distance(-1,index) > Optimizer.sf:
    # 					r = random.random()
    # 					totalsol.set_distance(-1,index,Optimizer.sf*r,fix=0)
    # 			totalsol.pop()
    # 			totalsol.translate(bulkcom)
            com = indc.get_center_of_mass()
            dist = (sum((bcom[i] - com[i])**2 for i in range(3)))**0.5
            if dist > Optimizer.sf:
                STR+='Shifting structure to within region\n'
                r = random.random()*Optimizer.sf
                comv = numpy.linalg.norm(com)
                ncom = [one*r/comv for one in com]
                trans = [ncom[i]-com[i] for i in range(3)]
                indices = []
                for one in indc:
                    id = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
                    totalsol[id].position += trans
    
        # Check for atoms that are too close
        min_len=0.7
        #pdb.set_trace()
        if not Optimizer.fixed_region:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                cutoffs=[2.0 for one in totalsol]
                nl=NeighborList(cutoffs,bothways=True,self_interaction=False)
                nl.update(totalsol)
                for one in totalsol[0:nat]:
                    nbatoms=Atoms()
                    nbatoms.append(one)
                    indices, offsets=nl.get_neighbors(one.index)
                    for index, d in zip(indices,offsets):
                        index = int(index)
                        sym=totalsol[index].symbol
                        pos=totalsol[index].position + numpy.dot(d,totalsol.get_cell())
                        at=Atom(symbol=sym,position=pos)
                        nbatoms.append(at)
                    while True:
                        dflag=False
                        for i in range(1,len(nbatoms)):
                            d=nbatoms.get_distance(0,i)
                            if d < min_len:
                                nbatoms.set_distance(0,i,min_len+.01,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                                dflag=True
                        if dflag==False:
                            break
                    for i in range(len(indices)):
                        totalsol[indices[i]].position=nbatoms[i+1].position
                    totalsol[one.index].position=nbatoms[0].position
                    nl.update(totalsol)
                if debug:
                    write_xyz(Optimizer.debugfile,totalsol,'After minlength check')
                    Optimizer.debugfile.flush()
            else:
                for i in range(len(indiv)):
                    for j in range(len(indiv)):
                        if i != j:
                            d=indiv.get_distance(i,j)
                            if d < min_len:
                                indiv.set_distance(i,j,min_len,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                if debug:
                    write_xyz(Optimizer.debugfile,indiv,'After minlength check')
                    Optimizer.debugfile.flush()
    
        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                pms=copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][len(pms['mass'])-1] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                except KeyError:
                    pms['pair_coeff'][0] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                calc = LAMMPS(parameters=pms, files=calc.files, keep_tmp_files=calc.keep_tmp_files, tmp_dir=calc.tmp_dir)
                lmin = copy.copy(Optimizer.lammps_min)
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc=Optimizer.calc
        if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
            totalsol.set_calculator(calc)
            totalsol.set_pbc(True)
        else:
            indiv.set_calculator(calc)
            indiv.set_pbc(True)	#Current bug in ASE optimizer-Lammps prevents pbc=false 
            if Optimizer.structure=='Cluster':
                indiv.set_cell([500,500,500])
                indiv.translate([250,250,250])
    
        cwd=os.getcwd()
        # Perform Energy Minimization
        if not Optimizer.parallel:
            Optimizer.output.flush()
        if Optimizer.ase_min == True:
            try:
                if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                    dyn=BFGS(totalsol)
                else:
                    dyn=BFGS(indiv)
                dyn.run(fmax=Optimizer.ase_min_fmax, steps=Optimizer.ase_min_maxsteps)
            except OverflowError:
                STR+='--- Error: Infinite Energy Calculated - Implement Random ---\n'
                box=Atoms()
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            except numpy.linalg.linalg.LinAlgError:
                STR+='--- Error: Singular Matrix - Implement Random ---\n'
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            # Get Energy of Minimized Structure
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                en=totalsol.get_potential_energy()
                #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(totalsol.get_stress())
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=0
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                individ[0]=totalsol[0:nat]
                bul=totalsol[(nat):len(totalsol)]
                STR+='Number of positions = '+repr(len(bul)+len(individ[0]))+'\n'
                individ[0].set_cell(csize)
                indiv=individ[0]
            else:
                en=indiv.get_potential_energy()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=indiv.get_isotropic_pressure(indiv.get_stress())
                    cell_max=numpy.maximum.reduce(indiv.get_positions())
                    cell_min=numpy.minimum.reduce(indiv.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else: 
                    pressure=0
                    volume=0
                na=indiv.get_number_of_atoms()
                ena=en/na
                energy=ena
                individ[0]=indiv
                bul=0
        else:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                if Optimizer.calc_method=='VASP':
                    en=totalsol.get_potential_energy()
                    calcb=Vasp(restart=True)
                    totalsol=calcb.get_atoms()
                    stress=calcb.read_stress()
                else:
                    try:
                        totcop=totalsol.copy()
                        if debug: write_xyz(Optimizer.debugfile,totcop,'Individual sent to lammps')
                        OUT=totalsol.calc.calculate(totalsol)
                        totalsol=OUT['atoms']
                        totalsol.set_pbc(True)
                        if Optimizer.fixed_region:
                            if debug:
                                print 'Energy of fixed region calc = ', OUT['thermo'][-1]['pe']
                            totalsol.set_calculator(Optimizer.static_calc)
                            OUT=totalsol.calc.calculate(totalsol)
                            totalsol=OUT['atoms']
                            totalsol.set_pbc(True)
                            if debug:
                                print 'Energy of static calc = ', OUT['thermo'][-1]['pe']
                        en=OUT['thermo'][-1]['pe']
                        stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
                        #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                        if debug:
                            write_xyz(Optimizer.debugfile,totalsol,'After Lammps Minimization')
                            Optimizer.debugfile.flush()
                    except Exception, e:
                        os.chdir(cwd)
                        STR+='WARNING: Exception during energy eval:\n'+repr(e)+'\n'
                        f=open('problem-structures.xyz','a')
                        write_xyz(f,totcop,data='Starting structure hindex='+individ.history_index)
                        write_xyz(f,totalsol,data='Lammps Min structure')
                        en=10
                        stress=0
                        f.close()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(stress)
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=totalsol.get_isotropic_pressure(stress)
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                if Optimizer.structure=='Defect':
                    if Optimizer.fixed_region==True or Optimizer.finddefects==False:
                        individ[0]=totalsol[0:nat]
                        bul=totalsol[(nat):len(totalsol)]
                        individ[0].set_cell(csize)
                    else:
                        if 'FI' in Optimizer.debug:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=Optimizer.debugfile)
                        else:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False)
                        individ[0]=outt[0]
                        bul=outt[1]
                        individ.vacancies = outt[2]
                        individ.swaps = outt[3]
                        STR += outt[4]
                    indiv=individ[0]
                else:
                    top,bul=find_top_layer(totalsol,Optimizer.surftopthick)
                    indiv=top.copy()
                    individ[0]=top.copy()
            else: