def convert_adsorbate(cls, adsorbate): """Converts the adsorbate to an Atoms object""" if isinstance(adsorbate, Atoms): ads = adsorbate elif isinstance(adsorbate, Atom): ads = Atoms([adsorbate]) else: # Hope it is a useful string or something like that if adsorbate == 'CO': # CO otherwise comes out as OC - very inconvenient ads = molecule(adsorbate, symbols=adsorbate) else: ads = molecule(adsorbate) ads.translate(-ads[0].position) return ads
def build_system(self, name): try: # Known molecule or atom? atoms = molecule(name) if len(atoms) == 2 and self.bond_length is not None: atoms.set_distance(0, 1, self.bond_length) except NotImplementedError: symbols = string2symbols(name) if len(symbols) == 1: magmom = ground_state_magnetic_moments[atomic_numbers[ symbols[0]]] atoms = Atoms(name, magmoms=[magmom]) elif len(symbols) == 2: # Dimer if self.bond_length is None: b = (covalent_radii[atomic_numbers[symbols[0]]] + covalent_radii[atomic_numbers[symbols[1]]]) else: b = self.bond_length atoms = Atoms(name, positions=[(0, 0, 0), (b, 0, 0)]) else: raise ValueError('Unknown molecule: ' + name) if self.unit_cell is None: atoms.center(vacuum=self.vacuum) else: atoms.cell = self.unit_cell atoms.center() return atoms
def test_huckel_e2(self): ethene = molecule('C2H4') m_ethene = ase_utils.to_molmod(ethene) ethene_h = huckel.Huckel(m_ethene, [{0,1}]) h_e = ethene_h.huckel_e self.assertAlmostEquals(h_e, 2*huckel.alpha + 2*huckel.beta)
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') # Basically, the entire CP2K input is passed in explicitly. # Disable ASE's input generation by setting everything to None. # ASE should only add the CELL and the COORD section. calc = CP2K(basis_set=None, basis_set_file=None, max_scf=None, cutoff=None, force_eval_method=None, potential_file=None, poisson_solver=None, pseudo_potential=None, stress_tensor=False, xc=None, label='test_H2_inp', inp=inp) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() energy_ref = -30.6989595886 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10 print('passed test "H2_None"')
def containatom(atom, formulas, data): molecules = [] for f in formulas: m = molecule(f, data=data) if atom in list(set(m.get_chemical_symbols())): molecules.append(f) return list(set(molecules))
def test_huckel_e3(self): benzene = molecule('C6H6') m_benzene = ase_utils.to_molmod(benzene) benzene_h = huckel.Huckel(m_benzene) bond_order = benzene_h.bond_order({1, 2}) self.assertAlmostEquals(bond_order, 2. / 3)
def test_multiple_elements(self): a = molecule('HCOOH') a.center(vacuum=5.0) io.write('HCOOH.cfg', a) i = neighbour_list("i", a, 1.85) self.assertArrayAlmostEqual(np.bincount(i), [2, 3, 1, 1, 1]) cutoffs = np.zeros([9, 9]) cutoffs[1, 6] = cutoffs[6, 1] = 1.2 i = neighbour_list("i", a, cutoffs, np.array(a.numbers, dtype=np.int32)) self.assertArrayAlmostEqual(np.bincount(i), [0, 1, 0, 0, 1]) cutoffs = np.zeros([9, 9]) cutoffs[6, 8] = cutoffs[8, 6] = 1.4 i = neighbour_list("i", a, cutoffs, np.array(a.numbers, dtype=np.int32)) self.assertArrayAlmostEqual(np.bincount(i), [1, 2, 1]) cutoffs = np.zeros([9, 9]) cutoffs[1, 6] = cutoffs[6, 1] = 1.2 cutoffs[6, 8] = cutoffs[8, 6] = 1.4 i = neighbour_list("i", a, cutoffs, np.array(a.numbers, dtype=np.int32)) self.assertArrayAlmostEqual(np.bincount(i), [1, 3, 1, 0, 1])
def build_system(self, name): try: # Known molecule or atom? atoms = molecule(name) if len(atoms) == 2 and self.bond_length is not None: atoms.set_distance(0, 1, self.bond_length) except NotImplementedError: symbols = string2symbols(name) if len(symbols) == 1: Z = atomic_numbers[symbols[0]] magmom = ground_state_magnetic_moments[Z] atoms = Atoms(name, magmoms=[magmom]) elif len(symbols) == 2: # Dimer if self.bond_length is None: b = (covalent_radii[atomic_numbers[symbols[0]]] + covalent_radii[atomic_numbers[symbols[1]]]) else: b = self.bond_length atoms = Atoms(name, positions=[(0, 0, 0), (b, 0, 0)]) else: raise ValueError('Unknown molecule: ' + name) if self.unit_cell is None: atoms.center(vacuum=self.vacuum) else: atoms.cell = self.unit_cell atoms.center() return atoms
def test_huckel_e3(self): benzene = molecule('C6H6') m_benzene = ase_utils.to_molmod(benzene) benzene_h = huckel.Huckel(m_benzene) bond_order = benzene_h.bond_order({1, 2}) self.assertAlmostEquals(bond_order, 2./3)
def analyse(calc, relaxed): A = [] for name in molecule_names: # molecule ea = np.nan dist = np.nan t = np.nan formulas = [name] for i in range(len(molecule(name, data=data))): formulas.append(name + '_bq' + str(i)) for formula in formulas: try: d = c.get(name=formula, relaxed=relaxed, calculator=calc) assert d.name == formula if 'bq' in formula: print 'bq', d.name ea = ea + d.energy else: print 'molecule', d.name ea = - d.energy dist = ((d.positions[0] - d.positions[-1])**2).sum()**0.5 t = d.time except (KeyError, ValueError): ea = np.nan dist = np.nan t = np.nan A.append((ea, dist, t)) return np.array(A).T
def waterMolecule(): atoms = molecule('H2O') print(atoms) atoms.center(vacuum=3.5) atoms.calc = ElectronicMinimize(atoms=atoms) print(atoms.get_potential_energy()) print(atoms.get_forces())
def h2dft(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', **par) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) e2 = h2.get_potential_energy() calc.set(xc='PBE') e2pbe = h2.get_potential_energy() h1 = h2.copy() del h1[1] h1.set_initial_magnetic_moments([1]) h1.calc = calc e1pbe = h1.get_potential_energy() calc.set(xc='LDA') e1 = h1.get_potential_energy() try: m1 = h1.get_magnetic_moment() except NotImplementedError: pass else: print(m1) print(2 * e1 - e2) print(2 * e1pbe - e2pbe) print(e1, e2, e1pbe, e2pbe) calc = Calculator(name) print(calc.parameters, calc.results, calc.atoms) assert not calc.calculation_required(h1, ['energy']) h1 = calc.get_atoms() print(h1.get_potential_energy()) label = 'dir/' + name + '-h1' calc = Calculator(label=label, atoms=h1, xc='LDA', **par) print(h1.get_potential_energy()) print(Calculator.read_atoms(label).get_potential_energy())
def h2dft(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', **par) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) e2 = h2.get_potential_energy() calc.set(xc='PBE') e2pbe = h2.get_potential_energy() h1 = h2.copy() del h1[1] h1.set_initial_magnetic_moments([1]) h1.calc = calc e1pbe = h1.get_potential_energy() calc.set(xc='LDA') e1 = h1.get_potential_energy() try: m1 = h1.get_magnetic_moment() except NotImplementedError: pass else: print m1 print(2 * e1 - e2) print(2 * e1pbe - e2pbe) print e1, e2, e1pbe, e2pbe calc = Calculator(name) print calc.parameters, calc.results, calc.atoms assert not calc.calculation_required(h1, ['energy']) h1 = calc.get_atoms() print h1.get_potential_energy() label = 'dir/' + name + '-h1' calc = Calculator(label=label, atoms=h1, xc='LDA', **par) print h1.get_potential_energy() print Calculator.read_atoms(label).get_potential_energy()
def test_huckel_e2(self): ethene = molecule('C2H4') m_ethene = ase_utils.to_molmod(ethene) ethene_h = huckel.Huckel(m_ethene, [{0, 1}]) h_e = ethene_h.huckel_e self.assertAlmostEquals(h_e, 2 * huckel.alpha + 2 * huckel.beta)
def waterMolecule(): atoms = molecule("H2O") print(atoms) atoms.center(vacuum=3.5) atoms.calc = ElectronicMinimize(atoms=atoms) print(atoms.get_potential_energy()) print(atoms.get_forces())
def test_H2_PBE(): calc = CP2K(xc='PBE', label='test_H2_PBE') h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() / Hartree diff = abs((energy + 0.961680073441) / energy) assert(diff < 1e-10) print('passed test "H2_PBE"')
def test_O2(): calc = CP2K(label='test_O2') o2 = molecule('O2', calculator=calc) o2.center(vacuum=2.0) energy = o2.get_potential_energy() / Hartree diff = abs((energy + 29.669802288970264) / energy) assert(diff < 1e-10) print('passed test "O2"')
def test_H2_LDA(): calc = CP2K(label='test_H2_LDA') h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() / Hartree diff = abs((energy + 0.932722287302) / energy) assert(diff < 1e-10) print('passed test "H2_LDA"')
def do_calculations(self, formulas): """Perform calculation on molecules, write results to .gpw files.""" atoms = {} for formula in formulas: for symbol in string2symbols(formula.split('_')[0]): atoms[symbol] = None formulas = formulas + atoms.keys() for formula in formulas: if path.isfile(formula + '.gpw'): continue barrier() open(formula + '.gpw', 'w') s = molecule(formula) s.center(vacuum=self.vacuum) cell = s.get_cell() h = self.h s.set_cell((cell / (4 * h)).round() * 4 * h) s.center() calc = GPAW(h=h, xc=self.xc, eigensolver=self.eigensolver, setups=self.setups, basis=self.basis, fixmom=True, txt=formula + '.txt') if len(s) == 1: calc.set(hund=True) s.set_calculator(calc) if formula == 'BeH': calc.initialize(s) calc.nuclei[0].f_si = [(1, 0, 0.5, 0, 0), (0.5, 0, 0, 0, 0)] if formula in ['NO', 'ClO', 'CH']: s.positions[:, 1] += h * 1.5 try: energy = s.get_potential_energy() except (RuntimeError, ConvergenceError): if rank == 0: print >> sys.stderr, 'Error in', formula traceback.print_exc(file=sys.stderr) else: print >> self.txt, formula, repr(energy) self.txt.flush() calc.write(formula) if formula in diatomic and self.calculate_dimer_bond_lengths: traj = PickleTrajectory(formula + '.traj', 'w') d = diatomic[formula][1] for x in range(-2, 3): s.set_distance(0, 1, d * (1.0 + x * 0.02)) traj.write(s)
def create_random_atoms(gd, nmolecules=10, name='NH2', mindist=4.5 / Bohr): """Create gas-like collection of atoms from randomly placed molecules. Applies rigid motions to molecules, translating the COM and/or rotating by a given angle around an axis of rotation through the new COM. These atomic positions obey the minimum distance requirement to zero-boundaries. Warning: This is only intended for testing parallel grid/LFC consistency. """ atoms = Atoms(cell=gd.cell_cv * Bohr, pbc=gd.pbc_c) # Store the original state of the random number generator randstate = np.random.get_state() seed = np.array([md5_array(data, numeric=True) for data in [nmolecules, gd.cell_cv, gd.pbc_c, gd.N_c]]).astype(int) np.random.seed(seed % 4294967296) for m in range(nmolecules): amol = molecule(name) amol.set_cell(gd.cell_cv * Bohr) # Rotate the molecule around COM according to three random angles # The rotation axis is given by spherical angles phi and theta v,phi,theta = np.random.uniform(0.0, 2*np.pi, 3) # theta [0,pi[ really axis = np.array([cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta)]) amol.rotate(axis, v) # Find the scaled length we must transverse along the given axes such # that the resulting displacement vector is `mindist` from the cell # face corresponding to that direction (plane with unit normal n_v). sdist_c = np.empty(3) if not gd.orthogonal: for c in range(3): n_v = gd.xxxiucell_cv[c] / np.linalg.norm(gd.xxxiucell_cv[c]) sdist_c[c] = mindist / np.dot(gd.cell_cv[c], n_v) else: sdist_c[:] = mindist / gd.cell_cv.diagonal() assert np.all(sdist_c > 0), 'Displacment vectors must be inside cell.' # Scaled dimensions of the smallest possible box centered on the COM spos_ac = amol.get_scaled_positions() # NB! must not do a "% 1.0" scom_c = np.dot(gd.icell_cv, amol.get_center_of_mass()) sbox_c = np.abs(spos_ac-scom_c[np.newaxis,:]).max(axis=0) sdelta_c = (1-np.array(gd.pbc_c)) * (sbox_c + sdist_c) assert (sdelta_c < 1.0-sdelta_c).all(), 'Box is too tight to fit atoms.' scenter_c = [np.random.uniform(d,1-d) for d in sdelta_c] center_v = np.dot(scenter_c, gd.cell_cv) # Translate the molecule such that COM is located at random center offset_av = (center_v-amol.get_center_of_mass()/Bohr)[np.newaxis,:] amol.set_positions(amol.get_positions()+offset_av*Bohr) assert np.linalg.norm(center_v-amol.get_center_of_mass()/Bohr) < 1e-9 atoms.extend(amol) # Restore the original state of the random number generator np.random.set_state(randstate) assert compare_atoms(atoms) return atoms
def test_restart(): calc = CP2K() h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) h2.get_potential_energy() calc.write('test_restart') # write a restart calc2 = CP2K(restart='test_restart') # load a restart assert not calc2.calculation_required(h2, ['energy']) print('passed test "restart"')
def molecule(name, **kwargs): "Deprecated." import warnings warnings.warn('ase.data.molecules.molecule is deprecated. ' 'Please use:' \ ' from ase.structure import molecule' \ ' instead.', DeprecationWarning, stacklevel=2) from ase.structure import molecule return molecule(name, **kwargs)
def main_octopus(): from octopus import Octopus from ase.structure import molecule system = molecule('H2') system.center(vacuum=1.5) system.pbc = 1 calc = Octopus() system.set_calculator(calc) system.get_potential_energy() check_interface(calc)
def test_geopt(): calc = CP2K(label='test_geopt') h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) dyn = BFGS(h2) dyn.run(fmax=0.05) dist = h2.get_distance(0, 1) diff = abs((dist - 1.36733746519) / dist) assert(diff < 1e-10) print('passed test "geopt"')
def main_gpaw(): from gpaw import GPAW from ase.structure import molecule system = molecule('H2') system.center(vacuum=1.5) system.pbc = 1 calc = GPAW(h=0.3, mode='lcao', txt=None) system.set_calculator(calc) system.get_potential_energy() check_interface(calc)
def h2(name, par): h2 = molecule('H2', pbc=par.pop('pbc', False)) h2.center(vacuum=2.0) h2.calc = get_calculator(name)(**par) e = h2.get_potential_energy() f = h2.get_forces() assert not h2.calc.calculation_required(h2, ['energy', 'forces']) write('h2.traj', h2) h2 = read('h2.traj') assert abs(e - h2.get_potential_energy()) < 1e-12 assert abs(f - h2.get_forces()).max() < 1e-12
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') calc = CP2K() h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) h2.get_potential_energy() calc.write('test_restart') # write a restart calc2 = CP2K(restart='test_restart') # load a restart assert not calc2.calculation_required(h2, ['energy']) print('passed test "restart"')
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable("$ASE_CP2K_COMMAND not defined") calc = CP2K(xc="XC_GGA_X_PBE XC_GGA_C_PBE", pseudo_potential="GTH-PBE", label="test_H2_libxc") h2 = molecule("H2", calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() energy_ref = -31.591716529642 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10 print('passed test "H2_libxc"')
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') calc = CP2K(label='test_H2_LDA') h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() energy_ref = -30.6989595886 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10 print('passed test "H2_LDA"')
def main(): formulas = g1 + atoms dimers = [formula for formula in g1 if len(molecule(formula)) == 2] kwargs = dict(vacuum=3.0, mode='lcao', basis='dzp') etest = BatchTest(GPAWEnergyTest('test/energy', **kwargs)) btest = BatchTest(GPAWBondLengthTest('test/bonds', **kwargs)) etest.run(formulas) btest.run(dimers)
def addWater(cnt, centerX, centerY, centerZ): water = molecule('H2O') cnt_length = 2*centerZ nH = int(cnt_length/(distance + 1)) + 1 z = 0 delta_z = distance for n in range(0, nH): z -= delta_z add_adsorbate(cnt, water, z , position=(centerX, centerY)) return cnt
def build_molecule(self, name): args = self.args try: # Known molecule or atom? atoms = molecule(name) except NotImplementedError: symbols = string2symbols(name) if len(symbols) == 1: Z = atomic_numbers[symbols[0]] magmom = ground_state_magnetic_moments[Z] atoms = Atoms(name, magmoms=[magmom]) elif len(symbols) == 2: # Dimer if args.bond_length is None: b = covalent_radii[atomic_numbers[symbols[0]]] + covalent_radii[atomic_numbers[symbols[1]]] else: b = args.bond_length atoms = Atoms(name, positions=[(0, 0, 0), (b, 0, 0)]) else: raise ValueError("Unknown molecule: " + name) else: if len(atoms) == 2 and args.bond_length is not None: atoms.set_distance(0, 1, args.bond_length) if args.unit_cell is None: atoms.center(vacuum=args.vacuum) else: a = [float(x) for x in args.unit_cell.split(",")] if len(a) == 1: cell = [a[0], a[0], a[0]] elif len(a) == 3: cell = a else: a, b, c, alpha, beta, gamma = a degree = np.pi / 180.0 cosa = np.cos(alpha * degree) cosb = np.cos(beta * degree) sinb = np.sin(beta * degree) cosg = np.cos(gamma * degree) sing = np.sin(gamma * degree) cell = [ [a, 0, 0], [b * cosg, b * sing, 0], [ c * cosb, c * (cosa - cosb * cosg) / sing, c * np.sqrt(sinb ** 2 - ((cosa - cosb * cosg) / sing) ** 2), ], ] atoms.cell = cell atoms.center() return atoms
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') calc = CP2K(label='test_O2', uks=True, cutoff=150 * units.Rydberg, basis_set="SZV-MOLOPT-SR-GTH") o2 = molecule('O2', calculator=calc) o2.center(vacuum=2.0) energy = o2.get_potential_energy() energy_ref = -861.057011375 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10 print('passed test "O2"')
def build_molecule(name, opts): try: # Known molecule or atom? atoms = molecule(name) except NotImplementedError: symbols = string2symbols(name) if len(symbols) == 1: Z = atomic_numbers[symbols[0]] magmom = ground_state_magnetic_moments[Z] atoms = Atoms(name, magmoms=[magmom]) elif len(symbols) == 2: # Dimer if opts.bond_length is None: b = (covalent_radii[atomic_numbers[symbols[0]]] + covalent_radii[atomic_numbers[symbols[1]]]) else: b = opts.bond_length atoms = Atoms(name, positions=[(0, 0, 0), (b, 0, 0)]) else: raise ValueError('Unknown molecule: ' + name) else: if len(atoms) == 2 and opts.bond_length is not None: atoms.set_distance(0, 1, opts.bond_length) if opts.unit_cell is None: atoms.center(vacuum=opts.vacuum) else: a = [float(x) for x in opts.unit_cell.split(',')] if len(a) == 1: cell = [a[0], a[0], a[0]] elif len(a) == 3: cell = a else: a, b, c, alpha, beta, gamma = a degree = np.pi / 180.0 cosa = np.cos(alpha * degree) cosb = np.cos(beta * degree) sinb = np.sin(beta * degree) cosg = np.cos(gamma * degree) sing = np.sin(gamma * degree) cell = [[a, 0, 0], [b * cosg, b * sing, 0], [ c * cosb, c * (cosa - cosb * cosg) / sing, c * np.sqrt(sinb**2 - ((cosa - cosb * cosg) / sing)**2) ]] atoms.cell = cell atoms.center() return atoms
def make_training_images(): atoms = molecule('CH4') atoms.set_calculator(EMT()) atoms.get_potential_energy(apply_constraint=False) images = [atoms] atoms = Atoms(atoms) atoms.set_calculator(EMT()) atoms[3].z += 0.5 atoms.get_potential_energy(apply_constraint=False) images += [atoms] return images
def analyse(): A = [] for name in molecule_names: try: ea = data[name].get('dissociation energy', np.nan) * kcal / mol dist = molecule(name, data=data).get_distance(0, 1) freq = data[name].get('harmonic frequency', np.nan) t = np.nan except KeyError: ea = np.nan dist = np.nan freq = np.nan t = np.nan A.append((ea, dist, freq, t)) return np.array(A).T
def test_H2_LS(): inp = """&FORCE_EVAL &DFT &QS LS_SCF ON &END QS &END DFT &END FORCE_EVAL""" calc = CP2K(label='test_H2_LS', inp=inp) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) energy = h2.get_potential_energy() / Hartree diff = abs((energy + 0.932722212414) / energy) assert(diff < 1e-10) print('passed test "H2_LS"')
def setUp(self): self._atoms = Atoms() self._mcount = 5 self._edge = 100.0 x = np.linspace(-self._edge / 2.0, self._edge / 2.0, self._mcount) c = 0 for i in x: for j in x: for k in x: ch4 = molecule("CH4") self._set_atoms_pos(ch4, (i, j, k)) self._atoms.extend(ch4) c += 1 Mixer.set_atom_ids(self._atoms)
def lmp_structure(self): atoms = GNT(dict(latx=self.latx, laty=5, latz=1, gnrtype=self.gnrtype)).lmp_structure() self.center_box(atoms) x = atoms.cell[0, 0] / 2 c60 = molecule('C60', data=extra_molecules.data) c60.rotate('z', 2 * pi / 5) c60.rotate('y', -pi / 4) right = c60[c60.positions[:, 0] > c60.cell[0, 0] / 2].copy() del c60[c60.positions[:, 0] > c60.cell[0, 0] / 2] c60.translate([-x, 0, 0]) right.translate([x, 0, 0]) atoms.extend(c60) atoms.extend(right) atoms.center(vacuum=10) return atoms
def setUp(self): self._atoms = Atoms() self._mcount = 5 self._edge = 100.0 x = np.linspace(-self._edge/2.0, self._edge/2.0, self._mcount) c = 0 for i in x: for j in x: for k in x: ch4 = molecule("CH4") self._set_atoms_pos(ch4, (i,j,k)) self._atoms.extend(ch4) c += 1 Mixer.set_atom_ids(self._atoms)
def setUp(self): for virtvar in []: assert getattr(self, virtvar) is not None, 'Virtual "%s"!' % virtvar parsize_domain, parsize_bands = create_parsize_maxbands( self.nbands, world.size) self.parallel = {'domain': parsize_domain, 'band': parsize_bands} self.atoms = molecule('Na2') self.atoms.center(vacuum=4.0) self.atoms.set_pbc(False) cell_c = np.sum(self.atoms.get_cell()**2, axis=1)**0.5 / Bohr ngpts = 16 * np.round(cell_c / (self.h * 16)) self.gsname = 'ut_tddft_gs' self.gscalc = GPAW(gpts=ngpts, nbands=self.nbands, basis='dzp', setups={'Na': '1'}, spinpol=(self.nspins == 2), parallel=self.parallel, txt=self.gsname + '.txt')
def check_db(c, db, test=None): if test is None: print("%10s %10s %10s ( %10s )" \ % ( "bond", "value", "reference", "error" )) print("%10s %10s %10s ( %10s )" \ % ( "----", "-----", "---------", "-----" )) for mol, values in db.items(): #if mol == 'H2O': if 1: a = molecule(mol) a.center(vacuum=10.0) a.set_pbc(False) a.set_initial_charges(np.zeros(len(a))) a.set_calculator(c) FIRE(a, logfile=None).run(fmax=0.001) for name, ( ( i1, i2 ), refvalue ) in values.items(): value = a.get_distance(i1, i2) if test is None: print('%10s %10.3f %10.3f ( %10.3f )' % \ ( name, value, refvalue, abs(value-refvalue) )) else: test.assertTrue(abs(value-refvalue) < 0.01)
from gpaw.xc.fxc import FXCCorrelation from gpaw.test import equal from gpaw.mpi import world if world.size == 1: scalapack1 = None scalapack2 = None elif world.size == 2: scalapack1 = (2, world.size // 2, 32) scalapack2 = None else: scalapack1 = (2, world.size // 2, 32) scalapack2 = (2, world.size // 4, 32) # N2 -------------------------------------- N2 = molecule('N2') N2.set_cell((2.5, 2.5, 3.5)) N2.center() calc = GPAW(mode='pw', eigensolver='rmm-diis', dtype=complex, xc='LDA', nbands=16, basis='dzp', convergence={'density': 1.e-6}) N2.set_calculator(calc) N2.get_potential_energy() calc.diagonalize_full_hamiltonian(nbands=80, scalapack=scalapack1) calc.write('N2.gpw', mode='all') ralda = FXCCorrelation('N2.gpw', xc='rALDA')
the forces are nonzero. Energy is compared to a previous calculation; if it differs significantly, that is considered an error. Forces are compared to a previous finite-difference result. """ import numpy as np from ase.structure import molecule from gpaw import GPAW from gpaw.utilities import unpack from gpaw.atom.basis import BasisMaker from gpaw.test import equal mol = molecule('H2O') mol.rattle(0.2) mol.center(vacuum=2.0) calc = GPAW(nbands=6, gpts=(32, 40, 40), setups='hgh', convergence=dict(eigenstates=1e-9, density=1e-5, energy=0.3e-5), txt='-') mol.set_calculator(calc) e = mol.get_potential_energy() niter = calc.get_number_of_iterations() F_ac = mol.get_forces() F_ac_ref = np.array([[7.33077718, 3.81069249, -6.07405156], [-0.9079617, -1.18203514, 3.43777589], [-0.61642527, -0.41889306, 2.332415]])
#!/usr/bin/env python2 from ase.structure import molecule from obcalc import OBForceField atoms = molecule('CO') calc = OBForceField() atoms.set_calculator(calc) e = atoms.get_potential_energy()
import numpy as np def array_almost_equal(a1, a2, tol=np.finfo(type(1.0)).eps): """Replacement for old numpy.testing.utils.array_almost_equal.""" return (np.abs(a1 - a2) < tol).all() # this test should be run with abinit! from ase.calculators.emt import EMT from ase.io import read, write from ase.structure import molecule m1 = molecule('O2') m1.center(2.0) write('abinit_save.in', images=m1, format='abinit') m1.set_calculator(EMT()) e1 = m1.get_potential_energy() f1 = m1.get_forces() m2 = read('abinit_save.in', format='abinit') m2.set_calculator(EMT()) e2 = m2.get_potential_energy() f2 = m1.get_forces() # assume atoms definitions are the same if energy/forces are the same: can we do better? assert abs(e1-e2) < 1.e-6, str(e1) + ' ' + str(e2) assert array_almost_equal(f1, f2, tol=1.e-6)
from ase.structure import molecule from jasp import * # first we define our molecules. These will automatically be at the coordinates from the G2 database. CO = molecule('CO') CO.set_cell([8, 8, 8], scale_atoms=False) H2O = molecule('H2O') H2O.set_cell([8, 8, 8], scale_atoms=False) CO2 = molecule('CO2') CO2.set_cell([8, 8, 8], scale_atoms=False) H2 = molecule('H2') H2.set_cell([8, 8, 8], scale_atoms=False) # now the calculators to get the energies with jasp('molecules/wgs/CO', xc='PBE', encut=350, ismear=0, ibrion=2, nsw=10, atoms=CO) as calc: try: eCO = CO.get_potential_energy() except (VaspSubmitted, VaspQueued): eCO = None with jasp('molecules/wgs/CO2', xc='PBE', encut=350, ismear=0, ibrion=2, nsw=10, atoms=CO2) as calc: try:
* basis_functions.construct_density as used in a normal calculation * axpy used on the psit_nG as constructed by lcao_to_grid * axpy used on the Phit_MG[i] * Phit_MG[j] * rho[j, i], where Phit_MG are the actual basis functions on the grid, constructed using lcao_to_grid TODO: non-gamma-point test """ from __future__ import print_function import numpy as np from ase.structure import molecule from gpaw import GPAW, ConvergenceError from gpaw.utilities.blas import axpy system = molecule('H2O') system.center(vacuum=2.5) calc = GPAW( mode='lcao', #basis='dzp', maxiter=1) system.set_calculator(calc) try: system.get_potential_energy() except ConvergenceError: pass wfs = calc.wfs kpt = wfs.kpt_u[0]
def create_item(self, name): m = molecule(name, data=self.data) m.set_cell(self.cell) m.set_pbc((0, 0, 0)) m.center() return m
from jasp import * from ase.structure import molecule H = molecule('H') H.set_cell([8, 8, 8], scale_atoms=False) with jasp('molecules/H-beef', xc='PBE', gga='BF', encut=350, ismear=0, atoms=H) as calc: try: eH = H.get_potential_energy() print(eH) except (VaspSubmitted, VaspQueued): print('running or queued') eH = None
#!/usr/bin/env python from ase import * from ase.structure import molecule from vasp import Vasp ### Setup calculators benzene = molecule('C6H6') benzene.set_cell([10, 10, 10]) benzene.center() calc1 = Vasp('molecules/benzene', xc='PBE', nbands=18, encut=350, atoms=benzene) calc1.set(lcharg=True) chlorobenzene = molecule('C6H6') chlorobenzene.set_cell([10, 10, 10]) chlorobenzene.center() chlorobenzene[11].symbol = 'Cl' calc2 = Vasp('molecules/chlorobenzene', xc='PBE', nbands=22, encut=350, atoms=chlorobenzene) calc2.set(lcharg=True) calc2.stop_if(None in (calc1.potential_energy, calc2.potential_energy)) x1, y1, z1, cd1 = calc1.get_charge_density() x2, y2, z2, cd2 = calc2.get_charge_density() cdiff = cd2 - cd1 print(cdiff.min(), cdiff.max()) ########################################## ##### set up visualization of charge difference
def run(formula='H2O', vacuum=2.0, cell=None, pbc=0, **morekwargs): print(formula, parallel) system = molecule(formula) kwargs = dict(basekwargs) kwargs.update(morekwargs) calc = GPAW(**kwargs) system.set_calculator(calc) system.center(vacuum) if cell is None: system.center(vacuum) else: system.set_cell(cell) system.set_pbc(pbc) try: system.get_potential_energy() except KohnShamConvergenceError: pass E = calc.hamiltonian.Etot F_av = calc.forces.calculate(calc.wfs, calc.density, calc.hamiltonian) global Eref, Fref_av if Eref is None: Eref = E Fref_av = F_av eerr = abs(E - Eref) ferr = abs(F_av - Fref_av).max() if calc.wfs.world.rank == 0: print('Energy', E) print() print('Forces') print(F_av) print() print('Errs', eerr, ferr) if eerr > tolerance or ferr > tolerance: if calc.wfs.world.rank == 0: stderr = sys.stderr else: stderr = devnull if eerr > tolerance: print('Failed!', file=stderr) print('E = %f, Eref = %f' % (E, Eref), file=stderr) msg = 'Energy err larger than tolerance: %f' % eerr if ferr > tolerance: print('Failed!', file=stderr) print('Forces:', file=stderr) print(F_av, file=stderr) print(file=stderr) print('Ref forces:', file=stderr) print(Fref_av, file=stderr) print(file=stderr) msg = 'Force err larger than tolerance: %f' % ferr print(file=stderr) print('Args:', file=stderr) print(formula, vacuum, cell, pbc, morekwargs, file=stderr) print(parallel, file=stderr) raise AssertionError(msg)
from ase.optimize import QuasiNewton from ase.constraints import FixAtoms from ase.calculators.emt import EMT from ase.vibrations import Vibrations import ase.io import numpy as np import chemcoord as cc if os.path.exists('CH3_Al.traj'): slab = ase.io.read('CH3_Al.traj') slab.set_calculator(EMT()) # Need to reset when loading from traj file else: slab = fcc111('Al', size=(2, 2, 2), vacuum=3.0) CH3 = molecule('CH3') add_adsorbate(slab, CH3, 2.5, 'ontop') constraint = FixAtoms(mask=[a.symbol == 'Al' for a in slab]) slab.set_constraint(constraint) slab.set_calculator(EMT()) dyn = QuasiNewton(slab, trajectory='QN_slab.traj') dyn.run(fmax=0.05) ase.io.write('CH3_Al.traj', slab) # Running vibrational analysis vib = Vibrations(slab, indices=[8, 9, 10, 11]) vib.run()
from ase.structure import molecule atoms = molecule('C6H6') # benzene # access properties on each atom print(' # sym p_x p_y p_z') print('------------------------------') for i, atom in enumerate(atoms): print('{0:3d}{1:^4s}{2:-8.2f}{3:-8.2f}{4:-8.2f}'.format(i, atom.symbol, atom.x, atom.y, atom.z)) # get all properties in arrays sym = atoms.get_chemical_symbols() pos = atoms.get_positions() num = atoms.get_atomic_numbers() atom_indices = range(len(atoms)) print() print(' # sym at# p_x p_y p_z') print('-------------------------------------') for i, s, n, p in zip(atom_indices, sym, num, pos): px, py, pz = p print('{0:3d}{1:>3s}{2:8d}{3:-8.2f}{4:-8.2f}{5:-8.2f}'.format(i, s, n, px, py, pz))
from ase.structure import molecule from ase.structure import graphene_nanoribbon from ase.optimize import QuasiNewton from gpaw import GPAW H2 = molecule('H2', cell=(10, 10, 10)) H2.center() calc = GPAW() H2.set_calculator(calc) dyn = QuasiNewton(H2, trajectory='H2.traj') dyn.run(fmax=0.05)
# Benzene on the slab from jasp import * from ase.lattice.surface import fcc111, add_adsorbate from ase.structure import molecule from ase.constraints import FixAtoms atoms = fcc111('Au', size=(3,3,3), vacuum=10) benzene = molecule('C6H6') benzene.translate(-benzene.get_center_of_mass()) # I want the benzene centered on the position in the middle of atoms # 20, 22, 23 and 25 p = (atoms.positions[20] + atoms.positions[22] + atoms.positions[23] + atoms.positions[25])/4.0 + [0.0, 0.0, 3.05] benzene.translate(p) atoms += benzene # now we constrain the slab c = FixAtoms(mask=[atom.symbol=='Au' for atom in atoms]) atoms.set_constraint(c) #from ase.visualize import view; view(atoms) with jasp('surfaces/Au-benzene-pbe', xc='PBE', encut=350, kpts=(4,4,1), ibrion=1, nsw=100, atoms=atoms) as calc: print atoms.get_potential_energy()
from ase.atoms import string2symbols from ase.data.g2_1 import data from ase.data.g2_1_ref import atomization_vasp, diatomic from ase.data.molecules import latex from ase.structure import molecule from ase.units import kcal, mol import numpy as np import pylab as plt dimers = diatomic.keys() dimers.remove('FH') molecules = atomization_vasp.keys() atoms = set() for m in molecules: atoms.update(molecule(m).get_chemical_symbols()) systems = molecules + list(atoms) E = {'NH3': -19.889, 'S2': -7.082, 'SiH2_s3B1d': -8.765, 'CH3OH': -30.696, 'SiH4': -18.877, 'Si2H6': -30.888, 'PH3': -15.567, 'PH2': -10.792, 'HF': -8.706, 'O2': -10.598, 'SiH3': -13.816, 'NH': -8.361, 'SH2': -11.166, 'ClO': -6.119, 'H2O2': -18.884, 'NO': -13.042, 'ClF': -4.948, 'LiH': -3.741, 'HCO': -17.574, 'CH3': -18.262, 'CH4': -24.157, 'Cl2': -3.609, 'HOCl': -11.314, 'SiH2_s1A1d': -9.483, 'SiO': -11.503, 'F2': -5.172, 'P2': -8.988, 'Si2': -5.217, 'CH': -6.239, 'CO': -15.281, 'CN': -13.384, 'LiF': -7.701, 'Na2': -1.194, 'SO2': -17.548, 'NaCl': -4.699, 'Li2': -1.445, 'NH2': -13.831, 'CS': -10.285, 'C2H6': -40.737, 'N2': -17.382, 'C2H4': -32.205, 'HCN': -20.159, 'C2H2': -23.174, 'CH2_s3B1d': -12.125, 'CH3Cl': -22.544, 'BeH': -3.520, 'CO2': -23.886, 'CH3SH': -27.720, 'OH': -8.089, 'N2H4': -31.003, 'H2O': -14.579, 'SO': -9.356, 'CH2_s1A1d': -11.451,