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
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 __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 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 __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
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()
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',
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)
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))
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)
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 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]
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]
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
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()]
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)
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 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)
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:
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
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
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)