コード例 #1
0
ファイル: general_io.py プロジェクト: SamKChang/qctoolkit
 def inUnit(self, unit):
   unitStr = self.unit + '-' + unit
   if not unitStr.lower() == 'eh-eh':
     self.Et, self.unit = qtk.convE(self.Et, unitStr)
     if hasattr(self, 'energies'):
       for key in self.energies.keys():
         self.energies[key], _ = qtk.convE(self.energies[key], unitStr)
   return self
コード例 #2
0
ファイル: general_io.py プロジェクト: andersx/qctoolkit
 def inUnit(self, unit):
     unitStr = self.unit + '-' + unit
     if not unitStr.lower() == 'eh-eh':
         self.Et, self.unit = qtk.convE(self.Et, unitStr)
         if hasattr(self, 'energies'):
             for key in self.energies.keys():
                 self.energies[key], _ = qtk.convE(self.energies[key],
                                                   unitStr)
     return self
コード例 #3
0
ファイル: general_io.py プロジェクト: andersx/qctoolkit
 def __sub__(self, other):
     out = copy.deepcopy(self)
     if isinstance(other, qtk.QM.general_io.GenericQMOutput):
         if self.unit == other.unit:
             out.Et = self.Et - other.Et
         else:
             unitStr = self.unit + '-' + other.unit
             out.Et = self.Et + qtk.convE(other.Et, unitStr, '-')
         out.scf_step = max(self.scf_step, other.scf_step)
     elif (type(other) is int) or (type(other) is float):
         out.Et = self.Et - other
     else:
         out.Et = np.nan
     return out
コード例 #4
0
ファイル: general_io.py プロジェクト: SamKChang/qctoolkit
 def __sub__(self, other):
   out = copy.deepcopy(self)
   if isinstance(other, qtk.QM.general_io.GenericQMOutput):
     if self.unit == other.unit:
       out.Et = self.Et - other.Et
     else:
       unitStr = self.unit + '-' + other.unit
       out.Et = self.Et + qtk.convE(other.Et, unitStr, '-')
     out.scp_step = max(self.scf_step, other.scf_step)
   elif (type(other) is int) or (type(other) is float):
     out.Et = self.Et - other
   else:
     out.Et = np.nan
   return out
コード例 #5
0
ファイル: abinit.py プロジェクト: andersx/qctoolkit
    def unfold(self,
               k_path,
               folds,
               epsilon=1E-5,
               WFK=None,
               overwrite=False,
               shift=None,
               **kwargs):

        path = self.path
        cwd = os.getcwd()
        os.chdir(path)

        f2b_list = sorted(glob.glob('*.f2b'))
        if not f2b_list or overwrite:

            if not WFK:
                WFK_card = '%s/*_WFK' % path
                WFK_list = sorted(glob.glob(WFK_card))
                if len(WFK_list) > 0:
                    WFK = WFK_list[-1]
                else:
                    qtk.exit('wavefunction file not found.')

            exe = qtk.setting.abinit_f2b_exe
            log_name = '%s_f2b.log' % self.name
            log = open(log_name, 'w')
            fold_str = [str(f) for f in folds]
            cmd_str = "%s %s %s" % (exe, WFK, ':'.join(fold_str))
            run = sp.Popen(cmd_str, shell=True, stdout=log)
            run.wait()
            log.close()
            f2b_list = sorted(glob.glob('*.f2b'))

        f2b = f2b_list[0]

        k_path = np.asarray(k_path)

        def dp2l_vec(X0_list, p0, p1):
            eps = epsilon
            denom = p1 - p0
            denomabs = np.linalg.norm(denom)
            if denomabs < eps:
                return False
            numer = np.cross(X0_list - p0[np.newaxis, :],
                             X0_list - p1[np.newaxis, :])
            return np.linalg.norm(numer, axis=1) / denomabs

        _data = read_csv(f2b,
                         delim_whitespace=True,
                         dtype='float64',
                         header=None).values

        os.chdir(cwd)
        KEIG = _data[:, :3]
        EIG = np.array(_data[:, 3]) * qtk.convE(1, 'Ha-ev')[0]
        if not hasattr(self, 'fermi_index'):
            self.fermi_index = self.molecule.getValenceElectrons() / 2 - 1

        if not shift:
            EIG = EIG - np.max(self.band[:, self.fermi_index])
        else:
            EIG = EIG - shift
        EIG = EIG.tolist()
        W = _data[:, 4]

        L = []
        ENE = []
        WGHT = []
        G = self.G_lattice.copy()

        for i in range(3):
            G[i, :] = G[i, :] * folds[i]

        k_path = k_path.dot(G)
        KEIG = KEIG.dot(G)

        itr_test = 0
        dl = 0
        for ikp in range(len(k_path) - 1):
            itr = 0
            p0 = k_path[ikp, :]
            p1 = k_path[ikp + 1, :]
            B = p0 - p1
            dk = np.linalg.norm(B)
            dist_vec = dp2l_vec(KEIG, p0, p1)
            ind1 = (dist_vec < epsilon)
            A_vec = (p0[np.newaxis, :] - KEIG)[ind1]
            x_vec = A_vec.dot(B.T) / dk
            ind2 = (x_vec > 0) * ((x_vec - dk) < epsilon)
            L.extend((x_vec[ind2] + dl).tolist())
            ENE.extend(np.asarray(EIG)[ind1][ind2].tolist())
            WGHT.extend(np.asarray(W)[ind1][ind2].tolist())
            dl = dl + dk
        L = np.array(L, dtype='float64')
        ENE = np.array(ENE, dtype='float64')
        WGHT = np.array(WGHT, dtype='float64')

        return L, ENE, WGHT
コード例 #6
0
ファイル: abinit.py プロジェクト: andersx/qctoolkit
    def __init__(self, qmout, **kwargs):
        PlanewaveOutput.__init__(self, qmout, **kwargs)
        out_file = open(qmout)
        data = out_file.readlines()
        out_file.close()

        EStrList = filter(lambda x: 'Etotal' in x, data)
        EList = filter(lambda x: 'ETOT' in x, data)
        self.scf_step = len(EList)
        if self.scf_step > 0:
            Et_list = [float(filter(None, s.split(' '))[2]) for s in EList]
            self.Et = Et_list[-1]
        elif len(EStrList) > 0:
            EStr = EStrList[-1]
            self.Et = float(EStr.split(' ')[-1])

        if len(EStrList) > 0:
            EStr = EStrList[-1]
            detailInd = data.index(EStr)
            self.detail = data[detailInd - 7:detailInd]

        GStr = filter(lambda x: 'G(1)' in x, data)[-1]
        ind_g = len(data) - data[::-1].index(GStr) - 1
        G_lattice = []
        for i in range(3):
            G_lattice.append(
                np.fromstring(data[ind_g + i].split('=')[-1], sep=' '))
        self.G_lattice = np.array(G_lattice)

        xangst = filter(lambda x: 'xangst' in x, data)[-1]
        angst_n = len(data) - data[::-1].index(xangst) - 1
        xcart = filter(lambda x: 'xcart' in x, data)[-1]
        cart_n = len(data) - data[::-1].index(xcart) - 1
        Rstr = copy.deepcopy(data[angst_n:cart_n])
        Rstr[0] = Rstr[0].replace('xangst', '')
        R = [[float(r) for r in filter(None, s.split(' '))] for s in Rstr]
        N = len(R)
        ZstrOriginal = filter(lambda x: ' typat' in x, data)[-1]
        Zstr = ZstrOriginal.replace('typat', '')
        Zind = [int(z) for z in filter(None, Zstr.split(' '))]
        ZindItr = data.index(ZstrOriginal)
        while len(Zind) != N:
            ZindItr += 1
            ZindNewStr = filter(None, data[ZindItr].split(' '))
            ZindNew = [int(z) for z in ZindNewStr]
            Zind.extend(ZindNew)
        NZnuc = filter(lambda x: 'ntypat' in x, data)[-1]
        NZnuc = int(filter(None, NZnuc.split(' '))[-1])
        Znuc = filter(lambda x: 'znucl ' in x, data)[-1]
        line_znuc = len(data) - data[::-1].index(Znuc)
        Znuc = filter(None, Znuc.replace('znucl', '').split(' '))
        Znuc = [float(z) for z in Znuc]
        while len(Znuc) < NZnuc:
            Znuc_new = filter(None, data[line_znuc].split(' '))
            Znuc_new = [float(z) for z in Znuc_new]
            Znuc.extend(Znuc_new)
            line_znuc = line_znuc + 1

        build = []
        for i in range(N):
            Z = [Znuc[Zind[i] - 1]]
            Z.extend(R[i])
            build.append(Z)
        self.molecule = qtk.Molecule()
        self.molecule.build(build)

        if self.scf_step > 0:
            fStr = filter(lambda x: 'tesian forces (hartree/b' in x, data)[-1]
            fInd = data.index(fStr)
            fData = data[fInd + 1:fInd + 1 + N]
            force = []
            for f in fData:
                fStr = filter(None, f.split(' '))[1:]
                force.append([float(fs) for fs in fStr])
            self.force = np.array(force)

        self.occupation = []
        try:
            r1p = re.compile(r'^[ a-z]{17} +[ 0-9.E+-]+$')
            r2p = re.compile(r'^ +[a-z]+ +.*$')
            report = filter(r2p.match, filter(r1p.match, data))
            occ_ptn_lst = filter(lambda x: ' occ ' in x, report)
            if len(occ_ptn_lst) > 0:
                occ_pattern = occ_ptn_lst[-1]
                occ_pattern_ind = len(report) - report[::-1].index(occ_pattern)
                occ_pattern_end = report[occ_pattern_ind]
                occ_ind_start = len(data) - data[::-1].index(occ_pattern) - 1
                occ_ind_end = len(data) - data[::-1].index(occ_pattern_end) - 1
                for i in range(occ_ind_start, occ_ind_end):
                    for occ in filter(None, data[i].split(' ')):
                        try:
                            self.occupation.append(float(occ))
                        except Exception as err:
                            pass
        except Exception as err:
            qtk.warning("error when extracting occupation number with" +\
              " error message: %s" % str(err))

        cell_pattern = re.compile(r'^ R.*=.* G.*=.*$')
        cell_list = filter(cell_pattern.match, data)
        cell = []
        for cstr in cell_list:
            cell.append([float(c) for c in filter(None, cstr.split(' '))[1:4]])
        self.lattice = np.array(cell) / 1.889726124993
        self.celldm = qtk.lattice2celldm(self.lattice)
        self.molecule.R_scale = qtk.xyz2fractional(self.molecule.R,
                                                   self.celldm)

        eigStr = os.path.join(os.path.split(qmout)[0], '*_EIG')
        eigFileList = sorted(glob.glob(eigStr))
        if len(eigFileList) != 0:
            if 'eig_index' in kwargs:
                eig_i = kwargs['eig_index']
            else:
                eig_i = -1
            if len(eigFileList) > 1:
                qtk.warning(
                  "more than one o_EIG files found " + \
                  "loading last file with name: %s" % eigFileList[eig_i]
                )
            eigFile = open(eigFileList[eig_i])
            eigData = eigFile.readlines()
            eigFile.close()
            unitStr = filter(lambda x: 'Eigenvalues' in x, eigData)[0]
            unitStr = unitStr.replace('(', '').replace(')', '')
            unit = filter(None, unitStr.split(' '))[1]
            spinList = filter(lambda x: 'SPIN' in x, eigData)
            if len(spinList) != 0:
                spinFactor = 2
                maxInd = eigData.index(spinList[-1])
            else:
                spinFactor = 1
                maxInd = len(eigData)
            ind = []
            for kStr in filter(lambda x: 'kpt#' in x, eigData):
                ind.append(eigData.index(kStr))
            band = []
            kpoints = []
            if spinFactor == 1:
                for i in range(len(ind)):
                    wcoord = eigData[ind[i]].split('wtk=')[-1].split(', kpt=')
                    weight = float(wcoord[0])
                    cStr = filter(None, wcoord[1].split('(')[0].split(' '))
                    coord = [float(c) for c in cStr]
                    coord.append(weight)
                    kpoints.append(coord)
                    s = ind[i] + 1
                    if i < len(ind) - 1:
                        e = ind[i + 1]
                    else:
                        e = len(eigData)
                    eig_i = filter(None, ''.join(eigData[s:e]).split(' '))
                    band.append([
                        qtk.convE(float(ew), '%s-eV' % unit)[0] for ew in eig_i
                    ])

                self.band = np.array(band)
                self.kpoints = np.array(kpoints)
                self.mo_eigenvalues = np.array(band[0]).copy()
                if len(self.occupation) > 0:
                    diff = np.diff(self.occupation)
                    ind = np.array(range(len(diff)))
                    pos = diff[np.where(abs(diff) > 0.5)]
                    mask = np.in1d(diff, pos)
                    if len(ind[mask]) > 0:
                        N_state = ind[mask][0]

                else:
                    qtk.warning("occupation number not available... " + \
                      "try to use molecule object with closed shell assumption"
                    )
                    N_state = self.molecule.getValenceElectrons() / 2 - 1

                vb = max(self.band[:, N_state])
                cb = min(self.band[:, N_state + 1])
                vb_pos = np.argmax(self.band[:, N_state])
                cb_pos = np.argmin(self.band[:, N_state + 1])
                self.Eg = cb - vb
                if vb_pos == cb_pos:
                    self.Eg_direct = True
                else:
                    self.Eg_direct = False
                self.fermi_index = N_state

            else:
                qtk.warning("spin polarized band data " +\
                            "extraction is not yet implemented")
        else:
            qtk.warning('no k-point information (o_EIG file) found')
コード例 #7
0
ファイル: espresso.py プロジェクト: SamKChang/qctoolkit
  def __init__(self, qmout, **kwargs):
    PlanewaveOutput.__init__(self, qmout, **kwargs)
    out_file = open(qmout)
    data = out_file.readlines()
    out_file.close()
    Et_pattern = re.compile("^.*total energy *=.*$")
    f_pattern = re.compile("^.*atom.*type.*force.*=.*$")
    Et_list = filter(Et_pattern.match, data)
    f_list = filter(f_pattern.match, data)
    if len(Et_list) > 0:
      Et_str = filter(Et_pattern.match, data)[-1]
      Et = float(Et_str.split()[-2])
      self.Et, self.unit = qtk.convE(Et, 'Ry-Eh')
      out_folder = os.path.split(os.path.abspath(qmout))[0]
      save = glob.glob(os.path.join(out_folder, '*.save'))

      # extract force information
      if len(f_list) > 0:
        fstr = [filter(None, fstr.split('=')[-1].split(' ')) 
                for fstr in f_list]
        # atomic unit force, HF/au, converted from Ry/au
        self.force = 0.5 * np.array(
          [[float(comp) for comp in atm] for atm in fstr]
        )

      # extract band structure from xml files
      if save:
        save = save[0]
        try:
          data_xml = os.path.join(save, 'data-file.xml')
          xml_file = open(data_xml)
          tree = ET.parse(xml_file)
          xml_file.close()
          self.xml = tree.getroot()
          kpoints = []
          band = []

          # extract celldm
          celldm = []
          cellVec = []
          for i in range(1, 4):
            cellvStr = filter(None, 
              self.xml[2][4][i].text.replace('\n', '').split(' ')
            )
            cellVec.append([float(v) for v in cellvStr])
          self.celldm = qtk.cellVec2celldm(cellVec)
    
          # extract structure
          R = []
          N = int(self.xml[3][0].text.replace('\n', ''))
          Nsp = int(self.xml[3][1].text.replace('\n', ''))
          for i in range(N):
            RiStr = self.xml[3][5+Nsp+i].get('tau')
            Ri = [float(r) * 0.529177249 for r in RiStr.split(' ')]
            ni = self.xml[3][5+Nsp+i].get('SPECIES')
            Z = [qtk.n2Z(ni)]
            Z.extend(Ri)
            R.append(Z)
          self.molecule = qtk.Molecule()
          self.molecule.build(R)

          # access data for each kpoint
          for k in self.xml[-2]:
            k_str = k[0].text
            coord = [float(c) for c in k_str.split()]
            weight = float(k[1].text.split()[0])
            coord.append(weight)
            kpoints.append(coord)
            ev_file = os.path.join(save, k[2].attrib['iotk_link'])
            k_xml_file = open(ev_file)
            k_xml = ET.parse(k_xml_file)
            k_xml_file.close()
            ev_k = k_xml.getroot()
            ev_str = ev_k[2].text.split()
            ev = [qtk.convE(float(entry), 'Eh-eV')[0]\
                  for entry in ev_str]
            band.append(ev)
            occ_str = ev_k[3].text.split()
            occ = [float(entry) for entry in occ_str]
          self.kpoints = np.array(kpoints)
          self.mo_eigenvalues = copy.deepcopy(band[0])
          self.band = np.array(band)
          self.occupation = occ
          diff = np.diff(occ)
          pos = diff[np.where(abs(diff) > 0.5)]
          mask = np.in1d(diff, pos)
          ind = np.array(range(len(diff)))
          if len(ind[mask]) > 0:
            N_state = ind[mask][0]
            vb = max(self.band[:, N_state])
            cb = min(self.band[:, N_state + 1])
            vb_pos = np.argmax(self.band[:, N_state])
            cb_pos = np.argmin(self.band[:, N_state + 1])
            self.Eg = cb - vb
            if vb_pos == cb_pos:
              self.Eg_direct = True
            else:
              self.Eg_direct = False

          cell = []
          for i in range(1, 4):
            vec = filter(
              None, 
              self.xml[2][4][i].text.replace('\n', '').split(' '))
            cell.append([float(v) for v in vec])
          self.lattice = np.array(cell) / 1.889726124993
          self.celldm = qtk.lattice2celldm(self.lattice)
          self.molecule.R_scale = qtk.xyz2fractional(
            self.molecule.R, self.celldm)
            
        except IOError:
          qtk.warning('xml file of job %s not found' % qmout)
    else:
      qtk.warning('job %s not finished' % qmout)
コード例 #8
0
ファイル: espresso.py プロジェクト: andersx/qctoolkit
    def __init__(self, qmout, **kwargs):
        PlanewaveOutput.__init__(self, qmout, **kwargs)
        out_file = open(qmout)
        data = out_file.readlines()
        out_file.close()
        Et_pattern = re.compile("^.*total energy *=.*$")
        f_pattern = re.compile("^.*atom.*type.*force.*=.*$")
        Et_list = filter(Et_pattern.match, data)
        f_list = filter(f_pattern.match, data)
        if len(Et_list) > 0:
            Et_str = filter(Et_pattern.match, data)[-1]
            Et = float(Et_str.split()[-2])
            self.Et, self.unit = qtk.convE(Et, 'Ry-Eh')
            out_folder = os.path.split(os.path.abspath(qmout))[0]
            save = glob.glob(os.path.join(out_folder, '*.save'))

            # extract force information
            if len(f_list) > 0:
                fstr = [
                    filter(None,
                           fstr.split('=')[-1].split(' ')) for fstr in f_list
                ]
                # atomic unit force, HF/au, converted from Ry/au
                self.force = 0.5 * np.array([[float(comp) for comp in atm]
                                             for atm in fstr])

            # extract band structure from xml files
            if save:
                save = save[0]
                try:
                    data_xml = os.path.join(save, 'data-file.xml')
                    xml_file = open(data_xml)
                    tree = ET.parse(xml_file)
                    xml_file.close()
                    self.xml = tree.getroot()
                    kpoints = []
                    band = []

                    # extract celldm
                    celldm = []
                    cellVec = []
                    for i in range(1, 4):
                        cellvStr = filter(
                            None,
                            self.xml[2][4][i].text.replace('\n',
                                                           '').split(' '))
                        cellVec.append([float(v) for v in cellvStr])
                    self.celldm = qtk.cellVec2celldm(cellVec)

                    # extract structure
                    R = []
                    N = int(self.xml[3][0].text.replace('\n', ''))
                    Nsp = int(self.xml[3][1].text.replace('\n', ''))
                    for i in range(N):
                        RiStr = self.xml[3][5 + Nsp + i].get('tau')
                        Ri = [float(r) * 0.529177249 for r in RiStr.split(' ')]
                        ni = self.xml[3][5 + Nsp + i].get('SPECIES')
                        Z = [qtk.n2Z(ni)]
                        Z.extend(Ri)
                        R.append(Z)
                    self.molecule = qtk.Molecule()
                    self.molecule.build(R)

                    # access data for each kpoint
                    for k in self.xml[-2]:
                        k_str = k[0].text
                        coord = [float(c) for c in k_str.split()]
                        weight = float(k[1].text.split()[0])
                        coord.append(weight)
                        kpoints.append(coord)
                        ev_file = os.path.join(save, k[2].attrib['iotk_link'])
                        k_xml_file = open(ev_file)
                        k_xml = ET.parse(k_xml_file)
                        k_xml_file.close()
                        ev_k = k_xml.getroot()
                        ev_str = ev_k[2].text.split()
                        ev = [qtk.convE(float(entry), 'Eh-eV')[0]\
                              for entry in ev_str]
                        band.append(ev)
                        occ_str = ev_k[3].text.split()
                        occ = [float(entry) for entry in occ_str]
                    self.kpoints = np.array(kpoints)
                    self.mo_eigenvalues = copy.deepcopy(band[0])
                    self.band = np.array(band)
                    self.occupation = occ
                    diff = np.diff(occ)
                    pos = diff[np.where(abs(diff) > 0.5)]
                    mask = np.in1d(diff, pos)
                    ind = np.array(range(len(diff)))
                    if len(ind[mask]) > 0:
                        N_state = ind[mask][0]
                        vb = max(self.band[:, N_state])
                        cb = min(self.band[:, N_state + 1])
                        vb_pos = np.argmax(self.band[:, N_state])
                        cb_pos = np.argmin(self.band[:, N_state + 1])
                        self.Eg = cb - vb
                        if vb_pos == cb_pos:
                            self.Eg_direct = True
                        else:
                            self.Eg_direct = False

                    cell = []
                    for i in range(1, 4):
                        vec = filter(
                            None,
                            self.xml[2][4][i].text.replace('\n',
                                                           '').split(' '))
                        cell.append([float(v) for v in vec])
                    self.lattice = np.array(cell) / 1.889726124993
                    self.celldm = qtk.lattice2celldm(self.lattice)
                    self.molecule.R_scale = qtk.xyz2fractional(
                        self.molecule.R, self.celldm)

                except IOError:
                    qtk.warning('xml file of job %s not found' % qmout)
        else:
            qtk.warning('job %s not finished' % qmout)
コード例 #9
0
ファイル: abinit.py プロジェクト: SamKChang/qctoolkit
  def __init__(self, qmout, **kwargs):
    PlanewaveOutput.__init__(self, qmout, **kwargs)
    out_file = open(qmout)
    data = out_file.readlines()
    out_file.close()

    EStrList = filter(lambda x: 'Etotal' in x, data)
    EList = filter(lambda x: 'ETOT' in x, data)
    self.scf_step = len(EList)
    if self.scf_step > 0:
      Et_list = [float(filter(None, s.split(' '))[2]) for s in EList]
      self.Et = Et_list[-1]
    elif len(EStrList) > 0:
      EStr = EStrList[-1]
      self.Et = float(EStr.split(' ')[-1])

    if len(EStrList) > 0:
      EStr = EStrList[-1]
      detailInd = data.index(EStr)
      self.detail = data[detailInd-7:detailInd]
  
    xangst = filter(lambda x: 'xangst' in x, data)[-1]
    angst_n = len(data) - data[::-1].index(xangst) - 1
    xcart = filter(lambda x: 'xcart' in x, data)[-1]
    cart_n = len(data) - data[::-1].index(xcart) - 1
    Rstr = copy.deepcopy(data[angst_n:cart_n])
    Rstr[0] = Rstr[0].replace('xangst', '')
    R = [[float(r) for r in filter(None, s.split(' '))] for s in Rstr]
    N = len(R)
    ZstrOriginal = filter(lambda x: ' typat' in x, data)[-1]
    Zstr = ZstrOriginal.replace('typat', '')
    Zind = [int(z) for z in filter(None, Zstr.split(' '))]
    ZindItr = data.index(ZstrOriginal)
    while len(Zind) != N:
      ZindItr += 1
      ZindNewStr = filter(None, data[ZindItr].split(' '))
      ZindNew = [int(z) for z in ZindNewStr]
      Zind.extend(ZindNew)
    Znuc = filter(lambda x: 'znucl ' in x, data)[-1]
    Znuc = filter(None, Znuc.replace('znucl', '').split(' '))
    Znuc = [float(z) for z in Znuc]
    build = []
    for i in range(N):
      Z = [Znuc[Zind[i]-1]]
      Z.extend(R[i])
      build.append(Z)
    self.molecule = qtk.Molecule()
    self.molecule.build(build)

    if self.scf_step > 0:
      fStr = filter(lambda x: 'tesian forces (hartree/b' in x, data)[-1]
      fInd = data.index(fStr)
      fData = data[fInd+1:fInd+1+N]
      force = []
      for f in fData:
        fStr = filter(None, f.split(' '))[1:]
        force.append([float(fs) for fs in fStr])
      self.force = np.array(force)

    self.occupation = []
    try:
      r1p = re.compile(r'^[ a-z]{17} +[ 0-9.E+-]+$')
      r2p = re.compile(r'^ +[a-z]+ +.*$')
      report = filter(r2p.match, filter(r1p.match, data))
      occ_pattern = filter(lambda x: ' occ ' in x, report)[-1]
      occ_pattern_ind = len(report) - report[::-1].index(occ_pattern)
      occ_pattern_end = report[occ_pattern_ind]
      occ_ind_start = len(data) - data[::-1].index(occ_pattern) - 1
      occ_ind_end = len(data) - data[::-1].index(occ_pattern_end) - 1
      for i in range(occ_ind_start, occ_ind_end):
        for occ in filter(None, data[i].split(' ')):
          try:
            self.occupation.append(float(occ))
          except:
            pass
    except Exception as err:
      qtk.warning("error when extracting occupation number with" +\
        " error message: %s" % str(err))

    cell_pattern = re.compile(r'^ R.*=.* G.*=.*$')
    cell_list = filter(cell_pattern.match, data)
    cell = []
    for cstr in cell_list:
      cell.append(
        [float(c) for c in filter(None, cstr.split(' '))[1:4]])
    self.lattice = np.array(cell) / 1.889726124993
    self.celldm = qtk.lattice2celldm(self.lattice)
    self.molecule.R_scale = qtk.xyz2fractional(
      self.molecule.R, self.celldm)

    eigStr = os.path.join(os.path.split(qmout)[0], '*_EIG')
    eigFileList = glob.glob(eigStr)
    if len(eigFileList) != 0:
      if len(eigFileList) > 1:
        qtk.warning("more than one o_EIG files found")
      eigFile = open(eigFileList[0])
      eigData = eigFile.readlines()
      eigFile.close()
      spinList = filter(lambda x: 'SPIN' in x, eigData)
      if len(spinList) != 0:
        spinFactor = 2
        maxInd = eigData.index(spinList[-1])
      else:
        spinFactor = 1
        maxInd = len(eigData)
      ind = []
      for kStr in filter(lambda x: 'kpt#' in x, eigData):
        ind.append(eigData.index(kStr))
      band = []
      kpoints = []
      if spinFactor == 1:
        for i in range(len(ind)):
          wcoord = eigData[ind[i]].split('wtk=')[-1].split(', kpt=')
          weight = float(wcoord[0])
          cStr = filter(None, wcoord[1].split('(')[0].split(' '))
          coord = [float(c) for c in cStr]
          coord.append(weight)
          kpoints.append(coord)
          s = ind[i] + 1
          if i < len(ind) - 1:
            e = ind[i+1]
          else:
            e = len(eigData)
          eig_i = filter(None, ''.join(eigData[s:e]).split(' '))
          band.append([qtk.convE(float(ew), 'Eh-eV')[0]
                       for ew in eig_i])
  
        self.band = np.array(band)
        self.kpoints = np.array(kpoints)
        self.mo_eigenvalues = np.array(band[0]).copy()
        if len(self.occupation) > 0:
          diff = np.diff(self.occupation)
          ind = np.array(range(len(diff)))
          pos = diff[np.where(abs(diff) > 0.5)]
          mask = np.in1d(diff, pos)
          if len(ind[mask]) > 0:
            N_state = ind[mask][0]
            vb = max(self.band[:, N_state])
            cb = min(self.band[:, N_state + 1])
            vb_pos = np.argmax(self.band[:, N_state])
            cb_pos = np.argmin(self.band[:, N_state + 1])
            self.Eg = cb - vb
            if vb_pos == cb_pos:
              self.Eg_direct = True
            else:
              self.Eg_direct = False
  
      else:
        qtk.warning("spin polarized band data " +\
                    "extraction is not yet implemented")
    else:
      qtk.warning('no k-point information (o_EIG file) found')
コード例 #10
0
ファイル: vasp.py プロジェクト: andersx/qctoolkit
    def __init__(self, qmoutXML, **kwargs):
        PlanewaveOutput.__init__(self, qmoutXML, **kwargs)
        if qmoutXML:
            #xml_file = open(qmoutXML)
            tree = ET.parse(qmoutXML)
            #xml_file.close()
            self.xml = tree.getroot()
            self.Et, self.unit = qtk.convE(float(self.xml[-2][-5][1].text),
                                           'eV-Eh', '-')
            self.info = self.xml[0][1].text
            self.SCFStep = len(self.xml[-2]) - 9

            try:
                # kpoints and band structure data
                kpoints = []
                band = []
                occ = []

                ktag = self.xml[2]
                if ktag.tag != 'kpoints':
                    qtk.exit("vasp xml structure for kpoints unexpected")
                if ktag[0].tag == 'generation':
                    k_ind = 1
                elif ktag[0].tag == 'varray':
                    k_ind = 0
                else:
                    qtk.exit("vasp xml for kpointss has unexpected tag: %s" %
                             ktag[0].tag)
                for i in range(len(ktag[k_ind])):
                    k_str = ktag[k_ind][i].text
                    weight = float(ktag[k_ind + 1][i].text)
                    band_k = []
                    occ_k = []
                    bk_xml = self.xml[-2][-3][0][5][0][i]
                    for b_xml in bk_xml:
                        b, o = [float(c) for c in b_xml.text.split()]
                        band_k.append(b)
                        occ_k.append(o)
                    coord = [float(c) for c in k_str.split()]
                    coord.append(weight)
                    kpoints.append(coord)
                    band.append(band_k)
                    occ.append(occ_k)
                self.mo_eigenvalues = copy.deepcopy(band[0])
                self.kpoints = np.array(kpoints)
                self.band = np.array(band)
                self.occupation = occ[0]

                diff = np.diff(occ[0])
                pos = diff[np.where(abs(diff) > 0.5)]
                mask = np.in1d(diff, pos)
                ind = np.array(range(len(diff)))
                if len(ind[mask]) > 0:
                    N_state = ind[mask][0]
                    vb = max(self.band[:, N_state])
                    cb = min(self.band[:, N_state + 1])
                    vb_pos = np.argmax(self.band[:, N_state])
                    cb_pos = np.argmin(self.band[:, N_state + 1])
                    self.Eg = cb - vb
                    if vb_pos == cb_pos:
                        self.Eg_direct = True
                    else:
                        self.Eg_direct = False

                ind = np.arange(len(self.kpoints))[self.kpoints[:, -1] == 0]
                if len(ind > 0):
                    ind_w = np.arange(len(
                        self.kpoints))[self.kpoints[:, -1] != 0]
                    self.band_weighted = self.band[ind_w]
                    self.kpoints_weighted = self.kpoints[ind_w]
                    self.band = self.band[ind]
                    self.kpoints = self.kpoints[ind]

                # DOS data
                dos = []
                self.E_fermi = float(self.xml[-2][-1][0].text)
                for dos_xml in self.xml[-2][-1][1][0][5][0]:
                    dos_lst = filter(None, dos_xml.text.split(' '))
                    dos_E = [float(d) for d in dos_lst]
                    dos.append(dos_E)
                self.dos = np.array(dos)

            except Exception as err:
                qtk.warning("error when accessing kpoint data for %s with err: %s"\
                            % (self.name, err))
コード例 #11
0
ファイル: vasp.py プロジェクト: SamKChang/qctoolkit
  def __init__(self, qmoutXML, **kwargs):
    PlanewaveOutput.__init__(self, qmoutXML, **kwargs)
    if qmoutXML:
      #xml_file = open(qmoutXML)
      tree = ET.parse(qmoutXML)
      #xml_file.close()
      self.xml = tree.getroot()
      self.Et, self.unit = qtk.convE(float(self.xml[-2][-5][1].text),
                                     'eV-Eh', '-')
      self.info = self.xml[0][1].text
      self.SCFStep = len(self.xml[-2])-9

      try:
        # kpoints and band structure data
        kpoints = []
        band = []
        occ = []
  
        for i in range(len(self.xml[2][1])):
          k_str = self.xml[2][1][i].text
          weight = float(self.xml[2][2][i].text)
          band_k = []
          occ_k = []
          bk_xml = self.xml[-2][-3][0][5][0][i]
          for b_xml in bk_xml:
            b, o = [float(c) for c in b_xml.text.split()]
            band_k.append(b)
            occ_k.append(o)
          coord = [float(c) for c in k_str.split()]
          coord.append(weight)
          kpoints.append(coord)
          band.append(band_k)
          occ.append(occ_k)
        self.mo_eigenvalues = copy.deepcopy(band[0])
        self.kpoints = np.array(kpoints)
        self.band = np.array(band)
        self.occupation = occ[0]
  
        diff = np.diff(occ[0])
        pos = diff[np.where(abs(diff) > 0.5)]
        mask = np.in1d(diff, pos)
        ind = np.array(range(len(diff)))
        if len(ind[mask]) > 0:
          N_state = ind[mask][0]
          vb = max(self.band[:, N_state])
          cb = min(self.band[:, N_state + 1])
          vb_pos = np.argmax(self.band[:, N_state])
          cb_pos = np.argmin(self.band[:, N_state + 1])
          self.Eg = cb - vb
          if vb_pos == cb_pos:
            self.Eg_direct = True
          else:
            self.Eg_direct = False
  
        # DOS data
        dos = []
        self.E_fermi = float(self.xml[-2][-1][0].text) 
        print self.E_fermi
        for dos_xml in self.xml[-2][-1][1][0][5][0]:
          dos_lst = filter(None, dos_xml.text.split(' '))
          dos_E = [float(d) for d in dos_lst]
          dos.append(dos_E)
        self.dos = np.array(dos)

      except:
        qtk.warning("error when accessing kpoint data for %s"\
                    % self.name)
コード例 #12
0
ファイル: molecule.py プロジェクト: SamKChang/qctoolkit
  def findBonds(self, ratio=setting.bond_ratio, **kwargs):
    del self.segments
    del self.bond_types
    self.segments = []
    self.bond_types = {}
    if 'no_report' not in kwargs or not kwargs['no_report']:
      qtk.report("Molecule", 
                 "finding bonds with cutoff ratio", 
                 ratio)
    def to_graph(l):
      G = networkx.Graph()
      for part in l:
        # each sublist is a bunch of nodes
        G.add_nodes_from(part)
        # it also imlies a number of edges:
        G.add_edges_from(to_edges(part))
      return G
    
    def to_edges(l):
      """ 
      treat `l` as a Graph and returns it's edges 
      to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]
      """
      it = iter(l)
      last = next(it)
    
      for current in it:
        yield last, current
        last = current 
    itr = 0
    bond_list = []
    bonded = [False for i in range(self.N)]
    for i in xrange(self.N):
      for j in xrange(i+1, self.N):
        d_ij = np.linalg.norm(self.R[i,:] - self.R[j,:])
        atom_i = getattr(pt, self.type_list[i])
        atom_j = getattr(pt, self.type_list[j])
        Ri = atom_i.covalent_radius + \
             atom_i.covalent_radius_uncertainty
        Rj = atom_j.covalent_radius + \
             atom_j.covalent_radius_uncertainty
        Dij = (Ri+Rj) * float(ratio)
        if d_ij < Dij:
          bonded[i] = True
          bonded[j] = True
          if self.Z[i] < self.Z[j]:
            atom_begin = self.Z[i]
            atom_end = self.Z[j]
            index_begin = i
            index_end = j
          else:
            atom_begin = self.Z[j]
            atom_end = self.Z[i]
            index_begin = j
            index_end = i
          self.bonds[itr] = {'atom_begin'  : atom_begin,
                             'index_begin' : index_begin,
                             'atom_end'    : atom_end,
                             'index_end'   : index_end,
                             'length'      : d_ij}
          bond_list.append([i, j])
          type_begin = qtk.Z2n(atom_begin)
          type_end   = qtk.Z2n(atom_end)
          bond_table = qtk.data.elements.bond_table
          bond_keys = []
          bond_keys = [
            type_begin + _ + type_end for _ in ['-', '=', '#']
          ]
          try:
            bond_type_ind = np.argmin(
              abs(
                np.array([
                          bond_table[k][0] for k in bond_keys
                          if k in bond_table.keys()
                         ]) - d_ij
              )
            )
          except Exception as _e:
            self.write_xyz()
            qtk.exit(
              "error while processing bond" +\
              str(bond_keys) + "with error message %s" % str(_e))
          bond_type = bond_keys[bond_type_ind]
          self.bonds[itr]['name'] = bond_type
          bond_energy = \
            bond_table[bond_keys[bond_type_ind]][1] * \
            qtk.convE(1, 'kj-kcal')[0]
          self.bonds[itr]['energy'] = bond_energy
          if np.isnan(bond_energy):
            qtk.warning("Non-tabliated covalent bond %s" % bond_type)
          if bond_type in self.bond_types:
            self.bond_types[bond_type] += 1
          else:
            self.bond_types[bond_type] = 1
          itr += 1

    segments = list(connected_components(to_graph(bond_list)))
    for s in range(len(segments)):
      segment = list(segments[s])
      new_mol = self.getSegment(segment, **kwargs)
      ns = len(self.segments)
      new_mol.name = new_mol.name + '_%d' % ns
      self.segments.append(new_mol)
    for s in [i for i in range(self.N) if not bonded[i]]:
      segment = [s]
      new_mol = self.getSegment(segment, **kwargs)
      ns = len(self.segments)
      new_mol.name = new_mol.name + '_%d' % ns
      self.segments.append(new_mol)
コード例 #13
0
  def findBonds(self, ratio=setting.bond_ratio, **kwargs):
    del self.segments
    del self.bond_types
    self.segments = []
    self.bond_types = {}
    if 'no_report' not in kwargs or not kwargs['no_report']:
      qtk.report("Molecule", 
                 "finding bonds with cutoff ratio", 
                 ratio)
    def to_graph(l):
      G = networkx.Graph()
      for part in l:
        # each sublist is a bunch of nodes
        G.add_nodes_from(part)
        # it also imlies a number of edges:
        G.add_edges_from(to_edges(part))
      return G
    
    def to_edges(l):
      """ 
      treat `l` as a Graph and returns it's edges 
      to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]
      """
      it = iter(l)
      last = next(it)
    
      for current in it:
        yield last, current
        last = current 
    itr = 0
    bond_list = []
    bonded = [False for i in range(self.N)]
    for i in xrange(self.N):
      for j in xrange(i+1, self.N):
        d_ij = np.linalg.norm(self.R[i,:] - self.R[j,:])
        atom_i = getattr(pt, self.type_list[i])
        atom_j = getattr(pt, self.type_list[j])
        Ri = atom_i.covalent_radius + \
             atom_i.covalent_radius_uncertainty
        Rj = atom_j.covalent_radius + \
             atom_j.covalent_radius_uncertainty
        Dij = (Ri+Rj) * float(ratio)
        if d_ij < Dij:
          bonded[i] = True
          bonded[j] = True
          if self.Z[i] < self.Z[j]:
            atom_begin = self.Z[i]
            atom_end = self.Z[j]
            index_begin = i
            index_end = j
          else:
            atom_begin = self.Z[j]
            atom_end = self.Z[i]
            index_begin = j
            index_end = i
          self.bonds[itr] = {'atom_begin'  : atom_begin,
                             'index_begin' : index_begin,
                             'atom_end'    : atom_end,
                             'index_end'   : index_end,
                             'length'      : d_ij}
          bond_list.append([i, j])
          type_begin = qtk.Z2n(atom_begin)
          type_end   = qtk.Z2n(atom_end)
          bond_table = qtk.data.elements.bond_table
          bond_keys = []
          bond_keys = [
            type_begin + _ + type_end for _ in ['-', '=', '#']
          ]
          try:
            bond_type_ind = np.argmin(
              abs(
                np.array([
                          bond_table[k][0] for k in bond_keys
                          if k in bond_table.keys()
                         ]) - d_ij
              )
            )
          except Exception as _e:
            qtk.warning(
              "error while processing bond" +\
              str(bond_keys) + "with error message %s" % str(_e))
            bond_type_ind = -1
          bond_type = bond_keys[bond_type_ind]
          self.bonds[itr]['name'] = bond_type
          try:
            bond_energy = \
              bond_table[bond_keys[bond_type_ind]][1] * \
              qtk.convE(1, 'kj-kcal')[0]
          except:
            bond_energy = np.nan
          self.bonds[itr]['energy'] = bond_energy
          if np.isnan(bond_energy):
            qtk.warning("Non-tabliated covalent bond %s" % bond_type)
          if bond_type in self.bond_types:
            self.bond_types[bond_type] += 1
          else:
            self.bond_types[bond_type] = 1
          itr += 1

    segments = list(connected_components(to_graph(bond_list)))
    for s in range(len(segments)):
      segment = list(segments[s])
      new_mol = self.getSegment(segment, **kwargs)
      ns = len(self.segments)
      new_mol.name = new_mol.name + '_%d' % ns
      self.segments.append(new_mol)
    for s in [i for i in range(self.N) if not bonded[i]]:
      segment = [s]
      new_mol = self.getSegment(segment, **kwargs)
      ns = len(self.segments)
      new_mol.name = new_mol.name + '_%d' % ns
      self.segments.append(new_mol)