def prep_run_file(self, next_run='next_run.sh'): """ run_fileを修正してnext_run.shを作成 run_listの実行したjobをコメントアウト """ work_path, fname_exe = self.run_list[0] key = "cd $PBS_O_WORKDIR\n" # work_pathが相対pathの場合、絶対pathに修正する if work_path[0] == '/': alt = "cd {0}\n".format(os.path.join(work_path)) else: alt = "cd {0}\n".format(os.path.join(os.getcwd(), work_path)) lines = Cabinet.read_file(fname_exe) # $PBS_O_WORKDIRの記述が無い場合errorメッセージを出力 try: pos = lines.index(key) except ValueError: print("{0}に'cd $PBS_O_WORKDIR'の記述がありません".format(fname_exe)) exit() lines[pos] = alt Cabinet.write_file(next_run, lines) finished = self.run_list.pop(0) finished[0] = '#' + finished[0] self.finished_list.append(finished) tmp_list = self.finished_list + self.run_list all_list = [" ".join(x) + "\n" for x in tmp_list] Cabinet.write_file(self.list_run_file, all_list)
def write_potcar(self, path, fname='POTCAR'): """ Make a combined single POTCAR file """ fname = os.path.join(path, fname) out_lines = [x for y in self.potentials_lines for x in y] Cabinet.write_file(fname, out_lines)
def __init__(self, poscar='POSCAR'): if type(poscar) is str: try: poscar_lines = Cabinet.read_file(poscar) except IOError: print("error: vaspy.Poscar could not " "find '{0}' file !!!".format(poscar)) exit() elif type(poscar) is list: poscar_lines = poscar elif poscar is None: print("POSCAR was not read !!! (Template POSCAR is loaded !!!)") poscar = os.path.join(MODULE_DIR, '../sorce/originalsVASP', 'poscar') poscar_lines = Cabinet.read_file(poscar) self.poscar_title = poscar_lines[0] self.cell_scale = float(poscar_lines[1]) self.cell_lattices = Cabinet.conv_lines2array(poscar_lines[2:5]) # self.cell_latticesはarrayとして読み込む if poscar_lines[5].split()[0].isdigit(): # vasp4 self.elements = None self.num_atoms = [int(x) for x in poscar_lines[5].split()] i = sum(self.num_atoms) sites = [[float(x) for x in y.split()[0:3]] for y in poscar_lines[7:7+i]] self.cell_sites = np.array(sites) self.vasp_version = 4 else: self.elements = poscar_lines[5].split() # vasp5 self.num_atoms = [int(x) for x in poscar_lines[6].split()] i = sum(self.num_atoms) sites = [[float(x) for x in y.split()[0:3]] for y in poscar_lines[8:8+i]] self.cell_sites = np.array(sites) self.vasp_version = 5
def write_poscar(self, poscar='POSCAR'): """ write_poscar(path) Make a 'POSCAR' file at 'path' """ Cabinet.reserve_file(poscar) Cabinet.write_file(poscar, str(self))
def make_list(keys, run_file='run.sh'): """ current directory中のkeyで引っ掛かるpathを list_run.txtに書き出す """ path_list = [] for key in keys: path_list += glob.glob(key) path_list = sorted(set(path_list)) Cabinet.make_list_run(path_list, run_file)
def run_job_and_get_id(self, fname_exe='next_run.sh'): """ jobを走らせる 走らせるファイルはnext_run.sh """ cmd = ['qsub', fname_exe] job_id = Popen(cmd, stdout=PIPE).communicate()[0] add_line = job_id.split('.')[0] + b'\n' self.running_jobs.append(add_line) Cabinet.write_file(self.running_jobs_file, self.running_jobs)
def write_kpoints(self, fname='KPOINTS', mode='M'): """Write KPOINTS file using self.kpoints""" if mode == 'M': mline = "Monkhorst Pack" elif mode == 'G': mline = "Gamma" kp_lines = ("Automatic mesh\n0\n{0}\n" " {1[0]} {1[1]} {1[2]}\n 0. 0. 0.\n" .format(mline, self.kpoints)) Cabinet.write_file(fname, kp_lines)
def make_list_run(self, run_file): """ next.py用のlist_run.txtを作成 """ lines = "" for param in self.series: path = param['path'] run_file = os.path.abspath(run_file) lines += "{0} {1}\n".format(path, run_file) Cabinet.write_file('list_run', lines)
def append_list_run(self, run_file): """ next.py用のlist_run.txtを追加 """ lines = "" for param in self.series: path = os.path.abspath(param['path']) run_file = os.path.abspath(run_file) lines += "{0} {1}\n".format(path, run_file) Cabinet.append_file('list_run', lines)
def std(src='POSCAR'): """ conventional standard cell に変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std_str = finder.get_conventional_standard_structure() dstpos = Poscar(std_str) dst = 'POSCAR_std' Cabinet.reserve_file(dst) dstpos.write_file(dst)
def prim(src): """ primitive cell に変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) prim_str = finder.get_primitive_standard_structure() dstpos = Poscar(prim_str) dst = 'POSCAR_prim' Cabinet.reserve_file(dst) dstpos.write_file(dst)
def standard(src="POSCAR"): """ standardに変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std = finder.get_conventional_standard_structure() dstpos = Poscar(std) dst = "POSCAR_std" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def refined(src="POSCAR"): """ refined poscar を 作成する """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8) std = finder.get_refined_structure() dstpos = Poscar(std) dst = "POSCAR_refined" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def primitive(src="POSCAR"): """ primitiveに変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) prim = finder.get_primitive_standard_structure() dstpos = Poscar(prim) dst = "POSCAR_prim" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def make_list(keys, is_file=False, run_file="run.sh"): """ current directory中のkeyで引っ掛かるpathを list_run.txtに書き出す """ path_list = [] for key in keys: path_list += glob.glob(key) path_list = sorted(set(path_list)) if is_file: path_list = [os.path.dirname(x) for x in path_list] Cabinet.make_list_run(path_list, run_file)
def plt_double(self, combipara, in_dir1, in_dir2, out_dir): """2種の結果のlattice依存性をプロット""" combi = Combinatorial(*combipara) combi.set_formula(2, 1) for composition in combi.compositions: formula = composition['formula'] formula = ''.join(formula.split('2')) total_elem = ['Fe'] + composition['elements'] total_num_atoms = [1] + composition['num_atoms'] print(formula) all_dir_list = glob.glob(os.path.join(in_dir1, formula, 'fixed_*')) regular = collect_vasp.Energy(all_dir_list, 'POSCAR', 'OSZICAR') regular['c/a'] /= 2 ** 0.5 fixed_elem = [total_elem[1], total_elem[0], total_elem[2]] fixed_elem = np.array([fixed_elem] * len(regular['elements'])) regular['elements'] = fixed_elem regular.set_enthalpy() regular.set_mae('OSZICAR_SOC001', 'OSZICAR_SOC100') all_dir_list = glob.glob(os.path.join(in_dir2, formula, 'fixed_*')) inverse = collect_vasp.Energy(all_dir_list, 'POSCAR', 'OSZICAR') inverse['c/a'] /= 2 ** 0.5 inverse['elements'] = fixed_elem inverse.set_enthalpy() inverse.set_mae('OSZICAR_SOC001', 'OSZICAR_SOC100') rlines = [str(regular)] ilines = [str(inverse)] fname_reg = "Fe2{0[0]}{0[1]}_reg.txt".format(composition['elements']) fname_inv = "Fe2{0[0]}{0[1]}_inv.txt".format(composition['elements']) Cabinet.write_file(os.path.join(out_dir, 'text', fname_reg), rlines) Cabinet.write_file(os.path.join(out_dir, 'text', fname_inv), ilines) def plot(): plt = grapy.Vertical(3) plt.set_title("Heusler Fe$_2${0[0]}{0[1]}" .format(composition['elements'])) plt.set_style('blue') plt.set123(regular, 'c/a', 'enthalpy', 'mag', 'mae') plt.set_style('magenta') plt.set123(inverse, 'c/a', 'enthalpy', 'mag', 'mae') plt.adjust_auto() plt.ax2.set_ylim(-0.5, 3) plt.plot('show') #fname = "Fe2{0[0]}{0[1]}.eps".format(composition['elements']) #plt.plot(os.path.join(out_dir, fname)) plot()
def for_FeB_witoutB(): #pylint: disable=C0103 """ for_FeBのBのサイトを0にして計算 """ fname = os.path.join('.', 'extended_convex_hull_POSCARS') poscars = uspex.POSCARS(fname) poscars.restrict_fractions(0, 0.5) poscars.restrict_fractions(1, 0.0) poscars.remove_elements(1) poscars.expand_poscars(['Fe']) path_list = [x['ID'] for x in poscars.poscars] Cabinet.make_list_run(path_list, 'run.sh')
def for_FeB(): #pylint: disable=C0103 """ FeBのUSPEXの計算結果(POSCARS)を展開する Feが50-100percentの範囲 """ fname = os.path.join('.', 'extended_convex_hull_POSCARS') poscars = uspex.POSCARS(fname) poscars.restrict_fractions(0, 0.5) poscars.restrict_fractions(1, 0.0) poscars.expand_poscars(['Fe', 'B']) path_list = [x['ID'] for x in poscars.poscars] Cabinet.make_list_run(path_list, 'run.sh')
def __fix_dict(incar_dict): """ 読み込んだincar_dictをintやfloat形式に修正 """ for key, value in incar_dict.items(): if len(value) > 1: fixed_val = [Cabinet.conv_str(x) for x in value] else: fixed_val = Cabinet.conv_str(value[0]) if fixed_val == '.TRUE.': fixed_val = True elif fixed_val == '.FALSE.': fixed_val = False incar_dict.update({key: fixed_val})
def __init__(self, num_run=1, fname_run='list_run', fname_running='running_jobs'): self.num_run = num_run self.list_run_file = fname_run self.running_jobs_file = fname_running lines = Cabinet.read_file(fname_run) self.finished_list = [x.split() for x in lines if x[0] == '#'] self.run_list = [x.split() for x in lines if x[0] != '#'] try: lines = Cabinet.read_file(fname_running) self.running_jobs = [x for x in lines if x != '\n'] except IOError: self.running_jobs = []
def get_enemag(oszicar='OSZICAR'): """ Read energy and magnetic momentum from OSZICAR/OUTCAR. Judge file type from first line of the read file. """ try: lines = Cabinet.read_file(oszicar) except IOError: lines = ['error'] try: head = lines[0].split()[0] except IndexError: print(oszicar) exit() if head == 'N': # OSZICAR output = vaspy.Oszicar(oszicar) elif head[0:4] == 'vasp': # OUTCAR output = vaspy.Outcar(oszicar) else: print("I cannot read {0}".format(oszicar)) return None, None, False if not output.results: print(oszicar) return None, None, False energy = output.results[-1]['energy'] mag = output.results[-1]['mag'] return energy, mag, True
def get_results(cls, fname='OSZICAR'): """ iterationの回数、nswの数、energy、magをdict形式でreturn 緩和毎にlistに追加する """ lines = Cabinet.read_file(fname) keywords = r"\s*([\d]+)\s+F=\s*([\d\-\.E\+]+)\s+E0=\s+.*\s+" meta = re.compile(keywords) keywords2 = r"\s*DAV:\s*([\d]+)\s+.*" meta2 = re.compile(keywords2) results = [] for i in range(0, len(lines)): if meta.match(lines[i]): relax_num, energy, mag = cls.get_3values(lines[i]) j = 1 while not meta2.match(lines[i-j]): j += 1 iter_num = lines[i-j].split()[1] results.append({'iter_num': iter_num, 'nsw_num': relax_num, 'energy': energy, 'mag': mag}) if not results: last_val = lines[-1].split() try: if math.fabs(float(last_val[3])) > 1e-5: print("{0} is unfinished with error. ".format(fname)) return [] except ValueError: print("{0} is unfinished with error. ".format(fname)) return [] print("{0} is unfinished but converged. " "(val. of mag is false)".format(fname)) results.append({'iter_num': int(last_val[1]), 'nsw_num': 1, 'energy': float(last_val[2]), 'mag': -100}) return results
def read_origin_file(fname): """ self.individualsの作成に用いる (__init__()で実行) Originから読み取ったすべてのindividualの情報を dict形式でreturnする どの様に進化したか 'background' 世代 'generation' 親 'parents' 子供 'children'(空)を要素に持つ またmake_family_tree()で使う'blood'(空)を定義 """ individuals = {} lines = Cabinet.read_file(fname) for line in lines: if line.split()[0] == '-' * 7: gene = int(line.split()[1].split('generation')[-1]) else: line = line.split(None, 1) id_indiv = int(line[0]) line = line[1].split(',') background = line[0].split('\n')[0] if background == 'random': parents = None else: line = line[1].split() parents = [int(x) for x in line[2:]] individuals.update({id_indiv: {'background': background, 'parents': parents, 'generation': gene, 'blood': None, 'children': []}}) return individuals
def read_outcar(self, fname='OUTCAR_ibzkp'): """ Read NGX, NGY, NGZ, NBANDS parameters from OUTCAR. """ lines = Cabinet.read_file(fname) ngx_key = re.compile(r".*WARNING:.*NGX\s*to\s*(\d+)*") ngy_key = re.compile(r".*WARNING:.*NGY\s*to\s*(\d+)*") ngz_key = re.compile(r".*WARNING:.*NGZ\s*to\s*(\d+)*") nbands_key = re.compile(r".*NBANDS\s*=\s*(\d+)*") ngx_value = None ngy_value = None ngz_value = None for i in range(0, len(lines)): ngx_meta = ngx_key.match(lines[i]) ngy_meta = ngy_key.match(lines[i]) ngz_meta = ngz_key.match(lines[i]) nbands_meta = nbands_key.match(lines[i]) if ngx_meta: ngx_value = int(ngx_meta.group(1)) elif ngy_meta: ngy_value = int(ngy_meta.group(1)) elif ngz_meta: ngz_value = int(ngz_meta.group(1)) elif nbands_meta: nbands_value = int(nbands_meta.group(1)) nbands_value += nbands_value % 2 # alt to even return {'ngx': ngx_value, 'ngy': ngy_value, 'ngz': ngz_value, 'nbands': nbands_value}
def read_potcar(self): """ Several POTCAR files lines are loaded based on self.psuedo_pot list. """ path_list = [os.path.join(self.VASP_POT_DIR, x, 'POTCAR') for x in self.psuedo_pot] potentials_lines = [Cabinet.read_file(x) for x in path_list] return potentials_lines
def __init__(self, dos): DataBox.__init__(self, []) self.dos_lines = Cabinet.read_file(dos) self.num_atoms = self.get_num_atoms(self.dos_lines[0]) (self.num_energy, self.fermi_energy) = self.get_parameters(self.dos_lines[5]) print(self.get_parameters(self.dos_lines[5])) self.dos_data = self.__prep_dos_data(self.num_atoms, self.labels_orbital)
def change_conc(): """ concを変更する """ list1 = [str(i*0.1) for i in range(0, 11)] list2 = ['001', '100'] list3 = ['0.950', '1.000', '1.050', '1.100', '1.150', '1.200', '1.250', '1.300', '1.350', '1.400', '1.450', '1.500'] combi = Combinatorial(list1, list2, list3) # print(combi.compositions) comp_list = [x['elements'] for x in combi.compositions] lines = "" for comp in comp_list: lines += "/".join(comp) + " run.sh\n" print(lines) Cabinet.write_file('list_run.txt', lines)
def prep_one(cls, cif_file, dst_dir): """ The dst_dir is current directory, this method search POSCAR and reserve it. If not, it will search whethre dst_dir already exist or not. If it already exist, this module will do nothing. If not, new directory make and prepare POSCAR file. """ if dst_dir == '.': Cabinet.reserve_file('POSCAR') elif glob.glob(dst_dir): line = ("\'{0}\' directory is already exist.\n" "Do Nothing...\n".format(dst_dir.split('/')[-1])) print(line) return else: Bash.mkdir(dst_dir) cls.conv2poscar(cif_file, dst_dir) shutil.copy(cif_file, dst_dir)
def is_running(self): """ jobが動作中かどうかcheckする 終了していた場合、running_jobsから削除 """ cmd = ['qstat'] jobs = Popen(cmd, stdout=PIPE).communicate()[0].split(b'\n') uname = getpass.getuser() still_run = [] for job_id in self.running_jobs: key = r"{0}.*{1}.*".format(job_id[:-1], uname) meta = re.compile(key) judge = True for job in jobs: if meta.match(job): judge = None if not judge: still_run.append(job_id) self.running_jobs = still_run Cabinet.write_file(self.running_jobs_file, self.running_jobs)
def get_elements(path): """ 元素名を修得 """ lines = Cabinet.read_file(path) key = r"\s*There are 3 types of atoms in the system:\s+([\w\s]+)" meta = re.compile(key) for line in lines: if meta.match(line): elements = meta.match(line).group(1) return elements.split()