Example #1
0
def test_water_cost_dist_fc():
    fn_chk = context.get_fn('test/water_hessian.chk')
    sample = load_chk(fn_chk)
    system = System(pos=sample['pos'], numbers=sample['numbers'], ffatypes=['O', 'H', 'H'])
    system.detect_bonds()
    fn_pars = context.get_fn('test/parameters_water.txt')
    parameters = Parameters.from_file(fn_pars)
    del parameters.sections['FIXQ']
    del parameters.sections['DAMPDISP']
    del parameters.sections['EXPREP']

    rules = [ScaleRule('BONDFUES', 'PARS', 'O\s*H', 2)]
    mods = [ParameterModifier(rules)]
    pt = ParameterTransform(parameters, mods)

    simulations = [GeoOptHessianSimulation('only', system)]
    tests = [FCTest(kjmol/angstrom**2, sample['pos'], sample['hessian'].reshape(9, 9), simulations[0], BondGroup(system))]
    assert tests[0].icgroup.cases == [[1, 0], [2, 0]]
    cost = CostFunction(pt, {'all': tests})

    x = np.array([1.0])
    assert abs(cost(x) - np.log(0.5*(5159.1871966 - 4.0088096730e+03)**2)) < 1

    x = np.array([1.1])
    assert abs(cost(x) - np.log(0.5*(5159.1871966 - 1.1*4.0088096730e+03)**2)) < 1

    x = np.array([0.8])
    assert abs(cost(x) - np.log(0.5*(5159.1871966 - 0.8*4.0088096730e+03)**2)) < 1
Example #2
0
def test_water_cost_angle_fc():
    fn_chk = context.get_fn('test/water_hessian.chk')
    sample = load_chk(fn_chk)
    system = System(pos=sample['pos'], numbers=sample['numbers'], ffatypes=['O', 'H', 'H'])
    system.detect_bonds()
    fn_pars = context.get_fn('test/parameters_water.txt')
    parameters = Parameters.from_file(fn_pars)
    del parameters.sections['FIXQ']
    del parameters.sections['DAMPDISP']
    del parameters.sections['EXPREP']

    rules = [ScaleRule('BENDCHARM', 'PARS', 'O\s*H', 3)]
    mods = [ParameterModifier(rules)]
    pt = ParameterTransform(parameters, mods)

    simulations = [GeoOptHessianSimulation('only', system)]
    tests = [FCTest(kjmol, sample['pos'], sample['hessian'].reshape(9, 9), simulations[0], BendGroup(system))]
    assert tests[0].icgroup.cases == [[2, 0, 1]]
    cost = CostFunction(pt, {'all': tests})

    x = np.array([1.0])
    assert abs(cost(x) - np.log(0.5*(394.59354836 - 302.068346061)**2)) < 1

    x = np.array([1.1])
    assert abs(cost(x) - np.log(0.5*(394.59354836 - 1.1*302.068346061)**2)) < 1

    x = np.array([0.8])
    assert abs(cost(x) - np.log(0.5*(394.59354836 - 0.8*302.068346061)**2)) < 1
Example #3
0
def test_uio66zrbrick_crossterms():
    with log.section('NOSETEST', 2):
        # Load input data for a ficticious system of an isolated
        # UiO-66 brick
        with path('quickff.data.systems.uio66-zr-brick', 'system.chk') as fn:
            data = load_chk(fn)
        system = System(data['numbers'],data['pos'],charges=data['charges'],
            ffatypes=data['ffatypes'],bonds=data['bonds'],radii=data['radii'])
        system.set_standard_masses()
        ai = SecondOrderTaylor('ai', coords=system.pos.copy(),
             grad=data['gradient'], hess=data['hessian'])
        # Run QuickFF
        with tmpdir('test_uio66') as dn:
            fn_yaff = os.path.join(dn, 'pars_cov.txt')
            fn_sys = os.path.join(dn, 'system.chk')
            fn_log = os.path.join(dn, 'quickff.log')
            program = DeriveFF(system, ai, Settings(consistent_cross_rvs=True,
                remove_dysfunctional_cross=True,fn_yaff=fn_yaff,fn_sys=fn_sys,log_file=fn_log))
            program.run()
        # Check force constants of cross terms and corresponding diagonal terms
        print("%50s %15s %15s"%("Basename","Cross FC","Diag FC"))
        for term in program.valence.terms:
            if not term.is_master(): continue
            if term.basename.startswith('Cross'):
                fc = program.valence.get_params(term.index, only='fc')
                for i in [0,1]:
                    fc_diag = program.valence.get_params(term.diag_term_indexes[i], only='fc')
                    print("%50s %15.6f %15.6f %50s" % (term.basename,fc,fc_diag,program.valence.terms[term.diag_term_indexes[i]].basename))
                    if fc_diag==0.0: assert fc==0.0
Example #4
0
def test_uio66zrbrick_crossterms():
    with log.section('NOSETEST', 2):
        # Load input data for a ficticious system of an isolated
        # UiO-66 brick
        name = 'uio66-zr-brick/system.chk'
        fn = context.get_fn(os.path.join('systems', name))
        data = load_chk(fn)
        system = System(data['numbers'],data['pos'],charges=data['charges'],
            ffatypes=data['ffatypes'],bonds=data['bonds'],radii=data['radii'])
        system.set_standard_masses()
        ai = SecondOrderTaylor('ai', coords=system.pos.copy(),
             grad=data['gradient'], hess=data['hessian'])
        # Run QuickFF
        with tmpdir('test_uio66') as dn:
            fn_yaff = os.path.join(dn, 'pars_cov.txt')
            fn_sys = os.path.join(dn, 'system.chk')
            fn_log = os.path.join(dn, 'quickff.log')
            program = DeriveFF(system, ai, Settings(consistent_cross_rvs=True,
                remove_dysfunctional_cross=True,fn_yaff=fn_yaff,fn_sys=fn_sys,log_file=fn_log))
            program.run()
        # Check force constants of cross terms and corresponding diagonal terms
        print("%50s %15s %15s"%("Basename","Cross FC","Diag FC"))
        for term in program.valence.terms:
            if not term.is_master(): continue
            if term.basename.startswith('Cross'):
                fc = program.valence.get_params(term.index, only='fc')
                for i in [0,1]:
                    fc_diag = program.valence.get_params(term.diag_term_indexes[i], only='fc')
                    print("%50s %15.6f %15.6f %50s" % (term.basename,fc,fc_diag,program.valence.terms[term.diag_term_indexes[i]].basename))
                    if fc_diag==0.0: assert fc==0.0
Example #5
0
def check_data(testname, data0, dtype):
    with tmpdir(__name__, testname) as dn:
        fn_test = os.path.join(dn, 'test.chk')
        dump_chk(fn_test, data0)
        data1 = load_chk(fn_test)
        assert data0.keys() == data1.keys()
        assert data0['values'] == data1['values']
        assert isinstance(data1['values'], dtype)
Example #6
0
def check_data_array(testname, data0, dtype):
    with tmpdir(__name__, testname) as dn:
        fn_test = os.path.join(dn, 'test.chk')
        dump_chk(fn_test, data0)
        data1 = load_chk(fn_test)
        assert data0.keys() == data1.keys()
        assert data1['values'].dtype == dtype
        assert (np.asarray(data0['values'], dtype=dtype) == data1['values']).all()
Example #7
0
    def from_file(cls, *fns, **user_kwargs):
        """Construct a new System instance from one or more files

           **Arguments:**

           fn1, fn2, ...
                A list of filenames that are read in order. Information in later
                files overrides information in earlier files.

           **Optional arguments:**

           Any argument from the default constructor ``__init__``. These must be
           given with keywords.

           **Supported file formats**

           .xyz
                Standard Cartesian coordinates file (in angstroms). Atomic
                positions and atomic numbers are read from this file. If the
                title consists of 3, 6 or 9 numbers, each group of three numbers
                is interpreted as a cell vector (in angstroms). A guess of the
                bonds will be made based on inter-atomic distances.

           .psf
                Atom types and bonds are read from this file

           .chk
                Internal text-based checkpoint format. It just contains a
                dictionary with the constructor arguments.
        """
        with log.section('SYS'):
            kwargs = {}
            for fn in fns:
                if fn.endswith('.xyz'):
                    from molmod import Molecule
                    mol = Molecule.from_file(fn)
                    kwargs['numbers'] = mol.numbers.copy()
                    kwargs['pos'] = mol.coordinates.copy()
                elif fn.endswith('.psf'):
                    from molmod.io import PSFFile
                    psf = PSFFile(fn)
                    kwargs['ffatypes'] = psf.atom_types
                    kwargs['bonds'] = np.array(psf.bonds, copy=False)
                    kwargs['charges'] = np.array(psf.charges, copy=False)
                elif fn.endswith('.chk'):
                    from molmod.io import load_chk
                    allowed_keys = [
                        'numbers', 'pos', 'scopes', 'scope_ids', 'ffatypes',
                        'ffatype_ids', 'bonds', 'rvecs', 'charges', 'radii',
                        'dipoles','radii2','masses',
                    ]
                    for key, value in load_chk(fn).iteritems():
                        if key in allowed_keys:
                            kwargs.update({key: value})
                elif fn.endswith('.h5'):
                    with h5.File(fn, 'r') as f:
                        return cls.from_hdf5(f)
                else:
                    raise IOError('Can not read from file \'%s\'.' % fn)
                if log.do_high:
                    log('Read system parameters from %s.' % fn)
            kwargs.update(user_kwargs)
        return cls(**kwargs)
Example #8
0
    def from_file(cls, *fns, **user_kwargs):
        """Construct a new System instance from one or more files

           **Arguments:**

           fn1, fn2, ...
                A list of filenames that are read in order. Information in later
                files overrides information in earlier files.

           **Optional arguments:**

           Any argument from the default constructor ``__init__``. These must be
           given with keywords.

           **Supported file formats**

           .xyz
                Standard Cartesian coordinates file (in angstroms). Atomic
                positions and atomic numbers are read from this file. If the
                title consists of 3, 6 or 9 numbers, each group of three numbers
                is interpreted as a cell vector (in angstroms). A guess of the
                bonds will be made based on inter-atomic distances.

           .psf
                Atom types and bonds are read from this file

           .chk
                Internal text-based checkpoint format. It just contains a
                dictionary with the constructor arguments.
        """
        with log.section('SYS'):
            kwargs = {}
            for fn in fns:
                if fn.endswith('.xyz'):
                    from molmod import Molecule
                    mol = Molecule.from_file(fn)
                    kwargs['numbers'] = mol.numbers.copy()
                    kwargs['pos'] = mol.coordinates.copy()
                elif fn.endswith('.psf'):
                    from molmod.io import PSFFile
                    psf = PSFFile(fn)
                    kwargs['ffatypes'] = psf.atom_types
                    kwargs['bonds'] = np.array(psf.bonds, copy=False)
                    kwargs['charges'] = np.array(psf.charges, copy=False)
                elif fn.endswith('.chk'):
                    from molmod.io import load_chk
                    allowed_keys = [
                        'numbers',
                        'pos',
                        'scopes',
                        'scope_ids',
                        'ffatypes',
                        'ffatype_ids',
                        'bonds',
                        'rvecs',
                        'charges',
                        'radii',
                        'valence_charges',
                        'dipoles',
                        'radii2',
                        'masses',
                    ]
                    for key, value in load_chk(fn).items():
                        if key in allowed_keys:
                            kwargs.update({key: value})
                elif fn.endswith('.h5'):
                    with h5.File(fn, 'r') as f:
                        return cls.from_hdf5(f)
                else:
                    raise IOError('Can not read from file \'%s\'.' % fn)
                if log.do_high:
                    log('Read system parameters from %s.' % fn)
            kwargs.update(user_kwargs)
        return cls(**kwargs)