예제 #1
0
def fitpred_new(pop, Optimizer):
    """Predator function to identify similar structures based on energy and replace one with new structure.
    """
    fitlist = [one.fitness for one in pop]
    nfitlist, nindices = remove_duplicates(fitlist, Optimizer.demin)
    STR = ''
    newpop = []
    if len(nfitlist) != len(fitlist):
        STR += 'Predator: Removed total of ' + repr(
            len(fitlist) - len(nfitlist)) + ' from population\n'
    otherlist = []
    for i in range(len(pop)):
        if i not in nindices:
            STR += 'Predator: Removed ' + repr(pop[i].history_index) + '\n'
            otherlist.append(pop[i])
        else:
            newpop.append(pop[i])
    while len(newpop) < Optimizer.nindiv:
        if Optimizer.structure == 'Defect' or Optimizer.structure == 'Cluster':
            ind = gen_pop_box(Optimizer.atomlist, Optimizer.size)
        elif Optimizer.structure == 'Crystal':
            outts = gen_pop_box(Optimizer.atomlist, Optimizer.size,
                                Optimizer.cell_shape_options)
            ind = outts[0]
        elif Optimizer.structure == 'Surface':
            mutopto = Optimizer.mutation_options
            Optimizer.mutation_options = ['Lattice_Alteration_rdrd']
            topind = random.choice(pop)[0].copy()
            ind, scheme = moves_switch(topind, Optimizer)
            Optimizer.mutation_options = mutopto
        individ = Individual(ind)
        #CHECK THIS LATER!! MAY NEED TO ADD MORE PROPERTIES!!
        individ.energy = 1000
        individ.fitness = 1000
        newpop.append(individ)
        STR += 'Predator: Adding mutated duplicates to new pop history=' + individ.history_index + '\n'
        nindices.append(individ.index)
    nindices.sort()
    if Optimizer.natural_selection_scheme == 'fussf':
        for ind in newpop:
            if ind.fingerprint == 0:
                ind.fingerprint = get_fingerprint(Optimizer, ind,
                                                  Optimizer.fpbin,
                                                  Optimizer.fpcutoff)
    if 'lambda,mu' in Optimizer.algorithm_type:
        try:
            mark = [
                index for index, n in enumerate(nindices)
                if n > Optimizer.nindiv - 1
            ][0]
        except:
            mark = Optimizer.nindiv
        Optimizer.mark = mark
        pop, str1 = lambdacommamu.lambdacommamu(newpop, Optimizer)
        STR += str1
    else:
        pop = selection_switch(newpop, Optimizer.nindiv,
                               Optimizer.natural_selection_scheme, Optimizer)
    pop = get_best(pop, len(pop))
    return pop, STR
예제 #2
0
def get_population(Optimizer):
    """
	Function to generate a population of structures.
	Inputs:
		Optimizer = structopt_stem Optimizer class object
	Outputs:
		pop = List of structopt_stem Individual class objects containing new structures.
	"""
    index1 = 0
    pop = []
    for i in range(Optimizer.nindiv):
        if Optimizer.structure == 'Defect':
            individ = get_defect_indiv(Optimizer)
        elif Optimizer.structure == 'Surface':
            individ = get_surface_indiv(Optimizer)
        elif Optimizer.structure == 'Crystal':
            individ = get_crystal_indiv(Optimizer)
        else:
            if 'sphere' in Optimizer.generate_flag:
                ind = gen_pop_sphere(Optimizer.atomlist,Optimizer.size)
            else:
                ind = gen_pop_box(Optimizer.atomlist,Optimizer.size)
            individ = Individual(ind)
        individ.index = index1
        if Optimizer.genealogy: 
            individ.history_index = repr(index1)
        Optimizer.output.write('Generated cluster individual with natoms = '+
            repr(individ[0].get_number_of_atoms())+'\n')
        pop.append(individ)
        index1=index1+1
    # Generate new atomlist concentrations based on cluster+box
    if Optimizer.structure == 'Defect':
        if Optimizer.alloy:
            concents=[]
            for ind in pop:
                cs=[]
                for sym,c,u,m in Optimizer.atomlist:
                    sylen=[atm for atm in ind[0] if atm.symbol==sym]
                    cs.append(len(sylen))
                concents.append(cs)
            natmlist=[0]*len(Optimizer.atomlist)
            for i in range(len(concents[0])):
                alls=[cs[i] for cs in concents]
                avgall=int(sum(alls)/len(alls))
                if avgall>=Optimizer.atomlist[i][1]:
                    natmlist[i]=(Optimizer.atomlist[i][0], avgall,
                        Optimizer.atomlist[i][2],Optimizer.atomlist[i][3])
                else:
                    natmlist[i]=(Optimizer.atomlist[i][0], Optimizer.atomlist[i][1],
                        Optimizer.atomlist[i][2],Optimizer.atomlist[i][3])
        else:
            natmlist=[0]*len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                atms1=[inds for inds in pop[0][0] if inds.symbol==Optimizer.atomlist[i][0]]
                natmlist[i]=(Optimizer.atomlist[i][0], len(atms1),Optimizer.atomlist[i][2],
                    Optimizer.atomlist[i][3])
        Optimizer.atomlist=natmlist
        Optimizer.output.write('\n\nNew atomlist concentrations based on cluster+box = '+
            repr(Optimizer.atomlist)+'\n')
    return pop
예제 #3
0
파일: fitpred_new.py 프로젝트: uw-cmg/MAST
def fitpred_new(pop,Optimizer):
    """Predator function to identify similar structures based on energy and replace one with new structure.
    """
    fitlist = [one.fitness for one in pop]
    nfitlist, nindices = remove_duplicates(fitlist, Optimizer.demin)
    STR = ''
    newpop = []
    if len(nfitlist) != len(fitlist):
        STR+='Predator: Removed total of '+repr(len(fitlist)-len(nfitlist))+' from population\n'
    otherlist = []
    for i in range(len(pop)):
        if i not in nindices:
            STR+='Predator: Removed '+repr(pop[i].history_index)+'\n'
            otherlist.append(pop[i])
        else:
            newpop.append(pop[i])
    while len(newpop) < Optimizer.nindiv:
        if Optimizer.structure=='Defect' or Optimizer.structure=='Cluster':
            ind=gen_pop_box(Optimizer.atomlist,Optimizer.size)
        elif Optimizer.structure=='Crystal':
            outts=gen_pop_box(Optimizer.atomlist,Optimizer.size,Optimizer.cell_shape_options)
            ind=outts[0]
        elif Optimizer.structure=='Surface':
            mutopto=Optimizer.mutation_options
            Optimizer.mutation_options=['Lattice_Alteration_rdrd']
            topind=random.choice(pop)[0].copy()
            ind, scheme = moves_switch(topind,Optimizer)
            Optimizer.mutation_options=mutopto
        individ=Individual(ind)
        #CHECK THIS LATER!! MAY NEED TO ADD MORE PROPERTIES!!
        individ.energy=1000
        individ.fitness=1000
        newpop.append(individ)
        STR+='Predator: Adding mutated duplicates to new pop history='+individ.history_index+'\n'
        nindices.append(individ.index)
    nindices.sort()
    if Optimizer.natural_selection_scheme=='fussf':
        for ind in newpop:
            if ind.fingerprint == 0:
                ind.fingerprint = get_fingerprint(Optimizer,ind,Optimizer.fpbin,Optimizer.fpcutoff)
    if 'lambda,mu' in Optimizer.algorithm_type:
        try:
            mark = [ index for index,n in enumerate(nindices) if n > Optimizer.nindiv-1][0]
        except:
            mark = Optimizer.nindiv
        Optimizer.mark = mark
        pop, str1 = lambdacommamu.lambdacommamu(newpop, Optimizer)
        STR+=str1
    else:
        pop = selection_switch(newpop, Optimizer.nindiv, Optimizer.natural_selection_scheme, Optimizer)
    pop = get_best(pop,len(pop))
    return pop, STR
예제 #4
0
def get_crystal_restart_indiv(Optimizer, indiv):
    """
    Function to generate an structopt Individual class object containing 
        a surface structure from a previously existing structure
    Inputs:
        Optimizer = structopt Optimizer class
        indiv = ASE Atoms object containing the previously existing structure
    Outputs:
        individ = structopt Individual class object containing surface structure data
    *** WARNING: This function is currently degenerate!  ***
    """
    crys = read_xyz(Optimizer.crysfile)
    #Recover cell from Structure Summary file
    # f = open(Optimizer.files[-1],'r')
    #     sline = f.readline()
    #     lines = f.readlines()
    #     popbygen = []
    #     n=0
    #     for line in lines:
    #         if 'Generation' in line:
    #             if len(popbygen) != 0:
    #                 popbygen.append(genlist)
    #             genlist = []
    #         else:
    #             genlist.append(line)
    #     f.close()
    cells = Optimizer.cryscell
    crys.set_cell(cells)
    individ = Individual(crys)
    return individ
예제 #5
0
def get_surface_restart_indiv(Optimizer, indiv):
    """
    Function to generate an structopt Individual class object containing 
        a surface structure from a previously existing structure
    Inputs:
        Optimizer = structopt Optimizer class
        indiv = ASE Atoms object containing the previously existing structure
    Outputs:
        individ = structopt Individual class object containing surface structure data
    """
    #Load surface structure
    surfs = read_xyz(Optimizer.surfacefile)
    cells = Optimizer.surfacecell
    surfs.set_cell(cells)
    surf.set_pbc([True,True,False])
    top,bulks=find_top_layer(indiv,Optimizer.surftopthick)
    individ=Individual(top)
    individ.bulki=bulks.copy()
    individ.bulko=bulks.copy()
    return individ
예제 #6
0
def get_defect_restart_indiv(Optimizer, indiv):
    """
    Function to generate an structopt Individual class object containing 
    	a defect structure from a previously existing structure
    Inputs:
    	Optimizer = structopt Optimizer class
    	indiv = ASE Atoms object containing the previously existing structure
    Outputs:
    	individ = structopt Individual class object containing defect structure data
    """
    if not Optimizer.solidbulk:
		#Initialize Bulk - Generate or load positions of bulk solid
		try:
		    rank = MPI.COMM_WORLD.Get_rank()
		except:
		    rank = 0
		outfilename = os.path.join(os.path.join(os.getcwd(),Optimizer.filename+'-rank'+repr(rank)),'Bulkfile.xyz')
		if Optimizer.evalsolid:
			bulk1, PureBulkEnpa, stro = gen_solid(Optimizer.solidfile,
				Optimizer.solidcell,outfilename,Optimizer.calc,Optimizer.calc_method)
			Optimizer.output.write(stro)
		else:
			bulk1 = gen_solid(Optimizer.solidfile,Optimizer.solidcell,outfilename)
			PureBulkEnpa = 0
		natomsbulk = len(bulk1)
		Optimizer.solidbulk = bulk1.copy()
		Optimizer.summary.write('CIBS Run Pure Bulk Energy per Atom:'+
			repr(PureBulkEnpa)+'\n')
		Optimizer.purebulkenpa = PureBulkEnpa
		Optimizer.natomsbulk = natomsbulk
    indiv.set_cell(Optimizer.solidcell)
    indiv.set_pbc(True)
    if Optimizer.restart_ints == 0:
        outt = find_defects(indiv,Optimizer.solidbulk,Optimizer.sf)
    else:
        indicop = [atm for atm in indiv if atm.symbol != 'X']
        indiv = Atoms(cell=Optimizer.solidcell, pbc=True)
        for atm in indicop:
            indiv.append(atm)
        outt=[indiv[0:Optimizer.restart_ints],indiv[Optimizer.restart_ints::], Atoms(),
        	Atoms(),'Assuming first '+repr(Optimizer.restart_ints)+' are interstitials\n']
    indi = outt[0].copy()
    bulki = outt[1].copy()
    individ = Individual(indi)
    individ.bulko = bulki.copy()
    individ.bulki = bulki.copy()
    individ.purebulkenpa = Optimizer.purebulkenpa
    individ.natomsbulk = Optimizer.natomsbulk
    individ.vacancies = outt[2].copy()
    individ.swaps = outt[3].copy()
    Optimizer.output.write(outt[4])
    return individ
예제 #7
0
def get_surface_indiv(Optimizer):
    """
    Function to generate an structopt Individual class object containing as surface structure.
    Inputs:
        Optimizer = structopt Optimizer class
    Outputs:
        individ = structopt Individual class object containing surface structure data
    """
    #Load surface structure
    surfs = read_xyz(Optimizer.surfacefile)
    cells = Optimizer.surfacecell
    surfs.set_cell(cells)
    surf.set_pbc([True, True, False])
    #Find top layer
    top, bulks = find_top_layer(surfs, Optimizer.surftopthick)
    mutopto = Optimizer.mutation_options
    Optimizer.mutation_options = ['lattice_alteration_rdrd']
    topind = top.copy()
    ind = moves_switch(topind, Optimizer)
    Optimizer.mutation_options = mutopto
    individ = Individual(ind)
    individ.bulki = bulks.copy()
    individ.bulko = bulks.copy()
    return individ
예제 #8
0
def get_surface_indiv(Optimizer):
    """
    Function to generate an structopt Individual class object containing as surface structure.
    Inputs:
        Optimizer = structopt Optimizer class
    Outputs:
        individ = structopt Individual class object containing surface structure data
    """
    #Load surface structure
    surfs = read_xyz(Optimizer.surfacefile)
    cells = Optimizer.surfacecell
    surfs.set_cell(cells)
    surf.set_pbc([True,True,False])
    #Find top layer
    top,bulks=find_top_layer(surfs,Optimizer.surftopthick)
    mutopto = Optimizer.mutation_options
    Optimizer.mutation_options = ['lattice_alteration_rdrd']
    topind = top.copy()
    ind = moves_switch(topind,Optimizer)
    Optimizer.mutation_options = mutopto
    individ = Individual(ind)
    individ.bulki = bulks.copy()
    individ.bulko = bulks.copy()
    return individ
예제 #9
0
def test_BestInds():
    tolerance = 0.99
    A = Optifake(10,tolerance,'Test','Cluster')
    bests = []
    for j in range(10):
        pop = []
        for i in range(5):
            pop.append(Individual(Atoms(),fitness=float(i)*0.9-j*1.3))
        bests = BestInds(pop,bests,A)
        bfits = [ind.fitness for ind in bests]
        pfits = [ind.fitness for ind in pop]

    diff = [abs(bfits[i]-bfits[i+1]) for i in range(len(bfits)-1)]
    if min(diff) < tolerance:
        print 'Error in BestInds test'
예제 #10
0
def get_crystal_indiv(Optimizer):
    """
    Function to generate an structopt Individual class object containing a crystal structure.
    Inputs:
    	Optimizer = structopt Optimizer class
    Outputs:
    	individ = structopt Individual class object containing crystal structure data
    """
    if 'sphere' in Optimizer.generate_flag:
        outts = gen_pop_sphere(Optimizer.atomlist, Optimizer.size,
                               Optimizer.cell_shape_options)
    else:
        outts = gen_pop_box(Optimizer.atomlist, Optimizer.size,
                            Optimizer.cell_shape_options)
    ind = outts[0]
    Optimizer.output.write(outts[1])
    individ = Individual(ind)
    return individ
예제 #11
0
def get_population(Optimizer):
    """
	Function to generate a population of structures.
	Inputs:
		Optimizer = structopt_stem Optimizer class object
	Outputs:
		pop = List of structopt_stem Individual class objects containing new structures.
	"""
    index1 = 0
    pop = []
    for i in range(Optimizer.nindiv):
        if Optimizer.structure == 'Defect':
            individ = get_defect_indiv(Optimizer)
        elif Optimizer.structure == 'Surface':
            individ = get_surface_indiv(Optimizer)
        elif Optimizer.structure == 'Crystal':
            individ = get_crystal_indiv(Optimizer)
        else:
            if 'sphere' in Optimizer.generate_flag:
                ind = gen_pop_sphere(Optimizer.atomlist, Optimizer.size)
            else:
                ind = gen_pop_box(Optimizer.atomlist, Optimizer.size)
            individ = Individual(ind)
        individ.index = index1
        if Optimizer.genealogy:
            individ.history_index = repr(index1)
        Optimizer.output.write('Generated cluster individual with natoms = ' +
                               repr(individ[0].get_number_of_atoms()) + '\n')
        pop.append(individ)
        index1 = index1 + 1
    # Generate new atomlist concentrations based on cluster+box
    if Optimizer.structure == 'Defect':
        if Optimizer.alloy:
            concents = []
            for ind in pop:
                cs = []
                for sym, c, u, m in Optimizer.atomlist:
                    sylen = [atm for atm in ind[0] if atm.symbol == sym]
                    cs.append(len(sylen))
                concents.append(cs)
            natmlist = [0] * len(Optimizer.atomlist)
            for i in range(len(concents[0])):
                alls = [cs[i] for cs in concents]
                avgall = int(sum(alls) / len(alls))
                if avgall >= Optimizer.atomlist[i][1]:
                    natmlist[i] = (Optimizer.atomlist[i][0], avgall,
                                   Optimizer.atomlist[i][2],
                                   Optimizer.atomlist[i][3])
                else:
                    natmlist[i] = (Optimizer.atomlist[i][0],
                                   Optimizer.atomlist[i][1],
                                   Optimizer.atomlist[i][2],
                                   Optimizer.atomlist[i][3])
        else:
            natmlist = [0] * len(Optimizer.atomlist)
            for i in range(len(Optimizer.atomlist)):
                atms1 = [
                    inds for inds in pop[0][0]
                    if inds.symbol == Optimizer.atomlist[i][0]
                ]
                natmlist[i] = (Optimizer.atomlist[i][0], len(atms1),
                               Optimizer.atomlist[i][2],
                               Optimizer.atomlist[i][3])
        Optimizer.atomlist = natmlist
        Optimizer.output.write(
            '\n\nNew atomlist concentrations based on cluster+box = ' +
            repr(Optimizer.atomlist) + '\n')
    return pop
예제 #12
0
def get_defect_indiv_random(Optimizer):
    """
    Function to generate a structopt Individual class structure with a defect structure.
    Inputs:
        Optimizer = structopt Optimizer class object
    Outputs:
        individ = structopt Individual class object containing defect structure data
    """
    #Initialize Bulk - Generate or load positions of bulk solid
    if not Optimizer.solidbulk:
        if 'Island_Method' not in Optimizer.algorithm_type:
            outfilename = os.path.join(
                os.path.join(os.getcwd(), Optimizer.filename), 'Bulkfile.xyz')
        else:
            from mpi4py import MPI
            rank = MPI.COMM_WORLD.Get_rank()
            outfilename = os.path.join(
                os.path.join(os.getcwd(),
                             Optimizer.filename + '-rank' + repr(rank)),
                'Bulkfile.xyz')
        if Optimizer.evalsolid:
            if Optimizer.parallel:
                from MAST.structopt_stem.tools.setup_calculator import setup_calculator
                Optimizer.calc = setup_calculator(Optimizer)
            bulk1, PureBulkEnpa, stro = gen_solid(Optimizer.solidfile,
                                                  Optimizer.solidcell,
                                                  outfilename, Optimizer.calc,
                                                  Optimizer.calc_method)
            Optimizer.output.write(stro)
        else:
            bulk1 = gen_solid(Optimizer.solidfile, Optimizer.solidcell,
                              outfilename)
            PureBulkEnpa = 0
        natomsbulk = len(bulk1)
        Optimizer.solidbulk = bulk1.copy()
        Optimizer.purebulkenpa = PureBulkEnpa
        Optimizer.natomsbulk = natomsbulk
    # Identify nearby atoms for region 2 inclusion
    bulk = Optimizer.solidbulk.copy()
    bulkcom = bulk.get_center_of_mass()
    bulk.translate(-bulkcom)
    if Optimizer.sf != 0:
        bulk.append(Atom(position=[0, 0, 0]))
        nbulk = Atoms(pbc=True, cell=bulk.get_cell())
        nr2 = Atoms(pbc=True, cell=bulk.get_cell())
        for i in range(len(bulk) - 1):
            dist = bulk.get_distance(-1, i)
            if dist <= Optimizer.sf:
                nr2.append(bulk[i])
            else:
                nbulk.append(bulk[i])
    else:
        nbulk = bulk.copy()
        nr2 = Atoms(pbc=True, cell=bulk.get_cell())
    #Update atom list with atoms in region 2
    natlist = []
    for sym, c, m, u in Optimizer.atomlist:
        atsym = [atm for atm in nr2 if atm.symbol == sym]
        natlist.append((sym, len(atsym), m, u))
    # Generate random individual and region 2
    if 'sphere' in Optimizer.generate_flag:
        ind = gen_pop_sphere(Optimizer.atomlist, Optimizer.size)
    elif 'dumbbell' in Optimizer.generate_flag:
        ind = Atoms(cell=[Optimizer.size for i in range(3)], pbc=True)
        for sym, c, m, u in Optimizer.atomlist:
            if c > 0:
                dums = generate_dumbbells(c,
                                          dumbbellsym=sym,
                                          nindiv=1,
                                          solid=Optimizer.solidbulk,
                                          size=Optimizer.size)[0]
                ind.extend(dums)
    else:
        ind = gen_pop_box(Optimizer.atomlist, Optimizer.size)
    nnr2 = gen_pop_sphere(natlist, Optimizer.sf * 2.0)
    nnr2.translate([-Optimizer.sf, -Optimizer.sf, -Optimizer.sf])
    nnr2.set_pbc(True)
    nnr2.set_cell(bulk.get_cell())
    # Initialize class individual with known values
    individ = Individual(ind)
    individ.purebulkenpa = Optimizer.purebulkenpa
    individ.natomsbulk = Optimizer.natomsbulk
    # Combine individual with R2
    icom = ind.get_center_of_mass()
    ind.translate(-icom)
    ind.extend(nnr2)
    ind.set_pbc(True)
    ind.set_cell(bulk.get_cell())
    # Recenter structure
    nbulk.translate(bulkcom)
    ind.translate(bulkcom)
    individ[0] = ind.copy()
    individ.bulki = nbulk.copy()
    individ.bulko = nbulk.copy()
    bulk = nbulk.copy()
    bul = bulk.copy()
    for atm in individ[0]:
        bul.append(atm)
    indices = []
    for sym, c, m, u in Optimizer.atomlist:
        if c < 0:
            if Optimizer.randvacst:
                alist = [one for one in bul if one.symbol == sym]
                count = abs(c)
                while count > 0:
                    indices.append(random.choice(alist).index)
                    count -= 1
            else:
                pos = individ[0][0:Optimizer.natoms].get_center_of_mass()
                count = abs(c)
                bul.append(Atom(position=pos))
                alist = [one for one in bul if one.symbol == sym]
                alistd = [(bul.get_distance(len(bul) - 1,
                                            one.index), one.index)
                          for one in alist]
                alistd.sort(reverse=True)
                bul.pop()
                while count > 0:
                    idx = alistd.pop()[1]
                    indices.append(idx)
                    count -= 1
    if len(indices) != 0:
        nbulklist = [
            at for at in bul
            if at.index not in indices and at.index < len(bulk)
        ]
        nalist = [
            at for at in bul
            if at.index not in indices and at.index >= len(bulk)
        ]
        bulkn = Atoms(cell=bulk.get_cell(), pbc=True)
        for atm in nbulklist:
            bulkn.append(atm)
        individ.bulki = bulkn.copy()
        individ.bulko = bulkn.copy()
        newind = Atoms()
        for atm in nalist:
            newind.append(atm)
        newind.set_cell(individ[0].get_cell())
        newind.set_pbc(True)
        individ[0] = newind
    return individ
예제 #13
0
     except Exception,e:
         Optimizer.output.write('WARNING: Trouble reading file: {0}'.format(Optimizer.files[i].name),exc_info=True)
         Optimizer.output.write('Error: {0}'.format(e))
         Optimizer.output.flush()
         Optimizer.nindiv-=1
     if successflag:
         Optimizer.output.write('Found good individual = {0}\n'.format(indiv))
         if Optimizer.structure == 'Defect':
             individ = get_defect_restart_indiv(Optimizer,indiv)
         elif Optimizer.structure == 'Surface':
             individ = get_surface_restart_indiv(Optimizer, indiv)
         else:
             cell = indiv.get_cell()
             if cell[0][0] == 1.0:
                indiv.set_cell([Optimizer.size,Optimizer.size,Optimizer.size])
             individ = Individual(indiv)
         individ.index = index1
         if Optimizer.genealogy: 
         	individ.history_index = repr(index1)
         pop.append(individ)
         index1 = index1+1
 if len(pop) == 0:
     raise RuntimeError('Unable to load any structures for Restart')
 # Generate new atomlist concentrations based on cluster+box
 if Optimizer.structure == 'Defect':
     if Optimizer.alloy:
         concents=[]
         for ind in pop:
             cs=[]
             for sym,c,u,m in Optimizer.atomlist:
                 sylen=[atm for atm in ind[0] if atm.symbol==sym]
예제 #14
0
def read_individual(indivfile, n=-1):
    """Function to write the data of an individual class object to a flat file
    Input:
        indivfile = String or fileobject for file to be read from
        n = which individual from file to return. Default is last individual written.
            optional All
    Output:
        returns an individual class object or list of individual class objects depending on value of n
    """
    if isinstance(indivfile, str):
        indivfile=open(indivfile, 'r')
    all_lines = indivfile.readlines()
    indivfile.close()
    linen = 0
    all_indivs = []
    while linen < len(all_lines):
        if '----------' in all_lines[linen]:
            individ = Individual(Atoms())
        elif 'Structure information' in all_lines[linen]:
            natomstruct = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natomstruct):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ = Individual(atomstruct)
            linen += 2+natomstruct
        elif 'structure cell' in all_lines[linen]:
            cell_line = all_lines[linen].split('=')
            structcell = eval(cell_line[1])
            individ[0].set_cell(structcell)
        elif 'fitness' in all_lines[linen]:
            fitline = all_lines[linen].split('=')
            individ.fitness = float(fitline[1])
        elif 'history_index' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.history_index = line[1].strip()
        elif 'index' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.index = float(line[1])
        elif 'tenergymx' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.tenergymx = float(line[1])
        elif 'tenergymin' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.tenergymin = float(line[1])
        elif 'energy' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.energy = float(line[1])
        elif 'pressure' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.pressure = float(line[1])
        elif 'volume' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.volume = float(line[1])
        elif 'force' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.force = float(line[1])
        elif 'purebulkenpa' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.purebulkenpa = float(line[1])
        elif 'natomsbulk' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.natomsbulk = float(line[1])
        elif 'fingerprint' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.fingerprint = eval(line[1])
        elif 'swpalist' in all_lines[linen]:
            line = all_lines[linen].split('=')
            individ.swaplist = eval(line[1])
        elif 'bulki cell' in all_lines[linen]:
            line = all_lines[linen].split('=')
            cell = eval(line[1])
            individ.bulki.set_cell(cell)
        elif 'bulki' in all_lines[linen]:
            natoms = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natoms):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ.bulki = atomstruct.copy()
            linen += 2+natoms
        elif 'bulko cell' in all_lines[linen]:
            line = all_lines[linen].split('=')
            cell = eval(line[1])
            individ.bulko.set_cell(cell)
        elif 'bulko' in all_lines[linen]:
            natoms = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natoms):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ.bulko = atomstruct.copy()
            linen += 2+natoms
        elif 'box cell' in all_lines[linen]:
            line = all_lines[linen].split('=')
            cell = eval(line[1])
            individ.box.set_cell(cell)
        elif 'box' in all_lines[linen]:
            natoms = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natoms):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ.box = atomstruct.copy()
            linen += 2+natoms
        elif 'vacancies cell' in all_lines[linen]:
            line = all_lines[linen].split('=')
            cell = eval(line[1])
            individ.vacancies.set_cell(cell)
        elif 'vacancies' in all_lines[linen]:
            natoms = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natoms):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ.vacancies = atomstruct.copy()
            linen += 2+natoms
        elif 'swaps cell' in all_lines[linen]:
            line = all_lines[linen].split('=')
            cell = eval(line[1])
            individ.swaps.set_cell(cell)
        elif 'swaps' in all_lines[linen]:
            natoms = int(all_lines[linen+1])
            atomstruct = Atoms()
            for i in range(natoms):
                a = all_lines[linen+i+3].split()
                sym = a[0]
                position = [float(a[1]),float(a[2]),float(a[3])]
                atomstruct.append(Atom(symbol=sym,position=position))
            individ.swaps = atomstruct.copy()
            linen += 2+natoms
        elif 'Finish' in all_lines[linen]:
            all_indivs.append(individ.duplicate())
        linen+=1
    if n=='All':
        return all_indivs
    else:
        return all_indivs[n]
예제 #15
0
def get_defect_restart_indiv(Optimizer, indiv):
    """
    Function to generate an structopt Individual class object containing 
    	a defect structure from a previously existing structure
    Inputs:
    	Optimizer = structopt Optimizer class
    	indiv = ASE Atoms object containing the previously existing structure
    Outputs:
    	individ = structopt Individual class object containing defect structure data
    """
    if not Optimizer.solidbulk:
        #Initialize Bulk - Generate or load positions of bulk solid
        try:
            rank = MPI.COMM_WORLD.Get_rank()
        except:
            rank = 0
        outfilename = os.path.join(
            os.path.join(os.getcwd(),
                         Optimizer.filename + '-rank' + repr(rank)),
            'Bulkfile.xyz')
        if Optimizer.evalsolid:
            bulk1, PureBulkEnpa, stro = gen_solid(Optimizer.solidfile,
                                                  Optimizer.solidcell,
                                                  outfilename, Optimizer.calc,
                                                  Optimizer.calc_method)
            Optimizer.output.write(stro)
        else:
            bulk1 = gen_solid(Optimizer.solidfile, Optimizer.solidcell,
                              outfilename)
            PureBulkEnpa = 0
        natomsbulk = len(bulk1)
        Optimizer.solidbulk = bulk1.copy()
        Optimizer.summary.write('CIBS Run Pure Bulk Energy per Atom:' +
                                repr(PureBulkEnpa) + '\n')
        Optimizer.purebulkenpa = PureBulkEnpa
        Optimizer.natomsbulk = natomsbulk
    indiv.set_cell(Optimizer.solidcell)
    indiv.set_pbc(True)
    if Optimizer.restart_ints == 0:
        outt = find_defects(indiv, Optimizer.solidbulk, Optimizer.sf)
    else:
        indicop = [atm for atm in indiv if atm.symbol != 'X']
        indiv = Atoms(cell=Optimizer.solidcell, pbc=True)
        for atm in indicop:
            indiv.append(atm)
        outt = [
            indiv[0:Optimizer.restart_ints], indiv[Optimizer.restart_ints::],
            Atoms(),
            Atoms(), 'Assuming first ' + repr(Optimizer.restart_ints) +
            ' are interstitials\n'
        ]
    indi = outt[0].copy()
    bulki = outt[1].copy()
    individ = Individual(indi)
    individ.bulko = bulki.copy()
    individ.bulki = bulki.copy()
    individ.purebulkenpa = Optimizer.purebulkenpa
    individ.natomsbulk = Optimizer.natomsbulk
    individ.vacancies = outt[2].copy()
    individ.swaps = outt[3].copy()
    Optimizer.output.write(outt[4])
    return individ
예제 #16
0
         Optimizer.output.write('Error: {0}'.format(e))
         Optimizer.output.flush()
         Optimizer.nindiv -= 1
     if successflag:
         Optimizer.output.write(
             'Found good individual = {0}\n'.format(indiv))
         if Optimizer.structure == 'Defect':
             individ = get_defect_restart_indiv(Optimizer, indiv)
         elif Optimizer.structure == 'Surface':
             individ = get_surface_restart_indiv(Optimizer, indiv)
         else:
             cell = indiv.get_cell()
             if cell[0][0] == 1.0:
                 indiv.set_cell(
                     [Optimizer.size, Optimizer.size, Optimizer.size])
             individ = Individual(indiv)
         individ.index = index1
         if Optimizer.genealogy:
             individ.history_index = repr(index1)
         pop.append(individ)
         index1 = index1 + 1
 if len(pop) == 0:
     raise RuntimeError('Unable to load any structures for Restart')
 # Generate new atomlist concentrations based on cluster+box
 if Optimizer.structure == 'Defect':
     if Optimizer.alloy:
         concents = []
         for ind in pop:
             cs = []
             for sym, c, u, m in Optimizer.atomlist:
                 sylen = [atm for atm in ind[0] if atm.symbol == sym]
예제 #17
0
def get_defect_indiv_random(Optimizer):
    """
    Function to generate a structopt Individual class structure with a defect structure.
    Inputs:
        Optimizer = structopt Optimizer class object
    Outputs:
        individ = structopt Individual class object containing defect structure data
    """
    #Initialize Bulk - Generate or load positions of bulk solid
    if not Optimizer.solidbulk:
        if 'Island_Method' not in Optimizer.algorithm_type:
            outfilename = os.path.join(os.path.join(os.getcwd(),Optimizer.filename),'Bulkfile.xyz')
        else:
            from mpi4py import MPI
            rank = MPI.COMM_WORLD.Get_rank()
            outfilename = os.path.join(os.path.join(os.getcwd(),Optimizer.filename+'-rank'+repr(rank)),'Bulkfile.xyz')
        if Optimizer.evalsolid:
            if Optimizer.parallel:
                from MAST.structopt_stem.tools.setup_calculator import setup_calculator
                Optimizer.calc = setup_calculator(Optimizer)
            bulk1, PureBulkEnpa, stro = gen_solid(Optimizer.solidfile,
                Optimizer.solidcell,outfilename,Optimizer.calc,Optimizer.calc_method)
            Optimizer.output.write(stro)
        else:
            bulk1 = gen_solid(Optimizer.solidfile,Optimizer.solidcell,outfilename)
            PureBulkEnpa = 0
        natomsbulk = len(bulk1)
        Optimizer.solidbulk = bulk1.copy()
        Optimizer.purebulkenpa = PureBulkEnpa
        Optimizer.natomsbulk = natomsbulk
    # Identify nearby atoms for region 2 inclusion
    bulk = Optimizer.solidbulk.copy()
    bulkcom = bulk.get_center_of_mass()
    bulk.translate(-bulkcom)
    if Optimizer.sf != 0:
        bulk.append(Atom(position=[0,0,0]))
        nbulk = Atoms(pbc=True, cell=bulk.get_cell())
        nr2 = Atoms(pbc=True, cell=bulk.get_cell())
        for i in range(len(bulk)-1):
            dist = bulk.get_distance(-1,i)
            if dist <= Optimizer.sf:
                nr2.append(bulk[i])
            else:
                nbulk.append(bulk[i])
    else:
        nbulk = bulk.copy()
        nr2 = Atoms(pbc=True, cell=bulk.get_cell())
    #Update atom list with atoms in region 2
    natlist = []
    for sym,c,m,u in Optimizer.atomlist:
        atsym = [atm for atm in nr2 if atm.symbol==sym]
        natlist.append((sym,len(atsym),m,u))
    # Generate random individual and region 2
    if 'sphere' in Optimizer.generate_flag:
        ind = gen_pop_sphere(Optimizer.atomlist,Optimizer.size)
    elif 'dumbbell' in Optimizer.generate_flag:
        ind = Atoms(cell=[Optimizer.size for i in range(3)], pbc=True)
        for sym,c,m,u in Optimizer.atomlist:
            if c > 0:
                dums = generate_dumbbells(c, dumbbellsym=sym, nindiv=1, solid = Optimizer.solidbulk, size=Optimizer.size)[0]
                ind.extend(dums)
    else:
        ind = gen_pop_box(Optimizer.atomlist,Optimizer.size)
    nnr2 = gen_pop_sphere(natlist, Optimizer.sf*2.0)
    nnr2.translate([-Optimizer.sf,-Optimizer.sf,-Optimizer.sf])
    nnr2.set_pbc(True)
    nnr2.set_cell(bulk.get_cell())
    # Initialize class individual with known values
    individ = Individual(ind)
    individ.purebulkenpa = Optimizer.purebulkenpa
    individ.natomsbulk = Optimizer.natomsbulk
    # Combine individual with R2
    icom = ind.get_center_of_mass()
    ind.translate(-icom)
    ind.extend(nnr2)
    ind.set_pbc(True)
    ind.set_cell(bulk.get_cell())
    # Recenter structure
    nbulk.translate(bulkcom)
    ind.translate(bulkcom)
    individ[0] = ind.copy()
    individ.bulki = nbulk.copy()
    individ.bulko = nbulk.copy()
    bulk = nbulk.copy()
    bul = bulk.copy()
    for atm in individ[0]:
        bul.append(atm)
    indices = []
    for sym,c,m,u in Optimizer.atomlist:
        if c < 0:
            if Optimizer.randvacst:
                alist = [one for one in bul if one.symbol==sym]
                count = abs(c)
                while count > 0:
                    indices.append(random.choice(alist).index)
                    count -= 1
            else:
                pos = individ[0][0:Optimizer.natoms].get_center_of_mass()
                count = abs(c)
                bul.append(Atom(position=pos))
                alist = [one for one in bul if one.symbol==sym]
                alistd = [(bul.get_distance(len(bul)-1,one.index),one.index)
                			for one in alist]
                alistd.sort(reverse=True)
                bul.pop()
                while count > 0:
                    idx = alistd.pop()[1]
                    indices.append(idx)
                    count-=1
    if len(indices) !=0:
        nbulklist = [at for at in bul if at.index not in indices and at.index<len(bulk)]
        nalist = [at for at in bul if at.index not in indices and at.index>=len(bulk)]
        bulkn = Atoms(cell=bulk.get_cell(),pbc=True)
        for atm in nbulklist:
            bulkn.append(atm)
        individ.bulki = bulkn.copy()
        individ.bulko = bulkn.copy()
        newind = Atoms()
        for atm in nalist:
            newind.append(atm)
        newind.set_cell(individ[0].get_cell())
        newind.set_pbc(True)									
        individ[0] = newind
    return individ