Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
t-young31 committed Jan 31, 2023
1 parent 065064c commit 6602065
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 76 deletions.
5 changes: 3 additions & 2 deletions autode/neb/original.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numpy as np
import matplotlib.pyplot as plt

from typing import Optional, Sequence, List, Any, Union, TYPE_CHECKING
from typing import Optional, Sequence, List, Any, TYPE_CHECKING
from copy import deepcopy

from autode.log import logger
Expand Down Expand Up @@ -168,7 +168,8 @@ def __init__(
mult=species.mult,
atoms=species.atoms.copy(),
)
self.solvent = species.solvent
self.solvent = deepcopy(species.solvent)
self.energy = deepcopy(species.energy)

self.iteration = 0 #: Current optimisation iteration of this image
self.k = k
Expand Down
5 changes: 2 additions & 3 deletions autode/opt/optimisers/dimer.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,11 +273,10 @@ def _update_gradient_at(self, point: DimerPoint) -> None:
)
calc.run()

self._coords.e = self._species.energy = calc.get_energy()
self._species.gradient = calc.get_gradients()
self._coords.e = self._species.energy

self._coords.set_g_at(
point, calc.get_gradients().flatten(), mass_weighted=False
point, self._species.gradient.flatten(), mass_weighted=False
)

calc.clean_up(force=True, everything=True)
Expand Down
3 changes: 1 addition & 2 deletions autode/transition_states/locate_tss.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,9 +356,8 @@ def _get_ts_neb_from_adaptive_path(
)

if neb.images.contains_peak:
peak_idx = neb.images.peak_idx
ts_guess = TSguess(
atoms=neb.images[peak_idx].species.atoms,
atoms=neb.peak_species.atoms,
reactant=reactant,
product=product,
bond_rearr=bond_rearr,
Expand Down
14 changes: 6 additions & 8 deletions doc/common/nci_FF_example.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import autode as ade
from autode.methods import XTB
from autode.calculations import Calculation
from scipy.optimize import minimize
import numpy as np

from scipy.optimize import minimize
from scipy.spatial import distance_matrix

ade.Config.max_num_complex_conformers = 10
Expand Down Expand Up @@ -85,17 +84,16 @@ def rotation_translation(

def set_charges_vdw(species):
"""Calculate the partial atomic charges to atoms with XTB"""
calc = Calculation(
calc = ade.Calculation(
name="tmp",
molecule=species,
method=XTB(),
keywords=ade.SinglePointKeywords([]),
method=ade.methods.XTB(),
keywords=ade.SinglePointKeywords(),
)
calc.run()
charges = calc.get_atomic_charges()

for i, atom in enumerate(species.atoms):
atom.charge = charges[i]
atom.charge = atom.partial_charge
atom.vdw = float(atom.vdw_radius)

return None
Expand Down
2 changes: 2 additions & 0 deletions tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from autode.bonds import FormingBond, BreakingBond
from autode.species import Species, Molecule
from autode.units import Unit, KcalMol
from . import testutils

test_species = Species(name="tmp", charge=0, mult=1, atoms=[Atom("He")])
test_mol = Molecule(smiles="O")
Expand Down Expand Up @@ -179,6 +180,7 @@ def test_products_made():
assert not path.products_made(product=diff_mol)


@testutils.requires_with_working_xtb_install
def test_adaptive_path():

species_no_atoms = Species(name="tmp", charge=0, mult=1, atoms=[])
Expand Down
2 changes: 1 addition & 1 deletion tests/test_pes/test_calculate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_calculate_no_species():
@testutils.requires_with_working_xtb_install
@work_in_tmp_dir(filenames_to_copy=[], kept_file_exts=[])
def test_calculate_1d():
pes = RelaxedPESnD(species=h2(), rs={(0, 1): (1.6, 10)})
pes = RelaxedPESnD(species=h2(), rs={(0, 1): (1.5, 10)})

pes.calculate(method=XTB())

Expand Down
7 changes: 4 additions & 3 deletions tests/test_ts/test_mode_checking.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,20 @@ def has_correct_mode(name, fbonds, bbonds):
keywords=orca.keywords.opt_ts,
n_cores=1,
)
calc.molecule = reac = Reactant(
# need to bypass the pre-calculation checks on the molecule. e.g. valid spin state
calc.molecule = reactant = Reactant(
name="r", atoms=xyz_file_to_atoms(f"{name}.xyz")
)

calc.set_output_filename(f"{name}.out")

# Don't require all bonds to be breaking/making in a 'could be ts' function
ts = TSbase(
atoms=reac.atoms,
atoms=reactant.atoms,
bond_rearr=BondRearrangement(
breaking_bonds=bbonds, forming_bonds=fbonds
),
)
ts.hessian = calc.get_hessian()
ts.hessian = reactant.hessian

return ts.imag_mode_has_correct_displacement(req_all=False)
3 changes: 2 additions & 1 deletion tests/test_ts/test_ts_adapt_neb.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ def test_ts_from_neb_optimised_after_adapt():

rxn = _sn2_reaction()
neb = NEB.from_file("dOr2Us_ll_ad_0-5_0-1_path.xyz")

assert len(neb.images) > 0
assert neb.images[0].species.solvent is not None
assert neb.images[0].solvent is not None

def get_ts_guess():
return _get_ts_neb_from_adaptive_path(
Expand Down
26 changes: 15 additions & 11 deletions tests/test_wrappers/test_gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from .. import testutils

here = os.path.dirname(os.path.abspath(__file__))
test_mol = Molecule(name="methane", smiles="C")
method = G09()

opt_keywords = OptKeywords(["PBE1PBE/Def2SVP", "Opt"])
Expand All @@ -39,6 +38,10 @@
sp_keywords = SinglePointKeywords(["PBE1PBE/Def2SVP"])


def methane():
return Molecule(name="methane", smiles="C")


def test_printing_ecp():

tmp_file = open("tmp.com", "w")
Expand Down Expand Up @@ -90,7 +93,7 @@ def test_input_print_max_opt():
keywds = opt_keywords.copy()
keywds.max_opt_cycles = 10

str_keywords = _get_keywords(CalculationInput(keywds), molecule=test_mol)
str_keywords = _get_keywords(CalculationInput(keywds), molecule=methane())

# Should be only a single instance of the maxcycles declaration
assert sum("maxcycles=10" in kw.lower() for kw in str_keywords) == 1
Expand Down Expand Up @@ -215,7 +218,7 @@ def test_bad_gauss_output():

calc = Calculation(
name="no_output",
molecule=test_mol,
molecule=methane(),
method=method,
keywords=opt_keywords,
)
Expand Down Expand Up @@ -248,7 +251,7 @@ def test_fix_angle_error():
@testutils.work_in_zipped_dir(os.path.join(here, "data", "g09.zip"))
def test_constraints():

a = test_mol.copy()
a = methane()
a.constraints.distance = {(0, 1): 1.2}
calc = Calculation(
name="const_dist_opt", molecule=a, method=method, keywords=opt_keywords
Expand All @@ -260,14 +263,14 @@ def test_constraints():
1.199 < np.linalg.norm(opt_atoms[0].coord - opt_atoms[1].coord) < 1.201
)

b = test_mol.copy()
b = methane()
b.constraints.cartesian = [0]
calc = Calculation(
name="const_cart_opt", molecule=b, method=method, keywords=opt_keywords
)
calc.run()
opt_atoms = b.atoms
assert np.linalg.norm(test_mol.atoms[0].coord - opt_atoms[0].coord) < 1e-3
assert np.linalg.norm(methane().atoms[0].coord - opt_atoms[0].coord) < 1e-3


@testutils.work_in_zipped_dir(os.path.join(here, "data", "g09.zip"))
Expand Down Expand Up @@ -299,9 +302,10 @@ def test_point_charge_calc():
# Methane single point using a point charge with a unit positive charge
# located at (10, 10, 10)

mol = methane()
calc = Calculation(
name="methane_point_charge",
molecule=test_mol,
molecule=mol,
method=method,
keywords=sp_keywords,
point_charges=[PointCharge(charge=1.0, x=10.0, y=10.0, z=10.0)],
Expand All @@ -323,14 +327,14 @@ def test_point_charge_calc():
assert float(z) == 10.0
assert float(charge) == 1.0

assert -40.428 < calc.get_energy() < -40.427
assert -40.428 < mol.energy < -40.427

# Gaussian needs x-matrix and nosymm in the input line to run optimisations
# with point charges..
for opt_keyword in ["Opt", "Opt=Tight", "Opt=(Tight)"]:
calc = Calculation(
name="methane_point_charge_o",
molecule=test_mol,
molecule=methane(),
method=method,
keywords=OptKeywords(["PBE1PBE/Def2SVP", opt_keyword]),
point_charges=[PointCharge(charge=1.0, x=3.0, y=3.0, z=3.0)],
Expand Down Expand Up @@ -417,5 +421,5 @@ def test_xtb_optts():
calc.run()

# Even though a Hessian is not requested it should be added
assert calc.get_hessian() is not None
assert np.isclose(calc.get_energy().to("Ha"), -13.1297380, atol=1e-5)
assert orca_ts.hessian is not None
assert np.isclose(orca_ts.energy.to("Ha"), -13.1297380, atol=1e-5)
32 changes: 14 additions & 18 deletions tests/test_wrappers/test_mopac.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ def test_other_spin_states():
keywords=Config.MOPAC.keywords.sp,
)
calc.run()
singlet_energy = calc.get_energy()

o_triplet = Molecule(atoms=[Atom("O")], mult=3)
o_triplet.name = "molecule"
Expand All @@ -104,9 +103,8 @@ def test_other_spin_states():
keywords=Config.MOPAC.keywords.sp,
)
calc.run()
triplet_energy = calc.get_energy()

assert triplet_energy < singlet_energy
assert o_triplet.energy < o_singlet.energy

h_doublet = Molecule(atoms=[Atom("H")], mult=2)
h_doublet.name = "molecule"
Expand All @@ -120,7 +118,7 @@ def test_other_spin_states():
calc.run()

# Open shell doublet should work
assert calc.get_energy() is not None
assert h_doublet.energy is not None

h_quin = Molecule(atoms=[Atom("H")], mult=5)
h_quin.name = "molecule"
Expand Down Expand Up @@ -148,11 +146,9 @@ def test_bad_geometry():
keywords=Config.MOPAC.keywords.opt,
)

calc.output.filename = "h2_overlap_opt_mopac.out"
assert not calc.terminated_normally

with pytest.raises(Exception):
_ = calc.get_energy()
# cannot even get the energy from the output file
calc.set_output_filename("h2_overlap_opt_mopac.out")

assert not method.optimiser_from(calc).converged

Expand All @@ -169,21 +165,23 @@ def test_constrained_opt():
keywords=Config.MOPAC.keywords.opt,
)
calc.run()
opt_energy = calc.get_energy()
opt_energy = methane.energy

# Constrained optimisation with a C–H distance of 1.2 Å
# (carbon is the first atom in the file)
constrained_methane = methane.copy()
methane.constraints.distance = {(0, 1): 1.2}

const = Calculation(
name="methane_const",
molecule=methane,
molecule=constrained_methane,
method=method,
keywords=Config.MOPAC.keywords.opt,
)
const.run()

assert opt_energy < const.get_energy()
assert calc.get_hessian() is None
assert methane.energy < constrained_methane.energy
assert methane.hessian is None


@testutils.work_in_zipped_dir(os.path.join(here, "data", "mopac.zip"))
Expand All @@ -198,10 +196,9 @@ def test_grad():
keywords=Config.MOPAC.keywords.grad,
)
grad_calc.run()
energy = grad_calc.get_energy()
assert energy is not None
assert h2.energy is not None

gradients = grad_calc.get_gradients()
gradients = h2.gradient
assert gradients.shape == (2, 3)

delta_r = 1e-5
Expand All @@ -210,7 +207,7 @@ def test_grad():
)
h2_disp.single_point(method)

delta_energy = h2_disp.energy - energy # Ha]
delta_energy = h2_disp.energy - h2.energy
grad = delta_energy / delta_r # Ha A^-1

# Difference between the absolute and finite difference approximation
Expand All @@ -227,10 +224,9 @@ def test_broken_grad():
method=method,
keywords=Config.MOPAC.keywords.grad,
)
grad_calc_broken.output.filename = "h2_grad_broken.out"

with pytest.raises(CouldNotGetProperty):
_ = grad_calc_broken.get_gradients()
grad_calc_broken.set_output_filename("h2_grad_broken.out")


@testutils.work_in_zipped_dir(os.path.join(here, "data", "mopac.zip"))
Expand Down
Loading

0 comments on commit 6602065

Please sign in to comment.