def write_input(self, structures, output_dir, make_dir_if_not_present=True, write_cif=False): """ NEB inputs has a special directory structure where inputs are in 00, 01, 02, .... Args: structures: list of Structure objects. There should be nimages + 2 structures (including start and end structures). output_dir: Directory to output the VASP input files make_dir_if_not_present: Set to True if you want the directory (and the whole path) to be created if it is not present. write_cif: If true, writes a cif along with each POSCAR """ if len(structures) != self.incar_settings['IMAGES'] + 2: raise ValueError('incorrect number of structures') if make_dir_if_not_present and not os.path.exists(output_dir): os.makedirs(output_dir) s0 = structures[0] self.get_incar(s0).write_file(os.path.join(output_dir, 'INCAR')) self.get_kpoints(s0).write_file(os.path.join(output_dir, 'KPOINTS')) self.get_potcar(s0).write_file(os.path.join(output_dir, 'POTCAR')) for i, s in enumerate(structures): d = os.path.join(output_dir, str(i).zfill(2)) if make_dir_if_not_present and not os.path.exists(d): os.makedirs(d) self.get_poscar(s).write_file(os.path.join(d, 'POSCAR')) if write_cif: write_structure(s, os.path.join(d, '{}.cif'.format(i)))
import pymatgen as pm import numpy as np import csv import copy import warnings import ewald from itertools import combinations, combinations_with_replacement, permutations from rotation_matrix import * from scipy.optimize import minimize from sys import maxint """ The tetpack module works like this: 1. Start with a solid-state structure, preferably something "tetrahedral close-packed (tcp)," e.g. gamma brass(Cu5Zn8) 2. Scan up to n nearest neighbors for each site (see function n_nearest_neighbors) 3. Pick out "most regular" tetrahedra formed by each site and any three neighbors (get_tets) 4. Remove duplicates (remove_duplicate_tets) 5. Build regular tetrahedra. They are aligned to best match the tetrahedral cell they are drawn from, which of course is not regular (see the tetrahedron class) 6. Add the perfect tetrahedra to a new periodic structure as methane -- C is the center, each H is a vertex (tetrahedron.add_to_structure) 7. compression, annealing...see compression.py There is a convenience method tetrahedron_from_structure that combines steps 1-6. It takes a pymatgen structure object and returns a new structure with tetrahedra (methanes) and a list of tetrahedra objects: Example: import pymatgen as pm #import pymatgen import tetpack #import this module gamma = pm.read_structure('mp-1368.mson') #load the gamma brass structure tet_str, tet_reg = tetpack.tetrahedra_from_structure(gamma) #generate a new pymatgen structure (periodic) and a list of tetrahedra objects pm.write_structure(tet_str, 'tet_str.cif') #export our methane tetrahedra to a CIF so we can view it in the crystallohraphic structure program of our choice! """
def make_super(size,filename): shutil.copyfile('POSCAR_primitive', filename) struct = mg.read_structure(filename) Structure.make_supercell(struct,size) mg.write_structure(struct,filename)
''' Created on September 22, 2013 @author: Tess ''' import pymatgen from pymatgen.symmetry.finder import SymmetryFinder s = pymatgen.read_structure('POSCAR') structure = SymmetryFinder(s).get_conventional_standard_structure() pymatgen.write_structure(structure,"POSCAR")
index = find_atom(r_coords,supercell) supercell.replace(index,supercell[index].specie,r_coords) if __name__=='__main__': center = [0.0, 0.0, 0.0] argv = sys.argv[1:] opts, args = getopt.getopt(argv,"s") Size = int(args[0]) size = int(args[1]) shift_vector = get_shift_vector(center,size,size) Shift_Vector = get_shift_vector(center,size,Size) supercell = mg.read_structure('POSCAR_super') shift_coords(supercell,Shift_Vector) relax = mg.read_structure('POSCAR_relax') shift_coords(relax,shift_vector) defect = mg.read_structure('POSCAR_defect') shift_coords(defect,shift_vector) compare_coords(relax,defect,supercell,size,Size) rescale(relax,size,Size) replace(supercell,relax) shift_coords(supercell,-Shift_Vector) mg.write_structure(supercell,'POSCAR_final')
index = find_atom(r_coords, supercell) supercell.replace(index, supercell[index].specie, r_coords) if __name__ == '__main__': center = [0.0, 0.0, 0.0] argv = sys.argv[1:] opts, args = getopt.getopt(argv, "s") Size = int(args[0]) size = int(args[1]) shift_vector = get_shift_vector(center, size, size) Shift_Vector = get_shift_vector(center, size, Size) supercell = mg.read_structure('POSCAR_super') shift_coords(supercell, Shift_Vector) relax = mg.read_structure('POSCAR_relax') shift_coords(relax, shift_vector) defect = mg.read_structure('POSCAR_defect') shift_coords(defect, shift_vector) compare_coords(relax, defect, supercell, size, Size) rescale(relax, size, Size) replace(supercell, relax) shift_coords(supercell, -Shift_Vector) mg.write_structure(supercell, 'POSCAR_final')
import pymatgen from pymatgen.symmetry.finder import SymmetryFinder s = pymatgen.read_structure('POSCAR') #print SymmetryFinder(s).find_primitive() structure = SymmetryFinder(s).find_primitive() pymatgen.write_structure(structure, "POSCAR")
import pymatgen as mg from pymatgen.core.structure import Structure filename = raw_input("file name:") l = raw_input("x scale:") m = raw_input("y scale:") n = raw_input("z scale:") struct = mg.read_structure(filename) Structure.make_supercell(struct, [l, m, n]) mg.write_structure(struct, "poscar_temp") f = open("poscar_temp") w = open("mast.inp", "w") def getinfo(line): line = line.strip("\n") data = line.split(" ") while 1: try: data.remove("") except: break return data line = [] elenum = [] line.append(f.readline())
import pymatgen as mg from pymatgen.core.structure import Structure filename = raw_input('file name:') l = raw_input('x scale:') m = raw_input('y scale:') n = raw_input('z scale:') struct = mg.read_structure(filename) Structure.make_supercell(struct, [l, m, n]) mg.write_structure(struct, "poscar_temp") f = open("poscar_temp") w = open("mast.inp", "w") def getinfo(line): line = line.strip('\n') data = line.split(' ') while 1: try: data.remove('') except: break return data line = [] elenum = [] line.append(f.readline())
def main(filename = 'mp-1368.mson', beta = 1.0, initial_temp = 1.0, precomputed_structure = False): def temperature(phi_, beta_, initial_temp_): #cooling profile. returns a temperature according to initial_temp*exp(-beta*phi), where phi is the current packing fraction, and beta is a free parameter return initial_temp_*np.exp(-beta_*phi_) #Filename of starting structure #Cutoff for tetrahedron distortion -- higher numbers will accept more distorted tetrahedra std_dev_cutoff = 0.50 #Initial factor for increasing all axes initial_increase_factor = 2.5 #Compression increment -- compress by fixed percentage: compression_factor = -0.01 #Tetrahedra become distorted due compounding numerical error. Re-regularize every n steps: normalization_frequency = 1 #Save structure every n steps: save_frequency = 1 #Controls how much tetrahedra can jostle during packing temp = 1. #How many tries to fit a tetrahedra before skipping resolution_max = 5000 #How far a tet can travel randomly distance_max = 1.0 #Initialize sturcture and tetrahedra print '\nLoading initial structure...', sys.stdout.flush() initial_structure = pm.read_structure(filename) if not precomputed_structure: path = initial_structure.composition.alphabetical_formula.replace(' ', '') + '_beta_' + str(beta) + '_T_' + str(initial_temp) if not os.path.exists(path): os.mkdir(path) print initial_structure.composition.alphabetical_formula + ' loaded.' print '\nExtracting tetrahedra...', sys.stdout.flush() tet_str, tet_reg = tetpack.tetrahedra_from_structure(initial_structure, stdcutoff=std_dev_cutoff) print str(len(tet_reg)) + ' initial tetrahedra extracted.' #Expand structure initally print '\nExpanding cell axes by factor of ' + str(initial_increase_factor) + '...', sys.stdout.flush() current_tet_str = tetpack.adjust_axes(tet_str, initial_increase_factor) current_tet_reg = map(tetpack.tetrahedron, [current_tet_str[5*i:5*i+5] for i in range(len(current_tet_str)/5)]) print 'done: \na = ' + str(current_tet_str.lattice.a) + '\nb = ' + str(current_tet_str.lattice.b) + '\nc = ' + str(current_tet_str.lattice.c) phi = tetpack.packing_density(current_tet_str) print '\nRelaxing structure via Ewald summation...' sys.stdout.flush() current_tet_str = tetpack.ewald_relaxation(current_tet_str, max_steps = 1, motion_factor = temperature(phi, beta, initial_temp)) else: path = filename.rstrip('.mson') + '_beta_' + str(beta) + '_T_' + str(initial_temp) if not os.path.exists(path): os.mkdir(path) current_tet_str = initial_structure current_tet_reg = map(tetpack.tetrahedron, [current_tet_str[5*i:5*i+5] for i in range(len(current_tet_str)/5)]) print '\nBeginning compression loop:' #Loop until collision collision = False step = 0 while(not collision): phi = tetpack.packing_density(current_tet_str) if np.mod(step, normalization_frequency) == 0: print 'Normalizing tetrahedra...', sys.stdout.flush() [tet.regularize() for tet in current_tet_reg] print 'done.' current_tet_str, current_tet_reg = compress(current_tet_str, current_tet_reg, temperature(phi, beta, initial_temp)*compression_factor) print 'Step '+ str(step) + ' packing fraction: ' + str(phi) + ' T:' + str(temperature(phi, beta, initial_temp)) + '...', sys.stdout.flush() failed = check_and_resolve_collisions(current_tet_str, current_tet_reg, temperature(phi, beta, initial_temp), distance_max, int(1./temperature(phi, beta, initial_temp)*resolution_max)) if failed: print 'Relaxing structure...', sys.stdout.flush() current_tet_str, current_tet_reg = compress(current_tet_str, current_tet_reg, -1.5* temperature(phi, beta, initial_temp)* compression_factor) phi = tetpack.packing_density(current_tet_str) print 'done. Packing fraction: ' + str(phi) print 'Single-step Ewald relaxation...' sys.stdout.flush() current_tet_str = tetpack.ewald_relaxation(current_tet_str, max_steps = 1, motion_factor = temperature(phi, beta, initial_temp)) print 'done.' failed = False else: if np.mod(step, save_frequency) == 0: print 'Writing structure...', sys.stdout.flush() pm.write_structure(current_tet_str, os.path.join(path, str(step) + '.cif')) tetpack.to_challenge_output(current_tet_str, os.path.join(path, str(step) + '.csv')) print 'done.' step += 1
''' Created on September 22, 2013 @author: Tess ''' import pymatgen from pymatgen.symmetry.finder import SymmetryFinder from pymatgen.core.structure_modifier import StructureModifier from pymatgen.core.structure_modifier import SupercellMaker s = pymatgen.read_structure('POSCAR') s.make_supercell([3,1,1]) pymatgen.write_structure(s,"POSCAR2")
def main(filename='mp-1368.mson', beta=1.0, initial_temp=1.0, precomputed_structure=False): def temperature(phi_, beta_, initial_temp_): #cooling profile. returns a temperature according to initial_temp*exp(-beta*phi), where phi is the current packing fraction, and beta is a free parameter return initial_temp_ * np.exp(-beta_ * phi_) #Filename of starting structure #Cutoff for tetrahedron distortion -- higher numbers will accept more distorted tetrahedra std_dev_cutoff = 0.50 #Initial factor for increasing all axes initial_increase_factor = 2.5 #Compression increment -- compress by fixed percentage: compression_factor = -0.01 #Tetrahedra become distorted due compounding numerical error. Re-regularize every n steps: normalization_frequency = 1 #Save structure every n steps: save_frequency = 1 #Controls how much tetrahedra can jostle during packing temp = 1. #How many tries to fit a tetrahedra before skipping resolution_max = 5000 #How far a tet can travel randomly distance_max = 1.0 #Initialize sturcture and tetrahedra print '\nLoading initial structure...', sys.stdout.flush() initial_structure = pm.read_structure(filename) if not precomputed_structure: path = initial_structure.composition.alphabetical_formula.replace( ' ', '') + '_beta_' + str(beta) + '_T_' + str(initial_temp) if not os.path.exists(path): os.mkdir(path) print initial_structure.composition.alphabetical_formula + ' loaded.' print '\nExtracting tetrahedra...', sys.stdout.flush() tet_str, tet_reg = tetpack.tetrahedra_from_structure( initial_structure, stdcutoff=std_dev_cutoff) print str(len(tet_reg)) + ' initial tetrahedra extracted.' #Expand structure initally print '\nExpanding cell axes by factor of ' + str( initial_increase_factor) + '...', sys.stdout.flush() current_tet_str = tetpack.adjust_axes(tet_str, initial_increase_factor) current_tet_reg = map(tetpack.tetrahedron, [ current_tet_str[5 * i:5 * i + 5] for i in range(len(current_tet_str) / 5) ]) print 'done: \na = ' + str(current_tet_str.lattice.a) + '\nb = ' + str( current_tet_str.lattice.b) + '\nc = ' + str( current_tet_str.lattice.c) phi = tetpack.packing_density(current_tet_str) print '\nRelaxing structure via Ewald summation...' sys.stdout.flush() current_tet_str = tetpack.ewald_relaxation(current_tet_str, max_steps=1, motion_factor=temperature( phi, beta, initial_temp)) else: path = filename.rstrip('.mson') + '_beta_' + str(beta) + '_T_' + str( initial_temp) if not os.path.exists(path): os.mkdir(path) current_tet_str = initial_structure current_tet_reg = map(tetpack.tetrahedron, [ current_tet_str[5 * i:5 * i + 5] for i in range(len(current_tet_str) / 5) ]) print '\nBeginning compression loop:' #Loop until collision collision = False step = 0 while (not collision): phi = tetpack.packing_density(current_tet_str) if np.mod(step, normalization_frequency) == 0: print 'Normalizing tetrahedra...', sys.stdout.flush() [tet.regularize() for tet in current_tet_reg] print 'done.' current_tet_str, current_tet_reg = compress( current_tet_str, current_tet_reg, temperature(phi, beta, initial_temp) * compression_factor) print 'Step ' + str(step) + ' packing fraction: ' + str( phi) + ' T:' + str(temperature(phi, beta, initial_temp)) + '...', sys.stdout.flush() failed = check_and_resolve_collisions( current_tet_str, current_tet_reg, temperature(phi, beta, initial_temp), distance_max, int(1. / temperature(phi, beta, initial_temp) * resolution_max)) if failed: print 'Relaxing structure...', sys.stdout.flush() current_tet_str, current_tet_reg = compress( current_tet_str, current_tet_reg, -1.5 * temperature(phi, beta, initial_temp) * compression_factor) phi = tetpack.packing_density(current_tet_str) print 'done. Packing fraction: ' + str(phi) print 'Single-step Ewald relaxation...' sys.stdout.flush() current_tet_str = tetpack.ewald_relaxation( current_tet_str, max_steps=1, motion_factor=temperature(phi, beta, initial_temp)) print 'done.' failed = False else: if np.mod(step, save_frequency) == 0: print 'Writing structure...', sys.stdout.flush() pm.write_structure(current_tet_str, os.path.join(path, str(step) + '.cif')) tetpack.to_challenge_output( current_tet_str, os.path.join(path, str(step) + '.csv')) print 'done.' step += 1
def prepare_for_zeo(dir, remove_duplicates = False, separator = None): ''' Takes a directory of cif files and filters zeo++ usable files. Requires pymatgen. Creates new directories: ./ready - oxidation state decorated files for zeo++ to use. ./no-rad - structures with species having no corresponding ionic radii in pymatgen database ./fails - structures which cannot be assigned oxidation states If remove_duplicates is set to true, it runs the files through remove_duplicates. Files pulled out of the database are of the format <id><speparator><formula>. The separator is usually '_' or '-'. ''' # TODO maybe let the user specify the location of the new directories files = [file for file in os.listdir(dir) if file.endswith('cif')] d = {} # Dictionary of the form d[<filename>]['struct'], d[<filename>]['mass'], d[<filename>]['radius'] fails, no_rad = [], [] for file in files: d[file] = {} # reading to pymatgen structure object s = mg.read_structure('{1}/{0}'.format(file, dir)) # AutoOxidationStateDecorationObject ox = oxi() try: # Oxidation state decorated structure s_ox = ox.apply_transformation(s) # Saving structure to dictionary d[file]['struct'] = s_ox # List of unique elements in the structure species = set(s_ox.species) radii = dict((str(sp), float(sp.ionic_radius)) for sp in species) masses = dict((str(sp), float(sp.atomic_mass)) for sp in species) d[file]['radii'] = radii d[file]['masses'] = masses for sp in species: if sp.ionic_radius == None: # These are charge decorated files which have an assigned oxidation state but no radius in pymatgen corresponding to that state # These files will have to be analyzed later, possibly using the crystal radius from the shannon table no_rad.append(file) break except: # These are files that cannot be assigned oxidation states - bond valence fails either due to disorder or is unable to find a charge neutral state fails.append(file) d[file]['struct'] = s d[file]['radii'] = None d[file]['masses'] = None # This is a list of usable files for zeo++ ready = list(set(files).difference(set(no_rad)).difference(set(fails))) for subd in ['zeo-ready', 'zeo-no-rad', 'zeo-fails']: # This creates subdirectories if not already present if not os.path.isdir('{0}/{1}'.format(dir, subd)): os.makedirs('{0}/{1}'.format(dir, subd)) if remove_duplicates: d_ready = remove_duplicates(ready, separator) ready = [d_ready[key] for key in d_ready] d_no_rad = remove_duplicates(no_rad, separator) no_rad = [d_no_rad[key] for key in d_no_rad] d_fails = remove_duplicates(fails, separator) fails = [d_fails[key] for key in d_fails] # Writing files into respective sub-directories for file in ready: mg.write_structure(d[file]['struct'], '{0}/zeo-ready/{1}'.format(dir, file)) # write the radius and the mass files also filename = file.rsplit('.cif',1)[0] write_rad_file(d[file]['radii'],'{0}/zeo-ready'.format(dir), filename) write_mass_file(d[file]['masses'],'{0}/zeo-ready'.format(dir), filename) for file in no_rad: # These files do not have a radius for atleast one of the species mg.write_structure(d[file]['struct'], '{0}/zeo-no-rad/{1}'.format(dir,file)) for file in fails: # Note: these files are not charge decorated and are simply the original cif files rewritten mg.write_structure(d[file]['struct'], '{0}/zeo-fails/{1}'.format(dir,file)) return len(ready), len(no_rad), len(fails)