def __init__(self, structure, is_selective=False): self.is_selective = is_selective for i in range(structure.num_sites): try: structure.replace(i, structure.species[i].element) except: structure.replace(i, structure.species[i]) self.poscar = structure if self.is_selective: for i in range(self.poscar.num_sites): try: self.poscar.replace(i, self.poscar.species[i].element, properties=None) except: self.poscar.replace(i, self.poscar.species[i], properties=None) full_formula = GMDStructure(self.poscar).formula(reduced=False) try: symmetry, groupnumber = self.poscar.get_space_group_info() except: groupnumber = 0 self.naming = "{0}_{1:03d}".format(full_formula, groupnumber)
def tiltingmolecule(self, s, ms, inputatom, changenum, fixcalc=None): s_matrix = s.lattice.matrix s_species = s.species ms_species = ms.species s_coord = np.dot(s.frac_coords, s_matrix).tolist() ms_coord = np.dot(ms.frac_coords, ms.lattice.matrix) name = GMDStructure(s).formula(reduced=False) # pick the index of inputatom and shuffle s_index = np.array([e for e,c in enumerate(s_species) if c.symbol == Element(inputatom).symbol]) if self.random_coord : np.random.shuffle(s_index) self.coord = s_index[:round(changenum*len(s_index))] else : for r in self.coord : if not r in s_index : print("%i isn't %s index\nPlease revise the index number\n" % (r, inputatom)) sys.exit(0) r_coord = [s_coord[f] for f in self.coord] # make array of degree if self.random_degree : self.degree = np.random.randint(360, size=(len(r_coord),3)) new_ = self.degree else : if not self.random_coord : self.degree = np.array(self.degree) new_ = self.degree else: new_ = [[self.degree[0], self.degree[1], self.degree[2]] for i in range(len(r_coord))] # add coordination lthe=[];lph=[];lps=[];original_coord=[] for coord, degree in zip(r_coord,new_): index = s_coord.index(coord) original_coord.append(coord) del s_coord[index] del s_species[index] the, ph, ps = degree[0], degree[1], degree[2] lthe.append(degree[0]) lph.append(degree[1]) lps.append(degree[2]) R = rotation(the, ph, ps) dot = np.dot(ms_coord, R) s_coord.extend(np.add(dot, coord).tolist()) s_species.extend(ms_species) # csv df = pd.DataFrame({'index':self.coord,"coords":original_coord,'Theta':lthe,'Phi':lph,'Psi':lps}) df = df.set_index('index') # add the properties of selective_dynamics if fixcalc != None : sp = _selective_bool(species=s_species, type_num=fixcalc) new_s = Structure(s_matrix, s_species, s_coord, coords_are_cartesian=True,site_properties={"selective_dynamics":sp}) else : new_s = Structure(s_matrix, s_species, s_coord, coords_are_cartesian=True) new_s.sort() return new_s, df
def analysis(args): if args.graph: dic = graphyaml(args.graph) with open('graph.yaml', 'w') as fi: yaml.dump(dic, fi, default_flow_style=False) print("%s generate the graph.yaml file" % (os.getcwd())) elif args.input: shell, numberlist = ShellPath().check() while True: number = int(input("Please enter the number >> ")) if number in numberlist: break mn = str(input("Please enter the mode ex) RCDB >> ")) with open("input.gmd", 'w') as fi: fi.write("### Perovgen input.gmd\n") fi.write("KPOINTS:\nA\nCONSTK=30\n\n") fi.write("INCAR:\nMPJ\n\n") fi.write("SHELL:\n%s\n\n" % (shell[number - 1][-1])) fi.write("CALMODE:\n%s\n" % (mn)) fi.close() elif args.pdos: path = pdospath() s = load_structure(os.getcwd())[0][0] if not s: print("Structure file doesn't exist!\n") sys.exit(1) # Total DOS print("Total DOS") os.system("%s dos width=0.03" % (path)) # partial DOS dic = defaultdict(list) print("pDOS") for e, i in enumerate(s.species): dic[i.symbol].append(e + 1) for k, v in dic.items(): for s in ['tot', 's', 'p']: with open("LIST", 'w') as fi: fi.write("{}_{}\n".format(k, s)) for i in v: if s == "tot": fi.write("%i tot tot\n" % (i)) elif s == "s": fi.write("%i s tot\n" % (i)) elif s == "p": fi.write("%i px tot\n" % (i)) fi.write("%i py tot\n" % (i)) fi.write("%i pz tot\n" % (i)) os.system("{} pdos width=0.03".format(path)) elif args.convert: files = load_structure(args.convert)[0] for e, f in enumerate(files): GMDStructure(f).convert_to_cif()
def database(args): if args.inputcif: files = [f for f in os.listdir(".") if "cif" in f] for s in files: struc = Structure.from_file(s) for i in range(struc.num_sites): try: struc.replace(i, struc.species[i].element) except: struc.replace(i, struc.species[i]) is1 = GMDStructure(struc).savefile()
def molecule(args): if args.ma: mafa = "MA" elif args.fa: mafa = "FA" elif args.gua: mafa = "GUA" elif args.dima: mafa = "diMA" elif args.trima: mafa = "triMA" elif args.tetrama: mafa = "tetraMA" elif args.zolium: mafa = "Zolium" ms = RandomMolecule._loadmolecule(mafa) inputatom, changenum, fixcalc, multiple = InputInform( random_coord=args.position, random_degree=args.degree).molecule_input() mole = RandomMolecule(random_coord=args.position, random_degree=args.degree) # Input strucpath = [] structure = load_structure(args.path)[0] e = 0 for s in structure: for i in range(multiple): molestruc, csv = mole.tiltingmolecule(s, ms, inputatom=inputatom, changenum=changenum, fixcalc=fixcalc) vaspname = GMDStructure(molestruc).formula(reduced=False) if not os.path.exists(vaspname): os.makedirs(vaspname) molestruc.to(filename="{0}/POSCAR_{1}_{2:04d}".format( vaspname, vaspname, e + 1)) strucpath.append("{0}/POSCAR_{1}_{2:04d}".format( vaspname, vaspname, e + 1)) if args.csv: if not os.path.exists("{}/CSV".format(vaspname)): os.makedirs("{}/CSV".format(vaspname)) csv.to_csv("{0}/CSV/{1}_{2:04d}.csv".format( vaspname, vaspname, e + 1)) e += 1 return strucpath
def element(args): r_atom = RandomAtom(random_coord=args.position, random_degree=args.degree) atom1, atom2, change, multiple = InputInform( random_coord=args.position, random_degree=args.degree).atom_input() #Input strucpath = [] structure = load_structure(args.path)[0] e = 0 for s in structure: for i in range(multiple): s1, s = r_atom.substitution(structure=s, atom1=atom1, atom2=atom2, ratio=change) vaspname = GMDStructure(s1).formula(reduced=False) if not os.path.exists(vaspname): os.makedirs(vaspname) s1.to(filename="{0}/POSCAR_{1}_{2:04d}".format( vaspname, vaspname, e + 1)) strucpath.append("{0}/POSCAR_{1}_{2:04d}".format( vaspname, vaspname, e + 1)) e += 1 return strucpath
def Process(calpath, inputspath, strucpath, ds=False, soc=False): inputs = inputgmd(inputspath) struc, filename = load_structure(strucpath)[0][0], load_structure( strucpath)[1][0] fn = os.path.basename(filename).split(".")[0] chgpath = None bandpath = None logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) file_handler = logging.FileHandler('{}/{}.log'.format(calpath, fn)) file_handler.setFormatter(formatter) logger.addHandler(file_handler) if "B" in inputs.calmode or "D" in inputs.calmode or "E" in inputs.calmode: if not "C" in inputs.calmode: for d in os.listdir(calpath): if os.path.isdir("{}/{}".format(calpath, d)): mode = d.split("_")[0] fn1 = '_'.join(d.split("_")[2:]) if mode == 'C' and fn == fn1: chgpath = "{}/{}/CHGCAR".format(calpath, d) if chgpath == None: logger.info("C moode doens't exist") sys.exit(1) if "E" in inputs.calmode: if not "B" in inputs.calmode: for d in os.listdir(calpath): if os.path.isdir("{}/{}".format(calpath, d)): mode = d.split("_")[0] fn1 = '_'.join(d.split("_")[2:]) if mode == 'B' and fn == fn1: bandpath = "{}/{}".format(calpath, d) if bandpath == None: logger.info("B moode doens't exist") sys.exit(1) for mt in inputs.calmode: os.chdir(calpath) runfolder = [] if mt == 'E': nelect1 = Eigenval("{}/EIGENVAL".format(bandpath)).nelect if soc: nelect = (int(nelect1), int(nelect1) + 1) else: nelect = (int(nelect1 / 2), int(nelect1 / 2) + 1) bsp = BSPlotting( vasprun=os.path.abspath("{}/vasprun.xml".format(bandpath)), kpoints=os.path.abspath("{}/KPOINTS".format(bandpath))) try: vbm = bsp.bs.kpoints[bsp.bsdict['vbm']['kpoint_index'] [0]].as_dict()['fcoords'] except: vbm = [0.000, 0.000, 0.000] try: cbm = bsp.bs.kpoints[bsp.bsdict['cbm']['kpoint_index'] [0]].as_dict()['fcoords'] except: cbm = [0.000, 0.000, 0.000] kpoints = (vbm, cbm) p = PerovInputs(structure=struc, is_selective=ds) # Revised INPUT FILES vi = p.inputfolder(inputs=inputs, method=mt, soc=soc) inputs = inputgmd(inputspath) try: symmetry, groupnumber = struc.get_space_group_info() except: groupnumber = 0 # Designate the folder name full_formula = GMDStructure(struc).formula(reduced=False) pretty_formula = GMDStructure(struc).formula() if "{}_{}_{}".format(mt, full_formula, fn) in os.listdir(calpath): logging.info("{}_{}_{} is already exists!".format( mt, full_formula, fn)) sys.exit(1) folder_name = "{0}/{1}_{2}_{3}".format(calpath, mt, full_formula, fn) vi.write_input(output_dir=folder_name) runfolder.append(folder_name) if mt == "E": folder_name_H = "{0}/H_{1}_{2}".format(calpath, full_formula, fn) vi.write_input(output_dir=folder_name_H) runfolder.append(folder_name_H) # Copy the other files to generated folder if mt == "D" or mt == "B": copyfile(chgpath, "{}/CHGCAR".format(folder_name)) elif mt == "E": copyfile(chgpath, "{}/CHGCAR".format(folder_name)) copyfile(chgpath, "{}/CHGCAR".format(folder_name_H)) MakingInpcar(struc, "{}/INPCAR".format(folder_name), nelect[1], kpoints[1]) MakingInpcar(struc, "{}/INPCAR".format(folder_name_H), nelect[0], kpoints[0]) logging.info("INPCAR is generated in {} mode ".format(mt)) for runf in runfolder: if mt == 'E': emc = GMDAnalysis() emc.effectivemass(path="{}".format(runf), secondstep=False) logging.info("KPOINTS is fixed in {} mode ".format(mt)) naming = os.path.basename(runf) rs = RunningShell(shell=inputs.shell, name=naming, path=runf) rs.running_mode(soc=soc, run=True) logging.info("{} mode calculation is being started".format(mt)) # Running Check while True: time.sleep(10) path1 = [] for j in runfolder: os.chdir(os.path.join(calpath, j)) try: vrun = Vasprun("%s/vasprun.xml" % (os.path.join(calpath, j)), parse_potcar_file=True) ionicsteps = vrun.nionic_steps nsw = vrun.incar['NSW'] if nsw == 1: path1.append("%s/CONTCAR" % (os.path.join(calpath, j))) elif nsw == ionicsteps: print( "[Notice] Realculation because ionic step is same NSW value" ) logging.info( "{} mode calculation is recalulated (ionic step is over)" .format(mt)) Recalculate() time.sleep(10) else: path1.append("%s/CONTCAR" % (os.path.join(calpath, j))) except ET.ParseError: # Error Check in R-mode if mt == "R": boolen, targetlist = fileopen("OUTCAR", "accuracy") if not boolen: try: number = subprocess.check_output( ['tail', '-n', '1', 'OSZICAR']).decode('utf-8') number1 = number.split()[0] time.sleep(180) number2 = subprocess.check_output( ['tail', '-n', '1', 'OSZICAR']).decode('utf-8') number3 = number2.split()[0] if int(number1) == int(number3): print( "[Notice] Reculation because it has not yet obtained a stabilizing structure." ) logging.info( "{} mode calculation is recalculated (unstbilized tructure)" .format(mt)) Recalculate() time.sleep(10) else: pass except: pass else: path1.append("%s/CONTCAR" % (os.path.join(calpath, j))) else: pass except FileNotFoundError: pass except AttributeError: pass if len(runfolder) == len(path1): os.chdir(calpath) logger.info("{} mode is calculated".format(mt)) break # Properties for DOS and effective mass if mt == "C": chgpath = CopyCHGCAR(path1[0]) elif mt == 'B': bandpath = os.path.split(path1[0])[0] bsp = BSPlotting( vasprun=os.path.abspath("{}/vasprun.xml".format(bandpath)), kpoints=os.path.abspath("{}/KPOINTS".format(bandpath))) #bsp.get_plot().savefig("{}/{}.pdf".format(calpath,fn)) #bsp.get_plot().savefig("{}/{}.png".format(calpath,fn)) bsp.printinform(path=calpath) elif mt == "D" or mt == "E": for i in runfolder: i = os.path.abspath(i) analysis_path = GMDAnalysis() if mt == "D": os.chdir(i) os.system("%s dos width=0.03" % (analysis_path.pdos)) analysis_path.partialDOS(structure=struc) logger.info("D mode folder is generated pdos files") elif mt == 'E': analysis_path.effectivemass(path=i, secondstep=True) em_e = open("{}/EM".format(i), 'r').readlines()[-12:] E = GMDExcitonbinding.harm_mean_em(em_e) logger.info("E mode folder is generated EM files") del runfolder[-1] os.chdir(calpath) # CONTCOAR TO POSCAR print("%s mode finished time : " % (mt), end=" ") print(time.strftime("%c\n", time.localtime(time.time())))
def AutoMolOpt(strucpath, inputs): pwd = os.getcwd() for isif in ["ISIF7", "ISIF2", "ISIF3"]: runfolder = [] struclist2 = [] for path in strucpath: #os.chdir(path) if isif == "ISIF7": struclist = load_structure(path)[0] elif isif == "ISIF2": path1 = [ "{}/ISIF7/{}/CONTCAR".format(path, f) for f in os.listdir("{}/ISIF7".format(path)) if "M_mode" in f ] struclist = load_structure(path1)[0] elif isif == "ISIF3": path1 = [ "{}/ISIF2/{}/CONTCAR".format(path, f) for f in os.listdir("{}/ISIF2".format(path)) if "M_mode" in f ] struclist = load_structure(path1)[0] makepath = "{}/{}".format(path, isif) os.makedirs(makepath) nf = 0 for e, s in enumerate(struclist): nf += 1 g = GMDStructure(s) v = g.vaspname() # revised poscar if isif == "ISIF2": sp = _selective_bool(species=g.species, type_num=4) new_s = Structure( s.lattice.matrix, g.species, g.coords, coords_are_cartesian=True, site_properties={"selective_dynamics": sp}) p = PerovInputs(structure=new_s) else: p = PerovInputs(structure=s, is_selective=True) # Control incar incar = GMDIncar(inputs).incar modeincar = PerovInputs._incarmode(incar=incar, method="M") if isif == "ISIF2": modeincar["ISIF"] = 2 elif isif == "ISIF7": modeincar["ISIF"] = 7 modeincar["NSW"] = 21 del modeincar["EDIFFG"] elif isif == "ISIF3": modeincar["ISIF"] = 3 modeincar["EDIFF"] = 1E-6 modeincar["EDIFFG"] = -0.01 modeincar["ENCUT"] = 520 # Writing the folder if isif == "ISIF7" or isif == "ISIF2": vi = p.inputfolder(incar=modeincar, number=20) else: if inputs["INCAR"][0] != "MPJ": vi = p.inputfolder(incar=incar, number=40) else: vi = p.inputfolder(incar=incar, number=None) folder_name = "%s_%i_M_mode" % (v, nf) vi.write_input( output_dir="{}/{}".format(makepath, folder_name)) runfolder.append("{}/{}".format(makepath, folder_name)) for runf in runfolder: rs = RunningShell(shell=inputs["SHELL"][0], name=os.path.split(runf)[-1], path=runf) rs.running_mode(soc=False, run=True) # Running Check while True: time.sleep(10) path1 = [] for j in runfolder: os.chdir(j) try: vrun = Vasprun("%s/vasprun.xml" % (os.path.join(pwd, j)), parse_potcar_file=True) ionicsteps = vrun.nionic_steps nsw = vrun.incar['NSW'] if nsw == ionicsteps: #print("Realculation") Recalculate() time.sleep(10) else: path1.append("%s/CONTCAR" % (os.path.join(pwd, j))) except: pass if len(runfolder) == len(path1): os.chdir(pwd) break print("###################################") print("\n%s finished time : " % (isif), end="") print(time.strftime("%c\n", time.localtime(time.time()))) print("###################################") for path in strucpath: path1 = [ "{}/ISIF3/{}/vasprun.xml".format(path, f) for f in os.listdir("{}/ISIF3".format(path)) if "M_mode" in f ] energy = [ Vasprun(p1, parse_potcar_file=True).final_energy for p1 in path1 ] index = energy.index(min(energy)) direct = os.path.dirname(path1[index]) os.system("mv {} {}/MINIMUM".format(direct, os.path.dirname(direct)))
def analyze_calculation(args): pwd = os.getcwd() if args.inputpath: inputs = inputgmd(args.inputpath) else: print( "\nUserError : gmd3 auto [path of input.gmd] [path of structure] [optional]\n" ) sys.exit(1) if not args.strucpath: print( "\nUserError : gmd3 auto [path of input.gmd] [path of structure] [optional]\n" ) sys.exit(1) else: if not load_structure(args.strucpath): print("\n[Warning] the structure file does not exist.\n") sys.exit(1) else: strucpath = load_structure(args.strucpath) openingphrase(inputs, strucpath[-1]) if args.directory: for struc, filename in zip(strucpath[0], strucpath[-1]): fn = os.path.basename(filename).split(".")[0] for mt in inputs.calmode: runfolder = [] p = PerovInputs(structure=struc, is_selective=args.deleteselect) try: symmetry, groupnumber = struc.get_space_group_info() except: groupnumber = 0 # Revised INPUT FILES vi = p.inputfolder(inputs=inputs, method=mt, soc=args.soc) inputs = inputgmd(args.inputpath) # Writing the Input directory full_formula = GMDStructure(struc).formula(reduced=False) pretty_formula = GMDStructure(struc).formula() root_dir = "{0}/{1}_{2:03d}".format(pwd, pretty_formula, groupnumber) folder_name = "{0}/{1}_{2}_{3}".format(root_dir, mt, full_formula, fn) vi.write_input(output_dir=folder_name) runfolder.append(folder_name) if mt == "E": folder_name_H = "{0}/H_{1}_{2}".format( root_dir, full_formula, fn) vi.write_input(output_dir=folder_name_H) runfolder.append(folder_name_H) for runf in runfolder: naming = os.path.basename(runf) rs = RunningShell(shell=inputs.shell, name=naming, path=runf) rs.running_mode(soc=args.soc, run=False) else: for struc, filename in zip(strucpath[0], strucpath[-1]): fn = os.path.basename(filename).split(".")[0] # directory f = open("{}/calnohup.py".format(os.path.dirname(__file__)), "r") ff = f.readlines() ff.insert( 0, "inputpath='{}'\n".format(os.path.abspath(args.inputpath))) ff.insert(1, "strucpath='{}'\n".format(filename)) if args.deleteselect: ff.insert(2, "ds=True\n") else: ff.insert(2, "ds=False\n") if args.soc: ff.insert(3, "orbit=True\n") else: ff.insert(3, "orbit=False\n") ff.insert(4, "mole=False\n") ff.insert(5, "\n") # directory name try: symmetry, groupnumber = struc.get_space_group_info() except: groupnumber = 0 pretty_formula = GMDStructure(struc).formula() root_dir = "{0}/{1}_{2:03d}".format(pwd, pretty_formula, groupnumber) os.makedirs(root_dir, exist_ok=True) with open("{}/run_{}.py".format(root_dir, fn), "w") as fi: for i in ff: fi.write(i) fi.close() #os.system("python {}/run_{}.py".format(root_dir,fn)) os.system("nohup python -u {}/run_{}.py > {}/gmd_{}.out &".format( root_dir, fn, root_dir, fn))