示例#1
0
def calc_ao(qc,
            drv=None,
            otype=None,
            ofid=None,
            numproc=None,
            slice_length=None):
    '''Computes and saves all atomic orbital or a derivative thereof.
  
  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec, qc.mo_spec :
      See :ref:`Central Variables` for details.
  drv : string or list of strings {None,'x','y', 'z', 'xx', 'xy', ...}, optional
      If not None, a derivative calculation of the atomic orbitals 
      is requested.
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    numproc : int, optional
      Specifies number of subprocesses for multiprocessing. 
      If None, uses the value from :mod:`options.numproc`.
    slice_length : int, optional
      Specifies the number of points per subprocess.
      If None, uses the value from :mod:`options.slice_length`.
    
  **Returns:**  
    ao_list : numpy.ndarray, shape=((NAO,) + N)
      Contains the computed NAO atomic orbitals on a grid. 
  '''

    slice_length = options.slice_length if slice_length is None else slice_length
    numproc = options.numproc if numproc is None else numproc
    datalabels = qc.ao_spec.get_labels()

    ao_list = core.rho_compute(qc,
                               calc_ao=True,
                               drv=drv,
                               slice_length=options.slice_length,
                               numproc=options.numproc)

    if otype is None:
        return ao_list

    if ofid is None:
        ofid = '%s_AO' % (options.outputname)

    if not options.no_output:
        output_written = main_output(ao_list,
                                     qc,
                                     outputname=ofid,
                                     datalabels=qc.ao_spec.get_labels(),
                                     otype=otype,
                                     drv=drv)

    return ao_list
示例#2
0
def get_ao(x):
  ao_list = core.ao_creator(global_args['geo_spec'],
                            [global_args['ao_spec'][int(x)]],
                            drv=global_args['drv'])
  
  if global_args['otype'] is not None:
    drv = global_args['drv']
    comments = '%03d.lxlylz=%s,at=%d' %(x,
                                         global_args['ao_spec'][x]['exp_list'][0],
                                         global_args['ao_spec'][x]['atom'])
    
    output.main_output(ao_list[0] if drv is None else ao_list,
                       global_args['geo_info'],
                       global_args['geo_spec'],
                       comments=comments,
                       outputname='%s_AO_%03d' % (global_args['ofid'],x),
                       otype=global_args['otype'],
                       omit=['h5','vmd','mayavi'],
                       drv = None if drv is None else [drv])
  return ao_list
示例#3
0
def run_orbkit(use_qc=None, check_options=True, standalone=False):
    '''Controls the execution of all computational tasks.
  
  **Parameters:**
  
  use_qc : QCinfo, optional
    If not None, the reading of a quantum chemistry output is omitted and
    the given QCinfo class is used for all computational tasks. 
    (See :ref:`Central Variables` in the manual for details on QCinfo.) 
  check_options : bool, optional
    If True, the specified options will be validated. 
  
  **Returns:**
  
  data : type and shape depend on the options.
    Contains orbkit's output. 
    See :ref:`High-Level Interface` in the manual for details.
  '''
    # Set some global variables
    global qc

    # Display program information
    display(lgpl_short)

    # Check for the correctness of orbkit.options
    if check_options:
        display('Checking orbkit.options...\n')
        options.check_options(display=display,
                              interactive=False,
                              info=True,
                              check_io=(use_qc is None))

    # Measurement of required execution time
    t = [time.time()]

    # Do we need to read out the info of all MOs?
    if (options.mo_set or options.calc_mo) is not False:
        options.all_mo = True

    if use_qc is None:
        # Read the input file
        qc = read.main_read(options.filename,
                            itype=options.itype,
                            all_mo=options.all_mo,
                            spin=options.spin,
                            cclib_parser=options.cclib_parser)
    else:
        # Use a user defined QCinfo class.
        qc = use_qc

    display('\nSetting up the grid...')
    if options.grid_file is not None:
        # Read the grid from an external file
        grid.read(options.grid_file)
    elif options.adjust_grid is not None:
        # Adjust the grid to geo_spec
        extend, step = options.adjust_grid
        grid.adjust_to_geo(qc, extend=extend, step=step)
    elif options.random_grid:
        # Create a randomized grid
        grid.random_grid(qc.geo_spec)

    # Initialize grid
    grid.grid_init(is_vector=options.is_vector)
    if options.is_vector:
        grid.is_regular = False
    display(grid.get_grid())  # Display the grid

    if not grid.is_regular and options.center_grid is not None:
        raise IOError(
            'The option --center is only supported for regular grids.')
    elif options.center_grid is not None:
        atom = grid.check_atom_select(options.center_grid,
                                      qc.geo_info,
                                      qc.geo_spec,
                                      interactive=True,
                                      display=display)
        # Center the grid to a specific atom and (0,0,0) if requested
        grid.center_grid(qc.geo_spec[atom - 1], display=display)

    if check_options or standalone:
        options.check_grid_output_compatibilty()

    t.append(time.time())  # A new time step

    # The calculation of all AOs (--calc_ao)
    if options.calc_ao != False:
        data = extras.calc_ao(qc, drv=options.drv, otype=options.otype)

        t.append(time.time())  # Final time
        good_bye_message(t)
        return data

    # The calculation of selected MOs (--calc_mo) or
    # the density formed by selected MOs (--mo_set)
    if (options.mo_set or options.calc_mo) != False:
        # What should the program do?
        if options.calc_mo != False:
            fid_mo_list = options.calc_mo
        elif options.mo_set != False:
            fid_mo_list = options.mo_set

        # Call the function for actual calculation
        if options.calc_mo != False:
            data = extras.calc_mo(qc,
                                  fid_mo_list,
                                  drv=options.drv,
                                  otype=options.otype)
        elif options.mo_set != False:
            data = extras.mo_set(qc,
                                 fid_mo_list,
                                 drv=options.drv,
                                 laplacian=options.laplacian,
                                 otype=options.otype)

        t.append(time.time())  # Final time
        good_bye_message(t)
        return data

    if options.gross_atomic_density is not None:
        atom = options.gross_atomic_density
        rho_atom = extras.numerical_mulliken_charges(atom, qc)

        if not grid.is_vector:
            mulliken_num = rho_atom[1]
            rho_atom = rho_atom[0]

        if not options.no_output:
            fid = '%s.h5' % options.outputname
            display('\nSaving to Hierarchical Data Format file (HDF5)...' +
                    '\n\t%(o)s' % {'o': fid})
            output.hdf5_write(fid,
                              mode='w',
                              gname='',
                              atom=core.numpy.array(atom),
                              geo_info=qc.geo_info,
                              geo_spec=qc.geo_spec,
                              gross_atomic_density=rho_atom,
                              x=grid.x,
                              y=grid.y,
                              z=grid.z)
            if not options.is_vector:
                output.hdf5_write(
                    fid,
                    mode='a',
                    gname='/numerical_mulliken_population_analysis',
                    **mulliken_num)

        t.append(time.time())
        good_bye_message(t)
        return rho_atom

    if options.mo_tefd is not None:
        mos = options.mo_tefd
        ao_list = core.ao_creator(qc.geo_spec, qc.ao_spec)
        mo_tefd = []
        index = []
        for i, j in mos:
            mo_tefd.append([])
            index.append([])
            for ii_d in options.drv:
                display('\nMO-TEFD: %s->%s %s-component' % (i, j, ii_d))
                tefd = extras.mo_transition_flux_density(i,
                                                         j,
                                                         qc,
                                                         drv=ii_d,
                                                         ao_list=ao_list)
                mo_tefd[-1].append(tefd)
                index[-1].append('%s->%s:%s' % (i, j, ii_d))

        if not options.no_output:
            from numpy import array
            fid = '%s.h5' % options.outputname
            display('\nSaving to Hierarchical Data Format file (HDF5)...' +
                    '\n\t%(o)s' % {'o': fid})
            HDF5_File = output.hdf5_open(fid, mode='w')
            data = {
                'geo_info': array(qc.geo_info),
                'geo_spec': array(qc.geo_spec),
                'mo_tefd:info': array(index),
                'mo_tefd': array(mo_tefd),
                'x': grid.x,
                'y': grid.y,
                'z': grid.z
            }
            output.hdf5_append(data, HDF5_File, name='')
            HDF5_File.close()

        t.append(time.time())
        good_bye_message(t)
        return mo_tefd

    t.append(time.time())  # A new time step

    # Compute the (derivative of the) electron density
    if options.no_slice:
        data = core.rho_compute_no_slice(qc,
                                         drv=options.drv,
                                         laplacian=options.laplacian,
                                         return_components=False)

    else:
        data = core.rho_compute(qc,
                                drv=options.drv,
                                slice_length=options.slice_length,
                                laplacian=options.laplacian,
                                numproc=options.numproc)
    if options.drv is None:
        rho = data
    elif options.laplacian:
        rho, delta_rho, laplacian_rho = data
    else:
        rho, delta_rho = data

    # Compute the reduced electron density if requested
    if options.z_reduced_density:
        if grid.is_vector:
            display('\nSo far, reducing the density is not supported for ' +
                    'vector grids.\nSkipping the reduction...\n')
        elif options.drv is not None:
            display(
                '\nSo far, reducing the density is not supported for ' +
                'the derivative of the density.\nSkipping the reduction...\n')
        else:
            from scipy import integrate
            display('\nReducing the density with respect to the z-axis.\n')
            rho = integrate.simps(rho,
                                  grid.x,
                                  dx=grid.delta_[0],
                                  axis=0,
                                  even='avg')
            rho = integrate.simps(rho,
                                  grid.y,
                                  dx=grid.delta_[1],
                                  axis=0,
                                  even='avg')

    t.append(time.time())  # A new time step

    # Generate the output requested
    if not options.no_output:
        output_written = output.main_output(rho,
                                            qc.geo_info,
                                            qc.geo_spec,
                                            outputname=options.outputname,
                                            otype=options.otype,
                                            data_id='rho',
                                            omit=['vmd', 'mayavi'],
                                            mo_spec=qc.mo_spec)
        if options.drv is not None:
            output_written.extend(
                output.main_output(delta_rho,
                                   qc.geo_info,
                                   qc.geo_spec,
                                   outputname=options.outputname,
                                   otype=options.otype,
                                   data_id='delta_rho',
                                   omit=['vmd', 'mayavi'],
                                   mo_spec=qc.mo_spec,
                                   drv=options.drv))
        if options.laplacian:
            output_written.extend(
                output.main_output(laplacian_rho,
                                   qc.geo_info,
                                   qc.geo_spec,
                                   outputname=options.outputname +
                                   '_laplacian',
                                   otype=options.otype,
                                   data_id='laplacian_rho',
                                   omit=['vmd', 'mayavi'],
                                   mo_spec=qc.mo_spec))
        if 'vmd' in options.otype:
            # Create VMD network
            display('\nCreating VMD network file...' +
                    '\n\t%(o)s.vmd' % {'o': options.outputname})
            cube_files = []
            for i in output_written:
                if i.endswith('.cb'):
                    cube_files.append(i)
            output.vmd_network_creator(options.outputname,
                                       cube_files=cube_files)

    t.append(time.time())  # Final time

    good_bye_message(t)

    if 'mayavi' in options.otype:
        plt_data = [rho]
        datalabels = ['rho']
        if options.drv is not None:
            plt_data.extend(delta_rho)
            datalabels.extend(
                ['d/d%s of %s' % (ii_d, 'rho') for ii_d in options.drv])
        if options.laplacian:
            plt_data.append(laplacian_rho)
            datalabels.append('laplacian of rho')
        output.main_output(plt_data,
                           qc.geo_info,
                           qc.geo_spec,
                           otype='mayavi',
                           datalabels=datalabels)

    # Return the computed data, i.e., rho for standard, and (rho,delta_rho)
    # for derivative calculations. For laplacian (rho,delta_rho,laplacian_rho)
    return data
示例#4
0
def calc_jmo(qc,
             ij,
             drv=['x', 'y', 'z'],
             numproc=1,
             otype=None,
             ofid='',
             **kwargs):
    '''Calculate one component (e.g. drv='x') of the 
  transition electoronic flux density between the 
  molecular orbitals i and j.
  
  .. math::
  
        moTEFD_{i,j}(r) = <mo_i|\delta(r-r')\\nabla_x|mo_j>
    
  **Parameters:**
  
     i: int
        index of the first mo (Bra)
     j: int
        index of the second mo (Ket)
     drv: {0,1,2,'x','y','z'}
        The desired component of the vector field of the 
        transition electoronic flux density

  **Returns:**
  
     mo_tefd : numpy.ndarray
  '''
    ij = numpy.asarray(ij)
    if ij.ndim == 1 and len(ij) == 2:
        ij.shape = (1, 2)
    assert ij.ndim == 2
    assert ij.shape[1] == 2

    u, indices = numpy.unique(ij, return_inverse=True)
    indices.shape = (-1, 2)

    mo_spec = qc.mo_spec[u]
    qc_select = qc.copy()
    qc_select.mo_spec = mo_spec
    labels = mo_spec.get_labels(format='short')

    mo_matrix = core.calc_mo_matrix(qc_select,
                                    drv=drv,
                                    numproc=numproc,
                                    **kwargs)
    jmo = numpy.zeros((len(drv), len(indices)) + grid.get_shape())
    datalabels = []
    for n, (i, j) in enumerate(indices):
        jmo[:, n] = -0.5 * (mo_matrix[:, i, j] - mo_matrix[:, j, i])
        datalabels.append('j( %s , %s )' % (labels[i], labels[j]))

    if not options.no_output:
        output_written = main_output(jmo,
                                     qc,
                                     outputname=ofid,
                                     datalabels=datalabels,
                                     otype=otype,
                                     drv=drv)
    return jmo
示例#5
0
def calc_mo(qc,
            fid_mo_list,
            drv=None,
            otype=None,
            ofid=None,
            numproc=None,
            slice_length=None):
    '''Calculates and saves the selected molecular orbitals or the derivatives thereof.
  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec, qc.mo_spec :
      See :ref:`Central Variables` for details.
    fid_mo_list : str
      Specifies the filename of the molecular orbitals list or list of molecular
      orbital labels (cf. :mod:`orbkit.read.mo_select` for details). 
      If fid_mo_list is 'all_mo', creates a list containing all molecular orbitals.
    drv : string or list of strings {None,'x','y', 'z', 'xx', 'xy', ...}, optional
      If not None, a derivative calculation of the molecular orbitals 
      is requested.
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    numproc : int, optional
      Specifies number of subprocesses for multiprocessing. 
      If None, uses the value from :mod:`options.numproc`.
    slice_length : int, optional
      Specifies the number of points per subprocess.
      If None, uses the value from :mod:`options.slice_length`.
    
  **Returns:**
    mo_list : numpy.ndarray, shape=((NMO,) + N)
      Contains the NMO=len(qc.mo_spec) molecular orbitals on a grid.
  '''
    mo_spec = qc.mo_spec[fid_mo_list]
    qc_select = qc.copy()
    qc_select.mo_spec = mo_spec

    slice_length = options.slice_length if slice_length is None else slice_length
    numproc = options.numproc if numproc is None else numproc

    # Calculate the AOs and MOs
    mo_list = core.rho_compute(qc_select,
                               calc_mo=True,
                               drv=drv,
                               slice_length=slice_length,
                               numproc=numproc)

    if otype is None:
        return mo_list

    if ofid is None:
        if '@' in options.outputname:
            outputname, group = options.outputname.split('@')
        else:
            outputname, group = options.outputname, ''
        outputname, autootype = os.path.splitext(outputname)
        ofid = '%s_MO%s@%s' % (outputname, autootype, group)
    if not options.no_output:
        output_written = main_output(mo_list,
                                     qc_select,
                                     outputname=ofid,
                                     datalabels=qc_select.mo_spec.get_labels(),
                                     otype=otype,
                                     drv=drv)

    return mo_list
示例#6
0
def mo_set(qc,
           fid_mo_list,
           drv=None,
           laplacian=None,
           otype=None,
           ofid=None,
           return_all=True,
           numproc=None,
           slice_length=None):
    '''Calculates and saves the density or the derivative thereof 
  using selected molecular orbitals.
  
  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec, qc.mo_spec :
      See :ref:`Central Variables` for details.
    fid_mo_list : str
      Specifies the filename of the molecular orbitals list or list of molecular
      orbital labels (cf. :mod:`orbkit.orbitals.MOClass.select` for details). 
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    drv : string or list of strings {None,'x','y', 'z', 'xx', 'xy', ...}, optional
      If not None, a derivative calculation is requested.
    return_all : bool
      If False, no data will be returned.
    numproc : int, optional
      Specifies number of subprocesses for multiprocessing. 
      If None, uses the value from :mod:`options.numproc`.
    slice_length : int, optional
      Specifies the number of points per subprocess.
      If None, uses the value from :mod:`options.slice_length`.
  
  **Returns:**
    datasets : numpy.ndarray, shape=((NSET,) + N)
      Contains the NSET molecular orbital sets on a grid.
    delta_datasets : numpy.ndarray, shape=((NSET,NDRV) + N)
      Contains the NDRV NSET molecular orbital set on a grid. This is only 
      present if derivatives are requested.
  '''

    #Can be an mo_spec or a list of mo_spec
    # For later iteration we'll make it into a list here if it is not
    mo_info_list = qc.mo_spec.select(fid_mo_list, flatten_input=False)

    drv = options.drv if drv is None else drv
    laplacian = options.laplacian if laplacian is None else laplacian
    slice_length = options.slice_length if slice_length is None else slice_length
    numproc = options.numproc if numproc is None else numproc

    if ofid is None:
        ofid = options.outputname

    datasets = []
    datalabels = []
    delta_datasets = []
    delta_datalabels = []
    cube_files = []

    for i_file, mo_info in enumerate(mo_info_list):
        qc_select = qc.copy()
        qc_select.mo_spec = mo_info
        label = 'mo_set:' + mo_info.selection_string
        display('\nStarting with the molecular orbital list \n\t' + label +
                '\n\t(Only regarding existing and occupied mos.)\n')

        data = core.rho_compute(qc_select,
                                drv=drv,
                                laplacian=laplacian,
                                slice_length=slice_length,
                                numproc=numproc)

        if drv is None:
            rho = data
            delta_datasets = numpy.zeros((0, ) + rho.shape)
        elif laplacian:
            rho, delta_rho, laplacian_rho = data
            delta_datasets.extend(delta_rho)
            delta_datasets.append(laplacian_rho)
            delta_datalabels.extend(
                ['d^2/d%s^2 %s' % (i, label) for i in 'xyz'])
            delta_datalabels.append('laplacian_of_' + label)
        else:
            rho, delta_rho = data
            delta_datasets.extend(delta_rho)
            delta_datalabels.extend(['d/d%s %s' % (i, label) for i in drv])

        datasets.append(rho)
        datalabels.append(label)

    datasets = numpy.array(datasets)
    delta_datasets = numpy.array(delta_datasets)
    delta_datalabels.append('mo_set')
    data = numpy.append(datasets, delta_datasets, axis=0)

    if not options.no_output:
        output_written = main_output(data,
                                     qc,
                                     outputname=ofid,
                                     datalabels=datalabels + delta_datalabels,
                                     otype=otype,
                                     drv=None)
    return data
示例#7
0
def calc_mo(qc, fid_mo_list, drv=None, otype=None, ofid=None,
            numproc=None, slice_length=None):
  '''Calculates and saves the selected molecular orbitals or the derivatives thereof.

  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec, qc.mo_spec :
      See :ref:`Central Variables` for details.
    fid_mo_list : str
      Specifies the filename of the molecular orbitals list or list of molecular
      orbital labels (cf. :mod:`orbkit.read.mo_select` for details). 
      If fid_mo_list is 'all_mo', creates a list containing all molecular orbitals.
    drv : int or string, {None, 'x', 'y', 'z', 0, 1, 2}, optional
      If not None, a derivative calculation of the atomic orbitals 
      is requested.
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    numproc : int, optional
      Specifies number of subprocesses for multiprocessing. 
      If None, uses the value from :mod:`options.numproc`.
    slice_length : int, optional
      Specifies the number of points per subprocess.
      If None, uses the value from :mod:`options.slice_length`.
    
  **Returns:**
    mo_list : numpy.ndarray, shape=((NMO,) + N)
      Contains the NMO=len(qc.mo_spec) molecular orbitals on a grid.
    mo_info : dict 
      Contains information of the selected molecular orbitals and has following Members:
        :mo: - List of molecular orbital labels.
        :mo_ii: - List of molecular orbital indices.
        :mo_spec: - Selected elements of mo_spec. See :ref:`Central Variables` for details.
        :mo_in_file: - List of molecular orbital labels within the fid_mo_list file.
        :sym_select: - If True, symmetry labels have been used. 
      
  '''
  mo_info = mo_select(qc.mo_spec, fid_mo_list, strict=True)
  qc_select = qc.todict()
  qc_select['mo_spec'] = mo_info['mo_spec']
  
  slice_length = options.slice_length if slice_length is None else slice_length
  numproc = options.numproc if numproc is None else numproc
  # Calculate the AOs and MOs 
  mo_list = core.rho_compute(qc_select,
                             calc_mo=True,
                             drv=drv,
                             slice_length=slice_length,
                             numproc=numproc)
  
  if otype is None:
    return mo_list, mo_info
  
  if ofid is None:
    ofid = '%s_MO' % (options.outputname)
  
  if not options.no_output:
    if 'h5' in otype:    
      output.main_output(mo_list,qc.geo_info,qc.geo_spec,data_id='MO',
                    outputname=ofid,
                    mo_spec=qc_select['mo_spec'],drv=drv,is_mo_output=True)
    # Create Output     
    cube_files = []
    for i,j in enumerate(qc_select['mo_spec']):
      outputname = '%s_%s' % (ofid,mo_info['mo'][i])
      comments = ('%s,Occ=%.1f,E=%+.4f' % (mo_info['mo'][i],
                                           j['occ_num'],
                                           j['energy']))
      index = numpy.index_exp[:,i] if drv is not None else i
      output_written = output.main_output(mo_list[index],
                                      qc.geo_info,qc.geo_spec,
                                      outputname=outputname,
                                      comments=comments,
                                      otype=otype,omit=['h5','vmd','mayavi'],
                                      drv=drv)
      
      for i in output_written:
        if i.endswith('.cb'):
          cube_files.append(i)
    
    if 'vmd' in otype and cube_files != []:
      display('\nCreating VMD network file...' +
                      '\n\t%(o)s.vmd' % {'o': ofid})
      output.vmd_network_creator(ofid,cube_files=cube_files)
  if 'mayavi' in otype:
    datalabels = ['MO %(sym)s, Occ=%(occ_num).2f, E=%(energy)+.4f E_h' % 
                  i for i in qc_select['mo_spec']]
    if drv is not None:
      tmp = []
      for i in drv:
        for j in datalabels:
          tmp.append('d/d%s of %s' % (i,j))
      datalabels = tmp
    data = mo_list.reshape((-1,) + grid.get_shape())
    
    output.main_output(data,qc.geo_info,qc.geo_spec,
                       otype='mayavi',datalabels=datalabels)
  
  return mo_list, mo_info
示例#8
0
def mo_set(qc, fid_mo_list, drv=None, laplacian=None,
           otype=None, ofid=None, return_all=True,
           numproc=None, slice_length=None):
  '''Calculates and saves the density or the derivative thereof 
  using selected molecular orbitals.
  
  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec, qc.mo_spec :
      See :ref:`Central Variables` for details.
    fid_mo_list : str
      Specifies the filename of the molecular orbitals list or list of molecular
      orbital labels (cf. :mod:`orbkit.read.mo_select` for details). 
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    drv : int or string, {None, 'x', 'y', 'z', 0, 1, 2}, optional
      If not None, a derivative calculation of the atomic orbitals 
      is requested.
    return_all : bool
      If False, no data will be returned.
    numproc : int, optional
      Specifies number of subprocesses for multiprocessing. 
      If None, uses the value from :mod:`options.numproc`.
    slice_length : int, optional
      Specifies the number of points per subprocess.
      If None, uses the value from :mod:`options.slice_length`.
  
  **Returns:**
    datasets : numpy.ndarray, shape=((NSET,) + N)
      Contains the NSET molecular orbital sets on a grid.
    delta_datasets : numpy.ndarray, shape=((NSET,NDRV) + N)
      Contains the NDRV NSET molecular orbital set on a grid. This is only 
      present if derivatives are requested.
    mo_info : dict 
      Contains information of the selected molecular orbitals and has following Members:
        :mo: - List of molecular orbital labels.
        :mo_ii: - List of molecular orbital indices.
        :mo_spec: - Selected elements of mo_spec. See :ref:`Central Variables` for details.
        :mo_in_file: - List of molecular orbital labels within the fid_mo_list file.
        :sym_select: - If True, symmetry labels have been used. 
  '''

  mo_info = mo_select(qc.mo_spec, fid_mo_list, strict=False)
  qc_select = qc.todict()
    
  drv = options.drv if drv is None else drv
  laplacian = options.laplacian if laplacian is None else laplacian
  slice_length = options.slice_length if slice_length is None else slice_length
  numproc = options.numproc if numproc is None else numproc
  
  if ofid is None:
    ofid = options.outputname
  if 'h5' in otype and os.path.exists('%s.h5' % ofid):
    raise IOError('%s.h5 already exists!' % ofid)
  
  datasets = []
  delta_datasets = []
  cube_files = []
  for i_file,j_file in enumerate(mo_info['mo_in_file']):
    display('Starting with the %d. element of the molecular orbital list (%s)...\n\t' % 
                (i_file+1,fid_mo_list) + str(j_file) + 
                '\n\t(Only regarding existing and occupied mos.)\n')
    
    qc_select['mo_spec'] = []
    for i_mo,j_mo in enumerate(mo_info['mo']):
      if j_mo in j_file:
        if mo_info['sym_select']: 
          ii_mo = numpy.argwhere(mo_info['mo_ii'] == j_mo)
        else: 
          ii_mo = i_mo
        qc_select['mo_spec'].append(mo_info['mo_spec'][int(ii_mo)])
    
    data = core.rho_compute(qc_select,
                            drv=drv,
                            laplacian=laplacian,
                            slice_length=slice_length,
                            numproc=numproc)
    datasets.append(data)
    if drv is None:
      rho = data
    elif laplacian:
      rho, delta_rho, laplacian_rho = data 
      delta_datasets.extend(delta_rho)
      delta_datasets.append(laplacian_rho)
    else:
      rho, delta_rho = data
      delta_datasets.append(delta_rho)
    
    if options.z_reduced_density:
      if grid.is_vector:
        display('\nSo far, reducing the density is not supported for vector grids.\n')
      elif drv is not None:
        display('\nSo far, reducing the density is not supported for the derivative of the density.\n')
      else:
        rho = integrate.simps(rho, grid.x, dx=grid.delta_[0], axis=0, even='avg')
        rho = integrate.simps(rho, grid.y, dx=grid.delta_[1], axis=0, even='avg')
    
    if not options.no_output:
      if 'h5' in otype:
        display('Saving to Hierarchical Data Format file (HDF5)...')
        group = '/mo_set:%03d' % (i_file+1)	
        display('\n\t%s.h5 in the group "%s"' % (ofid,group))	
        output.HDF5_creator(rho,ofid,qc.geo_info,qc.geo_spec,data_id='rho',
                            mode='w',group=group,mo_spec=qc_select['mo_spec'])
        if drv is not None:
          for i,j in enumerate(drv):
            data_id = 'rho_d%s' % j
            output.HDF5_creator(delta_rho[i],ofid,qc.geo_info,qc.geo_spec,
                                data_id=data_id,data_only=True,mode='a',
                                group=group,mo_spec=qc_select['mo_spec'])
          if laplacian:
            data_id = 'rho_laplacian' 
            output.HDF5_creator(laplacian_rho,ofid,qc.geo_info,qc.geo_spec,
                                data_id=data_id,data_only=True,mode='a',
                                group=group,mo_spec=qc_select['mo_spec'])
            
      fid = '%s_%03d' % (ofid, i_file+1) 
      cube_files.append('%s.cb' % fid)
      comments = ('mo_set:'+','.join(j_file))
      output.main_output(rho,qc.geo_info,qc.geo_spec,outputname=fid,
                         otype=otype,omit=['h5','vmd','mayavi'],
                         comments=comments)
      if drv is not None:
        for i,j in enumerate(drv):
          fid = '%s_%03d_d%s' % (ofid, i_file+1, j) 
          cube_files.append('%s.cb' % fid)
          comments = ('d%s_of_mo_set:' % j + ','.join(j_file))
          output.main_output(delta_rho[i],qc.geo_info,qc.geo_spec,outputname=fid,
                             otype=otype,omit=['h5','vmd','mayavi'],
                             comments=comments)  
        if laplacian:
          fid = '%s_%03d_laplacian' % (ofid, i_file+1) 
          cube_files.append('%s.cb' % fid)
          comments = ('laplacian_of_mo_set:' + ','.join(j_file))
          output.main_output(laplacian_rho,qc.geo_info,qc.geo_spec,outputname=fid,
                             otype=otype,omit=['h5','vmd','mayavi'],
                             comments=comments)  
          
  if 'vmd' in otype and cube_files != []:
      display('\nCreating VMD network file...' +
                      '\n\t%(o)s.vmd' % {'o': ofid})
      output.vmd_network_creator(ofid,cube_files=cube_files)
   
  datasets = numpy.array(datasets)
  if drv is None:
    if 'mayavi' in otype:
      output.main_output(datasets,qc.geo_info,qc.geo_spec,
                       otype='mayavi',datalabels=mo_info['mo_in_file'])
    return datasets, mo_info
  else:
    delta_datasets = numpy.array(delta_datasets)
    if 'mayavi' in otype:
      datalabels = []
      for i in mo_info['mo_in_file']:
        datalabels.extend(['d/d%s of %s' % (j,i) for j in drv])
        if laplacian:
          datalabels.append('laplacian of %s' % i)
      output.main_output(delta_datasets.reshape((-1,) + grid.get_shape()),
                         qc.geo_info,qc.geo_spec,otype='mayavi',datalabels=datalabels)
    return datasets, delta_datasets, mo_info
示例#9
0
def calc_ao(qc, drv=None, otype=None, ofid=None):  
  '''Computes and saves all atomic orbital or a derivative thereof.
  
  **Parameters:**
   
    qc.geo_spec, qc.geo_info, qc.ao_spec :
      See :ref:`Central Variables` for details.
    otype : str or list of str, optional
      Specifies output file type. See :data:`otypes` for details.
    ofid : str, optional
      Specifies output file name. If None, the filename will be based on
      :mod:`orbkit.options.outputname`.
    drv : int or string, {None, 'x', 'y', 'z', 'xx', 'xy', ...}, optional
      If not None, a derivative calculation of the atomic orbitals 
      is requested.
    
  **Returns:**    
  
    ao_list : numpy.ndarray, shape=((NAO,) + N)
      Contains the computed NAO atomic orbitals on a grid. Is only returned, if
      otype is None.
  '''
  from omp_functions import run
  
  if ofid is None:
    ofid = options.outputname
  dstr = '' if drv is None else '_d%s' % drv
  
  ao_spec = []
  lxlylz = []
  datalabels = []
  for sel_ao in range(len(qc.ao_spec)):
    if 'exp_list' in qc.ao_spec[sel_ao].keys():
      l = qc.ao_spec[sel_ao]['exp_list']
    else:
      l = core.exp[core.lquant[qc.ao_spec[sel_ao]['type']]]
    lxlylz.extend(l)
    for i in l:
      ao_spec.append(qc.ao_spec[sel_ao].copy())
      ao_spec[-1]['exp_list'] = [i]
      datalabels.append('lxlylz=%s,atom=%d' %(i,ao_spec[-1]['atom']))
  
  global_args = {'geo_spec':qc.geo_spec,
                 'geo_info':qc.geo_info,
                 'ao_spec':ao_spec,
                 'drv':drv,
                 'x':grid.x,
                 'y':grid.y,
                 'z':grid.z,
                 'is_vector':grid.is_vector,
                 'otype':otype,
                 'ofid':ofid}
  display('Starting the computation of the %d atomic orbitals'%len(ao_spec)+
         (' using %d subprocesses.' % options.numproc if options.numproc > 1 
          else '.' )
          )
  ao = run(get_ao,x=numpy.arange(len(ao_spec)).reshape((-1,1)),
           numproc=options.numproc,display=display,
           initializer=initializer,global_args=global_args)
    
  if otype is None or 'h5' in otype or 'mayavi' in otype:   
    ao_list = []
    for i in ao:
      ao_list.extend(i)      
    ao_list = numpy.array(ao_list)
    if otype is None or options.no_output:
      return ao_list
    
    if 'h5' in otype:
      import h5py
      fid = '%s_AO%s.h5' % (ofid,dstr)
      display('Saving to Hierarchical Data Format file (HDF5)...\n\t%s' % fid)
      output.hdf5_write(fid,mode='w',gname='general_info',
                        x=grid.x,y=grid.y,z=grid.z,
                        geo_info=qc.geo_info,geo_spec=qc.geo_spec,
                        lxlylz=numpy.array(lxlylz,dtype=numpy.int64),
                        aolabels=numpy.array(datalabels),
                        grid_info=numpy.array(grid.is_vector,dtype=int))      
      for f in output.hdf5_open(fid,mode='a'):
        output.hdf5_append(ao_spec,f,name='ao_spec')
        output.hdf5_append(ao_list,f,name='ao_list')
      
    if 'mayavi' in otype:
      output.main_output(ao_list,qc.geo_info,qc.geo_spec,
                         otype='mayavi',datalabels=datalabels)

  if 'vmd' in otype and options.vector is None:
    fid = '%s_AO%s' % (ofid,dstr)
    display('\nCreating VMD network file...' +
                    '\n\t%(o)s.vmd' % {'o': fid})
    output.vmd_network_creator(fid,
                            cube_files=['%s_AO%s_%03d.cb' % (ofid,
                                        dstr,x) for x in range(len(ao_spec))])
# Run orbkit
rho,delta_rho = core.rho_compute(qc,drv=['x','y','z'],numproc=4)

# Compute the reduced density gradient 
from numpy import sqrt,pi
s = (1./(2*(3*pi**2)**(1/3.)) * sqrt((delta_rho**2).sum(axis=0))/(rho**(4/3.)))

# Apply a density cutoff, i.e., consider only values for rho < 0.05 a.u.
s[rho>0.05] = 1e3

# Write a cube file and vmd script for the reduced density gradient 
output.main_output(s,
                   qc.geo_info,                 # atomic information
                   qc.geo_spec,                 # atomic coordinates
                   outputname='reduced_drho',
                   otype=['cb','vmd'],
                   iso=(-0.5,0.5)               # isocontour value of s = 0.5 a.u.
                   )

'''
Classify the interaction types
using the second derivatives of the density 
("the three eigenvalues of the electronic Hessian matrix")
'''
# Compute the second derivatives of the density
rho,delta2_rho = core.rho_compute(qc,drv=['xx','yy','zz'],numproc=4)

# Sort the three components of the derivatives
# The sign of the second value determines, if the interaction is bonding (negative)
# non-bonding (positive)
of the gross atomic density.

Hint: Use the VMD script file (ch2o.vmd) for depicting the results.
'''

from orbkit import read, grid, extras, output, atomic_populations, display

# Open molden file and read parameters
qc = read.main_read('ch2o.molden', itype='molden')

# Perform a Mulliken population analysis and write the output to a PDB file
pop = atomic_populations.mulliken(qc)
output.pdb_creator(qc.geo_info,
                   qc.geo_spec,
                   filename='ch2o',
                   charges=pop['charge'])

# Initialize the grid
display.display('\nSetting up the grid...')
grid.adjust_to_geo(qc, extend=5.0, step=0.1)
grid.grid_init()
display.display(grid.get_grid())

# Compute and save the gross atomic density of the C atom
rho_atom = extras.gross_atomic_density(1, qc)
output.main_output(rho_atom[0],
                   qc.geo_info,
                   qc.geo_spec,
                   outputname='ch2o',
                   otype='cb')
示例#12
0
文件: main.py 项目: wangvei/orbkit
def run_orbkit(use_qc=None,check_options=True,standalone=False):
  '''Controls the execution of all computational tasks.
  
  **Parameters:**
  
  use_qc : QCinfo, optional
    If not None, the reading of a quantum chemistry output is omitted and
    the given QCinfo class is used for all computational tasks. 
    (See :ref:`Central Variables` in the manual for details on QCinfo.) 
  check_options : bool, optional
    If True, the specified options will be validated. 
  
  **Returns:**
  
  data : type and shape depend on the options.
    Contains orbkit's output. 
    See :ref:`High-Level Interface` in the manual for details.
  '''
  # Set some global variables
  global qc
  
  # Display program information
  display(lgpl_short)
  
  # Check for the correctness of orbkit.options
  if check_options:
    display('Checking orbkit.options...\n')
    options.check_options(display=display,
                          interactive=False,
                          info=True,check_io=(use_qc is None))
  
  # Measurement of required execution time
  t=[time.time()]
  
  # Do we need to read out the info of all MOs?  
  if (options.mo_set or options.calc_mo) is not False: 
    options.all_mo = True
  
  if use_qc is None:  
    # Read the input file
    qc = read.main_read(options.filename,
                        itype=options.itype,
                        all_mo=options.all_mo,
                        spin=options.spin,
                        cclib_parser=options.cclib_parser)
  else:
    # Use a user defined QCinfo class.
    qc = use_qc

  if 'native' in options.otype:
    output.main_output(qc, outputname=options.outputname, otype='native', ftype=options.niotype)
    options.otype.remove('native')
    if not len(options.otype):
      t.append(time.time()) # Final time
      good_bye_message(t)
      return
  
  display('\nSetting up the grid...')
  if options.grid_file is not None: 
    # Read the grid from an external file
    grid.read(options.grid_file)
  elif options.adjust_grid is not None:
    # Adjust the grid to geo_spec 
    extend,step = options.adjust_grid      
    grid.adjust_to_geo(qc,extend=extend,step=step)  
  elif options.random_grid:
    # Create a randomized grid
    grid.random_grid(qc.geo_spec)
  
  # Initialize grid
  grid.grid_init(is_vector=options.is_vector)
  if options.is_vector:
    grid.is_regular = False
  display(grid.get_grid())   # Display the grid
  
  if not grid.is_regular and options.center_grid is not None:
    raise IOError('The option --center is only supported for regular grids.')
  elif options.center_grid is not None:
    atom = grid.check_atom_select(options.center_grid,qc.geo_info,qc.geo_spec,
                                  interactive=True,display=display)
    # Center the grid to a specific atom and (0,0,0) if requested
    grid.center_grid(qc.geo_spec[atom-1],display=display)
  
  if check_options or standalone:
    options.check_grid_output_compatibilty()
    
  t.append(time.time()) # A new time step
  
  # The calculation of all AOs (--calc_ao)
  if options.calc_ao != False:
    data = extras.calc_ao(qc,
                          drv=options.drv,
                          otype=options.otype)
    t.append(time.time()) # Final time
    good_bye_message(t)
    return data
  
  # The calculation of selected MOs (--calc_mo) or 
  # the density formed by selected MOs (--mo_set)
  if (options.mo_set or options.calc_mo) != False: 
    # What should the program do?
    if options.calc_mo != False:
      fid_mo_list = options.calc_mo
    elif options.mo_set != False:
      fid_mo_list = options.mo_set
    
    # Call the function for actual calculation 
    if options.calc_mo != False:
      data = extras.calc_mo(qc,
                            fid_mo_list,
                            drv=options.drv,
                            otype=options.otype)
    elif options.mo_set != False: 
      data = extras.mo_set(qc,
                           fid_mo_list,
                           drv=options.drv,
                           laplacian=options.laplacian,
                           otype=options.otype)
    
    t.append(time.time()) # Final time
    good_bye_message(t)
    return data


  if options.gross_atomic_density is not None:
    rho_atom = extras.gross_atomic_density(options.gross_atomic_density,qc,
                                           drv=options.drv)

    if not options.no_output:
      output_written = output.main_output(rho_atom,
                                          qc,
                                          outputname=options.outputname,
                                          otype=options.otype)
    t.append(time.time())
    good_bye_message(t)
    return rho_atom
  
  t.append(time.time()) # A new time step
  
  # Compute the (derivative of the) electron density 
  if options.no_slice:
    data = core.rho_compute_no_slice(qc,
                                     drv=options.drv,
                                     laplacian=options.laplacian,
                                     return_components = False)
  
  else:
    data = core.rho_compute(qc,
                            drv=options.drv,
                            slice_length=options.slice_length,
                            laplacian=options.laplacian,
                            numproc=options.numproc)
  if options.drv is None:
    rho = data
  elif options.laplacian:
    rho, delta_rho, laplacian_rho = data    
  else:
    rho, delta_rho = data
    
  t.append(time.time()) # A new time step

  # Generate the output requested 
  if not options.no_output:
    if not (options.drv is not None or options.laplacian):
      plt_data = rho
      datalabels = 'rho'
    else:
      plt_data = [rho]
      datalabels = ['rho']
      if options.drv is not None:
        plt_data.extend(delta_rho)    
        datalabels.extend(['d/d%s of %s' % (ii_d,'rho') for ii_d in options.drv])
      if options.laplacian:
        plt_data.append(laplacian_rho)
        datalabels.append('laplacian of rho')
    output.main_output(plt_data,qc,outputname=options.outputname,
                       otype=options.otype,datalabels=datalabels)
    
  t.append(time.time()) # Final time
  
  good_bye_message(t)
  
  # Return the computed data, i.e., rho for standard, and (rho,delta_rho)  
  # for derivative calculations. For laplacian (rho,delta_rho,laplacian_rho) 
  return data
示例#13
0
'''
Partial Charges and Gross Atomic Density

Example for the orbkit's non-grid based capabilities and for the computation
of the gross atomic density.

Hint: Use the VMD script file (ch2o.vmd) for depicting the results.
'''

from orbkit import read, grid, extras, output, atomic_populations, display

# Open molden file and read parameters
qc = read.main_read('ch2o.molden', itype='molden')

# Perform a Mulliken population analysis and write the output to a PDB file
pop = atomic_populations.mulliken(qc)
output.pdb_creator(qc.geo_info,
                   qc.geo_spec,
                   filename='ch2o',
                   charges=pop['charge'])

# Initialize the grid
display.display('Setting up the grid...')
grid.adjust_to_geo(qc, extend=5.0, step=0.1)
grid.grid_init()
display.display(grid.get_grid())

# Compute and save the gross atomic density of the C atom
rho_atom = extras.gross_atomic_density(1, qc)
output.main_output(rho_atom[0], qc, outputname='ch2o', otype='cb')
示例#14
0
display.display(grid.get_grid())

# Run orbkit
rho,delta_rho = core.rho_compute(qc,drv=['x','y','z'],numproc=4)

# Compute the reduced density gradient 
from numpy import sqrt,pi
s = (1./(2*(3*pi**2)**(1/3.)) * sqrt((delta_rho**2).sum(axis=0))/(rho**(4/3.)))

# Apply a density cutoff, i.e., consider only values for rho < 0.05 a.u.
s[rho>0.05] = 1e3

# Write a cube file and vmd script for the reduced density gradient 
output.main_output(s,
                   qc,                          # atomic information
                   outputname='reduced_drho',
                   otype=['cb','vmd'],
                   iso=(-0.5,0.5)               # isocontour value of s = 0.5 a.u.
                   )

'''
Classify the interaction types
using the second derivatives of the density 
("the three eigenvalues of the electronic Hessian matrix")
'''
# Compute the second derivatives of the density
rho,delta2_rho = core.rho_compute(qc,drv=['xx','yy','zz'],numproc=4)

# Sort the three components of the derivatives
# The sign of the second value determines, if the interaction is bonding (negative)
# non-bonding (positive)
delta2_rho.sort(axis=0)