Exemplo n.º 1
0
    def integrate_atoms(
        self,
        atoms,
        traj_file,
        n_steps,
        save_interval,
        steps=0,
        timestep=5.0,
        traj_dir="trajs",
        convert=False,
    ):
        if not os.path.exists(traj_dir):
            os.mkdir(traj_dir)
        traj_file = os.path.join(traj_dir, traj_file)
        if not os.path.exists(traj_file):
            traj = Trajectory(traj_file, "w")
            print("Creating trajectory {}...".format(traj_file))

            dyn = VelocityVerlet(atoms, timestep=timestep * units.fs)
            count = n_steps // save_interval
            for i in range(count):
                dyn.run(save_interval)
                energy = atoms.get_total_energy()
                forces = atoms.get_forces()
                traj.write(atoms)
                steps += save_interval
                print("Steps: {}, total energy: {}".format(steps, energy))
        else:
            print("Trajectory {} already exists!".format(traj_file))

        if convert:
            self.convert_trajectory(traj_file)

        return steps, traj_file
Exemplo n.º 2
0
def md(gen='poscar.gen', index=0, totstep=100):
    atoms = read(gen, index=index)
    atoms.calc = IRFF(atoms=atoms, libfile='ffield.json', rcut=None, nn=True)
    # dyn = BFGS(atoms)
    dyn = VelocityVerlet(atoms, 0.1 * units.fs)  # 5 fs time step.

    def printenergy(a=atoms):
        """Function to print the potential, kinetic and total energy"""
        natom = len(a)
        epot = a.get_potential_energy() / natom
        ekin = a.get_kinetic_energy() / natom
        T = ekin / (1.5 * units.kB)
        try:
            assert T <= 8000.0, 'Temperature goes too high!'
        except:
            print('Temperature goes too high, stop at step %d.' % dyn.nsteps)
            dyn.max_steps = dyn.nsteps - 1
        # print(a.get_forces())
        print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
              'Etot = %.3feV' % (epot, ekin, T, epot + ekin))

    traj = Trajectory('md.traj', 'w', atoms)
    dyn = VelocityVerlet(atoms, 0.1 * units.fs)  # 5 fs time step.

    dyn.attach(printenergy, interval=1)
    dyn.attach(traj.write, interval=1)
    dyn.run(totstep)
Exemplo n.º 3
0
def test_rattle():

    i = LJInteractions({('O', 'O'): (epsilon0, sigma0)})

    for calc in [
            TIP3P(),
            SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P()),
            EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i)
    ]:
        dimer = s22('Water_dimer')

        for m in [0, 3]:
            dimer.set_angle(m + 1, m, m + 2, angleHOH)
            dimer.set_distance(m, m + 1, rOH, fix=0)
            dimer.set_distance(m, m + 2, rOH, fix=0)

        fixOH1 = [(3 * i, 3 * i + 1) for i in range(2)]
        fixOH2 = [(3 * i, 3 * i + 2) for i in range(2)]
        fixHH = [(3 * i + 1, 3 * i + 2) for i in range(2)]
        dimer.set_constraint(FixBondLengths(fixOH1 + fixOH2 + fixHH))

        dimer.calc = calc

        e = dimer.get_potential_energy()
        md = VelocityVerlet(dimer,
                            8.0 * units.fs,
                            trajectory=calc.name + '.traj',
                            logfile=calc.name + '.log',
                            loginterval=5)
        md.run(25)
        de = dimer.get_potential_energy() - e
        assert abs(de - -0.028) < 0.001
Exemplo n.º 4
0
    def __init__(self, atoms, timestep=None, trajectory=None, dt=None, 
                 **kwargs):

        VelocityVerlet.__init__(self, atoms, timestep, trajectory, dt=dt)

        OTF.__init__(self, **kwargs)
        
        self.md_engine = 'VelocityVerlet'
Exemplo n.º 5
0
def test_rattle_linear():
    """Test RATTLE and QM/MM for rigid linear acetonitrile."""

    import numpy as np

    from ase import Atoms
    from ase.calculators.acn import (ACN, m_me, r_cn, r_mec, sigma_me, sigma_c,
                                     sigma_n, epsilon_me, epsilon_c, epsilon_n)
    from ase.calculators.qmmm import SimpleQMMM, EIQMMM, LJInteractionsGeneral
    from ase.md.verlet import VelocityVerlet
    from ase.constraints import FixLinearTriatomic
    import ase.units as units

    sigma = np.array([sigma_me, sigma_c, sigma_n])
    epsilon = np.array([epsilon_me, epsilon_c, epsilon_n])
    i = LJInteractionsGeneral(sigma, epsilon, sigma, epsilon, 3)

    for calc in [
            ACN(),
            SimpleQMMM([0, 1, 2], ACN(), ACN(), ACN()),
            EIQMMM([0, 1, 2], ACN(), ACN(), i)
    ]:

        dimer = Atoms('CCNCCN', [(-r_mec, 0, 0), (0, 0, 0), (r_cn, 0, 0),
                                 (r_mec, 3.7, 0), (0, 3.7, 0),
                                 (-r_cn, 3.7, 0)])

        masses = dimer.get_masses()
        masses[::3] = m_me
        dimer.set_masses(masses)

        fixd = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)])

        dimer.set_constraint(fixd)

        dimer.calc = calc

        d1 = dimer[:3].get_all_distances()
        d2 = dimer[3:].get_all_distances()
        e = dimer.get_potential_energy()

        md = VelocityVerlet(dimer,
                            2.0 * units.fs,
                            trajectory=calc.name + '.traj',
                            logfile=calc.name + '.log',
                            loginterval=20)
        md.run(100)

        de = dimer.get_potential_energy() - e

        assert np.all(abs(dimer[:3].get_all_distances() - d1) < 1e-10)
        assert np.all(abs(dimer[3:].get_all_distances() - d2) < 1e-10)
        assert abs(de - -0.005) < 0.001
Exemplo n.º 6
0
def maketraj(atoms, t, nstep):
    e = [atoms.get_potential_energy()]
    print "Shape of force:", atoms.get_forces().shape
    dyn = VelocityVerlet(atoms, 5 * units.fs)
    for i in range(nstep):
        dyn.run(10)
        energy = atoms.get_potential_energy()
        e.append(energy)
        if ismaster:
            print "Energy: ", energy
        if t is not None:
            t.write()
    return e
Exemplo n.º 7
0
def maketraj(atoms, t, nstep):
    e = [atoms.get_potential_energy()]
    print "Shape of force:", atoms.get_forces().shape
    dyn = VelocityVerlet(atoms, 5*units.fs)
    for i in range(nstep):
        dyn.run(10)
        energy = atoms.get_potential_energy()
        e.append(energy)
        if ismaster:
            print "Energy: ", energy
        if t is not None:
            t.write()
    return e
Exemplo n.º 8
0
def test_md(cp2k_factory):
    calc = cp2k_factory.calc(label='test_H2_MD')
    positions = [(0, 0, 0), (0, 0, 0.7245595)]
    atoms = Atoms('HH', positions=positions, calculator=calc)
    atoms.center(vacuum=2.0)

    MaxwellBoltzmannDistribution(atoms,
                                 temperature_K=0.5 * 300,
                                 force_temp=True)
    energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    dyn = VelocityVerlet(atoms, 0.5 * units.fs)
    dyn.run(20)

    energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    assert abs(energy_start - energy_end) < 1e-4
Exemplo n.º 9
0
 def set_lattice_params(self, md='NVE', **kwargs):
     #self.lattice_model.set(**kwargs)
     self.lattice_temperature = kwargs['lattice_temperature']
     self.lattice_time_step = kwargs['lattice_time_step']
     self.lattice_friction = kwargs['lattice_friction']
     if md == 'Langevin':
         self._lattice_dyn = Langevin(self.atoms,
                                      self.lattice_time_step,
                                      self.lattice_temperature,
                                      self.lattice_friction,
                                      trajectory='LattHist.traj')
     elif md == 'NVE':
         self._lattice_dyn = VelocityVerlet(self.atoms,
                                            dt=self.lattice_time_step,
                                            trajectory='LattHist.traj')
Exemplo n.º 10
0
        def test_apply_strain(self):
            calc = TersoffScr(**Tersoff_PRB_39_5566_Si_C__Scr)
            timestep = 1.0*units.fs

            atoms = ase.io.read('cryst_rot_mod.xyz')
            atoms.set_calculator(calc)

            # constraints
            top = atoms.positions[:, 1].max()
            bottom = atoms.positions[:, 1].min()
            fixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) |
                          (abs(atoms.positions[:, 1] - bottom) < 1.0))
            fix_atoms = FixAtoms(mask=fixed_mask)

            # strain
            orig_height = (atoms.positions[:, 1].max() - atoms.positions[:, 1].min())
            delta_strain = timestep*1e-5*(1/units.fs)
            rigid_constraints = False
            strain_atoms = ConstantStrainRate(orig_height, delta_strain)
            atoms.set_constraint(fix_atoms)

            # dynamics
            np.random.seed(0)
            simulation_temperature = 300*units.kB
            MaxwellBoltzmannDistribution(atoms, 2.0*simulation_temperature)
            dynamics = VelocityVerlet(atoms, timestep)

            def apply_strain(atoms, ConstantStrainRate, rigid_constraints):
                ConstantStrainRate.apply_strain(atoms, rigid_constraints)

            dynamics.attach(apply_strain, 1, atoms, strain_atoms, rigid_constraints)
            dynamics.run(100)

            # tests
            if rigid_constraints == True:
                answer = 0
                temp_answer = 238.2066417638124
            else:
                answer = 0.013228150080099255
                temp_answer = 236.76904696481486

            newpos = atoms.get_positions()
            current_height = newpos[:, 1].max() - newpos[:, 1].min()
            diff_height = (current_height - orig_height)
            self.assertAlmostEqual(diff_height, answer)

            temperature = (atoms.get_kinetic_energy()/(1.5*units.kB*len(atoms)))
            self.assertAlmostEqual(temperature, temp_answer)
Exemplo n.º 11
0
def constant_energy(nuclear_charges, coordinates, dump=None, calculator=None):
    """
    """

    if calculator is None:

        # LOAD AND SET MODEL
        parameters = {}
        parameters["offset"] = -97084.83100465109
        parameters["sigma"] = 10.0
        alphas = np.load(FILENAME_ALPHAS)
        X = np.load(FILENAME_REPRESENTATIONS)
        Q = np.load(FILENAME_CHARGES)
        alphas = np.array(alphas, order="F")
        X = np.array(X, order="F")
        calculator = QMLCalculator(parameters, X, Q, alphas)

    molecule = ase.Atoms(nuclear_charges, coordinates)
    molecule.set_calculator(calculator)

    # Set the momenta corresponding to T=300K
    MaxwellBoltzmannDistribution(molecule, 200 * units.kB)

    # We want to run MD with constant energy using the VelocityVerlet algorithm.
    dyn = VelocityVerlet(molecule, 1 * units.fs)  # 5 fs time step.

    # if dump is not None:
    #     traj = Trajectory(dump, 'w', molecule)
    #     dyn.attach(traj.write, interval=5)

    def printenergy(a=molecule,
                    t=None):  # store a reference to atoms in the definition.
        """Function to print the potential, kinetic and total energy."""
        epot = a.get_potential_energy() / len(a)
        ekin = a.get_kinetic_energy() / len(a)
        print('pEpot = %.2feV  Ekin = %.2feV (T=%3.0fK)  '
              'Etot = %.4feV t=%.4f' % (epot, ekin, ekin /
                                        (1.5 * units.kB), epot + ekin, t))

    for i in range(10):

        start = time.time()
        dyn.run(0)
        end = time.time()

        printenergy(t=end - start)

    return
Exemplo n.º 12
0
    def run(self):
        MaxwellBoltzmannDistribution(self.atoms, self.intT * units.kB)
        self.dyn = VelocityVerlet(self.atoms,
                                  self.time_step * units.fs,
                                  trajectory='md.traj')

        def printenergy(a=self.atoms):
            epot_ = a.get_potential_energy()
            r = a.calc.r.numpy()
            i_ = np.where(np.logical_and(r < self.rtole * self.ro, r > 0.0001))
            n = len(i_[0])

            self.Epot.append(epot_)
            self.epot = epot_ / self.natom
            self.ekin = a.get_kinetic_energy() / self.natom
            self.T = self.ekin / (1.5 * units.kB)
            self.step = self.dyn.nsteps

            print('Step %d Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
                  'Etot = %.3feV' % (self.step, self.epot, self.ekin, self.T,
                                     self.epot + self.ekin))

            try:
                assert n == 0 and self.T < self.Tmax, 'Atoms too closed!'
            except:
                for _ in i_:
                    print('atoms pair', _)
                print('Atoms too closed or temperature too high, stop at %d.' %
                      self.step)
                self.dyn.max_steps = self.dyn.nsteps - 1

        # traj = Trajectory('md.traj', 'w', self.atoms)
        self.dyn.attach(printenergy, interval=1)
        # self.dyn.attach(traj.write,interval=1)
        self.dyn.run(self.totstep)
Exemplo n.º 13
0
 def set_initial_velocities(self, distribution, energy):
     distribution(self.atoms, energy)
     try:
         os.remove(self.traj)
     except:
         pass
     try:
         os.remove(self._log)
     except:
         pass
     VelocityVerlet.__init__(self,
                             atoms=self.atoms,
                             timestep=self.dt,
                             trajectory=self.traj,
                             loginterval=1,
                             logfile=self._log,
                             append_trajectory=False)
     self.update_properties()
Exemplo n.º 14
0
def test_md(cp2k_factory):
    calc = cp2k_factory.calc(label='test_H2_MD')
    positions = [(0, 0, 0), (0, 0, 0.7245595)]
    atoms = Atoms('HH', positions=positions, calculator=calc)
    atoms.center(vacuum=2.0)

    # Run MD
    MaxwellBoltzmannDistribution(atoms, 0.5 * 300 * units.kB, force_temp=True)
    energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    dyn = VelocityVerlet(atoms, 0.5 * units.fs)
    #def print_md():
    #    energy = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    #    print("MD total-energy: %.10feV" %  energy)
    #dyn.attach(print_md, interval=1)
    dyn.run(20)

    energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy()

    assert energy_start - energy_end < 1e-4
    print('passed test "H2_MD"')
Exemplo n.º 15
0
def get_ANN_energy(input_file):
    (structure_file, T, dt, md_steps, print_steps, trajectory_file,
     potentials) = parse_input(input_file)
    # atomic structure
    atoms = ase.io.read(structure_file, format='vasp')
    # ANN calculator
    calc = ANNCalculator(potentials)
    atoms.set_calculator(calc)
    # initialize velocities
    MaxwellBoltzmannDistribution(atoms, temp=T * units.kB)
    # initialize MD
    md = VelocityVerlet(atoms, dt * units.fs, trajectory=trajectory_file)
    print("# {:5s} {:15s} {:15s} {:7s} {:15s}".format("step", "E_pot", "E_kin",
                                                      "T", "E_tot"))
    printenergy(0, atoms)
    istep = 0
    for i in range(int(md_steps / print_steps)):
        md.run(steps=print_steps)
        istep += print_steps
        printenergy(istep, atoms)
Exemplo n.º 16
0
    def MD(self):
        """Molecular Dynamic"""
        from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
        from ase import units
        from ase.md import MDLogger
        from ase.io.trajectory import PickleTrajectory
        from ase.md.langevin import Langevin
        from ase.md.verlet import VelocityVerlet

        dyndrivers = {
            'Langevin': Langevin,
            'None': VelocityVerlet,
        }

        useAsap = False

        mol = self.mol
        temperature = self.definedParams['temperature']
        init_temperature = self.definedParams['init_temperature']
        time_step = self.definedParams['time_step']
        nstep = self.definedParams['nstep']
        nprint = self.definedParams['nprint']
        thermostat = self.definedParams['thermostat']
        prop_file = os.path.join(self.definedParams['workdir'],
                                 self.definedParams['output_prefix'] + '.out')
        traj_file = os.path.join(self.definedParams['workdir'],
                                 self.definedParams['output_prefix'] + '.traj')

        MaxwellBoltzmannDistribution(mol, init_temperature * units.kB)

        if thermostat == 'None':
            dyn = VelocityVerlet(mol, time_step * units.fs)
        elif thermostat == 'Langevin':
            dyn = Langevin(mol, time_step * units.fs, temperature * units.kB,
                           0.01)
        else:
            raise ImplementationError(
                method, 'Thermostat is not implemented in the MD function')

        #Function to print the potential, kinetic and total energy
        traj = PickleTrajectory(traj_file, "a", mol)
        dyn.attach(MDLogger(dyn, mol, prop_file), interval=nprint)
        dyn.attach(traj.write, interval=nprint)

        dyn.run(nstep)
        traj.close()
Exemplo n.º 17
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_H2_MD')
    positions = [(0, 0, 0), (0, 0, 0.7245595)]
    atoms = Atoms('HH', positions=positions, calculator=calc)
    atoms.center(vacuum=2.0)

    # Run MD
    MaxwellBoltzmannDistribution(atoms, 0.5 * 300 * units.kB, force_temp=True)
    energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    dyn = VelocityVerlet(atoms, 0.5 * units.fs)
    #def print_md():
    #    energy = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    #    print("MD total-energy: %.10feV" %  energy)
    #dyn.attach(print_md, interval=1)
    dyn.run(20)

    energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy()

    assert energy_start - energy_end < 1e-4
    print('passed test "H2_MD"')
Exemplo n.º 18
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_H2_MD')
    positions = [(0, 0, 0), (0, 0, 0.7245595)]
    atoms = Atoms('HH', positions=positions, calculator=calc)
    atoms.center(vacuum=2.0)

    # Run MD
    MaxwellBoltzmannDistribution(atoms, 0.5 * 300 * units.kB, force_temp=True)
    energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    dyn = VelocityVerlet(atoms, 0.5 * units.fs)
    #def print_md():
    #    energy = atoms.get_potential_energy() + atoms.get_kinetic_energy()
    #    print("MD total-energy: %.10feV" %  energy)
    #dyn.attach(print_md, interval=1)
    dyn.run(20)

    energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy()

    assert energy_start - energy_end < 1e-4
    print('passed test "H2_MD"')
Exemplo n.º 19
0
def run_md_Morse(Morse_parameters, A0, steps=10000, trajectory="md.traj"):
    hbar_fs = (ase.units._hbar / ase.units._e) * 1.E15
    D, a, R0, frequency = Morse_parameters[0:4]
    r0 = R0
    calculator = MorsePotential2(a=a, D=D, r0=r0)
    #calculator = MorsePotential(rho0=6.0, epsilon=2.0, r0=1.0)
    period = (hbar_fs / frequency) / (2 * pi)
    pos = 1 * (r0 + A0)
    atoms = Atoms("HH", positions=[[0, 0, 0], [pos, 0, 0]], masses=[1.0, 1.0])
    constr = FixAtoms(indices=[0])
    atoms.set_constraint(constr)
    atoms.set_calculator(calculator)
    #    def V(d):
    #        atoms.set_positions([[0,0,0],[d,0,0]])
    #        return atoms.get_potential_energy()
    #    r_plot = linspace(-4.0,4.0,1000)
    #    V_plot = array([V(d) for d in r_plot])
    #    plt.plot(r_plot,V_plot)
    #    plt.show()

    dynamics = VelocityVerlet(atoms,
                              dt=(period / 20.) * ase.units.fs,
                              trajectory=trajectory)
    dynamics.run(20000)
Exemplo n.º 20
0
    def MD(self):
        """Molecular Dynamic"""
        from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
        from ase import units
        from ase.md import MDLogger
        from ase.io.trajectory import PickleTrajectory
        from ase.md.langevin import Langevin
        from ase.md.verlet import VelocityVerlet

        dyndrivers = {
            'Langevin': Langevin,
            'None': VelocityVerlet,
        }

        useAsap = False

        mol = self.mol
        temperature = self.definedParams['temperature']
        init_temperature = self.definedParams['init_temperature']
        time_step = self.definedParams['time_step']
        nstep = self.definedParams['nstep']
        nprint = self.definedParams['nprint']
        thermostat = self.definedParams['thermostat']
        prop_file = os.path.join(self.definedParams['workdir'],
                                 self.definedParams['output_prefix']+'.out')
        traj_file = os.path.join(self.definedParams['workdir'],
                                 self.definedParams['output_prefix']+'.traj')

        MaxwellBoltzmannDistribution(mol,init_temperature*units.kB)

        if thermostat == 'None':
            dyn = VelocityVerlet(mol, time_step*units.fs)
        elif thermostat == 'Langevin':
            dyn = Langevin(mol, time_step*units.fs, temperature*units.kB, 0.01 )
        else:
            raise ImplementationError(method,'Thermostat is not implemented in the MD function')

        #Function to print the potential, kinetic and total energy
        traj = PickleTrajectory(traj_file,"a",mol)
        dyn.attach(MDLogger(dyn,mol,prop_file),interval=nprint)
        dyn.attach(traj.write, interval = nprint)

        dyn.run(nstep)
        traj.close()
Exemplo n.º 21
0
def ase_md_playground():
    geom = AnaPot.get_geom((0.52, 1.80, 0), atoms=("H", ))
    atoms = geom.as_ase_atoms()
    # ase_calc = FakeASE(geom.calculator)
    # from ase.optimize import BFGS
    # dyn = BFGS(atoms)
    # dyn.run(fmax=0.05)

    import ase
    from ase import units
    from ase.io.trajectory import Trajectory
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.md.verlet import VelocityVerlet

    MaxwellBoltzmannDistribution(atoms, 300 * units.kB)
    momenta = atoms.get_momenta()
    momenta[0, 2] = 0.
    # Zero 3rd dimension
    atoms.set_momenta(momenta)

    dyn = VelocityVerlet(atoms, .005 * units.fs)  # 5 fs time step.


    def printenergy(a):
        """Function to print the potential, kinetic and total energy"""
        epot = a.get_potential_energy() / len(a)
        ekin = a.get_kinetic_energy() / len(a)
        print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
              'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin))

    # Now run the dynamics
    printenergy(atoms)
    traj_fn = 'asemd.traj'
    traj = Trajectory(traj_fn, 'w', atoms)
    dyn.attach(traj.write, interval=5)
    # dyn.attach(bumms().bimms, interval=1)

    dyn.run(10000)
    printenergy(atoms)
    traj.close()

    traj = ase.io.read(traj_fn+"@:")#, "r")
    pos = [a.get_positions() for a in traj]
    from pysisyphus.constants import BOHR2ANG
    pos = np.array(pos) / BOHR2ANG

    calc = geom.calculator
    calc.plot()

    ax = calc.ax
    ax.plot(*pos[:,0,:2].T)

    plt.show()
Exemplo n.º 22
0
        def test_apply_strain(self):
            calc = TersoffScr(**Tersoff_PRB_39_5566_Si_C__Scr)
            timestep = 1.0 * units.fs

            atoms = ase.io.read('cryst_rot_mod.xyz')
            atoms.set_calculator(calc)

            # constraints
            top = atoms.positions[:, 1].max()
            bottom = atoms.positions[:, 1].min()
            fixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) |
                          (abs(atoms.positions[:, 1] - bottom) < 1.0))
            fix_atoms = FixAtoms(mask=fixed_mask)

            # strain
            orig_height = (atoms.positions[:, 1].max() -
                           atoms.positions[:, 1].min())
            delta_strain = timestep * 1e-5 * (1 / units.fs)
            rigid_constraints = False
            strain_atoms = ConstantStrainRate(orig_height, delta_strain)
            atoms.set_constraint(fix_atoms)

            # dynamics
            np.random.seed(0)
            simulation_temperature = 300 * units.kB
            MaxwellBoltzmannDistribution(atoms, 2.0 * simulation_temperature)
            dynamics = VelocityVerlet(atoms, timestep)

            def apply_strain(atoms, ConstantStrainRate, rigid_constraints):
                ConstantStrainRate.apply_strain(atoms, rigid_constraints)

            dynamics.attach(apply_strain, 1, atoms, strain_atoms,
                            rigid_constraints)
            dynamics.run(100)

            # tests
            if rigid_constraints == True:
                answer = 0
                temp_answer = 238.2066417638124
            else:
                answer = 0.013228150080099255
                temp_answer = 236.76904696481486

            newpos = atoms.get_positions()
            current_height = newpos[:, 1].max() - newpos[:, 1].min()
            diff_height = (current_height - orig_height)
            self.assertAlmostEqual(diff_height, answer)

            temperature = (atoms.get_kinetic_energy() /
                           (1.5 * units.kB * len(atoms)))
            self.assertAlmostEqual(temperature, temp_answer)
Exemplo n.º 23
0
def run_md():

    # Use Asap for a huge performance increase if it is installed
    use_asap = True

    if use_asap:
        from asap3 import EMT
        size = 10
    else:
        from ase.calculators.emt import EMT
        size = 3

    # Set up a crystal
    atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                              symbol="Cu",
                              size=(size, size, size),
                              pbc=True)

    # Describe the interatomic interactions with the Effective Medium Theory
    atoms.calc = EMT()

    # Set the momenta corresponding to T=300K
    MaxwellBoltzmannDistribution(atoms, 300 * units.kB)

    # We want to run MD with constant energy using the VelocityVerlet algorithm.
    dyn = VelocityVerlet(atoms, 5 * units.fs)  # 5 fs time step.

    traj = Trajectory('cu.traj', 'w', atoms)
    dyn.attach(traj.write, interval=10)

    def printenergy(a=atoms):  # store a reference to atoms in the definition.
        epot, ekin = calcenergy(a)
        print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
              'Etot = %.3feV' % (epot, ekin, ekin /
                                 (1.5 * units.kB), epot + ekin))

    # Now run the dynamics
    dyn.attach(printenergy, interval=10)
    printenergy()
    dyn.run(200)
Exemplo n.º 24
0
    def run(self):
        self.dyn = VelocityVerlet(self.atoms,
                                  self.time_step * units.fs,
                                  trajectory='md.traj')

        def printenergy(a=self.atoms):
            epot_ = a.get_potential_energy()
            r = a.calc.r.detach().numpy()
            i_ = np.where(np.logical_and(r < self.rtole * self.ro, r > 0.0001))
            n = len(i_[0])

            if len(self.Epot) == 0:
                dE_ = 0.0
            else:
                dE_ = abs(epot_ - self.Epot[-1])
            self.Epot.append(epot_)

            self.epot = epot_ / self.natom
            self.ekin = a.get_kinetic_energy() / self.natom
            self.T = self.ekin / (1.5 * units.kB)
            self.step = self.dyn.nsteps

            print('Step %d Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
                  'Etot = %.3feV' % (self.step, self.epot, self.ekin, self.T,
                                     self.epot + self.ekin))
            try:
                if self.CheckDE:
                    assert n == 0 and dE_ < self.dEstop, 'Atoms too closed or Delta E too high!'
                else:
                    assert n == 0 and self.T < self.Tmax, 'Atoms too closed or Temperature goes too high!'
            except:
                # for _ in i_:
                #     print('atoms pair',_)
                print(
                    'Atoms too closed or Temperature goes too high, stop at %d.'
                    % self.step)
                self.dyn.max_steps = self.dyn.nsteps - 1

        # traj = Trajectory('md.traj', 'w', self.atoms)
        self.dyn.attach(printenergy, interval=1)
        # self.dyn.attach(traj.write,interval=1)
        self.dyn.run(self.totstep)
Exemplo n.º 25
0
def serve_md(nuclear_charges, coordinates, calculator=None, temp=None):
    """
    """

    if calculator is None:
        parameters = {}
        parameters["offset"] = -97084.83100465109
        parameters["sigma"] = 10.0
        alphas = np.load(FILENAME_ALPHAS)
        X = np.load(FILENAME_REPRESENTATIONS)
        Q = np.load(FILENAME_CHARGES, allow_pickle=True)
        alphas = np.array(alphas, order="F")
        X = np.array(X, order="F")
        calculator = QMLCalculator(parameters, X, Q, alphas)


    # SET MOLECULE
    molecule = ase.Atoms(nuclear_charges, coordinates)
    molecule.set_calculator(calculator)

    # SET ASE MD
    # Set the momenta corresponding to T=300K
    MaxwellBoltzmannDistribution(molecule, 200 * units.kB)

    time = 0.5

    if temp is None:
        # We want to run MD with constant energy using the VelocityVerlet algorithm.
        dyn = VelocityVerlet(molecule, time * units.fs)  # 1 fs time step.

    else:
        dyn = NVTBerendsen(molecule, time*units.fs, temp, time*units.fs, fixcm=False)

    # SET AND SERVE NARUPA MD
    imd = ASEImdServer(dyn)

    while True:
        imd.run(10)
        print("")
        dump_xyz(molecule, tmpdir + "snapshot.xyz")

    return
Exemplo n.º 26
0
def test_gfn2xtb_velocityverlet():
    """Perform molecular dynamics with GFN2-xTB and Velocity Verlet Integrator"""

    thr = 1.0e-5

    atoms = Atoms(
        symbols="NHCHC2H3OC2H3ONHCH3",
        positions=np.array([
            [1.40704587284727, -1.26605342016611, -1.93713466561923],
            [1.85007200612454, -0.46824072777417, -1.50918242392545],
            [-0.03362432532150, -1.39269245193812, -1.74003582081606],
            [-0.56857009928108, -1.01764444489068, -2.61263467107342],
            [-0.44096297340282, -2.84337808903410, -1.48899734014499],
            [-0.47991761226058, -0.55230954385212, -0.55520222968656],
            [-1.51566045903090, -2.89187354810876, -1.32273881320610],
            [-0.18116520746778, -3.45187805987944, -2.34920431470368],
            [0.06989722340461, -3.23298998903001, -0.60872832703814],
            [-1.56668253918793, 0.00552120970194, -0.52884675001441],
            [1.99245341064342, -1.73097165236442, -3.08869239114486],
            [3.42884244212567, -1.30660069291348, -3.28712665743189],
            [3.87721962540768, -0.88843123009431, -2.38921453037869],
            [3.46548545761151, -0.56495308290988, -4.08311788302584],
            [4.00253374168514, -2.16970938132208, -3.61210068365649],
            [1.40187968630565, -2.43826111827818, -3.89034127398078],
            [0.40869198386066, -0.49101709352090, 0.47992424955574],
            [1.15591901335007, -1.16524842262351, 0.48740266650199],
            [0.00723492494701, 0.11692276177442, 1.73426297572793],
            [0.88822128447468, 0.28499001838229, 2.34645658013686],
            [-0.47231557768357, 1.06737634000561, 1.52286682546986],
            [-0.70199987915174, -0.50485938116399, 2.28058247845421],
        ]),
    )

    calc = XTB(method="GFN2-xTB", cache_api=False)
    atoms.set_calculator(calc)

    dyn = VelocityVerlet(atoms, timestep=1.0 * fs)
    dyn.run(20)

    assert approx(atoms.get_potential_energy(), thr) == -896.9772346260584
    assert approx(atoms.get_kinetic_energy(), thr) == 0.022411127028842362

    atoms.calc.set(cache_api=True)
    dyn.run(20)

    assert approx(atoms.get_potential_energy(), thr) == -896.9913862530841
    assert approx(atoms.get_kinetic_energy(), thr) == 0.036580471363852810
Exemplo n.º 27
0
def train_pes_by_tempering(atoms,
                           gp,
                           cutoff,
                           ttime,
                           calculator=None,
                           model=None,
                           dt=2.,
                           ediff=0.01,
                           volatile=None,
                           target_temperature=1000.,
                           stages=1,
                           equilibration=5,
                           rescale_velocities=1.05,
                           pressure=None,
                           stress_equilibration=5,
                           rescale_cell=1.01,
                           randomize=True,
                           algorithm='fastfast',
                           name='model',
                           overwrite=True,
                           traj='tempering.traj',
                           logfile='leapfrog.log'):
    assert rescale_velocities > 1 and rescale_cell > 1

    if model is not None:
        if type(model) == str:
            model = PosteriorPotentialFromFolder(model)
        if gp is None:
            gp = model.gp

    if atoms.get_velocities() is None:
        t = target_temperature
        MaxwellBoltzmannDistribution(atoms, t * units.kB)
        Stationary(atoms)
        ZeroRotation(atoms)

    dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj)
    dyn = Leapfrog(dyn,
                   gp,
                   cutoff,
                   calculator=calculator,
                   model=model,
                   ediff=ediff,
                   volatile=volatile,
                   algorithm=algorithm,
                   logfile=logfile)

    t = 0
    T = '{} (instant)'.format(atoms.get_temperature())
    checkpoints = np.linspace(0, ttime, stages + 1)[1:]
    for k, target_t in enumerate(checkpoints):
        print('stage: {}, time: {}, target time: {}, (temperature={})'.format(
            k, t, target_t, T))
        while t < target_t:
            spu, e, T, s = dyn.run_updates(equilibration)
            t += spu * equilibration * dt
            dyn.rescale_velocities(
                rescale_velocities if T < target_temperature else 1. /
                rescale_velocities)
            if pressure is not None:
                spu, e, T, s = dyn.run_updates(stress_equilibration)
                t += spu * stress_equilibration * dt
                p = -s[:3].mean() / units.Pascal
                # figure out factor
                dp = p - pressure
                factor = (rescale_cell if dp > 0 else 1. / rescale_cell)
                if randomize:
                    factor = 1 + np.random.uniform(0, 1) * (factor - 1)
                # apply rescaling
                dyn.rescale_cell(factor)

        if k == stages - 1:
            dyn.model.to_folder(name,
                                info='temperature: {}'.format(T),
                                overwrite=overwrite)
        else:
            dyn.model.to_folder('{}_{}'.format(name, k),
                                info='temperature: {}'.format(T),
                                overwrite=overwrite)
    return dyn.get_atoms(), dyn.model
Exemplo n.º 28
0
# Describe the interatomic interactions with the Effective Medium Theory
atoms.set_calculator(EMT())

# Do a quick relaxation of the cluster
qn = QuasiNewton(atoms)
qn.run(0.001, 10)

# Set the momenta corresponding to T=1200K
MaxwellBoltzmannDistribution(atoms, 1200 * units.kB)
Stationary(atoms)  # zero linear momentum
ZeroRotation(atoms)  # zero angular momentum

# We want to run MD using the VelocityVerlet algorithm.

# Save trajectory:
dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory='moldyn4.traj')


def printenergy(a=atoms):  # store a reference to atoms in the definition.
    """Function to print the potential, kinetic and total energy."""
    epot = a.get_potential_energy() / len(a)
    ekin = a.get_kinetic_energy() / len(a)
    print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
          'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin))

dyn.attach(printenergy, interval=10)

# Now run the dynamics
printenergy()
dyn.run(2000)
Exemplo n.º 29
0
strain_atoms = ConstantStrainRate(orig_height,
                                  params.strain_rate * params.timestep)

atoms.set_constraint([fix_atoms, strain_atoms])

atoms.set_calculator(params.calc)

# ********* Setup and run MD ***********

# Set the initial temperature to 2*simT: it will then equilibriate to
# simT, by the virial theorem
MaxwellBoltzmannDistribution(atoms, 2.0 * params.sim_T)

# Initialise the dynamical system
dynamics = VelocityVerlet(atoms, params.timestep)


# Print some information every time step
def printstatus():
    if dynamics.nsteps == 1:
        print """
State      Time/fs    Temp/K     Strain      G/(J/m^2)  CrackPos/A D(CrackPos)/A 
---------------------------------------------------------------------------------"""

    log_format = (
        '%(label)-4s%(time)12.1f%(temperature)12.6f' +
        '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f    (%(d_crack_pos_x)+5.2f)'
    )

    atoms.info['label'] = 'D'  # Label for the status line
Exemplo n.º 30
0
    dimer = Atoms('CCNCCN', [(-r_mec, 0, 0), (0, 0, 0), (r_cn, 0, 0),
                             (r_mec, 3.7, 0), (0, 3.7, 0), (-r_cn, 3.7, 0)])

    masses = dimer.get_masses()
    masses[::3] = m_me
    dimer.set_masses(masses)

    fixd = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)])

    dimer.set_constraint(fixd)

    dimer.calc = calc

    d1 = dimer[:3].get_all_distances()
    d2 = dimer[3:].get_all_distances()
    e = dimer.get_potential_energy()

    md = VelocityVerlet(dimer,
                        2.0 * units.fs,
                        trajectory=calc.name + '.traj',
                        logfile=calc.name + '.log',
                        loginterval=20)
    md.run(100)

    de = dimer.get_potential_energy() - e

    assert np.all(abs(dimer[:3].get_all_distances() - d1) < 1e-10)
    assert np.all(abs(dimer[3:].get_all_distances() - d2) < 1e-10)
    assert abs(de - -0.005) < 0.001
Exemplo n.º 31
0
    
    qmmm_pot = ForceMixingCarvingCalculator(atoms, qm_region_mask,
                                            mm_pot, qm_pot,
                                            buffer_width=qm_outer_radius,
                                            pbc_type=[False, False, True])
    atoms.set_calculator(qmmm_pot)
#Otherwise it will recover temperature from the previous run.
#Use same random seed so that initialisations are deterministic.
    if not args.restart: 
        print 'Thermalizing atoms'
        np.random.seed(42)
        MaxwellBoltzmannDistribution(atoms, 2.0*sim_T)


    dynamics = VelocityVerlet(atoms, timestep)

    def print_context(ats=atoms, dyn=dynamics):
        print 'steps, T', dyn.nsteps, ats.get_kinetic_energy()/(1.5*units.kB*len(ats))
        print 'G', get_energy_release_rate(ats)/(units.J/units.m**2)
        print 'strain', get_strain(ats)
    dynamics.attach(print_context, interval=8)
    print 'Running Crack Simulation'
    dynamics.run(nsteps)
    print 'Crack Simulation Finished'
  elif args.lotf:
    crack_pos = atoms.info['CrackPos']
    r_scale = 1.00894848312
    mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot, cutoff_skin=2.0)
    #test potential
Exemplo n.º 32
0
    from asap3 import EMT
    size = 10
else:
    size = 3
    
# Set up a crystal
atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol="Cu",
                          size=(size,size,size), pbc=True)

# Describe the interatomic interactions with the Effective Medium Theory
atoms.set_calculator(EMT())

# Set the momenta corresponding to T=300K
MaxwellBoltzmannDistribution(atoms, 300*units.kB)

# We want to run MD with constant energy using the VelocityVerlet algorithm.
dyn = VelocityVerlet(atoms, 5*units.fs)  # 5 fs time step.

#Function to print the potential, kinetic and total energy
def printenergy(a):
    epot = a.get_potential_energy() / len(a)
    ekin = a.get_kinetic_energy() / len(a)
    print ("Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  Etot = %.3feV" %
           (epot, ekin, ekin/(1.5*units.kB), epot+ekin))

# Now run the dynamics
printenergy(atoms)
for i in range(20):
    dyn.run(10)
    printenergy(atoms)
Exemplo n.º 33
0
    Driver_='VelocityVerlet',
    Driver_MDRestartFrequency=5,
    Driver_Velocities_='',
    Driver_Velocities_empty='<<+ "velocities.txt"',
    Driver_Steps=500,
    Driver_KeepStationary='Yes',
    Driver_TimeStep=8.26,
    Driver_Thermostat_='Berendsen',
    Driver_Thermostat_Temperature=0.00339845142,  # 800 deg Celcius
    # Driver_Thermostat_Temperature=0.0, # 0 deg Kelvin
    Driver_Thermostat_CouplingStrength=0.01)

write_dftb_velocities(test, 'velocities.txt')
os.system('rm md.log.* md.out* geo_end*xyz')
test.set_calculator(calculator_NVE)
dyn = VelocityVerlet(test, 0.000 * fs)  # fs time step.
dyn.attach(MDLogger(dyn, test, 'md.log.NVE', header=True, stress=False,
                    peratom=False, mode='w'), interval=1)
dyn.run(1)  # run NVE ensemble using DFTB's own driver
test = read('geo_end.gen')
write('test.afterNVE.xyz', test)

read_dftb_velocities(test, filename='geo_end.xyz')
write_dftb_velocities(test, 'velocities.txt')

os.system('mv md.out md.out.NVE')
os.system('mv geo_end.xyz geo_end_NVE.xyz')

test.set_calculator(calculator_NVT)
os.system('rm md.log.NVT')
dyn.attach(MDLogger(dyn, test, 'md.log.NVT', header=True, stress=False,
Exemplo n.º 34
0
                dist = 0.001
            energy += self.A / dist**self.alpha
        return energy

    def __repr__(self):
        return 'Repulsion potential'

    def copy(self):
        return CentralRepulsion(self, R=self.R, A=self.A, alpha=self.alpha)


if __name__ == '__main__':
    from ase.cluster.cubic import FaceCenteredCubic
    from ase.calculators.emt import EMT
    from ase.md.verlet import VelocityVerlet
    from ase.units import fs

    atoms = FaceCenteredCubic('Ag', [(1, 0, 0)], [1], 4.09)
    atoms.center(10)

    atoms.set_calculator(EMT())
    c = ConstantForce(10, [0, 1, 0])  # y=dircted force
    atoms.set_constraint(c)

    md = VelocityVerlet(atoms, 1*fs, trajectory='cf_test.traj',
                        logfile='-')
    md.run(100)

    # from ase.visualize import view
    # view(atoms)
Exemplo n.º 35
0
# *** Milestone 3.1 -- exit early - we don't want to run the classical MD! ***

import sys
sys.exit(0)

# **** no changes compared to run_crack_classical.py below here yet ****

# ********* Setup and run MD ***********

# Set the initial temperature to 2*simT: it will then equilibriate to
# simT, by the virial theorem
MaxwellBoltzmannDistribution(atoms, 2.0*sim_T)

# Initialise the dynamical system
dynamics = VelocityVerlet(atoms, timestep)

# Print some information every time step
def printstatus():
    if dynamics.nsteps == 1:
        print """
State      Time/fs    Temp/K     Strain      G/(J/m^2)  CrackPos/A D(CrackPos)/A 
---------------------------------------------------------------------------------"""

    log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+
                  '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f    (%(d_crack_pos_x)+5.2f)')

    atoms.info['label'] = 'D'                # Label for the status line
    atoms.info['time'] = dynamics.get_time()/units.fs
    atoms.info['temperature'] = (atoms.get_kinetic_energy() /
                                 (1.5*units.kB*len(atoms)))
Exemplo n.º 36
0
      r_scale = 1.00894848312
      pot  = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)
      defect.set_calculator(pot)
    else:
      print 'No potential chosen', 1/0

    print 'Finding initial dislocation core positions...'
    try:
      defect.params['core']
    except KeyError:
      defect.params['core'] = np.array([98.0, 98.0, 1.49])

    defect  = set_quantum(defect, params.n_core)
    MaxwellBoltzmannDistribution(defect, 2.0*sim_T)
    if dyn_type =='eam':
       dynamics = VelocityVerlet(defect, timestep)
       dynamics.attach(pass_print_context(defect, dynamics))
    elif dyn_type =='LOTF':
       defect.info['core']= np.array([98.0, 98.0, 1.49])
       print 'Initializing LOTFDynamics'
       verbosity_push(PRINT_VERBOSE)
       dynamics = LOTFDynamics(defect, timestep,
                               params.extrapolate_steps,
                               check_force_error=False)
       dynamics.set_qm_update_func(update_qm_region)
       dynamics.attach(pass_print_context(defect, dynamics))
       dynamics.attach(traj_writer, print_interval, defect)
    else:
      print 'No dyn_type chosen', 1/0
    
    trajectory = AtomsWriter('{0}.traj.xyz'.format(input_file))
atoms.set_constraint([fix_atoms, strain_atoms])

atoms.set_calculator(params.calc)

# ********* Setup and run MD ***********

# Set the initial temperature to 2*simT: it will then equilibrate to
# simT, by the virial theorem
MaxwellBoltzmannDistribution(atoms, 2.0*params.sim_T)
p = atoms.get_momenta()
p[np.where(fixed_mask)] = 0
atoms.set_momenta(p)

# Initialise the dynamical system
dynamics = VelocityVerlet(atoms, params.timestep)
# dynamics = Langevin(atoms, params.timestep, params.sim_T * units.kB, 1e-4, fixcm=True)

# Print some information every time step
def printstatus():
    if dynamics.nsteps == 1:
        print """
State      Time/fs    Temp/K     Strain      G/(J/m^2)  CrackPos/A D(CrackPos)/A
---------------------------------------------------------------------------------"""

    log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+
                  '%(strain)12.4f%(crack_pos_x)12.2f    (%(d_crack_pos_x)+5.2f)')

    atoms.info['label'] = 'D'                  # Label for the status line
    atoms.info['time'] = dynamics.get_time()/units.fs
    atoms.info['temperature'] = get_temperature(atoms)
Exemplo n.º 38
0
    epot = atoms.get_potential_energy()
    print >>stdout, "Potential energy:", epot
    ReportTest("Initial potential energy", epot, -301358.3, 0.5)
    etot = epot + atoms.get_kinetic_energy()

    if 0:
        if cpulayout:
            traj = ParallelNetCDFTrajectory("parallel.nc", atoms)
        else:
            traj = NetCDFTrajectory("serial.nc", atoms)
        traj.Add("PotentialEnergies")
        traj.Update()
        traj.Close()
        print "Trajectory done"
    
    dyn = VelocityVerlet(atoms, 3*units.fs)
    etot2 = None
    for i in range(5):
        dyn.run(15)
        newetot = atoms.get_potential_energy()+ atoms.get_kinetic_energy()
        print >>stdout, "Total energy:", newetot
        temp = atoms.get_kinetic_energy() / (1.5*units.kB*natoms)
        print >>stdout, "Temp:", temp, "K"
        if etot2 == None:
            ReportTest("Total energy (first step)", newetot, etot, 40.0)
            etot2=newetot
        else:
            ReportTest(("Total energy (step %d)" % (i+1,)),
                       newetot, etot2, 20.0)
    print >>stdout, " *** This test completed ***"
Exemplo n.º 39
0
    #    pass

    def __repr__(self):
        return 'Push atoms out of the cell back to the cell'

    def copy(self):
        return ConstantForce(a=self.index, force=self.force)

if __name__ == '__main__':
    from ase.cluster.cubic import FaceCenteredCubic
    from ase.calculators.emt import EMT
    from ase.md.verlet import VelocityVerlet
    from ase.units import fs
    from constantforce import ConstantForce

    atoms = FaceCenteredCubic(
      'Ag', [(1, 0, 0)], [1], 4.09)
    atoms.center(10)
    atoms.pbc = True

    atoms.set_calculator( EMT() )
    cf = ConstantForce( 10, [0,1,0] )  # y=dircted force
    ic = ImprisonConstraint()
    atoms.set_constraint( [cf, ic] )

    md = VelocityVerlet( atoms, 1*fs, trajectory = 'cf_test.traj', logfile='-' )
    md.run(200)

    #~ from ase.visualize import view
    #~ view(atoms)
Exemplo n.º 40
0
    def update_atoms(self):
        pass

    def set_atoms(self, atoms):
        self.atoms = atoms
        self.update_atoms()


if __name__ == '__main__':
    from ase import Atoms
    atoms = Atoms(symbols='CeO', cell=[2, 2, 5], positions=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 2.4935832]]))
    atoms[0].charge = +4
    atoms[1].charge = -2
    calc = Buck({('Ce', 'O'): (1176.3, 0.381, 0.0)})
    #calc = Buck( {('Ce', 'O'): (0.0, 0.149, 0.0)} )
    atoms.set_calculator(calc)
    print('Epot = ', atoms.get_potential_energy())
    print('Force = ', atoms.get_forces())

    from ase.md.verlet import VelocityVerlet
    dyn = VelocityVerlet(atoms, dt=0.1*units.fs, trajectory='test.traj', logfile='-')
    dyn.run(1000)
    print('coodrs = ', atoms.get_positions())
    from ase.visualize import view
    view(atoms)




Exemplo n.º 41
0
def learn_pes_by_tempering(atoms,
                           gp,
                           cutoff,
                           ttime,
                           calculator=None,
                           model=None,
                           dt=2.,
                           ediff=0.01,
                           volatile=None,
                           target_temperature=1000.,
                           stages=1,
                           equilibration=5,
                           rescale_velocities=1.05,
                           pressure=None,
                           stress_equilibration=5,
                           rescale_cell=1.01,
                           eps='random',
                           algorithm='fastfast',
                           name='model',
                           overwrite=True,
                           traj='tempering.traj',
                           logfile='leapfrog.log'):
    """
    pressure (hydrostatic): 
        defined in units of Pascal and is equal to -(trace of stress tensor)/3 
    eps:
        if 'random', strain *= a random number [0, 1)
        if a positive float, strain *= 1-e^(-|dp/p|/eps) i.e. eps ~ relative p fluctuations
        else, no action
    """
    assert rescale_velocities > 1 and rescale_cell > 1
    if pressure is not None:
        warnings.warn('rescaling cell is not robust!')

    if model is not None:
        if type(model) == str:
            model = PosteriorPotentialFromFolder(model)
        if gp is None:
            gp = model.gp

    if atoms.get_velocities() is None:
        t = target_temperature
        MaxwellBoltzmannDistribution(atoms, t * units.kB)
        Stationary(atoms)
        ZeroRotation(atoms)

    dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj)
    dyn = Leapfrog(dyn,
                   gp,
                   cutoff,
                   calculator=calculator,
                   model=model,
                   ediff=ediff,
                   volatile=volatile,
                   algorithm=algorithm,
                   logfile=logfile)

    t = 0
    T = '{} (instant)'.format(atoms.get_temperature())
    checkpoints = np.linspace(0, ttime, stages + 1)[1:]
    for k, target_t in enumerate(checkpoints):
        print('stage: {}, time: {}, target time: {}, (temperature={})'.format(
            k, t, target_t, T))
        while t < target_t:
            spu, e, T, s = dyn.run_updates(equilibration)
            t += spu * equilibration * dt
            dyn.rescale_velocities(
                rescale_velocities if T < target_temperature else 1. /
                rescale_velocities)
            if pressure is not None:
                spu, e, T, s = dyn.run_updates(stress_equilibration)
                t += spu * stress_equilibration * dt
                p = -s[:3].mean() / units.Pascal
                # figure out strain
                dp = p - pressure
                strain = (rescale_cell if dp > 0 else 1. / rescale_cell) - 1
                if eps is 'random':
                    strain *= np.random.uniform()
                elif type(eps) == float and eps > 0 and abs(p) > 0:
                    strain *= 1 - np.exp(-np.abs(dp / p) / eps)
                # apply strain
                dyn.strain_atoms(np.eye(3) * strain)

        if k == stages - 1:
            dyn.model.to_folder(name,
                                info='temperature: {}'.format(T),
                                overwrite=overwrite)
        else:
            dyn.model.to_folder('{}_{}'.format(name, k),
                                info='temperature: {}'.format(T),
                                overwrite=overwrite)
    return dyn.get_atoms(), dyn.model
Exemplo n.º 42
0
def test(temp, frict):
    output = file('Langevin.dat', 'w')
    
    # Make a small perturbation of the momenta
    atoms.set_momenta(1e-6 * np.random.random([len(atoms), 3]))
    print 'Initializing ...'
    predyn = VelocityVerlet(atoms, 0.5)
    predyn.run(2500)

    dyn = Langevin(atoms, timestep, temp, frict)
    print ''
    print ('Testing Langevin dynamics with T = %f eV and lambda = %f' %
           (temp, frict))
    ekin = atoms.get_kinetic_energy()/len(atoms)
    print ekin
    output.write('%.8f\n' % ekin)

    print 'Equilibrating ...'

    # Initial guesses for least-squares fit
    a = 0.04
    b = 2*frict
    c = temp
    params = (a,b,c)
    fitdata = [(0, 2.0 / 3.0 * ekin)]

    tstart = time.time()
    for i in xrange(1,nequil+1):
        dyn.run(nminor)
        ekin = atoms.get_kinetic_energy() / len(atoms)
        fitdata.append((i*nminor*timestep, 2.0/3.0 * ekin))
        if usescipy and i % nequilprint == 0:
            (params, chisq) = leastSquaresFit(targetfunc, params, fitdata)
            print '%.6f  T_inf = %.6f (goal: %f), tau = %.2f,  k = %.6f' % \
                  (ekin, params[2], temp, 1.0/params[1], params[0])
        output.write('%.8f\n' % ekin)
    tequil = time.time() - tstart
    print 'This took %s minutes.' % (tequil / 60)
    output.write('&\n')
    assert abs(temp-params[2]) < 0.25*temp, 'Least-squares fit is way off'
    assert nequil*nminor*timestep > 3.0/params[1], 'Equiliberation was too short'
    fitdata = np.array(fitdata)

    print 'Recording statistical data - this takes ten times longer!'
    temperatures = []
    tstart = time.time()
    for i in xrange(1,nsteps+1):
        dyn.run(nminor)
        ekin = atoms.get_kinetic_energy() / len(atoms)
        temperatures.append(2.0/3.0 * ekin)
        if i % nprint == 0:
            tnow = time.time() - tstart
            tleft = (nsteps-i) * tnow / i
            print '%.6f    (time left: %.1f minutes)' % (ekin, tleft/60)
        output.write('%.8f\n' % ekin)
    output.write('&\n')
    output.close()

    temperatures = np.array(temperatures)
    mean = sum(temperatures) / len(temperatures)
    print 'Mean temperature:', mean, 'eV'
    print
    print 'This test is statistical, and may in rare cases fail due to a'
    print 'statistical fluctuation.'
    print
    assert abs(mean - temp) <= reltol*temp, 'Deviation is too large.'
    print 'Mean temperature:', mean, ' in ', temp, ' +/- ', reltol*temp

    return fitdata, params, temperatures
Exemplo n.º 43
0
def learn_pes_by_anealing(atoms,
                          gp,
                          cutoff,
                          calculator=None,
                          model=None,
                          dt=2.,
                          ediff=0.01,
                          volatile=None,
                          target_temperature=1000.,
                          stages=1,
                          equilibration=5,
                          rescale_velocities=1.05,
                          algorithm='fastfast',
                          name='model',
                          overwrite=True,
                          traj='anealing.traj',
                          logfile='leapfrog.log'):
    assert rescale_velocities > 1

    if model is not None:
        if type(model) == str:
            model = PosteriorPotentialFromFolder(model)
        if gp is None:
            gp = model.gp

    if atoms.get_velocities() is None:
        t = target_temperature / stages
        MaxwellBoltzmannDistribution(atoms, t * units.kB)
        Stationary(atoms)
        ZeroRotation(atoms)

    dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj)
    dyn = Leapfrog(dyn,
                   gp,
                   cutoff,
                   calculator=calculator,
                   model=model,
                   ediff=ediff,
                   volatile=volatile,
                   algorithm=algorithm,
                   logfile=logfile)

    # initial equilibration
    while dyn.volatile():
        _, e, t, s = dyn.run_updates(1)
    _, e, t, s = dyn.run_updates(equilibration)

    temperatures = np.linspace(t, target_temperature, stages + 1)[1:]
    heating = t < target_temperature
    cooling = not heating
    for k, target_t in enumerate(temperatures):
        print(
            'stage: {}, temperature: {}, target temperature: {}, ({})'.format(
                k, t, target_t, 'heating' if heating else 'cooling'))
        while (heating and t < target_t) or (cooling and t > target_t):
            dyn.rescale_velocities(rescale_velocities if heating else 1. /
                                   rescale_velocities)
            _, e, t, s = dyn.run_updates(equilibration)
        if k == stages - 1:
            dyn.model.to_folder(name,
                                info='temperature: {}'.format(t),
                                overwrite=overwrite)
        else:
            dyn.model.to_folder('{}_{}'.format(name, k),
                                info='temperature: {}'.format(t),
                                overwrite=overwrite)
    return dyn.get_atoms(), dyn.model
Exemplo n.º 44
0
              (abs(atoms.positions[:, 1] - bottom) < 1.0))
fix_atoms = FixAtoms(mask=fixed_mask)

strain_atoms = ConstantStrainRate(orig_height, strain_rate*timestep)
atoms.set_constraint([fix_atoms, strain_atoms])

mm_pot = Potential("IP SW", cutoff_skin=cutoff_skin)
mm_pot.set_default_properties(['stresses'])

atoms.set_calculator(mm_pot)

# ********* Setup and run MD ***********

MaxwellBoltzmannDistribution(atoms, 2.0*sim_T)

dynamics = VelocityVerlet(atoms, timestep)

def printstatus():
    if dynamics.nsteps == 1:
        print """
State      Time/fs    Temp/K     Strain      G/(J/m^2)  CrackPos/A D(CrackPos)/A 
---------------------------------------------------------------------------------"""

    log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+
                  '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f    (%(d_crack_pos_x)+5.2f)')

    atoms.info['label'] = 'D'                  # Label for the status line
    atoms.info['time'] = dynamics.get_time()/units.fs
    atoms.info['temperature'] = (atoms.get_kinetic_energy() /
                                 (1.5*units.kB*len(atoms)))
    atoms.info['strain'] = get_strain(atoms)
Exemplo n.º 45
0
Arquivo: 09.py Projeto: amaharaj/ASE
	else:
		i += 1	
c = FixAtoms(indices = array)
atoms.set_constraint(c)

# relax with Quasi Newtonian
qn = QuasiNewton(atoms, trajectory='qn.traj')
qn.run(fmax=0.001)
write('qn.final.xyz', atoms)

# Set the momenta corresponding to T=300K
MaxwellBoltzmannDistribution(atoms, 300*units.kB)
print 'Removing linear momentum and angular momentum'
Stationary(atoms) # zero linear momentum
ZeroRotation(atoms) # zero angular momentum

# We want to run MD using the VelocityVerlet algorithm.
dyn = VelocityVerlet(atoms, 0.1*units.fs, trajectory='moldyn4.traj') # save trajectory.

#Function to print the potential, kinetic and total energy.
def printenergy(a=atoms):    #store a reference to atoms in the definition.
    epot = a.get_potential_energy() / len(a)
    ekin = a.get_kinetic_energy() / len(a)
    print ("Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  Etot = %.3feV" %
           (epot, ekin, ekin/(1.5*units.kB), epot+ekin))
dyn.attach(printenergy, interval=10)

# Now run the dynamics
printenergy()
dyn.run(2000)
Exemplo n.º 46
0
        atoms.set_pbc(False)
        atoms.center(vacuum=6.0)
        atoms.set_velocities(np.zeros_like(atoms.get_positions()))
        cell_c = np.sum(atoms.get_cell()**2, axis=1)**0.5
        N_c = 16 * np.round(cell_c / (0.25 * 16))
        calc = GPAW(gpts=N_c, nbands=1, basis='dzp', setups={'Na': '1'},
                    txt=name + '_gs.txt')
        atoms.set_calculator(calc)
        atoms.get_potential_energy()
        calc.write(name + '_gs.gpw', mode='all')
        del atoms, calc
        time.sleep(10)

    while not os.path.isfile(name + '_gs.gpw'):
        print 'Node %d waiting for file...' % world.rank
        time.sleep(10)
    world.barrier()

    tdcalc = GPAW(name + '_gs.gpw', txt=name + '_td.txt')
    tdcalc.forces.reset() #XXX debug
    tdcalc.initialize_positions()
    atoms = tdcalc.get_atoms()

    traj = PickleTrajectory(name + '_td.traj', 'w', atoms)
    verlet = VelocityVerlet(atoms, timestep * 1e-3 * fs,
                            logfile=paropen(name + '_td.verlet', 'w'),
                            trajectory=traj)
    verlet.attach(Timing(paropen(name + '_td.log', 'w')), ndiv, atoms)
    verlet.run(niter)
    traj.close()
Exemplo n.º 47
0
    size = 3

# Set up a crystal
atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                          symbol="Cu",
                          size=(size, size, size),
                          pbc=True)

# Describe the interatomic interactions with the Effective Medium Theory
atoms.calc = EMT()

# Set the momenta corresponding to T=300K
MaxwellBoltzmannDistribution(atoms, 300 * units.kB)

# We want to run MD with constant energy using the VelocityVerlet algorithm.
dyn = VelocityVerlet(atoms, 5 * units.fs)  # 5 fs time step.


def printenergy(a=atoms):  # store a reference to atoms in the definition.
    """Function to print the potential, kinetic and total energy."""
    epot = a.get_potential_energy() / len(a)
    ekin = a.get_kinetic_energy() / len(a)
    print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
          'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin))


# Now run the dynamics
dyn.attach(printenergy, interval=10)
printenergy()
dyn.run(200)
Exemplo n.º 48
0
        print 'No cell geometry given, specifiy either disloc or crack', 1/0 
  
  # ********* Setup and run MD ***********
  # Set the initial temperature to 2*simT: it will then equilibriate to
  # simT, by the virial theorem
  if params.test_mode:
      np.random.seed(0) # use same random seed each time to be deterministic 
  if params.rescale_velo:
      MaxwellBoltzmannDistribution(atoms, 2.0*sim_T)
  # Save frames to the trajectory every `traj_interval` time steps
  # but only when interpolating
  trajectory = AtomsWriter(os.path.join(params.rundir, params.traj_file))
  # Initialise the dynamical system
  system_timer('init_dynamics')
  if params.extrapolate_steps == 1:
      dynamics = VelocityVerlet(atoms, params.timestep)
      check_force_error = False
      if not params.classical:
          qmmm_pot.set(calc_weights=True)
      dynamics.state_label = 'D'
  else:
    print 'Initializing LOTF Dynamics'
    dynamics = LOTFDynamics(atoms, params.timestep,
                            params.extrapolate_steps,
                            check_force_error=check_force_error)
  system_timer('init_dynamics')
#Function to update the QM region at the beginning of each extrapolation cycle   
  if not check_force_error:
      if params.extrapolate_steps == 1:
          if not params.classical:
              dynamics.attach(update_qm_region, 1, dynamics.atoms)