コード例 #1
0
ファイル: cell_relax_lammps.py プロジェクト: m-yu/MAST
def cell_relax_lammps(indiv, Optimizer):
    """Move function to perform Lammps box/relax for cell. Intended for use in Crystal Optimization
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    cwd1=os.getcwd()
    Optimizer.output.write('LAMMPS fix box/relax performed\n')
    parameters=copy.deepcopy(Optimizer.calc.parameters)
    passflag=True
    try:
        parameters['mass'][len(parameters['mass'])-1] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    except KeyError:
        try:
            parameters['pair_coeff'][0] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
        except KeyError:
            print 'WARNING: LAMMPS Cell relax move trouble with potential. SKIPPING'
            Optimizer.output.write('WARNING: Minimizer quit.  LAMMPS Cell relax move trouble with potential - Box relaxation unsuccessful\n')
            passflag=False
    if passflag:
        filesL = [ Optimizer.pot_file ]
        if Optimizer.lammps_keep_files:
            rank = 0
            path = os.path.join(os.getcwd(),'{0}-rank{1}'.format(Optimizer.filename,rank))
            if not os.path.exists(os.path.join(path,'LAMMPSFiles')):
                            os.mkdir(os.path.join(path,'LAMMPSFiles'))

            real_rank = MPI.COMM_WORLD.Get_rank()
            tmpdir = os.path.join(os.path.join(path, 'LAMMPSFiles'),'rank-{0}'.format(real_rank))
           # calc2 = LAMMPS(parameters=parameters, files=filesL,keep_tmp_files=True, tmp_dir=os.getcwd()+'/'+Optimizer.filename+'/Lammpsrun2/')
            calc2 = LAMMPS(parameters=parameters, files=filesL,keep_tmp_files=True, tmp_dir=tmpdir)
        else:
            calc2 = LAMMPS(parameters=parameters, files=filesL)
        atmsdup=indiv[0].copy()
        atmsdup.set_calculator(calc2)
        try:
            OUT=atmsdup.calc.calculate(atmsdup)
            indiv[0].set_cell(OUT['atoms'].get_cell())
            indiv[0].set_positions(OUT['atoms'].get_positions())
            Optimizer.output.write('Energy = '+repr(OUT['thermo'][-1]['pe']/indiv[0].get_number_of_atoms())+'\n')
        except:
            Optimizer.output.write('WARNING: Minimizer quit - Box relaxation unsuccessful\n')
        #pdb.set_trace()
        os.chdir(cwd1)
        calc2.clean()
        Optimizer.output.write(repr(indiv[0].get_cell())+'\n')
        muttype='LBR'
        if indiv.energy==0:
            indiv.history_index=indiv.history_index+'m'+muttype
        else:
            indiv.history_index=repr(indiv.index)+'m'+muttype
    return indiv
コード例 #2
0
def setup_fixed_region_calculator(Optimizer):
    """Function to set up a fixed region calculator for use with LAMMPS and ASE
    """
    calc = self.calc
    pms = copy.deepcopy(calc.parameters)
    nat = sum([c for sym,c,m,mu in self.atomlist])
    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'
    ncalc = LAMMPS(parameters=pms, files=calc.files,
    keep_tmp_files=calc.keep_tmp_files, tmp_dir=calc.tmp_dir)
    return ncalc
コード例 #3
0
ファイル: cell_relax_lammps.py プロジェクト: zhenming-xu/MAST
def cell_relax_lammps(indiv, Optimizer):
    """Move function to perform Lammps box/relax for cell. Intended for use in Crystal Optimization
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    cwd1=os.getcwd()
    Optimizer.output.write('LAMMPS fix box/relax performed\n')
    parameters=copy.deepcopy(Optimizer.calc.parameters)
    passflag=True
    try:
        parameters['mass'][len(parameters['mass'])-1] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    except KeyError:
        try:
            parameters['pair_coeff'][0] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
        except KeyError:
            print 'WARNING: LAMMPS Cell relax move trouble with potential. SKIPPING'
            Optimizer.output.write('WARNING: Minimizer quit.  LAMMPS Cell relax move trouble with potential - Box relaxation unsuccessful\n')
            passflag=False
    if passflag:
        filesL = [ Optimizer.pot_file ]
        if Optimizer.lammps_keep_files:
            calc2 = LAMMPS(parameters=parameters, files=filesL,keep_tmp_files=True, tmp_dir=os.getcwd()+'/'+Optimizer.filename+'/Lammpsrun2/')
        else:
            calc2 = LAMMPS(parameters=parameters, files=filesL)
        atmsdup=indiv[0].copy()
        atmsdup.set_calculator(calc2)
        try:
            OUT=atmsdup.calc.calculate(atmsdup)
            indiv[0].set_cell(OUT['atoms'].get_cell())
            indiv[0].set_positions(OUT['atoms'].get_positions())
            Optimizer.output.write('Energy = '+repr(OUT['thermo'][-1]['pe']/indiv[0].get_number_of_atoms())+'\n')
        except:
            Optimizer.output.write('WARNING: Minimizer quit - Box relaxation unsuccessful\n')
        #pdb.set_trace()
        os.chdir(cwd1)
        calc2.clean()
        Optimizer.output.write(repr(indiv[0].get_cell())+'\n')
        muttype='LBR'
        if indiv.energy==0:
            indiv.history_index=indiv.history_index+'m'+muttype
        else:
            indiv.history_index=repr(indiv.index)+'m'+muttype
    return indiv
コード例 #4
0
def eval_energy(Optimizer, individ):
    """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
    """
    #logger = initialize_logger(Optimizer.loggername)
    logger = logging.getLogger(Optimizer.loggername)
    if 'MAST' in Optimizer.calc_method:
        energy = individ.energy
        bul = individ.bulki
        signal = 'Received MAST structure\n'
        logger.info(
            'Received individual index = {0} from MAST with energy {1}. Returning with no evaluation'
            .format(individ.index, individ.energy))
    else:
        if Optimizer.parallel:
            rank = MPI.COMM_WORLD.Get_rank()
        logger.info(
            'Received individual HI = {0} with energy {1} for energy evaluation'
            .format(individ.history_index, individ.energy))
        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, 'Received by eval_energy')
            Optimizer.debugfile.flush()
            logger.debug('Writing recieved individual to debug file')
        # Establish individual structure for evaluation.  Piece together regions when necessary.
        if Optimizer.structure == 'Defect':
            indi = indiv.copy()
            bulk = individ.bulki
            nat = indi.get_number_of_atoms()
            if debug:
                logger.info(
                    'Extending defect structure to include bulk len(r1+r2)={0} len(bulk)={1}'
                    .format(nat, len(bulk)))
            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)
            if debug:
                logger.info(
                    'Extending surface structure to include bulk len(r1+r2)={0} len(bulk)={1}'
                    .format(nat, len(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])
        elif Optimizer.structure == 'Cluster':
            totalsol = indiv.copy()
            nat = len(totalsol)
            if debug:
                logger.info(
                    'Extending cluster with {0} atoms to center of evaluation box of size {1}'
                    .format(nat, Optimizer.large_box_size))
            origcell = indiv.get_cell()
            totalsol.set_cell([
                Optimizer.large_box_size, Optimizer.large_box_size,
                Optimizer.large_box_size
            ])
            totalsol.translate([
                Optimizer.large_box_size / 2.0, Optimizer.large_box_size / 2.0,
                Optimizer.large_box_size / 2.0
            ])
        elif Optimizer.structure == 'Crystal':
            totalsol = indiv.copy()
            nat = len(totalsol)
        else:
            print 'WARNING: In EvalEnergy. Optimizer.structure not recognized'
            logger.warning('Optimizer.structure not recognized')

        # Check for atoms that are too close or out of constrained location
        if Optimizer.constrain_position:
            if Optimizer.structure == 'Defect':
                if debug:
                    logger.info('Constraining positions of defect')
                totalsol, stro = constrain_positions(totalsol,
                                                     Optimizer.solidbulk,
                                                     Optimizer.sf)
                if debug:
                    logger.info(stro)
                STR += str0
        min_len = 0.7
        if not Optimizer.fixed_region:
            if debug:
                logger.info('Running check minimum distance')
            totalsol, STR = check_min_dist(totalsol, Optimizer.structure, nat,
                                           min_len, STR)
            if debug:
                write_xyz(Optimizer.debugfile, totalsol,
                          'After minlength check')
                Optimizer.debugfile.flush()
                logger.debug(
                    'Writing individual after checking minimum length')

        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                if debug:
                    logger.info('Setting up fixed region calculator')
                pms = copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][
                        len(pms['mass']) -
                        1] += '\ngroup RO id >= {0}\nfix freeze RO setforce 0.0 0.0 0.0\n'.format(
                            nat)
                except KeyError:
                    pms['pair_coeff'][
                        0] += '\ngroup RO id >= {0}\nfix freeze RO setforce 0.0 0.0 0.0\n'.format(
                            nat)
                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)
                if debug:
                    logger.info('Setting up no local minimization calculator')
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc = Optimizer.calc
        totalsol.set_calculator(calc)
        totalsol.set_pbc(True)

        # Perform Energy Minimization
        if not Optimizer.parallel:
            if debug:
                write_xyz(Optimizer.debugfile, totalsol,
                          'Individual sent to Energy Minimizer')
                logger.debug('Writing structure sent to energy minimizer')
        try:
            cwd = os.getcwd()
            if Optimizer.ase_min == True:
                if debug:
                    logger.info('Running ASE minimizer')
                if Optimizer.calc_method == 'LennardJones':
                    logger.warn('Must run ase LJ calculator with pbc=False')
                    totalsol.set_pbc(False)
                totalsol, energy, pressure, volume, STR = run_ase_min(
                    totalsol, Optimizer.ase_min_fmax,
                    Optimizer.ase_min_maxsteps, Optimizer.fitness_scheme, STR)
            else:
                if debug:
                    logger.info('Running local energy calculator')
                if Optimizer.fixed_region:
                    totalsol, energy, pressure, volume, STR = run_energy_eval(
                        totalsol, Optimizer.calc_method,
                        Optimizer.fixed_region, Optimizer.fitness_scheme, STR,
                        Optimizer.static_calc)
                else:
                    totalsol, energy, pressure, volume, STR = run_energy_eval(
                        totalsol, Optimizer.calc_method, False,
                        Optimizer.fitness_scheme, STR)
        except Exception, e:
            logger.critical('Error in energy evaluation: {0}'.format(e),
                            exc_info=True)
            path = os.path.join(cwd, 'TroubledLammps')
            if not os.path.exists(path):
                os.mkdir(path)
            #Copy files over
            shutil.copyfile(
                calc.trajfile,
                os.path.join(path, os.path.basename(calc.trajfile)))
            shutil.copyfile(calc.infile,
                            os.path.join(path, os.path.basename(calc.infile)))
            shutil.copyfile(calc.logfile,
                            os.path.join(path, os.path.basename(calc.logfile)))
            shutil.copyfile(
                calc.datafile,
                os.path.join(path, os.path.basename(calc.datafile)))
            raise RuntimeError('{0}:{1}'.format(Exception, e))
        if not Optimizer.parallel:
            if debug:
                write_xyz(Optimizer.debugfile, totalsol,
                          'Individual after Energy Minimization')
                Optimizer.debugfile.flush()
                logger.debug(
                    'Writing structure recieved from energy minimizer')

        # Separate structures into distinct pieces
        if Optimizer.structure == 'Defect':
            if Optimizer.fixed_region == True or Optimizer.finddefects == False:
                if debug:
                    logger.info(
                        'Identifying atoms in defect structure based on ID')
                individ[0] = totalsol[0:nat]
                bul = totalsol[(nat):len(totalsol)]
                individ[0].set_cell(csize)
            else:
                if debug:
                    logger.info(
                        'Applying find defects scheme to identify R1 and R2 for Defect'
                    )
                if 'FD' 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]
        elif Optimizer.structure == 'Surface':
            if debug:
                logger.info('Finding surface top layer')
            top, bul = find_top_layer(totalsol, Optimizer.surftopthick)
            indiv = top.copy()
            individ[0] = top.copy()
            bul = Atoms()
        elif Optimizer.structure == 'Crystal':
            if debug:
                logger.info('Checking crystal cell type')
            celltype = check_cell_type(totalsol)
            STR += 'Cell structure = {0}\n'.format(celltype)
            bul = Atoms()
            individ[0] = totalsol.copy()
        elif Optimizer.structure == 'Cluster':
            volume = get_cluster_volume(totalsol)
            bul = Atoms()
            if debug:
                logger.info(
                    'Translating cluster back to smaller box size location')
            totalsol.translate([
                -Optimizer.large_box_size / 2.0,
                -Optimizer.large_box_size / 2.0,
                -Optimizer.large_box_size / 2.0
            ])
            totalsol.set_cell(origcell)
            individ[0] = totalsol.copy()

        # Add concentration energy dependence
        if Optimizer.forcing == 'energy_bias':
            if debug:
                logger.info(
                    'Applying energy bias for atoms with different number of atoms of type than in atomlist'
                )
            n = [0] * len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                n[i] = len([
                    inds for inds in totalsol
                    if inds.symbol == Optimizer.atomlist[i][0]
                ])
                n[i] = abs(n[i] - Optimizer.atomlist[i][1])
            factor = sum(n)**3
            energy = (energy + factor) / totalsol.get_number_of_atoms()
            STR += 'Energy with Bias = {0}\n'.format(energy)
        elif Optimizer.forcing == 'chem_pot':
            if debug:
                logger.info(
                    'Applying chemical potential bias for atoms with different number of atoms of type than in atomlist'
                )
            n = [0] * len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                n[i] = len([
                    inds for inds in totalsol
                    if inds.symbol == Optimizer.atomlist[i][0]
                ])
                n[i] = n[i] * Optimizer.atomlist[i][3]
            factor = sum(n)
            energy = (energy + factor) / totalsol.get_number_of_atoms()
            STR += 'Energy with Chemical Potential = {0}\n'.format(energy)

        individ.energy = energy
        individ.buli = bul
        individ.pressure = pressure
        individ.volume = volume

        if Optimizer.fingerprinting:
            if debug:
                logger.info('Identifying fingerprint of new structure')
            individ.fingerprint = get_fingerprint(Optimizer, individ,
                                                  Optimizer.fpbin,
                                                  Optimizer.fpcutoff)
        if Optimizer.parallel:
            calc.clean()
            signal = 'Evaluated individual {0} on {1}\n'.format(
                individ.index, rank)
            signal += STR
        else:
            signal = STR
コード例 #5
0
from MAST.structopt.io.read_xyz import read_xyz
from MAST.structopt.io.write_xyz import write_xyz
from ase import Atom, Atoms
from MAST.structopt.tools.lammps import LAMMPS
import os

# Set up calculator
parcoff = '* * FeCr.cdeam Cr Fe'
pair_coeff = [parcoff]
parameters = {'pair_style': 'eam/cd', 'pair_coeff': pair_coeff}
mincomd = '1e-8 1e-8 5000 10000'
parameters['minimize'] = mincomd
filesL = ['FeCr.cdeam']
calc = LAMMPS(parameters=parameters,
              files=filesL,
              keep_tmp_files=True,
              tmp_dir=os.path.join(os.getcwd(), 'LAMMPSFiles'))

files = os.listdir(os.getcwd())
files = [file for file in files if '.xyz' in file]
for file in flist:
    # Read File
    structure = read_xyz(file, -1)
    # Calculate Energy
    structure.set_cell([22.96, 22.96, 22.96])
    structure.set_pbc(True)
    structure.set_calculator(calc)
    OUT = structure.calc.calculate(structure)
    totalsol = OUT['atoms']
    totalsol.set_pbc(True)
    en = OUT['thermo'][-1]['pe']
コード例 #6
0
ファイル: eval_energy2.py プロジェクト: zhenming-xu/MAST
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:
コード例 #7
0
ファイル: eval_energy_non_stem.py プロジェクト: uw-cmg/MAST
def eval_energy(Optimizer, individ):
    """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
    """
    #logger = initialize_logger(Optimizer.loggername)
    logger = logging.getLogger(Optimizer.loggername)
    if 'MAST' in Optimizer.calc_method:
        energy = individ.energy
        bul = individ.bulki
        signal = 'Received MAST structure\n'
        logger.info('Received individual index = {0} from MAST with energy {1}. Returning with no evaluation'.format(
            individ.index, individ.energy))
    else:
        if Optimizer.parallel: 
            rank = MPI.COMM_WORLD.Get_rank()
        logger.info('Received individual HI = {0} with energy {1} for energy evaluation'.format(
            individ.history_index, individ.energy))
        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,'Received by eval_energy')
            Optimizer.debugfile.flush()
            logger.debug('Writing recieved individual to debug file')
        # Establish individual structure for evaluation.  Piece together regions when necessary.
        if Optimizer.structure=='Defect':
            indi=indiv.copy()
            bulk=individ.bulki
            nat=indi.get_number_of_atoms()
            if debug: 
                logger.info('Extending defect structure to include bulk len(r1+r2)={0} len(bulk)={1}'.format(nat,len(bulk)))
            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)
            if debug:
                logger.info('Extending surface structure to include bulk len(r1+r2)={0} len(bulk)={1}'.format(nat,len(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])
        elif Optimizer.structure=='Cluster':
            totalsol = indiv.copy()
            nat = len(totalsol)
            if debug:
                logger.info('Extending cluster with {0} atoms to center of evaluation box of size {1}'.format(nat,Optimizer.large_box_size))
            origcell = indiv.get_cell()
            totalsol.set_cell([Optimizer.large_box_size,Optimizer.large_box_size,Optimizer.large_box_size])
            totalsol.translate([Optimizer.large_box_size/2.0,Optimizer.large_box_size/2.0,Optimizer.large_box_size/2.0])
        elif Optimizer.structure=='Crystal':
            totalsol = indiv.copy()
            nat = len(totalsol)
        else:
            print 'WARNING: In EvalEnergy. Optimizer.structure not recognized'
            logger.warning('Optimizer.structure not recognized')
        
        # Check for atoms that are too close or out of constrained location
        if Optimizer.constrain_position:
            if Optimizer.structure=='Defect':
                if debug:
                    logger.info('Constraining positions of defect')
                totalsol, stro = constrain_positions(totalsol, Optimizer.solidbulk, Optimizer.sf)
                if debug:
                    logger.info(stro)
                STR+=str0
        min_len=0.7
        if not Optimizer.fixed_region:
            if debug:
                logger.info('Running check minimum distance')
            totalsol, STR = check_min_dist(totalsol, Optimizer.structure, nat, min_len, STR)
            if debug:
                write_xyz(Optimizer.debugfile,totalsol,'After minlength check')
                Optimizer.debugfile.flush()
                logger.debug('Writing individual after checking minimum length')
        
        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                if debug:
                    logger.info('Setting up fixed region calculator')
                pms=copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][len(pms['mass'])-1] += '\ngroup RO id >= {0}\nfix freeze RO setforce 0.0 0.0 0.0\n'.format(nat)
                except KeyError:
                    pms['pair_coeff'][0] += '\ngroup RO id >= {0}\nfix freeze RO setforce 0.0 0.0 0.0\n'.format(nat)
                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)
                if debug:
                    logger.info('Setting up no local minimization calculator')
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc=Optimizer.calc
        totalsol.set_calculator(calc)
        totalsol.set_pbc(True)
        
        # Perform Energy Minimization
        if not Optimizer.parallel:
            if debug: 
                write_xyz(Optimizer.debugfile,totalsol,'Individual sent to Energy Minimizer')
                logger.debug('Writing structure sent to energy minimizer')
        try:
            cwd = os.getcwd()
            if Optimizer.ase_min == True:
                if debug:
                    logger.info('Running ASE minimizer')
                if Optimizer.calc_method=='LennardJones':
                    logger.warn('Must run ase LJ calculator with pbc=False')
                    totalsol.set_pbc(False)
                totalsol, energy, pressure, volume, STR = run_ase_min(totalsol, Optimizer.ase_min_fmax, Optimizer.ase_min_maxsteps, Optimizer.fitness_scheme, STR)
            else:
                if debug:
                    logger.info('Running local energy calculator')
                if Optimizer.fixed_region:
                    totalsol, energy, pressure, volume, STR = run_energy_eval(totalsol, Optimizer.calc_method, Optimizer.fixed_region, Optimizer.fitness_scheme, STR, Optimizer.static_calc)
                else:
                    totalsol, energy, pressure, volume, STR = run_energy_eval(totalsol, Optimizer.calc_method, False, Optimizer.fitness_scheme, STR)
        except Exception, e:
            logger.critical('Error in energy evaluation: {0}'.format(e), exc_info=True)
            path = os.path.join(cwd,'TroubledLammps')
            if not os.path.exists(path):
                os.mkdir(path)
            #Copy files over
            shutil.copyfile(calc.trajfile,os.path.join(path,os.path.basename(calc.trajfile)))
            shutil.copyfile(calc.infile,os.path.join(path,os.path.basename(calc.infile)))
            shutil.copyfile(calc.logfile,os.path.join(path,os.path.basename(calc.logfile)))
            shutil.copyfile(calc.datafile,os.path.join(path,os.path.basename(calc.datafile)))
            raise RuntimeError('{0}:{1}'.format(Exception,e))
        if not Optimizer.parallel:
            if debug:
                write_xyz(Optimizer.debugfile,totalsol,'Individual after Energy Minimization')
                Optimizer.debugfile.flush()
                logger.debug('Writing structure recieved from energy minimizer')
       
        # Separate structures into distinct pieces
        if Optimizer.structure=='Defect':
            if Optimizer.fixed_region==True or Optimizer.finddefects==False:
                if debug:
                    logger.info('Identifying atoms in defect structure based on ID')
                individ[0]=totalsol[0:nat]
                bul=totalsol[(nat):len(totalsol)]
                individ[0].set_cell(csize)
            else:
                if debug:
                    logger.info('Applying find defects scheme to identify R1 and R2 for Defect')
                if 'FD' 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]
        elif Optimizer.structure=='Surface':
            if debug:
                logger.info('Finding surface top layer')
            top,bul=find_top_layer(totalsol,Optimizer.surftopthick)
            indiv=top.copy()
            individ[0]=top.copy()
            bul = Atoms()
        elif Optimizer.structure=='Crystal':
            if debug:
                logger.info('Checking crystal cell type')
            celltype = check_cell_type(totalsol)
            STR+='Cell structure = {0}\n'.format(celltype)
            bul = Atoms()
            individ[0] = totalsol.copy()
        elif Optimizer.structure=='Cluster':
            volume = get_cluster_volume(totalsol)
            bul = Atoms()
            if debug:
                logger.info('Translating cluster back to smaller box size location')
            totalsol.translate([-Optimizer.large_box_size/2.0,-Optimizer.large_box_size/2.0,-Optimizer.large_box_size/2.0])
            totalsol.set_cell(origcell)
            individ[0] = totalsol.copy()
        
        # Add concentration energy dependence
        if Optimizer.forcing=='energy_bias':
            if debug:
                logger.info('Applying energy bias for atoms with different number of atoms of type than in atomlist')
            n=[0]*len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                n[i]=len([inds for inds in totalsol if inds.symbol==Optimizer.atomlist[i][0]])
                n[i]=abs(n[i]-Optimizer.atomlist[i][1])
            factor=sum(n)**3
            energy=(energy+factor)/totalsol.get_number_of_atoms()
            STR+='Energy with Bias = {0}\n'.format(energy)
        elif Optimizer.forcing=='chem_pot':
            if debug:
                logger.info('Applying chemical potential bias for atoms with different number of atoms of type than in atomlist')
            n=[0]*len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                n[i]=len([inds for inds in totalsol if inds.symbol==Optimizer.atomlist[i][0]])
                n[i]=n[i]*Optimizer.atomlist[i][3]
            factor=sum(n)
            energy=(energy+factor)/totalsol.get_number_of_atoms()
            STR+='Energy with Chemical Potential = {0}\n'.format(energy)

        individ.energy=energy
        individ.buli=bul
        individ.pressure=pressure
        individ.volume=volume
    
        if Optimizer.fingerprinting:
            if debug:
                logger.info('Identifying fingerprint of new structure')
            individ.fingerprint=get_fingerprint(Optimizer,individ,Optimizer.fpbin,Optimizer.fpcutoff)
        if Optimizer.parallel:
            calc.clean()
            signal = 'Evaluated individual {0} on {1}\n'.format(individ.index,rank)
            signal +=STR
        else:
            signal=STR
コード例 #8
0
ファイル: setup_calculator.py プロジェクト: zhenming-xu/MAST
def setup_calculator(Optimizer):
    """
    Subprogram to set up the ASE style calculator for a system
    Input:
        Optimizer  = Optimizer class object with parameters for setting up calculator
    Output:
        calc = ASE Calculator object for running a calculation
    """
    if 'SetCalc' in Optimizer.debug:
        debug = True
        #logger = initialize_logger(Optimizer.loggername)
        logger = logging.getLogger(Optimizer.loggername)
    else:
        debug = False
    atomlist = Optimizer.atomlist
    atomlist = sorted(atomlist, key=lambda symbol: symbol[0])
    if Optimizer.calc_method == 'VASP':
        if debug:
            logger.info('Setting up vasp calculator = {0}'.format(
                Optimizer.vaspcalc))
        calc = eval(Optimizer.vaspcalc)
    elif 'MAST' in Optimizer.calc_method:
        if debug:
            logger.info('Setting up dummy calculator for MAST')
        calc = LennardJones()
    elif Optimizer.calc_method == 'LennardJones':
        if debug:
            logger.info('Setting up Lennard Jones calculator from ASE')
        calc = LennardJones()
    else:
        if Optimizer.pair_style == 'tersoff':
            if debug:
                logger.info(
                    'Setting up LAMMPS calculator with Tersoff potential')
            parcoff = '* * {0}'.format(Optimizer.pot_file)
            for one in atomlist:
                parcoff += ' {0}'.format(one[0])
            pair_coeff = [parcoff]
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            parameters = { 'pair_style' : Optimizer.pair_style, \
            'pair_coeff' : pair_coeff , 'mass' : mass }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'eam':
            if debug:
                logger.info('Setting up LAMMPS calculator with EAM potential')
            pair_coeff = ['* * {0}'.format(Optimizer.pot_file)]
            parameters = {
                'pair_style': Optimizer.pair_style,
                'pair_coeff': pair_coeff
            }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'eam/fs':
            if debug:
                logger.info(
                    'Setting up LAMMPS calculator with EAM/FS potential')
            parcoff = '* * {0}'.format(Optimizer.pot_file)
            for one in atomlist:
                parcoff += ' {0}'.format(one[0])
            pair_coeff = [parcoff]
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            parameters = {
                'pair_style': Optimizer.pair_style,
                'pair_coeff': pair_coeff,
                'mass': mass
            }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'eam/cd':
            if debug:
                logger.info(
                    'Setting up LAMMPS calculator with EAM/CD potential')
            parcoff = '* * {0}'.format(Optimizer.pot_file)
            for one in atomlist:
                parcoff += ' {0}'.format(one[0])
            pair_coeff = [parcoff]
            parameters = {
                'pair_style': Optimizer.pair_style,
                'pair_coeff': pair_coeff
            }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'edip':
            if debug:
                logger.info('Setting up LAMMPS calculator with EDIP potential')
            parcoff = '* * {0}'.format(Optimizer.pot_file)
            for one in atomlist:
                parcoff += ' {0}'.format(one[0])
            pair_coeff = [parcoff]
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            parameters = { 'pair_style' : Optimizer.pair_style, \
            'pair_coeff' : pair_coeff , 'mass' : mass, 'newton': 'on' }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'bop':
            if debug:
                logger.info('Setting up LAMMPS calculator with BOP potential')
            parcoff = '* * {0}'.format(Optimizer.pot_file)
            for one in atomlist:
                parcoff += ' {0}'.format(one[0])
            parcoff += '\ncommunicate single cutoff {0}'.format(
                Optimizer.bopcutoff)
            pair_coeff = [parcoff]
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            parameters = { 'pair_style' : Optimizer.pair_style, \
            'pair_coeff' : pair_coeff, 'mass' : mass, 'newton': 'on' }
            filesL = [Optimizer.pot_file]
        elif Optimizer.pair_style == 'buck':
            if debug:
                logger.info(
                    'Setting up LAMMPS calculator with Buckingham potential')
            pairstyle = '{0} {1}'.format(Optimizer.pair_style,
                                         Optimizer.buckcutoff)
            pair_coeff = Optimizer.buckparameters
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            parameters = {'pair_style': pairstyle, 'pair_coeff': pair_coeff, \
             'mass' : mass }
            filesL = None
        elif Optimizer.pair_style == 'other':
            """WARNING: This style still needs work. Intended to allow user flexibility with potential specification"""
            if debug:
                logger.info(
                    'Setting up LAMMPS calculator with user input potential')
            mass = ['1 {0}'.format(atomlist[0][2])]
            if len(atomlist) > 1:
                for i in range(len(atomlist) - 1):
                    mass.append('{0} {1}'.format(i + 2, atomlist[i + 1][2]))
            if Optimizer.ps_other != None:
                if 'newton' in Optimizer.ps_other:
                    parameters = {'pair_style' : Optimizer.ps_name, \
                    'pair_coeff': [Optimizer.pair_coeff], 'mass': mass,'newton':'on'}
                else:
                    parameters = {'pair_style' : Optimizer.ps_name, \
                    'pair_coeff': [Optimizer.pair_coeff], 'mass': mass,'newton':'off'}
                if 'charges' in Optimizer.ps_other:
                    cs = Optimizer.ps_other.split('charges:')
                    parameters['mass'][len(parameters['mass']) - 1] += cs[1]
                    parameters['newton'] += '\natom_style charge'
            else:
                parameters = {'pair_style' : Optimizer.ps_name, \
                'pair_coeff': Optimizer.pair_coeff, 'mass': mass}
            if Optimizer.pot_file != None:
                filesL = [Optimizer.pot_file]
            else:
                filesL = None
        else:
            if debug:
                logger.warn(
                    'No LAMMPS potential recognized. Setting up LAMMPS calculator with Lennard Jones potential'
                )
            parameters = {}
            filesL = None
            print 'WARNING: No LAMMPS potential recognized. Assuming Lennard Jones Potential'
        if Optimizer.lammps_min != None:
            if debug:
                logger.info(
                    'Adding local energy minimizer to LAMMPS calculator')
            try:
                parameters['mass'][len(parameters['mass']) -
                                   1] += '\nmin_style {0}'.format(
                                       Optimizer.lammps_min_style)
            except KeyError:
                parameters['pair_coeff'][0] += '\nmin_style {0}'.format(
                    Optimizer.lammps_min_style)
            parameters['minimize'] = Optimizer.lammps_min
        parameters['thermosteps'] = Optimizer.lammps_thermo_steps
        if Optimizer.lammps_keep_files:
            if debug:
                logger.info('Setting up directory for keeping LAMMPS files')
            try:
                rank = MPI.COMM_WORLD.Get_rank()
                if Optimizer.parallel:
                    if 'Island_Method' not in Optimizer.algorithm_type:
                        real_rank = MPI.COMM_WORLD.Get_rank()
                        rank = 0
                        path = os.path.join(
                            os.getcwd(),
                            '{0}-rank{1}'.format(Optimizer.filename, rank))
                        if not os.path.exists(os.path.join(
                                path, 'LAMMPSFiles')):
                            os.mkdir(os.path.join(path, 'LAMMPSFiles'))
                            logger.info('Making directory: {0}'.format(
                                os.path.join(path, 'LAMMPSFiles')))
            except:
                rank = 0
            if filesL != None:
                path = os.path.join(
                    os.getcwd(), '{0}-rank{1}'.format(Optimizer.filename,
                                                      rank))
                if Optimizer.parallel and ('Island_Method'
                                           not in Optimizer.algorithm_type):
                    tmpdir = os.path.join(os.path.join(path, 'LAMMPSFiles'),
                                          'rank-{0}'.format(real_rank))
                    calc = LAMMPS(parameters=parameters, files=filesL, \
                        keep_tmp_files=True, tmp_dir=tmpdir)
                else:
                    calc = LAMMPS(parameters=parameters, files=filesL, \
                        keep_tmp_files=True, tmp_dir=os.path.join(path, 'LAMMPSFiles'))
            else:
                path = os.path.join(
                    os.getcwd(), '{0}-rank{1}'.format(Optimizer.filename,
                                                      rank))
                calc = LAMMPS(parameters=parameters, keep_tmp_files=True, \
                    tmp_dir=os.path.join(path,'LAMMPSFiles'))
        else:
            if filesL != None:
                calc = LAMMPS(parameters=parameters, files=filesL)
            else:
                calc = LAMMPS(parameters=parameters)
    return calc
コード例 #9
0
def cell_shape(indiv, Optimizer):
    """Move function to forcefully alter the unit cell shape
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    Optimizer.output.write('Cell Shape change mutation\n')
    Optimizer.output.write('Index = ' + repr(indiv.index) + '\n')
    structure = random.choice(Optimizer.cell_shape_options)
    cello = indiv[0].get_cell()
    if structure == 'cubic':
        #Set to cubic shape
        an, bn, cn = [numpy.linalg.norm(v) for v in cello]
        a = (an + bn + cn) / 3.0
        celln = numpy.array([[a, 0, 0], [0, a, 0], [0, 0, a]])
        Optimizer.output.write('Mutating to cubic\n')
        muttype = 'CSC'
    elif structure == 'hexagonal':
        #Set to hexagonal shape
        an, bn, cn = [numpy.linalg.norm(v) for v in cello]
        a = (an + bn) / 2.0
        c = cn
        if c <= a:
            c = random.uniform(a + 1, 10)
        trans = numpy.array([[1, 0, 0], [-0.5, (3.0**0.5) / 2.0, 0], [0, 0,
                                                                      1]])
        trans[0] = [a * i for i in trans[0]]
        trans[1] = [a * i for i in trans[1]]
        trans[2] = [c * i for i in trans[2]]
        celln = trans
        Optimizer.output.write('Mutating to Hexagonal\n')
        muttype = 'CSH'
    elif structure == 'tetragonal':
        #Set to tetragonal shape
        an, bn, cn = [numpy.linalg.norm(v) for v in cello]
        a = (an + bn) / 2.0
        c = cn
        if c == a:
            c = random.uniform(1, 10)
        celln = numpy.array([[a, 0, 0], [0, a, 0], [0, 0, c]])
        Optimizer.output.write('Mutating to tetragonal\n')
        muttype = 'CSTe'
    elif structure == 'orthorhombic':
        #Set to orthorhombic
        a = random.uniform(2, 10)
        b = random.uniform(2, 10)
        c = random.uniform(2, 10)
        celln = numpy.array([[a, 0, 0], [0, b, 0], [0, 0, c]])
        Optimizer.output.write('Mutating to orthorhombic\n')
        muttype = 'CSO'
    elif structure == 'monoclinic':
        #Set to monoclinic
        a, b, c = [numpy.linalg.norm(v) for v in cello]
        if a == b:
            b = random.uniform(1, 10)
        trans = numpy.array([(1 + random.random()) * c, 0,
                             (1 + random.random()) * c])
        celln = numpy.array([[a, 0, 0], [0, b, 0], [0, 0, 0]])
        celln[2] = trans
        Optimizer.output.write('Mutating to monoclinic\n')
        muttype = 'CSM'
    elif structure == 'triclinic':
        #Set to triclinic
        a, b, c = [numpy.linalg.norm(v) for v in cello]
        celln = numpy.array([[a, 0, 0],
                             [(1 + random.random()) * b,
                              (1 + random.random()) * b, 0],
                             [(1 + random.random()) * c, 0,
                              (1 + random.random()) * c]])
        Optimizer.output.write('Mutating to triclinic\n')
        muttype = 'CSTr'
    indiv[0].set_cell(celln)
    #Relax new box shape with Lammps box/reax for cell
    Optimizer.output.write('LAMMPS fix box/relax performed\n')
    cwd1 = os.getcwd()
    parameters = copy.deepcopy(Optimizer.calc.parameters)
    try:
        parameters['mass'][len(parameters['mass']) -
                           1] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    except KeyError:
        parameters['pair_coeff'][
            0] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    filesL = [Optimizer.pot_file]
    if Optimizer.lammps_keep_files:
        calc2 = LAMMPS(parameters=parameters,
                       files=filesL,
                       keep_tmp_files=True,
                       tmp_dir=os.getcwd() + '/' + Optimizer.filename +
                       '/Lammpsrun2/')
    else:
        calc2 = LAMMPS(parameters=parameters, files=filesL)
    atmsdup = indiv[0].copy()
    atmsdup.set_calculator(calc2)
    try:
        OUT = atmsdup.calc.calculate(atmsdup)
        indiv[0].set_cell(OUT['atoms'].get_cell())
        indiv[0].set_positions(OUT['atoms'].get_positions())
        Optimizer.output.write('Energy = ' +
                               repr(OUT['thermo'][-1]['pe'] /
                                    indiv[0].get_number_of_atoms()) + '\n')
    except:
        Optimizer.output.write(
            'WARNING: Minimizer quit - Box relaxation unsuccessful\n')
    #pdb.set_trace()
    os.chdir(cwd1)
    calc2.clean()
    Optimizer.output.write(repr(indiv[0].get_cell()) + '\n')
    if indiv.energy == 0:
        indiv.history_index = indiv.history_index + 'm' + muttype
    else:
        indiv.history_index = repr(indiv.index) + 'm' + muttype
    return indiv
コード例 #10
0
from MAST.structopt.tools.lammps import LAMMPS

# Set up calculator
parcoff = '* * SiC.edip C Si'
pair_coeff = [parcoff]
mass = ['1 12.011', '2 28.0855']
parameters = {
    'pair_style': 'edip',
    'pair_coeff': pair_coeff,
    'mass': mass,
    'newton': 'on'
}
mincomd = '1e-8 1e-8 5000 10000'
parameters['minimize'] = mincomd
filesL = ['SiC.edip']
calc = LAMMPS(parameters=parameters, files=filesL)

# Read File
structure = read_xyz('indiv00.xyz', -1)

# Calculate Energy
structure.set_cell([13.092, 13.092, 13.092])
structure.set_pbc(True)
structure.set_calculator(calc)
OUT = structure.calc.calculate(structure)
totalsol = OUT['atoms']
totalsol.set_pbc(True)
en = OUT['thermo'][-1]['pe']
#Write Relaxed Structure
write_xyz('re-relaxed.xyz', totalsol, repr(en))
fe = en
コード例 #11
0
ファイル: cell_shape.py プロジェクト: m-yu/MAST
def cell_shape(indiv, Optimizer):
    """Move function to forcefully alter the unit cell shape
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    Optimizer.output.write('Cell Shape change mutation\n')
    Optimizer.output.write('Index = '+repr(indiv.index)+'\n')
    structure=random.choice(Optimizer.cell_shape_options)
    cello=indiv[0].get_cell()
    if structure=='cubic':
        #Set to cubic shape
        an,bn,cn = [numpy.linalg.norm(v) for v in cello]
        a=(an+bn+cn)/3.0
        celln=numpy.array([[a,0,0],[0,a,0],[0,0,a]])
        Optimizer.output.write('Mutating to cubic\n')
        muttype='CSC'
    elif structure=='hexagonal':
        #Set to hexagonal shape
        an,bn,cn = [numpy.linalg.norm(v) for v in cello]
        a=(an+bn)/2.0
        c=cn
        if c<=a:
            c=random.uniform(a+1,10)
        trans=numpy.array([[1,0,0],[-0.5,(3.0**0.5)/2.0,0],[0,0,1]])
        trans[0]=[a*i for i in trans[0]]
        trans[1]=[a*i for i in trans[1]]
        trans[2]=[c*i for i in trans[2]]
        celln=trans
        Optimizer.output.write('Mutating to Hexagonal\n')
        muttype='CSH'
    elif structure=='tetragonal':
        #Set to tetragonal shape
        an,bn,cn = [numpy.linalg.norm(v) for v in cello]
        a=(an+bn)/2.0
        c=cn
        if c==a:
            c=random.uniform(1,10)
        celln=numpy.array([[a,0,0],[0,a,0],[0,0,c]])
        Optimizer.output.write('Mutating to tetragonal\n')
        muttype='CSTe'
    elif structure=='orthorhombic':
        #Set to orthorhombic
        a=random.uniform(2,10)
        b=random.uniform(2,10)
        c=random.uniform(2,10)
        celln=numpy.array([[a,0,0],[0,b,0],[0,0,c]])
        Optimizer.output.write('Mutating to orthorhombic\n')
        muttype='CSO'
    elif structure=='monoclinic':
        #Set to monoclinic
        a,b,c = [numpy.linalg.norm(v) for v in cello]
        if a==b:
            b=random.uniform(1,10)
        trans=numpy.array([(1+random.random())*c, 0, (1+random.random())*c])
        celln=numpy.array([[a,0,0],[0,b,0],[0,0,0]])
        celln[2]=trans
        Optimizer.output.write('Mutating to monoclinic\n')
        muttype='CSM'
    elif structure=='triclinic':
        #Set to triclinic
        a,b,c = [numpy.linalg.norm(v) for v in cello]
        celln=numpy.array([[a,0,0],[(1+random.random())*b,(1+random.random())*b,0],[(1+random.random())*c,0,(1+random.random())*c]])
        Optimizer.output.write('Mutating to triclinic\n')
        muttype='CSTr'
    indiv[0].set_cell(celln)
    #Relax new box shape with Lammps box/reax for cell
    Optimizer.output.write('LAMMPS fix box/relax performed\n')
    cwd1=os.getcwd()
    parameters=copy.deepcopy(Optimizer.calc.parameters)
    try:
        parameters['mass'][len(parameters['mass'])-1] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    except KeyError:
        parameters['pair_coeff'][0] += '\nfix 1 all box/relax iso 0.0 vmax 0.001'
    filesL = [ Optimizer.pot_file ]
    if Optimizer.lammps_keep_files:
        calc2 = LAMMPS(parameters=parameters, files=filesL,keep_tmp_files=True, tmp_dir=os.getcwd()+'/'+Optimizer.filename+'/Lammpsrun2/')
    else:
        calc2 = LAMMPS(parameters=parameters, files=filesL)
    atmsdup=indiv[0].copy()
    atmsdup.set_calculator(calc2)
    try:
        OUT=atmsdup.calc.calculate(atmsdup)
        indiv[0].set_cell(OUT['atoms'].get_cell())
        indiv[0].set_positions(OUT['atoms'].get_positions())
        Optimizer.output.write('Energy = '+repr(OUT['thermo'][-1]['pe']/indiv[0].get_number_of_atoms())+'\n')
    except:
        Optimizer.output.write('WARNING: Minimizer quit - Box relaxation unsuccessful\n')
    #pdb.set_trace()
    os.chdir(cwd1)
    calc2.clean()
    Optimizer.output.write(repr(indiv[0].get_cell())+'\n')
    if indiv.energy==0:
        indiv.history_index=indiv.history_index+'m'+muttype
    else:
        indiv.history_index=repr(indiv.index)+'m'+muttype
    return indiv