def __call__(self): """ Writes trajectory file for current atoms list. """ from ase import PickleTrajectory traj = PickleTrajectory('%s_it%i.trj' % (self.name, self.i), 'w') for image in self.images: traj.write(image) self.i += 1
def __call__(self): """ Writes trajectory file for current atoms list. """ from ase import PickleTrajectory traj = PickleTrajectory('%s_it%i.trj' %(self.name,self.i), 'w') for image in self.images: traj.write(image) self.i+=1
def calculate_from_trajectory(self, traj, startatom=None, selector=None): """Calculate the center of mass for a cluster in a trajectory file. traj: The trajectory object, or a file name. startatom (optional): Specifies an atom guaranteed to be in the cluster. If not specified, the atom with the highest coordination number is used (if there is only one cluster this should work). selector (optional): A function defining which atoms should be considered. The function is called with one argument, the atoms object, and should either return an array of booleans, one per atom, indicating if they should be included, or return an array of integers interpreted as the indices of the atoms to be included. This can e.g. be used to select a cluster sitting on a substrate. This method returns an array of center-of-mass positions, one for each frame in the trajectory. """ if isinstance(traj, str): if traj.endswith('.traj'): traj = PickleTrajectory(traj) elif traj.endswith('.bundle'): traj = BundleTrajectory(traj) else: raise ValueError("Cannot handle a file name not ending in .traj or .bundle: " + traj) result = [] for atoms in traj: if selector is not None: idx = selector(atoms) atoms = atoms[idx] result.append(self.calculate_center(atoms, startatom)) return result
class ExtendedTrajectory: def __init__(self,filename,atoms,n,mode='w',fixrcm=False): """ Trajectory for multiple copies of unit cell. parameters: =========== filename: output .traj -file atoms: hotbit.Atoms object n: tuple of number of symmetry operations or list of tuples for the symmetry operations mode: 'w' write or 'a' append fixrcm: Write trajectory with center of mass fixed at origin. """ self.atoms = atoms self.n = n self.ext = self.atoms.extended_copy(n) self.traj = PickleTrajectory(filename,mode,self.ext) #,properties=['energy']) self.fixrcm = fixrcm def set_atoms(self,atoms): self.atoms = atoms self.ext = self.atoms.extended_copy(self.n) self.traj.set_atoms(self.ext) def write(self): cp = self.atoms.extended_copy(self.n) if self.fixrcm: cp.translate( -cp.get_center_of_mass() ) self.ext.set_positions( cp.get_positions() ) self.traj.write()
def trajToExtTraj(traj, n, *args): R, T, angle1, angle2, n1, n2, path = args path_traj = path + 'sphere/md_data/T=%.0f/' %T checkAndCreateFolder(path_traj) traj_ext = PickleTrajectory(path_traj + 'md_Ext_R%.3f.traj' %R, 'w') for a in traj: c_symb = a.get_chemical_symbols() posits = a.positions atoms = Atoms(c_symb, positions = posits, container='Sphere') atoms.set_container(angle1=angle1,angle2=angle2,n1=n1,n2=n2,mode=4) traj_ext.write(atoms.extended_copy(n))
def trajToExtTraj(traj, n, *args): R, T, angle, H, path = args path_traj = path + 'cylinder/md_data/T=%.0f/' %T checkAndCreateFolder(path_traj) traj_ext = PickleTrajectory(path_traj + 'md_Ext_R%.3f.traj' %R,'w') for a in traj: c_symb = a.get_chemical_symbols() posits = a.positions atoms = Atoms(c_symb, positions = posits, container='Wedge') atoms.set_container(angle=angle, height=H, physical=False, pbcz=True) traj_ext.write(atoms.extended_copy(n))
def microcanonical(atoms, dt=1.0, steps=100, output=1, name=None, verbose=False): """ Perform little microcanonical simulation. parameters: ----------- atoms: dt: time step in fs steps: how many md steps output: output frequency name: TrajectoryRecording name verbose: increase verbosity Return TrajectoryRecording object for further analysis. """ if name == None: try: name = atoms.get_chemical_formula(mode="hill") except: name = 'microcanonical' name += '.trj' traj = PickleTrajectory(name, 'w', atoms) rec = TrajectoryRecording(atoms, verbose) md = VelocityVerlet(atoms, dt * fs) md.attach(rec, interval=output) md.attach(traj.write, interval=output) md.run(steps) return rec
def __init__(self,filename,atoms,n,mode='w',fixrcm=False): """ Trajectory for multiple copies of unit cell. parameters: =========== filename: output .traj -file atoms: hotbit.Atoms object n: tuple of number of symmetry operations or list of tuples for the symmetry operations mode: 'w' write or 'a' append fixrcm: Write trajectory with center of mass fixed at origin. """ self.atoms = atoms self.n = n self.ext = self.atoms.extended_copy(n) self.traj = PickleTrajectory(filename,mode,self.ext) #,properties=['energy']) self.fixrcm = fixrcm
class ExtendedTrajectory: def __init__(self,filename,atoms,n,mode='w'): """ Trajectory for multiple copies of unit cell. parameters: =========== filename: output .traj -file atoms: hotbit.Atoms object n: tuple of number of symmetry operations or list of tuples for the symmetry operations mode: 'w' write or 'a' append """ self.atoms = atoms self.n = n self.ext = self.atoms.extended_copy(n) self.traj = PickleTrajectory(filename,mode,self.ext) def write(self): cp = self.atoms.extended_copy(self.n) self.ext.set_positions( cp.get_positions() ) self.traj.write()
def run_neb_calculation(cpu): images = [PickleTrajectory('H.traj')[-1]] for i in range(nimages): images.append(images[0].copy()) images[-1].positions[6, 1] = 2 - images[0].positions[6, 1] neb = NEB(images, parallel=True, world=cpu) neb.interpolate() images[cpu.rank + 1].set_calculator(MorsePotential()) dyn = BFGS(neb) dyn.run(fmax=fmax) if cpu.rank == 1: results.append(images[2].get_potential_energy())
def cylinderDynamics(R, T, params): nk = params['nk'] #20 fmax = params['fmax'] #1E-2 fric = params['fric'] #0.002 dt = params['dt'] #5.0 mdsteps = params['mdsteps'] #int(10/fric/dt) path = params['path'] #'/space/tohekorh/Au_bend/files/' print 'radius',R, '\n' name = '%.1f' %R # Get the optimal flat atoms , unit-cell config for this temperature: atoms = get_opmAtomsFlat(T, params) # Take the diagonal of the cell: L = atoms.get_cell().diagonal() atoms.set_cell(L) # The wedge angle is: angle = L[1]/R # fiddle with atoms: atoms.rotate('y', np.pi/2) atoms.translate((-atoms[0].x, 0, 0) ) #view(atoms) # Initial map for atoms, to get the on surface of cylinder: phi_max = angle for a in atoms: r0 = a.position phi = r0[1]/L[1]*phi_max a.position[0] = R*np.cos(phi) a.position[1] = R*np.sin(phi) #view(atoms) # proper number of kappa points in angle direction, if angle >= 2*pi/3 the use genuine # physical boundary conditions and proper kappa-points. With 64 atoms in unit cell souhld not # happen as the radius -> very small if angle = 2*pi/3 or larger. # Check that the unit-cell angle is 2*pi/integer. This can be removed! if (2*np.pi/angle)%1 > 0: raise # This does not have any effect unless angle >= 2*pi/3: m = int(round(2*np.pi/angle)) physical = False if m <= 3: nk1 = m physical = True else: nk1 = nk # Set up the wedge container: atoms = Atoms(atoms = atoms, container = 'Wedge') atoms.set_container(angle = angle, height = L[0], physical = physical, pbcz = True) # Check that everything looks good: #view(atoms.extended_copy((2,1,2))) # FOLDERS path_opm = path + 'cylinder/opm/T=%.0f/' %T path_md = path + 'cylinder/md_data/T=%.0f/' %T checkAndCreateFolder(path_opm) checkAndCreateFolder(path_md) # CALCULATOR calc = Hotbit(SCC=False, kpts=(nk1, 1, nk), physical_k = physical, \ txt= path_opm + 'optimization_%s.cal' %name) atoms.set_calculator(calc) # RELAX opt = BFGS(atoms, trajectory= path_opm + 'optimization_%s.traj' %name) opt.run(fmax=fmax, steps=1000) # DYNAMICS traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R,'w',atoms) # Perform dynamics dyn = Langevin(atoms, dt*units.fs, units.kB*T, fric) dyn.attach(MDLogger(dyn, atoms, path_md + 'md_R%.3f.log' %R, header=True, stress=False, peratom=True, mode="w"), interval = 1) dyn.attach(traj.write) dyn.run(mdsteps) traj.close() # load the dynamics back, to make exteded trajectory: traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R) trajToExtTraj(traj, (2, 1, 2), R, T, angle, L[0], path)
plt.xlabel("DOS", fontsize=18) plt.savefig('Al_phonon.png') # Write modes for specific q-vector to trajectory files ph.write_modes([l / 2 for l in L], branches=[2], repeat=(8, 8, 8), kT=3e-4, center=True) # Generate png animation from subprocess import call from ase.io import PickleTrajectory, write trajfile = 'phonon.mode.2.traj' trajectory = PickleTrajectory(trajfile, 'r') for i, atoms in enumerate(trajectory): write('picture%02i.png' % i, atoms, show_unit_cell=2, rotation='-36x,26.5y,-25z') # Flatten images for better quality call(['convert', '-flatten', 'picture%02i.png' % i, 'picture%02i.png' % i]) # Make static pdf image for pdflatex call(['convert', 'picture00.png', 'Al_mode.pdf']) # Concatenate to gif animation call([ 'convert', '-delay', '5', '-loop', '0', '-dispose', 'Previous',
def sphereDynamics(R, T, params): d = params['d'] #2.934 nk = params['nk'] #20 fmax = params['fmax'] #1E-2 fric = params['fric'] #0.002 # equilibration time tau = 10 fs/fric (= mdsteps*dt) dt = params['dt'] #5.0 mdsteps = params['mdsteps'] #int(10/fric/dt) path = params['path'] #'/space/tohekorh/Au_bend/files/' uzsize = params['uz_size'] print 'radius',R name = '%.1f' %R # ATOMS #atoms = fcc111('Au',size=uzsize,a=np.sqrt(2)*d) atoms = get_opmAtomsFlat(T, params) atoms.rotate((0,0,1), -np.pi/6, rotate_cell = True) length1 = np.linalg.norm( atoms.get_cell()[0] ) length2 = np.linalg.norm( atoms.get_cell()[1] ) n1 = ( np.cos(np.pi/3), np.sin(np.pi/3), 0) n2 = (-np.cos(np.pi/3), np.sin(np.pi/3), 0) angle1 = length1/R angle2 = length2/R #view(atoms) # Scale the atoms close to ball Lx = np.linalg.norm(atoms.get_cell()[0] + atoms.get_cell()[1]) Ly = np.linalg.norm(atoms.get_cell()[0] - atoms.get_cell()[1]) phi_max = Ly/R theta_max = Lx/R for a in atoms: r0 = a.position phi = r0[1]/Ly*phi_max theta = r0[0]/Lx*theta_max a.position[0] = R*np.sin(theta) #*np.sin(theta) a.position[1] = R*np.sin(phi) #a.position[1] #R*np.sin(phi) #*np.sin(theta) a.position[2] = R*np.cos(theta) #atoms.translate((0,0,R)) # End scaling atoms = Atoms(atoms=atoms,container='Sphere') atoms.set_container(angle1=angle1,angle2=angle2,n1=n1,n2=n2,mode=4) #view(atoms.extended_copy((2,2,1))) # FOLDERS path_md = path + 'sphere/md_data/T=%.0f/' %T path_opm= path + 'sphere/opm/T=%.0f/' %T checkAndCreateFolder(path_md) checkAndCreateFolder(path_opm) # CALCULATOR calc = Hotbit(SCC=False, kpts=(nk,nk,1),txt= path_opm + 'optimization_%s.cal' %name,) atoms.set_calculator(calc) # RELAX opt = BFGS(atoms, trajectory= path_opm + 'optimization_%s.traj' %name) opt.run(fmax=fmax,steps=1000) #write(path_opm + 'opm_structure_R%.3f' %R, atoms, format='traj') # DYNAMICS traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R, 'w', atoms) dyn = Langevin(atoms, dt*units.fs, units.kB*T,fric) dyn.attach(MDLogger(dyn, atoms, path_md + 'md_R%.3f.log' %R, header=True, stress=False, peratom=True, mode="w"), interval = 1) dyn.attach(traj.write) dyn.run(mdsteps) traj.close() # load the dynamics back.. To write the extended trajectory traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R) trajToExtTraj(traj, (2, 2, 1), R, T, angle1, angle2, n1, n2, path)
import numpy as np from math import pi, sqrt from ase import Atoms from ase.calculators.lj import LennardJones from ase.optimize.basin import BasinHopping from ase.io import PickleTrajectory, read from ase.units import kB N = 7 R = N**(1. / 3.) pos = np.random.uniform(-R, R, (N, 3)) s = Atoms('He' + str(N), positions=pos) s.set_calculator(LennardJones()) ftraj = 'lowest.traj' traj = PickleTrajectory(ftraj, 'w', s) bh = BasinHopping(s, temperature=100 * kB, dr=0.5, optimizer_logfile=None) bh.attach(traj) bh.run(10) Emin, smin = bh.get_minimum() # recalc energy smin.set_calculator(LennardJones()) E = smin.get_potential_energy() assert abs(E - Emin) < 1e-15 traj.close() smim = read(ftraj) E = smin.get_potential_energy() assert abs(E - Emin) < 1e-15
from ase import Atoms from ase.calculators.emt import EMT from ase.md import VelocityVerlet from ase.io import PickleTrajectory a = 3.6 b = a / 2 fcc = Atoms('Cu', positions=[(0, 0, 0)], cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) fcc *= (2, 1, 1) fcc.set_calculator(EMT()) fcc.set_momenta([(0.9, 0.0, 0.0), (-0.9, 0, 0)]) md = VelocityVerlet(fcc, dt=0.1) def f(): print fcc.get_potential_energy(), fcc.get_total_energy() md.attach(f) md.attach(PickleTrajectory('Cu2.traj', 'w', fcc).write, interval=3) md.run(steps=20) fcc2 = PickleTrajectory('Cu2.traj', 'r')[-1]
return int(self.value - other.value) if __name__ == '__main__': import info # import ourselves to make info.Foo reachable # Create a molecule with an info attribute info = dict(creation_date='2011-06-27', chemical_name='Hydrogen', # custom classes also works provided that it is # imported and pickleable... foo=info.Foo(7), ) molecule = Atoms('H2', positions=[(0., 0., 0.), (0., 0., 1.1)], info=info) assert molecule.info == info # Copy molecule atoms = molecule.copy() assert atoms.info == info # Save molecule to trajectory traj = PickleTrajectory('info.traj', 'w', atoms=molecule) traj.write() del traj # Load molecule from trajectory t = PickleTrajectory('info.traj') atoms = t[-1] assert atoms.info == info
atoms.get_potential_energy = calc.get_potential_energy atoms.get_forces = calc.notimpl atoms.get_stress = calc.notimpl atoms.get_charges = calc.notimpl # get total energy at first ionic step en = get_total_energy(s) if en is not None: calc.set_energy(en) else: print >>stderr, 'no total energy found' exit(3) print(atoms) traj = PickleTrajectory(argv[2], 'w') traj.write(atoms) a = s.readline() while a != '': while a[:7] != 'CELL_PA' and a[:7] != 'ATOMIC_' and a != '': a = s.readline() if a == '': break if a[0] == 'A': coord = a.split('(')[-1] for i in range(natoms): pos[i][:] = s.readline().split()[1:4]
return int(self.value - other.value) if __name__ == '__main__': import info # import ourselves to make info.Foo reachable # Create a molecule with an info attribute info = dict( creation_date='2011-06-27', chemical_name='Hydrogen', # custom classes also works provided that it is # imported and pickleable... foo=info.Foo(7), ) molecule = Atoms('H2', positions=[(0., 0., 0.), (0., 0., 1.1)], info=info) assert molecule.info == info # Copy molecule atoms = molecule.copy() assert atoms.info == info # Save molecule to trajectory traj = PickleTrajectory('info.traj', 'w', atoms=molecule) traj.write() del traj # Load molecule from trajectory t = PickleTrajectory('info.traj') atoms = t[-1] assert atoms.info == info
import numpy as np from ase.lattice import bulk from ase.optimize import BFGS from ase.io import PickleTrajectory from ase.constraints import StrainFilter from gpaw import GPAW, PW co = bulk('Co') co.set_initial_magnetic_moments([1.6, 1.6]) co.calc = GPAW(mode=PW(700), xc='PBE', kpts=(8, 8, 4), txt='co.txt') BFGS(StrainFilter(co)).run(0.005) a0 = co.cell[0, 0] c0 = co.cell[2, 2] traj = PickleTrajectory('co.traj', 'w') eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 3): for c in c0 * np.linspace(1 - eps, 1 + eps, 3): co.set_cell(bulk('Co', a=a, covera=c / a).cell, scale_atoms=True) co.get_potential_energy() traj.write(co)
import numpy as np from ase import Atoms from ase.units import fs from ase.calculators.test import TestPotential from ase.calculators.emt import EMT from ase.md import VelocityVerlet from ase.io import PickleTrajectory, read from ase.optimize import QuasiNewton np.seterr(all='raise') a = Atoms('4X', masses=[1, 2, 3, 4], positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0.1, 0.2, 0.7)], calculator=TestPotential()) print a.get_forces() md = VelocityVerlet(a, dt=0.5 * fs, logfile='-', loginterval=500) traj = PickleTrajectory('4N.traj', 'w', a) md.attach(traj.write, 100) e0 = a.get_total_energy() md.run(steps=10000) del traj assert abs(read('4N.traj').get_total_energy() - e0) < 0.0001 qn = QuasiNewton(a) qn.run(0.001) assert abs(a.get_potential_energy() - 1.0) < 0.000002
from math import pi, sqrt from ase import Atoms from ase.calculators.lj import LennardJones from ase.optimize.basin import BasinHopping from ase.io import PickleTrajectory, read from ase.units import kB N = 7 R = N**(1./3.) pos = np.random.uniform(-R, R, (N, 3)) s = Atoms('He' + str(N), positions = pos) s.set_calculator(LennardJones()) ftraj = 'lowest.traj' traj = PickleTrajectory(ftraj, 'w', s) bh = BasinHopping(s, temperature=100 * kB, dr=0.5, optimizer_logfile=None) bh.attach(traj) bh.run(10) Emin, smin = bh.get_minimum() # recalc energy smin.set_calculator(LennardJones()) E = smin.get_potential_energy() assert abs(E - Emin) < 1e-15 traj.close() smim = read(ftraj) E = smin.get_potential_energy()
import sys from ase.test import NotAvailable if sys.platform in ['win32']: raise NotAvailable('Fails on Windows https://trac.fysik.dtu.dk/projects/ase/ticket/62') import os from ase import Atom, Atoms from ase.io import PickleTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))]) traj = PickleTrajectory('1.traj', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj traj = PickleTrajectory('1.traj', 'a') co = traj[-1] print co.positions co.positions[:] += 1 traj.write(co) del traj t = PickleTrajectory('1.traj', 'a') print t[-1].positions print '.--------' for a in t: print 1, a.positions[-1,2] co.positions[:] += 1 t.write(co)
import numpy as np from ase.lattice import bulk from ase.optimize import BFGS from ase.io import PickleTrajectory from ase.constraints import StrainFilter from gpaw import GPAW, PW co = bulk("Co") co.set_initial_magnetic_moments([1.6, 1.6]) co.calc = GPAW(mode=PW(700), xc="PBE", kpts=(8, 8, 4), txt="co.txt") BFGS(StrainFilter(co)).run(0.005) a0 = co.cell[0, 0] c0 = co.cell[2, 2] traj = PickleTrajectory("co.traj", "w") eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 3): for c in c0 * np.linspace(1 - eps, 1 + eps, 3): co.set_cell(bulk("Co", a=a, covera=c / a).cell, scale_atoms=True) co.get_potential_energy() traj.write(co)
image.constraints.append(constraint) # Displace last image: for i in xrange(1, 8, 1): images[-1].positions[-i] += (d / 2, -h1 / 3, 0) write('initial.traj', images[0]) # Relax height of Ag atom for initial and final states: for image in [images[0], images[-1]]: QuasiNewton(image).run(fmax=0.01) if 0: write('initial.pckl', image[0]) write('finial.pckl', image[-1]) # Interpolate positions between initial and final states: neb.interpolate() for image in images: print image.positions[-1], image.get_potential_energy() traj = PickleTrajectory('mep.traj', 'w') dyn = FIRE(neb, dt=0.1) #dyn = MDMin(neb, dt=0.1) #dyn = QuasiNewton(neb) dyn.attach(neb.writer(traj)) dyn.run(fmax=0.01, steps=150) for image in images: print image.positions[-1], image.get_potential_energy()
import numpy as np from ase import Atoms from ase.calculators.emt import EMT from ase.io import PickleTrajectory Cu = Atoms('Cu', pbc=(1, 0, 0), calculator=EMT()) traj = PickleTrajectory('Cu.traj', 'w') for a in np.linspace(2.0, 4.0, 20): Cu.set_cell([a, 1, 1], scale_atoms=True) traj.write(Cu)
import threading from ase.test import World from ase.io import PickleTrajectory from ase.neb import NEB from ase.calculators.morse import MorsePotential from ase.optimize import BFGS fmax = 0.05 nimages = 3 print [a.get_potential_energy() for a in PickleTrajectory('H.traj')] images = [PickleTrajectory('H.traj')[-1]] for i in range(nimages): images.append(images[0].copy()) images[-1].positions[6, 1] = 2 - images[0].positions[6, 1] neb = NEB(images) neb.interpolate() for image in images[1:]: image.set_calculator(MorsePotential()) dyn = BFGS(neb, trajectory='mep.traj') dyn.run(fmax=fmax) for a in neb.images: print a.positions[-1], a.get_potential_energy() results = [images[2].get_potential_energy()]
N = len(initial) # number of atoms # Make a mask of zeros and ones that select fixed atoms - the two # bottom layers: mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h constraint = FixAtoms(mask=mask) initial.set_constraint(constraint) # Calculate using EMT: initial.set_calculator(EMT()) # Relax the initial state: QuasiNewton(initial).run(fmax=0.05) e0 = initial.get_potential_energy() traj = PickleTrajectory('dimer_along.traj', 'w', initial) traj.write() # Making dimer mask list: d_mask = [False] * (N - 1) + [True] # Set up the dimer: d_control = DimerControl(initial_eigenmode_method='displacement', displacement_method='vector', logfile=None, mask=d_mask) d_atoms = MinModeAtoms(initial, d_control) # Displacement settings: displacement_vector = np.zeros((N, 3)) # Strength of displacement along y axis = along row:
from ase.constraints import StrainFilter, UnitCellFilter from ase.io import PickleTrajectory from ase.optimize.lbfgs import LBFGS from ase.optimize.mdmin import MDMin try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = PickleTrajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.lattice.surface import hcp0001 cu = hcp0001('Cu', (1, 1, 2), a=a / sqrt(2)) cu.cell[1, 0] += 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) print cu.get_forces() print cu.get_stress() f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = PickleTrajectory('Cu-hcp.traj', 'w', cu) opt.attach(t)
from ase import Atoms from ase.calculators.emt import EMT from ase.constraints import FixBondLength from ase.io import PickleTrajectory from ase.optimize import BFGS a = 3.6 b = a / 2 cu = Atoms('Cu2Ag', positions=[(0, 0, 0), (b, b, 0), (a, a, b)], calculator=EMT()) e0 = cu.get_potential_energy() print e0 d0 = cu.get_distance(0, 1) cu.set_constraint(FixBondLength(0, 1)) t = PickleTrajectory('cu2ag.traj', 'w', cu) qn = BFGS(cu) qn.attach(t.write) def f(): print cu.get_distance(0, 1) qn.attach(f) qn.run(fmax=0.01) assert abs(cu.get_distance(0, 1) - d0) < 1e-14
try: import scipy except ImportError: from ase.test import NotAvailable raise NotAvailable('This test needs scipy module.') import numpy as np from ase.io import read, PickleTrajectory from ase.lattice import bulk from ase.calculators.emt import EMT a0 = 3.52 / np.sqrt(2) c0 = np.sqrt(8 / 3.0) * a0 print '%.4f %.3f' % (a0, c0 / a0) for i in range(3): traj = PickleTrajectory('Ni.traj', 'w') eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 4): for c in c0 * np.linspace(1 - eps, 1 + eps, 4): ni = bulk('Ni', 'hcp', a=a, covera=c / a) ni.set_calculator(EMT()) ni.get_potential_energy() traj.write(ni) configs = read('Ni.traj@:') energies = [config.get_potential_energy() for config in configs] ac = [(config.cell[0, 0], config.cell[2, 2]) for config in configs] from ase.optimize import polyfit p = polyfit(ac, energies) from scipy.optimize import fmin_bfgs a0, c0 = fmin_bfgs(p, (a0, c0))
Z = slab.get_positions()[:, 2] indices = [i for i, z in enumerate(Z) if z < Z.mean()] constraint = FixAtoms(indices=indices) slab.set_constraint(constraint) dyn = QuasiNewton(slab) dyn.run(fmax=0.05) Z = slab.get_positions()[:, 2] print Z[0] - Z[1] print Z[1] - Z[2] print Z[2] - Z[3] b = 1.2 h = 2.0 slab += Atom('C', (d, 2 * y / 3, h)) slab += Atom('O', (3 * d / 2, y / 3, h)) traj = PickleTrajectory('initial.traj', 'w', slab) dyn = QuasiNewton(slab) dyn.attach(traj.write) dyn.run(fmax=0.05) #view(slab) # Make band: images = [slab.copy() for i in range(6)] neb = NEB(images, climb=True) # Set constraints and calculator: for image in images: image.set_calculator(EMT()) image.set_constraint(constraint) # Displace last image: images[-1].positions[-1] = (2 * d, 2 * y / 3, h)
try: import scipy except ImportError: from ase.test import NotAvailable raise NotAvailable('This test needs scipy module.') import numpy as np from ase.io import read, PickleTrajectory from ase.lattice import bulk from ase.calculators.emt import EMT a0 = 3.52 / np.sqrt(2) c0 = np.sqrt(8 / 3.0) * a0 print '%.4f %.3f' % (a0, c0 / a0) for i in range(3): traj = PickleTrajectory('Ni.traj', 'w') eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 4): for c in c0 * np.linspace(1 - eps, 1 + eps, 4): ni = bulk('Ni', 'hcp', a=a, covera=c / a) ni.set_calculator(EMT()) ni.get_potential_energy() traj.write(ni) traj.close() configs = read('Ni.traj@:') energies = [config.get_potential_energy() for config in configs] ac = [(config.cell[0, 0], config.cell[2, 2]) for config in configs] from ase.optimize import polyfit p = polyfit(ac, energies, 2) from scipy.optimize import fmin_bfgs
from ase.constraints import StrainFilter from ase.optimize.mdmin import MDMin from ase.io import PickleTrajectory try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = StrainFilter(cu, [1, 1, 1, 0, 0, 0]) opt = MDMin(f, dt=0.01) t = PickleTrajectory('Cu.traj', 'w', cu) opt.attach(t) opt.run(0.001) # HCP: from ase.lattice.surface import hcp0001 cu = hcp0001('Cu', (1, 1, 2), a=a / sqrt(2)) cu.cell[1, 0] += 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) f = StrainFilter(cu) opt = MDMin(f, dt=0.01) t = PickleTrajectory('Cu.traj', 'w', cu) opt.attach(t) opt.run(0.01)
import os from ase import Atom, Atoms from ase.io import PickleTrajectory co = Atoms([Atom('C', (0, 0, 0)), Atom('O', (0, 0, 1.2))]) traj = PickleTrajectory('1.traj', 'w', co) for i in range(5): co.positions[:, 2] += 0.1 traj.write() del traj traj = PickleTrajectory('1.traj', 'a') co = traj[-1] print co.positions co.positions[:] += 1 traj.write(co) del traj t = PickleTrajectory('1.traj', 'a') print t[-1].positions print '.--------' for a in t: print 1, a.positions[-1,2] co.positions[:] += 1 t.write(co) for a in t: print 2, a.positions[-1,2] assert len(t) == 7 co[0].number = 1 try: t.write(co)
ranks = range(i * n, (i + 1) * n) image = initial.copy() if rank in ranks: calc = GPAW(h=0.3, kpts=(2, 2, 1), txt='neb%d.txt' % j, communicator=ranks) image.set_calculator(calc) image.set_constraint(constraint) images.append(image) images.append(final) neb = NEB(images, parallel=True) neb.interpolate() qn = BFGS(neb, logfile='qn.log') traj = PickleTrajectory('neb%d.traj' % j, 'w', images[j], master=(rank % n == 0)) qn.attach(traj) qn.run(fmax=0.05)