Exemple #1
0
def read_system(name):
    # Load system data
    dn = 'quickff.data.systems'
    if '/' in name:
        words = name.split('/')
        dn += '.%s' % ('.'.join(words[:-1]))
        name = words[-1]
    with path(dn, name) as fn:
        numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(
            fn)
        fns_wpart = glob(os.path.join(os.path.dirname(fn), 'gaussian_mbis.h5'))
    # Try to load charges.
    charges = None
    if len(fns_wpart) > 0:
        with h5.File(fns_wpart[0], 'r') as f:
            charges = f['charges'][:]
    # Create system object.
    system = System(numbers, coords, charges=charges)
    system.detect_bonds()
    system.set_standard_masses()
    # Load ab initio data.
    ai = SecondOrderTaylor('ai',
                           coords=system.pos.copy(),
                           energy=energy,
                           grad=grad,
                           hess=hess,
                           pbc=pbc)
    return system, ai
Exemple #2
0
def read_system(name):
    fn = context.get_fn('systems/%s' %name)
    numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(fn)
    system = System(numbers, coords)
    system.detect_bonds()
    system.set_standard_masses()
    ai = SecondOrderTaylor('ai', coords=system.pos.copy(), energy=energy, grad=grad, hess=hess, pbc=pbc)
    return system, ai
Exemple #3
0
def read_system(name):
    # Load system data.
    fn = context.get_fn(os.path.join('systems', name))
    numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(fn)
    # Try to load charges.
    charges = None
    fns_wpart = glob(os.path.join(os.path.dirname(fn), 'gaussian_mbis.h5'))
    if len(fns_wpart) > 0:
        with h5.File(fns_wpart[0], 'r') as f:
            charges = f['charges'][:]
    # Create system object.
    system = System(numbers, coords, charges=charges)
    system.detect_bonds()
    system.set_standard_masses()
    # Load ab initio data.
    ai = SecondOrderTaylor('ai', coords=system.pos.copy(), energy=energy, grad=grad, hess=hess, pbc=pbc)
    return system, ai
Exemple #4
0
def read_system(name):
    # Load system data.
    fn = context.get_fn(os.path.join('systems', name))
    numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio(fn)
    # Try to load charges.
    charges = None
    fns_wpart = glob(os.path.join(os.path.dirname(fn), 'gaussian_mbis.h5'))
    if len(fns_wpart) > 0:
        with h5.File(fns_wpart[0], 'r') as f:
            charges = f['charges'][:]
    # Create system object.
    system = System(numbers, coords, charges=charges)
    system.detect_bonds()
    system.set_standard_masses()
    # Load ab initio data.
    ai = SecondOrderTaylor('ai', coords=system.pos.copy(), energy=energy, grad=grad, hess=hess, pbc=pbc)
    return system, ai
Exemple #5
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)
Exemple #6
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)
Exemple #7
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()
Exemple #8
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