Ejemplo n.º 1
0
 def mutateElement(self, oldZ, newZ):
   if oldZ != newZ:
     if type(oldZ) is str:
       oldZ = qtk.n2Z(oldZ)
     if type(newZ) is str:
       newZ = qtk.n2Z(newZ)
     newElem = qtk.Z2n(newZ)
     indices = []
     for i in range(self.N):
       if abs(self.Z[i] - oldZ) < 0.1:
         indices.append(i)
     self.setAtoms(indices, element=newElem)
Ejemplo n.º 2
0
 def mutateElement(self, oldZ, newZ):
   if oldZ != newZ:
     if type(oldZ) is str:
       oldZ = qtk.n2Z(oldZ)
     if type(newZ) is str:
       newZ = qtk.n2Z(newZ)
     newElem = qtk.Z2n(newZ)
     indices = []
     for i in range(self.N):
       if abs(self.Z[i] - oldZ) < 0.1:
         indices.append(i)
     self.setAtoms(indices, element=newElem)
Ejemplo n.º 3
0
 def get_index(inp_type):
   if inp_type:
     if type(inp_type) is str:
       Z = qtk.n2Z(inp_type)
     else:
       try:
         Z = int(inp_type)
       except Exception as err:
         qtk.exit("type not reconized with error:%s" % err)
     return np.arange(self.N)[np.asarray(self.Z) == Z]
Ejemplo n.º 4
0
  def read_xyz(self, name, **kwargs):
    xyz = open(name, 'r')
    content = xyz.readlines()
    xyz.close()
    content = [line.replace('\t', ' ') for line in content]

    prop_list = ['charge', 'celldm', 'scale', 'symmetry']
    for prop in prop_list:
      try:
        prop_str = filter(lambda x: prop in x, content)[0]
        prop_str = re.sub('.*:', '', prop_str)
        prop_data = prop_str.split(' ')
        prop_data = filter(None, prop_data)
        if len(prop_data) == 1:
          try:
            setattr(self, prop, float(prop_data[0]))
          except Exception as exc:
            if prop == 'symmetry':
              setattr(self, prop, prop_data[0].strip())
        elif len(prop_data) > 1:
          setattr(self, prop, [float(_) for _ in prop_data])
      except ValueError as exc:
        setattr(self, prop, False)
        qtk.warning("setting attribute %s with error: %s" % \
          (prop, exc))
      except:
        setattr(self, prop, False)
    
    if not self.charge:
      self.charge = 0
    if self.celldm or self.scale:
      self.periodic = True
    if self.celldm:
       assert len(self.celldm) == 6

    self.N = int(content[0])
    coord_list = content[2 : self.N + 2]
    coord = [filter(None,[a for a in entry.split(' ')]) 
             for entry in coord_list]
    type_list = list(np.array(coord)[:,0])
    self.type_list = [str(elem) for elem in type_list]
    self.Z = [qtk.n2Z(elem) for elem in self.type_list]
    self.Z = np.array(self.Z)
    self.R = np.array(coord)[:,1:4].astype(float)

    self.box = False
    if self.celldm:
      self.periodic = True
      angle = self.celldm[3:]
      angle_sum = sum([abs(entry) for entry in angle])
      if angle_sum == 0:
        self.box = self.celldm[:3]

      self.R_scale = copy.deepcopy(self.R)
      self.R = qtk.fractional2xyz(self.R_scale, self.celldm)
Ejemplo n.º 5
0
 def getMolecule(content):
   comment_p = re.compile(r'^ *\t*(?!([!#])).*$')
   data_p = re.compile(r'^[\ \t0-9\-\. ]+.*$')
   dataContent = filter(comment_p.match, content[3:])
   dataContent = filter(data_p.match, dataContent)
   N = len(dataContent)
   R = []
   molData = []
   for line in dataContent:
     data = filter(None, line.replace('\n', '').split(' '))
     molLine = [qtk.n2Z(data[3])]
     molLine.extend([float(r) for r in data[:3]])
     molData.append(molLine)
   return molData
Ejemplo n.º 6
0
 def getMolecule(content):
   comment_p = re.compile(r'^ *\t*(?!([!#])).*$')
   data_p = re.compile(r'^[\ \t0-9\-\. ]+.*$')
   dataContent = filter(comment_p.match, content[3:])
   dataContent = filter(data_p.match, dataContent)
   N = len(dataContent)
   R = []
   molData = []
   for line in dataContent:
     data = filter(None, line.replace('\n', '').split(' '))
     molLine = [qtk.n2Z(data[3])]
     molLine.extend([float(r) for r in data[:3]])
     molData.append(molLine)
   return molData
Ejemplo n.º 7
0
def Molecules(file_name, **kwargs):
    """read nested xyz file and return molecule list"""
    xyz = open(file_name, 'r')
    content = xyz.readlines()
    content = [line.replace('\t', ' ') for line in content]
    xyz.close()

    itr = 0
    more_data = True
    mols = []

    while more_data:
        try:
            N = int(content[itr])
            prop_list = content[itr + 1]
            try:
                prop_list = np.array(prop_list.split(' ')).astype(float)
            except Exception as err:
                qtk.warning(str(err))
                prop_list = prop_list
            coord_list = content[itr + 2:itr + N + 2]
            coord = [
                filter(None, [a for a in entry.split(' ')])
                for entry in coord_list
            ]
            type_list = list(np.array(coord)[:, 0])
            type_list = [str(elem) for elem in type_list]
            Z = np.array([qtk.n2Z(elem) for elem in type_list])
            R = np.array(coord)[:, 1:4].astype(float)
            mol_data = {}
            for var in ['N', 'type_list', 'Z', 'R']:
                mol_data[str(var)] = eval(var)
            itr += N + 2
            mols.append(qtk.Molecule(molecule_data=mol_data))
        except Exception as err:
            qtk.progress(
                "Molecules", "%d molecules have been loaded with message %s." %
                (len(mols), str(err)))
            more_data = False

    return mols
Ejemplo n.º 8
0
def read_vasp(chg_file):
    with open(chg_file) as cfile:
        content = cfile.readlines()
    grid_1d = np.fromstring(''.join(content[2:5]), dtype=float, sep=' ')
    grid = grid_1d.reshape([3, 3])
    type_list = filter(None, content[5].split(' '))[:-1]
    n_list = np.fromstring(content[6], dtype=int, sep=' ')
    Z = []
    for a in range(len(type_list)):
        for n in range(n_list[a]):
            Z.append(qtk.n2Z(type_list[a]))
    Z = np.array(Z)[:, None]
    N = sum(n_list)
    R_scale = np.fromstring(''.join(content[8:8 + N]), dtype=float,
                            sep=' ').reshape([N, 3])
    R = []
    for i in range(N):
        r = np.array([0, 0, 0])
        for j in range(3):
            r = r + R_scale[i, j] * grid.T[j] / 0.529177249
        R.append(r)
    R = np.array(R)
    zcoord = np.hstack([Z, R])

    V = np.dot(np.cross(grid[0], grid[1]), grid[2]) / (0.529177249)**3
    step = np.fromstring(content[9 + N], dtype=int, sep=' ')
    for i in range(3):
        grid[i] = grid[i] / (step[i] * 0.529177249)

    # numpy array.reshape does not change memory order
    # use ravel to unwine new order
    data = np.fromstring(''.join(content[10 + N:]), dtype=float, sep=' ')
    data = data.reshape(step, order='F') / V
    data_rav = data.ravel()
    data = data_rav.reshape(step)

    step = step[:, None]
    grid = np.hstack([step, grid])
    grid = np.vstack([[N, 0, 0, 0], grid])

    return data, zcoord, grid
Ejemplo n.º 9
0
def read_vasp(chg_file):
  with open(chg_file) as cfile:
    content = cfile.readlines()
  grid_1d = np.fromstring(''.join(content[2:5]), dtype=float, sep=' ')
  grid = grid_1d.reshape([3,3])
  type_list = filter(None, content[5].split(' '))[:-1]
  n_list = np.fromstring(content[6], dtype=int, sep=' ')
  Z = []
  for a in range(len(type_list)):
    for n in range(n_list[a]):
      Z.append(qtk.n2Z(type_list[a]))
  Z = np.array(Z)[:, None]
  N = sum(n_list)
  R_scale = np.fromstring(''.join(content[8:8+N]), 
                          dtype=float, sep=' ').reshape([N, 3])
  R = []
  for i in range(N):
    r = np.array([0,0,0])
    for j in range(3):
      r = r + R_scale[i, j] * grid.T[j] / 0.529177249
    R.append(r)
  R = np.array(R)
  zcoord = np.hstack([Z, R])

  V = np.dot(np.cross(grid[0], grid[1]), grid[2]) / (0.529177249)**3
  step = np.fromstring(content[9+N], dtype=int, sep=' ')
  for i in range(3):
    grid[i] = grid[i] / (step[i] * 0.529177249)

  # numpy array.reshape does not change memory order
  # use ravel to unwine new order
  data = np.fromstring(''.join(content[10+N:]), dtype=float, sep=' ')
  data = data.reshape(step, order='F') / V
  data_rav = data.ravel()
  data = data_rav.reshape(step)

  step = step[:, None]
  grid = np.hstack([step, grid])
  grid = np.vstack([[N, 0, 0, 0], grid])

  return data, zcoord, grid
Ejemplo n.º 10
0
 def haveBond(self, type_a, type_b):
   result = False
   type_a = type_a.title()
   type_b = type_b.title()
   if '0' not in self.bonds:
     self.findBonds()
   if qtk.n2Z(type_a) > qtk.n2Z(type_b):
     atom_begin = qtk.n2Z(type_b)
     atom_end = qtk.n2Z(type_a)
   else:
     atom_begin = qtk.n2Z(type_a)
     atom_end = qtk.n2Z(type_b)
   for key in self.bonds:
     if self.bonds[key]['atom_begin'] == atom_begin \
     and self.bonds[key]['atom_end'] == atom_end:
       result = True
   return result
Ejemplo n.º 11
0
 def haveBond(self, type_a, type_b):
   result = False
   type_a = type_a.title()
   type_b = type_b.title()
   if '0' not in self.bonds:
     self.findBonds()
   if qtk.n2Z(type_a) > qtk.n2Z(type_b):
     atom_begin = qtk.n2Z(type_b)
     atom_end = qtk.n2Z(type_a)
   else:
     atom_begin = qtk.n2Z(type_a)
     atom_end = qtk.n2Z(type_b)
   for key in self.bonds:
     if self.bonds[key]['atom_begin'] == atom_begin \
     and self.bonds[key]['atom_end'] == atom_end:
       result = True
   return result
Ejemplo n.º 12
0
 def setAtoms(self, index, **kwargs):
   if type(index) is int:
     index = [index]
   if 'element' in kwargs or 'Z' in kwargs:
     for i in index:
       if 'element' in kwargs:
         if type(kwargs['element']) is str:
           Z = qtk.n2Z(kwargs['element'])
           Zn = kwargs['element']
         elif type(kwargs['element']) is int\
         or type(kwargs['element']) is float:
           Z = kwargs['element']
           Zn = qtk.Z2n(Z)
       elif 'Z' in kwargs:
         Z = kwargs['Z']
         Zn = qtk.Z2n(Z)
       self.Z[i] = Z
       self.type_list[i] = Zn
   if 'string' in kwargs:
     minZ = min(min(self.Z)-1, 0)
     for i in index:
       self.string[i] = kwargs['string']
       self.Z[i] = minZ
Ejemplo n.º 13
0
 def setAtoms(self, index, **kwargs):
   if type(index) is int:
     index = [index]
   if 'element' in kwargs or 'Z' in kwargs:
     for i in index:
       if 'element' in kwargs:
         if type(kwargs['element']) is str:
           Z = qtk.n2Z(kwargs['element'])
           Zn = kwargs['element']
         elif type(kwargs['element']) is int\
         or type(kwargs['element']) is float:
           Z = kwargs['element']
           Zn = qtk.Z2n(Z)
       elif 'Z' in kwargs:
         Z = kwargs['Z']
         Zn = qtk.Z2n(Z)
       self.Z[i] = Z
       self.type_list[i] = Zn
   if 'string' in kwargs:
     minZ = min(min(self.Z)-1, 0)
     for i in index:
       self.string[i] = kwargs['string']
       self.Z[i] = minZ
Ejemplo n.º 14
0
        def writeInp(name=None, **setting):
            self.setting.update(setting)
            self.setting['no_molecule'] = False
            inp, molecule = \
              super(PlanewaveInput, self).write(name, **self.setting)

            molecule.sort()
            type_index = molecule.index
            type_list = molecule.type_list

            self.pp_path = qtk.setting.bigdft_pp
            if 'pp_path' in self.setting:
                self.pp_path = self.setting['pp_path']

            if 'pp_theory' not in self.setting:
                self.setting['pp_theory'] = self.setting['theory']

            pp_files = []
            typat = []
            for a in range(len(type_index) - 1):
                start = type_index[a]
                end = type_index[a + 1]
                for i in range(end - start):
                    typat.append(a + 1)
            for i in range(molecule.N):
                pp_file = 'psppar.' + molecule.type_list[i]
                pp_list = set([pp[1] for pp in pp_files])
                if pp_file not in pp_list:
                    pp_src = PPCheck(self.setting['theory'],
                                     self.setting['pp_theory'], self.pp_path,
                                     molecule.type_list[i])
                    pp_files.append([pp_src, pp_file])

            ##################
            # scf section #
            ##################
            self.content['scf'] = odict()

            # restart check #
            if 'restart' in self.setting and self.setting['restart']\
            and 'band_scan' not in self.setting\
            and 'dos_mesh' not in self.setting:
                self.content['scf']['irdwfk'] = 1
                self.content['scf']['getwfk'] = -1
            if 'restart_density' in self.setting \
            and self.setting['restart_density']\
            and 'band_scan' not in self.setting\
            and 'dos_mesh' not in self.setting:
                self.content['scf']['irdden'] = 1
                self.content['scf']['getden'] = -1

            if 'kmesh' not in self.setting:
                self.setting['kmesh'] = [1, 1, 1]
            if 'kshift' not in self.setting:
                self.setting['kshift'] = [0.0, 0.0, 0.0]

            # kpoints check #
            if 'kpoints' in self.setting:
                self.content['scf']['kptopt'] = 0
                self.content['scf']['nkpt'] = len(self.setting['kpoints'])
                self.content['scf']['kpt'] = self.setting['kpoints']
            else:
                if self.setting['full_kmesh']:
                    self.content['scf']['kptopt'] = 3
                self.content['scf']['ngkpt'] = self.setting['kmesh']
                if len(np.array(self.setting['kshift']).shape) > 1:
                    self.content['scf']['nshiftk'] = len(
                        self.setting['kshift'])
                self.content['scf']['shiftk'] = self.setting['kshift']
                nbnd = None
            if 'ks_states' in self.setting and self.setting['ks_states']:
                vs = int(round(molecule.getValenceElectrons() / 2.0))
                nbnd = self.setting['ks_states'] + vs
                if 'd_shell' in self.setting:
                    for a in molecule.type_list:
                        if a in self.setting['d_shell'] and qtk.n2ve(a) < 10:
                            nbnd += 5
                if 'band_scan' not in self.setting \
                and 'dos_mesh' not in self.setting:
                    self.content['scf']['nband'] = nbnd

            # system setup #
            if molecule.charge != 0:
                self.content['scf']['charge='] = molecule.charge
            if molecule.multiplicity != 1:
                self.content['scf']['nsppol'] = 2
                self.content['scf']['occopt'] = 7
            if 'save_restart' not in self.setting \
            or not self.setting['save_restart']:
                if 'restart' in self.setting and self.setting['restart']\
                and ('band_scan' not in self.setting\
                and 'dos_mesh' not in self.setting):
                    self.content['scf']['prtwf'] = 0
            #if 'wf_convergence' in self.setting:
            if 'band_scan' in self.setting\
            or 'dos_mesh' in self.setting:
                if 'restart' not in self.setting\
                or not self.setting['restart']:
                    self.content['scf']['tolwfr'] = \
                    self.setting['wf_convergence']
            else:
                self.content['scf']['tolwfr'] = \
                self.setting['wf_convergence']

            # clean up for the case of restart
            if 'restart' in self.setting and self.setting['restart']\
            and ('band_scan' in self.setting or 'dos_mesh' in self.setting):
                keep_lst = [
                    'nband',
                    'tolwfr',
                    'nstep',
                    'ecut',
                    'irdwfk',
                    'irdden',
                    'getwfk',
                    'getden',
                ]
                for key in self.content['scf'].iterkeys():
                    if key not in keep_lst and 'prt' not in key:
                        self.content['scf'].pop(key)

            ######################
            # additional setting #
            ######################
            if 'abinit_setting' in self.setting:
                self.content['additional'] = odict([])
                for item in self.setting['abinit_setting']:
                    self.content['additional'][item] = ' '

            def is_strnum(q):
                if isinstance(q, Number) or type(q) is str:
                    return True
                else:
                    return False

            #################
            # bandstructure #
            #################
            if 'band_scan' in self.setting and self.setting['band_scan']:

                if molecule.symmetry and molecule.symmetry.lower() == 'fcc':
                    if 'kshift' not in self.setting:
                        self.setting['kshift'] = [
                            [0.5, 0.5, 0.5],
                            [0.5, 0.0, 0.0],
                            [0.0, 0.5, 0.0],
                            [0.0, 0.0, 0.5],
                        ]

                bnds = self.setting['band_scan']
                if len(bnds) != 2 \
                or is_strnum(bnds[0]) \
                or len(bnds[0]) != len(bnds[1]) - 1:
                    qtk.exit('band_scan format: [lst_div, lst_coord]')

                bnd_content = odict([
                    ('iscf', -2),
                    ('getden', -1),
                    ('kptopt', -len(bnds[0])),
                    ('tolwfr', self.setting['wf_convergence']),
                    ('ndivk', bnds[0]),
                    ('kptbounds', bnds[1]),
                ])
                if nbnd:
                    bnd_content['nband'] = nbnd
                if 'save_restart' not in self.setting \
                or not self.setting['save_restart']:
                    bnd_content['prtwf'] = 0
                else:
                    bnd_content['prtwf'] = 1
                if 'save_density' not in self.setting \
                or not self.setting['save_density']:
                    bnd_content['prtden'] = 0
                else:
                    bnd_content['prtden'] = 1
                if 'dos_mesh' in self.setting:
                    bnd_content['prtden'] = 1

                if 'restart' in self.setting and self.setting['restart']:
                    bnd_content['irdden'] = 1
                    bnd_content['irdwfk'] = 1
                    bnd_content['getwfk'] = -1

                self.content['band_scan'] = bnd_content

            #####################
            # density of states #
            #####################
            if 'dos_mesh' in self.setting and self.setting['dos_mesh']:
                dos_content = odict([
                    ('iscf', -3),
                    ('ngkpt', self.setting['dos_mesh']),
                    ('shiftk', [0.0, 0.0, 0.0]),
                    ('tolwfr', self.setting['wf_convergence']),
                    ('prtwf', 0),
                ])
                if 'band_scan' in self.setting:
                    dos_content['getden'] = -2
                else:
                    dos_content['getden'] = -1

                if 'smearing' in self.setting:
                    smr = self.setting['smearing']
                    smr_dict = {
                        'fermi': 3,
                        'marzari': 4,
                        'marzari_monotonic': 5,
                        'paxton': 6,
                        'gaussian': 7,
                    }
                    if smr in smr_dict:
                        dos_content['occopt'] = smr_dict[smr]
                        dos_content['prtdos'] = 1
                    else:
                        qtk.warning("%s for occupation scheme not found" % smr)

                if nbnd:
                    dos_content['nband'] = nbnd

                if 'save_restart' not in self.setting \
                or not self.setting['save_restart']:
                    dos_content['prtwf'] = 0
                else:
                    dos_content['prtwf'] = 1
                if 'save_density' not in self.setting \
                or not self.setting['save_density']:
                    dos_content['prtden'] = 0
                else:
                    dos_content['prtden'] = 1

                if 'restart' in self.setting and self.setting['restart']:
                    dos_content['irdden'] = 1
                    dos_content['irdwfk'] = 1
                    dos_content['getwfk'] = -1

                self.content['dos'] = dos_content

            ################
            # cell section #
            ################
            self.content['cell'] = odict([
                ('ecut', float(self.setting['cutoff'] / 2.)),
                ('nstep', self.setting['scf_step']),
            ])

            self.content['cell']['acell'] = '3*1.889726124993'
            self.celldm2lattice()
            if not molecule.symmetry:
                self.content['cell']['chkprim'] = 0
            self.content['cell']['rprim'] = self.setting['lattice']

            #################
            # atoms section #
            #################
            znucl = []
            for a in range(len(type_index) - 1):
                symb = type_list[type_index[a]]
                znucl.append(int(qtk.n2Z(symb)))

            self.content['atoms'] = odict([
                ('natom', molecule.N),
                ('ntypat', (len(type_index) - 1)),
                ('typat', typat),
                ('znucl', znucl),
            ])
            if hasattr(molecule, 'scale') and molecule.scale:
                if hasattr(molecule, 'R_scale'):
                    R_scale = molecule.R_scale.copy()
                    for i in range(3):
                        s = molecule.scale[i]
                        if s > 0: R_scale[:, i] = R_scale[:, i] / s
                    self.content['atoms']['xred'] = R_scale
                else:
                    qtk.warning('R_scale not found but scale is set')
                    self.content['atoms']['xangst'] = molecule.R
            else:
                self.content['atoms']['xangst'] = molecule.R

            #########################
            # write content to file #
            #########################

            datasets = 1
            for key in ['band_scan', 'dos']:
                if key in self.content:
                    datasets += 1

            if self.setting['restart'] and datasets > 1:
                datasets -= 1

            self.content['datasets']['ndtset'] = datasets

            inp.write('# abinit input generated by qctoolkit\n')
            ds_itr = 0
            ds_str = ''

            if self.content['datasets']['ndtset'] == 1:
                self.content['datasets'].pop('ndtset')

            for section_key in self.content.iterkeys():
                if len(self.content[section_key]) > 0:
                    inp.write('\n# %s section\n' % section_key)
                if section_key in ['scf', 'band_scan', 'dos'] and datasets > 1:
                    ds_itr += 1
                    ds_str = str(ds_itr)
                for key, value in self.content[section_key].iteritems():
                    if ds_str and section_key in ['scf', 'band_scan', 'dos']:
                        key = key + ds_str
                    if is_strnum(value):
                        inp.write('%s %s\n' % (key, str(value)))
                    else:
                        inp.write('%s' % key)
                        head = ''.join([' ' for _ in key])
                        if 'xangst' in key\
                        or 'xcart' in key\
                        or 'xred' in key:
                            inp.write('\n\n')
                            for vec in value:
                                inp.write('%s' % head)
                                for v in vec:
                                    inp.write(' %s' % str(v))
                                inp.write('\n')
                        elif is_strnum(value[0]):
                            for v in value:
                                inp.write(' %s' % str(v))
                            inp.write('\n')
                        else:
                            for v in value[0]:
                                inp.write(' %s' % str(v))
                            inp.write('\n')
                            for vec in value[1:]:
                                inp.write('%s' % head)
                                for v in vec:
                                    inp.write(' %s' % str(v))
                                inp.write('\n')

            if 'restart_wavefunction_path' in self.setting:
                rstwf_path = self.setting['restart_wavefunction_path']
                if os.path.exists(rstwf_path):
                    wf_lst = sorted(
                        glob.glob(os.path.join(rstwf_path, '*o_*WFK')))
                    assert len(wf_lst) > 0
                    wf_src = os.path.abspath(wf_lst[-1])
                    pp_files.append([wf_src, name + 'i_WFK'])
                else:
                    qtk.warning('%s not found' % rstwf_path)

            if 'restart_wavefunction_file' in self.setting:
                rst_file = self.setting['restart_wavefunction_file']
                if os.path.exists(rst_file):
                    pp_files.append([rst_file, name + 'i_WFK'])
                else:
                    qtk.warning('%s not found' % rst_file)

            if 'restart_density_path' in self.setting:
                rstdn_path = self.setting['restart_density_path']
                if os.path.exists(rstdn_path):
                    dn_lst = sorted(
                        glob.glob(os.path.join(rstdn_path, '*o_*DEN')))
                    assert len(dn_lst) > 0
                    dn_src = os.path.abspath(dn_lst[-1])
                    pp_files.append([dn_src, name + 'i_DEN'])
                else:
                    qtk.warning('%s not found' % rstdn_path)

            if 'restart_density_file' in self.setting:
                rst_file = self.setting['restart_density_file']
                if os.path.exists(rst_file):
                    pp_files.append([rst_file, name + 'i_DEN'])
                else:
                    qtk.warning('%s not found' % rst_file)

            inp.close(dependent_files=pp_files)

            if hasattr(inp, 'final_name'):
                self.setting['no_molecule'] = True
                self.setting['root_dir'] = name
                files = \
                  super(PlanewaveInput, self).write(name, **self.setting)
                files.extension = 'files'
                files.write(inp.final_name + '\n')
                root = os.path.splitext(inp.final_name)[0]
                files.write(root + '.out\n')
                files.write(root + 'i\n')
                files.write(root + 'o\n')
                files.write(root + 'x\n')
                for pp in pp_files:
                    files.write(pp[1] + '\n')
                files.close(no_cleanup=True)

            return inp
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
  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)
Ejemplo n.º 17
0
     def getBasis():
       ######################################
       # extract basis function information #
       ######################################
     
       basis_dict = {"S":0, "P":1, "D":2, "F":3, "G":4, "H":5}
 
       basis_P = re.compile(r" *[0-9]+ [A-Z]  [0-9]\.[0-9]{8}")
       batom_P = re.compile(r"^  [0-9A-Za-z\-_\.]+ *\([A-Z][a-z]*\)")
       bname_P = re.compile(r"\((.*)\)")
       coord_P = re.compile(r"^ [0-9A-Za-z\.\-_]+ +[- ][0-9\.]{9,}")
       basisStr = filter(basis_P.match, data)
       batomStr = filter(batom_P.match, data)
       coordStr = filter(coord_P.match, data)
 
       # change 'Sulphur' to 'Sulfur' for NWChem format
       # 'Sulphur' 'Sulfur'
       def atomNameConv(old, new):
         _matched = filter(lambda x: old in x, batomStr)
         if _matched:
           _matched = _matched[0]
           _s = batomStr.index(_matched)
           batomStr[_s] = re.sub(old, new, batomStr[_s])
           _s = data.index(_matched)
           data[_s] = re.sub(old, new, data[_s])
       atomNameConv('Sulphur', 'Sulfur')
       atomNameConv('Aluminium', 'Aluminum')
 
       _exponents = [float(filter(None, s.split(' '))\
         [2]) for s in basisStr]
       _coefficients = [float(filter(None, s.split(' '))\
         [3]) for s in basisStr]
       _N = [int(filter(None, s.split(' '))[0])\
         for s in basisStr]
       _type = [filter(None, s.split(' '))[1]\
         for s in basisStr]
       _bfnInd = [data.index(batom) for batom in batomStr]
       _bfnEndPtn = re.compile(r" Summary of \"")
       _bfnEndStr = filter(_bfnEndPtn.match, data)[0]
       _bfnInd.append(data.index(_bfnEndStr))
 
       _ao_keys = [0]
       for ind in range(len(_bfnInd)-1):
         _key = _ao_keys[-1]
         for i in range(_bfnInd[ind]+4, _bfnInd[ind+1]):
           if len(data[i]) > 1:
             _key = _key + 1
         _ao_keys.append(_key)
       _atoms = [getattr(pt, bname_P.match(
         filter(None, s.split(' '))[1]).group(1).lower()).symbol\
         for s in batomStr]
       self.type_list = [re.split(r'[\._]',
         filter(None, s.split(' '))[0])[0].title()\
         for s in coordStr]
       self.type_list_unique = list(
         collections.OrderedDict.fromkeys(self.type_list)
       )
       self.R = np.array([filter(None, s.split(' '))[1:4]\
         for s in coordStr]).astype(float)
       self.N = len(self.R)
       self.Z = [qtk.n2Z(e) for e in self.type_list]
       self.R_bohr = 1.889725989 * self.R
       ZR = []
       for i in range(self.N):
         vec = [self.Z[i]]
         vec.extend(self.R[i])
         ZR.append(vec)
       self.molecule = qtk.Molecule()
       self.molecule.build(ZR)
 
       _N.append(0)
       self.basis = []
       for i in range(len(self.type_list)):
         e = self.type_list[i]
         center = self.R_bohr[i]
         ind = self.type_list_unique.index(e)
         bfn_base = {}
         bfn_base['atom'] = e
         bfn_base['center'] = center
         bfn_base['index'] = i
         exp = []
         cef = []
         for g in range(_ao_keys[ind], _ao_keys[ind+1]):
           exp.append(_exponents[g])
           cef.append(_coefficients[g])
           if _N[g] != _N[g+1] or g+1 >= _ao_keys[ind+1]:
             bfn = copy.deepcopy(bfn_base)
             bfn['exponents'] = copy.deepcopy(exp)
             bfn['coefficients'] = copy.deepcopy(cef)
             if _type[g] in basis_dict:
               _bfnList = self.basisList(basis_dict[_type[g]])
               for bStr in _bfnList:
                 bfn['type'] = _type[g].lower() + bStr
                 self.basis.append(copy.deepcopy(bfn))
             exp = []
             cef = []
Ejemplo n.º 18
0
  def write(self, name=None, **kwargs):
    self.setting.update(kwargs)
    self.setting['no_molecule'] = False
    inp, molecule = \
      super(PlanewaveInput, self).write(name, **self.setting)

    molecule.sort()
    type_index = molecule.index
    type_list = molecule.type_list

    self.pp_path = qtk.setting.bigdft_pp
    if 'pp_path' in self.setting:
      self.pp_path = self.setting['pp_path']

    if 'pp_theory' not in self.setting:
      self.setting['pp_theory'] = self.setting['theory']

    pp_files = []
    inp.write('# abinit input generated by qctoolkit\n')

    # restart section
    if 'restart' in self.setting and self.setting['restart']:
      inp.write('\n# restart, reading wavefunction from file\n')
      inp.write('irdwfk 1\n')
      inp.write('getwfk -1\n')
 
    # cell definition
    inp.write('\n# cell definition\n')
    # cell specified by Bohr
    if not molecule.symmetry:
      inp.write('# NOTE: cell defined by lattice vector, ')
      inp.write('NOT supported by abinit spacegroup detector!\n')
      inp.write('acell 3*1.889726124993\n')
      if 'lattice' not in self.setting:
        self.celldm2lattice()
      lattice_vec = self.setting['lattice']
      inp.write('chkprim 0\n')
    elif molecule.symmetry.lower() == 'fcc':
      inp.write("# fcc primitive cell\n")
      a0 = molecule.celldm[0] * 1.889726124993
      inp.write('acell 1 1 1\n')
      lattice_vec = 0.5 * a0 * np.array([
        [0, 1, 1],
        [1, 0, 1],
        [1, 1, 0],
      ])
    elif molecule.symmetry.lower() == 'bcc':
      inp.write("# bcc primitive cell\n")
      inp.write('acell 1 1 1\n')
      a0 = molecule.celldm[0] * 1.889726124993
      lattice_vec = 0.5 * a0 * np.array([
        [-1, 1, 1],
        [ 1,-1, 1],
        [ 1, 1,-1],
      ])
    strList = ['rprim', '', '']
    for i in range(3):
      vec = lattice_vec[i]
      inp.write('%5s % 11.6f % 11.6f % 11.6f\n' % (
        strList[i], vec[0], vec[1], vec[2],
      ))

    # atom definition
    inp.write("\n# atom definition\n")
    inp.write('ntypat %d\n' % (len(type_index) - 1))
    inp.write('znucl')
    for a in range(len(type_index)-1):
      symb = type_list[type_index[a]]
      Z = qtk.n2Z(symb)
      inp.write(' %d' % Z)
    inp.write('\n')

    # atom position
    inp.write("\n# atom position\n")
    inp.write("natom %d\n" % molecule.N)
    inp.write('typat')
    for a in range(len(type_index)-1):
      start = type_index[a]
      end = type_index[a+1]
      for i in range(end - start):
        inp.write(' %d' % (a+1))
    inp.write('\nxangst\n\n')
    for i in range(molecule.N):
      inp.write('  ')
      for j in range(3):
        inp.write(' % 11.6f' % molecule.R[i][j])
      inp.write('\n')

      # construct pp files depandency
      pp_file = 'psppar.' + molecule.type_list[i]
      pp_list = set([pp[1] for pp in pp_files])
      if pp_file not in pp_list:
        pp_src = PPCheck(self.setting['theory'],
                         self.setting['pp_theory'],
                         self.pp_path,
                         molecule.type_list[i])
        pp_files.append([pp_src, pp_file])

    inp.write('\n')

    # system setting
    inp.write("\n# system settings\n")
    # cutoff in Hartree
    inp.write('ecut %.2f\n' % float(self.setting['cutoff']/2.))
    if 'kmesh' not in self.setting:
      self.setting['kmesh'] = [1,1,1]
    if self.setting['full_kmesh']:
      inp.write('kptopt 3\n')
    inp.write('ngkpt')
    for k in self.setting['kmesh']:
      inp.write(' %d' % k)
    if 'kshift' not in self.setting:
      inp.write('\nshiftk 0.0 0.0 0.0')
    if 'ks_states' in self.setting and self.setting['ks_states']:
      vs = int(round(molecule.getValenceElectrons() / 2.0))
      nbnd = self.setting['ks_states'] + vs
      if 'd_shell' in self.setting:
        for a in molecule.type_list:
          if a in self.setting['d_shell'] and qtk.n2ve(a) < 10:
            nbnd += 5
      inp.write('\nnband %d' % nbnd)
    inp.write('\nnstep %d\n' % self.setting['scf_step']) 
    if 'wf_convergence' in self.setting:
      inp.write('toldfe %.2E\n' % self.setting['wf_convergence'])
    if molecule.charge != 0:
      inp.write('charge=%d\n' % molecule.charge)
    if molecule.multiplicity != 1:
      inp.write('nsppol 2 # for spin polarized\n')
      inp.write('occopt 7 # for relaxed occupation\n')

    if 'save_restart' in self.setting and self.setting['save_restart']:
      pass
    else:
      inp.write('prtwf 0\n')

    for item in self.content:
      inp.write(item)

    inp.close(dependent_files=pp_files)

    if hasattr(inp, 'final_name'):
      self.setting['no_molecule'] = True
      self.setting['root_dir'] = name
      files = \
        super(PlanewaveInput, self).write(name, **self.setting)
      files.extension = 'files'
      files.write(inp.final_name + '\n')
      root = os.path.splitext(inp.final_name)[0]
      files.write(root + '.out\n')
      files.write(root + 'i\n')
      files.write(root + 'o\n')
      files.write(root + 'x\n')
      for pp in pp_files:
        files.write(pp[1] + '\n')
      files.close(no_cleanup = True)

    return inp
Ejemplo n.º 19
0
        def getChild():
            child = {}
            for key in parent1.iterkeys():
                if key == 'mutation':
                    # implementation for element_count constraints
                    if self.element_count:
                        constraint_list = []
                        constraint_keys = []

                        # tool to constuct list
                        def _list_append(mcoord, i_list, Zc):
                            for g in range(len(mcoord)):
                                grp = mcoord[g]
                                for i in range(len(grp)):
                                    Z_p = grp[i]
                                    if Z_p == Zc:
                                        i_list.append((g, i))

                        # construct mutation list
                        for elem in self.element_count.iterkeys():
                            i_list = []
                            _Z = qtk.n2Z(elem)
                            _list_append(parent1['mutation'], i_list, _Z)
                            _list_append(parent2['mutation'], i_list, _Z)
                            constraint_list.append(i_list)
                            constraint_keys.append(elem)

                        while True:
                            selected_list = []
                            selected_coord = {}
                            consistant = True
                            for i in range(len(constraint_list)):
                                ind_location = constraint_list[i]
                                random.shuffle(ind_location)
                                elem = qtk.n2Z(constraint_keys[i])
                                _count = self.element_count[
                                    constraint_keys[i]][0]
                                _end = _count
                                while len(set(ind_location[:_end])) < _count:
                                    _end += 1
                                _new = list(set(ind_location[:_end]))
                                to_select = copy.deepcopy(selected_list)
                                to_select.extend(_new)
                                if len(set(to_select)) == \
                                len(selected_list) + len(_new):
                                    selected_list.extend(_new)
                                    for coord in _new:
                                        selected_coord.update({coord: elem})
                                    consistant = consistant & True
                                else:
                                    consistant = False
                            child_ind = []
                            for g in range(len(parent1['mutation'])):
                                child_list = []
                                for i in range(len(parent1['mutation'][g])):
                                    if selected_coord.has_key((g, i)):
                                        child_list.append(selected_coord[(g,
                                                                          i)])
                                    else:
                                        candidate = []
                                        A1 = qtk.Z2n(parent1['mutation'][g][i])
                                        A2 = qtk.Z2n(parent2['mutation'][g][i])
                                        if not self.element_count.has_key(A1):
                                            candidate.append(qtk.n2Z(A1))
                                        if not self.element_count.has_key(A2):
                                            candidate.append(qtk.n2Z(A2))
                                        if len(candidate) == 0:
                                            consistant = False
                                        else:
                                            child_list.append(
                                                random.choice(candidate))
                                child_ind.append(child_list)
                            if consistant:
                                break
                        for g in range(len(parent1['mutation'])):
                            for i in range(len(parent1['mutation'][g])):
                                if not selected_coord.has_key((g, i)):
                                    if random.random() < mutation_rate:
                                        child_ind[g][i] = random.choice(\
                                          self.mutation_target[g])
                                        elem = qtk.Z2n(child_ind[g][i])
                                        if self.element_count.has_key(elem):
                                            coord = random.choice([tupl for tupl,targ
                                              in selected_coord.iteritems()\
                                              if targ == qtk.n2Z(elem)])
                                            del selected_coord[coord]
                                            selected_coord.update({
                                                (g, i):
                                                qtk.n2Z(elem)
                                            })
                                            [gc, ic] = list(coord)
                                            new_targ = random.choice([z for z in \
                                                        self.mutation_target[gc]\
                                                        if not self.element_count\
                                                        .has_key(qtk.Z2n(z))])
                                            child_ind[gc][ic] = new_targ
                        child.update({'mutation': child_ind})

                    else:
                        child_mut = []
                        for i in range(len(parent1[key])):
                            # mix two parent
                            grp = parent1[key][i]
                            index = range(len(grp))
                            random.shuffle(index)
                            ind1 = index[:len(index) / 2]
                            if len(index) % 2 == 0:
                                ind2 = index[len(index) / 2:]
                                append = -1
                            else:
                                ind2 = index[len(index) / 2:-1]
                                append = index[-1]
                            new = [parent1[key][i][ind] for ind in ind1]
                            new.extend([parent2[key][i][ind] for ind in ind2])
                            if append >= 0:
                                if random.random() >= 0.5:
                                    new.append(parent1[key][i][append])
                                else:
                                    new.append(parent2[key][i][append])
                            # mutation, loop through each element
                            for j in range(len(new)):
                                if random.random() < mutation_rate:
                                    mut_target = [tar \
                                      for tar in self.mutation_target[i]\
                                      if tar != new[j]]
                                    new[j] = random.choice(mut_target)
                            child_mut.append(new)
                        child.update({'mutation': child_mut})
                else:
                    qtk.exit("ccs mate function is not yet implemented for "\
                             + key)
            return child
Ejemplo n.º 20
0
        def random_coord(self, mode):
            # determin coordinate type
            if mode == 'mutation':
                _dtype = int
                _list = copy.deepcopy(self.mutation_list)
                _targ = copy.deepcopy(self.mutation_target)

                # algorithm for element_count constraint
                # 1. construct mapping from flattened to nested mutation list
                # 2. select all candidate indices for constrainted element
                # 3. remove constrained element from target lists
                # 4. random choice of candidate for constrained mutation
                # 5. loop through all other indices without constrained elem

                # single constraint implementation
                if self.element_count:
                    new_list = []
                    new_targ = []
                    constraint = []
                    selected = []
                    for elem in self.element_count.iterkeys():
                        itr = 0
                        count = 0
                        _candidate = []
                        for sublist in _targ:
                            if qtk.n2Z(elem) in sublist:
                                _candidate.extend(
                                    range(itr, itr + len(_list[count])))
                                _targ[count].remove(qtk.n2Z(elem))
                            itr += len(_list[count])
                            count += 1
                        _candidate = [x for x in _candidate\
                                      if not x in flatten(selected)]

                        selection = sorted(random.sample(
                            _candidate,
                            random.choice(self.element_count[elem])),
                                           reverse=True)
                        selected.append(selection)

                        for ind in selection:
                            i, j = map2list(ind, _list)
                            constraint.append([(i, j), qtk.n2Z(elem)])
                    constraint_ind = [a[0] for a in constraint]
                # end of constraint setting

            elif mode == 'stretching':
                _list = self.stretching_list
                _targ = self.stretching_range
                _dtype = float
            elif mode == 'rotation':
                _list = self.rotation_list
                _targ = self.rotation_range
                _dtype = float

            # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            # main routine to generate a random coordinate
            _vec = []
            ind = 0
            for _group, _targp in zip(_list, _targ):
                _subvec = []
                for _atom in _group:
                    if _dtype == int:
                        # element_count constraint
                        if self.element_count:
                            i, j = map2list(ind, _list)
                            if (i, j) in constraint_ind:
                                index = constraint_ind.index((i, j))
                                _subvec.append(constraint[index][1])
                            else:
                                _subvec.append(random.choice(_targp))
                        # without constraint
                        else:
                            _subvec.append(random.choice(_targp))
                    elif _dtype == float:
                        _subvec.append(random.uniform(_targp[0], _targp[1]))
                    ind += 1
                _vec.append(_subvec)
            if len(_vec) > 0:
                return _vec
Ejemplo n.º 21
0
            def getBasis():
                ######################################
                # extract basis function information #
                ######################################

                basis_dict = {"S": 0, "P": 1, "D": 2, "F": 3, "G": 4, "H": 5}

                basis_P = re.compile(r" *[0-9]+ [A-Z]  [0-9]\.[0-9]{8}")
                batom_P = re.compile(r"^  [0-9A-Za-z\-_\.]+ *\([A-Z][a-z]*\)")
                bname_P = re.compile(r"\((.*)\)")
                coord_P = re.compile(r"^ [0-9A-Za-z\.\-_]+ +[- ][0-9\.]{9,}")
                basisStr = filter(basis_P.match, data)
                batomStr = filter(batom_P.match, data)
                coordStr = filter(coord_P.match, data)

                # change 'Sulphur' to 'Sulfur' for NWChem format
                # 'Sulphur' 'Sulfur'
                def atomNameConv(old, new):
                    _matched = filter(lambda x: old in x, batomStr)
                    if _matched:
                        _matched = _matched[0]
                        _s = batomStr.index(_matched)
                        batomStr[_s] = re.sub(old, new, batomStr[_s])
                        _s = data.index(_matched)
                        data[_s] = re.sub(old, new, data[_s])

                atomNameConv('Sulphur', 'Sulfur')
                atomNameConv('Aluminium', 'Aluminum')

                _exponents = [float(filter(None, s.split(' '))\
                  [2]) for s in basisStr]
                _coefficients = [float(filter(None, s.split(' '))\
                  [3]) for s in basisStr]
                _N = [int(filter(None, s.split(' '))[0])\
                  for s in basisStr]
                _type = [filter(None, s.split(' '))[1]\
                  for s in basisStr]
                _bfnInd = [data.index(batom) for batom in batomStr]
                _bfnEndPtn = re.compile(r" Summary of \"")
                _bfnEndStr = filter(_bfnEndPtn.match, data)[0]
                _bfnInd.append(data.index(_bfnEndStr))

                _ao_keys = [0]
                for ind in range(len(_bfnInd) - 1):
                    _key = _ao_keys[-1]
                    for i in range(_bfnInd[ind] + 4, _bfnInd[ind + 1]):
                        if len(data[i]) > 1:
                            _key = _key + 1
                    _ao_keys.append(_key)
                _atoms = [getattr(pt, bname_P.match(
                  filter(None, s.split(' '))[1]).group(1).lower()).symbol\
                  for s in batomStr]
                self.type_list = [re.split(r'[\._]',
                  filter(None, s.split(' '))[0])[0].title()\
                  for s in coordStr]
                self.type_list_unique = list(
                    collections.OrderedDict.fromkeys(self.type_list))
                self.R = np.array([filter(None, s.split(' '))[1:4]\
                  for s in coordStr]).astype(float)
                self.N = len(self.R)
                self.Z = [qtk.n2Z(e) for e in self.type_list]
                self.R_bohr = 1.889725989 * self.R
                ZR = []
                for i in range(self.N):
                    vec = [self.Z[i]]
                    vec.extend(self.R[i])
                    ZR.append(vec)
                self.molecule = qtk.Molecule()
                self.molecule.build(ZR)

                _N.append(0)
                self.basis = []
                for i in range(len(self.type_list)):
                    e = self.type_list[i]
                    center = self.R_bohr[i]
                    ind = self.type_list_unique.index(e)
                    bfn_base = {}
                    bfn_base['atom'] = e
                    bfn_base['center'] = center
                    bfn_base['index'] = i
                    exp = []
                    cef = []
                    for g in range(_ao_keys[ind], _ao_keys[ind + 1]):
                        exp.append(_exponents[g])
                        cef.append(_coefficients[g])
                        if _N[g] != _N[g + 1] or g + 1 >= _ao_keys[ind + 1]:
                            bfn = copy.deepcopy(bfn_base)
                            bfn['exponents'] = copy.deepcopy(exp)
                            bfn['coefficients'] = copy.deepcopy(cef)
                            if _type[g] in basis_dict:
                                _bfnList = self.basisList(basis_dict[_type[g]])
                                for bStr in _bfnList:
                                    bfn['type'] = _type[g].lower() + bStr
                                    self.basis.append(copy.deepcopy(bfn))
                            exp = []
                            cef = []
Ejemplo n.º 22
0
  def getEt(self, name):
    out = open(name, 'r')
    data = out.readlines()
    out.close()
    E_str = filter(lambda x: 'TOTAL ENERGY' in x, data)[-1]
    Et_report = float(E_str.split()[-2])
    rst_str = filter(lambda x: 'TOTAL ENERGY' in x, data)[-1]
    r_scf_str = filter(
      lambda x: 'MAXIMUM NUMBER OF ITERATIONS FOR SC' in x, data)[-1]
    r_scf = int(filter(None, r_scf_str.split(' '))[-2])
    p1 = re.compile('^.*\d  \d\.\d{3}E-\d\d.*$')
    scf_str = filter(p1.match, data)
    if scf_str:
      self.scf_step = len(scf_str)

    R_str = filter(lambda x: 'ATOMIC COORDINATES' in x, data)[-1]
    R_ind = len(data) - data[::-1].index(R_str)
    self.molecule.N = 1
    R_more = True
    ZR = []
    while R_more:
      ind = R_ind + self.molecule.N
      zr_lst = filter(None, data[ind].split(' '))
      if len(zr_lst) == 5:
        zr = [qtk.n2Z(zr_lst[1])]
        zr.extend([float(r) for r in zr_lst[2:]])
        ZR.append(zr)
        self.molecule.N = self.molecule.N + 1
      else:
        R_more = False
    self.molecule.build(ZR, unit='bohr')
      
      
    Et_scf = float(filter(None, scf_str[-1].split(' '))[3])
    if abs(Et_report - Et_scf) > 1E-6 :
      qtk.exit("%s is not finished" % qmout)
    else:
      self.Et = Et_report
    if self.scf_step == 1 and r_scf > 1:
      self.Et = nan
    detail = []
    for scf in scf_str:
      detail.append(filter(None, scf.split(' ')))
    report_str = filter(lambda x: 'A.U.' in x, data)
    report = report_str[:len(report_str)/2]
    self.detail = {}
    for s in report:
      entry = s.split()
      if filter(lambda x: '(' in x, entry):
        entry_txt = ' '.join(entry[1:-3])
      else:
        entry_txt = ' '.join(entry[:-3])
      energy = float(entry[-2])
      self.detail[entry_txt] = energy
    self.detail['scf'] = detail
      
    ev_str1 = filter(lambda x: '(EV)' in x, data)
    ev_str2 = filter(lambda x: ' EV\n' in x, data)
    if ev_str1 and ev_str2:
      self.mo_eigenvalues = []
      self.occupation = []
      ev_start = data.index(ev_str1[0]) + 1
      ev_end = data.index(ev_str2[0])
      for i in range(ev_start, ev_end):
        s = data[i].split()
        if len(s) == 6:
          ev = [float(s[1]), float(s[4])]
          occ = [float(s[2]), float(s[5])]
          self.mo_eigenvalues.extend(ev)
          self.occupation.extend(occ)
        elif len(s) == 3:
          ev = float(s[1])
          occ = float(s[2])
          self.mo_eigenvalues.append(ev)
          self.occupation.append(occ)
      diff = np.diff(np.array(self.occupation))
      pos = diff[np.where(abs(diff) > 1)]
      mask = np.in1d(diff, pos)
      ind = np.array(range(len(diff)))
      N_state = ind[mask][0]
      self.Eg = self.mo_eigenvalues[N_state + 1] -\
                self.mo_eigenvalues[N_state]
Ejemplo n.º 23
0
  def read_xyz(self, name, **kwargs):
    xyz = open(name, 'r')
    content = xyz.readlines()
    xyz.close()
    content = [line.replace('\t', ' ') for line in content]

    prop_list = ['charge', 'celldm', 'scale', 'symmetry', 'isolated']
    for prop in prop_list:
      try:
        prop_str = filter(lambda x: prop in x, content)[0]
        prop_str = re.sub('.*:', '', prop_str)
        prop_data = prop_str.split(' ')
        prop_data = filter(None, prop_data)
        if len(prop_data) == 1:
          try:
            setattr(self, prop, float(prop_data[0]))
          except Exception as exc:
            if prop == 'symmetry' or prop == 'isolated':
              setattr(self, prop, prop_data[0].strip())
        elif len(prop_data) > 1:
          setattr(self, prop, [float(_) for _ in prop_data])
      except ValueError as exc:
        setattr(self, prop, False)
        qtk.warning("setting attribute %s with error: %s" % \
          (prop, exc))
      except:
        setattr(self, prop, False)

    # convert celldm acoording to proper symmetry is still not working 
    # universally due to abinit and vasp k-point sampling 
    # require explicity reciprocal coordinate
    #if hasattr(self, 'symmetry') and self.symmetry in ['bcc', 'fcc']:
    #  new_dm = copy.deepcopy(self.celldm)
    #  if np.linalg.norm(np.array(new_dm[3:])) < 1E-5:
    #    lattice_cube = np.array(new_dm[:3]) * np.eye(3)
    #    if self.symmetry == 'fcc':
    #      vec1 = (lattice_cube[1] + lattice_cube[2])/2
    #      vec2 = (lattice_cube[0] + lattice_cube[2])/2
    #      vec3 = (lattice_cube[0] + lattice_cube[1])/2
    #    elif self.symmetry == 'bcc':
    #      vec1 = (-lattice_cube[0] + lattice_cube[1] + lattice_cube[2])/2
    #      vec2 = ( lattice_cube[0] - lattice_cube[1] + lattice_cube[2])/2
    #      vec3 = ( lattice_cube[0] + lattice_cube[1] - lattice_cube[2])/2
    #    nv1 = vec1 / np.linalg.norm(vec1)
    #    nv2 = vec2 / np.linalg.norm(vec2)
    #    nv3 = vec3 / np.linalg.norm(vec3)
    #    new_dm = [
    #      np.linalg.norm(vec1),
    #      np.linalg.norm(vec2),
    #      np.linalg.norm(vec3),
    #      np.dot(nv2, nv3),
    #      np.dot(nv1, nv3),
    #      np.dot(nv1, nv2),
    #    ]
    #    qtk.warning(
    #      "symmetry is %s but celldm is set to cubic, reset from %s to %s"\
    #      % (self.symmetry, str(self.celldm), str(new_dm))
    #    )
    #    self.celldm = new_dm
    
    if not self.charge:
      self.charge = 0
    if self.celldm or self.scale:
      self.periodic = True
    if self.celldm:
       assert len(self.celldm) == 6

    self.N = int(content[0])
    prop_list = content[1]
    try:
        self.prop_list = np.array(prop_list.split(' ')).astype(float)
    except:
        self.prop_list = prop_list
    coord_list = content[2 : self.N + 2]
    coord = [filter(None,[a for a in entry.replace("\n", '').split(' ')]) 
             for entry in coord_list]
    type_list = list(np.array(coord)[:,0])
    self.type_list = [str(elem) for elem in type_list]
    self.Z = [qtk.n2Z(elem) for elem in self.type_list]
    self.Z = np.array(self.Z)
    self.R = np.array(coord)[:,1:4].astype(float)

    self.box = False
    if self.celldm:
      self.periodic = True
      angle = self.celldm[3:]
      angle_sum = sum([abs(entry) for entry in angle])
      if angle_sum == 0:
        self.box = self.celldm[:3]

      if not self.isolated:
        self.R_scale = copy.deepcopy(self.R)
        self.R = qtk.fractional2xyz(self.R_scale, self.celldm)