예제 #1
0
def equilibrated(asap3, berendsenparams):
    """Make an atomic system with equilibrated temperature and pressure."""
    rng = np.random.RandomState(42)
    with seterr(all='raise'):
        print()
        # Must be big enough to avoid ridiculous fluctuations
        atoms = bulk('Au', cubic=True).repeat((3, 3, 3))
        #a[5].symbol = 'Ag'
        print(atoms)
        atoms.calc = asap3.EMT()
        MaxwellBoltzmannDistribution(atoms,
                                     temperature_K=100,
                                     force_temp=True,
                                     rng=rng)
        Stationary(atoms)
        assert abs(atoms.get_temperature() - 100) < 0.0001
        md = NPTBerendsen(atoms,
                          timestep=20 * fs,
                          logfile='-',
                          loginterval=200,
                          **berendsenparams['npt'])
        # Equilibrate for 20 ps
        md.run(steps=1000)
        T = atoms.get_temperature()
        pres = -atoms.get_stress(
            include_ideal_gas=True)[:3].sum() / 3 / GPa * 10000
        print("Temperature: {:.2f} K    Pressure: {:.2f} bar".format(T, pres))
        return atoms
예제 #2
0
def init_vel(cml):
    '''
    '''
    arg = parse_cml_args(cml)

    # read in the initial structure
    init_pos = read(arg.poscar)
    # set the momenta corresponding to T
    MaxwellBoltzmannDistribution(init_pos, arg.temperature * ase.units.kB)
    Stationary(init_pos)
    ZeroRotation(init_pos)

    # scale the temperature to T 
    vel = init_pos.get_velocities()
    Tn = init_pos.get_temperature()
    vel *= np.sqrt(arg.temperature / Tn)
    init_pos.set_velocities(vel)

    # write the structure
    write(arg.out, init_pos, vasp5=True, direct=True)

    # units in VASP and ASE are different
    vel = init_pos.get_velocities() * ase.units.fs
    # np.savetxt('init_vel.dat', vel, fmt='%20.16f')
    # append the velocities to the POSCAR
    with open(arg.out, 'a+') as pos:
        pos.write('\n')
        pos.write(
                '\n'.join([
                    ''.join(["%20.16f" % x for x in row])
                    for row in vel
                   ])
                )
예제 #3
0
def test_fixrotation_asap(asap3):
    rng = np.random.RandomState(123)

    with seterr(all='raise'):
        atoms = bulk('Au', cubic=True).repeat((3, 3, 10))
        atoms.pbc = False
        atoms.center(vacuum=5.0 + np.max(atoms.cell) / 2)
        print(atoms)
        atoms.calc = asap3.EMT()
        MaxwellBoltzmannDistribution(atoms, temperature_K=300, force_temp=True,
                                     rng=rng)
        Stationary(atoms)
        check_inertia(atoms)
        md = Langevin(
            atoms,
            timestep=20 * fs,
            temperature_K=300,
            friction=1e-3,
            logfile='-',
            loginterval=500,
            rng=rng)
        fx = FixRotation(atoms)
        md.attach(fx)
        md.run(steps=1000)
        check_inertia(atoms)
예제 #4
0
    def __init__(
        self,
        atoms,
        timestep,
        temperature,
        nvt_q,
        trajectory=None,
        logfile=None,
        loginterval=1,
        append_trajectory=False,
    ):
        # set angular and com momentum to zero, necessary for nose-hoover dynamics.
        ZeroRotation(atoms)
        Stationary(atoms)

        # thermostat parameters
        self.temp = temperature / units.kB
        self.nvt_q = nvt_q
        self.dt = timestep
        self.dtdt = np.power(self.dt, 2)
        self.nvt_bath = 0.0

        self.natoms = len(atoms)

        MolecularDynamics.__init__(
            self,
            atoms,
            timestep,
            trajectory,
            logfile,
            loginterval,
            append_trajectory=append_trajectory,
        )
예제 #5
0
    def __init__(
        self,
        atoms,
        timestep,
        temperature,
        nvt_q,
        trajectory=None,
        logfile=None,
        loginterval=1,
        append_trajectory=False,
    ):
        # set com momentum to zero
        Stationary(atoms)

        self.temp = temperature / units.kB
        self.nvt_q = nvt_q
        self.dt = timestep  # units: A/sqrt(u/eV)
        self.dtdt = np.power(self.dt, 2)
        self.nvt_bath = 0.0

        MolecularDynamics.__init__(
            self,
            atoms,
            timestep,
            trajectory,
            logfile,
            loginterval,
            append_trajectory=append_trajectory,
        )
예제 #6
0
def test_otf_md(md_engine, md_params, super_cell, flare_calc, qe_calc):
    np.random.seed(12345)

    flare_calculator = flare_calc[md_engine]
    # set up OTF MD engine
    otf_params = {
        'init_atoms': [0, 1, 2, 3],
        'output_name': md_engine,
        'std_tolerance_factor': 2,
        'max_atoms_added': len(super_cell.positions),
        'freeze_hyps': 10
    }
    #                  'use_mapping': flare_calculator.use_mapping}

    md_kwargs = md_params[md_engine]

    # intialize velocity
    temperature = md_params['temperature']
    MaxwellBoltzmannDistribution(super_cell, temperature * units.kB)
    Stationary(super_cell)  # zero linear momentum
    ZeroRotation(super_cell)  # zero angular momentum

    super_cell.set_calculator(flare_calculator)
    test_otf = ASE_OTF(super_cell,
                       timestep=1 * units.fs,
                       number_of_steps=3,
                       dft_calc=qe_calc,
                       md_engine=md_engine,
                       md_kwargs=md_kwargs,
                       **otf_params)

    # TODO: test if mgp matches gp
    # TODO: see if there's difference between MD timestep & OTF timestep

    # set up logger
    #    otf_logger = OTFLogger(test_otf, super_cell,
    #        logfile=md_engine+'.log', mode="w", data_in_logfile=True)
    #    test_otf.attach(otf_logger, interval=1)

    test_otf.run()

    for f in glob.glob("scf*.pw*"):
        os.remove(f)
    for f in glob.glob("*.npy"):
        os.remove(f)
    for f in glob.glob("kv3*"):
        shutil.rmtree(f)
    for f in glob.glob("otf_data"):
        shutil.rmtree(f, ignore_errors=True)
    for f in glob.glob("out"):
        shutil.rmtree(f, ignore_errors=True)

    for f in os.listdir("./"):
        if md_engine in f or 'lmp.mgp' in f:
            os.remove(f)
        if 'slurm' in f:
            os.remove(f)
예제 #7
0
def otf_md_test(md_engine):
    import atom_setup, flare_setup, qe_setup
    np.random.seed(12345)
    
    print(md_engine)

    # ----------- set up atoms -----------------
    super_cell = atom_setup.super_cell
    
    # ----------- setup flare calculator ---------------
    flare_calc = deepcopy(flare_setup.flare_calc)
    super_cell.set_calculator(flare_calc)
    
    # ----------- setup qe calculator --------------
    dft_calc = qe_setup.dft_calc
    
    # ----------- create otf object -----------
    # set up OTF MD engine
    md_params = {'timestep': 1 * units.fs, 'trajectory': None, 'dt': None, 
                 'externalstress': 0, 'ttime': 25, 'pfactor': 3375, 
                 'mask': None, 'temperature': 500, 'taut': 1, 'taup': 1,
                 'pressure': 0, 'compressibility': 0, 'fixcm': 1, 
                 'friction': 0.02}
    otf_params = {'dft_calc': dft_calc, 
                  'init_atoms': [0, 1, 2, 3],
                  'std_tolerance_factor': 2, 
                  'max_atoms_added' : len(super_cell.positions),
                  'freeze_hyps': 10, 
                  'use_mapping': super_cell.calc.use_mapping}
   
    # intialize velocity
    temperature = md_params['temperature']
    MaxwellBoltzmannDistribution(super_cell, temperature * units.kB)
    Stationary(super_cell)  # zero linear momentum
    ZeroRotation(super_cell)  # zero angular momentum

    test_otf = otf_md(md_engine, super_cell, md_params, otf_params)

    # set up logger
    test_otf.attach(OTFLogger(test_otf, super_cell, 
        logfile=md_engine+'.log', mode="w", data_in_logfile=True), 
        interval=1)
    
    # run otf
    number_of_steps = 3
    test_otf.otf_run(number_of_steps)

    os.system('rm {}.log'.format(md_engine)) 
    os.system('rm AgI.pw*')
    os.system('rm -r out')
    os.system('rm -r __pycache__')
    os.system('rm -r kv3')
    os.system('rm lmp.mgp')
    os.system('rm -r otf_data')
    os.system('rm *.npy')
예제 #8
0
def test_otf_md(md_engine, md_params, super_cell, flare_calc, qe_calc):
    np.random.seed(12345)

    flare_calculator = flare_calc[md_engine]
    # set up OTF MD engine
    otf_params = {
        "init_atoms": [0, 1, 2, 3],
        "output_name": md_engine,
        "std_tolerance_factor": 2,
        "max_atoms_added": len(super_cell.positions),
        "freeze_hyps": 10,
        "write_model": 1,
    }
    #                  'use_mapping': flare_calculator.use_mapping}

    md_kwargs = md_params[md_engine]

    # intialize velocity
    temperature = md_params["temperature"]
    MaxwellBoltzmannDistribution(super_cell, temperature * units.kB)
    Stationary(super_cell)  # zero linear momentum
    ZeroRotation(super_cell)  # zero angular momentum

    super_cell.set_calculator(flare_calculator)
    test_otf = ASE_OTF(
        super_cell,
        timestep=1 * units.fs,
        number_of_steps=number_of_steps,
        dft_calc=qe_calc,
        md_engine=md_engine,
        md_kwargs=md_kwargs,
        trajectory=md_engine + "_otf.traj",
        **otf_params,
    )

    # TODO: test if mgp matches gp
    # TODO: see if there's difference between MD timestep & OTF timestep

    test_otf.run()

    for f in glob.glob("scf*.pw*"):
        os.remove(f)
    for f in glob.glob("*.npy"):
        os.remove(f)
    for f in glob.glob("kv3*"):
        shutil.rmtree(f)
    for f in glob.glob("otf_data"):
        shutil.rmtree(f, ignore_errors=True)
    for f in glob.glob("out"):
        shutil.rmtree(f, ignore_errors=True)
    for f in os.listdir("./"):
        if ".mgp" in f or ".var" in f:
            os.remove(f)
        if "slurm" in f:
            os.remove(f)
예제 #9
0
    def build_atoms(self, system, size, temp, seed=None):
        assert system in self.systems.keys(), "System {} not found!".format(
            system)
        atoms = self.systems[system](size)
        rng = np.random
        if seed is not None:
            rng.seed(seed)
        MaxwellBoltzmannDistribution(atoms, temp * units.kB, rng=rng)
        Stationary(atoms)
        ZeroRotation(atoms)

        return atoms
예제 #10
0
파일: md.py 프로젝트: AmstrongLi/schnetpack
    def _init_velocities(self, temp_init=300, remove_translation=True, remove_rotation=True):
        """
        Initialize velocities for molecular dynamics

        Args:
            temp_init (float): Initial temperature in Kelvin (default 300)
            remove_translation (bool): Remove translation components of velocity (default True)
            remove_rotation (bool): Remove rotation components of velocity (default True)
        """
        MaxwellBoltzmannDistribution(self.molecule, temp_init * units.kB)
        if remove_translation:
            Stationary(self.molecule)
        if remove_rotation:
            ZeroRotation(self.molecule)
예제 #11
0
def init_velocities(atoms, temp):
  """Initialize atom velocities according to Maxwell-Bolzmann,
   then zero total linear and angular momenta.

  Args:
    atoms (ase.Atoms): initial configuration
    temp (float): temperature in Kelvin
  """
  from ase import units
  from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
  from ase.md.velocitydistribution import Stationary, ZeroRotation
  MaxwellBoltzmannDistribution(atoms, temp*units.kB)
  Stationary(atoms)
  ZeroRotation(atoms)
예제 #12
0
def test_verlet_asap(asap3):
    with seterr(all='raise'):
        a = bulk('Au').repeat((2, 2, 2))
        a[5].symbol = 'Ag'
        a.pbc = (True, True, False)
        print(a)
        a.calc = asap3.EMT()
        MaxwellBoltzmannDistribution(a, 300 * kB, force_temp=True)
        Stationary(a)
        assert abs(a.get_temperature() - 300) < 0.0001
        print(a.get_forces())
        md = VelocityVerlet(a, timestep=2 * fs, logfile='-', loginterval=500)
        traj = Trajectory('Au7Ag.traj', 'w', a)
        md.attach(traj.write, 100)
        e0 = a.get_total_energy()
        md.run(steps=10000)
        del traj
        assert abs(a.get_total_energy() - e0) < 0.0001
        assert abs(read('Au7Ag.traj').get_total_energy() - e0) < 0.0001
예제 #13
0
def md_run(origin_poscar_path, index):
    print('%d' % index + ' In directory : %s' % origin_poscar_path)
    atoms = read(origin_poscar_path)

    calc = ANNCalculator(potentials={
        "Ga": "Ga.10t-10t.nn",
        "N": "N.10t-10t.nn"
    })
    atoms.set_calculator(calc)

    MaxwellBoltzmannDistribution(atoms, 1200 * kB)
    Stationary(atoms)

    md = NVT(atoms, timestep=2 * fs, temperature=1000 * kB, friction=0.05)
    logger = MDLogger(md, atoms, '-', stress=True)
    md.attach(logger, interval=1)
    traj = Trajectory(
        "nvt_%s.traj" % (origin_poscar_path.split('/')[-1].split('.xsf')[0]),
        "w", atoms)
    md.attach(traj.write, interval=200)

    md.run(40000)
예제 #14
0
def init_vel(cml):
    '''
    '''
    arg = parse_cml_args(cml)

    # read in the initial structure
    init_pos = read(arg.poscar)

    # set the momenta corresponding to T
    MaxwellBoltzmannDistribution(init_pos,
                                 temperature_K=arg.temperature,
                                 force_temp=True)
    # set the center-of-mass to 0
    Stationary(init_pos)
    # set the total angular momentum to 0
    ZeroRotation(init_pos)

    ################################################################################
    # No need to do this, use "force_temp" parameter in MaxwellBoltzmannDistribution
    ################################################################################

    # scale the temperature to T
    # vel = init_pos.get_velocities()
    # Tn = init_pos.get_temperature()
    # vel *= np.sqrt(arg.temperature / Tn)
    # init_pos.set_velocities(vel)

    # write the structure
    write(arg.out, init_pos, vasp5=True, direct=True)

    # units in VASP and ASE are different
    vel = init_pos.get_velocities() * ase.units.fs
    # np.savetxt('init_vel.dat', vel, fmt='%20.16f')
    # append the velocities to the POSCAR
    with open(arg.out, 'a+') as pos:
        pos.write('\n')
        pos.write('\n'.join(
            [''.join(["%20.16f" % x for x in row]) for row in vel]))
예제 #15
0
파일: test.py 프로젝트: casv2/TF
def MD():
    old_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()

    orig_stdout = sys.stdout
    f = open('out.txt', 'w')
    sys.stdout = f

    #f = open('out_' + str(temp) + '.txt', 'w')
    #sys.stdout = f
    Tmin = 1000
    Tmax = 15000

    a0 = 5.43
    N = 1
    atoms = Diamond(symbol='Si', latticeconstant=a0)
    atoms *= (N, N, N)
    atoms.set_calculator(model.calculator)
    MaxwellBoltzmannDistribution(atoms, Tmin * units.kB)  ###is this allowed?
    Stationary(atoms)  # zero linear momentum
    ZeroRotation(atoms)

    def printenergy(a=atoms):
        epot = a.get_potential_energy() / len(a)
        ekin = a.get_kinetic_energy() / len(a)
        print(ekin)

    traj = Trajectory('Si.traj', 'w', atoms)

    for temp in np.linspace(Tmin, Tmax, 5):
        dyn = Langevin(atoms, 5 * units.fs, units.kB * temp, 0.002)
        dyn.attach(traj.write, interval=1)
        dyn.attach(printenergy, interval=1)
        dyn.run(100)

    sys.stdout = orig_stdout
    f.close()
예제 #16
0
def test_langevin_asap(asap3):
    with seterr(all='raise'):
        rng = np.random.RandomState(0)
        a = bulk('Au', cubic=True).repeat((4, 4, 4))
        a.pbc = (False, False, False)
        a.center(vacuum=2.0)
        print(a)
        a.calc = asap3.EMT()
        # Set temperature to 10 K
        MaxwellBoltzmannDistribution(a,
                                     temperature_K=10,
                                     force_temp=True,
                                     rng=rng)
        Stationary(a)
        assert abs(a.get_temperature() - 10) < 0.0001
        # Langevin dynamics should raise this to 300 K
        T = 300
        md = Langevin(a,
                      timestep=4 * fs,
                      temperature_K=T,
                      friction=0.01,
                      logfile='-',
                      loginterval=500,
                      rng=rng)
        md.run(steps=3000)
        # Now gather the temperature over 10000 timesteps, collecting it
        # every 5 steps
        temp = []
        for i in range(1500):
            md.run(steps=5)
            temp.append(a.get_temperature())
        temp = np.array(temp)
        avgtemp = np.mean(temp)
        fluct = np.std(temp)
        print("Temperature is {:.2f} K +/- {:.2f} K".format(avgtemp, fluct))
        assert abs(avgtemp - T) < 10.0
예제 #17
0
    def __init__(
        self,
        atomsbatch,
        mdparam=DEFAULTNVEPARAMS,
    ):

        # initialize the atoms batch system
        self.atomsbatch = atomsbatch
        self.mdparam = mdparam

        # todo: structure optimization before starting

        # intialize system momentum
        MaxwellBoltzmannDistribution(self.atomsbatch,
                                     self.mdparam['T_init'] * units.kB)
        Stationary(self.atomsbatch)  # zero linear momentum
        ZeroRotation(self.atomsbatch)

        # set thermostats
        integrator = self.mdparam['thermostat']

        self.integrator = integrator(self.atomsbatch,
                                     **self.mdparam['thermostat_params'])

        # attach trajectory dump
        self.traj = Trajectory(self.mdparam['traj_filename'], 'w',
                               self.atomsbatch)
        self.integrator.attach(self.traj.write,
                               interval=self.mdparam['save_frequency'])

        # attach log file
        self.integrator.attach(NeuralMDLogger(self.integrator,
                                              self.atomsbatch,
                                              self.mdparam['thermo_filename'],
                                              mode='a'),
                               interval=self.mdparam['save_frequency'])
예제 #18
0
def thermalize(temp, atoms, rng):
    MaxwellBoltzmannDistribution(atoms,
                                 temperature_K=temp,
                                 force_temp=True,
                                 rng=rng)
    Stationary(atoms)
예제 #19
0
def stationary_atoms(atoms):
    atoms = atoms.copy()
    Stationary(atoms)
    return atoms
예제 #20
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
예제 #21
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
예제 #22
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
예제 #23
0
# Set up a nanoparticle
atoms = FaceCenteredCubic('Cu',
                          surfaces=[[1, 0, 0], [1, 1, 0], [1, 1, 1]],
                          layers=(size, size, size),
                          vacuum=4)

# 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))
예제 #24
0
def test_otf_md(md_engine, super_cell, flare_calc, qe_calc):
    np.random.seed(12345)

    flare_calculator = flare_calc[md_engine]
    # set up OTF MD engine
    md_params = {
        'timestep': 1 * units.fs,
        'trajectory': None,
        'dt': 1 * units.fs,
        'externalstress': 0,
        'ttime': 25,
        'pfactor': 3375,
        'mask': None,
        'temperature': 500,
        'taut': 1,
        'taup': 1,
        'pressure': 0,
        'compressibility': 0,
        'fixcm': 1,
        'friction': 0.02
    }

    otf_params = {
        'dft_calc': qe_calc,
        'init_atoms': [0, 1, 2, 3],
        'std_tolerance_factor': 2,
        'max_atoms_added': len(super_cell.positions),
        'freeze_hyps': 10,
        'use_mapping': flare_calculator.use_mapping
    }

    # intialize velocity
    temperature = md_params['temperature']
    MaxwellBoltzmannDistribution(super_cell, temperature * units.kB)
    Stationary(super_cell)  # zero linear momentum
    ZeroRotation(super_cell)  # zero angular momentum

    super_cell.set_calculator(flare_calculator)
    test_otf = otf_md(md_engine, super_cell, md_params, otf_params)

    # set up logger
    otf_logger = OTFLogger(test_otf,
                           super_cell,
                           logfile=md_engine + '.log',
                           mode="w",
                           data_in_logfile=True)
    test_otf.attach(otf_logger, interval=1)

    # run otf
    number_of_steps = 3
    test_otf.otf_run(number_of_steps)

    for f in glob.glob("scf.pw*"):
        os.remove(f)
    for f in glob.glob("*.npy"):
        os.remove(f)
    for f in glob.glob("kv3*"):
        shutil.rmtree(f)

    for f in os.listdir("./"):
        if f in [f'{md_engine}.log', 'lmp.mgp']:
            os.remove(f)
        if f in ['out', 'otf_data']:
            shutil.rmtree(f)
예제 #25
0
파일: al.py 프로젝트: nw13slx/flare-RC
#input_data = dft_input['input_data']
#dft_calc = Espresso(pseudopotentials=dft_input['pseudopotentials'], label=dft_input['label'],
#                tstress=True, tprnfor=True, nosym=True,
#                input_data=input_data, kpts=dft_input['kpts'])

# -------------- set up otf npt md --------------------
timestep = 1  # fs
temperature = 100
externalstress = 0
ttime = 25
pfactor = 3375
logfile = 'al.log'

# intialize velocity
MaxwellBoltzmannDistribution(super_cell, 200 * units.kB)
Stationary(super_cell)  # zero linear momentum
ZeroRotation(super_cell)  # zero angular momentum

test_otf_npt = OTF_NPT(
    super_cell,
    timestep,
    temperature,
    externalstress,
    ttime,
    pfactor,
    mask=None,
    # on-the-fly parameters
    dft_calc=dft_calc,
    std_tolerance_factor=1,
    max_atoms_added=nat,
    freeze_hyps=0,
예제 #26
0
 def __init__(self, mol, gl, path, i, Bi):
     self.geom_print = gl.full_geom_print
     self.printSMILES = False
     self.procNum = i
     self.gl = gl
     self.biMolecular = Bi
     self.method = gl.trajMethod
     self.level = gl.trajLevel
     self.mdSteps = gl.mdSteps
     self.printFreq = gl.printFreq
     self.mixedTimestep = gl.mixedTimestep
     if self.biMolecular:
         try:
             self.initialT = gl.BiTemp
         except:
             print("No specific bimolecular temperature set, using the Langevin temperature instead")
             self.initialT = gl.LTemp
     else:
         self.initialT = gl.LTemp
     self.MDIntegrator =gl.MDIntegrator
     self.timeStep = gl.timeStep * units.fs
     self.eneBXD = gl.eneBXD
     self.comBXD = gl.comBXD
     try:
         self.minCOM = gl.minCOM
     except:
         self.minCOM = 3.0
     try:
         self.fragIdx = gl.fragIndices
     except:
         self.fragIdx = 0
     self.forces = np.zeros(mol.get_positions().shape)
     self.LangFric = gl.LFric
     self.LangTemp = self.initialT
     self.Mol = Atoms(symbols=mol.get_chemical_symbols(), positions = mol.get_positions())
     MaxwellBoltzmannDistribution(self.Mol, self.initialT * units.kB, force_temp=True)
     Stationary(self.Mol)
     ZeroRotation(self.Mol)
     self.velocity = self.Mol.get_velocities()
     print('initialising velocities for process ' + str(i) + '\n')
     print(str(self.velocity) + '\n')
     self.tempReactGeom = mol.copy()
     self.tempProdGeom = mol.copy()
     self.NEBguess = []
     self.TSgeom = mol.copy()
     self.productGeom = self.Mol.get_positions()
     try:
         self.window = gl.reactionWindow
         self.endOnReac = gl.endOnReaction
         self.consistantWindow = gl.reactionWindow
     except:
         pass
     if self.biMolecular:
         self.consistantWindow = int(gl.reactionWindow /4)
     self.savePath = path
     self.ReactionCountDown = 0
     self.MolList = []
     self.KeepTracking = True
     self.tempList = [1000]
     self.transindex = np.zeros(3)
     self.numberOfSteps = 0
     self.AssDisoc = False
     self.TSpoint = 0
     self.names=[]
     self.changePoints=[]
     self.adaptiveSteps = gl.maxAdapSteps