Пример #1
0
def write_chk(input_dict, working_directory='.'):
    # collect data and initialize Yaff system
    if 'cell' in input_dict.keys() and input_dict['cell'] is not None:
        system = System(input_dict['numbers'], input_dict['pos']*angstrom, rvecs=input_dict['cell']*angstrom, ffatypes=input_dict['ffatypes_man'], ffatype_ids=input_dict['ffatype_ids_man'])
    else:
        system = System(input_dict['numbers'], input_dict['pos']*angstrom, ffatypes=input_dict['ffatypes_man'], ffatype_ids=input_dict['ffatype_ids_man'])
    # determine masses, bonds and ffaypes from ffatype_rules
    system.detect_bonds()
    system.set_standard_masses()
    # write dictionnairy to MolMod CHK file
    system.to_file(posixpath.join(working_directory,'input.chk'))
    # Reload input.chk as dictionairy and add AI input data
    d = load_chk(posixpath.join(working_directory,'input.chk'))

    assert isinstance(input_dict['aiener'], float), "AI energy not defined in input, use job.read_abintio(...)"
    assert isinstance(input_dict['aigrad'], np.ndarray), "AI gradient not defined in input, use job.read_abintio(...)"
    assert isinstance(input_dict['aihess'], np.ndarray), "AI hessian not defined in input, use job.read_abintio(...)"
    d['energy'] = input_dict['aiener']
    d['grad'] = input_dict['aigrad']
    d['hess'] = input_dict['aihess']
    dump_chk(posixpath.join(working_directory,'input.chk'), d)
Пример #2
0
def main():
    args = parse_args()

    # Load system file
    if args.fn_sys.endswith('.fchk'):
        numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(
            args.fn_sys, do_hess=False)
        system = System(numbers,
                        coords,
                        rvecs=None,
                        charges=None,
                        radii=None,
                        masses=masses)
        system.detect_bonds()
    else:
        system = System.from_file(args.fn_sys)

    # Guess atom types if needed
    if args.ffatypes is not None:
        guess_ffatypes(system, args.ffatypes)
    ffatypes = [system.ffatypes[i] for i in system.ffatype_ids]

    # Load atomic charges
    fn_charges, _, path = args.charges.partition(':')
    if fn_charges.endswith('.h5'):
        with h5.File(fn_charges, 'r') as f:
            if not path in f:
                raise IOError(
                    'Given HDF5 file %s does not contain a dataset %s' %
                    (fn_charges, path))
            charges = f[path][:]
            radii = None
            if args.gaussian:
                path_radii = os.path.join(os.path.dirname(path), 'radii')
                if 'radii' in f[path]:
                    radii = average(f['%s/radii' % path][:],
                                    ffatypes,
                                    fmt='dict')
                else:
                    radii = average(get_ei_radii(system.numbers),
                                    ffatypes,
                                    fmt='dict')
    elif fn_charges.endswith('.chk'):
        sample = load_chk(fn_charges)
        if path in sample.keys():
            charges = sample[path]
        else:
            raise IOError(
                'Given CHK file %s does not contain a dataset with label %s' %
                (fn_charges, path))
        radii = None
        if args.gaussian:
            if 'radii' in sample.keys():
                radii = average(sample['radii'], ffatypes, fmt='dict')
    else:
        raise IOError(
            'Invalid extension, fn_charges should be a HDF5 or a CHK file.')

    # Derive charge parameters
    if args.bci:
        constraints = {}
        if args.bci_constraints is not None:
            constraints = read_bci_constraints(args.bci_constraints)
        bcis = charges_to_bcis(charges,
                               ffatypes,
                               system.bonds,
                               constraints=constraints,
                               verbose=args.verbose)
        make_yaff_ei(args.fn_out, None, bcis=bcis, radii=radii)
    else:
        charges = average(charges, ffatypes, fmt='dict', verbose=args.verbose)
        make_yaff_ei(args.fn_out, charges, radii=radii)
Пример #3
0
    def from_files(cls, fns, ei_path=None, vdw_path=None, bondsin=None):
    # original
    #def from_files(cls, fns, ei_path=None, vdw_path=None):
    #SHLL end
        '''
           A method to construct a System instance from input files. If
           the input files do not contain the topology, it is estimated
           from the geometry.

           **Arguments:**

           fns
                A list of file names. Files further on in the list will
                overwrite earlier files if there is overlap. txt files
                can only be used in hipart format to define charges. HDF5
                files can only be used in Horton format to define charges.
                The set of charges that will be extracted from the HDF5
                file is dependant on the charge scheme defined in the
                kwargs.

           **Optional Arguments:**

           ei_path
                A string defining the path in the HDF5 file which contains a
                dataset `EI_PATH/charges` (and `EI_PATH/radii` in case of
                Gaussian charges) from which the atomic charges will be
                extracted.

           vdw_path
                A string defining the path in the HDF5 file which contains 2
                datasets, `VDW_PATH/epsilons` and `VDW_PATH/sigmas` from which
                the atomic vdW parameters will be extracted.
        '''
        #initialise
        numbers = None
        charges = None
        radii = None
        epsilons = None
        sigmas = None
        ffatypes = None
        #SHLL 1512
        #-- Make it possible to manually define atom connectivity while reading others from file
        bonds = bondsin
        # original
        #bonds = None
        #SHLL end
        bends = None
        diheds = None
        opdists = None
        nlist = None
        ref = ReferenceData()
        #Read all input files
        for fn in fns:
            extension = fn.split('.')[-1]
            if extension in ['chk', 'mfs']:
                sample = load_chk(fn)
                for key, value in sample.iteritems():
                    if key in ['numbers']:
                        numbers = value
                    elif key in ['charges', 'ac', 'aq']:
                        charges = value
                    elif key in ['radii']:
                        radii = value
                    elif key in ['epsilons']:
                        epsilons = value
                    elif key in ['sigmas']:
                        sigmas = value
                    elif key in ['ffatypes', 'atypes']:
                        ffatypes = value
                    elif key in ['bonds']:
                        bonds = value
                    elif key in ['bends', 'angles']:
                        bends = value
                    elif key in ['diheds', 'dihedrals']:
                        diheds = value
                    elif key in ['opdists']:
                        opdists = value
                    elif key in ['coords', 'coordinates', 'pos']:
                        ref.update(coords=value.reshape([-1, 3]))
                    elif key in ['gradient', 'grad', 'gpos', 'forces']:
                        ref.update(grad=value.reshape([-1, 3]))
                    elif key in ['hessian', 'hess']:
                        natoms = int(np.sqrt(value.size/9))
                        ref.update(hess=value.reshape([natoms, 3, natoms, 3]))
            elif extension in ['fchk']:
                fchk = FCHKFile(fn)
                numbers = fchk.fields.get('Atomic numbers')
                ref.update(coords=fchk.fields.get('Current cartesian coordinates').reshape([len(numbers), 3]))
                ref.update(grad=fchk.fields.get('Cartesian Gradient').reshape([len(numbers), 3]))
                ref.update(hess=fchk.get_hessian().reshape([len(numbers), 3, len(numbers), 3]))
            elif extension in ['psf']:
                psf = PSFFile(fn)
                numbers = np.array(psf.numbers)
                ffatypes = np.array(psf.atom_types)
                charges = np.array(psf.charges)
                bonds = np.array(psf.bonds)
                bends = np.array(psf.bends)
                diheds = np.array(psf.dihedrals)
                nlist = psf.get_molecular_graph().neighbors
            elif extension in ['h5']:
                import h5py
                f = h5py.File(fn, 'r')
                if ei_path is None and vdw_path is None:
                    print '\nWARNING: a HDF5 file was given but both ei_path and'  +\
                          'vdw_path are None, HDF5 file is ignored.\n'
                if ei_path is not None:
                    charges = f['%s/charges' % ei_path][:]
                    if '%s/radii' %ei_path in f:
                        radii = f['%s/radii' %ei_path][:]
                if vdw_path is not None:
                    epsilons = f['%s/epsilons' % vdw_path][:]
                    sigmas = f['%s/sigmas' % vdw_path][:]
            else:
                raise IOError('Unsupported file format for %s' %fn)
        return cls(numbers, ref, ffatypes=ffatypes, charges=charges,
                   radii=radii, epsilons=epsilons, sigmas=sigmas, bonds=bonds,
                   bends=bends, diheds=diheds, opdists=opdists, nlist=nlist)
Пример #4
0
def main():
    options, args = parse()
    fn_sys, fn_in, path = args
    if fn_sys.endswith('.fchk'):
        numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(
            fn_sys, do_hess=False)
        system = System(numbers,
                        coords,
                        rvecs=None,
                        charges=None,
                        radii=None,
                        masses=masses)
        system.detect_bonds()
    else:
        system = System.from_file(fn_sys)
    if options.ffatypes is not None:
        guess_ffatypes(system, options.ffatypes)
    ffatypes = [system.ffatypes[i] for i in system.ffatype_ids]
    if fn_in.endswith('.h5'):
        h5 = h5py.File(fn_in)
        if not path in h5 or 'charges' not in h5[path]:
            raise IOError(
                'Given HDF5 file %s does not contain dataset %s/charges' %
                (fn_in, path))
        charges = h5['%s/charges' % path][:]
        radii = None
        if options.gaussian:
            if 'radii' in h5[path]:
                radii = average(h5['%s/radii' % path][:], ffatypes, fmt='dict')
            else:
                radii = average(get_ei_radii(system.numbers),
                                ffatypes,
                                fmt='dict')
    elif fn_in.endswith('.chk'):
        sample = load_chk(fn_in)
        if path in sample.keys():
            charges = sample[path]
        else:
            raise IOError(
                'Given CHK file %s does not contain dataset with label %s' %
                (fn_in, path))
        radii = None
        if options.gaussian:
            if 'radii' in sample.keys():
                radii = average(sample['radii'], ffatypes, fmt='dict')
    else:
        raise IOError(
            'Invalid extension, fn_in should be a HDF5 or a CHK file.')
    if options.output is None:
        if path == '.':
            fn_out = 'pars_ei.txt'
        else:
            fn_out = 'pars_ei_%s.txt' % path.replace('/', '_')
    else:
        fn_out = options.output
    if options.bci:
        constraints = {}
        if options.bci_constraints is not None:
            constraints = read_bci_constraints(options.bci_constraints)
        bcis = charges_to_bcis(charges,
                               ffatypes,
                               system.bonds,
                               constraints=constraints,
                               verbose=options.verbose)
        make_yaff_ei(fn_out, None, bcis=bcis, radii=radii)
    else:
        charges = average(charges,
                          ffatypes,
                          fmt='dict',
                          verbose=options.verbose)
        make_yaff_ei(fn_out, charges, radii=radii)
Пример #5
0
def main():
    options, fns = parse()
    #define logger
    if options.silent:
        log.set_level('silent')
    else:
        if options.very_verbose:
            log.set_level('highest')
        elif options.verbose:
            log.set_level('high')
        if options.logfile is not None and isinstance(options.logfile, str):
            log.write_to_file(options.logfile)
    with log.section('QFF', 1, timer='Initializing'):
        log.dump('Initializing system')
        #read system and ab initio reference
        system = None
        energy = 0.0
        grad = None
        hess = None
        rvecs = None
        for fn in fns:
            if fn.endswith('.fchk') or fn.endswith('.xml'):
                numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(
                    fn)
                if system is None:
                    system = System(numbers,
                                    coords,
                                    rvecs=rvecs,
                                    charges=None,
                                    radii=None,
                                    masses=masses)
                else:
                    system.pos = coords.copy()
                    system.cell = Cell(rvecs)
                    system.numbers = numbers.copy()
                    if masses is not None: system.masses = masses.copy()
                    system._init_derived()
            elif fn.endswith('.chk'):
                sample = load_chk(fn)
                if 'energy' in sample.keys(): energy = sample['energy']
                if 'grad' in sample.keys(): grad = sample['grad']
                elif 'gradient' in sample.keys(): grad = sample['gradient']
                if 'hess' in sample.keys(): hess = sample['hess']
                elif 'hessian' in sample.keys(): hess = sample['hessian']
                if system is None:
                    system = System.from_file(fn)
                else:
                    if 'pos' in sample.keys(): system.pos = sample['pos']
                    elif 'coords' in sample.keys():
                        system.pos = sample['coords']
                    if 'rvecs' in sample.keys():
                        system.cell = Cell(sample['rvecs'])
                    elif 'cell' in sample.keys():
                        system.cell = Cell(sample['cell'])
                    if 'bonds' in sample.keys(): system.bonds = sample['bonds']
                    if 'ffatypes' in sample.keys():
                        system.ffatypes = sample['ffatypes']
                    if 'ffatype_ids' in sample.keys():
                        system.ffatype_ids = sample['ffatype_ids']
                    system._init_derived()
            else:
                raise NotImplementedError('File format for %s not supported' %
                                          fn)
        assert system is not None, 'No system could be defined from input'
        assert grad is not None, 'No ab initio gradient found in input'
        assert hess is not None, 'No ab initio hessian found in input'
        #complete the system information
        if system.bonds is None: system.detect_bonds()
        if system.masses is None: system.set_standard_masses()
        if system.ffatypes is None:
            if options.ffatypes in ['low', 'medium', 'high', 'highest']:
                guess_ffatypes(system, options.ffatypes)
            elif options.ffatypes is not None:
                raise NotImplementedError(
                    'Guessing atom types from %s not implemented' %
                    options.ffatypes)
            else:
                raise AssertionError('No atom types defined')
        #construct ab initio reference
        ai = SecondOrderTaylor('ai',
                               coords=system.pos.copy(),
                               energy=energy,
                               grad=grad,
                               hess=hess,
                               pbc=pbc)
        #detect a priori defined contributions to the force field
        refs = []
        if options.ei is not None:
            if rvecs is None:
                ff = ForceField.generate(system,
                                         options.ei,
                                         rcut=50 * angstrom)
            else:
                ff = ForceField.generate(system,
                                         options.ei,
                                         rcut=20 * angstrom,
                                         alpha_scale=3.2,
                                         gcut_scale=1.5,
                                         smooth_ei=True)
            refs.append(YaffForceField('EI', ff))
        if options.vdw is not None:
            ff = ForceField.generate(system, options.vdw, rcut=20 * angstrom)
            refs.append(YaffForceField('vdW', ff))
        if options.covres is not None:
            ff = ForceField.generate(system, options.covres)
            refs.append(YaffForceField('Cov res', ff))
    #define quickff program
    assert options.program_mode in allowed_programs, \
        'Given program mode %s not allowed. Choose one of %s' %(
            options.program_mode,
            ', '.join([prog for prog in allowed_programs if not prog=='BaseProgram'])
        )
    mode = program_modes[options.program_mode]
    only_traj = 'PT_ALL'
    if options.only_traj is not None: only_traj = options.only_traj.split(',')
    program = mode(system,
                   ai,
                   ffrefs=refs,
                   fn_traj=options.fn_traj,
                   only_traj=only_traj,
                   plot_traj=options.ener_traj,
                   xyz_traj=options.xyz_traj,
                   suffix=options.suffix)
    #run program
    program.run()
Пример #6
0
def qff(args=None):
    if args is None:
        args = qff_parse_args()
    else:
        args = qff_parse_args(args)
    #define logger
    verbosity = None
    if args.silent:
        verbosity = 'silent'
    else:
        if args.very_verbose:
            verbosity = 'highest'
        elif args.verbose:
            verbosity = 'high'
    #get settings
    kwargs = {
        'fn_traj': args.fn_traj,
        'only_traj': args.only_traj,
        'program_mode': args.program_mode,
        'plot_traj': args.plot_traj,
        'xyz_traj': args.xyz_traj,
        'suffix': args.suffix,
        'log_level': verbosity,
        'log_file': args.logfile,
        'ffatypes': args.ffatypes,
        'ei': args.ei,
        'ei_rcut': args.ei_rcut,
        'vdw': args.vdw,
        'vdw_rcut': args.vdw_rcut,
        'covres': args.covres,
    }
    settings = Settings(fn=args.config_file, **kwargs)
    with log.section('INIT', 1, timer='Initializing'):
        log.dump('Initializing system')
        #read system and ab initio reference
        system = None
        energy = 0.0
        grad = None
        hess = None
        pbc = None
        rvecs = None
        for fn in args.fn:
            if fn.endswith('.fchk') or fn.endswith('.xml'):
                numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(
                    fn)
                if system is None:
                    system = System(numbers,
                                    coords,
                                    rvecs=rvecs,
                                    charges=None,
                                    radii=None,
                                    masses=masses)
                else:
                    system.pos = coords.copy()
                    system.cell = Cell(rvecs)
                    system.numbers = numbers.copy()
                    if masses is not None: system.masses = masses.copy()
                    system._init_derived()
            elif fn.endswith('.chk'):
                sample = load_chk(fn)
                if 'energy' in list(sample.keys()): energy = sample['energy']
                if 'grad' in list(sample.keys()): grad = sample['grad']
                elif 'gradient' in list(sample.keys()):
                    grad = sample['gradient']
                if 'hess' in list(sample.keys()): hess = sample['hess']
                elif 'hessian' in list(sample.keys()): hess = sample['hessian']
                if 'rvecs' in list(sample.keys()): pbc = [1, 1, 1]
                else: pbc = [0, 0, 0]
                if system is None:
                    system = System.from_file(fn)
                else:
                    if 'pos' in list(sample.keys()): system.pos = sample['pos']
                    elif 'coords' in list(sample.keys()):
                        system.pos = sample['coords']
                    if 'rvecs' in list(sample.keys()):
                        system.cell = Cell(sample['rvecs'])
                    elif 'cell' in list(sample.keys()):
                        system.cell = Cell(sample['cell'])
                    if 'bonds' in list(sample.keys()):
                        system.bonds = sample['bonds']
                    if 'ffatypes' in list(sample.keys()):
                        system.ffatypes = sample['ffatypes']
                    if 'ffatype_ids' in list(sample.keys()):
                        system.ffatype_ids = sample['ffatype_ids']
                    system._init_derived()
            else:
                raise NotImplementedError('File format for %s not supported' %
                                          fn)
        assert system is not None, 'No system could be defined from input'
        assert grad is not None, 'No ab initio gradient found in input'
        assert hess is not None, 'No ab initio hessian found in input'
        #complete the system information
        if system.bonds is None: system.detect_bonds()
        if system.masses is None: system.set_standard_masses()
        if system.ffatypes is None:
            if settings.ffatypes is not None:
                set_ffatypes(system, settings.ffatypes)
            else:
                raise AssertionError('No atom types defined')
        if settings.do_hess_negfreq_proj:
            log.dump(
                'Projecting negative frequencies out of the mass-weighted hessian.'
            )
            with log.section('SYS', 3, 'Initializing'):
                hess = project_negative_freqs(hess, system.masses)
        #construct ab initio reference
        ai = SecondOrderTaylor('ai',
                               coords=system.pos.copy(),
                               energy=energy,
                               grad=grad,
                               hess=hess,
                               pbc=pbc)
        #detect a priori defined contributions to the force field
        refs = []
        if settings.ei is not None:
            if rvecs is None:
                if settings.ei_rcut is None:
                    rcut = 50 * angstrom
                else:
                    rcut = settings.ei_rcut
                ff = ForceField.generate(system, settings.ei, rcut=rcut)
            else:
                if settings.ei_rcut is None:
                    rcut = 20 * angstrom
                else:
                    rcut = settings.ei_rcut
                ff = ForceField.generate(system,
                                         settings.ei,
                                         rcut=rcut,
                                         alpha_scale=3.2,
                                         gcut_scale=1.5,
                                         smooth_ei=True)
            refs.append(YaffForceField('EI', ff))
        if settings.vdw is not None:
            ff = ForceField.generate(system,
                                     settings.vdw,
                                     rcut=settings.vdw_rcut)
            refs.append(YaffForceField('vdW', ff))
        if settings.covres is not None:
            ff = ForceField.generate(system, settings.covres)
            refs.append(YaffForceField('Cov res', ff))
    #define quickff program
    assert settings.program_mode in allowed_programs, \
        'Given program mode %s not allowed. Choose one of %s' %(
            settings.program_mode,
            ', '.join([prog for prog in allowed_programs if not prog=='BaseProgram'])
        )
    mode = program_modes[settings.program_mode]
    program = mode(system, ai, settings, ffrefs=refs)
    #run program
    program.run()
    return program