def opt(self, rdkmol, dhls, logger='optlog.out'): Na = rdkmol.GetNumAtoms() X, S = __convert_rdkitmol_to_nparr__(rdkmol) atm=Atoms(symbols=S, positions=X) atm.set_calculator(ANIENS(self.ens)) #Set the ANI Ensemble as the calculator phi_fix = [] for d in dhls: phi_restraint=atm.get_dihedral(d) phi_fix.append([phi_restraint, d]) c = FixInternals(dihedrals=phi_fix, epsilon=1.e-9) atm.set_constraint(c) dyn = LBFGS(atm, logfile=logger) #Choose optimization algorith dyn.run(fmax=self.fmax, steps=1000) #optimize molecule to Gaussian's Opt=Tight fmax criteria, input in eV/A (I think) e=atm.get_potential_energy()*hdt.evtokcal s=atm.calc.stddev*hdt.evtokcal phi_value = [] for d in dhls: phi_value.append(atm.get_dihedral(d)*180./np.pi) #X = mol.get_positions() if self.printer: print('Phi value (degrees), energy (kcal/mol), sigma= ', phi_value, "{0:.2f}".format(e), "{0:.2f}".format(s)) return phi_value, e, s, atm
def test_qchem_calculator(): import numpy as np from ase.build import molecule from ase.calculators.qchem import QChem from ase.optimize import LBFGS mol = molecule('C2H6') calc = QChem(label='calc/ethane', method='B3LYP', basis='6-31+G*') mol.set_calculator(calc) # Check energy and forces np.testing.assert_allclose(mol.get_potential_energy(), -2172.379183703419, atol=10.) np.testing.assert_allclose(mol.get_forces(), np.array( [[0., 0.00240141, 0.04992568], [-0., -0.00240141, -0.04992568], [-0., 0.11626015, 0.07267481], [-0.10132204, -0.05804009, 0.07538475], [0.10132204, -0.05804009, 0.07538475], [-0., -0.11626015, -0.07267481], [-0.10132204, 0.05804009, -0.07538475], [0.10132204, 0.05804009, -0.07538475]]), atol=0.05) opt = LBFGS(mol) opt.run() assert opt.converged()
def optimize_rdkit_molecule(self, mrdk, cid, fmax=0.0001, steps=500, logger='opt.out'): mol = __convert_rdkitmol_to_aseatoms__(mrdk,cid) mol.set_calculator(ANI(False)) mol.calc.setnc(self.nc) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() xyz = mol.get_positions() for i,x in enumerate(xyz): mrdk.GetConformer(cid).SetAtomPosition(i,x)
def test_optimizer(atoms): pos = atoms.positions.copy() atoms.calc = get_calc(label='opt', scf='qc') opt_gauss = GaussianOptimizer(atoms) opt_gauss.run(fmax='tight') e_gaussopt = read('opt.log', index=-1).get_potential_energy() atoms.positions[:] = pos atoms.calc.set_label('sp') opt_ase = LBFGS(atoms, trajectory='ase_opt.traj') opt_ase.run(fmax=1e-2) e_aseopt = atoms.get_potential_energy() assert e_gaussopt - e_aseopt == pytest.approx(0., abs=1e-3)
def test_pressure(atoms, cellfilter): xcellfilter = cellfilter(atoms, scalar_pressure=10.0 * GPa) # test all derivatives f, fn = gradient_test(xcellfilter) assert abs(f - fn).max() < 5e-6 opt = LBFGS(xcellfilter) opt.run(1e-3) # check pressure is within 0.1 GPa of target sigma = atoms.get_stress() / GPa pressure = -(sigma[0] + sigma[1] + sigma[2]) / 3.0 assert abs(pressure - 10.0) < 0.1
def optimize_molecule(self, X, S, fmax=0.1, steps=10000, logger='opt.out'): mol = Atoms(symbols=S, positions=X) mol.set_pbc((False, False, False)) mol.set_calculator(ANIENS(self.ens)) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) #dyn = QuasiNewton(mol,logfile=logger) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() opt = True if steps == stps: opt = False return np.array(mol.get_positions(),dtype=np.float32), opt
def optimize_lammpslib(struc, lmp, parameters=None, path='tmp', calc_type=None, lmp_file=None, molecule=False, strain=np.ones([3, 3]), method='FIRE', fmax=0.01): if lmp_file is not None: lammps = LAMMPSlib(lmp=lmp, lmp_file=lmp_file, log_file='lammps.log', \ molecule=molecule, path=path) elif calc_type is not None: lammps = LAMMPSlib(lmp=lmp, lmpcmds=parameters, calc_type=calc_type, \ log_file='lammps.log', molecule=molecule, path=path) else: lammps = LAMMPSlib(lmp=lmp, lmpcmds=parameters, log_file='lammps.log', \ molecule=molecule, path=path) struc.set_calculator(lammps) box = mushybox(struc, fixstrain=strain) if method == 'FIRE': dyn = FIRE(box) else: dyn = LBFGS(box) dyn.run(fmax=fmax, steps=500) return struc
def g(k, do_abs=True): print(f'Static minimisation with k={k}, alpha={alpha0}.') sc.k = k * k1g sc.alpha = alpha0 sc.variable_alpha = False sc.variable_k = False sc.update_atoms() atoms = sc.atoms.copy() atoms.calc = sc.calc atoms.set_constraint(FixAtoms(mask=~sc.regionI)) print('I think it gets to here') if preconlbfgs: opt = PreconLBFGS(atoms, logfile=None) if lbfgs: opt = LBFGS(atoms, logfile=None) opt.run(fmax=1e-5) print('I do not know if it gets to here') atoms.write(traj, format="extxyz") sc.set_atoms(atoms) f_alpha = sc.get_crack_tip_force(mask=mask) print( f'Static minimisation with k={k}, alpha={alpha0} --> f_alpha={f_alpha}' ) if do_abs: f_alpha = abs(f_alpha) return f_alpha
def ase_popt(embedder, coords, atomnos, constrained_indexes=None, steps=500, targets=None, safe=False, safe_mask=None, traj=None, logfunction=None, title='temp'): ''' embedder: TSCoDe embedder object coords: atomnos: constrained_indexes: safe: if True, adds a potential that prevents atoms from scrambling safe_mask: bool array, with False for atoms to be excluded when calculating bonds to preserve traj: if set to a string, traj is used as a filename for the bending trajectory. not only the atoms will be printed, but also all the orbitals and the active pivot. ''' atoms = Atoms(atomnos, positions=coords) atoms.calc = get_ase_calc(embedder) constraints = [] if constrained_indexes is not None: for i, c in enumerate(constrained_indexes): i1, i2 = c tgt_dist = norm_of(coords[i1] - coords[i2]) if targets is None else targets[i] constraints.append(Spring(i1, i2, tgt_dist)) if safe: constraints.append( PreventScramblingConstraint( graphize(coords, atomnos, safe_mask), atoms, double_bond_protection=embedder.options.double_bond_protection, fix_angles=embedder.options.fix_angles_in_deformation)) atoms.set_constraint(constraints) t_start_opt = time.perf_counter() with LBFGS(atoms, maxstep=0.1, logfile=None, trajectory=traj) as opt: opt.run(fmax=0.05, steps=steps) iterations = opt.nsteps new_structure = atoms.get_positions() success = (iterations < 499) if logfunction is not None: exit_str = 'REFINED' if success else 'MAX ITER' logfunction( f' - {title} {exit_str} ({iterations} iterations, {time_to_string(time.perf_counter()-t_start_opt)})' ) energy = atoms.get_total_energy() * 23.06054194532933 #eV to kcal/mol return new_structure, energy, success
def opt_lammpslib(struc, lmp, parameters=None, mask=None, logfile='-', path='tmp', calc_type=None, lmp_file=None, molecule=False, method='FIRE', fmax=0.01, opt_cell=False, a=0.1, steps=500): """ mask: [1, 1, 1, 1, 1, 1], a, b, c, alpha, beta, gamma [1, 1, 0, 0, 0, 1] """ if lmp_file is not None: lammps = LAMMPSlib(lmp=lmp, lmp_file=lmp_file, log_file='lammps.log', \ molecule=molecule, path=path) elif calc_type is not None: lammps = LAMMPSlib(lmp=lmp, lmpcmds=parameters, calc_type=calc_type, \ log_file='lammps.log', molecule=molecule, path=path) else: lammps = LAMMPSlib(lmp=lmp, lmpcmds=parameters, log_file='lammps.log', \ molecule=molecule, path=path) #check_symmetry(si, 1.0e-6, verbose=True) struc.set_calculator(lammps) struc.set_constraint(FixSymmetry(struc)) if opt_cell: ecf = ExpCellFilter(struc, mask) if method == 'FIRE': dyn = FIRE(ecf, logfile=logfile, a=a) else: dyn = LBFGS(ecf, logfile=logfile) else: if method == 'FIRE': dyn = FIRE(struc, logfile=logfile) else: dyn = LBFGS(struc, logfile=logfile) dyn.run(fmax=fmax, steps=steps) return struc
def relax_atoms(atoms, tol=1e-3, method='lbfgs_precon', max_steps=1000, traj_file=None, **kwargs): import model atoms.set_calculator(model.calculator) if hasattr(model, 'Optimizer'): method = 'model_optimizer' opt = model.Optimizer(atoms) opt.run(tol, max_steps) elif method.startswith('lbfgs') or method == 'fire' or method == 'cg_n': if method == 'lbfgs_ASE': from ase.optimize import LBFGS opt = LBFGS(atoms, **kwargs) elif method == 'cg_n': from quippy import Minim opt = Minim(atoms, relax_positions=True, relax_cell=False, method='cg_n') else: from ase.optimize.precon.precon import Exp from ase.optimize.precon.lbfgs import PreconLBFGS precon = None if method.endswith('precon'): precon = Exp(3.0, recalc_mu=True) if method.startswith('lbfgs'): opt = PreconLBFGS(atoms, precon=precon, **kwargs) else: opt = FIRE(atoms, **kwargs) if traj_file is not None and method != 'cg_n': traj = open(traj_file, 'w') def write_trajectory(): write(traj, atoms, format='extxyz') opt.attach(write_trajectory) opt.run(tol, max_steps) try: traj.close() except: pass else: raise ValueError('unknown method %s!' % method) return atoms
def make_methylamine(): # Construct Methylamine. atoms = Atoms('NH2CH3') # Define connectivity. atoms_bonds = [ [0,1], [0,2], [0,3], [3,4], [3,5], [3,6] ] # Displace atoms so that they aren't on top of each other. atoms.rattle(0.001) # Construct VSEPR calculator. calculator = VSEPR(atoms, atoms_bonds) atoms.set_calculator(calculator) atoms.center() # Run optimization. opt = LBFGS(atoms, logfile='/dev/null') opt.run() return atoms
def optimize_rdkit_molecule(self, mrdk, cid, fmax=0.1, steps=10000, logger='opt.out'): mol = __convert_rdkitmol_to_aseatoms__(mrdk,cid) mol.set_pbc((False, False, False)) mol.set_calculator(ANIENS(self.ens)) dyn = LBFGS(mol,logfile=logger) #dyn = LBFGS(mol) #dyn = QuasiNewton(mol,logfile=logger) dyn.run(fmax=fmax,steps=steps) stps = dyn.get_number_of_steps() opt = True if steps == stps: opt = False xyz = mol.get_positions() for i,x in enumerate(xyz): mrdk.GetConformer(cid).SetAtomPosition(i,x) return opt
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False): """Calculate the surface energy from a list of slab images. Parameters ---------- images: List of slab images which the calculation is based on. The x and y dimensions of the images unit cell must be conserved. natoms: Number of atoms in a atomic layer in the slabs. calc: Calculator object that can be attached to the images. """ ucell = images[0].get_cell() layers = np.zeros(len(images)) energies = np.zeros(len(images)) if debug: print "Layers Energy LBFGS steps" for i, atoms in enumerate(images): cell = atoms.get_cell() if (ucell[0] != cell[0]).any() or (ucell[1] != cell[1]).any(): raise ValueError("The x and y dimensions of the unit cell must be conserved.") atoms.set_calculator(calc) dyn = LBFGS(atoms, logfile=None, trajectory=None) dyn.run(fmax=fmax, steps=1000) assert dyn.converged(), "LBFGS not converged in 100 steps!" layers[i] = len(atoms) / natoms energies[i] = atoms.get_potential_energy() if debug: print "%4i%12.3f%10i" % (layers[i], energies[i], dyn.get_number_of_steps()) p = polyfit(layers.reshape((-1,1)), energies, 1) surface_energy = p.c[0] / (2 * natoms) assert surface_energy > 0.0 return surface_energy
def relax_bare_cluster(cluster, relax_fmax=0.05): c0 = cluster.copy() orig_index = c0.get_array("orig_index") fix_list = np.loadtxt("cp2k_fix_list.txt", dtype="int") - 1 fix_orig_index = [orig_index[i] for i in fix_list] hydrogens = np.where(c0.get_atomic_numbers() == 1)[0] del c0[hydrogens] new_fix_list = [i for i, j in enumerate(c0.get_array("orig_index")) if j in fix_orig_index] pot = calc c0.set_calculator(pot) c0.get_potential_energy() c0.set_array("fixdip", np.array([True if i in new_fix_list else False for i in range(len(c0))])) c0.set_array("dipoles", np.zeros((len(c0), 3))) # pot.atoms.arrays['dipoles']) # c0.arrays['dipoles'][new_fix_list, :] = 0.0 const = FixAtoms(indices=new_fix_list) c0.set_constraint(const) opt = LBFGS(c0) opt.run(fmax=relax_fmax) return c0
def calculate(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) trajectory = PickleTrajectory(self.get_filename(name, 'traj'), 'w', atoms) if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=self.logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=self.logfile) fmax = args.maximum_force optimizer.attach(trajectory) optimizer.run(fmax=fmax) data = RunCommand.calculate(self, atoms, name) if hasattr(optimizer, 'force_calls'): data['force calls'] = optimizer.force_calls return data
def test_Ar_minimize(): from ase.calculators.lammpsrun import LAMMPS from ase.cluster.icosahedron import Icosahedron from ase.data import atomic_numbers, atomic_masses from numpy.testing import assert_allclose from ase.optimize import LBFGS ar_nc = Icosahedron('Ar', noshells=2) ar_nc.cell = [[300, 0, 0], [0, 300, 0], [0, 0, 300]] ar_nc.pbc = True params = {} params['pair_style'] = 'lj/cut 8.0' params['pair_coeff'] = ['1 1 0.0108102 3.345'] params['masses'] = ['1 {}'.format(atomic_masses[atomic_numbers['Ar']])] with LAMMPS(specorder=['Ar'], **params) as calc: ar_nc.calc = calc assert_allclose(ar_nc.get_potential_energy(), -0.468147667942117, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4) dyn = LBFGS(ar_nc, force_consistent=False) dyn.run(fmax=1E-6) assert_allclose(ar_nc.get_potential_energy(), -0.4791815886953914, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4)
def relax(self): from ase.optimize import LBFGS cached = sys.__stdout__ try: optimizer = LBFGS(self.ucf) optimizer.logfile = None optimised = optimizer.run(fmax=0.05, steps=100) except Exception: optimised = False self.doc["optimised"] = bool(optimised) self.doc["positions_abs"] = self.atoms.get_positions().tolist() self.doc["lattice_cart"] = self.atoms.get_cell().tolist() self.doc["lattice_abc"] = cart2abc(self.doc["lattice_cart"]) self.doc["positions_frac"] = cart2frac(self.doc["lattice_cart"], self.doc["positions_abs"]) self.doc["enthalpy_per_atom"] = float(self.calc.results["energy"] / len(self.doc["atom_types"])) self.doc["enthalpy"] = float(self.calc.results["energy"]) self.queue.put(self.doc) sys.stdout = cached
def test_unitcellfilter(asap3): cu = bulk('Cu') * (6, 6, 6) cu.calc = asap3.EMT() f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0)
def add_ligand(atoms, ligand, site, position=None): atoms.set_tags(0) ligand = ligand.copy() # Extract nanoparticle. np_idx = [ i for i in xrange(len(atoms)) if atoms[i].number > 20 ] nanoparticle = atoms[np_idx] # Pick a binding site and shift ligand above it. com = nanoparticle.get_center_of_mass() v = atoms[site].position - com v /= numpy.linalg.norm(v) ligand.center() displacement_length = 1.1 * ligand_size(ligand) if position is None: ligand.positions += atoms.positions[site] + displacement_length*v else: ligand.positions += position + displacement_length*v ligand.set_tags(1) # Create combined system. atoms += ligand # Construct VSEPR calculator with N-Au interaction. ligand_mask = [tag == 1 for tag in atoms.get_tags()] ligand_bonds = connect_bonds(atoms, mask=ligand_mask) calculator = VSEPR(atoms, ligand_bonds + [[site,len(atoms)-len(ligand)]], nonbonded=connect_nonbonded(atoms, connect_angles(ligand_bonds), r_cut=displacement_length*2)) atoms.set_calculator(calculator) atoms.set_constraint(FixAtoms(indices=range(len(atoms)-len(ligand)))) # Run optimization. opt = LBFGS(atoms, memory=10, maxstep=0.2) opt.run(fmax=1e-2)
def test_Ar_minimize(factory, ar_nc, params): with factory.calc(specorder=['Ar'], **params) as calc: ar_nc.calc = calc assert_allclose(ar_nc.get_potential_energy(), -0.468147667942117, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4) dyn = LBFGS(ar_nc, force_consistent=False) dyn.run(fmax=1E-6) assert_allclose(ar_nc.get_potential_energy(), -0.4791815886953914, atol=1e-4, rtol=1e-4) assert_allclose(ar_nc.get_forces(), calc.calculate_numerical_forces(ar_nc), atol=1e-4, rtol=1e-4)
def optimize(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) logfile = self.get_filename(name, 'log') if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=logfile) fmax = args.maximum_force trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) optimizer.attach(trajectory) optimizer.run(fmax=fmax)
def optimize(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=self.logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=self.logfile) fmax = args.maximum_force optimizer.attach(trajectory) optimizer.run(fmax=fmax) data = {} if hasattr(optimizer, 'force_calls'): data['force_calls'] = optimizer.force_calls return data
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False): """Calculate the surface energy from a list of slab images. Parameters ---------- images: List of slab images which the calculation is based on. The x and y dimensions of the images unit cell must be conserved. natoms: Number of atoms in a atomic layer in the slabs. calc: Calculator object that can be attached to the images. """ ucell = images[0].get_cell() layers = np.zeros(len(images)) energies = np.zeros(len(images)) if debug: print "Layers Energy LBFGS steps" for i, atoms in enumerate(images): cell = atoms.get_cell() if (ucell[0] != cell[0]).any() or (ucell[1] != cell[1]).any(): raise ValueError( "The x and y dimensions of the unit cell must be conserved.") atoms.set_calculator(calc) dyn = LBFGS(atoms, logfile=None, trajectory=None) dyn.run(fmax=fmax, steps=1000) assert dyn.converged(), "LBFGS not converged in 100 steps!" layers[i] = len(atoms) / natoms energies[i] = atoms.get_potential_energy() if debug: print "%4i%12.3f%10i" % (layers[i], energies[i], dyn.get_number_of_steps()) p = polyfit(layers.reshape((-1, 1)), energies, 1) surface_energy = p.c[0] / (2 * natoms) assert surface_energy > 0.0 return surface_energy
def optimize(atoms, sym=True, box=False, method='FIRE', fmax=0.01, steps=1000, logfile='ase.log'): if sym: atoms.set_constraint(FixSymmetry(atoms)) if box: ecf = ExpCellFilter(atoms) if method == 'FIRE': dyn = FIRE(ecf, logfile=logfile) else: dyn = LBFGS(ecf, logfile=logfile) else: if method == 'FIRE': dyn = FIRE(atoms, logfile=logfile) else: dyn = FIRE(atoms, logfile=logfile) dyn.run(fmax=fmax, steps=steps) atoms.set_constraint() return atoms
file_name = file_name_py.replace('.py', '') file_traj = file_name + '.traj' start_file = '../In2O3_110_clean.traj' mode = 'a' try: sys = Trajectory(file_traj, 'r')[-1] except (IOError, RuntimeError): print "Importing trajectory file from: %s" % start_file sys = read(start_file) sys.center(vacuum=5.0, axis=2) else: print "Importing trajectory file from: %s" % file_traj set_calc_In2O3(sys) print "Constraints:" print " c1: Fix bottom two layers." avg_z = np.mean([atom.z for atom in sys]) c1 = FixAtoms(mask=[atom.z < avg_z for atom in sys]) sys.set_constraint(c1) if testRun == True: run_testRun(sys) else: geo_traj = Trajectory(file_traj, mode, sys) dyn = LBFGS(sys, trajectory=geo_traj) dyn.run(fmax=0.05) energy = sys.get_potential_energy() print "Energy: %f" % energy print "Completed %s" % file_name_py
def run_tests(): import os import time from subprocess import CalledProcessError os.chdir(os.path.dirname(os.path.realpath(__file__))) from tscode.settings import (CALCULATOR, COMMANDS, DEFAULT_FF_LEVELS, DEFAULT_LEVELS, FF_CALC, FF_OPT_BOOL, PROCS) if CALCULATOR not in ('MOPAC','ORCA','GAUSSIAN','XTB'): raise Exception(f'{CALCULATOR} is not a valid calculator. Use MOPAC, ORCA, GAUSSIAN or XTB.') import numpy as np from ase.atoms import Atoms from ase.optimize import LBFGS from tscode.ase_manipulations import get_ase_calc from tscode.optimization_methods import opt_funcs_dict from tscode.utils import (HiddenPrints, clean_directory, loadbar, read_xyz, run_command, time_to_string) os.chdir('tests') t_start_run = time.perf_counter() data = read_xyz('C2H4.xyz') ########################################################################## print('\nRunning tests for TSCoDe. Settings used:') print(f'{CALCULATOR=}') if CALCULATOR != 'XTB': print(f'{CALCULATOR} COMMAND = {COMMANDS[CALCULATOR]}') print('\nTesting calculator...') ########################################################################## opt_funcs_dict[CALCULATOR](data.atomcoords[0], data.atomnos, method=DEFAULT_LEVELS[CALCULATOR], procs=PROCS, read_output=False) print(f'{CALCULATOR} raw calculator works.') ########################################################################## atoms = Atoms('HH', positions=np.array([[0, 0, 0], [0, 0, 1]])) atoms.calc = get_ase_calc((CALCULATOR, DEFAULT_LEVELS[CALCULATOR], PROCS, None)) LBFGS(atoms, logfile=None).run() clean_directory() print(f'{CALCULATOR} ASE calculator works.') ########################################################################## print(f'\n{FF_OPT_BOOL=}') ff = f'on. Calculator is {FF_CALC}. Checking its status.' if FF_OPT_BOOL else 'off.' print(f'Force Field optimization is turned {ff}') if FF_OPT_BOOL: if FF_CALC == 'OB': try: print('Trying to import the OpenBabel Python Module...') from openbabel import openbabel print('Module imported successfully.') except ImportError: raise Exception(f'Could not import OpenBabel Python module. Is standalone openbabel correctly installed?') else: # == 'XTB', 'GAUSSIAN' opt_funcs_dict[FF_CALC](data.atomcoords[0], data.atomnos, method=DEFAULT_FF_LEVELS[FF_CALC], procs=PROCS, read_output=False) print(f'{FF_CALC} FF raw calculator works.') ########################################################################## atoms.calc = get_ase_calc((FF_CALC, DEFAULT_FF_LEVELS[FF_CALC], PROCS, None)) LBFGS(atoms, logfile=None).run() clean_directory() print(f'{FF_CALC} ASE calculator works.') print('\nNo installation faults detected with the current settings. Running tests.') ########################################################################## tests = [] for f in os.listdir(): if f.endswith('.txt'): tests.append(os.path.realpath(f)) # os.chdir(os.path.dirname(os.getcwd())) # os.chdir('tscode') # # Back to ./tscode times = [] for i, f in enumerate(tests): name = f.split('\\')[-1].split('/')[-1][:-4] # trying to make it work for either Win, Linux (and Mac?) loadbar(i, len(tests), f'Running TSCoDe tests ({name}): ') t_start = time.perf_counter() try: with HiddenPrints(): run_command(f'python -m tscode {f} -n {name}') except CalledProcessError as error: print('\n\n--> An error occurred:\n') print(error.stderr.decode("utf-8")) quit() t_end = time.perf_counter() times.append(t_end-t_start) loadbar(len(tests), len(tests), f'Running TSCoDe tests ({name}): ') print() for i, f in enumerate(tests): print(' {:25s}{} s'.format(f.split('\\')[-1].split('/')[-1][:-4], round(times[i], 3))) print(f'\nTSCoDe tests completed with no errors. ({time_to_string(time.perf_counter() - t_start_run)})\n')
calc = fp_GD_Calculator() # atoms.set_calculator(calc) atoms.calc = calc ############################## Relaxation type ############################## ''' Ref : https://wiki.fysik.dtu.dk/ase/ase/optimize.html#module-optimize https://wiki.fysik.dtu.dk/ase/ase/constraints.html ''' af = atoms # af = StrainFilter(atoms) # af = UnitCellFilter(atoms) print(af.get_forces()) ############################## Relaxation method ############################## # opt = BFGS(af, maxstep = 1.e-3, trajectory = trajfile) # opt = FIRE(af, maxstep = 1.e-3, trajectory = trajfile) opt = LBFGS(af, maxstep = 1.e-1, trajectory = trajfile, memory = 10, use_line_search = True) # opt = LBFGS(af, maxstep = 1.e-3, trajectory = trajfile, memory = 10, use_line_search = False) # opt = SciPyFminCG(af, trajectory = trajfile) # opt = SciPyFminBFGS(af, trajectory = trajfile) opt.run(fmax = 1.e-10) traj = Trajectory(trajfile) ase.io.write('opt.vasp', traj[-1], direct = True, long_format=True, vasp5 = True)
from asap3 import * from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import LBFGS import numpy as np calc = EMT() symbol = 'Cu' syms = ((True, True, True), (False, False, False), (True, True, False), (True, False, False)) for symmetry in syms: print "Periodicity:", symmetry for n in (4,6): atoms = FaceCenteredCubic(symbol=symbol, size=(4, 8, n), pbc=symmetry) atoms.set_calculator(calc) dyn = LBFGS(atoms, trajectory=None, logfile=None) dyn.run(fmax=0.05) e = atoms.get_potential_energy() print "Layers, energy: %2i %8.3f" % (n, e) print "TEST PASSED."
import numpy as np from ase.build import molecule from ase.calculators.qchem import QChem from ase.optimize import LBFGS mol = molecule('C2H6') calc = QChem(label='calc/ethane', method='B3LYP', basis='6-31+G*') mol.set_calculator(calc) # Check energy and forces np.testing.assert_allclose(mol.get_potential_energy(), -2172.379183703419, atol=10.) np.testing.assert_allclose(mol.get_forces(), np.array([[0., 0.00240141, 0.04992568], [-0., -0.00240141, -0.04992568], [-0., 0.11626015, 0.07267481], [-0.10132204, -0.05804009, 0.07538475], [0.10132204, -0.05804009, 0.07538475], [-0., -0.11626015, -0.07267481], [-0.10132204, 0.05804009, -0.07538475], [0.10132204, 0.05804009, -0.07538475]]), atol=0.05) opt = LBFGS(mol) opt.run() assert opt.converged()
from ase.constraints import UnitCellFilter from ase.io import Trajectory 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 = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build 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 = Trajectory('Cu-hcp.traj', 'w', cu)
!wget https://www.quantum-espresso.org/upf_files/Na.pbesol-spn-kjpaw_psl.1.0.0.UPF !wget https://www.quantum-espresso.org/upf_files/Cl.pbesol-n-kjpaw_psl.1.0.0.UPF #---- from ase.build import bulk from ase.calculators.espresso import Espresso from ase.constraints import UnitCellFilter from ase.optimize import LBFGS import ase.io pseudopotentials = {'Na': 'Na.pbesol-spn-kjpaw_psl.1.0.0.UPF', 'Cl': 'Cl.pbesol-n-kjpaw_psl.1.0.0.UPF'} rocksalt = bulk('NaCl', crystalstructure='rocksalt', a=6.0) calc = Espresso(pseudopotentials=pseudopotentials,pseudo_dir = './', tstress=True, tprnfor=True, kpts=(3, 3, 3)) rocksalt.set_calculator(calc) ucf = UnitCellFilter(rocksalt) opt = LBFGS(ucf) opt.run(fmax=0.005) # cubic lattic constant print((8*rocksalt.get_volume()/len(rocksalt))**(1.0/3.0)) #---- # %cd /content !mkdir Cu # %cd Cu #---- !wget https://www.quantum-espresso.org/upf_files/Cu.pz-d-rrkjus.UPF #---- from ase import Atoms from ase.build import bulk from ase.calculators.espresso import Espresso atoms = bulk("Cu") pseudopotentials = {'Cu':'Cu.pz-d-rrkjus.UPF'}
import numpy as np from gpaw import GPAW, PW from ase.calculators.dftd3 import DFTD3 from ase.build import bulk from ase.constraints import UnitCellFilter from ase.optimize import LBFGS np.random.seed(0) diamond = bulk('C') diamond.rattle(stdev=0.1, seed=0) diamond.cell += np.random.normal(scale=0.1, size=(3, 3)) dft = GPAW(xc='PBE', kpts=(8, 8, 8), mode=PW(400)) d3 = DFTD3(dft=dft) diamond.set_calculator(d3) ucf = UnitCellFilter(diamond) opt = LBFGS(ucf, logfile='diamond_opt.log', trajectory='diamond_opt.traj') opt.run(fmax=0.05)
dimer = Atoms('OH2OH2', [(0, 0, 0), (-r * cos(a / 2), r * sin(a / 2), 0), (-r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0), (-r * cos(a), 0, r * sin(a)), (-r, 0, 0)]) dimer.positions[3:, 0] += 2.8 dimer.constraints = FixBondLengths([ ((selection[i] + 3) % 6, (selection[i - 1] + 3) % 6) for i in range(3) ]) dimer.calc = EIQMMM(selection, GPAW(txt=name + '.txt', h=0.16), TIP4P(), interaction, vacuum=4, embedding=Embedding(rc=0.2, rc2=20, width=1), output=name + '.out') opt = LBFGS(dimer, trajectory=name + '.traj') opt.run(0.02) monomer = dimer[selection] monomer.center(vacuum=4) monomer.calc = GPAW(txt=name + 'M.txt', h=0.16) opt = PreconLBFGS(monomer, precon=Exp(A=3), trajectory=name + 'M.traj') opt.run(0.02) e0 = monomer.get_potential_energy() be = dimer.get_potential_energy() - e0 d = dimer.get_distance(0, 3) print(name, be, d) if name == '012': assert abs(be - -0.288) < 0.002 assert abs(d - 2.76) < 0.02 else:
# 1.1. Set up structure: atoms=read('../'+fo2+'.xsf') mask = [atom.position[2] < 17 for atom in atoms] fixlayers = FixAtoms(mask=mask) atoms.set_constraint(fixlayers) atoms.set_pbc([1,1,1]) # 2. Benchmark. ############################################################################### # 2.C Optimize using LBFGS. initial_lbfgs = atoms.copy() initial_lbfgs.set_calculator(calc) lbfgs_opt = LBFGS(initial_lbfgs, trajectory=fo2+'_lbfgs.traj') itime=time.default_timer() lbfgs_opt.run(fmax=0.01) logging.warning('lbfgs = %s', time.default_timer()-itime) # 2.D Optimize using FIRE. initial_fire = atoms.copy() initial_fire.set_calculator(calc) fire_opt = FIRE(initial_fire, trajectory=fo2+'_fire.traj') itime=time.default_timer() fire_opt.run(fmax=0.01) logging.warning('fires = %s', time.default_timer()-itime) # 2.A. Optimize structure using MLMin (CatLearn). initial_mlmin = atoms.copy() initial_mlmin.set_calculator(calc)
def test_unitcellfilter(asap3): 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.calc = asap3.EMT() f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.calc = asap3.EMT() print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
from ase_interface import aniensloader import ase import time from ase import units from ase.io import read, write from ase.optimize import BFGS, LBFGS # Read molecule from xyz mol = read('data/water.xyz') # Current ANI model options are: # '../ani_models/ani-1ccx_8x.info' Coupled cluster transfer learned model # '../ani_models/ani-1x_8x.info' Full ANI-1x wb97x/6-31g* dataset model mol.set_calculator(ANIENS(aniensloader('../ani_models/ani-1ccx_8x.info', 0))) # Calculate energy ei = mol.get_potential_energy() print("Initial Energy: ", ei) # Optimize molecule print("Optimizing...") start_time = time.time() dyn = LBFGS(mol) dyn.run(fmax=0.001) print('[ANI Optimization - Total time:', time.time() - start_time, 'seconds]') # Calculate energy ef = mol.get_potential_energy() print("Final Energy: ", ef)