energies = [] print OPTIONS cr = 0.15 fe = 1.0 - cr for opt in OPTIONS: a0 = 3.554 * opt / np.sqrt(2) # c0 = np.sqrt(8 / 3.0) * a0 c0 = 1.585 * a0 atoms = Atoms('Fe4', scaled_positions=[(0, 0, 0), (1. / 3., 1. / 3., 1. / 4.), (0, 0, 2. / 4.), (2. / 3., 2. / 3., 3. / 4.)], cell=[[1. / 2. * a0, sqrt(3) / 2. * a0, 0], [-1. / 2. * a0, sqrt(3) / 2. * a0, 0], [0, 0, 2.0 * c0]], pbc=(1, 1, 1)) # atoms.set_cell([[1/2, sqrt(3)/2, 0],[-1/2, sqrt(3)/2, 0] ,[0,0,1]]) print atoms.get_cell() print atoms.positions atoms.set_tags([1, 1, 1, 1]) alloys = [] alloys.append(Alloy(1, 'Fe', fe, 0.0)) alloys.append(Alloy(1, 'Cr', cr, 0.0))
import numpy as np from ase import Atoms from gpaw import GPAW, PW, FermiDirac from gpaw.mpi import world ecut = 200 kpoints = [1, 1, 4] atoms = Atoms('HLi', cell=[6, 6, 3.4], pbc=True, positions=[[3, 3, 0], [3, 3, 1.6]]) for xc in ['LDA', 'PBE']: def calculate(d, k): label = 'gpaw.{xc}.domain{d}.kpt{k}'.format(xc=xc, d=d, k=k) atoms.calc = GPAW(mode=PW(ecut), xc=xc, txt=label + '.txt', parallel={ 'domain': d, 'kpt': k }, kpts={'size': kpoints}, occupations=FermiDirac(width=0.1)) def stopcalc(): atoms.calc.scf.converged = True atoms.calc.attach(stopcalc, 4)
# creates: NaCl_C6H6.png import numpy as np from ase import Atoms from ase.io import write from ase.build import molecule a = 5.64 # Lattice constant for NaCl cell = [a / np.sqrt(2), a / np.sqrt(2), a] atoms = Atoms(symbols='Na2Cl2', pbc=True, cell=cell, scaled_positions=[(.0, .0, .0), (.5, .5, .5), (.5, .5, .0), (.0, .0, .5)]) * (3, 4, 2) + molecule('C6H6') # Move molecule to 3.5Ang from surface, and translate one unit cell in xy atoms.positions[-12:, 2] += atoms.positions[:-12, 2].max() + 3.5 atoms.positions[-12:, :2] += cell[:2] # Mark a single unit cell atoms.cell = cell # View used to start ag, and find desired viewing angle # view(atoms) rot = '35x,63y,36z' # found using ag: 'view -> rotate' # Common kwargs for eps, png, pov generic_projection_settings = { 'rotation': rot, # text string with rotation (default='' ) 'radii': .85, # float, or a list with one float per atom
elements = ['C'] results = [0.0168960169771] electrons = [6] lambda_coeff = 2.0 for symbol in elements: xcname = '1.0_LDA_K_TF+1.0_LDA_X' g = gen(symbol, xcname=xcname, scalarrel=False, orbital_free=True, tw_coeff=lambda_coeff) for element, result, e in zip(elements, results, electrons): atom = Atoms(element, positions=[(c, c, c)], cell=(a, a, a)) mixer = Mixer(0.3, 5, 1) eigensolver = CG(tw_coeff=lambda_coeff) calc = GPAW(h=h, txt='-', xc=xcname, maxiter=240, mixer=mixer, eigensolver=eigensolver) atom.set_calculator(calc) E = atom.get_total_energy() n = calc.get_all_electron_density()
from ase.ga.standard_comparators import InteratomicDistanceComparator from ase import Atoms from ase.calculators.singlepoint import SinglePointCalculator a1 = Atoms('AgAgAg', positions=[[0, 0, 0], [1.5, 0, 0], [1.5, 1.5, 0]]) a2 = Atoms('AgAgAg', positions=[[0, 0, 0], [1.4, 0, 0], [1.5, 1.5, 0]]) e1 = 1.0 e2 = 0.8 a1.set_calculator(SinglePointCalculator(e1, None, None, None, a1)) a2.set_calculator(SinglePointCalculator(e2, None, None, None, a2)) comp1 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.03, pair_cor_max=0.7, dE=0.3) assert comp1.looks_like(a1, a2) comp2 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.03, pair_cor_max=0.7, dE=0.15) assert not comp2.looks_like(a1, a2) comp3 = InteratomicDistanceComparator(n_top=3, pair_cor_cum_diff=0.02, pair_cor_max=0.7, dE=0.3) assert not comp3.looks_like(a1, a2)
# creates: transport_setup.png import numpy as np from ase import Atoms from ase.build import molecule from ase.io import write a = 3.92 # Experimental lattice constant sqrt = np.sqrt cell = np.array([[a / sqrt(3), 0., 0.], [0., a / sqrt(2), 0.], [0., a / sqrt(8), a * sqrt(3 / 8.)]]) repeat = (1, 3, 3) A = Atoms('Pt', pbc=True, positions=[(0., 0., 0.)], cell=[1, 1, 1]) B = Atoms('Pt', pbc=True, positions=[(0., 1 / 3., 1 / 3.)], cell=[1, 1, 1]) C = Atoms('Pt', pbc=True, positions=[(0., 2 / 3., 2 / 3.)], cell=[1, 1, 1]) A *= repeat B *= repeat C *= repeat pyramid_BC = Atoms( 'Pt4', pbc=True, tags=[1, 1, 1, 2], positions=[ (0., 1 / 3., 1 / 3.), # B (0., 4 / 3., 1 / 3.), # B (0., 1 / 3., 4 / 3.), # B (1., 2 / 3., 2 / 3.) ], # C
from ase import Atoms from gpaw.fdtd.poisson_fdtd import QSFDTD from gpaw.fdtd.polarizable_material import PermittivityPlus, PolarizableMaterial, PolarizableSphere from gpaw.mpi import world from gpaw.tddft import photoabsorption_spectrum, units from gpaw.test import equal import numpy as np # Whole simulation cell (Angstroms) cell = [20, 20, 30] # Quantum subsystem atom_center = np.array([10.0, 10.0, 20.0]) atoms = Atoms( 'Na2', [atom_center + [0.0, 0.0, -1.50], atom_center + [0.0, 0.0, +1.50]]) # Classical subsystem sphere_center = np.array([10.0, 10.0, 10.0]) classical_material = PolarizableMaterial() classical_material.add_component( PolarizableSphere(permittivity=PermittivityPlus(data=[[1.20, 0.20, 25.0]]), center=sphere_center, radius=5.0)) # Wrap calculators qsfdtd = QSFDTD(classical_material=classical_material, atoms=atoms, cells=(cell, 2.50), spacings=[1.60, 0.40], remove_moments=(1, 4), communicator=world)
from math import sin, cos, pi from ase import Atoms from ase.build import fcc111, fcc100, add_adsorbate from ase.db import connect from ase.constraints import FixAtoms from ase.lattice.cubic import FaceCenteredCubic from ase.cluster import wulff_construction systems = [] cell = (5, 5, 5) atoms = Atoms('H2', [(0, 0, 0), (0, 0, 1.4)], cell=cell) atoms.center() systems.append((atoms, 'Hydrogen molecule')) # atoms = FaceCenteredCubic(directions=[[1, -1, 0], [1, 1, 0], [0, 0, 1]], size=(2, 2, 2), symbol='Cu', pbc=(1, 1, 1)) atoms.rattle(stdev=0.1, seed=42) systems.append((atoms, 'Shaken bulk copper')) # a = 2.70 c = 1.59 * a slab = Atoms('2Cu', [(0., 0., 0.), (1 / 3., 1 / 3., -0.5 * c)], tags=(0, 1), pbc=(1, 1, 0))
from ase import Atoms from gpaw import GPAW, PW from ase.optimize import BFGS from ase.build import fcc111, add_adsorbate, bulk from gpaw import GPAW, PW from ase.io import read, write adsorbate = Atoms('CO') adsorbate[1].z = 1.43 #panjang ikatan CO a = 4.046 #lattice Al slab = fcc111('Al', (1, 1, 3), a=a, vacuum=10) add_adsorbate(slab, adsorbate, 1.8, 'ontop') calc = GPAW(mode=PW(750), xc='PBE', kpts=(8, 8, 1), parallel={'band': 1}, txt='relax-top.txt') slab.calc = calc slab.get_potential_energy() relax = BFGS(slab, logfile='bfgs.log', trajectory='top.traj') relax.run(fmax=0.05) energy = slab.get_potential_energy()
from math import sqrt from ase import Atom, Atoms from ase.neb import NEB from ase.constraints import FixAtoms from ase.vibrations import Vibrations from ase.visualize import view from ase.calculators.emt import EMT from ase.optimize import QuasiNewton, BFGS # Distance between Cu atoms on a (100) surface: d = 3.6 / sqrt(2) initial = Atoms('Cu', positions=[(0, 0, 0)], cell=(d, d, 1.0), pbc=(True, True, False)) initial *= (2, 2, 1) # 2x2 (100) surface-cell # Approximate height of Ag atom on Cu(100) surfece: h0 = 2.0 initial += Atom('Ag', (d / 2, d / 2, h0)) if 0: view(initial) # Make band: images = [initial.copy() for i in range(6)] neb = NEB(images, climb=True) # Set constraints and calculator: constraint = FixAtoms(range(len(initial) - 1)) for image in images:
from ase import Atoms from ase.units import Hartree from gpaw import GPAW h2 = Atoms('H2', [(0, 0, 0), (0, 0, 1)]) h2.center(vacuum=2.0) calc = GPAW(nbands=2, convergence={'eigenstates': 1e-3}) h2.set_calculator(calc) e0 = h2.get_potential_energy() r0 = calc.wfs.eigensolver.error * Hartree**2 / 2 assert r0 < 1e-3 calc.write('h2', 'all') # refine the restart file containing the wfs calc = GPAW('h2', convergence={'eigenstates': 1e-5}) e1 = calc.get_atoms().get_potential_energy() r1 = calc.wfs.eigensolver.error * Hartree**2 / 2 assert r1 < 1e-5
from ase import Atoms from gpaw.transport.calculator import Transport from gpaw.atom.basis import BasisMaker from gpaw.occupations import FermiDirac from gpaw.poisson import PoissonSolver from gpaw.mixer import Mixer import pickle a = 3.6 L = 7.00 basis = BasisMaker('Na').generate(1, 1, energysplit=0.3) atoms = Atoms('Na12', pbc=(0, 0, 1), cell=[L, L, 12 * a]) atoms.positions[:12, 2] = [i * a for i in range(12)] atoms.positions[:, :2] = L / 2. atoms.center() pl_atoms1 = range(4) pl_atoms2 = range(8, 12) pl_cell1 = (L, L, 4 * a) pl_cell2 = pl_cell1 t = Transport(h=0.3, xc='LDA', basis={'Na': basis}, kpts=(1, 1, 1), occupations=FermiDirac(0.1), mode='lcao', poissonsolver=PoissonSolver(nn=2, relax='GS'), txt='Na_lcao.txt', mixer=Mixer(0.1, 5, weight=100.0),
from ase import Atoms, Atom from vasp import Vasp atoms = Atoms([Atom('O', [5, 5, 5], magmom=1)], cell=(6, 6, 6)) calc = Vasp( 'molecules/O_s', encut=300, xc='PBE', ispin=2, ismear=0, sigma=0.001, setups=[['O', '_s']], # specifies O_s potential atoms=atoms) print calc.potential_energy
def test_neb(plt): from ase import Atoms from ase.constraints import FixAtoms import ase.io from ase.neb import NEB, NEBTools from ase.calculators.morse import MorsePotential from ase.optimize import BFGS, QuasiNewton def calc(): # Common calculator for all images. return MorsePotential() # Create and relax initial and final states. initial = Atoms('H7', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0.5, 0.5, 1)], constraint=[FixAtoms(range(6))], calculator=calc()) dyn = QuasiNewton(initial) dyn.run(fmax=0.01) final = initial.copy() final.calc = calc() final.positions[6, 1] = 2 - initial.positions[6, 1] dyn = QuasiNewton(final) dyn.run(fmax=0.01) # Run NEB without climbing image. fmax = 0.05 nimages = 4 images = [initial] for index in range(nimages - 2): images += [initial.copy()] images[-1].calc = calc() images += [final] neb = NEB(images) neb.interpolate() dyn = BFGS(neb, trajectory='mep.traj') dyn.run(fmax=fmax) # Check climbing image. neb.climb = True dyn.run(fmax=fmax) # Check NEB tools. nt_images = ase.io.read('mep.traj', index='-{:d}:'.format(nimages)) nebtools = NEBTools(nt_images) nt_fmax = nebtools.get_fmax(climb=True) Ef, dE = nebtools.get_barrier() print(Ef, dE, fmax, nt_fmax) assert nt_fmax < fmax assert abs(Ef - 1.389) < 0.001 # Plot one band. nebtools.plot_band() # Plot many (ok, 2) bands. nt_images = ase.io.read('mep.traj', index='-{:d}:'.format(2 * nimages)) nebtools = NEBTools(nt_images) nebtools.plot_bands()
#https://wiki.fysik.dtu.dk/gpaw/tutorials/plotting/plot_wave_functions.html from ase import Atoms from gpaw import GPAW d = 1.1 # bondlength of hydrogen molecule a = 5.0 # sidelength of unit cell c = a / 2 atoms = Atoms('CO', positions=[(c - d / 2, c, c), (c + d / 2, c, c)], cell=(a, a, a)) calc = GPAW(nbands=5, h=0.2, txt=None) atoms.set_calculator(calc) # Start a calculation: energy = atoms.get_potential_energy() # Save wave functions: calc.write('CO.gpw', mode='all')
def tags2atoms(tags, store_tags=False, primitive_cell=False, subtrans_included=True, fractional_occupancies=True): """Returns an Atoms object from a cif tags dictionary. See read_cif() for a description of the arguments.""" if primitive_cell and subtrans_included: raise RuntimeError( 'Primitive cell cannot be determined when sublattice translations ' 'are included in the symmetry operations listed in the CIF file, ' 'i.e. when `subtrans_included` is True.') cell_tags = ['_cell_length_a', '_cell_length_b', '_cell_length_c', '_cell_angle_alpha', '_cell_angle_beta', '_cell_angle_gamma'] # If any value is missing, ditch periodic boundary conditions has_pbc = True try: cell_values = [tags[ct] for ct in cell_tags] a, b, c, alpha, beta, gamma = cell_values except KeyError: has_pbc = False # Now get positions try: scaled_positions = np.array([tags['_atom_site_fract_x'], tags['_atom_site_fract_y'], tags['_atom_site_fract_z']]).T except KeyError: scaled_positions = None try: positions = np.array([tags['_atom_site_cartn_x'], tags['_atom_site_cartn_y'], tags['_atom_site_cartn_z']]).T except KeyError: positions = None if (positions is None) and (scaled_positions is None): raise RuntimeError('No positions found in structure') elif scaled_positions is not None and not has_pbc: raise RuntimeError('Structure has fractional coordinates but not ' 'lattice parameters') symbols = [] if '_atom_site_type_symbol' in tags: labels = tags['_atom_site_type_symbol'] else: labels = tags['_atom_site_label'] for s in labels: # Strip off additional labeling on chemical symbols m = re.search(r'([A-Z][a-z]?)', s) symbol = m.group(0) symbols.append(symbol) # Symmetry specification, see # http://www.iucr.org/resources/cif/dictionaries/cif_sym for a # complete list of official keys. In addition we also try to # support some commonly used depricated notations no = None if '_space_group.it_number' in tags: no = tags['_space_group.it_number'] elif '_space_group_it_number' in tags: no = tags['_space_group_it_number'] elif '_symmetry_int_tables_number' in tags: no = tags['_symmetry_int_tables_number'] symbolHM = None if '_space_group.Patterson_name_h-m' in tags: symbolHM = tags['_space_group.patterson_name_h-m'] elif '_symmetry_space_group_name_h-m' in tags: symbolHM = tags['_symmetry_space_group_name_h-m'] elif '_space_group_name_h-m_alt' in tags: symbolHM = tags['_space_group_name_h-m_alt'] if symbolHM is not None: symbolHM = old_spacegroup_names.get(symbolHM.strip(), symbolHM) for name in ['_space_group_symop_operation_xyz', '_space_group_symop.operation_xyz', '_symmetry_equiv_pos_as_xyz']: if name in tags: sitesym = tags[name] break else: sitesym = None # The setting needs to be passed as either 1 or two, not None (default) setting = 1 spacegroup = 1 if sitesym is not None: if isinstance(sitesym, str): sitesym = [sitesym] subtrans = [(0.0, 0.0, 0.0)] if subtrans_included else None spacegroup = spacegroup_from_data( no=no, symbol=symbolHM, sitesym=sitesym, subtrans=subtrans, setting=setting) elif no is not None: spacegroup = no elif symbolHM is not None: spacegroup = symbolHM else: spacegroup = 1 kwargs = {} if store_tags: kwargs['info'] = tags.copy() if 'D' in symbols: deuterium = [symbol == 'D' for symbol in symbols] symbols = [symbol if symbol != 'D' else 'H' for symbol in symbols] else: deuterium = False setting_name = None if '_symmetry_space_group_setting' in tags: setting = int(tags['_symmetry_space_group_setting']) if setting < 1 or setting > 2: raise ValueError('Spacegroup setting must be 1 or 2, not %d' % setting) elif '_space_group_crystal_system' in tags: setting_name = tags['_space_group_crystal_system'] elif '_symmetry_cell_setting' in tags: setting_name = tags['_symmetry_cell_setting'] if setting_name: no = Spacegroup(spacegroup).no # rhombohedral systems if no in (146, 148, 155, 160, 161, 166, 167): if setting_name == 'hexagonal': setting = 1 elif setting_name in ('trigonal', 'rhombohedral'): setting = 2 else: warnings.warn( 'unexpected crystal system %r for space group %r' % ( setting_name, spacegroup)) # FIXME - check for more crystal systems... else: warnings.warn( 'crystal system %r is not interpreted for space group %r. ' 'This may result in wrong setting!' % ( setting_name, spacegroup)) occupancies = None if fractional_occupancies: try: occupancies = tags['_atom_site_occupancy'] # no warnings in this case kwargs['onduplicates'] = 'keep' except KeyError: pass else: try: if not np.allclose(tags['_atom_site_occupancy'], 1.): warnings.warn( 'Cif file containes mixed/fractional occupancies. ' 'Consider using `fractional_occupancies=True`') kwargs['onduplicates'] = 'keep' except KeyError: pass if has_pbc: if scaled_positions is None: _ = Atoms(symbols, positions=positions, cell=[a, b, c, alpha, beta, gamma]) scaled_positions = _.get_scaled_positions() if deuterium: numbers = np.array([atomic_numbers[s] for s in symbols]) masses = atomic_masses[numbers] masses[deuterium] = 2.01355 kwargs['masses'] = masses atoms = crystal(symbols, basis=scaled_positions, cellpar=[a, b, c, alpha, beta, gamma], spacegroup=spacegroup, occupancies=occupancies, setting=setting, primitive_cell=primitive_cell, **kwargs) else: atoms = Atoms(symbols, positions=positions, info=kwargs.get('info', None)) if occupancies is not None: # Compile an occupancies dictionary occ_dict = {} for i, sym in enumerate(symbols): occ_dict[i] = {sym: occupancies[i]} atoms.info['occupancy'] = occ_dict if deuterium: masses = atoms.get_masses() masses[atoms.numbers == 1] = 1.00783 masses[deuterium] = 2.01355 atoms.set_masses(masses) return atoms
def get_siesta_cart(self, label='siesta'): fin = open('in.fdf', 'r') lines = fin.readlines() fin.close() # getting informations from input file for i, line in enumerate(lines): l = line.split() if len(l) > 0: if l[0] == 'NumberOfSpecies': ns = int(l[1]) if l[0] == 'NumberOfAtoms': self.natom = int(l[1]) if l[0] == '%block': if l[1] == 'ChemicalSpeciesLabel': spl = i + 1 if l[1] == 'AtomicCoordinatesAndAtomicSpecies': atml = i + 1 sp = [] for isp in range(ns): l = lines[spl + isp].split() sp.append(l[2]) for na in range(self.natom): l = lines[atml + na].split() self.atom_name.append(sp[int(l[3]) - 1]) fe = open(label + '.MD_CAR', 'r') lines = fe.readlines() fe.close() nl = len(lines) if nl - (self.natom + 7) * self.nframe != 0: fra = (nl - (self.natom + 7) * self.nframe) / (self.natom + 7) print('- %d frames more than expected, error case ... ... ...' % fra) exit() lsp = lines[5].split() nsp = [int(l) for l in lsp] xs = [] if self.traj: his = TrajectoryWriter(self.structure + '.traj', mode='w') for nf in range(self.nframe): block = self.natom + 7 nl = block * nf la = lines[nl + 2].split() lb = lines[nl + 3].split() lc = lines[nl + 4].split() a = [float(la[0]), float(la[1]), float(la[2])] b = [float(lb[0]), float(lb[1]), float(lb[2])] c = [float(lc[0]), float(lc[1]), float(lc[2])] x = [] il = 0 for i, s in enumerate(nsp): for ns in range(s): l = lines[nl + 7 + il].split() xd = [float(l[0]), float(l[1]), float(l[2])] x1 = xd[0] * a[0] + xd[1] * b[0] + xd[2] * c[0] x2 = xd[0] * a[1] + xd[1] * b[1] + xd[2] * c[1] x3 = xd[0] * a[2] + xd[1] * b[2] + xd[2] * c[2] x.append([x1, x2, x3]) il += 1 xs.append(x) if self.traj: A = Atoms(self.atom_name, x, cell=[a, b, c], pbc=[True, True, True]) his.write(atoms=A) self.cell = np.array([a, b, c]) if self.traj: his.close() return xs
from __future__ import print_function from math import pi, cos, sin from ase import Atom, Atoms from gpaw import GPAW, PoissonSolver from gpaw.test import equal, gen # Generate setup for oxygen with half a core-hole: gen('O', name='hch1s', corehole=(1, 0, 0.5)) if 1: a = 5.0 d = 0.9575 t = pi / 180 * 104.51 H2O = Atoms([Atom('O', (0, 0, 0)), Atom('H', (d, 0, 0)), Atom('H', (d * cos(t), d * sin(t), 0))], cell=(a, a, a), pbc=False) H2O.center() calc = GPAW(nbands=10, h=0.2, setups={'O': 'hch1s'}, poissonsolver=PoissonSolver(use_charge_center=True)) H2O.set_calculator(calc) e = H2O.get_potential_energy() niter = calc.get_number_of_iterations() calc.write('h2o.gpw') else: calc = GPAW('h2o.gpw', poissonsolver=PoissonSolver(use_charge_center=True)) calc.initialize_positions() from gpaw.xas import RecursionMethod
def pymatgen2ase(struc): atoms = Atoms(symbols=struc.atomic_numbers, cell=struc.lattice.matrix) atoms.set_scaled_positions(struc.frac_coords) return atoms
(1.638, 3.457, 3.084), (-0.075, 5.662, 4.233), (-0.182, 6.512, 3.776), (-0.241, 5.961, 5.212), (3.243, 2.585, 3.878), (3.110, 2.343, 4.817), (4.262, 2.718, 3.780), (5.942, 2.582, 3.712), (6.250, 3.500, 3.566), (6.379, 2.564, 4.636), (2.686, 5.638, 5.164), (1.781, 5.472, 4.698), (2.454, 6.286, 5.887), (6.744, 5.276, 3.826), (6.238, 5.608, 4.632), (7.707, 5.258, 4.110), (8.573, 8.472, 0.407), (9.069, 7.656, 0.067), (8.472, 8.425, 1.397), (8.758, 8.245, 2.989), (9.294, 9.091, 3.172), (7.906, 8.527, 3.373), (4.006, 7.734, 3.021), (4.685, 8.238, 3.547), (3.468, 7.158, 3.624), (5.281, 6.089, 6.035), (5.131, 7.033, 6.378), (4.428, 5.704, 5.720), (5.067, 7.323, 0.662), (5.785, 6.667, 0.703), (4.718, 7.252, 1.585) ] prefix = 'b256H2O' L = 9.8553729 atoms = Atoms('32(OH2)', positions=positions) atoms.set_cell((L, L, L), scale_atoms=False) atoms.set_pbc(1) r = [2, 2, 2] atoms = atoms.repeat(r) n = [56 * ri for ri in r] # nbands (>=128) is the number of bands per 32 water molecules nbands = 2 * 6 * 11 # 132 for ri in r: nbands = nbands * ri # the next line decreases memory usage es = RMM_DIIS(keep_htpsit=False) calc = GPAW( nbands=nbands, # uncomment next two lines to use lcao/sz #mode='lcao',
from time import time from ase import Atoms from ase.optimize import BFGS from ase.io import read from gpaw import GPAW from gpaw.test import equal from gpaw.mpi import world a = 4.0 # Size of unit cell (Angstrom) c = a / 2 d = 0.74 # Experimental bond length molecule = Atoms('H2', [(c - d / 2, c, c), (c + d / 2, c, c)], cell=(a, a, a), pbc=False) calc = GPAW(h=0.2, nbands=1, xc={ 'name': 'PBE', 'stencil': 1 }, txt=None, poissonsolver={'name': 'fd'}) molecule.set_calculator(calc) e1 = molecule.get_potential_energy() niter1 = calc.get_number_of_iterations() calc.write('H2.gpw') calc.write('H2a.gpw', mode='all') molecule.get_forces() calc.write('H2f.gpw') calc.write('H2fa.gpw', mode='all')
def test_gs_minimum_energy(): atoms = Atoms('H2', positions=[[0, 0, 0], [0, 0, Re]]) atoms.calc = MorsePotential(epsilon=De, r0=Re) assert atoms.get_potential_energy() == -De
def plot_delta(direcs=None, batch_size=1, dft='siesta'): for m in direcs: mol = m rn = IRNN(libfile='ffield.json', direcs=direcs, dft=dft, opt=[], optword='all', batch_size=batch_size, rc_scale='none', interactive=True) molecules = rn.initialize() rn.session(learning_rate=1.0e-10, method='AdamOptimizer') D = rn.get_value(rn.D) Dlp = rn.get_value(rn.Dlp) Dp_ = {} for sp in rn.spec: if rn.nsp[sp] > 0: Dp_[sp] = tf.gather_nd(rn.Deltap, rn.atomlist[sp]) Dp = rn.get_value(Dp_) atlab = rn.lk.atlab traj = Trajectory('delta.traj', 'w') trajp = Trajectory('deltap.traj', 'w') trajlp = Trajectory('deltalp.traj', 'w') natom = molecules[mol].natom d = np.zeros([natom, batch_size]) dp = np.zeros([natom, batch_size]) dlp = np.zeros([natom, batch_size]) cell = rn.cell[mol] for sp in rn.spec: if rn.nsp[sp] > 0: for l, lab in enumerate(atlab[sp]): if lab[0] == mol: i = int(lab[1]) d[i] = D[sp][l] dp[i] = Dp[sp][l] dlp[i] = Dlp[sp][l] for nf in range(batch_size): A = Atoms(symbols=molecules[mol].atom_name, positions=molecules[mol].x[nf], charges=d[:, nf], cell=cell, pbc=(1, 1, 1)) traj.write(A) Ap = Atoms(symbols=molecules[mol].atom_name, positions=molecules[mol].x[nf], charges=dp[:, nf], cell=cell, pbc=(1, 1, 1)) trajp.write(Ap) Alp = Atoms(symbols=molecules[mol].atom_name, positions=molecules[mol].x[nf], charges=dlp[:, nf], cell=cell, pbc=(1, 1, 1)) trajlp.write(Alp) traj.close() trajp.close() trajlp.close()
def test_gs_vibrations(testdir): # check ground state vibrations atoms = Atoms('H2', positions=[[0, 0, 0], [0, 0, Re]]) atoms.calc = MorsePotential(epsilon=De, r0=Re, rho0=rho0) vib = Vibrations(atoms) vib.run()
pseudo_path = 'pseudos' if not os.path.exists(pseudo_path): os.makedirs(pseudo_path) if not os.path.exists(run_path): os.makedirs(run_path) # Make dummy pseudopotentials. for symbol in 'HCO': with open('{0}/{1}.lda.psf'.format(pseudo_path, symbol), 'w') as fd: fd.close() # Change to test directory. os.chdir(run_path) # Setup test structures. h = Atoms('H', [(0.0, 0.0, 0.0)]) co2 = Atoms('CO2', [(0.0, 0.0, 0.0), (-1.178, 0.0, 0.0), (1.178, 0.0, 0.0)]) ch4 = Atoms( 'CH4', np.array([[0.000000, 0.000000, 0.000000], [0.682793, 0.682793, 0.682793], [-0.682793, -0.682793, 0.682790], [-0.682793, 0.682793, -0.682793], [0.682793, -0.682793, -0.682793]])) # Setup required environment variables. os.environ['SIESTA_PP_PATH'] = '../' + pseudo_path # Test the initialization. siesta = Siesta() assert isinstance(siesta, FileIOCalculator) assert isinstance(siesta.implemented_properties, tuple)
had failed to ever register as a neighbor, then we'll get zero once again. """ import numpy as np from ase.calculators.kim import KIM from ase import Atoms # Create calculator calc = KIM("ex_model_Ar_P_Morse_07C") # Create dimer with separation just beyond cutoff distance. We *want* # these atoms to register as neighbors of one another since they fall # within the skinned influence distance of 9.78 Angstroms. model_cutoff = 8.15 skin_distance = 0.2 * model_cutoff distance_orig = model_cutoff + 0.1 * skin_distance atoms = Atoms("Ar2", positions=[[0, 0, 0], [distance_orig, 0, 0]]) atoms.set_calculator(calc) # Get energy -- should be zero e_outside_cutoff = atoms.get_potential_energy() # Now reduce the separation distance to something well within the model # cutoff -- should get something significantly non-zero atoms.positions[1, 0] -= 0.5 * skin_distance # Get new energy e_inside_cutoff = atoms.get_potential_energy() assert not np.isclose(e_outside_cutoff, e_inside_cutoff)
from math import sin, cos, pi import numpy as np from ase import Atoms from ase.build import fcc111, add_adsorbate from ase.db import connect from ase.constraints import FixedPlane, FixAtoms from ase.lattice.cubic import FaceCenteredCubic systems = [] cell = (5, 5, 5) atoms = Atoms('H2', [(0, 0, 0), (0, 0, 1.4)], cell=cell) atoms.center() systems.append((atoms, 'Hydrogen molecule')) # atoms = FaceCenteredCubic(directions=[[1, -1, 0], [1, 1, 0], [0, 0, 1]], size=(3, 3, 3), symbol='Cu', pbc=(1, 1, 1)) atoms.rattle(stdev=0.1, seed=42) systems.append((atoms, 'Shaken bulk copper')) # a = 2.70 c = 1.59 * a slab = Atoms('2Cu', [(0., 0., 0.), (1 / 3., 1 / 3., -0.5 * c)], tags=(0, 1),
def run(glo): # Get path to current directory path = os.getcwd() #Check whether there is a directory for putting calcuation data in. If not create it if not os.path.exists(path + '/Raw'): os.mkdir(path + '/Raw') #Set restart bool for now glo.restart = True # Add system name to path syspath = path + '/' + glo.dirName #Make working directories for each core for i in range(0, glo.cores): if not os.path.exists(path + '/Raw/' + str(i)): os.mkdir(path + '/Raw/' + str(i)) #Start counter which tracks the kinetic timescale mechanismRunTime = 0.0 #Set reaction instance reacs = dict( ("reac_" + str(i), rxn.Reaction(glo.cartesians, glo.species, i, glo)) for i in range(glo.cores)) #Initialise Master Equation object me = MasterEq.MasterEq() # Open files for saving summary mainsumfile = open(('mainSummary.txt'), "a") while mechanismRunTime < glo.maxSimulationTime: # Minimise starting Geom and write summary xml for channel if reacs['reac_0'].have_reactant == False: outputs = [] if __name__ == 'Main': arguments = [] for i in range(0, glo.cores): name = 'reac_' + str(i) arguments.append(reacs[name]) p = multiprocessing.Pool(glo.cores) results = p.map(minReac, arguments) outputs = [result for result in results] for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name] = outputs[i] else: for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name].have_reactant = False # Update path for new minima minpath = syspath + '/' + reacs['reac_0'].ReacName # Get smiles name for initial geom and create directory for first minimum if not os.path.exists(minpath): os.makedirs(minpath) #Copy MESMER file from mes folder MESpath = syspath + '/MESMER/' symb = "".join(reacs[name].CombReac.get_chemical_symbols()) if reacs['reac_0'].energyDictionary[symb] == 0.0: for i in range(0, glo.cores): name = 'reac_' + str(i) d = {symb: reacs[name].reactantEnergy} reacs[name].energyDictionary.update(d) # If a MESMER file has not been created for the current minima then create one if not os.path.exists(MESpath): os.makedirs(MESpath) copyfile('mestemplate.xml', MESpath + 'mestemplate.xml') copyfile('mestemplate.xml', MESpath + 'mestemplateFull.xml') MESFullPath = MESpath + 'mestemplateFull.xml' MESpath = MESpath + 'mestemplate.xml' io.writeMinXML(reacs['reac_0'], MESpath, True, False) io.writeMinXML(reacs['reac_0'], MESFullPath, True, False) if reacs['reac_0'].is_bimol_reac == True: io.writeMinXML(reacs['reac_0'], MESpath, True, True) io.writeMinXML(reacs['reac_0'], MESFullPath, True, True) glo.restart = False else: MESFullPath = MESpath + 'mestemplateFull.xml' MESpath = MESpath + 'mestemplate.xml' # If this is a restart then need to find the next new product from the ME, otherwise start trajectories if glo.restart == False: # Open files for saving summary sumfile = open((minpath + '/summary.txt'), "w") reacs['reac_0'].printReac(minpath) for r in range(0, glo.ReactIters): tempPaths = dict(("tempPath_" + str(i), minpath + '/temp' + str(i) + '_' + str(r)) for i in range(glo.cores)) # Now set up tmp directory for each thread for i in range(0, glo.cores): if not os.path.exists(tempPaths[('tempPath_' + str(i))]): os.makedirs(tempPaths[('tempPath_' + str(i))]) if r % 2 == 0: glo.trajMethod = glo.trajMethod1 glo.trajLevel = glo.trajLevel1 else: glo.trajMethod = glo.trajMethod2 glo.trajLevel = glo.trajLevel2 # If this is the first species and it is a bimolecular channel, then initialise a bimolecular trajectory # Otherwise initialise unimolecular trajectory at minima if glo.InitialBi == True: trajs = dict( ("traj_" + str(i), Trajectory.Trajectory( reacs[('reac_' + str(i))].CombReac, glo, tempPaths[( 'tempPath_' + str(i))], str(i), True)) for i in range(glo.cores)) else: trajs = dict( ("traj_" + str(i), Trajectory.Trajectory( reacs[('reac_' + str(i))].CombReac, glo, tempPaths[( 'tempPath_' + str(i))], str(i), False)) for i in range(glo.cores)) results2 = [] outputs2 = [] if __name__ == "Main": arguments1 = [] arguments2 = [] for i in range(0, glo.cores): name = 'reac_' + str(i) name2 = 'traj_' + str(i) arguments1.append(reacs[name]) arguments2.append(trajs[name2]) arguments = list( zip(arguments1, arguments2, [minpath] * glo.cores, [MESpath] * glo.cores, range(glo.cores), [glo] * glo.cores)) p = multiprocessing.Pool(glo.cores) results2 = p.map(runNormal, arguments) outputs2 = [result for result in results2] for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name] = outputs2[i][0] sumfile.write( str(reacs[name].ProdName) + '_' + str(reacs[name].biProdName) + '\t' + str(reacs[name].forwardBarrier) + '\t' + str(outputs2[i][1].numberOfSteps)) sumfile.flush() # run a master eqution to estimate the lifetime of the current species me.runTillReac(MESpath) me.newSpeciesFound = False # check whether there is a possible bimolecular rection for current intermediate if len(glo.BiList) > 0 and glo.InitialBi == False: for i in range(0, len(glo.BiList)): baseXYZ = reacs['reac_0'].CombReac.get_chemical_symbols() if me.time > (1 / float(glo.BiRates[i])): print( "assessing whether or not to look for bimolecular channel. Rate = " + str(float(glo.BiRates[i])) + "Mesmer reaction time = " + str(me.time)) glo.InitialBi = True xyz = CT.get_bi_xyz(reacs['reac_0'].ReacName, glo.BiList[i]) spec = np.append( baseXYZ, np.array(glo.BiList[i].get_chemical_symbols())) combinedMol = Atoms(symbols=spec, positions=xyz) #Set reaction instance for j in range(0, glo.cores): name = 'reac_' + str(j) d = {symb: reacs[name].reactantEnergy} reacs[name].re_init_bi(xyz, spec) biTrajs = dict( ("traj_" + str(k), Trajectory.Trajectory( combinedMol, glo, tempPaths[( 'tempPath_' + str(k))], str(k), True)) for k in range(glo.cores)) biTempPaths = dict(("tempPath_" + str(k), minpath + '/temp' + str(j)) for k in range(glo.cores)) if __name__ == "Main": arguments1 = [] arguments2 = [] for j in range(0, glo.cores): name = 'reac_' + str(j) name2 = 'traj_' + str(j) biTrajs[name2].fragIdx = (len(baseXYZ), len(xyz)) arguments1.append(reacs[name]) arguments2.append(biTrajs[name2]) arguments = list( zip(arguments1, arguments2, [minpath] * glo.cores, [MESpath] * glo.cores, range(glo.cores), [glo] * glo.cores, [glo.BiList[i]] * glo.cores)) p = multiprocessing.Pool(glo.cores) p.map(runNormal, arguments) glo.InitialBi = False # Run ME from the given minimum. While loop until species formed is new sumfile.close() glo.restart = False glo.InitialBi = False while me.newSpeciesFound == False: me.runTillReac(MESpath) mechanismRunTime += me.time out = me.prodName + ' ' + str(mechanismRunTime) + '\n' me.visitedList.append(me.prodName) mainsumfile.write(out) mainsumfile.flush() if not os.path.exists(syspath + '/' + me.prodName): os.makedirs(syspath + '/' + me.prodName) for i in range(0, glo.cores): if os.path.exists(syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName): reacs[('reac_' + str(i))].newReac( syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName, me.prodName, False) else: print("cant find path " + str(syspath + '/' + reacs[ ('reac_' + str(i))].ReacName + '/' + me.prodName)) try: reacs[('reac_' + str(i))].newReac( syspath + '/' + me.prodName, me.prodName, True) except: reacs[('reac_' + str(i))].newReacFromSMILE( me.prodName) io.update_me_start(me.prodName, me.ene, MESpath) me.newSpeciesFound = True else: if me.repeated() == True: me.equilCount += 1 if me.equilCount >= 20: mainsumfile.write('lumping' + ' ' + str(reacs['reac_0'].ReacName) + ' ' + str(me.prodName) + '\n') me.prodName = io.lumpSpecies(reacs['reac_0'].ReacName, me.prodName, MESpath, MESpath) mainsumfile.flush() me.equilCount = 1 minpath = syspath + '/' + me.prodName for i in range(0, glo.cores): if os.path.exists(syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName): reacs[('reac_' + str(i))].newReac( syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName, me.prodName, False) else: try: reacs[('reac_' + str(i))].newReac( syspath + '/' + me.prodName, me.prodName, True) except: reacs[('reac_' + str(i))].newReacFromSMILE( me.prodName) io.update_me_start(me.prodName, me.ene, MESpath) me.newspeciesFound = False glo.restart = False mainsumfile.close()
from ase import Atoms from ase.io import write from ase.test import cli write('x.json', Atoms('X')) # Make sure ASE's gui can run in terminal mode without $DISPLAY and tkinter: cli('ase -T gui --terminal x.json@id=1')
from __future__ import print_function, division import os, unittest, numpy as np try: from ase import Atoms from gpaw import GPAW fname = os.path.dirname(os.path.abspath(__file__)) + '/h2o.gpw' if os.path.isfile(fname): calc = GPAW(fname, txt=None) # read previous calculation if the file exists else: from gpaw import PoissonSolver atoms = Atoms('H2O', positions=[[0.0, -0.757, 0.587], [0.0, +0.757, 0.587], [0.0, 0.0, 0.0]]) atoms.center(vacuum=3.5) convergence = { 'density': 1e-7 } # Increase accuracy of density for ground state poissonsolver = PoissonSolver( eps=1e-14, remove_moment=1 + 3 ) # Increase accuracy of Poisson Solver and apply multipole corrections up to l=1 calc = GPAW( basis='dzp', xc='LDA', h=0.3, nbands=23, convergence=convergence, poissonsolver=poissonsolver,