Esempio n. 1
0
    def test_harmonic(self):
        a = 20.0
        hb = HarmonicBasis(20, a)
        x = np.arange(0.0, a, 0.1)
        v = 0.5*(x-a/2)**2
        #v = 5*(1+np.cos(2*np.pi*x/a))**2
        v_coeffs = hb.fit_fn(x, v, 20, even=True, v_threshold=0.1)
        energies, orbitals = hb.solve(1, v_coeffs, evecs=True)
        expected = np.arange(10) + 0.5
        self.assertAlmostEqual(energies[0], 0.5, 1)
        self.assertAlmostEqual(energies[1], 1.5, 1)
        self.assertAlmostEqual(energies[2], 2.5, 1)
        self.assertAlmostEqual(energies[3], 3.5, 1)
        self.assertAlmostEqual(energies[4], 4.5, 1)
        self.assertAlmostEqual(energies[5], 5.5, 1)
        self.assertAlmostEqual(energies[6], 6.5, 1)

        import matplotlib.pyplot as pt
        x = np.arange(0.0, a, 0.001)
        pt.clf()
        for i in xrange(10):
            f = hb.eval_fn(x, orbitals[:,i])
            pt.plot(x, f)
        with tmpdir(__name__, 'test_harmonic1') as dn:
            pt.savefig(os.path.join(dn, "harmonic_wavefunctions.png"))
        pt.clf()
        v = hb.eval_fn(x, v_coeffs)
        pt.plot(x, v)
        for energy in energies[:10]:
            pt.axhline(energy)
        pt.xlim(0,a)
        with tmpdir(__name__, 'test_harmonic2') as dn:
            pt.savefig(os.path.join(dn, "harmonic_levels.png"))
Esempio n. 2
0
    def test_harmonic(self):
        a = 20.0
        hb = HarmonicBasis(20, a)
        x = np.arange(0.0, a, 0.1)
        v = 0.5 * (x - a / 2)**2
        #v = 5*(1+np.cos(2*np.pi*x/a))**2
        v_coeffs = hb.fit_fn(x, v, 20, even=True, v_threshold=0.1)
        energies, orbitals = hb.solve(1, v_coeffs, evecs=True)
        expected = np.arange(10) + 0.5
        self.assertAlmostEqual(energies[0], 0.5, 1)
        self.assertAlmostEqual(energies[1], 1.5, 1)
        self.assertAlmostEqual(energies[2], 2.5, 1)
        self.assertAlmostEqual(energies[3], 3.5, 1)
        self.assertAlmostEqual(energies[4], 4.5, 1)
        self.assertAlmostEqual(energies[5], 5.5, 1)
        self.assertAlmostEqual(energies[6], 6.5, 1)

        import matplotlib.pyplot as pt
        x = np.arange(0.0, a, 0.001)
        pt.clf()
        for i in range(10):
            f = hb.eval_fn(x, orbitals[:, i])
            pt.plot(x, f)
        with tmpdir(__name__, 'test_harmonic1') as dn:
            pt.savefig(os.path.join(dn, "harmonic_wavefunctions.png"))
        pt.clf()
        v = hb.eval_fn(x, v_coeffs)
        pt.plot(x, v)
        for energy in energies[:10]:
            pt.axhline(energy)
        pt.xlim(0, a)
        with tmpdir(__name__, 'test_harmonic2') as dn:
            pt.savefig(os.path.join(dn, "harmonic_levels.png"))
Esempio n. 3
0
    def test_checkpoint(self):
        molecule = load_molecule_cp2k(
            pkg_resources.resource_filename("tamkin", "data/test/cp2k/pentane/sp.out"),
            pkg_resources.resource_filename("tamkin", "data/test/cp2k/pentane/freq.out"))
        nma1 = NMA(molecule)
        with tmpdir(__name__, 'test_checkpoint') as dn:
            fn_out = os.path.join(dn, 'test.chk')
            nma1.write_to_file(fn_out)
            nma2 = NMA.read_from_file(fn_out)

        self.assertEqual(nma1.freqs.shape, nma2.freqs.shape)
        self.assertEqual(nma1.modes.shape, nma2.modes.shape)
        self.assertEqual(nma1.masses.shape, nma2.masses.shape)
        self.assertEqual(nma1.numbers.shape, nma2.numbers.shape)
        self.assertEqual(nma1.coordinates.shape, nma2.coordinates.shape)
        self.assertEqual(nma1.inertia_tensor.shape, nma2.inertia_tensor.shape)

        assert abs(nma1.freqs - nma2.freqs).max()/abs(nma1.freqs).max() < 1e-15
        assert abs(nma1.modes - nma2.modes).max()/abs(nma1.modes).max() < 1e-15
        assert abs(nma1.masses - nma2.masses).max()/abs(nma1.masses).max() < 1e-15
        assert abs(nma1.coordinates - nma2.coordinates).max()/abs(nma1.coordinates).max() < 1e-15
        assert abs(nma1.inertia_tensor - nma2.inertia_tensor).max()/abs(nma1.inertia_tensor).max() < 1e-15
        assert (nma1.numbers==nma2.numbers).all()

        self.assertAlmostEqual(nma1.mass, nma2.mass)
        self.assertAlmostEqual(nma1.energy, nma2.energy)
        self.assertEqual(nma1.multiplicity, nma2.multiplicity)
        self.assertEqual(nma1.symmetry_number, nma2.symmetry_number)
Esempio n. 4
0
    def test_checkpoint(self):
        molecule = load_molecule_cp2k(
            pkg_resources.resource_filename(__name__, "../data/test/cp2k/pentane/sp.out"),
            pkg_resources.resource_filename(__name__, "../data/test/cp2k/pentane/freq.out"))
        nma1 = NMA(molecule)
        with tmpdir(__name__, 'test_checkpoint') as dn:
            fn_out = os.path.join(dn, 'test.chk')
            nma1.write_to_file(fn_out)
            nma2 = NMA.read_from_file(fn_out)

        self.assertEqual(nma1.freqs.shape, nma2.freqs.shape)
        self.assertEqual(nma1.modes.shape, nma2.modes.shape)
        self.assertEqual(nma1.masses.shape, nma2.masses.shape)
        self.assertEqual(nma1.numbers.shape, nma2.numbers.shape)
        self.assertEqual(nma1.coordinates.shape, nma2.coordinates.shape)
        self.assertEqual(nma1.inertia_tensor.shape, nma2.inertia_tensor.shape)

        self.assert_(abs(nma1.freqs - nma2.freqs).max()/abs(nma1.freqs).max() < 1e-15)
        self.assert_(abs(nma1.modes - nma2.modes).max()/abs(nma1.modes).max() < 1e-15)
        self.assert_(abs(nma1.masses - nma2.masses).max()/abs(nma1.masses).max() < 1e-15)
        self.assert_(abs(nma1.coordinates - nma2.coordinates).max()/abs(nma1.coordinates).max() < 1e-15)
        self.assert_(abs(nma1.inertia_tensor - nma2.inertia_tensor).max()/abs(nma1.inertia_tensor).max() < 1e-15)
        self.assert_((nma1.numbers==nma2.numbers).all())

        self.assertAlmostEqual(nma1.mass, nma2.mass)
        self.assertAlmostEqual(nma1.energy, nma2.energy)
        self.assertEqual(nma1.multiplicity, nma2.multiplicity)
        self.assertEqual(nma1.symmetry_number, nma2.symmetry_number)
Esempio n. 5
0
    def test_ethane_hindered(self):
        molecule = load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/ethane/gaussian.fchk"))
        nma = NMA(molecule)
        rot_scan = load_rotscan_g03log(
            pkg_resources.resource_filename(__name__, "../data/test/rotor/gaussian.log"))
        rotor = Rotor(rot_scan, molecule, rotsym=3, even=True, cancel_freq='scan')
        pf = PartFun(nma, [ExtTrans(), ExtRot(6), rotor])
        self.assertAlmostEqual(rotor.cancel_freq/lightspeed*centimeter, 298, 0)
        rotor = Rotor(rot_scan, molecule, rotsym=3, even=True)
        self.assertAlmostEqual(rotor.cancel_freq/lightspeed*centimeter, 314, 0)
        pf = PartFun(nma, [ExtTrans(), ExtRot(6), rotor])
        self.assertArraysAlmostEqual(
            rotor.hb.eval_fn(rot_scan.potential[0], rotor.v_coeffs),
            rot_scan.potential[1] - rot_scan.potential[1].min(), 1e-4
        )
        # reference data from legacy code (Veronique & co)
        self.assertAlmostEqual(rotor.moment/amu, 11.092362911176032, 2)
        self.assertAlmostEqual(rotor.reduced_moment/amu, 5.5461814555880098, 2)
        self.assertAlmostEqual(np.exp(rotor.log_terms(100.0)[1]), 0.12208E+00, 1)
        self.assertAlmostEqual(rotor.heat_capacity_terms(100.0)[1]/(joule/mol/kelvin), 2.567, 0)
        self.assertAlmostEqual(rotor.entropy_terms(100.0)[1]/(joule/mol), 0.766, 0)
        self.assertAlmostEqual(np.exp(rotor.log_terms(800.0)[1]), 0.21108E+01, 1)
        self.assertAlmostEqual(rotor.heat_capacity_terms(800.0)[1]/(joule/mol/kelvin), 6.346, 1)
        self.assertAlmostEqual(rotor.entropy_terms(800.0)[1]/(joule/mol), 14.824, 1)

        with tmpdir(__name__, 'test_ethane_hindered') as dn:
            rotor.plot_levels(os.path.join(dn, "ethane_hindered_levels.png"), 300)
            pf.write_to_file(os.path.join(dn, "ethane_hindered.txt"))
            ta = ThermoAnalysis(pf, [200,300,400,500,600,700,800,900])
            ta.write_to_file(os.path.join(dn, "ethane_hindered_thermo.csv"))
Esempio n. 6
0
    def test_legacy1(self):
        a = 2*np.pi
        mass = 5.5*amu
        hb = HarmonicBasis(100, a)
        v_coeffs = np.zeros(hb.size, float)
        v_coeffs[0] = 0.5*11.5*kjmol*np.sqrt(a)
        v_coeffs[5] = 0.5*11.5*kjmol*np.sqrt(a/2)
        self.assertArraysAlmostEqual(
            hb.eval_fn(np.array([0, a/6]), v_coeffs),
            np.array([11.5*kjmol, 0.0]),
        )
        energies, orbitals = hb.solve(mass, v_coeffs, evecs=True)

        import matplotlib.pyplot as pt
        x = np.arange(0.0, a, 0.001)
        pt.clf()
        for i in xrange(10):
            f = hb.eval_fn(x, orbitals[:,i])
            pt.plot(x, f+i)
        with tmpdir(__name__, 'test_legacy1') as dn:
            pt.savefig(os.path.join(dn, "legacy_wavefunctions.png"))

        # check energy levels
        expected = np.array([
            1.7635118, 1.76361979, 5.11795465, 8.04553104, 8.1095722,
            10.3876796, 11.8999683, 12.9078395, 14.6739639, 16.7836847,
            19.1722507,
            1.76361979,  5.11795465, 5.12218335, 8.1095722, 10.3876796,
            10.8661504, 12.9078395, 14.6739639, 16.7544718, 19.1722507,
        ])
        expected.sort()
        self.assertArraysAlmostEqual(energies[:10]/kjmol, expected[:10], 1e-3)
        self.assertAlmostEqual(np.exp(-energies/(100*boltzmann)).sum()/3.0, 0.12208E+00, 5)
Esempio n. 7
0
def compare_lammps_yaff_swap_noncovalent(name, thresh=1.0):
    # Load the system
    fn_system = pkg_resources.resource_filename(__name__, '../../data/test/system_%s.chk'%name)
    system = System.from_file(fn_system)
    # Generate the YAFF ForceField
    fn_pars = pkg_resources.resource_filename(__name__, '../../data/test/parameters_%s.txt'%name)
    ff = ForceField.generate(system, fn_pars, alpha_scale=3.2, gcut_scale=1.5, rcut=15.0*angstrom, smooth_ei=True)
    gpos_yaff, vtens_yaff = np.zeros(ff.system.pos.shape), np.zeros((3,3))
    eyaff = ff.compute(gpos=gpos_yaff, vtens=vtens_yaff)
    pyaff = np.trace(vtens_yaff)/3.0/ff.system.cell.volume
    # Replace noncovalent contributions with LAMMPS table
    with tmpdir(__name__, 'test_liblammps_swap') as dirname:
        fn_system = os.path.join(dirname,'system.dat')
        fn_table = os.path.join(dirname,'table.dat')
        ff_lammps = swap_noncovalent_lammps(ff, fn_system=fn_system,
            fn_table=fn_table)
        gpos_lammps, vtens_lammps = np.zeros(ff.system.pos.shape), np.zeros((3,3))
        elammps = ff_lammps.compute(gpos=gpos_lammps, vtens=vtens_lammps)
        plammps = np.trace(vtens_lammps)/3.0/ff.system.cell.volume
        rmsd_gpos = np.std(gpos_yaff-gpos_lammps)
        rmsd_vtens = np.std(vtens_yaff-vtens_lammps)
        print("E_YAFF = %12.4f E_LAMMPS = %12.4f E_DIFF = %12.4f kJ/mol"%(eyaff/kjmol,elammps/kjmol,(eyaff-elammps)/kjmol))
        print("P_YAFF = %12.4f P_LAMMPS = %12.4f P_DIFF = %12.4f MPa"%(pyaff/mpa,plammps/mpa,(pyaff-plammps)/mpa))
        print("RMSD GPOS  = %12.8f kJ/mol/A"%(rmsd_gpos/kjmol*angstrom))
        print("RMSD VTENS = %12.8f kJ/mol"%(rmsd_vtens/kjmol))
        assert np.abs(eyaff-elammps)<1e-1*kjmol*thresh
        assert np.abs(pyaff-plammps)<1*mpa*thresh
        assert rmsd_gpos<1e-2*kjmol/angstrom*thresh
        assert rmsd_vtens<0.5*kjmol*thresh
Esempio n. 8
0
def compare_lammps_yaff_ff(ff, thresh=1.0, do_ei=True, do_vdw=True):
    lammps_ffa, lammps_ffa_ids = get_lammps_ffatypes(ff)
    gpos_yaff, vtens_yaff = np.zeros(ff.system.pos.shape), np.zeros((3,3))
    eyaff = ff.compute(gpos=gpos_yaff, vtens=vtens_yaff)
    with tmpdir(__name__, 'test_liblammps') as dirname:
        # Write LAMMPS data file
        fn_system = os.path.join(dirname,'system.dat')
        write_lammps_system_data(ff.system, ff=ff,fn=fn_system)
        # Write LAMMPS table file
        fn_table = os.path.join(dirname,'table.dat')
        write_lammps_table(ff,fn=fn_table)
        # Construct the LAMMPS force-field contribution
        fn_log = os.path.join(dirname,'lammps.log')
        part_lammps = ForcePartLammps(ff,fn_log=fn_log,scalings_table=np.zeros(3),scalings_ei=np.zeros(3),
            fn_system=fn_system,fn_table=fn_table,do_ei=do_ei, do_table=do_vdw)
        gpos_lammps, vtens_lammps = np.zeros(ff.system.pos.shape), np.zeros((3,3))
        elammps = part_lammps.compute(gpos=gpos_lammps, vtens=vtens_lammps)
        rmsd_gpos = np.std(gpos_yaff-gpos_lammps)
        rmsd_vtens = np.std(vtens_yaff-vtens_lammps)
#        print("E_YAFF = %12.4f E_LAMMPS = %12.4f E_DIFF = %12.4f kJ/mol"%(eyaff/kjmol,elammps/kjmol,(eyaff-elammps)/kjmol))
#        print("RMSD GPOS  = %12.8f kJ/mol/A"%(rmsd_gpos/kjmol*angstrom))
#        print("RMSD VTENS = %12.8f kJ/mol"%(rmsd_vtens/kjmol))
        assert np.abs(eyaff-elammps)<1e-3*kjmol*thresh
        assert rmsd_gpos<1e-4*kjmol/angstrom*thresh
        assert rmsd_vtens<1e-2*kjmol*thresh
Esempio n. 9
0
def test_molecule_checkpoint_full():
    mol1 = load_molecule_g03fchk(
        pkg_resources.resource_filename(__name__, "../data/test/sterck/aa.fchk"))
    mol1.set_default_graph()
    mol1.unit_cell = UnitCell(np.identity(3, float)*25)
    mol1.symbols = [periodic[n].symbol for n in mol1.numbers]
    with tmpdir(__name__, 'test_molecule_checkpoint_full') as dn:
        fn_out = os.path.join(dn, "molecule_checkpoint_full.chk")
        mol1.write_to_file(fn_out)
        mol2 = Molecule.read_from_file(fn_out)

    assert mol1.numbers.shape == mol2.numbers.shape
    assert abs(mol1.numbers - mol2.numbers).max() == 0
    assert mol1.coordinates.shape == mol2.coordinates.shape
    assert abs(mol1.coordinates - mol2.coordinates).max() < 1e-10
    assert mol1.masses.shape == mol2.masses.shape
    assert abs(mol1.masses - mol2.masses).max() < 1e-10
    assert abs(mol1.energy - mol2.energy) < 1e-10
    assert mol1.gradient.shape == mol2.gradient.shape
    assert abs(mol1.gradient - mol2.gradient).max() < 1e-10
    assert mol1.hessian.shape == mol2.hessian.shape
    assert abs(mol1.hessian - mol2.hessian).max() < 1e-10
    assert mol1.multiplicity == mol2.multiplicity
    assert mol1.symmetry_number == mol2.symmetry_number
    assert mol1.periodic == mol2.periodic

    assert mol1.graph.edges == mol2.graph.edges
    assert mol1.title == mol2.title
    assert mol1.unit_cell.matrix.shape == mol2.unit_cell.matrix.shape
    assert abs(mol1.unit_cell.matrix - mol2.unit_cell.matrix).max() < 1e-10
    assert mol1.unit_cell.active.shape == mol2.unit_cell.active.shape
    assert (mol1.unit_cell.active == mol2.unit_cell.active).all()
    assert mol1.symbols == mol2.symbols
Esempio n. 10
0
def test_consistency_io():
    for fn_parameters in '../../data/test/parameters_bks.txt', '../../data/test/parameters_water.txt':
        pf1 = Parameters.from_file(pkg_resources.resource_filename(__name__, fn_parameters))
        with tmpdir(__name__, 'test_consistency_io') as dn:
            pf1.write_to_file('%s/parameters_foo.txt' % dn)
            pf2 = Parameters.from_file('%s/parameters_foo.txt' % dn)
            check_consistent(pf1, pf2)
Esempio n. 11
0
def test_plumed_md():
    with tmpdir(__name__, 'test_plumed_md') as dirname:
        ff = get_ff_water32()
        kappa, V0 = 1.6 * kjmol / angstrom**6, ff.system.cell.volume
        # PLUMED input commands
        commands = "vol: VOLUME\n"
        commands += "RESTRAINT ARG=vol AT=%.20f KAPPA=%.20f LABEL=restraint\n"%\
            (V0/nanometer**3,kappa/kjmol*nanometer**6)
        commands += "PRINT STRIDE=1 ARG=vol FILE=%s\n" % (os.path.join(
            dirname, 'cv.log'))
        commands += "FLUSH STRIDE=1\n"
        # Write PLUMED commands to file
        fn = os.path.join(dirname, 'plumed.dat')
        with open(fn, 'w') as f:
            f.write(commands)
        # Setup Plumed
        timestep = 1.0 * femtosecond
        plumed = ForcePartPlumed(ff.system, timestep=timestep, fn=fn)
        ff.add_part(plumed)
        # Setup integrator with a barostat, so plumed has to compute forces
        # more than once per timestep
        tbc = TBCombination(MTKBarostat(ff, 300, 1 * bar), NHCThermostat(300))
        verlet = VerletIntegrator(ff, timestep, hooks=[tbc, plumed])
        # Run a short MD simulation, keeping track of the CV (volume in this case)
        cvref = [ff.system.cell.volume]
        for i in range(4):
            verlet.run(1)
            cvref.append(ff.system.cell.volume)
        # Read the PLUMED output and compare with reference
        cv = np.loadtxt(os.path.join(dirname, 'cv.log'))
        assert cv.shape[0] == 5
        assert np.allclose(cv[:, 0] * picosecond, np.arange(5) * timestep)
        assert np.allclose(cv[:, 1] * nanometer**3, cvref)
Esempio n. 12
0
 def test_dump_modes_xyz(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename(__name__,
                                         "../data/test/an/ethanol.cor"),
         pkg_resources.resource_filename(
             __name__, "../data/test/an/ethanol.hess.full"))
     nma = NMA(molecule)
     with tmpdir(__name__, 'test_dump_modes_xyz') as dn:
         prefix = os.path.join(dn, 'mode')
         dump_modes_xyz(nma, 6, prefix=prefix, amplitude=50.0)
         with open(prefix + ".6.xyz") as f:
             # 1st line
             line = f.readline().strip()
             self.assertEqual(line, "9")
             # 2nd line
             line = f.readline().strip()
             self.assertEqual(line, "frame 0")
             # 3rd line
             line = f.readline()
             words = line.split()
             self.assertEqual(len(words), 4)
             self.assertEqual(words[0], "C")
             self.assertEqual(words[2], "0.081608346")
             for i in range(9):
                 line = f.readline().strip()
             self.assertEqual(line, "9")
Esempio n. 13
0
    def test_reaction_analysis_sterck(self):
        pf_react1 = PartFun(
            NMA(
                load_molecule_g03fchk(
                    pkg_resources.resource_filename(
                        __name__, "../data/test/sterck/aa.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])
        pf_react2 = PartFun(
            NMA(
                load_molecule_g03fchk(
                    pkg_resources.resource_filename(
                        __name__, "../data/test/sterck/aarad.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])
        pf_ts = PartFun(
            NMA(
                load_molecule_g03fchk(
                    pkg_resources.resource_filename(
                        __name__, "../data/test/sterck/paats.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])

        km = KineticModel([pf_react1, pf_react2], pf_ts)
        ra = ReactionAnalysis(km, 280, 360)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea / kjmol, 25.96, 1)
        self.assertAlmostEqual(km.unit, meter**3 / mol / second)
        self.assertEqual(km.unit_name, "m^3 mol^-1 s^-1")
        self.assertAlmostEqual(np.log(ra.A / km.unit), np.log(2.29E+02), 1)

        with tmpdir(__name__, 'test_reaction_analysis_sterck') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_aa.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_aa.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_aa.png"))
Esempio n. 14
0
    def test_plot_spectrum(self):
        molecule = load_molecule_charmm(
            pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.cor"),
            pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.hess.full"))
        nma = NMA(molecule)
        invcm = lightspeed/centimeter
        with tmpdir(__name__, 'test_plot_spectrum') as dn:
            plot_spectrum_lines(
                os.path.join(dn, "spectrum-lines.1.png"),
                [nma.freqs, nma.freqs], title="standard settings")
            plot_spectrum_lines(
                os.path.join(dn, "spectrum-lines.2.png"),
                [nma.freqs, nma.freqs], low=-10.0*invcm, high=500.0*invcm, title="zoom")

            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.1.png"),
                [nma.freqs], title="standard settings")
            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.2.png"),
                [nma.freqs], low=-10.0*invcm, high=1500.0*invcm, title="zoom")
            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.3.png"),
                [nma.freqs], low=-10.0*invcm, high=1500.0*invcm, width=50.0*invcm, title="width")
            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.4.png"),
                [nma.freqs], low=-10.0*invcm, high=1500.0*invcm, width=50.0*invcm, step=20.0*invcm, title="step size")
            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.5.png"),
                [nma.freqs, nma.freqs*1.1], title="two spectra")
            plot_spectrum_dos(
                os.path.join(dn, "spectrum-dos.6.png"),
                [nma.freqs, nma.freqs*1.1], all_amps=[1.0,2.0], title="different amplitude")
Esempio n. 15
0
    def test_reaction_analysis_sterck(self):
        pf_react1 = PartFun(NMA(load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/sterck/aa.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])
        pf_react2 = PartFun(NMA(load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/sterck/aarad.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])
        pf_ts = PartFun(NMA(load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/sterck/paats.fchk"))),
            [ExtTrans(cp=False), ExtRot(1)])

        km = KineticModel([pf_react1, pf_react2], pf_ts)
        ra = ReactionAnalysis(km, 280, 360)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea/kjmol, 25.96, 1)
        self.assertAlmostEqual(km.unit, meter**3/mol/second)
        self.assertEqual(km.unit_name, "m^3 mol^-1 s^-1")
        self.assertAlmostEqual(np.log(ra.A/km.unit), np.log(2.29E+02), 1)

        with tmpdir(__name__, 'test_reaction_analysis_sterck') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_aa.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_aa.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_aa.png"))
Esempio n. 16
0
    def test_reaction_analysis_mat(self):
        pf_react = PartFun(
            NMA(
                load_molecule_g03fchk(
                    pkg_resources.resource_filename(
                        __name__, "../data/test/mat5T/react.fchk"))), [])
        pf_ts = PartFun(
            NMA(
                load_molecule_g03fchk(
                    pkg_resources.resource_filename(
                        __name__, "../data/test/mat5T/ts.fchk"))), [])

        km = KineticModel([pf_react], pf_ts)
        ra = ReactionAnalysis(km, 100, 1200, temp_step=50)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea / kjmol, 160.6, 0)
        self.assertAlmostEqual(km.unit, 1.0 / second)
        self.assertEqual(km.unit_name, "s^-1")
        self.assertAlmostEqual(np.log(ra.A / km.unit), np.log(3.33e10), 0)
        with tmpdir(__name__, 'test_reaction_analysis_mat1') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat1.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat1.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat1.png"))

        wigner = Wigner(pf_ts)  # Blind test of the wigner correction and
        # the corrected reaction analysis.
        km = KineticModel([pf_react], pf_ts, tunneling=wigner)
        ra = ReactionAnalysis(km, 100, 1200, temp_step=50)
        with tmpdir(__name__, 'test_reaction_analysis_mat2') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat1w.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat1w.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat1w.png"))

        km = KineticModel([pf_react], pf_ts)
        ra = ReactionAnalysis(km, 670, 770)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea / kjmol, 161.9, 1)
        self.assertAlmostEqual(np.log(ra.A / km.unit), np.log(4.08e10), 0)
        with tmpdir(__name__, 'test_reaction_analysis_mat3') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat2.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat2.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat2.png"))
Esempio n. 17
0
    def test_load_dump_indices1(self):
        subs = range(10)
        with tmpdir(__name__, 'test_load_dump_indices1') as dn:
            dump_indices(os.path.join(dn, "subs-atoms.1.txt"), subs, shift=0)
            dump_indices(os.path.join(dn, "subs-atoms.2.txt"), subs, shift=1)
            dump_indices(os.path.join(dn, "subs-atoms.3.txt"), subs)

            subs1 = load_indices(os.path.join(dn, "subs-atoms.1.txt"), shift=0)
            subs2 = load_indices(os.path.join(dn, "subs-atoms.2.txt"),
                                 shift=-1)
            subs22 = load_indices(os.path.join(
                dn, "subs-atoms.2.txt"))  # should not matter
            subs3 = load_indices(os.path.join(dn, "subs-atoms.3.txt"))

            blocks = [range(10), range(10, 20)]
            dump_indices(os.path.join(dn, "blocks.1.txt"), blocks, shift=0)
            dump_indices(os.path.join(dn, "blocks.2.txt"), blocks, shift=1)
            dump_indices(os.path.join(dn, "blocks.3.txt"), blocks)

            blocks1 = load_indices(os.path.join(dn, "blocks.1.txt"),
                                   shift=0,
                                   groups=True)
            blocks2 = load_indices(os.path.join(dn, "blocks.2.txt"),
                                   shift=-1,
                                   groups=True)
            blocks22 = load_indices(os.path.join(dn, "blocks.2.txt"),
                                    groups=True)  # should not matter
            blocks3 = load_indices(os.path.join(dn, "blocks.3.txt"),
                                   groups=True)

        self.assertEqual(len(subs), len(subs1))
        for (i, j) in zip(subs, subs1):
            self.assertEqual(i, j)
        self.assertEqual(len(subs), len(subs2))
        for i, j in zip(subs, subs2):
            self.assertEqual(i, j)
        self.assertEqual(len(subs), len(subs22))
        for i, j in zip(subs, subs22):
            self.assertEqual(i, j)
        self.assertEqual(len(subs), len(subs3))
        for i, j in zip(subs, subs3):
            self.assertEqual(i, j)

        self.assertEqual(len(blocks), len(blocks1))
        for bl, bl1 in zip(blocks, blocks1):
            for i, j in zip(bl, bl1):
                self.assertEqual(i, j)
        self.assertEqual(len(blocks), len(blocks2))
        for bl, bl1 in zip(blocks, blocks2):
            for i, j in zip(bl, bl1):
                self.assertEqual(i, j)
        self.assertEqual(len(blocks), len(blocks22))
        for bl, bl1 in zip(blocks, blocks22):
            for i, j in zip(bl, bl1):
                self.assertEqual(i, j)
        self.assertEqual(len(blocks), len(blocks3))
        for bl, bl1 in zip(blocks, blocks3):
            for i, j in zip(bl, bl1):
                self.assertEqual(i, j)
Esempio n. 18
0
def test_consistency_io():
    for fn_parameters in '../../data/test/parameters_bks.txt', '../../data/test/parameters_water.txt':
        pf1 = Parameters.from_file(
            pkg_resources.resource_filename(__name__, fn_parameters))
        with tmpdir(__name__, 'test_consistency_io') as dn:
            pf1.write_to_file('%s/parameters_foo.txt' % dn)
            pf2 = Parameters.from_file('%s/parameters_foo.txt' % dn)
            check_consistent(pf1, pf2)
Esempio n. 19
0
 def test_thermo_analysis_mat(self):
     # just a blind test to see test whether the code does not crash.
     pf = PartFun(NMA(load_molecule_g03fchk(
         pkg_resources.resource_filename("tamkin", "data/test/mat5T/react.fchk"))),
         [ExtTrans(), ExtRot(1)])
     ta = ThermoAnalysis(pf, [200,300,400,500,600,700,800,900])
     with tmpdir(__name__, 'test_thermo_analysis_mat') as dn:
         ta.write_to_file(os.path.join(dn, "thermo_mat2.csv"))
Esempio n. 20
0
 def test_thermo_analysis_mat(self):
     # just a blind test to see test whether the code does not crash.
     pf = PartFun(NMA(load_molecule_g03fchk(
         pkg_resources.resource_filename(__name__, "../data/test/mat5T/react.fchk"))),
         [ExtTrans(), ExtRot(1)])
     ta = ThermoAnalysis(pf, [200,300,400,500,600,700,800,900])
     with tmpdir(__name__, 'test_thermo_analysis_mat') as dn:
         ta.write_to_file(os.path.join(dn, "thermo_mat2.csv"))
Esempio n. 21
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)
Esempio n. 22
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()
Esempio n. 23
0
def test_mtd_alanine():
    try:
        from plumed import Plumed
    except:
        from nose.plugins.skip import SkipTest
        raise SkipTest(
            'Could not import PLUMED, skipping PLUMED related tests')
    # MTD settings
    sigma = 0.35 * rad
    pace = 4
    K = 1.2 * kjmol
    # Construct metadynamics as a Yaff hook
    ff = get_alaninedipeptide_amber99ff()
    cv = CVInternalCoordinate(ff.system, DihedAngle(4, 6, 8, 14))
    with h5.File('yaff.sampling.test.test_enhanced.test_mtd_alanine.h5',
                 driver='core',
                 backing_store=False) as f:
        hdf5 = HDF5Writer(f)
        mtd = MTDHook(ff,
                      cv,
                      sigma,
                      K,
                      f=f,
                      start=pace,
                      step=pace,
                      periodicities=2 * np.pi)
        nvt = VerletIntegrator(ff, 1.0 * femtosecond, hooks=[mtd])
        vel0 = nvt.vel.copy()
        nvt.run(12)
        # Check HDF5 output
        assert 'hills' in f
        assert np.all(f['hills/q0'][:] == mtd.hills.q0s)
        assert np.all(f['hills/K'][:] == mtd.hills.Ks)
        assert f['hills/sigma'].shape[0] == 1
        assert f['hills/sigma'][0] == sigma
    # Same simulation using PLUMED
    with tmpdir(__name__, 'test_mtd_alanine') as dirname:
        # PLUMED input commands
        commands = "phi: TORSION ATOMS=5,7,9,15\n"
        commands += "metad: METAD ARG=phi PACE=%d HEIGHT=%f SIGMA=%f FILE=%s\n"\
            % (pace, K/kjmol, sigma/rad, os.path.join(dirname,'hills'))
        commands += "FLUSH STRIDE=1"
        # Write PLUMED commands to file
        fn = os.path.join(dirname, 'plumed.dat')
        with open(fn, 'w') as f:
            f.write(commands)
        # Setup Plumed
        ff = get_alaninedipeptide_amber99ff()
        plumed = ForcePartPlumed(ff.system, fn=fn)
        ff.add_part(plumed)
        nvt = VerletIntegrator(ff,
                               1.0 * femtosecond,
                               hooks=[plumed],
                               vel0=vel0)
        nvt.run(12)
        hills = np.loadtxt(os.path.join(dirname, 'hills'))
    # Compare hill centers
    assert np.all(np.abs(hills[:, 1] - mtd.hills.q0s[:, 0]) < 1e-10 * rad)
Esempio n. 24
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)
Esempio n. 25
0
 def test_dump_modes_gaussian(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename("tamkin", "data/test/an/ethanol.cor"),
         pkg_resources.resource_filename("tamkin", "data/test/an/ethanol.hess.full"))
     nma = NMA(molecule)
     with tmpdir(__name__, 'test_dump_modes_gaussian') as dn:
         # blind test, no double checking of the output file
         fn_log = os.path.join(dn, 'modes_gaussian.log')
         dump_modes_gaussian(fn_log, nma)
Esempio n. 26
0
 def test_dump_modes_gaussian(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.cor"),
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.hess.full"))
     nma = NMA(molecule)
     with tmpdir(__name__, 'test_dump_modes_gaussian') as dn:
         # blind test, no double checking of the output file
         fn_log = os.path.join(dn, 'modes_gaussian.log')
         dump_modes_gaussian(fn_log, nma)
Esempio n. 27
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)
Esempio n. 28
0
def test_lammps_system_data_water32():
    system = get_system_water32()
    with tmpdir(__name__, 'test_lammps_system_water32') as dirname:
        fn = os.path.join(dirname, 'lammps.system')
        write_lammps_system_data(system, fn=fn)
        with open(fn, 'r') as f:
            lines = f.readlines()
        natom = int(lines[2].split()[0])
        assert natom == system.natom
        assert (system.natom + system.bonds.shape[0] + 23) == len(lines)
Esempio n. 29
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'))
Esempio n. 30
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)
Esempio n. 31
0
def test_blav():
    # generate a time-correlated random signal
    n = 50000
    eps0 = 30.0/n
    eps1 = 1.0
    y = np.sin(np.random.normal(0, eps0, n).cumsum() + np.random.normal(0, eps1, n))
    # create a temporary directory to write the plot to
    with tmpdir(__name__, 'test_blav') as dn:
        fn_png = '%s/blav.png' % dn
        error, sinef = blav(y, 100, fn_png)
        assert os.path.isfile(fn_png)
Esempio n. 32
0
    def test_reaction_analysis_mat(self):
        pf_react = PartFun(NMA(load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/mat5T/react.fchk"))), [])
        pf_ts = PartFun(NMA(load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/mat5T/ts.fchk"))), [])

        km = KineticModel([pf_react], pf_ts)
        ra = ReactionAnalysis(km, 100, 1200, temp_step=50)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea/kjmol, 160.6, 0)
        self.assertAlmostEqual(km.unit, 1.0/second)
        self.assertEqual(km.unit_name, "s^-1")
        self.assertAlmostEqual(np.log(ra.A/km.unit), np.log(3.33e10), 0)
        with tmpdir(__name__, 'test_reaction_analysis_mat1') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat1.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat1.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat1.png"))

        wigner = Wigner(pf_ts) # Blind test of the wigner correction and
        # the corrected reaction analysis.
        km = KineticModel([pf_react], pf_ts, tunneling=wigner)
        ra = ReactionAnalysis(km, 100, 1200, temp_step=50)
        with tmpdir(__name__, 'test_reaction_analysis_mat2') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat1w.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat1w.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat1w.png"))

        km = KineticModel([pf_react], pf_ts)
        ra = ReactionAnalysis(km, 670, 770)
        # not a very accurate check because the fit is carried out differently
        # in the fancy excel file where these numbers come from.
        self.assertAlmostEqual(ra.Ea/kjmol, 161.9, 1)
        self.assertAlmostEqual(np.log(ra.A/km.unit), np.log(4.08e10), 0)
        with tmpdir(__name__, 'test_reaction_analysis_mat3') as dn:
            ra.plot_arrhenius(os.path.join(dn, "arrhenius_mat2.png"))
            ra.monte_carlo()
            ra.write_to_file(os.path.join(dn, "reaction_mat2.txt"))
            ra.plot_parameters(os.path.join(dn, "parameters_mat2.png"))
Esempio n. 33
0
def run_opt_water32(suffix, prefix):
    # Work in a temporary directory
    with tmpdir(suffix, prefix) as dn_tmp:
        # Setup a test FF
        ff = get_ff_water32()
        # Run a test simulation
        with h5.File('%s/output.h5' % dn_tmp) as f:
            hdf5 = HDF5Writer(f)
            opt = CGOptimizer(FullCellDOF(ff), hooks=hdf5)
            opt.run(5)
            assert opt.counter == 5
            yield dn_tmp, opt, f
Esempio n. 34
0
def run_opt_water32(suffix, prefix):
    # Work in a temporary directory
    with tmpdir(suffix, prefix) as dn_tmp:
        # Setup a test FF
        ff = get_ff_water32()
        # Run a test simulation
        with h5.File('%s/output.h5' % dn_tmp) as f:
            hdf5 = HDF5Writer(f)
            opt = CGOptimizer(FullCellDOF(ff), hooks=hdf5)
            opt.run(5)
            assert opt.counter == 5
            yield dn_tmp, opt, f
Esempio n. 35
0
def run_nve_water32(suffix, prefix):
    # Work in a temporary directory
    with tmpdir(suffix, prefix) as dn_tmp:
        # Setup a test FF
        ff = get_ff_water32()
        # Run a test simulation
        with h5.File('%s/output.h5' % dn_tmp) as f:
            hdf5 = HDF5Writer(f)
            nve = VerletIntegrator(ff, 1.0*femtosecond, hooks=hdf5)
            nve.run(5)
            assert nve.counter == 5
            yield dn_tmp, nve, f
Esempio n. 36
0
 def test_timer(self):
     timer = Timer()
     timer.sample("start")
     for i in range(100000):
         j = i**2
     timer.sample("done")
     self.assertEqual(timer.labels[0], "start")
     self.assertEqual(timer.labels[1], "done")
     #timer.dump()  # to write logfile to screen
     # just testing whether writing to file works
     with tmpdir(__name__, 'test_timer') as dn:
         timer.write_to_file(os.path.join(dn, "logfile-timings.txt"))
Esempio n. 37
0
def test_xyz_select():
    with tmpdir(__name__, 'test_xyz_select') as dn:
        fn_xyz = os.path.join(dn, 'foobar.xyz')
        xyz = XYZWriter(fn_xyz, select=[0,1,2])
        nve = VerletIntegrator(get_ff_water32(), 1.0*femtosecond, hooks=[xyz])
        nve.run(15)
        assert os.path.isfile(fn_xyz)
        assert nve.counter == 15
        ## Ugly hack to make tests pass on Windows. The root cause is that the SliceReader
        ## in molmod.io.common is poorly written.
        xyz.xyz_writer._auto_close = False
        xyz.xyz_writer._f.close()
Esempio n. 38
0
def test_blav():
    # generate a time-correlated random signal
    n = 50000
    eps0 = 30.0 / n
    eps1 = 1.0
    y = np.sin(
        np.random.normal(0, eps0, n).cumsum() + np.random.normal(0, eps1, n))
    # create a temporary directory to write the plot to
    with tmpdir(__name__, 'test_blav') as dn:
        fn_png = '%s/blav.png' % dn
        error, sinef = blav(y, 100, fn_png)
        assert os.path.isfile(fn_png)
Esempio n. 39
0
 def test_mbh(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.cor"),
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.hess.full"))
     blocks = load_indices(
         pkg_resources.resource_filename(__name__, "../data/test/an/fixed.07.txt"),
         groups=True)
     nma = NMA(molecule, MBH(blocks))
     self.check_ortho(nma.modes)
     with tmpdir(__name__, 'test_mbh') as dn:
         dump_modes_molden(os.path.join(dn, "ethanol.mbh.molden.log"), nma)
     self.check_ortho(nma.modes)   # write_molden should not have changed this
Esempio n. 40
0
 def test_timer(self):
     timer = Timer()
     timer.sample("start")
     for i in range(100000):
         j = i**2
     timer.sample("done")
     self.assertEqual(timer.labels[0], "start")
     self.assertEqual(timer.labels[1], "done")
     #timer.dump()  # to write logfile to screen
     # just testing whether writing to file works
     with tmpdir(__name__, 'test_timer') as dn:
         timer.write_to_file(os.path.join(dn, "logfile-timings.txt"))
Esempio n. 41
0
 def test_constrain1(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename("tamkin", "data/test/an/ethanol.cor"),
         pkg_resources.resource_filename("tamkin", "data/test/an/ethanol.hess.full"))
     fixed = [[1,2]]
     nma = NMA(molecule, Constrain(fixed))
     #print nma.freqs/lightspeed*centimeter
     self.check_ortho(nma.modes)
     self.assertEqual(nma.modes.shape[0],27)
     self.assertEqual(nma.modes.shape[1],26)
     with tmpdir(__name__, 'test_constrain1') as dn:
         dump_modes_molden(os.path.join(dn, "ethanol.constr.molden.log"), nma)
Esempio n. 42
0
 def test_constrain2(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.cor"),
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.hess.full"))
     fixed = [[1,2], [0,4], [0,5],[2,8],[3,4],[4,5],[5,6],[6,7],[7,8],[7,1],[7,3]]
     nma = NMA(molecule, Constrain(fixed))
     #print nma.freqs/lightspeed*centimeter
     self.check_ortho(nma.modes)
     self.assertEqual(nma.modes.shape[0],27)
     self.assertEqual(nma.modes.shape[1],16)
     with tmpdir(__name__, 'test_constrain2') as dn:
         dump_modes_molden(os.path.join(dn, "ethanol.constr.molden.log"), nma)
Esempio n. 43
0
def run_nve_water32(suffix, prefix):
    # Work in a temporary directory
    with tmpdir(suffix, prefix) as dn_tmp:
        # Setup a test FF
        ff = get_ff_water32()
        # Run a test simulation
        with h5.File('%s/output.h5' % dn_tmp) as f:
            hdf5 = HDF5Writer(f)
            nve = VerletIntegrator(ff, 1.0 * femtosecond, hooks=hdf5)
            nve.run(5)
            assert nve.counter == 5
            yield dn_tmp, nve, f
Esempio n. 44
0
def run_nvt_water32(suffix, prefix):
    # Work in a temporary directory
    with tmpdir(suffix, prefix) as dn_tmp:
        # Setup a test FF
        ff = get_ff_water32()
        # Run a test simulation
        with h5.File('%s/output.h5' % dn_tmp) as f:
            hdf5 = HDF5Writer(f)
            thermostat = LangevinThermostat(temp=300)
            nvt = VerletIntegrator(ff, 1.0*femtosecond, hooks=[hdf5, thermostat])
            nvt.run(5)
            assert nvt.counter == 5
            yield dn_tmp, nvt, f
Esempio n. 45
0
    def test_load_dump_indices1(self):
        subs = range(10)
        with tmpdir(__name__, 'test_load_dump_indices1') as dn:
            dump_indices(os.path.join(dn, "subs-atoms.1.txt"), subs, shift=0)
            dump_indices(os.path.join(dn, "subs-atoms.2.txt"), subs, shift=1)
            dump_indices(os.path.join(dn, "subs-atoms.3.txt"), subs)

            subs1 = load_indices(os.path.join(dn, "subs-atoms.1.txt"), shift=0)
            subs2 = load_indices(os.path.join(dn, "subs-atoms.2.txt"), shift=-1)
            subs22 = load_indices(os.path.join(dn, "subs-atoms.2.txt"))  # should not matter
            subs3 = load_indices(os.path.join(dn, "subs-atoms.3.txt"))

            blocks = [range(10), range(10,20)]
            dump_indices(os.path.join(dn, "blocks.1.txt"), blocks, shift=0)
            dump_indices(os.path.join(dn, "blocks.2.txt"), blocks, shift=1)
            dump_indices(os.path.join(dn, "blocks.3.txt"), blocks)

            blocks1 = load_indices(os.path.join(dn, "blocks.1.txt"), shift=0, groups=True)
            blocks2 = load_indices(os.path.join(dn, "blocks.2.txt"), shift=-1, groups=True)
            blocks22 = load_indices(os.path.join(dn, "blocks.2.txt"), groups=True)  # should not matter
            blocks3 = load_indices(os.path.join(dn, "blocks.3.txt"), groups=True)

        self.assertEqual(len(subs),len(subs1))
        for (i,j) in zip(subs,subs1):
            self.assertEqual(i,j)
        self.assertEqual(len(subs),len(subs2))
        for i,j in zip(subs,subs2):
            self.assertEqual(i,j)
        self.assertEqual(len(subs),len(subs22))
        for i,j in zip(subs,subs22):
            self.assertEqual(i,j)
        self.assertEqual(len(subs),len(subs3))
        for i,j in zip(subs,subs3):
            self.assertEqual(i,j)

        self.assertEqual(len(blocks),len(blocks1))
        for bl,bl1 in zip(blocks,blocks1):
            for i,j in zip(bl,bl1):
                self.assertEqual(i,j)
        self.assertEqual(len(blocks),len(blocks2))
        for bl,bl1 in zip(blocks,blocks2):
            for i,j in zip(bl,bl1):
                self.assertEqual(i,j)
        self.assertEqual(len(blocks),len(blocks22))
        for bl,bl1 in zip(blocks,blocks22):
            for i,j in zip(bl,bl1):
                self.assertEqual(i,j)
        self.assertEqual(len(blocks),len(blocks3))
        for bl,bl1 in zip(blocks,blocks3):
            for i,j in zip(bl,bl1):
                self.assertEqual(i,j)
Esempio n. 46
0
 def test_pcm_correction(self):
     mol = load_molecule_g03fchk(
         pkg_resources.resource_filename(__name__, "../data/test/sterck/aa_1h2o_a.fchk"))
     pf0 = PartFun(NMA(mol), [])
     pf1 = PartFun(NMA(mol), [PCMCorrection((-5*kjmol,300))])
     pf2 = PartFun(NMA(mol), [PCMCorrection((-5*kjmol,300), (-10*kjmol,600))])
     # real tests
     self.assertAlmostEqual(pf0.free_energy(300)-5*kjmol, pf1.free_energy(300))
     self.assertAlmostEqual(pf0.free_energy(300)-5*kjmol, pf2.free_energy(300))
     self.assertAlmostEqual(pf0.free_energy(600)-5*kjmol, pf1.free_energy(600))
     self.assertAlmostEqual(pf0.free_energy(600)-10*kjmol, pf2.free_energy(600))
     # blind tests
     pf2.heat_capacity(300)
     with tmpdir(__name__, 'test_pcm_correction') as dn:
         pf1.write_to_file(os.path.join(dn, "pcm_partf1.txt"))
         pf2.write_to_file(os.path.join(dn, "pcm_partf2.txt"))
Esempio n. 47
0
    def test_flat(self):
        a = 10.0
        mass = 1.0
        hb = HarmonicBasis(10, a)
        energies, orbitals = hb.solve(mass, np.zeros(hb.size), evecs=True)

        import matplotlib.pyplot as pt
        x = np.arange(0.0, a, 0.001)
        pt.clf()
        for i in xrange(10):
            f = hb.eval_fn(x, orbitals[:,i])
            pt.plot(x, f+i)
        with tmpdir(__name__, 'test_flat') as dn:
            pt.savefig(os.path.join(dn, "flat_wavefunctions.png"))

        indexes = np.array([0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10])
        expected = 0.5/mass*(2*indexes*np.pi/a)**2
        self.assertArraysAlmostEqual(energies, expected, 1e-4)
Esempio n. 48
0
    def test_ethyl_free(self):
        molecule = load_molecule_g03fchk(
            pkg_resources.resource_filename(__name__, "../data/test/ethyl/gaussian.fchk"))
        nma = NMA(molecule)
        dihedral = [5, 1, 0, 2]
        rot_scan = RotScan(dihedral, molecule)
        rotor = Rotor(rot_scan, molecule, rotsym=6, even=True)
        self.assertAlmostEqual(rotor.cancel_freq/lightspeed*centimeter, 141.2, 0)
        pf = PartFun(nma, [ExtTrans(), ExtRot(1), rotor])
        # reference data from legacy code (Veronique & co)
        self.assertAlmostEqual(rotor.reduced_moment/amu, 4.007, 1)
        self.assertAlmostEqual(np.exp(rotor.log_terms(100.0)[1]), 0.6386, 1)
        self.assertAlmostEqual(np.exp(-rotor.log_terms(100.0)[0]), 0.4168, 1)
        self.assertAlmostEqual(np.exp(rotor.log_terms(800.0)[1]), 1.8062, 1)
        self.assertAlmostEqual(np.exp(-rotor.log_terms(800.0)[0]), 3.9273, 1)

        with tmpdir(__name__, 'test_ethyl_free') as dn:
            rotor.plot_levels(os.path.join(dn, "ethyl_free_levels.png"), 300)
            pf.write_to_file(os.path.join(dn, "ethyl_free.txt"))
            ta = ThermoAnalysis(pf, [200,300,400,500,600,700,800,900])
            ta.write_to_file(os.path.join(dn, "ethyl_free_thermo.csv"))
Esempio n. 49
0
def test_molecule_checkpoint_basic():
    mol1 = load_molecule_g03fchk(
        pkg_resources.resource_filename(__name__, "../data/test/sterck/aa.fchk"))
    with tmpdir(__name__, 'test_molecule_checkpoint_basic') as dn:
        fn_out = os.path.join(dn, "molecule_checkpoint_basic.chk")
        mol1.write_to_file(fn_out)
        mol2 = Molecule.read_from_file(fn_out)

    assert mol1.numbers.shape == mol2.numbers.shape
    assert abs(mol1.numbers - mol2.numbers).max() == 0
    assert mol1.coordinates.shape == mol2.coordinates.shape
    assert abs(mol1.coordinates - mol2.coordinates).max() < 1e-10
    assert mol1.masses.shape == mol2.masses.shape
    assert abs(mol1.masses - mol2.masses).max() < 1e-10
    assert abs(mol1.energy - mol2.energy) < 1e-5
    assert mol1.gradient.shape == mol2.gradient.shape
    assert abs(mol1.gradient - mol2.gradient).max() < 1e-10
    assert mol1.hessian.shape == mol2.hessian.shape
    assert abs(mol1.hessian - mol2.hessian).max() < 1e-10
    assert mol1.multiplicity == mol2.multiplicity
    assert mol1.symmetry_number == mol2.symmetry_number
    assert mol1.periodic == mol2.periodic
Esempio n. 50
0
    def test_fit_fn_sym(self):
        a = 9.0
        hb = HarmonicBasis(90, a)
        grid = np.arange(0.0, 1.501, 0.1)
        f = np.exp(-(grid/2)**2)
        f -= f.mean()
        coeffs = hb.fit_fn(grid, f, 30, rotsym=3, even=True)
        g = hb.eval_fn(grid, coeffs)
        self.assertArraysAlmostEqual(f, g)
        grid = np.arange(0.0, 9.001, 0.1)
        g = hb.eval_fn(grid, coeffs)
        self.assertArraysAlmostEqual(f, g[0:16])
        self.assertArraysAlmostEqual(f, g[30:46])
        self.assertArraysAlmostEqual(f, g[60:76])
        self.assertArraysAlmostEqual(f[::-1], g[15:31])
        self.assertArraysAlmostEqual(f[::-1], g[45:61])
        self.assertArraysAlmostEqual(f[::-1], g[75:91])

        import matplotlib.pyplot as pt
        pt.clf()
        pt.plot(grid, g, "k-", lw=2)
        pt.plot(grid[:16], f, "rx", mew=2)
        with tmpdir(__name__, 'test_fit_fn_sym') as dn:
            pt.savefig(os.path.join(dn, "test_fit_fn_sym.png"))
Esempio n. 51
0
    def test_load_dump_indices2(self):
        randint = np.random.randint
        for counter in xrange(20):
            for compact in True, False:
                shift = randint(-5,5)
                indices = []
                for i in xrange(randint(10,20)):
                    l = list(set(randint(0,10,randint(20))))
                    if len(l) > 0:
                        indices.append(l)
                indices_flat = sum(indices, [])

                with tmpdir(__name__, '{}_{}'.format('test_load_dump_indices2', counter)) as dn:
                    dump_indices(os.path.join(dn, "indices_blocks.txt"), indices, compact=compact, shift=shift)
                    dump_indices(os.path.join(dn, "indices_flat.txt"), indices_flat, compact=compact, shift=shift)

                    check = load_indices(os.path.join(dn, "indices_blocks.txt"), shift=-shift, groups=True)
                    self.assertEqual(indices, check)
                    check = load_indices(os.path.join(dn, "indices_blocks.txt"), shift=-shift)
                    self.assertEqual(indices_flat, check)
                    check = load_indices(os.path.join(dn, "indices_flat.txt"), shift=-shift, groups=True)
                    self.assertEqual([indices_flat], check)
                    check = load_indices(os.path.join(dn, "indices_flat.txt"), shift=-shift)
                    self.assertEqual(indices_flat, check)
Esempio n. 52
0
 def test_dump_modes_xyz(self):
     molecule = load_molecule_charmm(
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.cor"),
         pkg_resources.resource_filename(__name__, "../data/test/an/ethanol.hess.full"))
     nma = NMA(molecule)
     with tmpdir(__name__, 'test_dump_modes_xyz') as dn:
         prefix = os.path.join(dn, 'mode')
         dump_modes_xyz(nma, 6, prefix=prefix, amplitude=50.0)
         with open(prefix + ".6.xyz") as f:
             # 1st line
             line = f.readline().strip()
             self.assertEqual(line,"9")
             # 2nd line
             line = f.readline().strip()
             self.assertEqual(line,"frame 0")
             # 3rd line
             line = f.readline()
             words = line.split()
             self.assertEqual(len(words),4)
             self.assertEqual(words[0],"C")
             self.assertEqual(words[2],"0.081608346")
             for i in range(9):
                 line = f.readline().strip()
             self.assertEqual(line,"9")