def prepare_for_md(dir): ''' Filters out cif files with disorder. Creates new directories: ./md-ready ./disordered ''' if not dir.endswith('/'): dir+='/' files = get_cif_files(dir) ordered, disordered = [], [] for file in files: s = mg.read_structure(dir+file) if s.is_ordered: ordered.append(file) else: disordered.append(file) for subd in ['md-ready', 'disordered']: # This creates subdirectories if not already present if not os.path.isdir('{0}/{1}'.format(dir, subd)): os.makedirs('{0}/{1}'.format(dir, subd)) for file in ordered: shutil.copy(dir + file, dir + 'md-ready/') for file in disordered: shutil.copy(dir + file, dir + 'disordered/') return
def csvbuilder(target_dir, output, column_functions, nary=10): """ Build a csv from structure files. Keyword arguments: target_dir -- string of path to look for structure files output -- filename for output csv column_functions -- list of function that build the csv. Each function should take a pymatgen Structure as a parmeter and return a single numeric or categorical (string or character) value nary -- limit to n-ary structures (e.g. nary = 2 only binary and elemental, nary = 3 only ternary, binary, and elemental, etc.) """ structure_files = os.listdir(target_dir) with open(output, 'wb') as csvfile: next_row = 0 structurewriter = csv.writer(csvfile) for structure_filename in structure_files: a = pm.read_structure(os.path.join(target_dir, structure_filename)) if next_row > 0 and numberOfSpecies(a) < nary: row = [structure_filename] + [f(a) for f in column_functions] structurewriter.writerow(row) next_row += 1 elif numberOfSpecies(a) < nary: colnames = ['fileNames'] + [f.func_name for f in column_functions] structurewriter.writerow(colnames) row = [structure_filename] + [f(a) for f in column_functions] structurewriter.writerow(row) next_row += 2
def coordinationcsv(element, target_dir, output, column_functions): """ Build a coordination csv from structure files. Writes a csv file, one line per structure, containing the average coordination value for 'element' in that sturcture. Any other data columns can be included, per csvbuilder Keyword arguments: element -- string for the element symbol target_dir -- string of path to look for structure files output -- filename for output csv column_functions -- list of function that build the csv. Each function should take a pymatgen Structure as a parmeter and return a single numeric or categorical (string or character) value """ structure_files = os.listdir(target_dir) with open(output, 'wb') as csvfile: next_row = 0 structurewriter = csv.writer(csvfile) for structure_filename in structure_files: a = pm.read_structure(os.path.join(target_dir, structure_filename)) elements = [x.symbol for x in a.species] coordination = a.site_properties['coordination_no'] if next_row > 0 and element in elements: avg_coordination = np.mean([x[1] for x in zip(elements, coordination) if x[0]==element]) row = [f(a) for f in column_functions] + [avg_coordination] structurewriter.writerow(row) next_row += 1 elif element in elements: avg_coordination = np.mean([x[1] for x in zip(elements, coordination) if x[0]==element]) colnames = [f.func_name for f in column_functions] + ['avgCoordination'] structurewriter.writerow(colnames) row = [f(a) for f in column_functions] + [avg_coordination] structurewriter.writerow(row) next_row += 2
def get_structure(self, directory): """Returns the final structure from an optimization""" abspath = '%s/%s/' % (self.directory, directory) if ('vasprun.xml' in os.listdir(abspath)): return Vasprun('%s/vasprun.xml' % abspath).final_structure elif ('CONTCAR' in os.listdir(abspath)): return pmg.read_structure('%s/CONTCAR' % abspath)
def read(inp): my_struct = {} struct = mg.read_structure(inp) for i in range(len(struct)): try: my_struct[str(struct[i].specie)] except: my_struct[str(struct[i].specie)] = [] # New element specie added my_struct[str(struct[i].specie)].append([struct[i].a,struct[i].b,struct[i].c]) return my_struct
def read_CARs(self,GGA,HSE): perfect = defaultdict(defaultdict) defect = defaultdict(lambda:defaultdict(defaultdict)) PA = dict() CARs = os.listdir('.') perfect_tag = self.inputs['perfect'] defect_tag = self.inputs['defect'] for i in range(len(CARs)): keywords = CARs[i].split('_') if not 'CAR' in CARs[i]: continue if 'HSE' in CARs[i]: size = keywords[1]+'_HSE' elif keywords[1] in ' '.join(HSE['size']): size = keywords[1]+'_GGA' else: size = keywords[1] if keywords[0]==perfect_tag and keywords[-1]=='OSZICAR': perfect[size]['energy'] = float(open(CARs[i]).readlines()[-1].split('E0=')[1].split()[0]) elif keywords[0]==defect_tag and keywords[-1]=='OSZICAR': defect[keywords[2]][keywords[3]][size] = float(open(CARs[i]).readlines()[-1].split('E0=')[1].split()[0]) elif keywords[0]==perfect_tag and keywords[-1]=='OUTCAR': PA[size] = self.pa.read_outcar(CARs[i]) elif keywords[0]==defect_tag and keywords[-1]=='OUTCAR': PA['%s_%s_%s'%(keywords[2],keywords[3],size)] = self.pa.read_outcar(CARs[i]) elif keywords[0]==perfect_tag and (keywords[-1]=='POSCAR' or keywords[-1]=='CONTCAR'): shutil.copy(CARs[i],'POSCAR') Ele = pmg.read_structure('POSCAR').species ele = dict() for k in range(len(Ele)): if not Ele[k] in ele.keys(): ele[Ele[k]] = 1 else: ele[Ele[k]] += 1 perfect[size]['ele'] = ele elif keywords[0]==defect_tag and (keywords[-1]=='POSCAR' or keywords[-1]=='CONTCAR'): shutil.copy(CARs[i],'POSCAR') Ele = pmg.read_structure('POSCAR').species ele = dict() os.system('rm POSCAR') for k in range(len(Ele)): if not Ele[k] in ele.keys(): ele[Ele[k]] = 1 else: ele[Ele[k]] += 1 defect[keywords[2]]['ele'][size] = ele return [perfect,defect,PA]
def get_latt(self,model,latt): """Obtaining lattice information from the POSCAR. Args: types <dict>: type of frequency model, types={'types':<int>} lattice <str>: specific name of the POSCAR given by the user """ data={'a':0,'c':0,'No.':0} os.system('cp '+latt+'_POSCAR POSCAR') struct = mg.read_structure('POSCAR') os.system('rm POSCAR') reduced = mg.symmetry.finder.SymmetryFinder(struct,0.001).get_primitive_standard_structure() data['No.'] = len(struct) if model==5: data['a'] = reduced.lattice.abc[0]*np.sqrt(2)*10**(-8) if model==14: data['a'] = reduced.lattice.abc[0]*np.sqrt(2)*10**(-8) if model==8: data['a'] = reduced.lattice.abc[0]*10**(-8) data['c'] = reduced.lattice.abc[2]*10**(-8) return data
def cif2cssr(cif, outfile = None, remove = ['Li+']): ''' Converts cif files to Zeo++ CSSR files, deletes species specified in remove. Must have pymatgen installed. Structure must be ordered and oxidation state decorated ''' filename = cif.rsplit('.',1)[0] s = mg.read_structure(cif) if remove != None: s.remove_species(remove) if outfile == None: outfile = filename + '.cssr' try: cssr = ZeoCssr(s) cssr.write_file(outfile) except: cssr = None return cssr
def corrctReflection(relax,defect): # Correct periodically reflected atoms according to the perfect cell. # relax is the CONTCAR (after relaxation) and defect is the POSCAR (before relaxation). shift = array([0,0,0]) for ele in relax.keys(): for i in range(len(relax[ele])): for j in range(3): shift[j] = shift[j] + relax[ele][i][j] - defect[ele][i][j] shift = shift/len(mg.read_structure('POSCAR_defect')) for ele in relax.keys(): for i in range(len(relax[ele])): for j in range(3): relax[ele][i][j]=relax[ele][i][j]-shift[j] if abs(relax[ele][i][j]-defect[ele][i][j])>abs(relax[ele][i][j]+defect[ele][i][j]-1): if abs(relax[ele][i][j]-defect[ele][i][j]-1)<abs(relax[ele][i][j]-defect[ele][i][j]+1): relax[ele][i][j] = relax[ele][i][j] - 1 else: relax[ele][i][j] = relax[ele][i][j] + 1 return relax
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)
def loop_structures(self, mode='i'): """ reading the structures specified in spec, add special points, and excecute the specs mode: i: loop structures for input generation o: loop structures for output parsing w: print all results """ print('loop structures mode ', mode) mp_key = os.environ['MP_KEY'] mp_list_vasp = ['mp-149', 'mp-2534', 'mp-8062', 'mp-2469', 'mp-1550', 'mp-830', 'mp-1986', 'mp-10695', 'mp-66', 'mp-1639', 'mp-1265', 'mp-1138', 'mp-23155', 'mp-111'] if self.data['source'] == 'mp-vasp': items_list = mp_list_vasp elif self.data['source'] in ['poscar', 'cif']: files = os.listdir('.') items_list = files elif self.data['source'] == 'mar_exp': items_list = [] local_serv = pymongo.Connection("marilyn.pcpm.ucl.ac.be") local_db_gaps = local_serv.band_gaps pwd = os.environ['MAR_PAS'] local_db_gaps.authenticate("setten", pwd) for c in local_db_gaps.exp.find(): name = Structure.from_dict(c['icsd_data']['structure']).composition.reduced_formula, c['icsd_id'],\ c['MP_id'] print(name) #Structure.from_dict(c['icsd_data']['structure']).to(fmt='cif',filename=name) items_list.append({'name': 'mp-' + c['MP_id'], 'icsd': c['icsd_id'], 'mp': c['MP_id']}) else: items_list = [line.strip() for line in open(self.data['source'])] for item in items_list: print('\n') # special case, this should be encaptulated if self.data['source'] == 'mar_exp': print('structure from marilyn', item['name'], item['icsd'], item['mp']) exp = local_db_gaps.exp.find({'MP_id': item['mp']})[0] structure = Structure.from_dict(exp['icsd_data']['structure']) structure = refine_structure(structure) structure.to(fmt='cif', filename=item['name']) try: kpts = local_db_gaps.GGA_BS.find({'transformations.history.0.id': item['icsd']})[0]['calculations']\ [-1]['band_structure']['kpoints'] except (IndexError, KeyError): kpts = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] structure.kpts = kpts print('kpoints:', structure.kpts[0], structure.kpts[1]) structure.item = item['name'] else: if item.startswith('POSCAR_'): structure = pmg.read_structure(item) comment = Poscar.from_file(item).comment # print comment if comment.startswith("gap"): structure.vbm_l = comment.split(" ")[1] structure.vbm = (comment.split(" ")[2], comment.split(" ")[3], comment.split(" ")[4]) structure.cbm_l = comment.split(" ")[5] structure.cbm = (comment.split(" ")[6], comment.split(" ")[7], comment.split(" ")[8]) else: # print "no bandstructure information available, adding GG as 'gap'" structure = add_gg_gap(structure) elif 'xyz' in item: structure = pmg.read_structure(item) raise NotImplementedError elif item.startswith('mp-'): with MPRester(mp_key) as mp_database: print('structure from mp database', item) structure = mp_database.get_structure_by_material_id(item, final=True) try: bandstructure = mp_database.get_bandstructure_by_material_id(item) structure.vbm_l = bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].label structure.cbm_l = bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].label structure.cbm = tuple(bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].frac_coords) structure.vbm = tuple(bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].frac_coords) except (MPRestError, IndexError, KeyError) as err: print(err.message) structure = add_gg_gap(structure) else: continue structure.kpts = [list(structure.cbm), list(structure.vbm)] structure.item = item print(item, s_name(structure)) if mode == 'i': self.excecute_flow(structure) elif mode == 'w': self.print_results(structure) elif mode == 's': self.insert_in_database(structure) elif mode == 'o': # if os.path.isdir(s_name(structure)) or os.path.isdir(s_name(structure)+'.conv'): self.process_data(structure) if 'ceci' in self.data['mode'] and mode == 'i': os.chmod("job_collection", stat.S_IRWXU)
for i in range(len(relax)): r_coords = relax[i].frac_coords 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')
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)
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 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 loop_structures(self, mode='i'): """ reading the structures specified in spec, add special points, and excecute the specs mode: i: loop structures for input generation o: loop structures for output parsing w: print all results """ print('loop structures mode ', mode) mp_key = os.environ['MP_KEY'] mp_list_vasp = ['mp-149', 'mp-2534', 'mp-8062', 'mp-2469', 'mp-1550', 'mp-830', 'mp-1986', 'mp-10695', 'mp-66', 'mp-1639', 'mp-1265', 'mp-1138', 'mp-23155', 'mp-111'] if self.data['source'] == 'mp-vasp': items_list = mp_list_vasp elif self.data['source'] == 'poscar': files = os.listdir('.') items_list = files elif self.data['source'] == 'mar_exp': items_list = [] local_serv = pymongo.Connection("marilyn.pcpm.ucl.ac.be") local_db_gaps = local_serv.band_gaps pwd = os.environ['MAR_PAS'] local_db_gaps.authenticate("setten", pwd) for c in local_db_gaps.exp.find(): print(Structure.from_dict(c['icsd_data']['structure']).composition.reduced_formula, c['icsd_id'],\ c['MP_id']) items_list.append({'name': 'mp-' + c['MP_id'], 'icsd': c['icsd_id'], 'mp': c['MP_id']}) else: items_list = [line.strip() for line in open(self.data['source'])] for item in items_list: print('\n') # special case, this should be encaptulated if self.data['source'] == 'mar_exp': print('structure from marilyn', item['name'], item['icsd'], item['mp']) exp = local_db_gaps.exp.find({'MP_id': item['mp']})[0] structure = Structure.from_dict(exp['icsd_data']['structure']) structure = refine_structure(structure) try: kpts = local_db_gaps.GGA_BS.find({'transformations.history.0.id': item['icsd']})[0]['calculations']\ [-1]['band_structure']['kpoints'] except (IndexError, KeyError): kpts = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] structure.kpts = kpts print('kpoints:', structure.kpts[0], structure.kpts[1]) structure.item = item['name'] else: if item.startswith('POSCAR_'): structure = pmg.read_structure(item) comment = Poscar.from_file(item).comment # print comment if comment.startswith("gap"): structure.vbm_l = comment.split(" ")[1] structure.vbm = (comment.split(" ")[2], comment.split(" ")[3], comment.split(" ")[4]) structure.cbm_l = comment.split(" ")[5] structure.cbm = (comment.split(" ")[6], comment.split(" ")[7], comment.split(" ")[8]) else: # print "no bandstructure information available, adding GG as 'gap'" structure = add_gg_gap(structure) elif 'xyz' in item: structure = pmg.read_structure(item) raise NotImplementedError elif item.startswith('mp-'): with MPRester(mp_key) as mp_database: print('structure from mp database', item) structure = mp_database.get_structure_by_material_id(item, final=True) try: bandstructure = mp_database.get_bandstructure_by_material_id(item) structure.vbm_l = bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].label structure.cbm_l = bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].label structure.cbm = tuple(bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].frac_coords) structure.vbm = tuple(bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].frac_coords) except (MPRestError, IndexError, KeyError) as err: print(err.message) structure = add_gg_gap(structure) else: continue structure.kpts = [list(structure.cbm), list(structure.vbm)] structure.item = item print(item, s_name(structure)) if mode == 'i': self.excecute_flow(structure) elif mode == 'w': self.print_results(structure) elif mode == 's': self.insert_in_database(structure) elif mode == 'o': # if os.path.isdir(s_name(structure)) or os.path.isdir(s_name(structure)+'.conv'): self.process_data(structure) if 'ceci' in self.data['mode'] and mode == 'i': os.chmod("job_collection", stat.S_IRWXU)
Created on September 10, 2013 @author: Qimin ''' import sys import pymatgen import math from pymatgen.symmetry.finder import SymmetryFinder file = str(sys.argv[1]) spacegroup = str(sys.argv[2]) max = float(sys.argv[3]) min = float(sys.argv[4]) iter = float(sys.argv[5]) s = pymatgen.read_structure(file) def getLowSymPrec(s,max,min,spacegroup,iter): SG = str(spacegroup) if SG!=str(SymmetryFinder(s,symprec=max).get_spacegroup_number()): print "Not reasonable spacegroup or max too large" return -1 elif SG==str(SymmetryFinder(s,symprec=min).get_spacegroup_number()): return min else: upperbound = max lowerbound = min i=0 while i<iter: trial = 10**((math.log(upperbound,10)+math.log(lowerbound,10))/2) if SG==str(SymmetryFinder(s,symprec=trial).get_spacegroup_number()):
seg = np.concatenate([pts[:-1], pts[1:]], axis=1) nseg = len(k)-1 r = [0.5*(red[i]+red[i+1]) for i in range(nseg)] g = [0.5*(green[i]+green[i+1]) for i in range(nseg)] b = [0.5*(blue[i]+blue[i+1]) for i in range(nseg)] a = np.ones(nseg, np.float)*alpha lc = LineCollection(seg, colors=zip(r,g,b,a), linewidth = 2) ax.add_collection(lc) if __name__ == "__main__": # read data # --------- # kpoints labels path = HighSymmKpath(mg.read_structure("./CONTCAR")).kpath["path"] labels = [r"$%s$" % lab for lab in path[0][0:4]] # bands bands = Vasprun("./vasprun.xml").get_band_structure("./KPOINTS", line_mode = True) # projected bands data = Procar("./PROCAR").data # density of states dosrun = Vasprun("./vasprun.xml") # set up matplotlib plot # ---------------------- # general options for plot
r_coords = relax[i].frac_coords 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())
# read args if len(sys.argv) > 1: if len(sys.argv) == 2: fstruct = sys.argv[1] else: fstruct = sys.argv[-1] if "-d" in sys.argv: try: ndiv = int(sys.argv[sys.argv.index("-d") + 1]) except ValueError, IndexError: print("-d must be followed by an integer") exit(1) # read structure if os.path.exists(fstruct): struct = mg.read_structure(fstruct) else: print("File %s does not exist" % fstruct) exit(1) # symmetry information struct_sym = SymmetryFinder(struct) print("lattice type : {0}".format(struct_sym.get_lattice_type())) print("space group : {0} ({1})".format(struct_sym.get_spacegroup_symbol(), struct_sym.get_spacegroup_number())) # Compute first brillouin zone ibz = HighSymmKpath(struct) ibz.get_kpath_plot(savefig="path.png") print("ibz type : {0}".format(ibz.name))
def loop_structures(self, mode="i"): """ reading the structures specified in spec, add special points, and excecute the specs mode: i: loop structures for input generation o: loop structures for output parsing w: print all results """ print("loop structures mode ", mode) mp_key = os.environ["MP_KEY"] mp_list_vasp = [ "mp-149", "mp-2534", "mp-8062", "mp-2469", "mp-1550", "mp-830", "mp-1986", "mp-10695", "mp-66", "mp-1639", "mp-1265", "mp-1138", "mp-23155", "mp-111", ] if self.data["source"] == "mp-vasp": items_list = mp_list_vasp elif self.data["source"] in ["poscar", "cif"]: files = os.listdir(".") items_list = files elif self.data["source"] == "mar_exp": items_list = [] local_serv = pymongo.Connection("marilyn.pcpm.ucl.ac.be") local_db_gaps = local_serv.band_gaps pwd = os.environ["MAR_PAS"] local_db_gaps.authenticate("setten", pwd) for c in local_db_gaps.exp.find(): name = ( Structure.from_dict(c["icsd_data"]["structure"]).composition.reduced_formula, c["icsd_id"], c["MP_id"], ) print(name) # Structure.from_dict(c['icsd_data']['structure']).to(fmt='cif',filename=name) items_list.append({"name": "mp-" + c["MP_id"], "icsd": c["icsd_id"], "mp": c["MP_id"]}) else: items_list = [line.strip() for line in open(self.data["source"])] for item in items_list: print("\n") # special case, this should be encaptulated if self.data["source"] == "mar_exp": print("structure from marilyn", item["name"], item["icsd"], item["mp"]) exp = local_db_gaps.exp.find({"MP_id": item["mp"]})[0] structure = Structure.from_dict(exp["icsd_data"]["structure"]) structure = refine_structure(structure) structure.to(fmt="cif", filename=item["name"]) try: kpts = local_db_gaps.GGA_BS.find({"transformations.history.0.id": item["icsd"]})[0]["calculations"][ -1 ]["band_structure"]["kpoints"] except (IndexError, KeyError): kpts = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] structure.kpts = kpts print("kpoints:", structure.kpts[0], structure.kpts[1]) structure.item = item["name"] else: if item.startswith("POSCAR_"): structure = pmg.read_structure(item) comment = Poscar.from_file(item).comment # print comment if comment.startswith("gap"): structure.vbm_l = comment.split(" ")[1] structure.vbm = (comment.split(" ")[2], comment.split(" ")[3], comment.split(" ")[4]) structure.cbm_l = comment.split(" ")[5] structure.cbm = (comment.split(" ")[6], comment.split(" ")[7], comment.split(" ")[8]) else: # print "no bandstructure information available, adding GG as 'gap'" structure = add_gg_gap(structure) elif "xyz" in item: structure = pmg.read_structure(item) raise NotImplementedError elif item.startswith("mp-"): with MPRester(mp_key) as mp_database: print("structure from mp database", item) structure = mp_database.get_structure_by_material_id(item, final=True) try: bandstructure = mp_database.get_bandstructure_by_material_id(item) structure.vbm_l = bandstructure.kpoints[bandstructure.get_vbm()["kpoint_index"][0]].label structure.cbm_l = bandstructure.kpoints[bandstructure.get_cbm()["kpoint_index"][0]].label structure.cbm = tuple( bandstructure.kpoints[bandstructure.get_cbm()["kpoint_index"][0]].frac_coords ) structure.vbm = tuple( bandstructure.kpoints[bandstructure.get_vbm()["kpoint_index"][0]].frac_coords ) except (MPRestError, IndexError, KeyError) as err: print(err.message) structure = add_gg_gap(structure) else: continue structure.kpts = [list(structure.cbm), list(structure.vbm)] structure.item = item print(item, s_name(structure)) if mode == "i": try: self.excecute_flow(structure) except Exception as exc: print("input generation failed") print(exc) elif mode == "w": try: self.print_results(structure) except: print("writing output failed") elif mode == "s": try: self.insert_in_database(structure) except: print("database insertion failed") elif mode == "o": # if os.path.isdir(s_name(structure)) or os.path.isdir(s_name(structure)+'.conv'): try: self.process_data(structure) except: print("output parsing failed") if "ceci" in self.data["mode"] and mode == "i": os.chmod("job_collection", stat.S_IRWXU)
nseg = len(k) - 1 r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)] g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)] b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)] a = np.ones(nseg, np.float) * alpha lc = LineCollection(seg, colors=zip(r, g, b, a), linewidth=2) ax.add_collection(lc) if __name__ == "__main__": # read data # --------- # kpoints labels path = HighSymmKpath(mg.read_structure("./POSCAR")).kpath["path"] labels = list() for p in path: if len(labels) != 0: labels[-1] = r"$%s,%s$" % (labels[-1].strip("$"), p[0]) else: labels.append(r"$%s$" % p[0]) for kp in p[1:]: labels.append(r"$%s$" % kp) # density of state dosrun = Vasprun("../../DOS/Cu/vasprun.xml") spd_dos = dosrun.complete_dos.get_spd_dos() # bands run = Vasprun("vasprun.xml", parse_projected_eigen=True)
import numpy as np import math import pymatgen from pymatgen.symmetry.finder import SymmetryFinder s = pymatgen.read_structure('POSCAR') # composition print "Formula:\t"+str(s.composition.formula) # spacegroup print "Spacegroup:\t"+str(SymmetryFinder(s).get_spacegroup()) # lattice constant lengths print "---------" print "a\tb\tc" print "\t".join(str(round(each,2)) for each in s.lattice.abc) # and angles print "alpha\tbeta\tgamma" print "\t".join(str(round(each,2)) for each in s.lattice.angles) print "---------" # total number of sites print "Num. of Sites: "+str(s.num_sites) print "---------" # print symmetrically distinct atoms and their wyckoff positions print "Wyckoff Postions" equiv=SymmetryFinder(s).get_symmetry_dataset()["equivalent_atoms"] wy=SymmetryFinder(s).get_symmetry_dataset()["wyckoffs"] # GROUP ATOMS BY EQUIVALENT POSITIONS #
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())