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 __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 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 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 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 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_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_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 get_results(self, fname='OUTCAR'): """ energy, magの値を修得 """ lines = Cabinet.read_file(fname) energy = self.get_energy(lines) mag = self.get_mag(lines) elements = self.get_elements(lines) results = {'energy': energy, 'mag': mag, 'elements': elements} return results
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()
def get_data_single(fname): """ 一つのoutputファイルからデータ修得 変数が多いので分割することも要検討 """ lines = Cabinet.read_file(fname) key_energy = r"\s*total energy=\s*([-\d\.]*)\s*" meta_energy = re.compile(key_energy) key_atoms = (r"\s*ntyp=\s*([\d]+)\s+natm=\s*([\d]+)\s+" r"ncmpx=\s*([\d]+)\s*") meta_atoms = re.compile(key_atoms) key_latt = (r"\s*brvtyp=\s*([^\s]+)\s+a=\s*([\d\.]+)\s+" r"c/a=\s*([\d\.]+)\s+b/a=\s*([\d\.]+)\s*") meta_latt = re.compile(key_latt) for line in lines: if meta_latt.match(line): latt_a = meta_latt.match(line).group(2) if meta_atoms.match(line): ntype = int(meta_atoms.match(line).group(1)) num_atoms = int(meta_atoms.match(line).group(2)) if meta_energy.match(line): energy = float(meta_energy.match(line).group(1)) pos_compo = lines.index(" type of site\n") key_type = r"\s*type=([^\s]+)\s+.*" meta_type = re.compile(key_type) key_conc = (r"\s*component=\s*([\d]+)\s+anclr=\s*([\d\.]+)\s+" r"conc=\s*([\d\.]+)\s*") meta_conc = re.compile(key_conc) i = 1 site_id = 0 compo = [] while lines[pos_compo+i] != "\n": if meta_type.match(lines[pos_compo+i]): site_id += 1 type_name = meta_type.match(lines[pos_compo+i]).group(1) compo.append({'site_id': site_id, 'type_name': type_name, 'compositions':[]}) if meta_conc.match(lines[pos_compo+i]): component = meta_conc.match(lines[pos_compo+i]).group(1) anclr = float(meta_conc.match(lines[pos_compo+i]).group(2)) conc = meta_conc.match(lines[pos_compo+i]).group(3) compo[-1]['compositions'].append({'Z': int(anclr), 'component': int(component), 'concentration': float(conc)}) i += 1 try: return {'energy': energy/num_atoms, 'num_atoms': num_atoms, 'latt_a': latt_a, 'compo': compo} except UnboundLocalError: print('error {0}'.format(fname)) return None
def get_composition(fname='./POTCAR'): """ POTCARから元素を読む PAW_PBEから始まる行に元素名が記載されているのでそこを読む 空行は例外処理でpassする """ lines = Cabinet.read_file(fname) elements = [] for line in lines: try: if line.split()[0] == 'PAW_PBE': elements.append(line.split()[1].split('_')[0]) except IndexError: pass return elements
def read_float(fname): """ ファイルをfloatデータとして読み込み float化できない文字がある行はスキップ """ stock = [] rows = Cabinet.read_file(fname) for row in rows: row = row.split() try: row = [float(x) for x in row] # 全てをfloat化 stock.append(row) except ValueError: pass return stock
def from_file(cls, fname): """ Read a Incar file, and make a incar_dict. """ lines = Cabinet.read_file(fname) incar_dict = {} for line in lines: if line[0] not in ('#', '\n'): para_list = line.split('#')[0].split('!')[0] # ^ remove comment_out ^ para_list = para_list.split() key = para_list[0].lower() value_list = para_list[2:] incar_dict.update({key: value_list}) cls.__fix_dict(incar_dict) return incar_dict
def fix(modname, fname): """ modnameはパッケジされている場合に必要 """ lines = Cabinet.read_file(fname) key = r"\s*from\s+(.*)\s+import\s+\*" meta = re.compile(key) star_list = [meta.match(x).group(1) for x in lines if meta.match(x)] for module in star_list: exec('import {0}{1}'.format(modname, module)) try: a = eval('{0}{1}.__all__'.format(modname, module)) except AttributeError: b = eval('dir({0}{1})'.format(modname, module)) a = [x for x in b if x[0] != '_'] print('from {0} import {1}'.format(module, ', '.join(a))) print()
def get_ene_mag(oszicar='OSZICAR'): """ Read energy and magnetic momentum from OSZICAR/OUTCAR. """ try: lines = Cabinet.read_file(oszicar) except IOError: lines = '' if lines[0].split()[0] == 'N': # OSZICAR output = vaspy.Oszicar(oszicar) elif lines[0].split()[0][0:4] == 'vasp': # OUTCAR output = vaspy.Outcar(oszicar) else: print("I cannot read {0}".format(oszicar)) return None, None energy = output.results[-1]['energy'] mag = output.results[-1]['mag'] return energy, mag
def test_readfrom_lines(self): """ read from lines format""" posc_lines = Cabinet.read_file(os.path.join(self.path, "POSCAR")) poscar = vaspy.Poscar(posc_lines) print(poscar.poscar_title)
def test_outcar(self): """for outcar obj""" outcar = vaspy.Outcar(os.path.join(self.path, "OUTCAR")) o_lines = Cabinet.read_file(os.path.join(self.path, "OUTCAR")) print(outcar.get_mag(o_lines))
def __init__(self, fname): output_lines = Cabinet.read_file(fname) self.data = self.get_data(output_lines)
def __init__(self, path): self.path = os.path.dirname(path) self.bgp_lines = Cabinet.read_file(path) poscar_lines = self.split_structure() self.poscars = [{'ID': x['ID'], 'object': vaspy.Poscar(x['lines'])} for x in poscar_lines]