def __init__(self, specs,systemSpecies = None, directory = None): from aBuild.database.crystal import Crystal #Initialize from a dictionary if isinstance(specs,dict): if self._all_present(specs): self.POTCAR = POTCAR(specs["potcars"]) self.KPOINTS = KPOINTS(specs["kpoints"]) if isinstance(specs["crystal"],Crystal): self.crystal = specs["crystal"] else: self.crystal = Crystal(specs["crystal"],specs["species"]) self.handleSpecialTags(specs) self.INCAR = INCAR(specs["incar"]) else: msg.fatal("I don't have all the necessary information to initialize: {}".format(specs.keys())) #Initialize from a path elif isinstance(specs, str): self.POTCAR = POTCAR(path.join(specs,'POTCAR')) self.KPOINTS = KPOINTS(path.join(specs,'KPOINTS')) self.crystal = Crystal(path.join(specs,'POSCAR'),systemSpecies,crystalSpecies = self.POTCAR.species) self.directory = specs else: msg.fatal("Unable to initialize a VASP object from the data that you passed in:", specs) if directory is not None: self.directory = directory
def __init__(self, specs, systemSpecies, directory=None): from aBuild.database.crystal import Crystal if isinstance(specs, dict): self.INCAR = INCAR(specs["incar"]) self.POTCAR = POTCAR(specs["potcar"]) self.KPOINTS = KPOINTS(specs["kpoints"]) if isinstance(specs["crystal"], Crystal): self.crystal = specs["crystal"] else: self.crystal = Crystal(specs["crystal"], systemSpecies) elif isinstance(specs, str): self.POTCAR = POTCAR(path.join(specs, 'POTCAR')) self.KPOINTS = KPOINTS(path.join(specs, 'KPOINTS')) self.crystal = Crystal(path.join(specs, 'POSCAR'), systemSpecies, crystalSpecies=self.POTCAR.species) self.directory = specs else: msg.fatal( "Unable to initialize a VASP object from the data that you passed in:", specs) if directory is not None: self.directory = directory
def setup_relax_select_input(self): from os import remove, path from aBuild.enumeration import Enumerate from aBuild.database.crystal import Crystal from aBuild.fitting.mtp import MTP from aBuild.utility import unpackProtos, getAllPerms, getProtoPaths from glob import glob self.dataset = "gss" # rename(path.join(self.root,'fitting/mtp') fittingRoot = path.join(self.root, 'fitting', 'mtp') for ilat in range(self.nEnums): lat = self.enumDicts[ilat]["lattice"] if lat == 'protos': structures = getProtoPaths() # subdivide = [structures[x:x+100] for x in range() ] for struct in structures: print("Proto structure:", struct) scrambleOrder = getAllPerms(self.knary, justCyclic='uniqueUnaries' in struct) for scramble in scrambleOrder: thisCrystal = Crystal(struct, self.species) #print("Atom counts before scramble {}".format(thisCrystal.atom_counts)) thisCrystal.scrambleAtoms(scramble) #print("Atom counts after scramble {}".format(thisCrystal.atom_counts)) with open(path.join(fittingRoot, 'to-relax.cfg'), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) else: enumLattice = Enumerate(self.enumDicts[ilat]) for struct in range(1, enumLattice.nConfigs + 1): print("Lattice", lat, "structure:", struct) enumLattice.generatePOSCAR(struct) thisCrystal = Crystal( path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)), self.species) with open(path.join(fittingRoot, 'to-relax.cfg'), 'a+') as f: f.writelines('\n'.join(thisCrystal.lines('mtprelax'))) delpath = path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)) remove(delpath) fittingRoot = path.join(self.root, 'fitting', 'mtp') thisMTP = MTP(fittingRoot, settings=self.fitting) thisMTP.calc_grade() thisMTP.write_relaxin()
def init_file(self, datafile, systemSpecies, linesformat): from aBuild.database.crystal import Crystal possibleFiles = { 'new_training.cfg': 'mlpadd', 'train.cfg': 'mlptrain', 'structures.in': 'ce' } #selectedFile = path.join(self.root,'new_training.cfg') with open(datafile, 'r') as f: lines = f.readlines() self.crystals = [] nCrystals = 0 for index, line in enumerate(lines): if line == 'BEGIN_CFG\n': # nCrystals += 1 #if numOfStructs is not 'all' and (nCrystals < start or nCrystals > start + numOfStructs): # continue nAtoms = int(lines[index + 2].split()[0]) structlines = lines[index:index + 11 + nAtoms] thisCrystal = Crystal(structlines, systemSpecies, lFormat=linesformat) self.crystals.append(thisCrystal)
def randomDisplacements(self, POSCAR): from os import path from aBuild.database.crystal import Crystal toRelax = path.join(self.root, 'fitting', 'mtp', 'to_relax.cfg') for i in range(1000): thisCrystal = Crystal(POSCAR, systemSpecies=self.species) thisCrystal.randomDisplace() print(thisCrystal.lines('mtprelax')) with open(toRelax, 'a+') as f: f.writelines('\n'.join(thisCrystal.lines('mtprelax')))
def _init_mlp(self, datafile): from aBuild.database.crystal import Crystal import os from os import path from aBuild.calculators.vasp import VASP with open(datafile, 'r') as f: lines = f.readlines() self.crystals = [] nCrystals = 0 # Get information for pures so I can calculate formation energies root = os.getcwd() pures = [ VASP(path.join(root, 'training_set', 'pure' + x), systemSpecies=self.species) for x in self.species ] puresDict = {} for ispec, spec in enumerate(self.species): pures[ispec].read_results() # puresDict[spec] = pures[ispec].crystal.results["energypatom"] print(pures, 'pures') for index, line in enumerate(lines): if 'BEGIN' in line: indexStart = index elif 'END' in line: indexEnd = index structlines = lines[indexStart:indexEnd + 1] print("Processed {} crystals".format(nCrystals)) nCrystals += 1 thisCrystal = Crystal(structlines, self.species, lFormat='mlp') if thisCrystal.results == None: if thisCrystal.minDist > 1.5: self.crystals.append(thisCrystal) else: thisCrystal.results["fEnth"] = thisCrystal.results[ "energyF"] / thisCrystal.nAtoms - sum([ pures[i].crystal.results["energyF"] / pures[i].crystal.nAtoms * thisCrystal.concentrations[i] for i in range(thisCrystal.nTypes) ]) if thisCrystal.results[ "energyF"] < 100 and thisCrystal.minDist > 1.5: self.crystals.append(thisCrystal) else: print( "Not adding structure {}. Seems like an extreme one." .format(thisCrystal.title)) print("Energy: {}".format( thisCrystal.results["energyF"])) print("MinDist: {}".format(thisCrystal.minDist))
def build_relax_select_input(self): from os import remove, path from aBuild.enumeration import Enumerate from aBuild.database.crystal import Crystal from aBuild.fitting.mtp import MTP from aBuild.utility import unpackProtos, getAllPerms from glob import glob fittingRoot = path.join(self.root, 'fitting', 'mtp') for ilat in range(self.nEnums): lat = self.enumDicts[ilat]["lattice"] enumLattice = Enumerate(self.enumDicts[ilat]) if lat == 'protos': structures = getProtoPaths() for struct in structures: scrambleOrder = getAllPerms(self.knary, justCyclic='uniqueUnaries' in struct) for scramble in scrambleOrder: thisCrystal = Crystal(struct, species=self.species) thisCrystal.scrambleAtoms(scramble) thisMTP = MTP(fittingRoot, dataSet=[thisCrystal], forRelax=True) with open(path.join(fittingRoot, 'to-relax.cfg'), 'a+') as f: f.writelines(thisMTP.lines) else: for struct in range(1, enumLattice.nEnumStructs + 1): enumLattice.generatePOSCAR(struct) thisCrystal = Crystal.fromPOSCAR( enumLattice.root, self.species, filename="poscar.{}.{}".format(lat, struct), title=' '.join([lat, " str #: {}"]).format(struct)) thisMTP = MTP(fittingRoot, dataSet=[thisCrystal], forRelax=True) with open(path.join(fittingRoot, 'to-relax.cfg'), 'a+') as f: f.writelines(thisMTP.lines) delpath = path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)) remove(delpath) thisMTP.write_relaxin()
def from_dictionary(specsDict): from aBuild.database.crystal import Crystal specsDict["potcar"]["build"] = "manual" specsDict["potcar"]["directory"] = None potcarobj = POTCAR(specsDict["potcar"]) kpointsobj = KPOINTS(specsDict["kpoints"]) if isinstance(specsDict["crystal"], Crystal): crystal = specsDict["crystal"] else: print("This just happened!!!") crystal = Crystal(specsDict["crystal"]) specsDict["incar"][ "nAtoms"] = crystal.nAtoms #for ensuring MAGMOM tag is correct incarobj = INCAR(specsDict["incar"]) return VASP(incarobj, kpointsobj, potcarobj, crystal, specsDict["directory"])
def __init__(self, specs,systemSpecies,directory = None): #crystal,potential, from aBuild.database.crystal import Crystal # self.crystal = crystal self.species = systemSpecies # self.potential = potential if isinstance(specs,dict): self.crystal = specs["crystal"] self.potential = specs["potential"] elif isinstance(specs, str): self.crystal = Crystal(path.join(specs,'input.in'),systemSpecies) self.settings = self.parse_lammps_settings(specs) self.directory = specs
def init_enum(self, enumdicts, systemSpecies, runGetKpoints=True): from aBuild.enumeration import Enumerate from aBuild.calculators.vasp import VASP from aBuild.database.crystal import Crystal from aBuild.jobs import Job from random import randrange from aBuild.utility import chdir # from crystal import Crystal from os import path import os # if not path.isdir(self.root): # os.mkdir(self.root) print("Building database from enumerations") self.crystals = [] # configIndex = startPoint = self._starting_point for eDict in enumdicts: enumController = Enumerate(eDict) if enumController.nEnumStructs == 0: msg.warn( 'There are no enumerated structures for lattice type {}. Not building any VASP folders for them.' .format(self.enumDicts[index]["lattice"])) enumController.buildInputFile() enumController.enumerate() # Loop to generate random structures for a given lattice type for i in range(eDict["nconfigs"]): rStruct = randrange(1, enumController.nEnumStructs) print('Adding {} structure # {} to database'.format( eDict["lattice"], rStruct)) with open('structNums', 'a+') as f: f.write(eDict["lattice"] + ' ' + str(rStruct) + '\n') #print("Building VASP folder for {} structure #: {}".format(eDict["lattice"],rStruct)) enumController.generatePOSCAR(rStruct) poscarpath = path.join( enumController.root, "poscar.{}.{}".format(eDict["lattice"], rStruct)) thisCrystal = Crystal( poscarpath, systemSpecies=systemSpecies ) #title = ' '.join([self.enumDicts[index]["lattice"]," str #: {}"]).format(rStruct) self.crystals.append(thisCrystal)
def build_ToRelax(self, enumDicts, species, AFM=False, start=1, end=None): from aBuild.enumeration import Enumerate from aBuild.utility import unpackProtos, getAllPerms, getProtoPaths from aBuild.database.crystal import Crystal from os import remove, path print('Building to-relax.cfg') print(enumDicts) nEnums = len(enumDicts) knary = len(species) for ilat in range(nEnums): lat = enumDicts[ilat]["name"] if lat == 'protos': structures = getProtoPaths(knary) for struct in structures: print("Proto structure:", struct) scrambleOrder = getAllPerms(knary, justCyclic='uniqueUnaries' in struct) for scramble in scrambleOrder: thisCrystal = Crystal(struct, species) #print("Atom counts before scramble {}".format(thisCrystal.atom_counts)) thisCrystal.scrambleAtoms(scramble) if not thisCrystal.concsOK( concRestrictions=enumDicts[ilat]["concs"]): continue print(thisCrystal.title) mindist = thisCrystal.minDist print( mindist, "actual min dist<-----------------------------------------------------------------------------------------------------" ) if mindist > 2 and thisCrystal.nAtoms < 60: if not AFM: print('Adding to file') #print("Atom counts after scramble {}".format(thisCrystal.atom_counts)) with open(path.join(self.root, 'to-relax.cfg'), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) elif thisCrystal.getAFMPlanes([1, 0, 0]): print("Original Crystal is AFM compatible") with open( path.join(self.root, 'to-relax.cfg_' + str(start)), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) # break else: print("Checking super-periodics") superCrystal = thisCrystal.superPeriodics(2) if superCrystal != []: print('Found a super-Periodic that works') print(superCrystal.basis, 'basis') print(superCrystal.atom_counts, 'atom counts') with open( path.join( self.root, 'to-relax.cfg_' + str(start)), 'a+') as f: f.writelines('\n'.join( superCrystal.lines('mtprelax'))) # break else: enumLattice = Enumerate(enumDicts[ilat]) print(end, 'end') if end == None: end = enumLattice.nConfigs + 1 filetag = '' else: filetag = '_' + str(start) #for struct in range(enumLattice.nConfigs+1): for struct in range(start, end): print("Lattice", lat, "structure:", struct) enumLattice.generatePOSCAR(struct) thisCrystal = Crystal( path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)), species) if not AFM: print('Writing to file!!!!!', end) with open( path.join(self.root, 'to_relax.cfg' + filetag), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) elif thisCrystal.getAFMPlanes([1, 0, 0]): print("Original Crystal is AFM compatible") with open( path.join(self.root, 'to_relax.cfg' + filetag), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) else: print("Checking super-periodics") superCrystal = thisCrystal.superPeriodics(2) if superCrystal != []: print('Found a super-Periodic that works') with open( path.join(self.root, 'to_relax.cfg' + filetag), 'a+') as f: f.writelines('\n'.join( superCrystal.lines('mtprelax'))) # print(thisCrystal.appMinDist,' approp Min Dist') # print(thisCrystal.minDist, 'actual min dist') # with open(path.join(self.root,'to-relax.cfg'),'a+') as f: # f.writelines('\n'.join(thisCrystal.lines('mtprelax') )) delpath = path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)) remove(delpath) end = None
def init_enum(self, enumdicts, systemSpecies, runGetKpoints=True): from aBuild.enumeration import Enumerate from aBuild.calculators.vasp import VASP from aBuild.database.crystal import Crystal from aBuild.jobs import Job from random import randrange from aBuild.utility import chdir from numpy import array from os import remove, path # from crystal import Crystal from os import path import os # if not path.isdir(self.root): # os.mkdir(self.root) print("Building database from enumerations") self.crystals = [] # configIndex = startPoint = self._starting_point for eDict in enumdicts: enumController = Enumerate(eDict) if enumController.nEnumStructs == 0: msg.warn( 'There are no enumerated structures for lattice type {}. Not building any VASP folders for them.' .format(self.enumDicts[index]["lattice"])) enumController.buildInputFile() enumController.enumerate() # Loop to generate random structures for a given lattice type for i in range(eDict["nconfigs"]): rStruct = 16254 #randrange(1,enumController.nEnumStructs) print('Adding {} structure # {} to database'.format( eDict["lattice"], rStruct)) with open('structNums', 'a+') as f: f.write(eDict["name"] + ' ' + str(rStruct) + '\n') #print("Building VASP folder for {} structure #: {}".format(eDict["lattice"],rStruct)) enumController.generatePOSCAR(rStruct) poscarpath = path.join( enumController.root, "poscar.{}.{}".format(eDict["name"], rStruct)) thisCrystal = Crystal( poscarpath, systemSpecies=systemSpecies ) #title = ' '.join([self.enumDicts[index]["lattice"]," str #: {}"]).format(rStruct) if self.restrictions is None: self.crystals.append(thisCrystal) elif thisCrystal.getAFMPlanes([1, 0, 0]): print('parent is AFM compatible') self.crystals.append(thisCrystal) import sys sys.exit() else: superCrystal = thisCrystal.superPeriodics(2) if superCrystal != []: print('super periodic structures is AFM compatible') print(superCrystal.minDist, 'minDist') print(superCrystal.basis, ' basis') print(array(superCrystal.Bv_direct), 'direct') print(array(superCrystal.Bv_cartesian), 'cartesian') self.crystals.append(superCrystal) import sys sys.exit() else: print("Can't find an AFM compatible structure") import sys sys.exit() # self.crystals.append(thisCrystal) delpath = path.join( enumController.root, "poscar.{}.{}".format(eDict["name"], rStruct)) remove(delpath)
enumController.enumerate() # Loop to generate random structures for a given lattice type <<<<<<< HEAD for i in range(eDict["nconfigs"]): rStruct = 16254#randrange(1,enumController.nEnumStructs) print('Adding {} structure # {} to database'.format(eDict["lattice"],rStruct) ) with open('structNums','a+') as f: f.write(eDict["name"] + ' ' + str(rStruct) + '\n') #print("Building VASP folder for {} structure #: {}".format(eDict["lattice"],rStruct)) enumController.generatePOSCAR(rStruct) poscarpath = path.join(enumController.root,"poscar.{}.{}".format(eDict["name"],rStruct)) thisCrystal = Crystal(poscarpath, systemSpecies = systemSpecies) #title = ' '.join([self.enumDicts[index]["lattice"]," str #: {}"]).format(rStruct) if self.restrictions is None: self.crystals.append(thisCrystal) elif thisCrystal.getAFMPlanes([1,0,0]): print('parent is AFM compatible') self.crystals.append(thisCrystal) import sys sys.exit() else: superCrystal = thisCrystal.superPeriodics(2) if superCrystal != []: print('super periodic structures is AFM compatible') print(superCrystal.minDist, 'minDist') print(superCrystal.basis,' basis') print(array(superCrystal.Bv_direct), 'direct') print(array(superCrystal.Bv_cartesian), 'cartesian')
def build_ToRelax(self, enums, species, AFM=False, start=1, end=None): from aBuild.enumeration import Enumerate from aBuild.utility import unpackProtos, getAllPerms, getProtoPaths from aBuild.database.crystal import Crystal from os import remove, path print('Building to_relax.cfg') nEnums = len(enums) knary = len(species) for ilat in range(nEnums): lat = enums[ilat].lattice.lattice_name if lat == 'protos': structures = getProtoPaths(knary) for struct in structures: print("Proto structure:", struct) scrambleOrder = getAllPerms(knary, justCyclic='uniqueUnaries' in struct) for scramble in scrambleOrder: thisCrystal = Crystal(struct, species) #print("Atom counts before scramble {}".format(thisCrystal.atom_counts)) thisCrystal.scrambleAtoms(scramble) if not thisCrystal.concsOK( concRestrictions=enums[ilat]["concs"]): continue mindist = thisCrystal.minDist if mindist > 2: with open(path.join(self.root, 'to_relax.cfg'), 'a+') as f: f.writelines('\n'.join( thisCrystal.lines('mtprelax'))) else: enumLattice = enums[ilat] if end == None: end = enumLattice.nConfigs + 1 filetag = '' else: filetag = '_' + str(start) #for struct in range(enumLattice.nConfigs+1): for struct in range(start, end): print("Generating {} crystal structure # {}.".format( lat, struct)) enumLattice.generatePOSCAR(struct) # When initializing a crystal object from a poscar generated by makestr.x, I know that the crystal species is # the same as the system species because it generates zeros in the atom counts list. print('initializing object') thisCrystal = Crystal.from_poscar( path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)), species) thisCrystal.set_latpar(modify=enumLattice.latticeExpand) with open(path.join(self.root, 'to_relax.cfg' + filetag), 'a+') as f: f.writelines('\n'.join(thisCrystal.lines('mtprelax'))) delpath = path.join(enumLattice.root, "poscar.{}.{}".format(lat, struct)) remove(delpath)
if not path.isfile(dataFile): msg.fatal('data file does not exist') data = dataset(dataFile,self.species) <<<<<<< HEAD data.generateConvexHullPlot(plotAll = plotAll) ======= data.generateConvexHullPlot() ############################################################ #generate a .cif file from the POSCAR provided def generate_cif(self,groundStatePoscar): from os import path from aBuild.database.crystal import Crystal #generate the .cif file input = Crystal(groundStatePoscar,self.species) input.generate_cif() ############################################################ >>>>>>> 03893ba98eddd6991de841e54e88613fa8b4165d def errorsReport(self,datafile = None, predictFile = None): from aBuild.database.dataset import dataset from numpy.linalg import norm from numpy import average,array dataSet = dataset(datafile,self.species,lFormat = 'mlp') predictSet = dataset(predictFile,self.species,lFormat = 'mlp') diffsEnergy = [] diffsForces = [] for i in dataSet.crystals:
def _init_dataReport(datafile, species, onlyCloseToHull=False, cutoff=5e-3, getCrystallographicInfo=False, enums=None): if getCrystallographicInfo and enumDicts == None: msg.fatal( "Can't extract crystallographic information without the enumeration dictionaries" ) with open(datafile, 'r') as f: lines = f.readlines() del lines[:4] required = [ "lattice", "basis", "atom_types", "crystalSpecies", "latpar", "coordsys", "systemSpecies" ] nAtoms = int((len(lines[0].split()) - 9) / 2) lookup = {} for enum in enums: lookup[enum.lattice.lattice_name] = enum # In case we don't want the full crystallographic information, # let's build an empty crystal object that we can fill up with # the information that we want. templateDict = {} for key in required: templateDict[key] = None templateDict["results"] = {} # crystal = Crystal(templateDict) count = 0 crystals = [] for line in lines: formationEnthalpy = float(line.split()[8]) energyF = float(line.split()[6]) title = ' '.join(line.split()[:6]) atomCounts = list(map(int, line.split()[-nAtoms:])) lattice = str(line.split()[1].split('_')[1]) structNum = int(line.split()[5]) if len(line.split()) == 16: distanceToHull = float(line.split()[9]) else: distanceToHull = None if onlyCloseToHull: if distanceToHull > cutoff: continue if getCrystallographicInfo: crystal = Crystal.fromEnum(lookup[lattice], structNum, species) crystal.results["fEnth"] = formationEnthalpy crystal.results["energyF"] = energyF crystal.results["distToHull"] = distanceToHull else: templateDict["fEnth"] = formationEnergy templateDict["energyF"] = energyF templateDict["distanceToHull"] = distanceToHull templateDict["title"] = title templateDict["atom_counts"] = atomCounts templateDict["crystalSpecies"] = species crystal = Crystal(templateDict) count += 1 print("Read in crystal {}".format(count)) crystals.append(crystal) return dataset(crystals)
from os import remove,path print('Building to-relax.cfg') nEnums = len(enumDicts) knary = len(species) for ilat in range(nEnums): lat = enumDicts[ilat]["name"] if lat == 'protos': #for prototype structures, we want to make sure that the mindist is okay structures = getProtoPaths(knary) for struct in structures: print("Proto structure:", struct) scrambleOrder = getAllPerms(knary,justCyclic = 'uniqueUnaries' in struct) for scramble in scrambleOrder: thisCrystal = Crystal(struct,species) #print("Atom counts before scramble {}".format(thisCrystal.atom_counts)) thisCrystal.scrambleAtoms(scramble) if not thisCrystal.concsOK(concRestrictions = enumDicts[ilat]["concs"]): continue print(thisCrystal.title) mindist = thisCrystal.minDist print(mindist, "actual min dist<-----------------------------------------------------------------------------------------------------") <<<<<<< HEAD if mindist > 2 and thisCrystal.nAtoms < 60: if not AFM: print('Adding to file') #print("Atom counts after scramble {}".format(thisCrystal.atom_counts)) with open(path.join(self.root,'to-relax.cfg'),'a+') as f: