Beispiel #1
0
def test_iter_matches_nobornane_rhodium():
    rules = [
        ('H', '1'),
        ('C_H1', '6&=1%1'),
        ('C_H2', '6&=2%1'),
        ('C_H3', '6&=3%1'),
        ('C', '6'),  # all remaining carbons
        ('P', '15'),
        ('Rh', '45'),
    ]
    system = System.from_file(
        pkg_resources.resource_filename(
            __name__, '../data/test/rhodium_complex_nobornane.xyz'))
    system.detect_bonds()
    system.detect_ffatypes(rules)
    system_ref = System.from_file(
        pkg_resources.resource_filename(__name__,
                                        '../data/test/nobornane.xyz'))
    system_ref.detect_bonds()
    system_ref.detect_ffatypes(rules)
    selected = set(next(system.iter_matches(system_ref)))
    reference = set([
        77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
        95
    ])
    np.testing.assert_equal(selected, reference)
Beispiel #2
0
def test_iter_matches_guaianolide():
    system = System.from_file(context.get_fn('test/guaianolide.xyz'))
    system.detect_bonds()
    system_ref = System.from_file(context.get_fn('test/guaianolide_framework_ordered.xyz'))
    system_ref.detect_bonds()
    order = np.array(system.iter_matches(system_ref).next())
    np.testing.assert_equal(order, [8, 9, 4, 7, 14, 12, 11, 10, 5, 6, 13, 16, 15, 2, 0, 1, 3])
Beispiel #3
0
def test_iter_matches_guaianolide():
    system = System.from_file(context.get_fn('test/guaianolide.xyz'))
    system.detect_bonds()
    system_ref = System.from_file(context.get_fn('test/guaianolide_framework_ordered.xyz'))
    system_ref.detect_bonds()
    order = np.array(system.iter_matches(system_ref).next())
    np.testing.assert_equal(order, [8, 9, 4, 7, 14, 12, 11, 10, 5, 6, 13, 16, 15, 2, 0, 1, 3])
Beispiel #4
0
def test_CAU13_xylene():
    host = System.from_file(pkg_resources.resource_filename(__name__, '../../data/test/CAU_13.chk'))
    guest = System.from_file(pkg_resources.resource_filename(__name__, '../../data/test/xylene.chk'))
    pars_fn = pkg_resources.resource_filename(__name__, '../../data/test/parameters_CAU-13_xylene.txt')
    complex = host.merge(guest)
    for tailcorrections in False, True:
        # Construct force fields
        ff_complex = ForceField.generate(complex, pars_fn, tailcorrections=tailcorrections)
        ff_host    = ForceField.generate(host, pars_fn, tailcorrections=tailcorrections)
        ff_exclude = ForceField.generate(complex, pars_fn, nlow=host.natom, tailcorrections=tailcorrections)
        # The nlow keyword is meant to exclude all pair interactions when both
        # atomic indices are smaller than nlow
        # The energy of this force field should be exactly equal to the energy of
        # the entire complex (featuring framework-framework, framework-guest, and
        # guest-guest interactions) minus the energy of the framework (featuring
        # only framework-framework interactions). Note that this is not what is
        # usually considered an interaction energy, because for instance guest-guest
        # valence interactions are still included.
        e_complex = ff_complex.compute()
        e_host    = ff_host.compute()
        e_exclude = ff_exclude.compute()
        # Compare energies part by part
        nparts = len(ff_complex.parts)
        assert len(ff_host.parts)==nparts
        assert len(ff_exclude.parts)==nparts
        for ipart in range(nparts):
            eref = ff_complex.parts[ipart].energy - ff_host.parts[ipart].energy
            ecomp = ff_exclude.parts[ipart].energy
            print("%20s %15.9f %15.9f"%  (ff_exclude.parts[ipart].name, eref, ecomp))
            assert np.abs(eref-ecomp)<1e-10
Beispiel #5
0
def test_iter_matches_guaianolide():
    system = System.from_file(
        pkg_resources.resource_filename(__name__,
                                        '../data/test/guaianolide.xyz'))
    system.detect_bonds()
    system_ref = System.from_file(
        pkg_resources.resource_filename(
            __name__, '../data/test/guaianolide_framework_ordered.xyz'))
    system_ref.detect_bonds()
    order = np.array(next(system.iter_matches(system_ref)))
    np.testing.assert_equal(
        order, [8, 9, 4, 7, 14, 12, 11, 10, 5, 6, 13, 16, 15, 2, 0, 1, 3])
Beispiel #6
0
    def load_chk(self, fn):
        """
        Load the atom types, atom type ids and structure by reading a .chk file.

        **Arguments**

        fn      the path to the chk file
        """

        system = System.from_file(fn)
        system.set_standard_masses()
        if len(system.pos.shape) != 2:
            raise IOError(
                "Something went wrong, positions in CHK file %s should have Nx3 dimensions"
                % fn)
        if system.cell.rvecs is not None and len(system.cell.rvecs) > 0:
            self.structure = Atoms(
                positions=system.pos.copy() / angstrom,
                numbers=system.numbers,
                masses=system.masses,
                cell=system.cell.rvecs / angstrom,
                pbc=True,
            )
        else:
            self.structure = Atoms(
                positions=system.pos.copy() / angstrom,
                numbers=system.numbers,
                masses=system.masses,
            )
        if system.ffatypes is not None:
            self.ffatypes = system.ffatypes
        if system.ffatype_ids is not None:
            self.ffatype_ids = system.ffatype_ids
Beispiel #7
0
def load_system_xyz(fn):
    '''Load atomic numbers, coordinates and cell parameters from fn'''
    # Load the cell vectors from the second line.
    print 'Loading atomic structure from XYZ file.'
    with open(fn) as f:
        # Skip one line.
        f.next()
        # Read rvecs (real-space cell vectors).
        real_numbers = []
        for word in f.next().split():
            try:
                real_numbers.append(float(word))
            except ValueError:
                pass
        print 'Detected %i real numbers in title line.' % len(real_numbers)
        if len(real_numbers) >= 9:
            rvecs = np.array(real_numbers[:9]).reshape(3, 3)*angstrom
            print 'Treating system as periodic with the following cell vectors'
            print 'in Angstrom. (Cell vectors are displayed as rows.)'
            print rvecs/angstrom
        else:
            print 'I\'m assuming the system is aperiodic because there are less'
            print 'than nine real numbers in the title line.'
            rvecs = None

    # Let Yaff read the rest of the file.
    print
    return System.from_file(fn, rvecs=rvecs)
Beispiel #8
0
def load_system_xyz(fn):
    '''Load atomic numbers, coordinates and cell parameters from fn'''
    # Load the cell vectors from the second line.
    print 'Loading atomic structure from XYZ file.'
    with open(fn) as f:
        # Skip one line.
        f.next()
        # Read rvecs (real-space cell vectors).
        real_numbers = []
        for word in f.next().split():
            try:
                real_numbers.append(float(word))
            except ValueError:
                pass
        print 'Detected %i real numbers in title line.' % len(real_numbers)
        if len(real_numbers) >= 9:
            rvecs = np.array(real_numbers[:9]).reshape(3, 3) * angstrom
            print 'Treating system as periodic with the following cell vectors'
            print 'in Angstrom. (Cell vectors are displayed as rows.)'
            print rvecs / angstrom
        else:
            print 'I\'m assuming the system is aperiodic because there are less'
            print 'than nine real numbers in the title line.'
            rvecs = None

    # Let Yaff read the rest of the file.
    print
    return System.from_file(fn, rvecs=rvecs)
Beispiel #9
0
def test_iter_matches_single_atom():
    system = System.from_file(context.get_fn('test/rhodium_complex_nobornane.xyz'))
    system.detect_bonds()
    system_ref = System(pos=np.zeros((1, 3), float), numbers = np.array([45]))
    system_ref.detect_bonds()
    selected = set(system.iter_matches(system_ref).next())
    reference = set([28])
    np.testing.assert_equal(selected, reference)
Beispiel #10
0
def test_chk():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_chk')
    try:
        system0.to_file('%s/tmp.chk' % dirname)
        system1 = System.from_file('%s/tmp.chk' % dirname)
        compare_water32(system0, system1, 1e-10)
    finally:
        shutil.rmtree(dirname)
Beispiel #11
0
def test_chk():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_chk')
    try:
        system0.to_file('%s/tmp.chk' % dirname)
        system1 = System.from_file('%s/tmp.chk' % dirname)
        compare_water32(system0, system1, 1e-10)
    finally:
        shutil.rmtree(dirname)
Beispiel #12
0
def test_xyz():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_xyz')
    try:
        system0.to_file('%s/tmp.xyz' % dirname)
        system1 = System.from_file('%s/tmp.xyz' % dirname, rvecs=system0.cell.rvecs, ffatypes=system0.ffatypes, ffatype_ids=system0.ffatype_ids)
        compare_water32(system0, system1, 1e-10, xyz=True)
    finally:
        shutil.rmtree(dirname)
Beispiel #13
0
def test_hdf5():
    system0 = get_system_water32()
    with tmpdir(__name__, 'test_hdf5') as dirname:
        fn = '%s/tmp.h5' % dirname
        system0.to_file(fn)
        with h5.File(fn) as f:
            assert 'system' in f
        system1 = System.from_file(fn)
        compare_water32(system0, system1)
Beispiel #14
0
def test_xyz():
    system0 = get_system_water32()
    with tmpdir(__name__, 'test_xyz') as dirname:
        system0.to_file('%s/tmp.xyz' % dirname)
        system1 = System.from_file('%s/tmp.xyz' % dirname,
                                   rvecs=system0.cell.rvecs,
                                   ffatypes=system0.ffatypes,
                                   ffatype_ids=system0.ffatype_ids)
        compare_water32(system0, system1, 1e-10, xyz=True)
Beispiel #15
0
def test_xyz():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_xyz')
    try:
        system0.to_file('%s/tmp.xyz' % dirname)
        system1 = System.from_file('%s/tmp.xyz' % dirname, rvecs=system0.cell.rvecs, ffatypes=system0.ffatypes, ffatype_ids=system0.ffatype_ids)
        compare_water32(system0, system1, 1e-10, xyz=True)
    finally:
        shutil.rmtree(dirname)
Beispiel #16
0
    def __init__(self, latency=1.0, name="", yaffpara=None, yaffsys=None, yafflog='yaff.log', rcut=18.89726133921252, alpha_scale=3.5, gcut_scale=1.1, skin=0, smooth_ei=False, reci_ei='ewald', pars=None, dopbc=False, threaded=True):
        """Initialises FFYaff and enables a basic Yaff force field.

        Args:

           yaffpara: File name of the Yaff parameter file

           yaffsys: File name of the Yaff system file

           yafflog: File name to which Yaff will write some information about the system and the force field

           pars: Optional dictionary, giving the parameters needed by the driver.

           **kwargs: All keyword arguments that can be provided when generating
                     a Yaff force field; see constructor of FFArgs in Yaff code

        """

        from yaff import System, ForceField, log
        import codecs
        import locale
        import atexit

        # a socket to the communication library is created or linked
        super(FFYaff, self).__init__(latency, name, pars, dopbc)

        # A bit weird to use keyword argument for a required argument, but this
        # is also done in the code above.
        if yaffpara is None:
            raise ValueError("Must provide a Yaff parameter file.")

        if yaffsys is None:
            raise ValueError("Must provide a Yaff system file.")

        self.yaffpara = yaffpara
        self.yaffsys = yaffsys
        self.rcut = rcut
        self.alpha_scale = alpha_scale
        self.gcut_scale = gcut_scale
        self.skin = skin
        self.smooth_ei = smooth_ei
        self.reci_ei = reci_ei
        self.yafflog = yafflog

        # Open log file
        logf = open(yafflog, 'w')
        # Tell Python to close the file when the script exits
        atexit.register(logf.close)

        # Redirect Yaff log to file
        log._file = codecs.getwriter(locale.getpreferredencoding())(logf)

        self.system = System.from_file(self.yaffsys)
        self.ff = ForceField.generate(self.system, self.yaffpara, rcut=self.rcut, alpha_scale=self.alpha_scale, gcut_scale=self.gcut_scale, skin=self.skin, smooth_ei=self.smooth_ei, reci_ei=self.reci_ei)

        log._active = False
Beispiel #17
0
    def __init__(self, latency=1.0, name="", threaded=False, yaffpara=None, yaffsys=None, yafflog='yaff.log', rcut=18.89726133921252, alpha_scale=3.5, gcut_scale=1.1, skin=0, smooth_ei=False, reci_ei='ewald', pars=None, dopbc=False):
        """Initialises FFYaff and enables a basic Yaff force field.

        Args:

           yaffpara: File name of the Yaff parameter file

           yaffsys: File name of the Yaff system file

           yafflog: File name to which Yaff will write some information about the system and the force field

           pars: Optional dictionary, giving the parameters needed by the driver.

           **kwargs: All keyword arguments that can be provided when generating
                     a Yaff force field; see constructor of FFArgs in Yaff code

        """

        from yaff import System, ForceField, log
        import codecs
        import locale
        import atexit

        # a socket to the communication library is created or linked
        super(FFYaff, self).__init__(latency, name, pars, dopbc, threaded=threaded)

        # A bit weird to use keyword argument for a required argument, but this
        # is also done in the code above.
        if yaffpara is None:
            raise ValueError("Must provide a Yaff parameter file.")

        if yaffsys is None:
            raise ValueError("Must provide a Yaff system file.")

        self.yaffpara = yaffpara
        self.yaffsys = yaffsys
        self.rcut = rcut
        self.alpha_scale = alpha_scale
        self.gcut_scale = gcut_scale
        self.skin = skin
        self.smooth_ei = smooth_ei
        self.reci_ei = reci_ei
        self.yafflog = yafflog

        # Open log file
        logf = open(yafflog, 'w')
        # Tell Python to close the file when the script exits
        atexit.register(logf.close)

        # Redirect Yaff log to file
        log._file = codecs.getwriter(locale.getpreferredencoding())(logf)

        self.system = System.from_file(self.yaffsys)
        self.ff = ForceField.generate(self.system, self.yaffpara, rcut=self.rcut, alpha_scale=self.alpha_scale, gcut_scale=self.gcut_scale, skin=self.skin, smooth_ei=self.smooth_ei, reci_ei=self.reci_ei)

        log._active = False
Beispiel #18
0
def test_iter_matches_single_atom():
    system = System.from_file(
        pkg_resources.resource_filename(
            __name__, '../data/test/rhodium_complex_nobornane.xyz'))
    system.detect_bonds()
    system_ref = System(pos=np.zeros((1, 3), float), numbers=np.array([45]))
    system_ref.detect_bonds()
    selected = set(next(system.iter_matches(system_ref)))
    reference = set([28])
    np.testing.assert_equal(selected, reference)
Beispiel #19
0
def test_lammps_ffconversion_mil53():
    fn_system = pkg_resources.resource_filename(
        __name__, '../../data/test/system_mil53.chk')
    fn_pars = pkg_resources.resource_filename(
        __name__, '../../data/test/parameters_mil53.txt')
    system = System.from_file(fn_system)
    with tmpdir(__name__, 'test_lammps_ffconversion_mil53') as dirname:
        ff2lammps(system, fn_pars, dirname)
        # No test for correctness, just check that output files are present
        assert os.path.isfile(os.path.join(dirname, 'lammps.in'))
        assert os.path.isfile(os.path.join(dirname, 'lammps.data'))
Beispiel #20
0
def test_hdf5_assign_ffatypes():
    system0 = get_system_water32()
    with tmpdir(__name__, 'test_hdf5_assign_ffatypes') as dirname:
        system0.ffatypes = ['O', 'H']
        system0.ffatype_ids = np.array([0, 1, 1] * 32)
        fn = '%s/tmp.h5' % dirname
        system0.to_file(fn)
        with h5.File(fn) as f:
            assert 'system' in f
        system1 = System.from_file(fn)
        compare_water32(system0, system1)
Beispiel #21
0
def test_hdf5():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_hdf5')
    try:
        fn = '%s/tmp.h5' % dirname
        system0.to_file(fn)
        with h5.File(fn) as f:
            assert 'system' in f
        system1 = System.from_file(fn)
        compare_water32(system0, system1)
    finally:
        shutil.rmtree(dirname)
Beispiel #22
0
def test_hdf5():
    system0 = get_system_water32()
    dirname = tempfile.mkdtemp('yaff', 'test_hdf5')
    try:
        fn = '%s/tmp.h5' % dirname
        system0.to_file(fn)
        with h5.File(fn) as f:
            assert 'system' in f
        system1 = System.from_file(fn)
        compare_water32(system0, system1)
    finally:
        shutil.rmtree(dirname)
Beispiel #23
0
    def __init__(self, system_file, adsorbate_file, ff_file, rcut):

        system = System.from_file(system_file)
        adsorbate = System.from_file(adsorbate_file)

        self.sigmas_MOF, self.epsilons_MOF, self.charges_MOF, self.radii_MOF = self.get_data(
            system, ff_file, rcut)
        self.sigmas_ads, self.epsilons_ads, self.charges_ads, self.radii_ads = self.get_data(
            adsorbate, ff_file, rcut)

        system.set_standard_masses()
        self.pos_MOF = system.pos
        self.rvecs = system.cell.rvecs
        self.numbers_MOF = system.numbers
        self.mass_MOF = sum(system.masses)
        self.system = system

        self.pos_ads = adsorbate.pos
        self.numbers_ads = adsorbate.numbers
        #        self.mass_ads = sum(atomic_masses[self.numbers_ads])
        self.system_ads = adsorbate

        self.parameter_list()
Beispiel #24
0
def load_ff(uselammps=False,supercell=(1,1,1),overwrite_table=False):
    # Load the system
    system = System.from_file('system.chk').supercell(supercell[0],
        supercell[1],supercell[2])
    # Generate the YAFF ForceField
    ff = ForceField.generate(system, 'pars.txt', alpha_scale=3.2,
        gcut_scale=1.5, rcut=15.0*angstrom, smooth_ei=True)
    if uselammps:
        fn_system = 'system_%s.dat'%".".join(["%d"%s for s in supercell])
        fn_table = 'table.dat'
        ff_lammps = swap_noncovalent_lammps(ff, fn_system=fn_system,
             fn_table=fn_table, overwrite_table=overwrite_table, comm=comm)
        return ff_lammps
    else:
        return ff
Beispiel #25
0
def collect_output(fn_pars, fn_sys):
    # this routine reads the output parameter file containing the covalent pars
    output_dict = {'generic/bond': [], 'generic/bend': [], 'generic/torsion': [], 'generic/oopdist': [], 'generic/cross': []}
    kinds = ['bond', 'bend', 'torsion', 'oopdist', 'cross']
    with open(fn_pars, 'r') as f:
        for line in f.readlines():
            for key in kinds:
                if key in line.lower():
                    output_dict['generic/%s' %key].append(line)
    system = System.from_file(fn_sys)
    output_dict['system/numbers'] = system.numbers
    output_dict['system/pos'] = system.pos/angstrom
    if system.cell is not None:
        output_dict['system/rvecs'] = system.cell.rvecs/angstrom
    output_dict['system/bonds'] = system.bonds
    output_dict['system/ffatypes'] = np.asarray(system.ffatypes,'S22')
    output_dict['system/ffatype_ids'] = system.ffatype_ids
    return output_dict
Beispiel #26
0
def main():
    rcut = 15.0 * angstrom
    for nx, ny, nz in [(1, 1, 1), (1, 2, 1), (2, 2, 1), (2, 2, 2), (2, 3, 2),
                       (3, 3, 2), (3, 3, 3), (3, 4, 3), (4, 4, 3),
                       (4, 4, 4)][:]:
        # Generate supercell system
        system = System.from_file('system.chk').supercell(nx, ny, nz)
        dn = 'lammps_%s' % ('.'.join("%d" % n for n in [nx, ny, nz]))
        if not os.path.isdir(dn): os.makedirs(dn)
        # Tabulate vdW interactions
        if not os.path.isfile('lammps.table'):
            ff = ForceField.generate(system, ['pars.txt'], rcut=rcut)
            write_lammps_table(ff,
                               fn='lammps.table',
                               rmin=0.50 * angstrom,
                               nrows=2500,
                               unit_style='real')
        # Write the LAMMPS input files
        ff2lammps(system,
                  'pars.txt',
                  dn,
                  rcut=15.0 * angstrom,
                  tailcorrections=False,
                  tabulated=True,
                  unit_style='real')
        # Adapt the sampling options, which are defined in the last 5 lines
        # of lammps.in
        with open(os.path.join(dn, 'lammps.in'), 'r') as f:
            lines = f.readlines()
        with open(os.path.join(dn, 'lammps.in'), 'w') as f:
            for line in lines[:-5]:
                f.write(line)
            f.write("timestep 1.0 # in time units\n")
            f.write(
                "velocity all create 600.0 5 # initial temperature in Kelvin and random seed\n"
            )
            f.write("fix 1 all nvt temp 300.0 300.0 100.0\n")
            f.write(
                "fix_modify 1 energy yes # Add thermo/barostat contributions to energy\n"
            )
            f.write("run 100\n")
Beispiel #27
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()
Beispiel #28
0
def test_chk():
    system0 = get_system_water32()
    with tmpdir(__name__, 'test_chk') as dirname:
        system0.to_file('%s/tmp.chk' % dirname)
        system1 = System.from_file('%s/tmp.chk' % dirname)
        compare_water32(system0, system1, 1e-10)
Beispiel #29
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
Beispiel #30
0
        ffa1 = ff.system.ffatypes[ff.system.ffatype_ids[number[1]]]
        if ffa0 > ffa1:
            name = '%s-%s' % (ffa0, ffa1)
        else:
            name = '%s-%s' % (ffa1, ffa0)
        ftab.write("%s\nN %d R %f %f\n\n" %
                   (name, energies.shape[0], distances[0], distances[-1]))
        for irow, row in enumerate(energies):
            ftab.write("%05d %+13.8f %+21.12f %+21.12f\n" %
                       (irow + 1, row[0], row[1], row[2]))
        print name
        #break


if __name__ == '__main__':
    sys = System.from_file('init.chk')
    system = sys.supercell(1, 2, 1)
    log.set_level(log.silent)
    fns = []
    for fn in os.listdir(os.getcwd()):
        if fn.startswith('pars') and fn.endswith('.txt'):
            fns.append(fn)
    ff = ForceField.generate(system,
                             fns,
                             rcut=15.0 * angstrom,
                             alpha_scale=3.2,
                             gcut_scale=1.5,
                             smooth_ei=True)

    log.set_level(log.low)
    write_lammps_data(system)
Beispiel #31
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)
Beispiel #32
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)
Beispiel #33
0
# ff = ForceField.generate(system, )
# ff.add_part(ForcePartPressure(system, p*p_unit))
#
# opt = CGOptimizer(StrainCellDOF(ff, gpos_rms=1e-6, grvecs_rms=1e-6))
# opt.run(500)
# system.to_file('opt%d.chk' % p)
#
# print(system.cell.volume/angstrom**3, ff.part_press.pext/p_unit, ff.energy/e_unit)

pressures = np.linspace(-1000, 2000, 31, endpoint=True)
print(pressures)

results = np.zeros((len(pressures), 12), dtype=np.float32)

for i, p in enumerate(pressures):
    system = System.from_file(chk_file)
    ff = ForceField.generate(system,
                             ff_file,
                             rcut=20 * angstrom,
                             alpha_scale=4.0,
                             gcut_scale=2.0,
                             smooth_ei=True,
                             reci_ei='ewald')

    ff.add_part(ForcePartPressure(system, p * p_unit))

    opt = CGOptimizer(StrainCellDOF(ff, gpos_rms=1e-6, grvecs_rms=1e-6))
    opt.run(2000)

    system.to_file('results/opt%d.chk' % p)
    system.to_file('results/opt%d.xyz' % p)
def test_exclusion():
    def random_rotation(pos):
        com = np.average(pos, axis=0)
        pos -= com
        while True:
            V1 = np.random.rand()
            V2 = np.random.rand()
            S = V1**2 + V2**2
            if S < 1:
                break
        theta = np.array([
            2 * np.pi * (2 * V1 * np.sqrt(1 - S) - 0.5),
            2 * np.pi * (2 * V2 * np.sqrt(1 - S) - 0.5),
            np.pi * ((1 - 2 * S) / 2)
        ])
        R_x = np.array([[1, 0, 0], [0, np.cos(theta[0]), -np.sin(theta[0])],
                        [0, np.sin(theta[0]),
                         np.cos(theta[0])]])
        R_y = np.array([[np.cos(theta[1]), 0,
                         np.sin(theta[1])], [0, 1, 0],
                        [-np.sin(theta[1]), 0,
                         np.cos(theta[1])]])
        R_z = np.array([[np.cos(theta[2]), -np.sin(theta[2]), 0],
                        [np.sin(theta[2]),
                         np.cos(theta[2]), 0], [0, 0, 1]])
        R = np.dot(R_z, np.dot(R_y, R_x))
        pos_new = np.zeros((len(pos), len(pos[0])))
        for i, p in enumerate(pos):
            pos_new[i] = np.dot(R, np.array(p).T)
        return pos_new + com

    def get_adsorbate_pos(adsorbate, rvecs):
        pos = adsorbate.pos
        pos = random_rotation(pos)
        pos -= np.average(pos, axis=0)
        new_com = np.random.rand() * rvecs[0] + np.random.rand(
        ) * rvecs[1] + np.random.rand() * rvecs[2]
        return pos + new_com

    # Empty framework
    system = System.from_file(
        pkg_resources.resource_filename(__name__,
                                        '../../data/test/CAU_13.chk'))
    N_system = len(system.pos)
    ff_file = pkg_resources.resource_filename(
        __name__, '../../data/test/parameters_CAU-13_xylene.txt')

    ff = ForceField.generate(system, ff_file)
    ff.nlist.update()
    E_parts = {part.name: part.compute() for part in ff.parts}

    ff_new = ForceField.generate(system,
                                 ff_file,
                                 exclude_frame=True,
                                 n_frame=N_system)
    ff_new.nlist.update()
    E_parts_new = {part.name: part.compute() for part in ff_new.parts}

    # Add 4 adsorbates
    adsorbate = System.from_file(
        pkg_resources.resource_filename(__name__,
                                        '../../data/test/xylene.chk'))

    pos = system.pos
    ffatypes = np.append(system.ffatypes, adsorbate.ffatypes)
    bonds = system.bonds
    numbers = system.numbers
    ffatype_ids = system.ffatype_ids
    charges = system.charges
    masses = system.masses

    for i in range(4):
        pos = np.append(pos,
                        get_adsorbate_pos(adsorbate, system.cell.rvecs),
                        axis=0)
        bonds = np.append(bonds,
                          adsorbate.bonds + N_system + len(adsorbate.pos) * i,
                          axis=0)
        numbers = np.append(numbers, adsorbate.numbers, axis=0)
        ffatype_ids = np.append(ffatype_ids,
                                adsorbate.ffatype_ids +
                                max(system.ffatype_ids) + 1,
                                axis=0)
        charges = np.append(charges, adsorbate.charges, axis=0)
        masses = np.append(masses, adsorbate.masses, axis=0)

    # Framework with 4 adsorbates
    system = System(numbers, pos, ffatypes=ffatypes, ffatype_ids=ffatype_ids, bonds=bonds,\
                    rvecs = system.cell.rvecs, charges=charges, masses=masses)

    ff = ForceField.generate(system, ff_file)
    ff_new = ForceField.generate(system,
                                 ff_file,
                                 exclude_frame=True,
                                 n_frame=N_system)

    # Test 100 random configurations
    for i in range(100):
        new_pos = ff.system.pos
        for i in range(4):
            new_pos[N_system + i * len(adsorbate.pos):N_system +
                    (i + 1) * len(adsorbate.pos)] = get_adsorbate_pos(
                        adsorbate, system.cell.rvecs)

        ff.update_pos(new_pos)
        ff_new.update_pos(new_pos)
        ff.nlist.update()
        ff_new.nlist.update()

        E_parts_rand = {part.name: part.compute() for part in ff.parts}
        E_parts_new_rand = {part.name: part.compute() for part in ff_new.parts}
        for key, _ in E_parts.items():
            assert (E_parts[key] - E_parts_rand[key]) - (
                E_parts_new[key] - E_parts_new_rand[key]) < 10e-12
Beispiel #35
0
 def get_yaff_system(self):
     system = System.from_file(posixpath.join(self.working_directory, self.input['fn_sys']))
     return system
#!/usr/bin/env python

import numpy as np
from yaff import System, angstrom, ForceField

from quickff.tools import set_ffatypes

# system_cluster = System.from_file('system_mbisgauss.chk')

# system_cluster.ffatypes

# rvecs = np.diag([25.832]*3)*angstrom
rvecs = np.identity(3) * 25.832 * angstrom
system = System.from_file('IRMOF-1.xyz', rvecs=rvecs)
system.detect_bonds()
set_ffatypes(system, "high")
# system.set_standard_masses()
system.to_file('init.chk')

# ff = ForceField.generate(system, 'pars_yaff_mbisgauss.txt')
def test_exclusion():

    def random_rotation(pos):
        com = np.average(pos, axis=0)
        pos -= com
        while True:
            V1 = np.random.rand(); V2 = np.random.rand(); S = V1**2 + V2**2;
            if S < 1:
                break;
        theta = np.array([2*np.pi*(2*V1*np.sqrt(1-S)-0.5), 2*np.pi*(2*V2*np.sqrt(1-S)-0.5), np.pi*((1-2*S)/2)])
        R_x = np.array([[1, 0, 0],[0, np.cos(theta[0]), -np.sin(theta[0])],[0, np.sin(theta[0]), np.cos(theta[0])]])
        R_y = np.array([[np.cos(theta[1]), 0, np.sin(theta[1])],[0, 1, 0],[-np.sin(theta[1]), 0, np.cos(theta[1])]])
        R_z = np.array([[np.cos(theta[2]), -np.sin(theta[2]),0],[np.sin(theta[2]), np.cos(theta[2]),0],[0, 0, 1]])
        R = np.dot(R_z, np.dot( R_y, R_x ))
        pos_new = np.zeros((len(pos), len(pos[0])))
        for i, p in enumerate(pos):
            pos_new[i] = np.dot(R, np.array(p).T)
        return pos_new + com

    def get_adsorbate_pos(adsorbate, rvecs):
        pos = adsorbate.pos
        pos = random_rotation(pos)
        pos -= np.average(pos, axis=0)
        new_com = np.random.rand()*rvecs[0] + np.random.rand()*rvecs[1] + np.random.rand()*rvecs[2]
        return pos + new_com

    # Empty framework
    system = System.from_file(pkg_resources.resource_filename(__name__, '../../data/test/CAU_13.chk'))
    N_system = len(system.pos)
    ff_file = pkg_resources.resource_filename(__name__, '../../data/test/parameters_CAU-13_xylene.txt')

    ff = ForceField.generate(system, ff_file)
    ff.nlist.update()
    E_parts = {part.name:part.compute() for part in ff.parts}

    ff_new = ForceField.generate(system, ff_file, exclude_frame=True, n_frame=N_system)
    ff_new.nlist.update()
    E_parts_new = {part.name:part.compute() for part in ff_new.parts}

    # Add 4 adsorbates
    adsorbate = System.from_file(pkg_resources.resource_filename(__name__, '../../data/test/xylene.chk'))

    pos = system.pos
    ffatypes = np.append(system.ffatypes, adsorbate.ffatypes)
    bonds = system.bonds
    numbers = system.numbers
    ffatype_ids = system.ffatype_ids
    charges = system.charges
    masses = system.masses

    for i in range(4):
        pos = np.append(pos, get_adsorbate_pos(adsorbate,system.cell.rvecs), axis=0)
        bonds = np.append(bonds, adsorbate.bonds + N_system + len(adsorbate.pos) * i,axis=0)
        numbers = np.append(numbers, adsorbate.numbers, axis=0)
        ffatype_ids = np.append(ffatype_ids, adsorbate.ffatype_ids + max(system.ffatype_ids) + 1, axis=0)
        charges = np.append(charges, adsorbate.charges, axis=0)
        masses = np.append(masses, adsorbate.masses, axis=0)

    # Framework with 4 adsorbates
    system = System(numbers, pos, ffatypes=ffatypes, ffatype_ids=ffatype_ids, bonds=bonds,\
                    rvecs = system.cell.rvecs, charges=charges, masses=masses)

    ff = ForceField.generate(system, ff_file)
    ff_new = ForceField.generate(system, ff_file, exclude_frame=True, n_frame=N_system)

    # Test 100 random configurations
    for i in range(100):
        new_pos = ff.system.pos
        for i in range(4):
            new_pos[N_system+i*len(adsorbate.pos):N_system+(i+1)*len(adsorbate.pos)] = get_adsorbate_pos(adsorbate,system.cell.rvecs)

        ff.update_pos(new_pos)
        ff_new.update_pos(new_pos)
        ff.nlist.update()
        ff_new.nlist.update()

        E_parts_rand = {part.name:part.compute() for part in ff.parts}
        E_parts_new_rand = {part.name:part.compute() for part in ff_new.parts}
        for key, _ in E_parts.items():
            assert (E_parts[key]-E_parts_rand[key]) - (E_parts_new[key]-E_parts_new_rand[key]) < 10e-12